index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/c3r/c3r-cli/src/main/java/com/amazonaws/c3r | Create_ds/c3r/c3r-cli/src/main/java/com/amazonaws/c3r/cli/EncryptMode.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.cli;
import com.amazonaws.c3r.action.CsvRowMarshaller;
import com.amazonaws.c3r.action.ParquetRowMarshaller;
import com.amazonaws.c3r.action.RowMarshaller;
import com.amazonaws.c3r.cleanrooms.CleanRoomsDao;
import com.amazonaws.c3r.config.ClientSettings;
import com.amazonaws.c3r.config.ColumnSchema;
import com.amazonaws.c3r.config.EncryptConfig;
import com.amazonaws.c3r.config.ParquetConfig;
import com.amazonaws.c3r.config.TableSchema;
import com.amazonaws.c3r.data.CsvValue;
import com.amazonaws.c3r.data.ParquetValue;
import com.amazonaws.c3r.encryption.keys.KeyUtil;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.io.FileFormat;
import com.amazonaws.c3r.json.GsonUtil;
import com.amazonaws.c3r.utils.C3rCliProperties;
import com.amazonaws.c3r.utils.C3rSdkProperties;
import com.amazonaws.c3r.utils.FileUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import picocli.CommandLine;
import javax.crypto.SecretKey;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import static com.amazonaws.c3r.cli.Main.generateCommandLine;
/**
* Supports cryptographic computations on data in preparation for upload to an AWS Clean Rooms collaboration.
*/
@Slf4j
@Getter
@CommandLine.Command(name = "encrypt",
mixinStandardHelpOptions = true,
version = C3rSdkProperties.VERSION,
descriptionHeading = "%nDescription:%n",
description = "Encrypt data content for use in an AWS Clean Rooms collaboration.")
public class EncryptMode implements Callable<Integer> {
/**
* Required command line arguments.
*/
@Getter
static class RequiredArgs {
/**
* {@value CliDescriptions#INPUT_DESCRIPTION_CRYPTO}.
*/
@CommandLine.Parameters(description = CliDescriptions.INPUT_DESCRIPTION_CRYPTO,
paramLabel = "<input>")
private String input = null;
/**
* {@value CliDescriptions#SCHEMA_DESCRIPTION}.
*/
@CommandLine.Option(names = {"--schema", "-s"},
description = CliDescriptions.SCHEMA_DESCRIPTION,
required = true,
paramLabel = "<file>")
private String schema = null;
/**
* {@value CliDescriptions#ID_DESCRIPTION}.
*/
@CommandLine.Option(names = {"--id"},
description = CliDescriptions.ID_DESCRIPTION,
paramLabel = "<value>",
required = true)
private UUID id = null;
}
/**
* Required values as specified by the user.
*/
@CommandLine.ArgGroup(multiplicity = "1", exclusive = false, heading = "%nRequired parameters:%n")
private RequiredArgs requiredArgs = new RequiredArgs();
/**
* Optional command line arguments.
*/
@Getter
static class OptionalArgs {
/**
* {@value CliDescriptions#AWS_PROFILE_DESCRIPTION}.
*/
@CommandLine.Option(names = {"--profile", "-l"},
description = CliDescriptions.AWS_PROFILE_DESCRIPTION)
private String profile = null;
/**
* {@value CliDescriptions#AWS_REGION_DESCRIPTION}.
*/
@CommandLine.Option(names = {"--region", "-g"},
description = CliDescriptions.AWS_REGION_DESCRIPTION)
private String region = null;
/**
* {@value CliDescriptions#FILE_FORMAT_DESCRIPTION}.
*/
@CommandLine.Option(names = {"--fileFormat", "-e"},
description = CliDescriptions.FILE_FORMAT_DESCRIPTION,
paramLabel = "<format>")
private FileFormat fileFormat = null;
/**
* {@value CliDescriptions#OUTPUT_DESCRIPTION_CRYPTO}.
*/
@CommandLine.Option(names = {"--output", "-o"},
description = CliDescriptions.OUTPUT_DESCRIPTION_CRYPTO,
paramLabel = "<file>")
private String output = null;
/**
* {@value CliDescriptions#OVERWRITE_DESCRIPTION}.
*/
@CommandLine.Option(names = {"--overwrite", "-f"},
description = CliDescriptions.OVERWRITE_DESCRIPTION)
private boolean overwrite = false;
/**
* {@value CliDescriptions#DRY_RUN_DESCRIPTION}.
*/
@CommandLine.Option(names = {"--dryRun", "-n"},
description = CliDescriptions.DRY_RUN_DESCRIPTION)
private boolean dryRun = false;
/**
* {@value CliDescriptions#ENCRYPT_CSV_INPUT_NULL_VALUE_DESCRIPTION}.
*/
@CommandLine.Option(names = {"--csvInputNULLValue", "-r"},
description = CliDescriptions.ENCRYPT_CSV_INPUT_NULL_VALUE_DESCRIPTION,
paramLabel = "<value>")
private String csvInputNullValue = null;
/**
* {@value CliDescriptions#ENCRYPT_CSV_OUTPUT_NULL_VALUE_DESCRIPTION}.
*/
@CommandLine.Option(names = {"--csvOutputNULLValue", "-w"},
description = CliDescriptions.ENCRYPT_CSV_OUTPUT_NULL_VALUE_DESCRIPTION,
paramLabel = "<value>")
private String csvOutputNullValue = null;
/**
* {@value CliDescriptions#PARQUET_BINARY_AS_STRING}.
*/
@CommandLine.Option(names = {"--parquetBinaryAsString"},
description = CliDescriptions.PARQUET_BINARY_AS_STRING)
private Boolean parquetBinaryAsString = null;
/**
* {@value CliDescriptions#TEMP_DIR_DESCRIPTION}.
*/
@CommandLine.Option(names = {"--tempDir", "-d"},
description = CliDescriptions.TEMP_DIR_DESCRIPTION,
paramLabel = "<dir>")
private String tempDir = FileUtil.TEMP_DIR;
/**
* {@value CliDescriptions#ENABLE_STACKTRACE_DESCRIPTION}.
*/
@CommandLine.Option(names = {"--enableStackTraces", "-v"},
description = CliDescriptions.ENABLE_STACKTRACE_DESCRIPTION)
private boolean enableStackTraces = false;
}
/**
* Optional values as specified by the user.
*/
@CommandLine.ArgGroup(exclusive = false, heading = "%nOptional parameters:%n")
private OptionalArgs optionalArgs = new OptionalArgs();
/** DAO for interacting with AWS Clean Rooms. */
private final CleanRoomsDao cleanRoomsDao;
/**
* Return a default CLI instance for encryption.
*
* <p>
* Note: {@link #getApp} is the intended method for manually creating this class
* with the appropriate CLI settings.
*/
EncryptMode() {
this.cleanRoomsDao = CleanRoomsDao.builder().apiName(C3rCliProperties.API_NAME).build();
}
/**
* Return a CLI instance for an encryption pass with a custom {@link CleanRoomsDao}.
*
* <p>
* Note: {@link #getApp} is the intended method for manually creating this class
* with the appropriate CLI settings.
*
* @param cleanRoomsDao Custom {@link CleanRoomsDao} to use for Clean Rooms API calls
*/
EncryptMode(final CleanRoomsDao cleanRoomsDao) {
this.cleanRoomsDao = cleanRoomsDao;
}
/**
* Get the encrypt mode command line application with a custom {@link CleanRoomsDao}.
*
* @param cleanRoomsDao Custom {@link CleanRoomsDao} to use for Clean Rooms API calls
* @return CommandLine interface for `encrypt` with customized AWS Clean Rooms access and standard CLI settings
*/
public static CommandLine getApp(final CleanRoomsDao cleanRoomsDao) {
return generateCommandLine(new EncryptMode(cleanRoomsDao));
}
/**
* Get the settings from AWS Clean Rooms for this collaboration.
*
* @return Cryptographic computing rules for collaboration
*/
public ClientSettings getClientSettings() {
final var dao = cleanRoomsDao != null
? cleanRoomsDao
: CleanRoomsDao.builder().apiName(C3rCliProperties.API_NAME).build();
return dao.withProfile(optionalArgs.profile).withRegion(optionalArgs.region)
.getCollaborationDataEncryptionMetadata(requiredArgs.id.toString());
}
/**
* All the configuration information needed for encrypting data.
*
* @return All cryptographic settings and information on data processing
* @throws C3rRuntimeException If the schema file can't be parsed
* @throws C3rIllegalArgumentException If the schema file is empty
*/
public EncryptConfig getConfig() {
final String tempDir = (optionalArgs.tempDir != null) ? optionalArgs.tempDir : FileUtil.TEMP_DIR;
final SecretKey keyMaterial = KeyUtil.sharedSecretKeyFromString(System.getenv(KeyUtil.KEY_ENV_VAR));
final TableSchema tableSchema;
try {
tableSchema = GsonUtil.fromJson(FileUtil.readBytes(requiredArgs.getSchema()), TableSchema.class);
} catch (Exception e) {
throw new C3rRuntimeException("Failed to parse the table schema file: " + requiredArgs.getSchema()
+ ". Please see the stack trace for where the parsing failed.", e);
}
if (tableSchema == null) {
throw new C3rIllegalArgumentException("The table schema file was empty: " + requiredArgs.getSchema());
}
return EncryptConfig.builder()
.sourceFile(requiredArgs.getInput())
.fileFormat(optionalArgs.fileFormat)
.targetFile(optionalArgs.output)
.tempDir(tempDir)
.overwrite(optionalArgs.overwrite)
.csvInputNullValue(optionalArgs.csvInputNullValue)
.csvOutputNullValue(optionalArgs.csvOutputNullValue)
.secretKey(keyMaterial)
.salt(requiredArgs.getId().toString())
.settings(getClientSettings())
.tableSchema(tableSchema)
.build();
}
/**
* All the configuration information needed specifically for Parquet files.
*
* @return All the settings on processing Parquet data
*/
public ParquetConfig getParquetConfig() {
return ParquetConfig.builder().binaryAsString(optionalArgs.parquetBinaryAsString).build();
}
/**
* Ensure required settings exist.
*
* @throws C3rIllegalArgumentException If user input is invalid
*/
private void validate() {
FileUtil.verifyReadableFile(requiredArgs.getSchema());
if (requiredArgs.getId() == null || requiredArgs.getId().toString().isBlank()) {
throw new C3rIllegalArgumentException("Specified collaboration identifier is blank.");
}
}
/**
* Log information about how the data is being encrypted.
*
* @param columnSchemas Description of how input data should be transformed during the encryption process
*/
void printColumCategoryInfo(final List<ColumnSchema> columnSchemas) {
if (columnSchemas.isEmpty()) {
return;
}
log.info("{} {} column{} being generated:",
columnSchemas.size(),
columnSchemas.get(0).getType(),
columnSchemas.size() > 1 ? "s" : "");
for (var c : columnSchemas) {
log.info(" * " + c.getTargetHeader());
}
}
/**
* Print summary information about what will be in the encrypted output.
*
* @param tableSchema How data will be transformed during encryption
*/
private void printColumnTransformInfo(final TableSchema tableSchema) {
final var sealedColumns = new ArrayList<ColumnSchema>();
final var fingerprintColumns = new ArrayList<ColumnSchema>();
final var cleartextColumns = new ArrayList<ColumnSchema>();
for (var c : tableSchema.getColumns()) {
switch (c.getType()) {
case SEALED:
sealedColumns.add(c);
break;
case FINGERPRINT:
fingerprintColumns.add(c);
break;
default:
cleartextColumns.add(c);
break;
}
}
printColumCategoryInfo(sealedColumns);
printColumCategoryInfo(fingerprintColumns);
printColumCategoryInfo(cleartextColumns);
}
/**
* Encrypt data for upload to an AWS Clean Rooms.
*
* @return {@link Main#SUCCESS} if no errors, else {@link Main#FAILURE}
*/
@Override
public Integer call() {
try {
validate();
final EncryptConfig cfg = getConfig();
final ParquetConfig pCfg = getParquetConfig();
printColumnTransformInfo(cfg.getTableSchema());
if (!optionalArgs.dryRun) {
log.info("Encrypting data from {}.", cfg.getSourceFile());
switch (cfg.getFileFormat()) {
case CSV:
if (pCfg.isSet()) {
throw new C3rIllegalArgumentException("Parquet options specified for CSV file.");
}
final RowMarshaller<CsvValue> csvRowMarshaller = CsvRowMarshaller.newInstance(cfg);
csvRowMarshaller.marshal();
csvRowMarshaller.close();
break;
case PARQUET:
final RowMarshaller<ParquetValue> parquetRowMarshaller = ParquetRowMarshaller.newInstance(cfg, pCfg);
parquetRowMarshaller.marshal();
parquetRowMarshaller.close();
break;
default:
throw new C3rIllegalArgumentException("Unrecognized file format: " + cfg.getFileFormat());
}
log.info("Encrypted data was saved to {}.", cfg.getTargetFile());
} else {
log.info("Dry run: No data will be encrypted from {}.", cfg.getSourceFile());
}
} catch (Exception e) {
Main.handleException(e, optionalArgs.enableStackTraces);
return Main.FAILURE;
}
return Main.SUCCESS;
}
} | 2,700 |
0 | Create_ds/c3r/c3r-cli/src/main/java/com/amazonaws/c3r | Create_ds/c3r/c3r-cli/src/main/java/com/amazonaws/c3r/cli/package-info.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/**
* Command line interface for using Cryptographic Computing for Clean Rooms with AWS Clean Rooms.
*
* <p>
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
@DefaultAnnotation(NonNull.class)
package com.amazonaws.c3r.cli;
import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
import lombok.NonNull; | 2,701 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/PermittableGroupIds.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public interface PermittableGroupIds {
String INTEROPERATION_SINGLE = "interoperation__v1__single";
String INTEROPERATION_BULK = "interoperation__v1__bulk";
}
| 2,702 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/EventConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1;
@SuppressWarnings("unused")
public interface EventConstants {
String DESTINATION = "interoperation-v1";
String SELECTOR_NAME = "action";
String OPERATION_HEADER = "operation";
String INITIALIZE = "initialize";
String SELECTOR_INITIALIZE = OPERATION_HEADER + " = '" + INITIALIZE + "'";
}
| 2,703 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/util/InteroperationUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.util;
public class InteroperationUtil {
}
| 2,704 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/util/MathUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.util;
import org.apache.fineract.cn.deposit.api.v1.definition.domain.Currency;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class MathUtil {
public static final MathContext DEFAULT_MATH_CONTEXT = new MathContext(2, RoundingMode.HALF_EVEN);
public static final MathContext CALCULATION_MATH_CONTEXT = new MathContext(5, RoundingMode.HALF_EVEN);
public static Double nullToZero(Double value) {
return nullToDefault(value, 0D);
}
public static Double nullToDefault(Double value, Double def) {
return value == null ? def : value;
}
public static Double zeroToNull(Double value) {
return isEmpty(value) ? null : value;
}
/** @return parameter value or ZERO if it is negative */
public static Double negativeToZero(Double value) {
return isGreaterThanZero(value) ? value : 0D;
}
public static boolean isEmpty(Double value) {
return value == null || value.equals(0D);
}
public static boolean isGreaterThanZero(Double value) {
return value != null && value > 0D;
}
public static boolean isLessThanZero(Double value) {
return value != null && value < 0D;
}
public static boolean isZero(Double value) {
return value != null && value.equals(0D);
}
public static boolean isEqualTo(Double first, Double second) {
return nullToZero(first).equals(nullToZero(second));
}
public static boolean isGreaterThan(Double first, Double second) {
return nullToZero(first) > nullToZero(second);
}
public static boolean isLessThan(Double first, Double second) {
return nullToZero(first) < nullToZero(second);
}
public static boolean isGreaterThanOrEqualTo(Double first, Double second) {
return nullToZero(first) >= nullToZero(second);
}
public static boolean isLessThanOrEqualZero(Double value) {
return nullToZero(value) <= 0D;
}
/** @return parameter value or negated value to positive */
public static Double abs(Double value) {
return value == null ? 0D : Math.abs(value);
}
/** @return calculates minimum of the two values considering null values
* @param notNull if true then null parameter is omitted, otherwise returns null */
public static Double min(Double first, Double second, boolean notNull) {
return first == null
? (notNull ? second : null)
: second == null ? (notNull ? first : null) : Math.min(first, second);
}
/** @return calculates minimum of the values considering null values
* @param notNull if true then null parameter is omitted, otherwise returns null */
public static Double min(Double first, Double second, Double third, boolean notNull) {
return min(min(first, second, notNull), third, notNull);
}
/** @return sum the two values considering null values */
public static Double add(Double first, Double second) {
return first == null
? second
: second == null ? first : first + second;
}
/** @return sum the values considering null values */
public static Double add(Double first, Double second, Double third) {
return add(add(first, second), third);
}
/** @return sum the values considering null values */
public static Double add(Double first, Double second, Double third, Double fourth) {
return add(add(add(first, second), third), fourth);
}
/** @return sum the values considering null values */
public static Double add(Double first, Double second, Double third, Double fourth, Double fifth) {
return add(add(add(add(first, second), third), fourth), fifth);
}
/** @return first minus second considering null values, maybe negative */
public static Double subtract(Double first, Double second) {
return first == null
? null
: second == null ? first : first - second;
}
/** @return first minus the others considering null values, maybe negative */
public static Double subtractToZero(Double first, Double second, Double third) {
return subtractToZero(subtract(first, second), third);
}
/** @return first minus the others considering null values, maybe negative */
public static Double subtractToZero(Double first, Double second, Double third, Double fourth) {
return subtractToZero(subtract(subtract(first, second), third), fourth);
}
/** @return NONE negative first minus second considering null values */
public static Double subtractToZero(Double first, Double second) {
return negativeToZero(subtract(first, second));
}
/** @return BigDecimal with scale set to the 'digitsAfterDecimal' of the parameter currency */
public static Double normalize(Double amount, @NotNull Currency currency) {
return amount == null ? null : normalize(BigDecimal.valueOf(amount), currency).doubleValue();
}
/** @return BigDecimal with scale set to the 'digitsAfterDecimal' of the parameter currency */
public static Double normalize(Double amount, @NotNull MathContext mc) {
return amount == null ? null : normalize(BigDecimal.valueOf(amount), mc).doubleValue();
}
/** @return BigDecimal null safe negate */
public static Double negate(Double amount) {
return isEmpty(amount) ? amount : amount * -1;
}
// ----------------- BigDecimal -----------------
public static BigDecimal nullToZero(BigDecimal value) {
return nullToDefault(value, BigDecimal.ZERO);
}
public static BigDecimal nullToDefault(BigDecimal value, BigDecimal def) {
return value == null ? def : value;
}
public static BigDecimal zeroToNull(BigDecimal value) {
return isEmpty(value) ? null : value;
}
/** @return parameter value or ZERO if it is negative */
public static BigDecimal negativeToZero(BigDecimal value) {
return isGreaterThanZero(value) ? value : BigDecimal.ZERO;
}
public static boolean isEmpty(BigDecimal value) {
return value == null || BigDecimal.ZERO.compareTo(value) == 0;
}
public static boolean isGreaterThanZero(BigDecimal value) {
return value != null && value.compareTo(BigDecimal.ZERO) > 0;
}
public static boolean isLessThanZero(BigDecimal value) {
return value != null && value.compareTo(BigDecimal.ZERO) < 0;
}
public static boolean isZero(BigDecimal value) {
return value != null && value.compareTo(BigDecimal.ZERO) == 0;
}
public static boolean isEqualTo(BigDecimal first, BigDecimal second) {
return nullToZero(first).compareTo(nullToZero(second)) == 0;
}
public static boolean isGreaterThan(BigDecimal first, BigDecimal second) {
return nullToZero(first).compareTo(nullToZero(second)) > 0;
}
public static boolean isLessThan(BigDecimal first, BigDecimal second) {
return nullToZero(first).compareTo(nullToZero(second)) < 0;
}
public static boolean isGreaterThanOrEqualTo(BigDecimal first, BigDecimal second) {
return nullToZero(first).compareTo(nullToZero(second)) >= 0;
}
public static boolean isLessThanOrEqualZero(BigDecimal value) {
return nullToZero(value).compareTo(BigDecimal.ZERO) <= 0;
}
/** @return parameter value or negated value to positive */
public static BigDecimal abs(BigDecimal value) {
return value == null ? BigDecimal.ZERO : value.abs();
}
/** @return calculates minimum of the two values considering null values
* @param notNull if true then null parameter is omitted, otherwise returns null */
public static BigDecimal min(BigDecimal first, BigDecimal second, boolean notNull) {
return notNull
? first == null
? second
: second == null ? first : min(first, second, false)
: isLessThan(first, second) ? first : second;
}
/** @return calculates minimum of the values considering null values
* @param notNull if true then null parameter is omitted, otherwise returns null */
public static BigDecimal min(BigDecimal first, BigDecimal second, BigDecimal third, boolean notNull) {
return min(min(first, second, notNull), third, notNull);
}
/** @return sum the two values considering null values */
public static BigDecimal add(BigDecimal first, BigDecimal second) {
return add(first, second, CALCULATION_MATH_CONTEXT);
}
/** @return sum the two values considering null values */
public static BigDecimal add(BigDecimal first, BigDecimal second, MathContext mc) {
return first == null
? second
: second == null ? first : first.add(second, mc);
}
/** @return sum the values considering null values */
public static BigDecimal add(BigDecimal first, BigDecimal second, BigDecimal third) {
return add(first, second, third, CALCULATION_MATH_CONTEXT);
}
/** @return sum the values considering null values */
public static BigDecimal add(BigDecimal first, BigDecimal second, BigDecimal third, MathContext mc) {
return add(add(first, second, mc), third, mc);
}
/** @return sum the values considering null values */
public static BigDecimal add(BigDecimal first, BigDecimal second, BigDecimal third, BigDecimal fourth) {
return add(first, second, third, fourth, CALCULATION_MATH_CONTEXT);
}
/** @return sum the values considering null values */
public static BigDecimal add(BigDecimal first, BigDecimal second, BigDecimal third, BigDecimal fourth, MathContext mc) {
return add(add(add(first, second, mc), third, mc), fourth, mc);
}
/** @return sum the values considering null values */
public static BigDecimal add(BigDecimal first, BigDecimal second, BigDecimal third, BigDecimal fourth, BigDecimal fifth) {
return add(first, second, third, fourth, fifth, CALCULATION_MATH_CONTEXT);
}
/** @return sum the values considering null values */
public static BigDecimal add(BigDecimal first, BigDecimal second, BigDecimal third, BigDecimal fourth, BigDecimal fifth, MathContext mc) {
return add(add(add(add(first, second, mc), third, mc), fourth, mc), fifth, mc);
}
/** @return first minus second considering null values, maybe negative */
public static BigDecimal subtract(BigDecimal first, BigDecimal second) {
return first == null
? null
: second == null ? first : first.subtract(second, CALCULATION_MATH_CONTEXT);
}
/** @return NONE negative first minus second considering null values */
public static BigDecimal subtractToZero(BigDecimal first, BigDecimal second) {
return negativeToZero(subtract(first, second));
}
/** @return first minus the others considering null values, maybe negative */
public static BigDecimal subtractToZero(BigDecimal first, BigDecimal second, BigDecimal third) {
MathContext mc = CALCULATION_MATH_CONTEXT;
return subtractToZero(subtract(first, second), third);
}
/** @return first minus the others considering null values, maybe negative */
public static BigDecimal subtractToZero(BigDecimal first, BigDecimal second, BigDecimal third, BigDecimal fourth) {
return subtractToZero(subtract(subtract(first, second), third), fourth);
}
/** @return BigDecimal with scale set to the 'digitsAfterDecimal' of the parameter currency */
public static BigDecimal normalize(BigDecimal amount, @NotNull Currency currency) {
return amount == null ? null : amount.setScale(currency.getScale(), CALCULATION_MATH_CONTEXT.getRoundingMode());
}
/** @return BigDecimal with scale set to the 'digitsAfterDecimal' of the parameter currency */
public static BigDecimal normalize(BigDecimal amount, @NotNull MathContext mc) {
return amount == null ? null : amount.setScale(mc.getPrecision(), mc.getRoundingMode());
}
/** @return BigDecimal null safe negate */
public static BigDecimal negate(BigDecimal amount) {
return negate(amount, CALCULATION_MATH_CONTEXT);
}
/** @return BigDecimal null safe negate */
public static BigDecimal negate(BigDecimal amount, MathContext mc) {
return isEmpty(amount) ? amount : amount.negate(mc);
}
}
| 2,705 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/InteropActionState.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain;
public enum InteropActionState {
ACCEPTED,
REJECTED
}
| 2,706 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/InteropIdentifierType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain;
public enum InteropIdentifierType {
MSISDN,
EMAIL,
PERSONAL_ID,
BUSINESS,
DEVICE,
ACCOUNT_ID,
IBAN,
ALIAS
}
| 2,707 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/InteropAmountType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain;
public enum InteropAmountType {
SEND,
RECEIVE
}
| 2,708 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/InteropState.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain;
public enum InteropState {
REQUESTED,
QUOTED,
PREPARED,
COMMITTED,
ABORTED,
;
public static InteropState[] VALUES = values();
public static InteropState forAction(InteropActionType action) {
switch (action) {
case REQUEST:
return REQUESTED;
case QUOTE:
return QUOTED;
case PREPARE:
return PREPARED;
case COMMIT:
return COMMITTED;
case ABORT:
return ABORTED;
default:
return null; // TODO fail
}
}
}
| 2,709 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/InteropTransactionScenario.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain;
public enum InteropTransactionScenario {
DEPOSIT,
WITHDRAWAL,
TRANSFER,
PAYMENT,
REFUND
}
| 2,710 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/InteropInitiatorType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain;
public enum InteropInitiatorType {
CONSUMER,
AGENT,
BUSINESS,
DEVICE
}
| 2,711 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/TransactionType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain;
/**
* @code org.apache.fineract.cn.accounting.service.internal.repository.AccountEntryEntity.type
*/
public enum TransactionType {
ACCOUNT_OPENING("ACCO"),
ACCOUNT_CLOSING("ACCC"),
ACCOUNT_TRANSFER("ACCT"),
ACH_CREDIT("ACDT"),
ACH_DEBIT("ADBT"),
ACH_ADJUSTMENTS("ADJT"),
ACH_PREAUTHORISED("APAC"),
ACH_RETURN("ARET"),
ACH_REVERSAL("AREV"),
ACH_SETTLEMENT("ASET"),
ACH_TRANSACTION("ATXN"),
ARP_DEBIT("ARPD"),
CURRENCY_DEPOSIT("FCDP"),
CURRENCY_WITHDRAWAL("FCWD"),
BRANCH_TRANSFER("BACT"),
BRANCH_DEPOSIT("BCDP"),
BRANCH_WITHDRAWAL("BCWD"),
CASH_DEPOSIT("CDPT"),
CASH_WITHDRAWAL("CWDL"),
CASH_LETTER("CASH"),
CHEQUE("CCHQ"),
BRANCH_CHEQUE("BCHQ"),
CERTIFIED_CHEQUE("CCCH"),
CROSSED_CHEQUE("CRCQ"),
CHEQUE_REVERSAL("CQRV"),
CHEQUE_OPEN("OPCQ"),
CHEQUE_ORDER("ORCQ"),
CHARGES_PAYMENT("CHRG"),
FEES_PAYMENT("FEES"),
TAXES_PAYMENT("TAXE"),
PRINCIPAL_PAYMENT("PPAY"),
INTEREST_PAYMENT("INTR"),
DIRECTDEBIT_PAYMENT("PMDD"),
DIRECTDEBIT_PREAUTHORISED("PADD"),
BRANCH_DIRECTDEBIT("BBDD"),
SMARTCARD_PAYMENT("SMRT"),
POINTOFSALE_CREDITCARD("POSC"),
POINTOFSALE_DEBITCARD("POSD"),
POINTOFSALE_PAYMENT("POSP"),
DOMESTIC_CREDIT("DMCT"),
INTRACOMPANY_TRANSFER("ICCT"),
MIXED_DEPOSIT("MIXD"),
MISCELLANEOUS_DEPOSIT("MSCD"),
OTHER("OTHR"),
CONTROLLED_DISBURSEMENT("CDIS"),
CONTROLLED_DISBURSEMENT2("DSBR"),
CREDIT_ADJUSTMENT("CAJT"),
DEBIT_ADJUSTMENT("DAJT"),
EXCHANGERATE_ADJUSTMENT("ERTA"),
YID_ADJUSTMENT("YTDA"),
REIMBURSEMENT("RIMB"),
DRAWDOWN("DDWN"),
ERROR_NOTAVAILABLE("NTAV"),
ERROR_POSTING("PSTE"),
ERROR_CANCELLATION("RCDD"),
ERROR_CANCELLATION2("RPCR"),
ERROR_ZEROBALANCE("ZABA"),
;
private final String code;
TransactionType(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
| 2,712 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/InteropTransferActionType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain;
public enum InteropTransferActionType {
PREPARE,
CREATE,
;
}
| 2,713 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/InteropTransactionRole.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain;
public enum InteropTransactionRole {
PAYER,
PAYEE,
;
public boolean isWithdraw() {
return this == PAYER;
}
public TransactionType getTransactionType() {
return this == PAYER ? TransactionType.CURRENCY_WITHDRAWAL : TransactionType.CURRENCY_DEPOSIT;
}
}
| 2,714 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/InteropStateMachine.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain;
import org.apache.fineract.cn.lang.ServiceException;
import javax.validation.constraints.NotNull;
public class InteropStateMachine {
private InteropStateMachine() {
}
/**
* Executes the given transition from one status to another when the given transition (actualEvent + action) is valid.
*
* @param currentState actual {@link InteropState}
* @param action the {@link InteropActionType}
* @return the new {@link InteropState} for the tag if the given transition is valid
*
*/
public static InteropState handleTransition(InteropState currentState, @NotNull InteropActionType action) {
InteropState transitionState = getTransitionState(currentState, action);
if (transitionState == null) {
throw new ServiceException("State transition is not valid: ({0}) and action: ({1})", currentState, action);
}
return transitionState;
}
public static boolean isValidAction(InteropState currentState, @NotNull InteropActionType action) {
if (currentState == null || action == InteropActionType.ABORT)
return true;
InteropState transitionState = getTransitionState(currentState, action);
return transitionState != null && transitionState.ordinal() > currentState.ordinal();
}
private static InteropState getTransitionState(InteropState currentState, @NotNull InteropActionType action) {
return InteropState.forAction(action);
}
}
| 2,715 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/InteropActionType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain;
public enum InteropActionType {
REQUEST,
QUOTE,
PREPARE,
COMMIT,
ABORT,
;
public static InteropActionType[] VALUES = values();
}
| 2,716 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/InteropResponseData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropActionState;
import javax.validation.constraints.NotNull;
import java.beans.Transient;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
public abstract class InteropResponseData {
@NotNull
private final String transactionCode;
@NotNull
private final InteropActionState state;
private final String expiration;
private final List<ExtensionData> extensionList;
protected InteropResponseData(@NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, List<ExtensionData> extensionList) {
this.transactionCode = transactionCode;
this.state = state;
this.expiration = format(expiration);
this.extensionList = extensionList;
}
public String getTransactionCode() {
return transactionCode;
}
public InteropActionState getState() {
return state;
}
public String getExpiration() {
return expiration;
}
@Transient
public LocalDateTime getExpirationDate() {
return parse(expiration);
}
public List<ExtensionData> getExtensionList() {
return extensionList;
}
protected static LocalDateTime parse(String date) {
return date == null ? null : LocalDateTime.parse(date, DateTimeFormatter.ISO_DATE_TIME);
}
protected static String format(LocalDateTime date) {
return date == null ? null : date.format(DateTimeFormatter.ISO_DATE_TIME);
}
}
| 2,717 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/InteropTransferCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropActionType;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropTransferActionType;
import javax.validation.constraints.NotNull;
import java.beans.Transient;
public class InteropTransferCommand extends InteropTransferRequestData {
@NotNull
private final InteropTransferActionType action;
public InteropTransferCommand(@NotNull InteropTransferRequestData requestData, @NotNull InteropTransferActionType action) {
super(requestData.getTransactionCode(), requestData.getAccountId(), requestData.getAmount(), requestData.getTransactionRole(),
requestData.getNote(), requestData.getExpiration(), requestData.getExtensionList(), requestData.getTransferCode(),
requestData.getFspFee(), requestData.getFspCommission());
this.action = action;
}
public InteropTransferActionType getAction() {
return action;
}
@NotNull
@Transient
@Override
public InteropActionType getActionType() {
return action == InteropTransferActionType.PREPARE ? InteropActionType.PREPARE : InteropActionType.COMMIT;
}
}
| 2,718 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/ExtensionData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotNull;
public class ExtensionData {
@NotNull
@Length(min = 1, max = 128)
private String key;
@NotNull
@Length(min = 1, max = 128)
private String value;
protected ExtensionData() {
}
public ExtensionData(@NotNull String key, @NotNull String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
protected void setKey(String key) {
this.key = key;
}
protected void setValue(String value) {
this.value = value;
}
}
| 2,719 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/InteropTransactionRequestResponseData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropActionState;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.time.LocalDateTime;
import java.util.List;
public class InteropTransactionRequestResponseData extends InteropResponseData {
@NotNull
@Pattern(regexp = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$")
private final String requestCode;
private InteropTransactionRequestResponseData(@NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, List<ExtensionData> extensionList,
@NotNull String requestCode) {
super(transactionCode, state, expiration, extensionList);
this.requestCode = requestCode;
}
public static InteropTransactionRequestResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state,
LocalDateTime expiration, List<ExtensionData> extensionList,
@NotNull String requestCode) {
return new InteropTransactionRequestResponseData(transactionCode, state, expiration, extensionList, requestCode);
}
public static InteropTransactionRequestResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state,
LocalDateTime expiration, @NotNull String requestCode) {
return build(transactionCode, state, expiration, null, requestCode);
}
public String getRequestCode() {
return requestCode;
}
}
| 2,720 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/InteropRequestData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.apache.fineract.cn.deposit.api.v1.definition.domain.Currency;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropActionType;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropTransactionRole;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.beans.Transient;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
public abstract class InteropRequestData {
public static final String IDENTIFIER_SEPARATOR = "_";
@NotNull
@Pattern(regexp = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$")
private String transactionCode;
@Pattern(regexp = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$")
private String requestCode;
@NotEmpty
@Length(max = 32)
private String accountId;
@NotNull
@Valid
private MoneyData amount;
@NotNull
private InteropTransactionRole transactionRole;
@Valid
private InteropTransactionTypeData transactionType;
@Length(max = 128)
private String note;
@Valid
private GeoCodeData geoCode;
private LocalDateTime expiration;
@Size(max = 16)
@Valid
private List<ExtensionData> extensionList;
protected InteropRequestData() {
}
protected InteropRequestData(@NotNull String transactionCode, String requestCode, @NotNull String accountId, @NotNull MoneyData amount,
@NotNull InteropTransactionRole transactionRole, InteropTransactionTypeData transactionType, String note,
GeoCodeData geoCode, LocalDateTime expiration, List<ExtensionData> extensionList) {
this.transactionCode = transactionCode;
this.requestCode = requestCode;
this.accountId = accountId;
this.amount = amount;
this.transactionType = transactionType;
this.transactionRole = transactionRole;
this.note = note;
this.geoCode = geoCode;
this.expiration = expiration;
this.extensionList = extensionList;
}
protected InteropRequestData(@NotNull String transactionCode, @NotNull String accountId, @NotNull MoneyData amount, @NotNull InteropTransactionRole transactionRole) {
this(transactionCode, null, accountId, amount, transactionRole, null, null, null, null, null);
}
@NotNull
public String getTransactionCode() {
return transactionCode;
}
public String getRequestCode() {
return requestCode;
}
@NotNull
public String getAccountId() {
return accountId;
}
@NotNull
public MoneyData getAmount() {
return amount;
}
public InteropTransactionTypeData getTransactionType() {
return transactionType;
}
@NotNull
public InteropTransactionRole getTransactionRole() {
return transactionRole;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public GeoCodeData getGeoCode() {
return geoCode;
}
public void setGeoCode(GeoCodeData geoCode) {
this.geoCode = geoCode;
}
public LocalDateTime getExpiration() {
return expiration;
}
public LocalDate getExpirationLocalDate() {
return expiration == null ? null : expiration.toLocalDate();
}
public void setExpiration(LocalDateTime expiration) {
this.expiration = expiration;
}
public List<ExtensionData> getExtensionList() {
return extensionList;
}
public void setExtensionList(List<ExtensionData> extensionList) {
this.extensionList = extensionList;
}
public void normalizeAmounts(@NotNull Currency currency) {
amount.normalizeAmount(currency);
}
protected void setTransactionCode(String transactionCode) {
this.transactionCode = transactionCode;
}
protected void setRequestCode(String requestCode) {
this.requestCode = requestCode;
}
protected void setAccountId(String accountId) {
this.accountId = accountId;
}
protected void setAmount(MoneyData amount) {
this.amount = amount;
}
protected void setTransactionRole(InteropTransactionRole transactionRole) {
this.transactionRole = transactionRole;
}
protected void setTransactionType(InteropTransactionTypeData transactionType) {
this.transactionType = transactionType;
}
@Transient
public abstract InteropActionType getActionType();
@Transient
@NotNull
public String getIdentifier() {
return transactionCode;
}
}
| 2,721 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/InteropIdentifierCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropIdentifierType;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
public class InteropIdentifierCommand extends InteropIdentifierData {
@NotNull
private InteropIdentifierType idType;
@NotEmpty
@Length(max = 128)
private String idValue;
@Length(max = 128)
private String subIdOrType;
protected InteropIdentifierCommand() {
}
public InteropIdentifierCommand(@NotNull InteropIdentifierData requestData, @NotNull InteropIdentifierType idType, @NotNull String idValue, String subIdOrType) {
super(requestData.getAccountId());
this.idType = idType;
this.idValue = idValue;
this.subIdOrType = subIdOrType;
}
@NotNull
public InteropIdentifierType getIdType() {
return idType;
}
@NotNull
public String getIdValue() {
return idValue;
}
public String getSubIdOrType() {
return subIdOrType;
}
}
| 2,722 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/InteropTransferRequestData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.apache.fineract.cn.deposit.api.v1.definition.domain.Currency;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropActionType;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropTransactionRole;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.beans.Transient;
import java.time.LocalDateTime;
import java.util.List;
public class InteropTransferRequestData extends InteropRequestData {
@NotNull
@Pattern(regexp = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$")
private String transferCode;
@Valid
private MoneyData fspFee;
@Valid
private MoneyData fspCommission;
protected InteropTransferRequestData() {
super();
}
public InteropTransferRequestData(@NotNull String transactionCode, @NotNull String accountId, @NotNull MoneyData amount,
@NotNull InteropTransactionRole transactionRole, String note, LocalDateTime expiration,
List<ExtensionData> extensionList, @NotNull String transferCode, MoneyData fspFee, MoneyData fspCommission) {
super(transactionCode, null, accountId, amount, transactionRole, null, note, null, expiration, extensionList);
this.transferCode = transferCode;
this.fspFee = fspFee;
this.fspCommission = fspCommission;
}
public InteropTransferRequestData(@NotNull String transactionCode, @NotNull String accountId, @NotNull MoneyData amount,
@NotNull InteropTransactionRole transactionRole, @NotNull String transferCode) {
this(transactionCode, accountId, amount, transactionRole, null, null, null, transferCode, null, null);
}
private InteropTransferRequestData(InteropRequestData other, @NotNull String transferCode, MoneyData fspFee, MoneyData fspCommission) {
this(other.getTransactionCode(), other.getAccountId(), other.getAmount(), other.getTransactionRole(),
other.getNote(), other.getExpiration(), other.getExtensionList(), transferCode, fspFee, fspCommission);
}
public String getTransferCode() {
return transferCode;
}
public MoneyData getFspFee() {
return fspFee;
}
public MoneyData getFspCommission() {
return fspCommission;
}
public void normalizeAmounts(@NotNull Currency currency) {
super.normalizeAmounts(currency);
if (fspFee != null)
fspFee.normalizeAmount(currency);
}
@Transient
@Override
public InteropActionType getActionType() {
return null;
}
@Transient
@NotNull
@Override
public String getIdentifier() {
return transferCode;
}
}
| 2,723 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/InteropQuoteRequestData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.apache.fineract.cn.deposit.api.v1.definition.domain.Currency;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropActionType;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropAmountType;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropTransactionRole;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.beans.Transient;
import java.time.LocalDateTime;
import java.util.List;
public class InteropQuoteRequestData extends InteropRequestData {
@NotNull
@Pattern(regexp = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$")
private String quoteCode;
@NotNull
private InteropAmountType amountType;
@Valid
private MoneyData fees; // only for disclosed Payer fees on the Payee side
private InteropQuoteRequestData() {
super();
}
public InteropQuoteRequestData(@NotNull String transactionCode, String requestCode, @NotNull String accountId, @NotNull MoneyData amount,
@NotNull InteropTransactionRole transactionRole, @NotNull InteropTransactionTypeData transactionType,
String note, GeoCodeData geoCode, LocalDateTime expiration, List<ExtensionData> extensionList,
@NotNull String quoteCode, @NotNull InteropAmountType amountType, MoneyData fees) {
super(transactionCode, requestCode, accountId, amount, transactionRole, transactionType, note, geoCode, expiration, extensionList);
this.quoteCode = quoteCode;
this.amountType = amountType;
this.fees = fees;
}
public InteropQuoteRequestData(@NotNull String transactionCode, @NotNull String accountId, @NotNull InteropAmountType amountType,
@NotNull MoneyData amount, @NotNull InteropTransactionRole transactionRole, @NotNull InteropTransactionTypeData transactionType,
@NotNull String quoteCode) {
this(transactionCode, null, accountId, amount, transactionRole, transactionType, null, null, null, null, quoteCode,
amountType, null);
}
private InteropQuoteRequestData(@NotNull InteropRequestData other, @NotNull String quoteCode, @NotNull InteropAmountType amountType,
MoneyData fees) {
this(other.getTransactionCode(), other.getRequestCode(), other.getAccountId(), other.getAmount(), other.getTransactionRole(),
other.getTransactionType(), other.getNote(), other.getGeoCode(), other.getExpiration(), other.getExtensionList(),
quoteCode, amountType, fees);
}
public String getQuoteCode() {
return quoteCode;
}
public InteropAmountType getAmountType() {
return amountType;
}
public MoneyData getFees() {
return fees;
}
public void normalizeAmounts(@NotNull Currency currency) {
super.normalizeAmounts(currency);
if (fees != null)
fees.normalizeAmount(currency);
}
protected void setQuoteCode(String quoteCode) {
this.quoteCode = quoteCode;
}
protected void setAmountType(InteropAmountType amountType) {
this.amountType = amountType;
}
protected void setFees(MoneyData fees) {
this.fees = fees;
}
@NotNull
@Transient
@Override
public InteropActionType getActionType() {
return InteropActionType.QUOTE;
}
@Transient
@NotNull
@Override
public String getIdentifier() {
return quoteCode;
}
}
| 2,724 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/GeoCodeData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
public class GeoCodeData {
@NotNull
@Pattern(regexp = "^(\\+|-)?(?:90(?:(?:\\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\\.[0-9]{1,6})?))$")
private String latitude;
@NotNull
@Pattern(regexp = "^(\\+|-)?(?:180(?:(?:\\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\\.[0-9]{1,6})?))$")
private String longitude;
protected GeoCodeData() {
}
public GeoCodeData(String latitude, String longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
protected void setLatitude(String latitude) {
this.latitude = latitude;
}
protected void setLongitude(String longitude) {
this.longitude = longitude;
}
}
| 2,725 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/InteropIdentifierData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
public class InteropIdentifierData {
@NotEmpty
@Length(max = 32)
private String accountId;
protected InteropIdentifierData() {
}
public InteropIdentifierData(@NotNull String accountId) {
this.accountId = accountId;
}
@NotNull
public String getAccountId() {
return accountId;
}
protected void setAccountId(String accountId) {
this.accountId = accountId;
}
}
| 2,726 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/InteropIdentifierDeleteCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropIdentifierType;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
public class InteropIdentifierDeleteCommand {
@NotNull
private InteropIdentifierType idType;
@NotEmpty
@Length(max = 128)
private String idValue;
@Length(max = 128)
private String subIdOrType;
protected InteropIdentifierDeleteCommand() {
}
public InteropIdentifierDeleteCommand(@NotNull InteropIdentifierType idType, @NotNull String idValue, String subIdOrType) {
this.idType = idType;
this.idValue = idValue;
this.subIdOrType = subIdOrType;
}
@NotNull
public InteropIdentifierType getIdType() {
return idType;
}
@NotNull
public String getIdValue() {
return idValue;
}
public String getSubIdOrType() {
return subIdOrType;
}}
| 2,727 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/InteropTransferResponseData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropActionState;
import javax.validation.constraints.NotNull;
import java.beans.Transient;
import java.time.LocalDateTime;
import java.util.List;
public class InteropTransferResponseData extends InteropResponseData {
@NotNull
private final String transferCode;
private String completedTimestamp;
private InteropTransferResponseData(@NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration,
List<ExtensionData> extensionList, @NotNull String transferCode, LocalDateTime completedTimestamp) {
super(transactionCode, state, expiration, extensionList);
this.transferCode = transferCode;
this.completedTimestamp = format(completedTimestamp);
}
public static InteropTransferResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state,
LocalDateTime expiration, List<ExtensionData> extensionList,
@NotNull String transferCode, LocalDateTime completedTimestamp) {
return new InteropTransferResponseData(transactionCode, state, expiration, extensionList, transferCode, completedTimestamp);
}
public static InteropTransferResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state,
LocalDateTime expiration, @NotNull String transferCode, LocalDateTime completedTimestamp) {
return build(transactionCode, state, expiration, transferCode, completedTimestamp);
}
public String getTransferCode() {
return transferCode;
}
public String getCompletedTimestamp() {
return completedTimestamp;
}
@Transient
public LocalDateTime getCompletedTimestampDate() {
return parse(completedTimestamp);
}
}
| 2,728 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/InteropTransactionRequestData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropActionType;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropTransactionRole;
import javax.validation.constraints.NotNull;
import java.beans.Transient;
import java.time.LocalDateTime;
import java.util.List;
public class InteropTransactionRequestData extends InteropRequestData {
protected InteropTransactionRequestData() {
super();
}
public InteropTransactionRequestData(@NotNull String transactionCode, @NotNull String requestCode, @NotNull String accountId,
@NotNull MoneyData amount, @NotNull InteropTransactionTypeData transactionType, String note,
GeoCodeData geoCode, LocalDateTime expiration, List<ExtensionData> extensionList) {
super(transactionCode, requestCode, accountId, amount, InteropTransactionRole.PAYER, transactionType, note, geoCode, expiration, extensionList);
}
public InteropTransactionRequestData(@NotNull String transactionCode, @NotNull String requestCode, @NotNull String accountId,
@NotNull MoneyData amount, @NotNull InteropTransactionTypeData transactionType) {
this(transactionCode, requestCode, accountId, amount, transactionType, null, null, null, null);
}
private InteropTransactionRequestData(InteropRequestData other) {
this(other.getTransactionCode(), other.getRequestCode(), other.getAccountId(), other.getAmount(), other.getTransactionType(),
other.getNote(), other.getGeoCode(), other.getExpiration(), other.getExtensionList());
}
@NotNull
@Transient
@Override
public InteropActionType getActionType() {
return InteropActionType.REQUEST;
}
@Transient
@NotNull
@Override
public String getIdentifier() {
return getRequestCode();
}
}
| 2,729 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/MoneyData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.apache.fineract.cn.deposit.api.v1.definition.domain.Currency;
import org.apache.fineract.cn.interoperation.api.v1.util.MathUtil;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
public class MoneyData {
@NotNull
@Min(0)
@Digits(integer = 15, fraction = 4) // interoperation schema allows integer = 18, AccountEntity amount allows fraction = 5
private BigDecimal amount;
@NotNull
@Length(min = 3, max = 3)
private String currency;
protected MoneyData() {
}
MoneyData(BigDecimal amount, String currency) {
this.amount = amount;
this.currency = currency;
}
public static MoneyData build(BigDecimal amount, String currency) {
return amount == null ? null : new MoneyData(amount, currency);
}
public static MoneyData build(BigDecimal amount, Currency currency) {
return amount == null ? null : build(amount, currency.getCode());
}
public BigDecimal getAmount() {
return amount;
}
public String getCurrency() {
return currency;
}
public void normalizeAmount(@NotNull Currency currency) {
if (!currency.getCode().equals(this.currency))
throw new UnsupportedOperationException("Internal error: Invalid currency " + currency.getCode());
MathUtil.normalize(amount, currency);
}
protected void setAmount(BigDecimal amount) {
this.amount = amount;
}
protected void setCurrency(String currency) {
this.currency = currency;
}
}
| 2,730 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/InteropQuoteResponseData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropActionState;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;
public class InteropQuoteResponseData extends InteropResponseData {
@NotNull
private final String quoteCode;
private MoneyData fspFee;
private MoneyData fspCommission;
private InteropQuoteResponseData(@NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, List<ExtensionData> extensionList, @NotNull String quoteCode,
MoneyData fspFee, MoneyData fspCommission) {
super(transactionCode, state, expiration, extensionList);
this.quoteCode = quoteCode;
this.fspFee = fspFee;
this.fspCommission = fspCommission;
}
public static InteropQuoteResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, List<ExtensionData> extensionList,
@NotNull String quoteCode, MoneyData fspFee, MoneyData fspCommission) {
return new InteropQuoteResponseData(transactionCode, state, expiration, extensionList, quoteCode, fspFee, fspCommission);
}
public static InteropQuoteResponseData build(@NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, @NotNull String quoteCode,
MoneyData fspFee, MoneyData fspCommission) {
return build(transactionCode, state, expiration, null, quoteCode, fspFee, fspCommission);
}
public String getQuoteCode() {
return quoteCode;
}
public MoneyData getFspFee() {
return fspFee;
}
public MoneyData getFspCommission() {
return fspCommission;
}
public void setFspCommission(MoneyData fspCommission) {
this.fspCommission = fspCommission;
}
}
| 2,731 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/data/InteropTransactionTypeData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.data;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropInitiatorType;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropTransactionRole;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropTransactionScenario;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
public class InteropTransactionTypeData {
@NotNull
private InteropTransactionScenario scenario;
@Pattern(regexp = "^[A-Z_]{1,32}$")
private String subScenario;
@NotNull
private InteropTransactionRole initiator;
@NotNull
private InteropInitiatorType initiatorType;
protected InteropTransactionTypeData() {
}
public InteropTransactionTypeData(InteropTransactionScenario scenario, String subScenario, InteropTransactionRole initiator, InteropInitiatorType initiatorType) {
this.scenario = scenario;
this.subScenario = subScenario;
this.initiator = initiator;
this.initiatorType = initiatorType;
}
public InteropTransactionScenario getScenario() {
return scenario;
}
public String getSubScenario() {
return subScenario;
}
public InteropTransactionRole getInitiator() {
return initiator;
}
public InteropInitiatorType getInitiatorType() {
return initiatorType;
}
protected void setScenario(InteropTransactionScenario scenario) {
this.scenario = scenario;
}
protected void setSubScenario(String subScenario) {
this.subScenario = subScenario;
}
protected void setInitiator(InteropTransactionRole initiator) {
this.initiator = initiator;
}
protected void setInitiatorType(InteropInitiatorType initiatorType) {
this.initiatorType = initiatorType;
}
}
| 2,732 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/domain/validation/InteroperationDataValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.domain.validation;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.InteropIdentifierCommand;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.InteropIdentifierDeleteCommand;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.InteropQuoteRequestData;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.InteropTransactionRequestData;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.InteropTransferCommand;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class InteroperationDataValidator {
public InteroperationDataValidator() {
}
public InteropIdentifierCommand registerAccountIdentifier(InteropIdentifierCommand requestData) {
return requestData;
}
public InteropIdentifierDeleteCommand deleteAccountIdentifier(InteropIdentifierDeleteCommand requestData) {
return requestData;
}
public InteropTransactionRequestData validateCreateRequest(InteropTransactionRequestData requestData) {
return requestData;
}
public InteropQuoteRequestData validateCreateQuote(InteropQuoteRequestData requestData) {
return requestData;
}
public InteropTransferCommand validatePrepareTransfer(InteropTransferCommand requestData) {
return validateCommitTransfer(requestData);
}
public InteropTransferCommand validateCommitTransfer(InteropTransferCommand requestData) {
return requestData;
}
private void throwExceptionIfValidationWarningsExist(List<String> errors) {
if (errors != null && !errors.isEmpty()) {
throw new UnsupportedOperationException(String.join(", ", errors)); // TODO
}
}
}
| 2,733 |
0 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1 | Create_ds/fineract-cn-interoperation/api/src/main/java/org/apache/fineract/cn/interoperation/api/v1/client/InteroperationManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.api.v1.client;
import org.apache.fineract.cn.api.util.CustomFeignClientsConfiguration;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@SuppressWarnings("unused")
@FeignClient(value = "interoperation-v1", path = "/interoperation/v1", configuration = CustomFeignClientsConfiguration.class)
public interface InteroperationManager {
@RequestMapping(
value = "/health",
method = RequestMethod.GET,
consumes = MediaType.ALL_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
void fetchActions();
}
| 2,734 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/InteropApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service;
import org.springframework.boot.SpringApplication;
public class InteropApplication {
public InteropApplication() {
super();
}
public static void main(String[] args) {
SpringApplication.run(InteropServiceConfiguration.class, args);
}
}
| 2,735 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/ServiceConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service;
public interface ServiceConstants {
String LOGGER_NAME = "interoperation-logger";
String GSON_NAME = "interoperation-gson";
}
| 2,736 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/InteropServiceConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service;
import com.google.gson.Gson;
import org.apache.fineract.cn.accounting.api.v1.client.LedgerManager;
import org.apache.fineract.cn.anubis.config.EnableAnubis;
import org.apache.fineract.cn.async.config.EnableAsync;
import org.apache.fineract.cn.cassandra.config.EnableCassandra;
import org.apache.fineract.cn.command.config.EnableCommandProcessing;
import org.apache.fineract.cn.deposit.api.v1.client.DepositAccountManager;
import org.apache.fineract.cn.lang.config.EnableServiceException;
import org.apache.fineract.cn.lang.config.EnableTenantContext;
import org.apache.fineract.cn.mariadb.config.EnableMariaDB;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SuppressWarnings("WeakerAccess")
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
@EnableAsync
@EnableTenantContext
@EnableCassandra
@EnableMariaDB
@EnableCommandProcessing
@EnableAnubis
@EnableServiceException
@EnableFeignClients(clients = {
LedgerManager.class,
DepositAccountManager.class
})
@ComponentScan({
"org.apache.fineract.cn.interoperation.service.rest",
"org.apache.fineract.cn.interoperation.service.internal.service",
"org.apache.fineract.cn.interoperation.service.internal.repository",
"org.apache.fineract.cn.interoperation.service.internal.command.handler",
"org.apache.fineract.cn.interoperation.api.v1.domain.validation",
"org.apache.fineract.cn.interoperation.internal.command.handler"
})
@EnableJpaRepositories(basePackages = "org.apache.fineract.cn.interoperation.service.internal.repository")
@EntityScan(basePackages = "org.apache.fineract.cn.interoperation.service.internal.repository")
public class InteropServiceConfiguration extends WebMvcConfigurerAdapter {
public InteropServiceConfiguration() {
super();
}
@Bean(name = ServiceConstants.LOGGER_NAME)
public Logger logger() {
return LoggerFactory.getLogger(ServiceConstants.LOGGER_NAME);
}
@Bean(name = ServiceConstants.GSON_NAME)
public Gson gson() {
return new Gson();
}
}
| 2,737 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/repository/InteropIdentifierRepository.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service.internal.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
@Repository
public interface InteropIdentifierRepository extends JpaRepository<InteropIdentifierEntity, Long>, JpaSpecificationExecutor<InteropIdentifierEntity> {
}
| 2,738 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/repository/InteropActionEntity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service.internal.repository;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropActionState;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropActionType;
import org.apache.fineract.cn.mariadb.util.LocalDateTimeConverter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Entity
@Table(name = "hathor_actions", uniqueConstraints = {
@UniqueConstraint(name = "uk_hathor_actions_id", columnNames = {"identifier"}),
@UniqueConstraint(name = "uk_hathor_actions_type", columnNames = {"transaction_id", "action_type"}),
@UniqueConstraint(name = "uk_hathor_actions_seq", columnNames = {"transaction_id", "seq_no"})
})
public class InteropActionEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "identifier", nullable = false, length = 64)
private String identifier;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "transaction_id", referencedColumnName="id", nullable = false)
private InteropTransactionEntity transaction;
@Column(name = "action_type", nullable = false, length = 32)
@Enumerated(EnumType.STRING)
private InteropActionType actionType;
@Column(name = "seq_no", nullable = false)
private int seqNo;
@Column(name = "state", nullable = false, length = 32)
@Enumerated(EnumType.STRING)
private InteropActionState state;
@Column(name = "amount", nullable = false)
private BigDecimal amount;
@Column(name = "fee")
private BigDecimal fee;
@Column(name = "commission")
private BigDecimal commission;
//
// @Column(name = "charges", nullable = false, length = 1024)
// private String charges;
//
// @Column(name = "ledgers", nullable = false, length = 1024)
// private String ledgers;
@Column(name = "error_code", length = 4)
private String errorCode;
@Column(name = "error_msg", length = 128)
private String errorMsg;
@Column(name = "expiration_date")
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime expirationDate;
@Column(name = "created_by", nullable = false, length = 32)
private String createdBy;
@Column(name = "created_on", nullable = false)
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime createdOn;
protected InteropActionEntity() {
}
public InteropActionEntity(@NotNull String identifier, @NotNull InteropTransactionEntity transaction, @NotNull InteropActionType actionType,
int seqNo, @NotNull String createdBy, @NotNull LocalDateTime createdOn) {
this.identifier = identifier;
this.transaction = transaction;
this.actionType = actionType;
this.seqNo = seqNo;
this.createdBy = createdBy;
this.createdOn = createdOn;
}
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public String getIdentifier() {
return identifier;
}
private void setIdentifier(String identifier) {
this.identifier = identifier;
}
public InteropTransactionEntity getTransaction() {
return transaction;
}
private void setTransaction(InteropTransactionEntity transaction) {
this.transaction = transaction;
}
public InteropActionType getActionType() {
return actionType;
}
private void setActionType(InteropActionType actionType) {
this.actionType = actionType;
}
public int getSeqNo() {
return seqNo;
}
private void setSeqNo(int seqNo) {
this.seqNo = seqNo;
}
public InteropActionState getState() {
return state;
}
public void setState(InteropActionState state) {
this.state = state;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public BigDecimal getFee() {
return fee;
}
public void setFee(BigDecimal fee) {
this.fee = fee;
}
public BigDecimal getCommission() {
return commission;
}
public void setCommission(BigDecimal commission) {
this.commission = commission;
}
//
// public String getCharges() {
// return charges;
// }
//
// public void setCharges(String charges) {
// this.charges = charges;
// }
//
// public String getLedgers() {
// return ledgers;
// }
//
// public void setLedgers(String ledgers) {
// this.ledgers = ledgers;
// }
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public LocalDateTime getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(LocalDateTime expirationDate) {
this.expirationDate = expirationDate;
}
public String getCreatedBy() {
return createdBy;
}
private void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public LocalDateTime getCreatedOn() {
return createdOn;
}
private void setCreatedOn(LocalDateTime createdOn) {
this.createdOn = createdOn;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InteropActionEntity that = (InteropActionEntity) o;
return identifier.equals(that.identifier);
}
@Override
public int hashCode() {
return identifier.hashCode();
}
}
| 2,739 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/repository/InteropTransactionEntity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service.internal.repository;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropState;
import org.apache.fineract.cn.interoperation.api.v1.domain.TransactionType;
import org.apache.fineract.cn.mariadb.util.LocalDateTimeConverter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "hathor_transactions", uniqueConstraints = {@UniqueConstraint(name = "uk_hathor_transactions_id", columnNames = {"identifier"})})
public class InteropTransactionEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "identifier", nullable = false, length = 36)
private String identifier;
@Column(name = "a_name", length = 256)
private String name;
@Column(name = "description", length = 1024)
private String description;
@Column(name = "transaction_type", nullable = false, length = 32)
@Enumerated(EnumType.STRING)
private TransactionType transactionType;
@Column(name = "amount", nullable = false)
private BigDecimal amount;
@Column(name = "state", nullable = false, length = 32)
@Enumerated(EnumType.STRING)
private InteropState state;
@Column(name = "customer_account_identifier", nullable = false, length = 32)
private String customerAccountIdentifier;
@Column(name = "payable_account_identifier", length = 32)
private String prepareAccountIdentifier;
@Column(name = "nostro_account_identifier", nullable = false, length = 32)
private String nostroAccountIdentifier;
@Column(name = "transaction_date")
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime transactionDate;
@Column(name = "expiration_date")
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime expirationDate;
@Column(name = "created_by", nullable = false, length = 32)
private String createdBy;
@Column(name = "created_on", nullable = false)
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime createdOn;
@Column(name = "last_modified_by", length = 32)
private String lastModifiedBy;
@Column(name = "last_modified_on")
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime lastModifiedOn;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "transaction", orphanRemoval = true, fetch=FetchType.LAZY)
@OrderBy("seqNo")
private List<InteropActionEntity> actions = new ArrayList<>();
protected InteropTransactionEntity() {
}
public InteropTransactionEntity(@NotNull String identifier, @NotNull String customerAccountIdentifier, @NotNull String createdBy,
@NotNull LocalDateTime createdOn) {
this.identifier = identifier;
this.customerAccountIdentifier = customerAccountIdentifier;
this.createdBy = createdBy;
this.createdOn = createdOn;
}
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public String getIdentifier() {
return identifier;
}
private void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public TransactionType getTransactionType() {
return transactionType;
}
public void setTransactionType(TransactionType transactionType) {
this.transactionType = transactionType;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public InteropState getState() {
return state;
}
public void setState(InteropState state) {
this.state = state;
}
public String getCustomerAccountIdentifier() {
return customerAccountIdentifier;
}
private void setCustomerAccountIdentifier(String customerAccountIdentifier) {
this.customerAccountIdentifier = customerAccountIdentifier;
}
public String getPrepareAccountIdentifier() {
return prepareAccountIdentifier;
}
public void setPrepareAccountIdentifier(String prepareAccountIdentifier) {
this.prepareAccountIdentifier = prepareAccountIdentifier;
}
public String getNostroAccountIdentifier() {
return nostroAccountIdentifier;
}
public void setNostroAccountIdentifier(String nostroAccountIdentifier) {
this.nostroAccountIdentifier = nostroAccountIdentifier;
}
public LocalDateTime getTransactionDate() {
return transactionDate;
}
public void setTransactionDate(LocalDateTime transactionDate) {
this.transactionDate = transactionDate;
}
public LocalDateTime getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(LocalDateTime expirationDate) {
this.expirationDate = expirationDate;
}
public String getCreatedBy() {
return createdBy;
}
private void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public LocalDateTime getCreatedOn() {
return createdOn;
}
private void setCreatedOn(LocalDateTime createdOn) {
this.createdOn = createdOn;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public LocalDateTime getLastModifiedOn() {
return lastModifiedOn;
}
public void setLastModifiedOn(LocalDateTime lastModifiedOn) {
this.lastModifiedOn = lastModifiedOn;
}
public List<InteropActionEntity> getActions() {
return actions;
}
public void setActions(List<InteropActionEntity> actions) {
this.actions = actions;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InteropTransactionEntity that = (InteropTransactionEntity) o;
return identifier.equals(that.identifier);
}
@Override
public int hashCode() {
return identifier.hashCode();
}
}
| 2,740 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/repository/InteropIdentifierEntity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service.internal.repository;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropIdentifierType;
import org.apache.fineract.cn.mariadb.util.LocalDateTimeConverter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
@Entity
@Table(name = "hathor_identifiers", uniqueConstraints = {
@UniqueConstraint(name = "uk_hathor_identifiers_value", columnNames = {"type", "a_value", "sub_value_or_type"})
})
public class InteropIdentifierEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "customer_account_identifier", nullable = false, length = 32)
private String customerAccountIdentifier;
@Column(name = "type", nullable = false, length = 32)
@Enumerated(EnumType.STRING)
private InteropIdentifierType type;
@Column(name = "a_value", nullable = false, length = 128)
private String value;
@Column(name = "sub_value_or_type", length = 128)
private String subValueOrType;
@Column(name = "created_by", nullable = false, length = 32)
private String createdBy;
@Column(name = "created_on", nullable = false)
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime createdOn;
@Column(name = "last_modified_by", length = 32)
private String lastModifiedBy;
@Column(name = "last_modified_on")
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime lastModifiedOn;
protected InteropIdentifierEntity() {
}
public InteropIdentifierEntity(@NotNull String customerAccountIdentifier, @NotNull InteropIdentifierType type, @NotNull String value,
String subValueOrType, @NotNull String createdBy, @NotNull LocalDateTime createdOn) {
this.customerAccountIdentifier = customerAccountIdentifier;
this.type = type;
this.value = value;
this.subValueOrType = subValueOrType;
this.createdBy = createdBy;
this.createdOn = createdOn;
}
public InteropIdentifierEntity(@NotNull String customerAccountIdentifier, @NotNull InteropIdentifierType type, @NotNull String createdBy,
@NotNull LocalDateTime createdOn) {
this(customerAccountIdentifier, type, null, null, createdBy, createdOn);
}
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public String getCustomerAccountIdentifier() {
return customerAccountIdentifier;
}
private void setCustomerAccountIdentifier(String customerAccountIdentifier) {
this.customerAccountIdentifier = customerAccountIdentifier;
}
public InteropIdentifierType getType() {
return type;
}
private void setType(InteropIdentifierType type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getSubValueOrType() {
return subValueOrType;
}
public void setSubValueOrType(String subValueOrType) {
this.subValueOrType = subValueOrType;
}
public String getCreatedBy() {
return createdBy;
}
private void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public LocalDateTime getCreatedOn() {
return createdOn;
}
private void setCreatedOn(LocalDateTime createdOn) {
this.createdOn = createdOn;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public LocalDateTime getLastModifiedOn() {
return lastModifiedOn;
}
public void setLastModifiedOn(LocalDateTime lastModifiedOn) {
this.lastModifiedOn = lastModifiedOn;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InteropIdentifierEntity that = (InteropIdentifierEntity) o;
if (!customerAccountIdentifier.equals(that.customerAccountIdentifier)) return false;
if (type != that.type) return false;
if (!value.equals(that.value)) return false;
return subValueOrType != null ? subValueOrType.equals(that.subValueOrType) : that.subValueOrType == null;
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + value.hashCode();
result = 31 * result + (subValueOrType != null ? subValueOrType.hashCode() : 0);
return result;
}
}
| 2,741 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/repository/InteropActionRepository.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service.internal.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import javax.validation.constraints.NotNull;
@Repository
public interface InteropActionRepository extends JpaRepository<InteropActionEntity, Long> {
InteropActionEntity findByIdentifier(@NotNull String identifier);
}
| 2,742 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/repository/InteropTransactionRepository.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service.internal.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import javax.validation.constraints.NotNull;
@Repository
public interface InteropTransactionRepository extends JpaRepository<InteropTransactionEntity, Long> {
InteropTransactionEntity findOneByIdentifier(@NotNull String identifier);
}
| 2,743 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/command/InitializeServiceCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service.internal.command;
public class InitializeServiceCommand {
public InitializeServiceCommand() {
super();
}
}
| 2,744 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/command | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/command/handler/MigrationAggregate.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service.internal.command.handler;
import org.apache.fineract.cn.command.annotation.Aggregate;
import org.apache.fineract.cn.command.annotation.CommandHandler;
import org.apache.fineract.cn.command.annotation.EventEmitter;
import org.apache.fineract.cn.interoperation.api.v1.EventConstants;
import org.apache.fineract.cn.interoperation.service.ServiceConstants;
import org.apache.fineract.cn.interoperation.service.internal.command.InitializeServiceCommand;
import org.apache.fineract.cn.lang.ApplicationName;
import org.apache.fineract.cn.mariadb.domain.FlywayFactoryBean;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
@Aggregate
public class MigrationAggregate {
private final Logger logger;
private final DataSource dataSource;
private final FlywayFactoryBean flywayFactoryBean;
private final ApplicationName applicationName;
@Autowired
public MigrationAggregate(@Qualifier(ServiceConstants.LOGGER_NAME) final Logger logger,
final DataSource dataSource,
final FlywayFactoryBean flywayFactoryBean,
final ApplicationName applicationName) {
super();
this.logger = logger;
this.dataSource = dataSource;
this.flywayFactoryBean = flywayFactoryBean;
this.applicationName = applicationName;
}
@CommandHandler
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.INITIALIZE)
@Transactional
public String process(final InitializeServiceCommand initializeCommand) {
this.logger.info("Starting migration for interoperation version: {}.", applicationName.getVersionString());
this.flywayFactoryBean.create(this.dataSource).migrate();
return EventConstants.INITIALIZE;
}
}
| 2,745 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/command | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/command/handler/InteropHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service.internal.command.handler;
import org.apache.fineract.cn.command.annotation.Aggregate;
import org.apache.fineract.cn.command.annotation.CommandHandler;
import org.apache.fineract.cn.command.annotation.CommandLogLevel;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.InteropIdentifierCommand;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.InteropIdentifierData;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.InteropIdentifierDeleteCommand;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.InteropQuoteRequestData;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.InteropQuoteResponseData;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.InteropTransactionRequestData;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.InteropTransactionRequestResponseData;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.InteropTransferCommand;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.InteropTransferResponseData;
import org.apache.fineract.cn.interoperation.api.v1.domain.validation.InteroperationDataValidator;
import org.apache.fineract.cn.interoperation.service.ServiceConstants;
import org.apache.fineract.cn.interoperation.service.internal.service.InteropService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import javax.validation.constraints.NotNull;
@SuppressWarnings("unused")
@Aggregate
public class InteropHandler {
private final Logger logger;
private final InteroperationDataValidator dataValidator;
private final InteropService interopService;
@Autowired
public InteropHandler(@Qualifier(ServiceConstants.LOGGER_NAME) final Logger logger,
InteroperationDataValidator interoperationDataValidator,
InteropService interopService) {
this.logger = logger;
this.dataValidator = interoperationDataValidator;
this.interopService = interopService;
}
@NotNull
@Transactional
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
public InteropIdentifierData registerAccountIdentifier(@NotNull InteropIdentifierCommand command) {
command = dataValidator.registerAccountIdentifier(command);
return interopService.registerAccountIdentifier(command);
}
@NotNull
@Transactional
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
public InteropIdentifierData deleteAccountIdentifier(@NotNull InteropIdentifierDeleteCommand command) {
command = dataValidator.deleteAccountIdentifier(command);
return interopService.deleteAccountIdentifier(command);
}
@NotNull
@Transactional
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
public InteropTransactionRequestResponseData createTransactionRequest(@NotNull InteropTransactionRequestData command) {
// only when Payee request transaction from Payer, so here role must be always Payer
command = dataValidator.validateCreateRequest(command);
return interopService.createTransactionRequest(command);
}
@NotNull
@Transactional
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
public InteropQuoteResponseData createQuote(@NotNull InteropQuoteRequestData command) {
command = dataValidator.validateCreateQuote(command);
return interopService.createQuote(command);
}
@NotNull
@Transactional
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
public InteropTransferResponseData performTransfer(@NotNull InteropTransferCommand command) {
switch (command.getAction()) {
case PREPARE: {
command = dataValidator.validatePrepareTransfer(command);
return interopService.prepareTransfer(command);
}
case CREATE: {
command = dataValidator.validateCommitTransfer(command);
return interopService.commitTransfer(command);
}
default:
return null;
}
}
}
| 2,746 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/service/InteropService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service.internal.service;
import org.apache.fineract.cn.accounting.api.v1.domain.Account;
import org.apache.fineract.cn.accounting.api.v1.domain.AccountType;
import org.apache.fineract.cn.accounting.api.v1.domain.Creditor;
import org.apache.fineract.cn.accounting.api.v1.domain.Debtor;
import org.apache.fineract.cn.accounting.api.v1.domain.JournalEntry;
import org.apache.fineract.cn.api.util.UserContextHolder;
import org.apache.fineract.cn.deposit.api.v1.definition.domain.Charge;
import org.apache.fineract.cn.deposit.api.v1.definition.domain.Currency;
import org.apache.fineract.cn.deposit.api.v1.definition.domain.ProductDefinition;
import org.apache.fineract.cn.deposit.api.v1.instance.domain.ProductInstance;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropActionState;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropActionType;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropIdentifierType;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropState;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropStateMachine;
import org.apache.fineract.cn.interoperation.api.v1.domain.TransactionType;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.*;
import org.apache.fineract.cn.interoperation.api.v1.util.MathUtil;
import org.apache.fineract.cn.interoperation.service.ServiceConstants;
import org.apache.fineract.cn.interoperation.service.internal.repository.InteropActionEntity;
import org.apache.fineract.cn.interoperation.service.internal.repository.InteropActionRepository;
import org.apache.fineract.cn.interoperation.service.internal.repository.InteropIdentifierEntity;
import org.apache.fineract.cn.interoperation.service.internal.repository.InteropIdentifierRepository;
import org.apache.fineract.cn.interoperation.service.internal.repository.InteropTransactionEntity;
import org.apache.fineract.cn.interoperation.service.internal.repository.InteropTransactionRepository;
import org.apache.fineract.cn.interoperation.service.internal.service.helper.InteropAccountingService;
import org.apache.fineract.cn.interoperation.service.internal.service.helper.InteropDepositService;
import org.apache.fineract.cn.lang.DateConverter;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.MathContext;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
//import static org.apache.fineract.cn.interoperation.api.v1.util.InteroperationUtil.DEFAULT_ROUTING_CODE;
@Service
public class InteropService {
public static final String ACCOUNT_NAME_NOSTRO = "Interoperation NOSTRO";
private final Logger logger;
private final InteropIdentifierRepository identifierRepository;
private final InteropTransactionRepository transactionRepository;
private final InteropActionRepository actionRepository;
private final InteropDepositService depositService;
private final InteropAccountingService accountingService;
@Autowired
public InteropService(@Qualifier(ServiceConstants.LOGGER_NAME) final Logger logger,
InteropIdentifierRepository interopIdentifierRepository,
InteropTransactionRepository interopTransactionRepository,
InteropActionRepository interopActionRepository,
InteropDepositService interopDepositService,
InteropAccountingService interopAccountingService) {
this.logger = logger;
this.identifierRepository = interopIdentifierRepository;
this.transactionRepository = interopTransactionRepository;
this.actionRepository = interopActionRepository;
this.depositService = interopDepositService;
this.accountingService = interopAccountingService;
}
@NotNull
public InteropIdentifierData getAccountByIdentifier(@NotNull InteropIdentifierType idType, @NotNull String idValue, String subIdOrType) {
InteropIdentifierEntity identifier = findIdentifier(idType, idValue, subIdOrType);
if (identifier == null)
throw new UnsupportedOperationException("Account not found for identifier " + idType + "/" + idValue + (subIdOrType == null ? "" : ("/" + subIdOrType)));
return new InteropIdentifierData(identifier.getCustomerAccountIdentifier());
}
@NotNull
@Transactional(propagation = Propagation.MANDATORY)
public InteropIdentifierData registerAccountIdentifier(@NotNull InteropIdentifierCommand request) {
//TODO: error handling
String accountId = request.getAccountId();
validateAndGetAccount(accountId);
String createdBy = getLoginUser();
LocalDateTime createdOn = getNow();
InteropIdentifierEntity identifier = new InteropIdentifierEntity(accountId, request.getIdType(), request.getIdValue(),
request.getSubIdOrType(), createdBy, createdOn);
identifierRepository.save(identifier);
return new InteropIdentifierData(accountId);
}
@NotNull
@Transactional(propagation = Propagation.MANDATORY)
public InteropIdentifierData deleteAccountIdentifier(@NotNull InteropIdentifierDeleteCommand request) {
InteropIdentifierType idType = request.getIdType();
String idValue = request.getIdValue();
String subIdOrType = request.getSubIdOrType();
InteropIdentifierEntity identifier = findIdentifier(idType, idValue, subIdOrType);
if (identifier == null)
throw new UnsupportedOperationException("Account not found for identifier " + idType + "/" + idValue + (subIdOrType == null ? "" : ("/" + subIdOrType)));
String customerAccountIdentifier = identifier.getCustomerAccountIdentifier();
identifierRepository.delete(identifier);
return new InteropIdentifierData(customerAccountIdentifier);
}
public InteropTransactionRequestResponseData getTransactionRequest(@NotNull String transactionCode, @NotNull String requestCode) {
InteropActionEntity action = validateAndGetAction(transactionCode, calcActionIdentifier(requestCode, InteropActionType.REQUEST),
InteropActionType.REQUEST);
return InteropTransactionRequestResponseData.build(transactionCode, action.getState(), action.getExpirationDate(), requestCode);
}
@NotNull
@Transactional(propagation = Propagation.MANDATORY)
public InteropTransactionRequestResponseData createTransactionRequest(@NotNull InteropTransactionRequestData request) {
// only when Payee request transaction from Payer, so here role must be always Payer
//TODO: error handling
AccountWrapper accountWrapper = validateAndGetAccount(request);
//TODO: transaction expiration separated from action expiration
InteropTransactionEntity transaction = validateAndGetTransaction(request, accountWrapper);
InteropActionEntity action = addAction(transaction, request);
transactionRepository.save(transaction);
return InteropTransactionRequestResponseData.build(request.getTransactionCode(), action.getState(), action.getExpirationDate(),
request.getExtensionList(), request.getRequestCode());
}
public InteropQuoteResponseData getQuote(@NotNull String transactionCode, @NotNull String quoteCode) {
InteropActionEntity action = validateAndGetAction(transactionCode, calcActionIdentifier(quoteCode, InteropActionType.QUOTE),
InteropActionType.QUOTE);
Currency currency = getCurrency(action);
return InteropQuoteResponseData.build(transactionCode, action.getState(), action.getExpirationDate(), quoteCode,
MoneyData.build(action.getFee(), currency), MoneyData.build(action.getCommission(), currency));
}
@NotNull
@Transactional(propagation = Propagation.MANDATORY)
public InteropQuoteResponseData createQuote(@NotNull InteropQuoteRequestData request) {
//TODO: error handling
AccountWrapper accountWrapper = validateAndGetAccount(request);
//TODO: transaction expiration separated from action expiration
InteropTransactionEntity transaction = validateAndGetTransaction(request, accountWrapper);
TransactionType transactionType = request.getTransactionRole().getTransactionType();
String accountId = accountWrapper.account.getIdentifier();
List<Charge> charges = depositService.getCharges(accountId, transactionType);
BigDecimal amount = request.getAmount().getAmount();
BigDecimal fee = MathUtil.normalize(calcTotalCharges(charges, amount), MathUtil.DEFAULT_MATH_CONTEXT);
Double withdrawableBalance = getWithdrawableBalance(accountWrapper.account, accountWrapper.productDefinition);
boolean withdraw = request.getTransactionRole().isWithdraw();
BigDecimal total = MathUtil.nullToZero(withdraw ? MathUtil.add(amount, fee) : fee);
if (withdraw && withdrawableBalance < total.doubleValue())
throw new UnsupportedOperationException("Account balance is not enough to pay the fee " + accountId);
// TODO add action and set the status to failed in separated transaction
InteropActionEntity action = addAction(transaction, request);
action.setFee(fee);
// TODO: extend Charge with a property that could be stored in charges
transactionRepository.save(transaction);
InteropQuoteResponseData build = InteropQuoteResponseData.build(request.getTransactionCode(), action.getState(),
action.getExpirationDate(), request.getExtensionList(), request.getQuoteCode(),
MoneyData.build(fee, accountWrapper.productDefinition.getCurrency()), null);
return build;
}
public InteropTransferResponseData getTransfer(@NotNull String transactionCode, @NotNull String transferCode) {
InteropActionEntity action = validateAndGetAction(transactionCode, calcActionIdentifier(transferCode, InteropActionType.PREPARE),
InteropActionType.PREPARE, false);
if (action == null)
action = validateAndGetAction(transactionCode, calcActionIdentifier(transferCode, InteropActionType.COMMIT),
InteropActionType.COMMIT);
return InteropTransferResponseData.build(transactionCode, action.getState(), action.getExpirationDate(), transferCode, action.getCreatedOn());
}
@NotNull
@Transactional(propagation = Propagation.MANDATORY)
public InteropTransferResponseData prepareTransfer(@NotNull InteropTransferCommand request) {
//TODO: error handling
//TODO: ABORT
AccountWrapper accountWrapper = validateAndGetAccount(request);
LocalDateTime transactionDate = getNow();
//TODO: transaction expiration separated from action expiration
InteropTransactionEntity transaction = validateAndGetTransaction(request, accountWrapper, transactionDate, true);
validateTransfer(request, accountWrapper);
TransactionType transactionType = request.getTransactionRole().getTransactionType();
List<Charge> charges = depositService.getCharges(accountWrapper.account.getIdentifier(), transactionType);
// TODO add action and set the status to failed in separated transaction
InteropActionEntity action = addAction(transaction, request, transactionDate);
MoneyData fee = request.getFspFee();
action.setFee(fee == null ? null : fee.getAmount());
// TODO: extend Charge with a property that could be stored in charges
prepareTransfer(request, accountWrapper, action, charges, transactionDate);
transactionRepository.save(transaction);
return InteropTransferResponseData.build(request.getTransferCode(), action.getState(), action.getExpirationDate(),
request.getExtensionList(), request.getTransferCode(), transactionDate);
}
@NotNull
@Transactional(propagation = Propagation.MANDATORY)
public InteropTransferResponseData commitTransfer(@NotNull InteropTransferCommand request) {
//TODO: error handling
//TODO: ABORT
AccountWrapper accountWrapper = validateAndGetAccount(request);
LocalDateTime transactionDate = getNow();
//TODO: transaction expiration separated from action expiration
InteropTransactionEntity transaction = validateAndGetTransaction(request, accountWrapper, transactionDate, true);
transaction.setTransactionDate(transactionDate);
validateTransfer(request, accountWrapper);
TransactionType transactionType = request.getTransactionRole().getTransactionType();
List<Charge> charges = depositService.getCharges(accountWrapper.account.getIdentifier(), transactionType);
// TODO add action and set the status to failed in separated transaction
InteropActionEntity action = addAction(transaction, request, transactionDate);
MoneyData fee = request.getFspFee();
action.setFee(fee == null ? null : fee.getAmount());
// TODO: extend Charge with a property that could be stored in charges
bookTransfer(request, accountWrapper, action, charges, transactionDate);
transactionRepository.save(transaction);
return InteropTransferResponseData.build(request.getTransferCode(), action.getState(), action.getExpirationDate(),
request.getExtensionList(), request.getTransferCode(), transactionDate);
}
Double getWithdrawableBalance(Account account, ProductDefinition productDefinition) {
// on-hold amount, if any, is subtracted to payable account
return MathUtil.subtractToZero(account.getBalance(), productDefinition.getMinimumBalance());
}
private void prepareTransfer(@NotNull InteropTransferCommand request, @NotNull AccountWrapper accountWrapper, @NotNull InteropActionEntity action,
List<Charge> charges, LocalDateTime transactionDate) {
BigDecimal amount = request.getAmount().getAmount();
// TODO: validate amount with quote amount
boolean isDebit = request.getTransactionRole().isWithdraw();
if (!isDebit)
return;
String prepareAccountId = action.getTransaction().getPrepareAccountIdentifier();
Account payableAccount = prepareAccountId == null ? null : validateAndGetAccount(request, prepareAccountId);
if (payableAccount == null) {
logger.warn("Can not prepare transfer: Payable account was not found for " + accountWrapper.account.getIdentifier());
return;
}
final JournalEntry journalEntry = createJournalEntry(action.getIdentifier(), TransactionType.CURRENCY_WITHDRAWAL.getCode(),
DateConverter.toIsoString(transactionDate), request.getNote(), getLoginUser());
HashSet<Debtor> debtors = new HashSet<>(1);
HashSet<Creditor> creditors = new HashSet<>(1);
addCreditor(accountWrapper.account.getIdentifier(), amount.doubleValue(), creditors);
addDebtor(payableAccount.getIdentifier(), amount.doubleValue(), debtors);
prepareCharges(request, accountWrapper, action, charges, payableAccount, debtors, creditors);
if (debtors.isEmpty()) // must be same size as creditors
return;
journalEntry.setDebtors(debtors);
journalEntry.setCreditors(creditors);
accountingService.createJournalEntry(journalEntry);
}
private void prepareCharges(@NotNull InteropTransferCommand request, @NotNull AccountWrapper accountWrapper, @NotNull InteropActionEntity action,
@NotNull List<Charge> charges, Account payableAccount, HashSet<Debtor> debtors, HashSet<Creditor> creditors) {
MoneyData fspFee = request.getFspFee(); // TODO compare with calculated and with quote
BigDecimal amount = request.getAmount().getAmount();
Currency currency = accountWrapper.productDefinition.getCurrency();
BigDecimal total = MathUtil.normalize(calcTotalCharges(charges, amount), currency);
if (MathUtil.isEmpty(total)) {
return;
}
if (creditors == null) {
creditors = new HashSet<>(1);
}
if (debtors == null) {
debtors = new HashSet<>(charges.size());
}
addCreditor(accountWrapper.account.getIdentifier(), total.doubleValue(), creditors);
addDebtor(payableAccount.getIdentifier(), total.doubleValue(), debtors);
}
private void bookTransfer(@NotNull InteropTransferCommand request, @NotNull AccountWrapper accountWrapper, @NotNull InteropActionEntity action,
List<Charge> charges, LocalDateTime transactionDate) {
boolean isDebit = request.getTransactionRole().isWithdraw();
String accountId = accountWrapper.account.getIdentifier();
String message = request.getNote();
double doubleAmount = request.getAmount().getAmount().doubleValue();
String loginUser = getLoginUser();
String transactionTypeCode = (isDebit ? TransactionType.CURRENCY_WITHDRAWAL : TransactionType.CURRENCY_DEPOSIT).getCode();
String transactionDateString = DateConverter.toIsoString(transactionDate);
InteropTransactionEntity transaction = action.getTransaction();
Account nostroAccount = validateAndGetAccount(request, transaction.getNostroAccountIdentifier());
Account payableAccount = null;
double preparedAmount = 0d;
double accountNostroAmount = doubleAmount;
if (isDebit) {
InteropActionEntity prepareAction = findAction(transaction, InteropActionType.PREPARE);
if (prepareAction != null) {
JournalEntry prepareJournal = accountingService.findJournalEntry(prepareAction.getIdentifier());
if (prepareJournal == null)
throw new UnsupportedOperationException("Can not find prepare result for " + action.getActionType() +
"/" + request.getIdentifier());
payableAccount = validateAndGetAccount(request, transaction.getPrepareAccountIdentifier());
preparedAmount = prepareJournal.getDebtors().stream().mapToDouble(d -> Double.valueOf(d.getAmount())).sum();
if (preparedAmount < doubleAmount)
throw new UnsupportedOperationException("Prepared amount " + preparedAmount + " is less than transfer amount " +
doubleAmount + " for " + request.getIdentifier());
// now fails if prepared is not enough
accountNostroAmount = preparedAmount >= doubleAmount ? 0d : doubleAmount - preparedAmount;
double fromPrepareToNostroAmount = doubleAmount - accountNostroAmount;
preparedAmount -= fromPrepareToNostroAmount;
if (fromPrepareToNostroAmount > 0) {
final JournalEntry fromPrepareToNostroEntry = createJournalEntry(action.getIdentifier(),
transactionTypeCode, transactionDateString, message + " #commit", loginUser);
HashSet<Debtor> debtors = new HashSet<>(1);
HashSet<Creditor> creditors = new HashSet<>(1);
addCreditor(payableAccount.getIdentifier(), fromPrepareToNostroAmount, creditors);
addDebtor(nostroAccount.getIdentifier(), fromPrepareToNostroAmount, debtors);
fromPrepareToNostroEntry.setDebtors(debtors);
fromPrepareToNostroEntry.setCreditors(creditors);
accountingService.createJournalEntry(fromPrepareToNostroEntry);
}
}
}
if (accountNostroAmount > 0) {
// can not happen that prepared amount is less than requested transfer amount (identifier and message can be default)
final JournalEntry journalEntry = createJournalEntry(action.getIdentifier(), transactionTypeCode,
transactionDateString, message/* + (payableAccount == null ? "" : " #difference")*/, loginUser);
HashSet<Debtor> debtors = new HashSet<>(1);
HashSet<Creditor> creditors = new HashSet<>(1);
addCreditor(isDebit ? accountId : nostroAccount.getIdentifier(), accountNostroAmount, creditors);
addDebtor(isDebit ? nostroAccount.getIdentifier() : accountId, accountNostroAmount, debtors);
journalEntry.setDebtors(debtors);
journalEntry.setCreditors(creditors);
accountingService.createJournalEntry(journalEntry);
}
preparedAmount = bookCharges(request, accountWrapper, action, charges, payableAccount, preparedAmount, transactionDate);
if (preparedAmount > 0) {
// throw new UnsupportedOperationException("Prepared amount differs from transfer amount " + doubleAmount + " for " + request.getIdentifier());
// transfer back remaining prepared amount TODO: JM maybe fail this case?
final JournalEntry fromPrepareToAccountEntry = createJournalEntry(action.getIdentifier() + InteropRequestData.IDENTIFIER_SEPARATOR + "diff",
transactionTypeCode, transactionDateString, message + " #release difference", loginUser);
HashSet<Debtor> debtors = new HashSet<>(1);
HashSet<Creditor> creditors = new HashSet<>(1);
addCreditor(payableAccount.getIdentifier(), preparedAmount, creditors);
addDebtor(accountId, preparedAmount, debtors);
fromPrepareToAccountEntry.setDebtors(debtors);
fromPrepareToAccountEntry.setCreditors(creditors);
accountingService.createJournalEntry(fromPrepareToAccountEntry);
}
}
private double bookCharges(@NotNull InteropTransferCommand request, @NotNull AccountWrapper accountWrapper, @NotNull InteropActionEntity action,
@NotNull List<Charge> charges, Account payableAccount, double preparedAmount, LocalDateTime transactionDate) {
boolean isDebit = request.getTransactionRole().isWithdraw();
String accountId = accountWrapper.account.getIdentifier();
String message = request.getNote();
BigDecimal amount = request.getAmount().getAmount();
Currency currency = accountWrapper.productDefinition.getCurrency();
BigDecimal calcFee = MathUtil.normalize(calcTotalCharges(charges, amount), currency);
BigDecimal requestFee = request.getFspFee().getAmount();
if (!MathUtil.isEqualTo(calcFee, requestFee))
throw new UnsupportedOperationException("Quote fee " + requestFee + " differs from transfer fee " + calcFee);
if (MathUtil.isEmpty(calcFee)) {
return preparedAmount;
}
String loginUser = getLoginUser();
String transactionTypeCode = (isDebit ? TransactionType.CURRENCY_WITHDRAWAL : TransactionType.CURRENCY_DEPOSIT).getCode();
String transactionDateString = DateConverter.toIsoString(transactionDate);
ArrayList<Charge> unpaidCharges = new ArrayList<>(charges);
if (preparedAmount > 0) {
InteropActionEntity prepareAction = findAction(action.getTransaction(), InteropActionType.PREPARE);
if (prepareAction != null) {
final JournalEntry fromPrepareToRevenueEntry = createJournalEntry(action.getIdentifier() + InteropRequestData.IDENTIFIER_SEPARATOR + "fee",
transactionTypeCode, transactionDateString, message + " #commit fee", loginUser);
double payedAmount = 0d;
HashSet<Debtor> debtors = new HashSet<>(1);
HashSet<Creditor> creditors = new HashSet<>(1);
for (Charge charge : charges) {
BigDecimal value = calcChargeAmount(amount, charge, currency, true);
if (value == null)
continue;
double doubleValue = value.doubleValue();
if (doubleValue > preparedAmount) {
break;
}
unpaidCharges.remove(charge);
preparedAmount -= doubleValue;
payedAmount += doubleValue;
addDebtor(charge.getIncomeAccountIdentifier(), doubleValue, debtors);
}
if (!unpaidCharges.isEmpty())
throw new UnsupportedOperationException("Prepared amount " + preparedAmount + " is less than transfer fee amount for " +
request.getIdentifier());
if (payedAmount > 0) {
addCreditor(payableAccount.getIdentifier(), payedAmount, creditors);
fromPrepareToRevenueEntry.setDebtors(debtors);
fromPrepareToRevenueEntry.setCreditors(creditors);
accountingService.createJournalEntry(fromPrepareToRevenueEntry);
}
}
}
if (!unpaidCharges.isEmpty()) {
// can not happen that prepared amount is more or less than requested transfer amount (identifier and message can be default)
final JournalEntry journalEntry = createJournalEntry(action.getIdentifier() + InteropRequestData.IDENTIFIER_SEPARATOR + "fee",
transactionTypeCode, transactionDateString, message + " #fee", loginUser);
HashSet<Debtor> debtors = new HashSet<>(1);
HashSet<Creditor> creditors = new HashSet<>(1);
double payedAmount = 0d;
for (Charge charge : charges) {
BigDecimal value = calcChargeAmount(amount, charge, currency, true);
if (value == null)
continue;
double doubleValue = value.doubleValue();
payedAmount += doubleValue;
addDebtor(charge.getIncomeAccountIdentifier(), doubleValue, debtors);
}
if (payedAmount > 0) {
addCreditor(accountId, payedAmount, creditors);
journalEntry.setDebtors(debtors);
journalEntry.setCreditors(creditors);
accountingService.createJournalEntry(journalEntry);
}
}
return preparedAmount;
}
// Util
private JournalEntry createJournalEntry(String actionIdentifier, String transactionType, String transactionDate, String message, String loginUser) {
final JournalEntry fromPrepareToNostroEntry = new JournalEntry();
fromPrepareToNostroEntry.setTransactionIdentifier(actionIdentifier);
fromPrepareToNostroEntry.setTransactionType(transactionType);
fromPrepareToNostroEntry.setTransactionDate(transactionDate);
fromPrepareToNostroEntry.setMessage(message);
fromPrepareToNostroEntry.setClerk(loginUser);
return fromPrepareToNostroEntry;
}
private void addCreditor(String accountNumber, double amount, HashSet<Creditor> creditors) {
Creditor creditor = new Creditor();
creditor.setAccountNumber(accountNumber);
creditor.setAmount(Double.toString(amount));
creditors.add(creditor);
}
private void addDebtor(String accountNumber, double amount, HashSet<Debtor> debtors) {
Debtor debtor = new Debtor();
debtor.setAccountNumber(accountNumber);
debtor.setAmount(Double.toString(amount));
debtors.add(debtor);
}
private BigDecimal calcChargeAmount(BigDecimal amount, Charge charge) {
return calcChargeAmount(amount, charge, null, false);
}
private BigDecimal calcChargeAmount(@NotNull BigDecimal amount, @NotNull Charge charge, Currency currency, boolean norm) {
Double value = charge.getAmount();
if (value == null)
return null;
BigDecimal portion = BigDecimal.valueOf(100.00d);
MathContext mc = MathUtil.CALCULATION_MATH_CONTEXT;
BigDecimal feeAmount = BigDecimal.valueOf(MathUtil.nullToZero(charge.getAmount()));
BigDecimal result = charge.getProportional()
? amount.multiply(feeAmount.divide(portion, mc), mc)
: feeAmount;
return norm ? MathUtil.normalize(result, currency) : result;
}
@NotNull
private BigDecimal calcTotalCharges(@NotNull List<Charge> charges, BigDecimal amount) {
return charges.stream().map(charge -> calcChargeAmount(amount, charge)).reduce(MathUtil::add).orElse(BigDecimal.ZERO);
}
private Account validateAndGetAccount(@NotNull String accountId) {
//TODO: error handling
Account account = accountingService.findAccount(accountId);
validateAccount(account);
return account;
}
private AccountWrapper validateAndGetAccount(@NotNull InteropRequestData request) {
//TODO: error handling
String accountId = request.getAccountId();
Account account = accountingService.findAccount(accountId);
validateAccount(request, account);
ProductInstance product = depositService.findProductInstance(accountId);
ProductDefinition productDefinition = depositService.findProductDefinition(product.getProductIdentifier());
Currency currency = productDefinition.getCurrency();
if (!currency.getCode().equals(request.getAmount().getCurrency()))
throw new UnsupportedOperationException();
request.normalizeAmounts(currency);
Double withdrawableBalance = getWithdrawableBalance(account, productDefinition);
if (request.getTransactionRole().isWithdraw() && withdrawableBalance < request.getAmount().getAmount().doubleValue())
throw new UnsupportedOperationException();
return new AccountWrapper(account, product, productDefinition, withdrawableBalance);
}
private Account validateAndGetPayableAccount(@NotNull InteropRequestData request, @NotNull AccountWrapper wrapper) {
String referenceId = wrapper.account.getReferenceAccount();
if (referenceId == null)
return null;
return validateAndGetAccount(request, referenceId);
}
@NotNull
private Account validateAndGetNostroAccount(@NotNull InteropRequestData request) {
//TODO: error handling
List<Account> nostros = fetchAccounts(false, ACCOUNT_NAME_NOSTRO, AccountType.ASSET.name(), false, null, null, null, null);
int size = nostros.size();
if (size != 1)
throw new UnsupportedOperationException("NOSTRO Account " + (size == 0 ? "not found" : "is ambigous"));
Account nostro = nostros.get(0);
validateAccount(request, nostro);
return nostro;
}
@NotNull
private Account validateAndGetAccount(@NotNull InteropRequestData request, @NotNull String accountId) {
//TODO: error handling
Account account = accountingService.findAccount(accountId);
validateAccount(request, account);
return account;
}
private void validateAccount(Account account) {
if (account == null)
throw new UnsupportedOperationException("Account not found");
if (!account.getState().equals(Account.State.OPEN.name()))
throw new UnsupportedOperationException("Account is in state " + account.getState());
}
private void validateAccount(@NotNull InteropRequestData request, Account account) {
validateAccount(account);
String accountId = account.getIdentifier();
if (account.getHolders() != null) { // customer account
ProductInstance product = depositService.findProductInstance(accountId);
ProductDefinition productDefinition = depositService.findProductDefinition(product.getProductIdentifier());
if (!Boolean.TRUE.equals(productDefinition.getActive()))
throw new UnsupportedOperationException("NOSTRO Product Definition is inactive");
Currency currency = productDefinition.getCurrency();
if (!currency.getCode().equals(request.getAmount().getCurrency()))
throw new UnsupportedOperationException();
}
}
private BigDecimal validateTransfer(@NotNull InteropTransferRequestData request, @NotNull AccountWrapper accountWrapper) {
BigDecimal amount = request.getAmount().getAmount();
boolean isDebit = request.getTransactionRole().isWithdraw();
Currency currency = accountWrapper.productDefinition.getCurrency();
BigDecimal total = isDebit ? amount : MathUtil.negate(amount);
MoneyData fspFee = request.getFspFee();
if (fspFee != null) {
if (!currency.getCode().equals(fspFee.getCurrency()))
throw new UnsupportedOperationException();
//TODO: compare with calculated quote fee
total = MathUtil.add(total, fspFee.getAmount());
}
MoneyData fspCommission = request.getFspCommission();
if (fspCommission != null) {
if (!currency.getCode().equals(fspCommission.getCurrency()))
throw new UnsupportedOperationException();
//TODO: compare with calculated quote commission
total = MathUtil.subtractToZero(total, fspCommission.getAmount());
}
if (isDebit && accountWrapper.withdrawableBalance < request.getAmount().getAmount().doubleValue())
throw new UnsupportedOperationException();
return total;
}
public List<Account> fetchAccounts(boolean includeClosed, String term, String type, boolean includeCustomerAccounts,
Integer pageIndex, Integer size, String sortColumn, String sortDirection) {
return accountingService.fetchAccounts(includeClosed, term, type, includeCustomerAccounts, pageIndex, size, sortColumn, sortDirection);
}
public InteropIdentifierEntity findIdentifier(@NotNull InteropIdentifierType idType, @NotNull String idValue, String subIdOrType) {
return identifierRepository.findOne(Specifications.where(idTypeEqual(idType)).and(idValueEqual(idValue)).and(subIdOrTypeEqual(subIdOrType)));
}
public static Specification<InteropIdentifierEntity> idTypeEqual(@NotNull InteropIdentifierType idType) {
return (Root<InteropIdentifierEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> cb.and(cb.equal(root.get("type"), idType));
}
public static Specification<InteropIdentifierEntity> idValueEqual(@NotNull String idValue) {
return (Root<InteropIdentifierEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> cb.and(cb.equal(root.get("value"), idValue));
}
public static Specification<InteropIdentifierEntity> subIdOrTypeEqual(String subIdOrType) {
return (Root<InteropIdentifierEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
Path<Object> path = root.get("subValueOrType");
return cb.and(subIdOrType == null ? cb.isNull(path) : cb.equal(path, subIdOrType));
};
}
@NotNull
private String calcActionIdentifier(@NotNull String actionCode, @NotNull InteropActionType actionType) {
return actionType == InteropActionType.PREPARE || actionType == InteropActionType.COMMIT ? actionType + InteropRequestData.IDENTIFIER_SEPARATOR + actionCode : actionCode;
}
private InteropActionEntity validateAndGetAction(@NotNull String transactionCode, @NotNull String actionIdentifier, @NotNull InteropActionType actionType) {
return validateAndGetAction(transactionCode, actionIdentifier, actionType, true);
}
private InteropActionEntity validateAndGetAction(@NotNull String transactionCode, @NotNull String actionIdentifier, @NotNull InteropActionType actionType, boolean one) {
//TODO: error handling
InteropActionEntity action = actionRepository.findByIdentifier(actionIdentifier);
if (action == null) {
if (one)
throw new UnsupportedOperationException("Interperation action " + actionType + '/' + actionIdentifier + " was not found for this transaction " + transactionCode);
return null;
}
if (!action.getTransaction().getIdentifier().equals(transactionCode))
throw new UnsupportedOperationException("Interperation action " + actionType + '/' + actionIdentifier + " does not exist in this transaction " + transactionCode);
if (action.getActionType() != actionType)
throw new UnsupportedOperationException("Interperation action " + actionIdentifier + " is not this type " + actionType);
return action;
}
@NotNull
private InteropTransactionEntity validateAndGetTransaction(@NotNull InteropRequestData request, @NotNull AccountWrapper accountWrapper) {
return validateAndGetTransaction(request, accountWrapper, true);
}
@NotNull
private InteropTransactionEntity validateAndGetTransaction(@NotNull InteropRequestData request, @NotNull AccountWrapper accountWrapper, boolean create) {
return validateAndGetTransaction(request, accountWrapper, getNow(), create);
}
@NotNull
private InteropTransactionEntity validateAndGetTransaction(@NotNull InteropRequestData request, @NotNull AccountWrapper accountWrapper,
@NotNull LocalDateTime createdOn, boolean create) {
//TODO: error handling
String transactionCode = request.getTransactionCode();
InteropTransactionEntity transaction = transactionRepository.findOneByIdentifier(request.getTransactionCode());
InteropState state = InteropStateMachine.handleTransition(transaction == null ? null : transaction.getState(), request.getActionType());
LocalDateTime now = getNow();
if (transaction == null) {
if (!create)
throw new UnsupportedOperationException("Interperation transaction " + request.getTransactionCode() + " does not exist ");
transaction = new InteropTransactionEntity(transactionCode, accountWrapper.account.getIdentifier(), getLoginUser(), now);
transaction.setState(state);
transaction.setAmount(request.getAmount().getAmount());
transaction.setName(request.getNote());
transaction.setTransactionType(request.getTransactionRole().getTransactionType());
Account payableAccount = validateAndGetPayableAccount(request, accountWrapper);
transaction.setPrepareAccountIdentifier(payableAccount == null ? null : payableAccount.getIdentifier());
transaction.setNostroAccountIdentifier(validateAndGetNostroAccount(request).getIdentifier());
transaction.setExpirationDate(request.getExpiration());
}
LocalDateTime expirationDate = transaction.getExpirationDate();
if (expirationDate != null && expirationDate.isBefore(now))
throw new UnsupportedOperationException("Interperation transaction expired on " + expirationDate);
return transaction;
}
private Currency getCurrency(InteropActionEntity action) {
ProductInstance product = depositService.findProductInstance(action.getTransaction().getCustomerAccountIdentifier());
ProductDefinition productDefinition = depositService.findProductDefinition(product.getProductIdentifier());
return productDefinition.getCurrency();
}
private InteropActionEntity addAction(@NotNull InteropTransactionEntity transaction, @NotNull InteropRequestData request) {
return addAction(transaction, request, getNow());
}
private InteropActionEntity addAction(@NotNull InteropTransactionEntity transaction, @NotNull InteropRequestData request,
@NotNull LocalDateTime createdOn) {
InteropActionEntity lastAction = getLastAction(transaction);
InteropActionType actionType = request.getActionType();
String actionIdentifier = calcActionIdentifier(request.getIdentifier(), request.getActionType());
InteropActionEntity action = new InteropActionEntity(actionIdentifier, transaction, request.getActionType(),
(lastAction == null ? 0 : lastAction.getSeqNo() + 1), getLoginUser(),
(lastAction == null ? transaction.getCreatedOn() : createdOn));
action.setState(InteropActionState.ACCEPTED);
action.setAmount(request.getAmount().getAmount());
action.setExpirationDate(request.getExpiration());
transaction.getActions().add(action);
InteropState currentState = transaction.getState();
if (transaction.getId() != null || InteropStateMachine.isValidAction(currentState, actionType)) // newly created was already set
transaction.setState(InteropStateMachine.handleTransition(currentState, actionType));
return action;
}
private InteropActionEntity getLastAction(InteropTransactionEntity transaction) {
List<InteropActionEntity> actions = transaction.getActions();
int size = actions.size();
return size == 0 ? null : actions.get(size - 1);
}
private InteropActionEntity findAction(InteropTransactionEntity transaction, InteropActionType actionType) {
List<InteropActionEntity> actions = transaction.getActions();
for (InteropActionEntity action : actions) {
if (action.getActionType() == actionType)
return action;
}
return null;
}
private LocalDateTime getNow() {
return LocalDateTime.now(Clock.systemUTC());
}
private String getLoginUser() {
return UserContextHolder.checkedGetUser();
}
public static class AccountWrapper {
@NotNull
private final Account account;
@NotNull
private final ProductInstance product;
@NotNull
private final ProductDefinition productDefinition;
@NotNull
private final Double withdrawableBalance;
public AccountWrapper(Account account, ProductInstance product, ProductDefinition productDefinition, Double withdrawableBalance) {
this.account = account;
this.product = product;
this.productDefinition = productDefinition;
this.withdrawableBalance = withdrawableBalance;
}
}
}
| 2,747 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/service | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/service/helper/InteropDepositService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service.internal.service.helper;
import org.apache.fineract.cn.deposit.api.v1.client.DepositAccountManager;
import org.apache.fineract.cn.deposit.api.v1.definition.domain.Action;
import org.apache.fineract.cn.deposit.api.v1.definition.domain.Charge;
import org.apache.fineract.cn.deposit.api.v1.definition.domain.DividendDistribution;
import org.apache.fineract.cn.deposit.api.v1.definition.domain.ProductDefinition;
import org.apache.fineract.cn.deposit.api.v1.instance.domain.AvailableTransactionType;
import org.apache.fineract.cn.deposit.api.v1.instance.domain.ProductInstance;
import org.apache.fineract.cn.interoperation.api.v1.domain.TransactionType;
import org.apache.fineract.cn.interoperation.service.ServiceConstants;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class InteropDepositService {
private Logger logger;
private DepositAccountManager depositAccountManager;
@Autowired
public InteropDepositService(@Qualifier(ServiceConstants.LOGGER_NAME) Logger logger,
DepositAccountManager depositAccountManager) {
super();
this.logger = logger;
this.depositAccountManager = depositAccountManager;
}
public List<Charge> getWithdrawCharges(String accountIdentifier) {
return getCharges(accountIdentifier, TransactionType.CURRENCY_WITHDRAWAL);
}
public List<Charge> getDepositCharges(String accountIdentifier) {
return getCharges(accountIdentifier, TransactionType.CURRENCY_DEPOSIT);
}
public List<Charge> getCharges(String accountIdentifier, TransactionType transactionType) {
List<Action> actions = depositAccountManager.fetchActions();
List<String> actionIds = actions
.stream()
.filter(action -> action.getTransactionType().equals(transactionType.getCode()))
.map(Action::getIdentifier)
.collect(Collectors.toList());
ProductInstance productInstance = depositAccountManager.findProductInstance(accountIdentifier);
ProductDefinition productDefinition = depositAccountManager.findProductDefinition(productInstance.getProductIdentifier());
return productDefinition.getCharges()
.stream()
.filter(charge -> actionIds.contains(charge.getActionIdentifier()))
.collect(Collectors.toList());
}
public void createAction(@NotNull Action action) {
depositAccountManager.create(action);
}
public List<Action> fetchActions() {
return depositAccountManager.fetchActions();
}
public void createProductDefinition(@NotNull ProductDefinition productDefinition) {
depositAccountManager.create(productDefinition);
}
public List<ProductDefinition> fetchProductDefinitions() {
return depositAccountManager.fetchProductDefinitions();
}
public ProductDefinition findProductDefinition(@NotNull String identifier) {
return depositAccountManager.findProductDefinition(identifier);
}
public List<ProductInstance> findProductInstances(@NotNull String identifier) {
return depositAccountManager.findProductInstances(identifier);
}
public void createProductInstance(@NotNull ProductInstance productInstance) {
depositAccountManager.create(productInstance);
}
public List<ProductInstance> fetchProductInstances(@NotNull String customer) {
return depositAccountManager.fetchProductInstances(customer);
}
public Set<AvailableTransactionType> fetchPossibleTransactionTypes(String customer) {
return depositAccountManager.fetchPossibleTransactionTypes(customer);
}
public ProductInstance findProductInstance(@NotNull String accountIdentifier) {
return depositAccountManager.findProductInstance(accountIdentifier);
}
public void dividendDistribution(@NotNull String identifier, @NotNull DividendDistribution distribution) {
depositAccountManager.dividendDistribution(identifier, distribution);
}
public List<DividendDistribution> fetchDividendDistributions(@NotNull String identifier) {
return depositAccountManager.fetchDividendDistributions(identifier);
}
}
| 2,748 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/service | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/internal/service/helper/InteropAccountingService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service.internal.service.helper;
import com.google.common.collect.Lists;
import org.apache.fineract.cn.accounting.api.v1.client.AccountNotFoundException;
import org.apache.fineract.cn.accounting.api.v1.client.LedgerManager;
import org.apache.fineract.cn.accounting.api.v1.client.LedgerNotFoundException;
import org.apache.fineract.cn.accounting.api.v1.domain.Account;
import org.apache.fineract.cn.accounting.api.v1.domain.AccountEntry;
import org.apache.fineract.cn.accounting.api.v1.domain.AccountPage;
import org.apache.fineract.cn.accounting.api.v1.domain.JournalEntry;
import org.apache.fineract.cn.accounting.api.v1.domain.Ledger;
import org.apache.fineract.cn.interoperation.service.ServiceConstants;
import org.apache.fineract.cn.lang.ServiceException;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
@Service
public class InteropAccountingService {
private Logger logger;
private LedgerManager ledgerManager;
@Autowired
public InteropAccountingService(@Qualifier(ServiceConstants.LOGGER_NAME) Logger logger,
LedgerManager ledgerManager) {
super();
this.logger = logger;
this.ledgerManager = ledgerManager;
}
public void createAccount(String equityLedger,
String productName,
String customer,
String accountNumber,
String alternativeAccountNumber,
Double balance) {
try {
Ledger ledger = ledgerManager.findLedger(equityLedger);
Account account = new Account();
account.setIdentifier(accountNumber);
account.setType(ledger.getType());
account.setLedger(equityLedger);
account.setName(productName);
account.setHolders(new HashSet<>(Lists.newArrayList(customer)));
account.setBalance(balance != null ? balance : 0.00D);
account.setAlternativeAccountNumber(alternativeAccountNumber);
ledgerManager.createAccount(account);
} catch (LedgerNotFoundException lnfex) {
throw ServiceException.notFound("Ledger {0} not found.", equityLedger);
}
}
public List<Account> fetchAccounts(boolean includeClosed, String term, String type, boolean includeCustomerAccounts,
Integer pageIndex, Integer size, String sortColumn, String sortDirection) {
return ledgerManager.fetchAccounts(includeClosed, term, type, includeCustomerAccounts, pageIndex, size, sortColumn, sortDirection).getAccounts();
}
public Account findAccount(final String accountNumber) {
try {
return this.ledgerManager.findAccount(accountNumber);
} catch (final AccountNotFoundException anfex) {
final AccountPage accountPage = this.ledgerManager.fetchAccounts(true, accountNumber, null, true,
0, 10, null, null);
return accountPage.getAccounts()
.stream()
.filter(account -> account.getAlternativeAccountNumber().equals(accountNumber))
.findFirst()
.orElseThrow(() -> ServiceException.notFound("Account {0} not found.", accountNumber));
}
}
public void modifyAccount(Account account) {
ledgerManager.modifyAccount(account.getIdentifier(), account);
}
public List<AccountEntry> fetchAccountEntries(String identifier, String dateRange, String direction) {
return ledgerManager
.fetchAccountEntries(identifier, dateRange, null, 0, 1, "transactionDate", direction)
.getAccountEntries();
}
public List<JournalEntry> fetchJournalEntries(final String dateRange, final String accountNumber, final BigDecimal amount) {
return ledgerManager.fetchJournalEntries(dateRange, accountNumber, amount);
}
public JournalEntry findJournalEntry(@NotNull String transactionIdentifier) {
return ledgerManager.findJournalEntry(transactionIdentifier);
}
public void createJournalEntry(@NotNull JournalEntry journalEntry) {
ledgerManager.createJournalEntry(journalEntry);
}
}
| 2,749 |
0 | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service | Create_ds/fineract-cn-interoperation/service/src/main/java/org/apache/fineract/cn/interoperation/service/rest/InteropRestController.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.interoperation.service.rest;
import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType;
import org.apache.fineract.cn.anubis.annotation.Permittable;
import org.apache.fineract.cn.command.domain.CommandCallback;
import org.apache.fineract.cn.command.gateway.CommandGateway;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropIdentifierType;
import org.apache.fineract.cn.interoperation.api.v1.domain.InteropTransferActionType;
import org.apache.fineract.cn.interoperation.api.v1.domain.data.*;
import org.apache.fineract.cn.interoperation.service.internal.command.InitializeServiceCommand;
import org.apache.fineract.cn.interoperation.service.internal.service.InteropService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import static org.apache.fineract.cn.interoperation.api.v1.PermittableGroupIds.INTEROPERATION_SINGLE;
@SuppressWarnings("unused")
@RestController
@RequestMapping("/") //interoperation/v1
public class InteropRestController {
private CommandGateway commandGateway;
private InteropService interopService;
@Autowired
public InteropRestController(CommandGateway commandGateway,
InteropService interopService) {
this.commandGateway = commandGateway;
this.interopService = interopService;
}
@Permittable(value = AcceptedTokenType.SYSTEM)
@RequestMapping(
value = "/initialize",
method = RequestMethod.POST,
consumes = MediaType.ALL_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public
@ResponseBody
ResponseEntity<Void> initialize() {
this.commandGateway.process(new InitializeServiceCommand());
return ResponseEntity.accepted().build();
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = INTEROPERATION_SINGLE)
@RequestMapping(
value = "/health",
method = RequestMethod.GET,
consumes = MediaType.ALL_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<Void> health(@Context UriInfo uriInfo) {
return ResponseEntity.ok().build();
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = INTEROPERATION_SINGLE)
@RequestMapping(
value = "/parties/{idType}/{idValue}",
method = RequestMethod.GET,
consumes = MediaType.ALL_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<InteropIdentifierData> getAccountByIdentifier(@PathVariable("idType") InteropIdentifierType idType,
@PathVariable("idValue") String idValue) {
InteropIdentifierData account = interopService.getAccountByIdentifier(idType, idValue, null);
return ResponseEntity.ok(account);
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = INTEROPERATION_SINGLE)
@RequestMapping(
value = "/parties/{idType}/{idValue}/{subIdOrType}",
method = RequestMethod.GET,
consumes = MediaType.ALL_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<InteropIdentifierData> getAccountByIdentifier(@PathVariable("idType") InteropIdentifierType idType,
@PathVariable("idValue") String idValue,
@PathVariable(value = "subIdOrType") String subIdOrType) {
InteropIdentifierData account = interopService.getAccountByIdentifier(idType, idValue, subIdOrType);
return ResponseEntity.ok(account);
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = INTEROPERATION_SINGLE)
@RequestMapping(
value = "/parties/{idType}/{idValue}",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseBody
public ResponseEntity<InteropIdentifierData> registerAccountIdentifier(@PathVariable("idType") InteropIdentifierType idType,
@PathVariable("idValue") String idValue,
@RequestBody @Valid InteropIdentifierData requestData)
throws Throwable {
CommandCallback<InteropIdentifierData> result = commandGateway.process(new InteropIdentifierCommand(requestData,
idType, idValue, null), InteropIdentifierData.class);
return ResponseEntity.ok(result.get());
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = INTEROPERATION_SINGLE)
@RequestMapping(
value = "/parties/{idType}/{idValue}/{subIdOrType}",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseBody
public ResponseEntity<InteropIdentifierData> registerAccountIdentifier(@PathVariable("idType") InteropIdentifierType idType,
@PathVariable("idValue") String idValue,
@PathVariable(value = "subIdOrType", required = false) String subIdOrType,
@RequestBody @Valid InteropIdentifierData requestData)
throws Throwable {
CommandCallback<InteropIdentifierData> result = commandGateway.process(new InteropIdentifierCommand(requestData,
idType, idValue, subIdOrType), InteropIdentifierData.class);
return ResponseEntity.ok(result.get());
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = INTEROPERATION_SINGLE)
@RequestMapping(
value = "/parties/{idType}/{idValue}",
method = RequestMethod.DELETE,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseBody
public ResponseEntity<InteropIdentifierData> deleteAccountIdentifier(@PathVariable("idType") InteropIdentifierType idType,
@PathVariable("idValue") String idValue)
throws Throwable {
CommandCallback<InteropIdentifierData> result = commandGateway.process(new InteropIdentifierDeleteCommand(idType, idValue, null), InteropIdentifierData.class);
return ResponseEntity.ok(result.get());
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = INTEROPERATION_SINGLE)
@RequestMapping(
value = "/parties/{idType}/{idValue}/{subIdOrType}",
method = RequestMethod.DELETE,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseBody
public ResponseEntity<InteropIdentifierData> deleteAccountIdentifier(@PathVariable("idType") InteropIdentifierType idType,
@PathVariable("idValue") String idValue,
@PathVariable(value = "subIdOrType", required = false) String subIdOrType)
throws Throwable {
CommandCallback<InteropIdentifierData> result = commandGateway.process(new InteropIdentifierDeleteCommand(idType, idValue, subIdOrType), InteropIdentifierData.class);
return ResponseEntity.ok(result.get());
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = INTEROPERATION_SINGLE)
@RequestMapping(
value = "transactions/{transactionCode}/requests/{requestCode}",
method = RequestMethod.GET,
consumes = MediaType.ALL_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseBody
public ResponseEntity<InteropTransactionRequestResponseData> getTransactionRequest(@PathVariable("transactionCode") String transactionCode,
@PathVariable("requestCode") String requestCode) {
InteropTransactionRequestResponseData result = interopService.getTransactionRequest(transactionCode, requestCode);
return ResponseEntity.ok(result);
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = INTEROPERATION_SINGLE)
@RequestMapping(
value = "/requests",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseBody
public ResponseEntity<InteropTransactionRequestResponseData> createTransactionRequest(@RequestBody @Valid InteropTransactionRequestData requestData)
throws Throwable {
CommandCallback<InteropTransactionRequestResponseData> result = commandGateway.process(requestData, InteropTransactionRequestResponseData.class);
return ResponseEntity.ok(result.get());
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = INTEROPERATION_SINGLE)
@RequestMapping(
value = "transactions/{transactionCode}/quotes/{quoteCode}",
method = RequestMethod.GET,
consumes = MediaType.ALL_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseBody
public ResponseEntity<InteropQuoteResponseData> getQuote(@PathVariable("transactionCode") String transactionCode,
@PathVariable("quoteCode") String quoteCode) {
InteropQuoteResponseData result = interopService.getQuote(transactionCode, quoteCode);
return ResponseEntity.ok(result);
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = INTEROPERATION_SINGLE)
@RequestMapping(
value = "/quotes",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseBody
public ResponseEntity<InteropQuoteResponseData> createQuote(@RequestBody @Valid InteropQuoteRequestData requestData) throws Throwable {
CommandCallback<InteropQuoteResponseData> result = commandGateway.process(requestData, InteropQuoteResponseData.class);
return ResponseEntity.ok(result.get());
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = INTEROPERATION_SINGLE)
@RequestMapping(
value = "transactions/{transactionCode}/transfers/{transferCode}",
method = RequestMethod.GET,
consumes = MediaType.ALL_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseBody
public ResponseEntity<InteropTransferResponseData> getTransfer(@PathVariable("transactionCode") String transactionCode,
@PathVariable("transferCode") String transferCode) {
InteropTransferResponseData result = interopService.getTransfer(transactionCode, transferCode);
return ResponseEntity.ok(result);
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = INTEROPERATION_SINGLE)
@RequestMapping(
value = "/transfers",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseBody
public ResponseEntity<InteropTransferResponseData> performTransfer(@RequestParam("action") String action,
@RequestBody @Valid InteropTransferRequestData requestData)
throws Throwable {
CommandCallback<InteropTransferResponseData> result = commandGateway.process(new InteropTransferCommand(requestData, InteropTransferActionType.valueOf(action)),
InteropTransferResponseData.class);
return ResponseEntity.ok(result.get());
}
} | 2,750 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/test/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/test/java/org/apache/commons/rng/examples/jmh/core/LXMBenchmarkTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import java.math.BigInteger;
import java.util.function.LongSupplier;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.examples.jmh.core.LXMBenchmark.LCG128Source;
import org.apache.commons.rng.examples.jmh.core.LXMBenchmark.LXM128Source;
import org.apache.commons.rng.examples.jmh.core.LXMBenchmark.UnsignedMultiply128Source;
import org.apache.commons.rng.examples.jmh.core.LXMBenchmark.UnsignedMultiplyHighSource;
import org.apache.commons.rng.simple.RandomSource;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.opentest4j.TestAbortedException;
/**
* Test for methods used in {@link LXMBenchmark}. This checks the different versions of
* 128-bit multiplication compute the correct result (verified using BigInteger).
*/
class LXMBenchmarkTest {
/** 2^63. */
private static final BigInteger TWO_POW_63 = BigInteger.ONE.shiftLeft(63);
/**
* A function operating on 2 long values.
*/
interface LongLongFunction {
/**
* Apply the function.
*
* @param a Argument a
* @param b Argument b
* @return the result
*/
long apply(long a, long b);
}
/**
* A function operating on 4 long values.
*/
interface LongLongLongLongFunction {
/**
* Apply the function.
*
* @param a Argument a
* @param b Argument b
* @param c Argument c
* @param d Argument d
* @return the result
*/
long apply(long a, long b, long c, long d);
}
@Test
@EnabledForJreRange(min = JRE.JAVA_9)
void testMathMultiplyHigh() {
try {
assertUnsignedMultiply(UnsignedMultiplyHighSource::mathMultiplyHigh, null);
} catch (NoSuchMethodError e) {
throw new TestAbortedException("Update mathMultiplyHigh to call Math.multiplyHigh");
}
}
@Test
// Note: JAVA_18 is not in the enum
@EnabledForJreRange(min = JRE.OTHER)
void testMathUnsignedMultiplyHigh() {
try {
assertUnsignedMultiply(UnsignedMultiplyHighSource::mathUnsignedMultiplyHigh, null);
} catch (NoSuchMethodError e) {
throw new TestAbortedException("Update mathUnsignedMultiplyHigh to call Math.unsignedMultiplyHigh");
}
}
@Test
void testUnsignedMultiplyHigh() {
assertUnsignedMultiply(UnsignedMultiplyHighSource::unsignedMultiplyHigh, null);
}
@Test
void testUnsignedMultiplyHighWithLow() {
final long[] lo = {0};
assertUnsignedMultiply((a, b) -> UnsignedMultiplyHighSource.unsignedMultiplyHigh(a, b, lo), lo);
}
private static void assertUnsignedMultiply(LongLongFunction fun, long[] lo) {
final UniformRandomProvider rng = RandomSource.JSF_64.create();
for (int i = 0; i < 100; i++) {
final long a = rng.nextLong();
final long b = rng.nextLong();
Assertions.assertEquals(unsignedMultiplyHigh(a, b),
fun.apply(a, b));
if (lo != null) {
Assertions.assertEquals(a * b, lo[0]);
}
}
}
@Test
void testUnsignedMultiplyHighML() {
final UniformRandomProvider rng = RandomSource.JSF_64.create();
final long b = LXMBenchmark.ML;
for (int i = 0; i < 100; i++) {
final long a = rng.nextLong();
Assertions.assertEquals(unsignedMultiplyHigh(a, b),
UnsignedMultiplyHighSource.unsignedMultiplyHighML(a));
}
}
@Test
void testUnsignedMultiplyHighWithProducts() {
assertUnsignedMultiply128((a, b, c, d) ->
UnsignedMultiplyHighSource.unsignedMultiplyHigh(b, d) +
a * d + b * c, null);
}
@Test
void testUnsignedMultiply128() {
final long[] lo = {0};
assertUnsignedMultiply128((a, b, c, d) -> UnsignedMultiply128Source.unsignedMultiply128(a, b, c, d, lo), lo);
}
private static void assertUnsignedMultiply128(LongLongLongLongFunction fun, long[] lo) {
final UniformRandomProvider rng = RandomSource.JSF_64.create();
for (int i = 0; i < 100; i++) {
final long a = rng.nextLong();
final long b = rng.nextLong();
final long c = rng.nextLong();
final long d = rng.nextLong();
Assertions.assertEquals(unsignedMultiplyHigh(a, b, c, d),
fun.apply(a, b, c, d));
if (lo != null) {
Assertions.assertEquals(b * d, lo[0]);
}
}
}
@Test
void testUnsignedSquareHigh() {
final UniformRandomProvider rng = RandomSource.JSF_64.create();
for (int i = 0; i < 100; i++) {
final long a = rng.nextLong();
Assertions.assertEquals(unsignedMultiplyHigh(a, a),
UnsignedMultiply128Source.unsignedSquareHigh(a));
}
}
@Test
void testUnsignedSquare128() {
final long[] lo = {0};
final UniformRandomProvider rng = RandomSource.JSF_64.create();
for (int i = 0; i < 100; i++) {
final long a = rng.nextLong();
final long b = rng.nextLong();
Assertions.assertEquals(unsignedMultiplyHigh(a, b, a, b),
UnsignedMultiply128Source.unsignedSquare128(a, b, lo));
Assertions.assertEquals(b * b, lo[0]);
}
}
/**
* Compute the unsigned multiply of two values using BigInteger.
*
* @param a First value
* @param b Second value
* @return the upper 64-bits of the 128-bit result
*/
private static long unsignedMultiplyHigh(long a, long b) {
final BigInteger ba = toUnsignedBigInteger(a);
final BigInteger bb = toUnsignedBigInteger(b);
return ba.multiply(bb).shiftRight(64).longValue();
}
/**
* Compute the unsigned multiply of two 128-bit values using BigInteger.
*
* <p>This computes the upper 64-bits of a 128-bit result that would
* be generated by multiplication to a native 128-bit integer type.
*
* @param a First value
* @param b Second value
* @return the upper 64-bits of the truncated 128-bit result
*/
private static long unsignedMultiplyHigh(long ah, long al, long bh, long bl) {
final BigInteger a = toUnsignedBigInteger(ah, al);
final BigInteger b = toUnsignedBigInteger(bh, bl);
return a.multiply(b).shiftRight(64).longValue();
}
/**
* Create a big integer treating the value as unsigned.
*
* @param v Value
* @return the big integer
*/
private static BigInteger toUnsignedBigInteger(long v) {
return v < 0 ?
TWO_POW_63.add(BigInteger.valueOf(v & Long.MAX_VALUE)) :
BigInteger.valueOf(v);
}
/**
* Create a 128-bit big integer treating the value as unsigned.
*
* @param hi High part of value
* @param lo High part of value
* @return the big integer
*/
private static BigInteger toUnsignedBigInteger(long hi, long lo) {
return toUnsignedBigInteger(hi).shiftLeft(64).add(toUnsignedBigInteger(lo));
}
/**
* Test all 128-bit LCG implementations compute the same state update.
*/
@RepeatedTest(value = 50)
void testLcg128() {
final long ah = RandomSource.createLong();
final long al = RandomSource.createLong() | 1;
final LongSupplier a = new LCG128Source.ReferenceLcg128(ah, al)::getAsLong;
final LongSupplier[] b = new LongSupplier[] {
new LCG128Source.ReferenceLcg128(ah, al)::getAsLong,
new LCG128Source.ReferenceLcg128Final(ah, al)::getAsLong,
new LCG128Source.CompareUnsignedLcg128(ah, al)::getAsLong,
new LCG128Source.ConditionalLcg128(ah, al)::getAsLong,
new LCG128Source.ConditionalLcg128Final(ah, al)::getAsLong,
new LCG128Source.BranchlessLcg128(ah, al)::getAsLong,
new LCG128Source.BranchlessFullLcg128(ah, al)::getAsLong,
new LCG128Source.BranchlessFullComposedLcg128(ah, al)::getAsLong,
};
for (int i = 0; i < 10; i++) {
final long expected = a.getAsLong();
for (int j = 0; j < b.length; j++) {
Assertions.assertEquals(expected, b[j].getAsLong());
}
}
}
/**
* Test all 128-bit LCG based implementation of a LXM generator compute the same state update.
*/
@RepeatedTest(value = 50)
void testLxm128() {
final long ah = RandomSource.createLong();
final long al = RandomSource.createLong();
// Native seed: LCG add, LCG state, XBG
// This requires the initial state of the XBG and LCG.
final long[] seed = {ah, al,
LXM128Source.S0, LXM128Source.S1,
LXM128Source.X0, LXM128Source.X1};
final UniformRandomProvider rng = RandomSource.L128_X128_MIX.create(seed);
final LongSupplier a = rng::nextLong;
final LongSupplier[] b = new LongSupplier[] {
new LXM128Source.ReferenceLxm128(ah, al)::getAsLong,
new LXM128Source.BranchlessLxm128(ah, al)::getAsLong,
};
for (int i = 0; i < 10; i++) {
final long expected = a.getAsLong();
for (int j = 0; j < b.length; j++) {
Assertions.assertEquals(expected, b[j].getAsLong());
}
}
}
}
| 2,751 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/test/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/test/java/org/apache/commons/rng/examples/jmh/sampling/distribution/ZigguratSamplerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.distribution;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.Arrays;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.apache.commons.math3.distribution.AbstractRealDistribution;
import org.apache.commons.math3.distribution.ExponentialDistribution;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.commons.math3.stat.inference.ChiSquareTest;
import org.apache.commons.rng.RestorableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.distribution.ContinuousSampler;
import org.apache.commons.rng.simple.RandomSource;
/**
* Test for ziggurat samplers in the {@link ZigguratSamplerPerformance} class.
*
* <p>This test is copied from the {@code commons-rng-sampling} module to ensure all implementations
* correctly sample from the distribution.
*/
class ZigguratSamplerTest {
/**
* The seed for the RNG used in the distribution sampling tests.
*
* <p>This has been chosen to allow the test to pass with all generators.
* Set to null test with a random seed.
*
* <p>Note that the p-value of the chi-square test is 0.001. There are multiple assertions
* per test and multiple samplers. The total number of chi-square tests is above 100
* and failure of a chosen random seed on a few tests is common. When using a random
* seed re-run the test multiple times. Systematic failure of the same sampler
* should be investigated further.
*/
private static final Long SEED = 0xd1342543de82ef95L;
/**
* Create arguments with the name of the factory.
*
* @param name Name of the factory
* @param factory Factory to create the sampler
* @return the arguments
*/
private static Arguments args(String name) {
// Create the factory.
// Here we delegate to the static method used to create all the samplers for testing.
final Function<UniformRandomProvider, ContinuousSampler> factory =
rng -> ZigguratSamplerPerformance.Sources.createSampler(name, rng);
return Arguments.of(name, factory);
}
/**
* Create a stream of constructors of a Gaussian sampler.
*
* <p>Note: This method exists to allow this test to be duplicated in the examples JMH
* module where many implementations are tested.
*
* @return the stream of constructors
*/
private static Stream<Arguments> gaussianSamplers() {
// Test all but MOD_GAUSSIAN (tested in the common-rng-sampling module)
return Stream.of(
args(ZigguratSamplerPerformance.GAUSSIAN_128),
args(ZigguratSamplerPerformance.GAUSSIAN_256),
args(ZigguratSamplerPerformance.MOD_GAUSSIAN2),
args(ZigguratSamplerPerformance.MOD_GAUSSIAN_SIMPLE_OVERHANGS),
args(ZigguratSamplerPerformance.MOD_GAUSSIAN_INLINING),
args(ZigguratSamplerPerformance.MOD_GAUSSIAN_INLINING_SHIFT),
args(ZigguratSamplerPerformance.MOD_GAUSSIAN_INLINING_SIMPLE_OVERHANGS),
args(ZigguratSamplerPerformance.MOD_GAUSSIAN_INT_MAP),
args(ZigguratSamplerPerformance.MOD_GAUSSIAN_E_MAX_TABLE),
args(ZigguratSamplerPerformance.MOD_GAUSSIAN_E_MAX_2),
args(ZigguratSamplerPerformance.MOD_GAUSSIAN_TERNARY),
args(ZigguratSamplerPerformance.MOD_GAUSSIAN_512));
}
/**
* Create a stream of constructors of an exponential sampler.
*
* <p>Note: This method exists to allow this test to be duplicated in the examples JMH
* module where many implementations are tested.
*
* @return the stream of constructors
*/
private static Stream<Arguments> exponentialSamplers() {
// Test all but MOD_EXPONENTIAL (tested in the common-rng-sampling module)
return Stream.of(
args(ZigguratSamplerPerformance.EXPONENTIAL),
args(ZigguratSamplerPerformance.MOD_EXPONENTIAL2),
args(ZigguratSamplerPerformance.MOD_EXPONENTIAL_SIMPLE_OVERHANGS),
args(ZigguratSamplerPerformance.MOD_EXPONENTIAL_INLINING),
args(ZigguratSamplerPerformance.MOD_EXPONENTIAL_LOOP),
args(ZigguratSamplerPerformance.MOD_EXPONENTIAL_LOOP2),
args(ZigguratSamplerPerformance.MOD_EXPONENTIAL_RECURSION),
args(ZigguratSamplerPerformance.MOD_EXPONENTIAL_INT_MAP),
args(ZigguratSamplerPerformance.MOD_EXPONENTIAL_E_MAX_TABLE),
args(ZigguratSamplerPerformance.MOD_EXPONENTIAL_E_MAX_2),
args(ZigguratSamplerPerformance.MOD_EXPONENTIAL_TERNARY),
args(ZigguratSamplerPerformance.MOD_EXPONENTIAL_TERNARY_SUBTRACT),
args(ZigguratSamplerPerformance.MOD_EXPONENTIAL_512));
}
// -------------------------------------------------------------------------
// All code below here is copied from:
// commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/ZigguratSamplerTest.java
// -------------------------------------------------------------------------
/**
* Creates the gaussian distribution.
*
* @return the distribution
*/
private static AbstractRealDistribution createGaussianDistribution() {
return new NormalDistribution(null, 0.0, 1.0);
}
/**
* Creates the exponential distribution.
*
* @return the distribution
*/
private static AbstractRealDistribution createExponentialDistribution() {
return new ExponentialDistribution(null, 1.0);
}
/**
* Test Gaussian samples using a large number of bins based on uniformly spaced
* quantiles. Added for RNG-159.
*
* @param name Name of the sampler
* @param factory Factory to create the sampler
*/
@ParameterizedTest(name = "{index} => {0}")
@MethodSource("gaussianSamplers")
void testGaussianSamplesWithQuantiles(String name, Function<UniformRandomProvider, ContinuousSampler> factory) {
final int bins = 2000;
final AbstractRealDistribution dist = createGaussianDistribution();
final double[] quantiles = new double[bins];
for (int i = 0; i < bins; i++) {
quantiles[i] = dist.inverseCumulativeProbability((i + 1.0) / bins);
}
testSamples(quantiles, factory, ZigguratSamplerTest::createGaussianDistribution,
// Test positive and negative ranges to check symmetry.
// Smallest layer is 0.292 (convex region)
new double[] {0, 0.2},
new double[] {-0.35, -0.1},
// Around the mean
new double[] {-0.1, 0.1},
new double[] {-0.4, 0.6},
// Inflection point at x=1
new double[] {-1.1, -0.9},
// A concave region
new double[] {2.1, 2.5},
// Tail = 3.64
new double[] {2.5, 8});
}
/**
* Test Gaussian samples using a large number of bins uniformly spaced in a range.
* Added for RNG-159.
*
* @param name Name of the sampler
* @param factory Factory to create the sampler
*/
@ParameterizedTest(name = "{index} => {0}")
@MethodSource("gaussianSamplers")
void testGaussianSamplesWithUniformValues(String name, Function<UniformRandomProvider, ContinuousSampler> factory) {
final int bins = 2000;
final double[] values = new double[bins];
final double minx = -8;
final double maxx = 8;
// Bin width = 16 / 2000 = 0.008
for (int i = 0; i < bins; i++) {
values[i] = minx + (maxx - minx) * (i + 1.0) / bins;
}
// Ensure upper bound is the support limit
values[bins - 1] = Double.POSITIVE_INFINITY;
testSamples(values, factory, ZigguratSamplerTest::createGaussianDistribution,
// Test positive and negative ranges to check symmetry.
// Smallest layer is 0.292 (convex region)
new double[] {0, 0.2},
new double[] {-0.35, -0.1},
// Around the mean
new double[] {-0.1, 0.1},
new double[] {-0.4, 0.6},
// Inflection point at x=1
new double[] {-1.01, -0.99},
new double[] {0.98, 1.03},
// A concave region
new double[] {1.03, 1.05},
// Tail = 3.64
new double[] {3.6, 3.8},
new double[] {3.7, 8});
}
/**
* Test exponential samples using a large number of bins based on uniformly spaced quantiles.
*
* @param name Name of the sampler
* @param factory Factory to create the sampler
*/
@ParameterizedTest(name = "{index} => {0}")
@MethodSource("exponentialSamplers")
void testExponentialSamplesWithQuantiles(String name, Function<UniformRandomProvider, ContinuousSampler> factory) {
final int bins = 2000;
final AbstractRealDistribution dist = createExponentialDistribution();
final double[] quantiles = new double[bins];
for (int i = 0; i < bins; i++) {
quantiles[i] = dist.inverseCumulativeProbability((i + 1.0) / bins);
}
testSamples(quantiles, factory, ZigguratSamplerTest::createExponentialDistribution,
// Smallest layer is 0.122
new double[] {0, 0.1},
new double[] {0.05, 0.15},
// Around the mean
new double[] {0.9, 1.1},
// Tail = 7.57
new double[] {1.5, 12});
}
/**
* Test exponential samples using a large number of bins uniformly spaced in a range.
*
* @param name Name of the sampler
* @param factory Factory to create the sampler
*/
@ParameterizedTest(name = "{index} => {0}")
@MethodSource("exponentialSamplers")
void testExponentialSamplesWithUniformValues(String name, Function<UniformRandomProvider, ContinuousSampler> factory) {
final int bins = 2000;
final double[] values = new double[bins];
final double minx = 0;
// Enter the tail of the distribution
final double maxx = 12;
// Bin width = 12 / 2000 = 0.006
for (int i = 0; i < bins; i++) {
values[i] = minx + (maxx - minx) * (i + 1.0) / bins;
}
// Ensure upper bound is the support limit
values[bins - 1] = Double.POSITIVE_INFINITY;
testSamples(values, factory, ZigguratSamplerTest::createExponentialDistribution,
// Smallest layer is 0.122
new double[] {0, 0.1},
new double[] {0.05, 0.15},
// Around the mean
new double[] {0.9, 1.1},
// Tail = 7.57
new double[] {7.5, 7.7},
new double[] {7.7, 12});
}
/**
* Test samples using the provided bins. Values correspond to the bin upper
* limit. It is assumed the values span most of the distribution. Additional
* tests are performed using a region of the distribution sampled.
*
* @param values Bin upper limits
* @param factory Factory to create the sampler
* @param distribution The distribution under test
* @param ranges Ranges of the distribution to test
*/
private static void testSamples(double[] values,
Function<UniformRandomProvider, ContinuousSampler> factory,
Supplier<AbstractRealDistribution> distribution,
double[]... ranges) {
final int bins = values.length;
final int samples = 10000000;
final long[] observed = new long[bins];
final RestorableUniformRandomProvider rng = RandomSource.XO_SHI_RO_128_PP.create(SEED);
final ContinuousSampler sampler = factory.apply(rng);
for (int i = 0; i < samples; i++) {
final double x = sampler.sample();
final int index = findIndex(values, x);
observed[index]++;
}
// Compute expected
final AbstractRealDistribution dist = distribution.get();
final double[] expected = new double[bins];
double x0 = Double.NEGATIVE_INFINITY;
for (int i = 0; i < bins; i++) {
final double x1 = values[i];
expected[i] = dist.probability(x0, x1);
x0 = x1;
}
final double significanceLevel = 0.001;
final double lowerBound = dist.getSupportLowerBound();
final ChiSquareTest chiSquareTest = new ChiSquareTest();
// Pass if we cannot reject null hypothesis that the distributions are the same.
final double pValue = chiSquareTest.chiSquareTest(expected, observed);
Assertions.assertFalse(pValue < 0.001,
() -> String.format("(%s <= x < %s) Chi-square p-value = %s",
lowerBound, values[bins - 1], pValue));
// Test regions of the ziggurat.
for (final double[] range : ranges) {
final int min = findIndex(values, range[0]);
final int max = findIndex(values, range[1]);
// Must have a range of 2
if (max - min + 1 < 2) {
// This will probably occur if the quantiles test uses too small a range
// for the tail. The tail is so far into the CDF that a single bin is
// often used to represent it.
Assertions.fail("Invalid range: " + Arrays.toString(range));
}
final long[] observed2 = Arrays.copyOfRange(observed, min, max + 1);
final double[] expected2 = Arrays.copyOfRange(expected, min, max + 1);
final double pValueB = chiSquareTest.chiSquareTest(expected2, observed2);
Assertions.assertFalse(pValueB < significanceLevel,
() -> String.format("(%s <= x < %s) Chi-square p-value = %s",
min == 0 ? lowerBound : values[min - 1], values[max], pValueB));
}
}
/**
* Find the index of the value in the data such that:
* <pre>
* data[index - 1] <= x < data[index]
* </pre>
*
* <p>This is a specialised binary search that assumes the bounds of the data are the
* extremes of the support, and the upper support is infinite. Thus an index cannot
* be returned as equal to the data length.
*
* @param data the data
* @param x the value
* @return the index
*/
private static int findIndex(double[] data, double x) {
int low = 0;
int high = data.length - 1;
// Bracket so that low is just above the value x
while (low <= high) {
final int mid = (low + high) >>> 1;
final double midVal = data[mid];
if (x < midVal) {
// Reduce search range
high = mid - 1;
} else {
// Set data[low] above the value
low = mid + 1;
}
}
// Verify the index is correct
Assertions.assertTrue(x < data[low]);
if (low != 0) {
Assertions.assertTrue(x >= data[low - 1]);
}
return low;
}
}
| 2,752 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/RandomSourceValues.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
/**
* A benchmark state that can retrieve the various {@link RandomSource} values.
*
* <p>The state will include only those that do not require additional constructor arguments.</p>
*/
@State(Scope.Benchmark)
public class RandomSourceValues {
/**
* RNG providers. This list is maintained in the order of the {@link RandomSource} enum.
*
* <p>Include only those that do not require additional constructor arguments.</p>
*
* <p>Note: JMH does support using an Enum for the {@code @Param} annotation. However
* the default set will encompass all the enum values, including those that require
* additional constructor arguments. So this list is maintained manually.</p>
*/
@Param({"JDK",
"WELL_512_A",
"WELL_1024_A",
"WELL_19937_A",
"WELL_19937_C",
"WELL_44497_A",
"WELL_44497_B",
"MT",
"ISAAC",
"SPLIT_MIX_64",
"XOR_SHIFT_1024_S",
"TWO_CMRES",
"MT_64",
"MWC_256",
"KISS",
"XOR_SHIFT_1024_S_PHI",
"XO_RO_SHI_RO_64_S",
"XO_RO_SHI_RO_64_SS",
"XO_SHI_RO_128_PLUS",
"XO_SHI_RO_128_SS",
"XO_RO_SHI_RO_128_PLUS",
"XO_RO_SHI_RO_128_SS",
"XO_SHI_RO_256_PLUS",
"XO_SHI_RO_256_SS",
"XO_SHI_RO_512_PLUS",
"XO_SHI_RO_512_SS",
"PCG_XSH_RR_32",
"PCG_XSH_RS_32",
"PCG_RXS_M_XS_64",
"PCG_MCG_XSH_RR_32",
"PCG_MCG_XSH_RS_32",
"MSWS",
"SFC_32",
"SFC_64",
"JSF_32",
"JSF_64",
"XO_SHI_RO_128_PP",
"XO_RO_SHI_RO_128_PP",
"XO_SHI_RO_256_PP",
"XO_SHI_RO_512_PP",
"XO_RO_SHI_RO_1024_PP",
"XO_RO_SHI_RO_1024_S",
"XO_RO_SHI_RO_1024_SS",
"PCG_XSH_RR_32_OS",
"PCG_XSH_RS_32_OS",
"PCG_RXS_M_XS_64_OS",
"L64_X128_SS",
"L64_X128_MIX",
"L64_X256_MIX",
"L64_X1024_MIX",
"L128_X128_MIX",
"L128_X256_MIX",
"L128_X1024_MIX",
"L32_X64_MIX"})
private String randomSourceName;
/** The RandomSource. */
private RandomSource randomSource;
/**
* Gets the random source.
*
* @return the random source
*/
public RandomSource getRandomSource() {
return randomSource;
}
/**
* Look-up the {@link RandomSource} from the name.
*/
@Setup
public void setup() {
randomSource = RandomSource.valueOf(randomSourceName);
}
}
| 2,753 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/RandomSources.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh;
import org.apache.commons.rng.UniformRandomProvider;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
/**
* A benchmark state that can retrieve the various generators defined by
* {@link org.apache.commons.rng.simple.RandomSource RandomSource} values.
*
* <p>The state will include only those that do not require additional constructor arguments.</p>
*/
@State(Scope.Benchmark)
public class RandomSources extends RandomSourceValues {
/** RNG. */
private UniformRandomProvider generator;
/**
* Gets the generator.
*
* @return the RNG.
*/
public UniformRandomProvider getGenerator() {
return generator;
}
/**
* Look-up the {@link org.apache.commons.rng.simple.RandomSource RandomSource} from the
* name and instantiates the generator.
*/
@Override
@Setup
public void setup() {
super.setup();
generator = getRandomSource().create();
}
}
| 2,754 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 code to perform a
* <a href="http://openjdk.java.net/projects/code-tools/jmh">JMH</a> performance benchmark.
*
* <p>
* Support for a new {@link org.apache.commons.rng.UniformRandomProvider UniformRandomProvider}
* with a defined enum value in {@link org.apache.commons.rng.simple.RandomSource RandomSource}
* can be added by updating:
* </p>
*
* <ul>
* <li>The {@link org.apache.commons.rng.examples.jmh.RandomSourceValues RandomSourceValues} class
* <li>The {@link org.apache.commons.rng.examples.jmh.core.BaselineSources BaselineSources} class
* <li>The {@link org.apache.commons.rng.examples.jmh.simple.ConstructionPerformance
* ConstructionPerformance} class
* </ul>
*/
package org.apache.commons.rng.examples.jmh;
| 2,755 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/JumpBenchmark.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.LongJumpableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
/**
* Executes benchmark for jump operations of jumpable RNGs.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = { "-server", "-Xms128M", "-Xmx128M" })
public class JumpBenchmark {
/**
* Encapsulates a method to jump an RNG.
*/
@State(Scope.Benchmark)
public abstract static class BaseJumpableSource {
/** The generator of the next RNG copy from a jump. */
private Supplier<UniformRandomProvider> gen;
/**
* Perform a jump.
*
* @return the value
*/
UniformRandomProvider jump() {
return gen.get();
}
/**
* Create the jump function.
*/
@Setup
public void setup() {
gen = createJumpFunction();
}
/**
* Creates the jump function.
* The jump will copy the RNG and then move forward the state of the source
* RNG by a large number of steps. The copy is returned.
*
* @return the copy RNG
*/
protected abstract Supplier<UniformRandomProvider> createJumpFunction();
}
/**
* Exercise the {@link JumpableUniformRandomProvider#jump()} function.
*/
public static class JumpableSource extends BaseJumpableSource {
/**
* RNG providers.
*
* <p>Note: Some providers have exactly the same jump method and state size
* so are commented out.
*/
@Param({"XOR_SHIFT_1024_S",
//"XOR_SHIFT_1024_S_PHI",
"XO_SHI_RO_128_PLUS",
//"XO_SHI_RO_128_SS",
"XO_RO_SHI_RO_128_PLUS",
//"XO_RO_SHI_RO_128_SS",
"XO_SHI_RO_256_PLUS",
//"XO_SHI_RO_256_SS",
"XO_SHI_RO_512_PLUS",
//"XO_SHI_RO_512_SS",
//"XO_SHI_RO_128_PP",
"XO_RO_SHI_RO_128_PP", // Different update from XO_SHI_RO_128_PLUS
//"XO_SHI_RO_256_PP",
//"XO_SHI_RO_512_PP",
"XO_RO_SHI_RO_1024_PP",
//"XO_RO_SHI_RO_1024_S",
//"XO_RO_SHI_RO_1024_SS",
// Although the LXM jump is the same for all generators with the same LCG
// the performance is different as it captures state copy overhead.
//"L64_X128_SS",
"L64_X128_MIX",
"L64_X256_MIX",
"L64_X1024_MIX",
"L128_X128_MIX",
"L128_X256_MIX",
"L128_X1024_MIX",
"L32_X64_MIX"})
private String randomSourceName;
/** {@inheritDoc} */
@Override
protected Supplier<UniformRandomProvider> createJumpFunction() {
final UniformRandomProvider rng = RandomSource.valueOf(randomSourceName).create();
if (rng instanceof JumpableUniformRandomProvider) {
return ((JumpableUniformRandomProvider) rng)::jump;
}
throw new IllegalStateException("Invalid jump source: " + randomSourceName);
}
}
/**
* Exercise the {@link LongJumpableUniformRandomProvider#longJump()} function.
*
* <p>Note: Any RNG with a long jump function also has a jump function.
* This list should be a subset of {@link JumpableSource}. Testing both methods
* is redundant unless the long jump function requires a different routine.
* Providers listed here have a different long jump and may be slower/faster
* than the corresponding jump function.
*
* <p>Note: To test other providers the benchmark may be invoked using the
* JMH command line:
* <pre>
* java -jar target/examples-jmh.jar JumpBenchmark.longJump -p randomSourceName=L64_X128_MIX,L128_X128_MIX
* </pre>
*/
public static class LongJumpableSource extends BaseJumpableSource {
/**
* Select RNG providers.
*/
@Param({
// Requires the LCG to be advanced 2^32 rather than 1 cycle which
// can use precomputed coefficients.
"L64_X128_MIX",
"L64_X256_MIX",
"L64_X1024_MIX",
// Requires the LCG to be advanced 2^64 rather than 1 cycle which
// leaves the entire lower state unchanged and is computationally simpler
// using precomputed coefficients.
"L128_X128_MIX",
"L128_X256_MIX",
"L128_X1024_MIX",
// Requires the LCG to be advanced 2^16 rather than 1 cycle which
// can use precomputed coefficients.
"L32_X64_MIX"})
private String randomSourceName;
/** {@inheritDoc} */
@Override
protected Supplier<UniformRandomProvider> createJumpFunction() {
final UniformRandomProvider rng = RandomSource.valueOf(randomSourceName).create();
if (rng instanceof LongJumpableUniformRandomProvider) {
return ((LongJumpableUniformRandomProvider) rng)::longJump;
}
throw new IllegalStateException("Invalid long jump source: " + randomSourceName);
}
}
/**
* Jump benchmark.
*
* @param data Source of the jump
* @return the copy
*/
@Benchmark
public UniformRandomProvider jump(JumpableSource data) {
return data.jump();
}
/**
* Long jump benchmark.
*
* @param data Source of the long jump
* @return the copy
*/
@Benchmark
public UniformRandomProvider longJump(LongJumpableSource data) {
return data.jump();
}
}
| 2,756 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/NextBytesGenerationPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import org.apache.commons.rng.UniformRandomProvider;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
/**
* Executes benchmark to compare the speed of generation of random numbers from the
* various source providers for {@link UniformRandomProvider#nextBytes(byte[])}.
*/
public class NextBytesGenerationPerformance extends AbstractBenchmark {
/**
* The value. This is a pre-allocated array. Must NOT be final to prevent JVM
* optimisation!
*/
private byte[] value = new byte[BaselineGenerationPerformance.NEXT_BYTES_SIZE];
/**
* The benchmark state (retrieve the various "RandomSource"s).
*/
@State(Scope.Benchmark)
public static class Sources extends BaselineSources {
/** {@inheritDoc} */
@Override
protected UniformRandomProvider createBaseline() {
return BaselineUtils.getNextBytes();
}
}
/**
* Baseline for a JMH method call with no return value.
*/
@Benchmark
public void baselineVoid() {
// Do nothing, this is a baseline
}
/**
* Baseline for a JMH method call returning a {@code byte[]}.
*
* @return the value
*/
@Benchmark
public byte[] baselineBytes() {
return value;
}
/**
* Exercise the {@link UniformRandomProvider#nextBytes(byte[])} method.
*
* @param sources Source of randomness.
* @return the boolean
*/
@Benchmark
public byte[] nextBytes(Sources sources) {
// The array allocation is not part of the benchmark.
sources.getGenerator().nextBytes(value);
return value;
}
}
| 2,757 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/AbstractBenchmark.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
/**
* Declares the JMH annotations for the benchmarks to compare the speed of generation of
* random numbers from the various source providers for
* {@link org.apache.commons.rng.UniformRandomProvider UniformRandomProvider}.
*
* <p>Note: Implementing this as an {@code @interface} annotation results in errors as the
* meta-annotation is not expanded by the JMH annotation processor. The processor does however
* allow all annotations to be inherited from abstract classes.</p>
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(value = 1, jvmArgs = { "-server", "-Xms128M", "-Xmx128M" })
@State(Scope.Benchmark)
public abstract class AbstractBenchmark {
/**
* Create a new instance.
*/
protected AbstractBenchmark() {
// Hide public constructor to prevent instantiation
}
// Empty. Serves as an annotation placeholder.
}
| 2,758 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/CachedNextGenerationPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import java.util.function.IntSupplier;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.source64.LongProvider;
import org.apache.commons.rng.examples.jmh.RandomSources;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
/**
* Executes a benchmark to compare the speed of generation of random numbers from the
* various source providers using the bit cache verses simple generation.
*/
public class CachedNextGenerationPerformance extends AbstractBenchmark {
/** The value. Must NOT be final to prevent JVM optimisation! */
private boolean booleanValue;
/** The value. Must NOT be final to prevent JVM optimisation! */
private int intValue;
/**
* Provides a function to obtain a boolean value from the various "RandomSource"s.
* It exercise the default nextBoolean() method (which may use
* a cache of bits) against a sign test on the native output.
*/
@State(Scope.Benchmark)
public static class BooleanSources extends RandomSources {
/** Functional interface for a boolean generator. */
interface BooleanSupplier {
/**
* @return the boolean
*/
boolean getAsBoolean();
}
/**
* The method to create the boolean value.
*/
@Param({"nextBoolean", "signTest"})
private String method;
/** The generator. */
private BooleanSupplier generator;
/**
* @return the next boolean
*/
boolean next() {
return generator.getAsBoolean();
}
/** {@inheritDoc} */
@Override
@Setup
public void setup() {
// Create the generator.
super.setup();
final UniformRandomProvider rng = getGenerator();
// Create the method to generate the boolean
if ("signTest".equals(method)) {
if (rng instanceof LongProvider) {
generator = () -> rng.nextLong() < 0;
} else {
// Assumed IntProvider
generator = () -> rng.nextInt() < 0;
}
} else if ("nextBoolean".equals(method)) {
// Do not use a method handle 'rng::nextBoolean' for the nextBoolean
// to attempt to maintain a comparable lambda function. The JVM may
// optimise this away.
generator = () -> rng.nextBoolean();
} else {
throw new IllegalStateException("Unknown boolean method: " + method);
}
}
}
/**
* Provides a function to obtain an int value from the various "RandomSource"s
* that produce 64-bit output.
* It exercise the default nextInt() method (which may use
* a cache of bits) against a shift on the native output.
*/
@State(Scope.Benchmark)
public static class IntSources {
/**
* RNG providers. This list is maintained in the order of the {@link RandomSource} enum.
*
* <p>Include only those that are a {@link LongProvider}.</p>
*/
@Param({"SPLIT_MIX_64",
"XOR_SHIFT_1024_S",
"TWO_CMRES",
"MT_64",
"XOR_SHIFT_1024_S_PHI",
"XO_RO_SHI_RO_128_PLUS",
"XO_RO_SHI_RO_128_SS",
"XO_SHI_RO_256_PLUS",
"XO_SHI_RO_256_SS",
"XO_SHI_RO_512_PLUS",
"XO_SHI_RO_512_SS",
"PCG_RXS_M_XS_64",
"SFC_64",
"JSF_64",
"XO_RO_SHI_RO_128_PP",
"XO_SHI_RO_256_PP",
"XO_SHI_RO_512_PP",
"XO_RO_SHI_RO_1024_PP",
"XO_RO_SHI_RO_1024_S",
"XO_RO_SHI_RO_1024_SS",
"PCG_RXS_M_XS_64_OS"})
private String randomSourceName;
/**
* The method to create the int value.
*/
@Param({"nextInt", "shiftLong"})
private String method;
/** The generator. */
private IntSupplier gen;
/**
* @return the next int
*/
int next() {
return gen.getAsInt();
}
/** Create the int source. */
@Setup
public void setup() {
final UniformRandomProvider rng = RandomSource.valueOf(randomSourceName).create();
if (!(rng instanceof LongProvider)) {
throw new IllegalStateException("Not a LongProvider: " + rng.getClass().getName());
}
// Create the method to generate the int
if ("shiftLong".equals(method)) {
gen = () -> (int) (rng.nextLong() >>> 32);
} else if ("nextInt".equals(method)) {
// Do not use a method handle 'rng::nextInt' for the nextInt
// to attempt to maintain a comparable lambda function. The JVM may
// optimise this away.
gen = () -> rng.nextInt();
} else {
throw new IllegalStateException("Unknown int method: " + method);
}
}
}
/**
* Baseline for a JMH method call with no return value.
*/
@Benchmark
public void baselineVoid() {
// Do nothing, this is a baseline
}
/**
* Baseline for a JMH method call returning a {@code boolean}.
*
* @return the value
*/
@Benchmark
public boolean baselineBoolean() {
return booleanValue;
}
/**
* Baseline for a JMH method call returning an {@code int}.
*
* @return the value
*/
@Benchmark
public int baselineInt() {
return intValue;
}
/**
* Exercise the boolean generation method.
*
* @param sources Source of randomness.
* @return the boolean
*/
@Benchmark
public boolean nextBoolean(BooleanSources sources) {
return sources.next();
}
/**
* Exercise the int generation method.
*
* @param sources Source of randomness.
* @return the int
*/
@Benchmark
public int nextInt(IntSources sources) {
return sources.next();
}
}
| 2,759 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/RngNextIntInRangeBenchmark.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.source32.IntProvider;
import org.apache.commons.rng.sampling.PermutationSampler;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
/**
* Executes benchmark to compare the speed of random number generators to create
* an int value in a range.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = { "-server", "-Xms128M", "-Xmx128M" })
public class RngNextIntInRangeBenchmark {
/** The value. Must NOT be final to prevent JVM optimisation! */
private int intValue;
/**
* The upper range for the {@code int} generation.
*/
@State(Scope.Benchmark)
public static class IntRange {
/**
* The upper range for the {@code int} generation.
*
* <p>Note that the while loop uses a rejection algorithm. From the Javadoc for
* java.util.Random:</p>
*
* <pre>
* "The probability of a value being rejected depends on n. The
* worst case is n=2^30+1, for which the probability of a reject is 1/2,
* and the expected number of iterations before the loop terminates is 2."
* </pre>
*/
@Param({"16", "17", "256", "257", "4096", "4097",
// Worst case power-of-2: (1 << 30)
"1073741824",
// Worst case: (1 << 30) + 1
"1073741825", })
private int n;
/**
* Gets the upper bound {@code n}.
*
* @return the upper bound
*/
public int getN() {
return n;
}
}
/**
* The data used for the shuffle benchmark.
*/
@State(Scope.Benchmark)
public static class IntData {
/**
* The size of the data.
*/
@Param({ "4", "16", "256", "4096", "16384" })
private int size;
/** The data. */
private int[] data;
/**
* Gets the data.
*
* @return the data
*/
public int[] getData() {
return data;
}
/**
* Create the data.
*/
@Setup
public void setup() {
data = PermutationSampler.natural(size);
}
}
/**
* The source generator.
*/
@State(Scope.Benchmark)
public static class Source {
/**
* The name of the generator.
*/
@Param({ "jdk", "jdkPow2", "lemire", "lemirePow2", "lemire31", "lemire31Pow2"})
private String name;
/** The random generator. */
private UniformRandomProvider rng;
/**
* Gets the random generator.
*
* @return the generator
*/
public UniformRandomProvider getRng() {
return rng;
}
/** Create the generator. */
@Setup
public void setup() {
final long seed = ThreadLocalRandom.current().nextLong();
if ("jdk".equals(name)) {
rng = new JDK(seed);
} else if ("jdkPow2".equals(name)) {
rng = new JDKPow2(seed);
} else if ("lemire".equals(name)) {
rng = new Lemire(seed);
} else if ("lemirePow2".equals(name)) {
rng = new LemirePow2(seed);
} else if ("lemire31".equals(name)) {
rng = new Lemire31(seed);
} else if ("lemire31Pow2".equals(name)) {
rng = new Lemire31Pow2(seed);
}
}
}
/**
* Implement the SplitMix algorithm from {@link java.util.SplittableRandom
* SplittableRandom} to output 32-bit int values.
*
* <p>This is a base generator to test nextInt(int) methods.
*/
abstract static class SplitMix32 extends IntProvider {
/**
* The golden ratio, phi, scaled to 64-bits and rounded to odd.
*/
private static final long GOLDEN_RATIO = 0x9e3779b97f4a7c15L;
/** The state. */
protected long state;
/**
* Create a new instance.
*
* @param seed the seed
*/
SplitMix32(long seed) {
state = seed;
}
@Override
public int next() {
long key = state += GOLDEN_RATIO;
// 32 high bits of Stafford variant 4 mix64 function as int:
// http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
key = (key ^ (key >>> 33)) * 0x62a9d9ed799705f5L;
return (int) (((key ^ (key >>> 28)) * 0xcb24d0a5c88c35b3L) >>> 32);
}
/**
* Check the value is strictly positive.
*
* @param n the value
*/
void checkStrictlyPositive(int n) {
if (n <= 0) {
throw new IllegalArgumentException("not strictly positive: " + n);
}
}
}
/**
* Implement the nextInt(int) method of the JDK excluding the case for a power-of-2 range.
*/
static class JDK extends SplitMix32 {
/**
* Create a new instance.
*
* @param seed the seed
*/
JDK(long seed) {
super(seed);
}
@Override
public int nextInt(int n) {
checkStrictlyPositive(n);
int bits;
int val;
do {
bits = next() >>> 1;
val = bits % n;
} while (bits - val + n - 1 < 0);
return val;
}
}
/**
* Implement the nextInt(int) method of the JDK with a case for a power-of-2 range.
*/
static class JDKPow2 extends SplitMix32 {
/**
* Create a new instance.
*
* @param seed the seed
*/
JDKPow2(long seed) {
super(seed);
}
@Override
public int nextInt(int n) {
checkStrictlyPositive(n);
final int nm1 = n - 1;
if ((n & nm1) == 0) {
// Power of 2
return next() & nm1;
}
int bits;
int val;
do {
bits = next() >>> 1;
val = bits % n;
} while (bits - val + nm1 < 0);
return val;
}
}
/**
* Implement the nextInt(int) method of Lemire (2019).
*
* @see <a href="https://arxiv.org/abs/1805.10941SplittableRandom"> Lemire
* (2019): Fast Random Integer Generation in an Interval</a>
*/
static class Lemire extends SplitMix32 {
/** 2^32. */
static final long POW_32 = 1L << 32;
/**
* Create a new instance.
*
* @param seed the seed
*/
Lemire(long seed) {
super(seed);
}
@Override
public int nextInt(int n) {
checkStrictlyPositive(n);
long m = (next() & 0xffffffffL) * n;
long l = m & 0xffffffffL;
if (l < n) {
// 2^32 % n
final long t = POW_32 % n;
while (l < t) {
m = (next() & 0xffffffffL) * n;
l = m & 0xffffffffL;
}
}
return (int) (m >>> 32);
}
}
/**
* Implement the nextInt(int) method of Lemire (2019) with a case for a power-of-2 range.
*/
static class LemirePow2 extends SplitMix32 {
/** 2^32. */
static final long POW_32 = 1L << 32;
/**
* Create a new instance.
*
* @param seed the seed
*/
LemirePow2(long seed) {
super(seed);
}
@Override
public int nextInt(int n) {
checkStrictlyPositive(n);
final int nm1 = n - 1;
if ((n & nm1) == 0) {
// Power of 2
return next() & nm1;
}
long m = (next() & 0xffffffffL) * n;
long l = m & 0xffffffffL;
if (l < n) {
// 2^32 % n
final long t = POW_32 % n;
while (l < t) {
m = (next() & 0xffffffffL) * n;
l = m & 0xffffffffL;
}
}
return (int) (m >>> 32);
}
}
/**
* Implement the nextInt(int) method of Lemire (2019) modified to 31-bit arithmetic to use
* an int modulus operation.
*/
static class Lemire31 extends SplitMix32 {
/** 2^32. */
static final long POW_32 = 1L << 32;
/**
* Create a new instance.
*
* @param seed the seed
*/
Lemire31(long seed) {
super(seed);
}
@Override
public int nextInt(int n) {
checkStrictlyPositive(n);
long m = (nextInt() & 0x7fffffffL) * n;
long l = m & 0x7fffffffL;
if (l < n) {
// 2^31 % n
final long t = (Integer.MIN_VALUE - n) % n;
while (l < t) {
m = (nextInt() & 0x7fffffffL) * n;
l = m & 0x7fffffffL;
}
}
return (int) (m >>> 31);
}
}
/**
* Implement the nextInt(int) method of Lemire (2019) modified to 31-bit arithmetic to use
* an int modulus operation, with a case for a power-of-2 range.
*/
static class Lemire31Pow2 extends SplitMix32 {
/** 2^32. */
static final long POW_32 = 1L << 32;
/**
* Create a new instance.
*
* @param seed the seed
*/
Lemire31Pow2(long seed) {
super(seed);
}
@Override
public int nextInt(int n) {
checkStrictlyPositive(n);
final int nm1 = n - 1;
if ((n & nm1) == 0) {
// Power of 2
return next() & nm1;
}
long m = (nextInt() & 0x7fffffffL) * n;
long l = m & 0x7fffffffL;
if (l < n) {
// 2^31 % n
final long t = (Integer.MIN_VALUE - n) % n;
while (l < t) {
m = (nextInt() & 0x7fffffffL) * n;
l = m & 0x7fffffffL;
}
}
return (int) (m >>> 31);
}
}
/**
* Baseline for a JMH method call returning an {@code int}.
*
* @return the value
*/
@Benchmark
public int baselineInt() {
return intValue;
}
/**
* Exercise the {@link UniformRandomProvider#nextInt()} method.
*
* @param range the range
* @param source Source of randomness.
* @return the int
*/
@Benchmark
public int nextIntN(IntRange range, Source source) {
return source.getRng().nextInt(range.getN());
}
/**
* Exercise the {@link UniformRandomProvider#nextInt()} method in a loop.
*
* @param range the range
* @param source Source of randomness.
* @return the int
*/
@Benchmark
@OperationsPerInvocation(65_536)
public int nextIntNloop65536(IntRange range, Source source) {
int sum = 0;
for (int i = 0; i < 65_536; i++) {
sum += source.getRng().nextInt(range.getN());
}
return sum;
}
/**
* Exercise the {@link UniformRandomProvider#nextInt(int)} method by shuffling
* data.
*
* @param data the data
* @param source Source of randomness.
* @return the shuffle data
*/
@Benchmark
public int[] shuffle(IntData data, Source source) {
final int[] array = data.getData();
shuffle(array, source.getRng());
return array;
}
/**
* Perform a Fischer-Yates shuffle.
*
* @param array the array
* @param rng the random generator
*/
private static void shuffle(int[] array, UniformRandomProvider rng) {
for (int i = array.length - 1; i > 0; i--) {
// Swap index with any position down to 0
final int j = rng.nextInt(i);
final int tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
/**
* Exercise the {@link UniformRandomProvider#nextInt(int)} method by creating
* random indices for shuffling data.
*
* @param data the data
* @param source Source of randomness.
* @return the sum
*/
@Benchmark
public int pseudoShuffle(IntData data, Source source) {
int sum = 0;
for (int i = data.getData().length - 1; i > 0; i--) {
sum += source.getRng().nextInt(i);
}
return sum;
}
}
| 2,760 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/NextDoubleGenerationPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import org.apache.commons.rng.UniformRandomProvider;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
/**
* Executes benchmark to compare the speed of generation of random numbers from the
* various source providers for {@link UniformRandomProvider#nextDouble()}.
*/
public class NextDoubleGenerationPerformance extends AbstractBenchmark {
/** The value. Must NOT be final to prevent JVM optimisation! */
private double value;
/**
* The benchmark state (retrieve the various "RandomSource"s).
*/
@State(Scope.Benchmark)
public static class Sources extends BaselineSources {
/** {@inheritDoc} */
@Override
protected UniformRandomProvider createBaseline() {
return BaselineUtils.getNextDouble();
}
}
/**
* Baseline for a JMH method call with no return value.
*/
@Benchmark
public void baselineVoid() {
// Do nothing, this is a baseline
}
/**
* Baseline for a JMH method call returning a {@code double}.
*
* @return the value
*/
@Benchmark
public double baselineDouble() {
return value;
}
/**
* Exercise the {@link UniformRandomProvider#nextDouble()} method.
*
* @param sources Source of randomness.
* @return the double
*/
@Benchmark
public double nextDouble(Sources sources) {
return sources.getGenerator().nextDouble();
}
}
| 2,761 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/NextIntGenerationPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import org.apache.commons.rng.UniformRandomProvider;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
/**
* Executes benchmark to compare the speed of generation of random numbers from the
* various source providers for {@link UniformRandomProvider#nextInt()} and
* {@link UniformRandomProvider#nextInt(int)}.
*/
public class NextIntGenerationPerformance extends AbstractBenchmark {
/** The value. Must NOT be final to prevent JVM optimisation! */
private int value;
/**
* The benchmark state (retrieve the various "RandomSource"s).
*/
@State(Scope.Benchmark)
public static class Sources extends BaselineSources {
/** {@inheritDoc} */
@Override
protected UniformRandomProvider createBaseline() {
return BaselineUtils.getNextInt();
}
}
/**
* Baseline for a JMH method call with no return value.
*/
@Benchmark
public void baselineVoid() {
// Do nothing, this is a baseline
}
/**
* Baseline for a JMH method call returning an {@code int}.
*
* @return the value
*/
@Benchmark
public int baselineInt() {
return value;
}
/**
* Exercise the {@link UniformRandomProvider#nextInt()} method.
*
* @param sources Source of randomness.
* @return the int
*/
@Benchmark
public int nextInt(Sources sources) {
return sources.getGenerator().nextInt();
}
/**
* Exercise the {@link UniformRandomProvider#nextInt(int)} method.
*
* @param sources Source of randomness.
* @return the int
*/
@Benchmark
public int nextIntN(Sources sources) {
return sources.getGenerator().nextInt(BaselineGenerationPerformance.NEXT_INT_LIMIT);
}
}
| 2,762 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/NextFloatGenerationPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import org.apache.commons.rng.UniformRandomProvider;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
/**
* Executes benchmark to compare the speed of generation of random numbers from the
* various source providers for {@link UniformRandomProvider#nextFloat()}.
*/
public class NextFloatGenerationPerformance extends AbstractBenchmark {
/** The value. Must NOT be final to prevent JVM optimisation! */
private float value;
/**
* The benchmark state (retrieve the various "RandomSource"s).
*/
@State(Scope.Benchmark)
public static class Sources extends BaselineSources {
/** {@inheritDoc} */
@Override
protected UniformRandomProvider createBaseline() {
return BaselineUtils.getNextFloat();
}
}
/**
* Baseline for a JMH method call with no return value.
*/
@Benchmark
public void baselineVoid() {
// Do nothing, this is a baseline
}
/**
* Baseline for a JMH method call returning a {@code float}.
*
* @return the value
*/
@Benchmark
public float baselineFloat() {
return value;
}
/**
* Exercise the {@link UniformRandomProvider#nextFloat()} method.
*
* @param sources Source of randomness.
* @return the float
*/
@Benchmark
public float nextFloat(Sources sources) {
return sources.getGenerator().nextFloat();
}
}
| 2,763 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/BaselineGenerationPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import org.apache.commons.rng.UniformRandomProvider;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import java.util.concurrent.TimeUnit;
/**
* Benchmarks to check linearity in the baseline implementations of {@link UniformRandomProvider}.
*
* <p>These ordinarily do not need to be run. The benchmarks can be used to determine
* if the baseline scales linearly with workload. If not then the JVM has removed the
* baseline from the testing loop given that its result is predictable. The ideal
* baseline will:</p>
*
* <ul>
* <li>Run as fast as possible
* <li>Not be removed from the execution path
* </ul>
*
* <p>The results of this benchmark should be plotted for each method using [numValues] vs [run time]
* to check linearity.</p>
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = { "-server", "-Xms128M", "-Xmx128M" })
public class BaselineGenerationPerformance {
/**
* The size of the array for testing {@link UniformRandomProvider#nextBytes(byte[])}.
*
* <p>This is a small prime number (127). This satisfies the following requirements:</p>
*
* <ul>
* <li>The number of bytes will be allocated when testing so the allocation overhead
* should be small.
* <li>The number must be set so that filling the bytes from an {@code int} or {@code long}
* source has no advantage for the 32-bit source, e.g. the same number of underlying bits have
* to be generated. Note: 127 / 4 ~ 32 ints or 127 / 8 ~ 16 longs.
* <li>The number should not be a factor of 4 to prevent filling completely using a 32-bit
* source. This tests the edge case of partial fill.
* </ul>
*/
static final int NEXT_BYTES_SIZE = 127;
/**
* The upper limit for testing {@link UniformRandomProvider#nextInt(int)}.
*
* <p>This is the biggest prime number for an {@code int} (2147483629) to give a worst case
* run-time for the method.</p>
*/
static final int NEXT_INT_LIMIT = 2_147_483_629;
/**
* The upper limit for testing {@link UniformRandomProvider#nextLong(long)}.
*
* <p>This is the biggest prime number for a {@code long} (9223372036854775783L) to
* give a worst case run-time for the method.</p>
*/
static final long NEXT_LONG_LIMIT = 9_223_372_036_854_775_783L;
/**
* The provider for testing {@link UniformRandomProvider#nextBytes(byte[])}.
*/
private UniformRandomProvider nextBytesProvider = BaselineUtils.getNextBytes();
/**
* The provider for testing {@link UniformRandomProvider#nextInt()} and
* {@link UniformRandomProvider#nextInt(int)}.
*/
private UniformRandomProvider nextIntProvider = BaselineUtils.getNextInt();
/**
* The provider for testing {@link UniformRandomProvider#nextLong()} and
* {@link UniformRandomProvider#nextLong(long)}.
*/
private UniformRandomProvider nextLongProvider = BaselineUtils.getNextLong();
/**
* The provider for testing {@link UniformRandomProvider#nextBoolean()}.
*/
private UniformRandomProvider nextBooleanProvider = BaselineUtils.getNextBoolean();
/**
* The provider for testing {@link UniformRandomProvider#nextFloat()}.
*/
private UniformRandomProvider nextFloatProvider = BaselineUtils.getNextFloat();
/**
* The provider for testing {@link UniformRandomProvider#nextDouble()}.
*/
private UniformRandomProvider nextDoubleProvider = BaselineUtils.getNextDouble();
/**
* Number of random values to generate when testing linearity. This must be high to avoid
* JIT optimisation of small loop constructs.
*
* <p>Note: Following the convention in the JMH Blackhole::consumCPU(long) method
* the loops are constructed to count down (although since there is no consumption
* of the loop counter the loop construct may be rewritten anyway).</p>
*/
@Param({"50000", "100000", "150000", "200000", "250000"})
private int numValues;
/**
* Exercise the {@link UniformRandomProvider#nextBytes(byte[])} method.
*
* <p>Note: Currently there is not a test for
* {@link UniformRandomProvider#nextBytes(byte[], int, int)} since the two methods are
* implemented by the base Int/LongProvider class using the same code.</p>
*
* @param bh Data sink.
*/
@Benchmark
public void nextBytes(Blackhole bh) {
// The array allocation is not part of the benchmark.
final byte[] result = new byte[NEXT_BYTES_SIZE];
for (int i = numValues; i > 0; i--) {
nextBytesProvider.nextBytes(result);
bh.consume(result);
}
}
/**
* Exercise the {@link UniformRandomProvider#nextInt()} method.
*
* @param bh Data sink.
*/
@Benchmark
public void nextInt(Blackhole bh) {
for (int i = numValues; i > 0; i--) {
bh.consume(nextIntProvider.nextInt());
}
}
/**
* Exercise the {@link UniformRandomProvider#nextInt(int)} method.
*
* @param bh Data sink.
*/
@Benchmark
public void nextIntN(Blackhole bh) {
for (int i = numValues; i > 0; i--) {
bh.consume(nextIntProvider.nextInt(NEXT_INT_LIMIT));
}
}
/**
* Exercise the {@link UniformRandomProvider#nextLong()} method.
*
* @param bh Data sink.
*/
@Benchmark
public void nextLong(Blackhole bh) {
for (int i = numValues; i > 0; i--) {
bh.consume(nextLongProvider.nextLong());
}
}
/**
* Exercise the {@link UniformRandomProvider#nextLong(long)} method.
*
* @param bh Data sink.
*/
@Benchmark
public void nextLongN(Blackhole bh) {
for (int i = numValues; i > 0; i--) {
bh.consume(nextLongProvider.nextLong(NEXT_LONG_LIMIT));
}
}
/**
* Exercise the {@link UniformRandomProvider#nextBoolean()} method.
*
* @param bh Data sink.
*/
@Benchmark
public void nextBoolean(Blackhole bh) {
for (int i = numValues; i > 0; i--) {
bh.consume(nextBooleanProvider.nextBoolean());
}
}
/**
* Exercise the {@link UniformRandomProvider#nextFloat()} method.
*
* @param bh Data sink.
*/
@Benchmark
public void nextFloat(Blackhole bh) {
for (int i = numValues; i > 0; i--) {
bh.consume(nextFloatProvider.nextFloat());
}
}
/**
* Exercise the {@link UniformRandomProvider#nextDouble()} method.
*
* @param bh Data sink.
*/
@Benchmark
public void nextDouble(Blackhole bh) {
for (int i = numValues; i > 0; i--) {
bh.consume(nextDoubleProvider.nextDouble());
}
}
}
| 2,764 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/FloatingPointGenerationPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
/**
* Executes benchmark to compare the speed of generation of floating point
* numbers from the integer primitives.
*/
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = { "-server", "-Xms128M", "-Xmx128M" })
public class FloatingPointGenerationPerformance {
/**
* Mimic the generation of the SplitMix64 algorithm.
*
* <p>The final mixing step must be included otherwise the output numbers are sequential
* and the test may run with a lack of numbers with higher order bits.</p>
*/
@State(Scope.Benchmark)
public static class LongSource {
/** The state. */
private long state = ThreadLocalRandom.current().nextLong();
/**
* Get the next long.
*
* @return the long
*/
public final long nextLong() {
long z = state += 0x9e3779b97f4a7c15L;
z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
return z ^ (z >>> 31);
}
/**
* Get the next int.
*
* <p>Returns the 32 high bits of Stafford variant 4 mix64 function as int.
*
* @return the int
*/
public final int nextInt() {
long z = state += 0x9e3779b97f4a7c15L;
z = (z ^ (z >>> 33)) * 0x62a9d9ed799705f5L;
return (int)(((z ^ (z >>> 28)) * 0xcb24d0a5c88c35b3L) >>> 32);
}
}
// Benchmark methods
/**
* @param source the source
* @return the long
*/
@Benchmark
public long nextDoubleBaseline(LongSource source) {
return source.nextLong();
}
/**
* @param source the source
* @return the double
*/
@Benchmark
public double nextDoubleUsingBitsToDouble(LongSource source) {
// Combine 11 bit unsigned exponent with value 1023 (768 + 255) with 52 bit mantissa
// 0x300L = 256 + 512 = 768
// 0x0ff = 255
// This makes a number in the range 1.0 to 2.0 so subtract 1.0
return Double.longBitsToDouble(0x3ffL << 52 | source.nextLong() >>> 12) - 1.0;
}
/**
* @param source the source
* @return the double
*/
@Benchmark
public double nextDoubleUsingMultiply52bits(LongSource source) {
return (source.nextLong() >>> 12) * 0x1.0p-52d; // 1.0 / (1L << 52)
}
/**
* @param source the source
* @return the double
*/
@Benchmark
public double nextDoubleUsingMultiply53bits(LongSource source) {
return (source.nextLong() >>> 11) * 0x1.0p-53d; // 1.0 / (1L << 53)
}
/**
* @param source the source
* @return the int
*/
@Benchmark
public int nextFloatBaseline(LongSource source) {
return source.nextInt();
}
/**
* @param source the source
* @return the float
*/
@Benchmark
public float nextFloatUsingBitsToFloat(LongSource source) {
// Combine 8 bit unsigned exponent with value 127 (112 + 15) with 23 bit mantissa
// 0x70 = 64 + 32 + 16 = 112
// 0x0f = 15
// This makes a number in the range 1.0f to 2.0f so subtract 1.0f
return Float.intBitsToFloat(0x7f << 23 | source.nextInt() >>> 9) - 1.0f;
}
/**
* @param source the source
* @return the float
*/
@Benchmark
public float nextFloatUsingMultiply23bits(LongSource source) {
return (source.nextInt() >>> 9) * 0x1.0p-23f; // 1.0f / (1 << 23)
}
/**
* @param source the source
* @return the float
*/
@Benchmark
public float nextFloatUsingMultiply24bits(LongSource source) {
return (source.nextInt() >>> 8) * 0x1.0p-24f; // 1.0f / (1 << 24)
}
}
| 2,765 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/LXMBenchmark.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.function.LongSupplier;
import java.util.stream.LongStream;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
/**
* Executes a benchmark for operations used in the LXM family of RNGs.
*
* <h2>Note</h2>
*
* <p>Some code in this benchmark is commented out. It requires a higher
* version of Java than the current target. Bumping the JMH module to a higher
* minimum java version prevents running benchmarks on the target JVM for
* the Commons RNG artifacts. Thus these benchmarks must be manually reinstated by
* uncommenting the code and updating the Java version in the module pom.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = { "-server", "-Xms128M", "-Xmx128M" })
public class LXMBenchmark {
/** Low half of 128-bit LCG multiplier. The upper half is {@code 1L}. */
static final long ML = 0xd605bbb58c8abbfdL;
/** Baseline for generation of 1 long value. */
private static final String BASELINE1 = "baseline1";
/** Baseline for generation of 2 long values. */
private static final String BASELINE2 = "baseline2";
/** Baseline for generation of 4 long values. */
private static final String BASELINE4 = "baseline4";
/** Reference implementation. */
private static final String REFERENCE = "reference";
/** Branchless implementation. */
private static final String BRANCHLESS = "branchless";
/**
* Encapsulates a method to compute an unsigned multiply of 64-bit values to create
* the upper and optionally low 64-bits of the 128-bit result.
*
* <p>This tests methods used to compute an update of a 128-bit linear congruential
* generator (LCG).
*/
@State(Scope.Benchmark)
public static class UnsignedMultiplyHighSource {
/** A mask to convert an {@code int} to an unsigned integer stored as a {@code long}. */
private static final long INT_TO_UNSIGNED_BYTE_MASK = 0xffff_ffffL;
/** Precomputed upper split (32-bits) of the low half of the 128-bit multiplier constant. */
private static final long X = ML >>> 32;
/** Precomputed lower split (32-bits) of the low half of the 128-bit multiplier constant. */
private static final long Y = ML & INT_TO_UNSIGNED_BYTE_MASK;
/**
* The method to compute the value.
*/
@Param({BASELINE1,
// Require JDK 9+
//"mathMultiplyHigh", "mathMultiplyHighWithML",
// Require JDK 18+
//"mathUnsignedMultiplyHigh", "mathUnsignedMultiplyHighWithML",
"unsignedMultiplyHigh", "unsignedMultiplyHighWithML",
"unsignedMultiplyHighML",
"unsignedMultiplyHighPlusMultiplyLow", "unsignedMultiplyHighAndLow",
})
private String method;
/** Flag to indicate numbers should be precomputed.
* Note: The multiply method is extremely fast and number generation can take
* a significant part of the overall generation time. */
@Param({"true", "false"})
private boolean precompute;
/** The generator of the next value. */
private LongSupplier gen;
/**
* Compute the next value.
*
* @return the value
*/
long next() {
return gen.getAsLong();
}
/**
* Create the generator of output values.
*/
@Setup
public void setup() {
final JumpableUniformRandomProvider rng =
(JumpableUniformRandomProvider) RandomSource.XO_RO_SHI_RO_128_PP.create();
LongSupplier ga;
LongSupplier gb;
// Optionally precompute numbers.
if (precompute) {
final long[] values = LongStream.generate(rng::nextLong).limit(1024).toArray();
class A implements LongSupplier {
private int i;
@Override
public long getAsLong() {
return values[i++ & 1023];
}
}
ga = new A();
class B implements LongSupplier {
private int i;
@Override
public long getAsLong() {
// Using any odd increment will sample all values (after wrapping)
return values[(i += 3) & 1023];
}
}
gb = new B();
} else {
ga = rng::nextLong;
gb = rng.jump()::nextLong;
}
if (BASELINE1.equals(method)) {
gen = () -> ga.getAsLong();
} else if (BASELINE2.equals(method)) {
gen = () -> ga.getAsLong() ^ gb.getAsLong();
} else if ("mathMultiplyHigh".equals(method)) {
gen = () -> mathMultiplyHigh(ga.getAsLong(), gb.getAsLong());
} else if ("mathMultiplyHighWithML".equals(method)) {
gen = () -> mathMultiplyHigh(ga.getAsLong(), ML);
} else if ("mathUnsignedMultiplyHigh".equals(method)) {
gen = () -> mathUnsignedMultiplyHigh(ga.getAsLong(), gb.getAsLong());
} else if ("mathUnsignedMultiplyHighWithML".equals(method)) {
gen = () -> mathUnsignedMultiplyHigh(ga.getAsLong(), ML);
} else if ("unsignedMultiplyHigh".equals(method)) {
gen = () -> unsignedMultiplyHigh(ga.getAsLong(), gb.getAsLong());
} else if ("unsignedMultiplyHighWithML".equals(method)) {
gen = () -> unsignedMultiplyHigh(ga.getAsLong(), ML);
} else if ("unsignedMultiplyHighML".equals(method)) {
// Note:
// Running this benchmark should show the explicit precomputation
// of the ML parts does not increase performance. The JVM can
// optimise the call to unsignedMultiplyHigh(a, b) when b is constant.
gen = () -> unsignedMultiplyHighML(ga.getAsLong());
} else if ("unsignedMultiplyHighPlusMultiplyLow".equals(method)) {
gen = () -> {
final long a = ga.getAsLong();
final long b = gb.getAsLong();
return unsignedMultiplyHigh(a, b) ^ (a * b);
};
} else if ("unsignedMultiplyHighAndLow".equals(method)) {
// Note:
// Running this benchmark should show this method is slower.
// A CPU supporting parallel instructions can multiply (a*b)
// in parallel to calling unsignedMultiplyHigh.
final long[] lo = {0};
gen = () -> {
final long a = ga.getAsLong();
final long b = gb.getAsLong();
final long hi = unsignedMultiplyHigh(a, b, lo);
return hi ^ lo[0];
};
} else {
throw new IllegalStateException("Unknown method: " + method);
}
}
/**
* Compute the unsigned multiply of two values using Math.multiplyHigh.
* <p>Requires JDK 9.
* From JDK 10 onwards this method is an intrinsic candidate.
*
* @param a First value
* @param b Second value
* @return the upper 64-bits of the 128-bit result
*/
static long mathMultiplyHigh(long a, long b) {
// Requires JDK 9
// Note: Using runtime reflection to create a method handle
// has not been done to avoid any possible artifact during timing
// of this very fast method. To benchmark with this method
// requires uncommenting this code and compiling with an
// appropriate source level.
//return Math.multiplyHigh(a, b) + ((a >> 63) & b) + ((b >> 63) & a);
throw new NoSuchMethodError();
}
/**
* Compute the unsigned multiply of two values using Math.unsignedMultiplyHigh.
* <p>Requires JDK 18.
* This method is an intrinsic candidate.
*
* @param a First value
* @param b Second value
* @return the upper 64-bits of the 128-bit result
*/
static long mathUnsignedMultiplyHigh(long a, long b) {
// Requires JDK 18
//return Math.unsignedMultiplyHigh(a, b);
throw new NoSuchMethodError();
}
/**
* Multiply the two values as if unsigned 64-bit longs to produce the high 64-bits
* of the 128-bit unsigned result.
*
* <p>This method computes the equivalent of:
* <pre>{@code
* Math.multiplyHigh(a, b) + ((a >> 63) & b) + ((b >> 63) & a)
* }</pre>
*
* <p>Note: The method {@code Math.multiplyHigh} was added in JDK 9
* and should be used as above when the source code targets Java 11
* to exploit the intrinsic method.
*
* <p>Note: The method {@code Math.unsignedMultiplyHigh} was added in JDK 18
* and should be used when the source code target allows.
*
* @param value1 the first value
* @param value2 the second value
* @return the high 64-bits of the 128-bit result
*/
static long unsignedMultiplyHigh(long value1, long value2) {
// Computation is based on the following observation about the upper (a and x)
// and lower (b and y) bits of unsigned big-endian integers:
// ab * xy
// = b * y
// + b * x0
// + a0 * y
// + a0 * x0
// = b * y
// + b * x * 2^32
// + a * y * 2^32
// + a * x * 2^64
//
// Summation using a character for each byte:
//
// byby byby
// + bxbx bxbx 0000
// + ayay ayay 0000
// + axax axax 0000 0000
//
// The summation can be rearranged to ensure no overflow given
// that the result of two unsigned 32-bit integers multiplied together
// plus two full 32-bit integers cannot overflow 64 bits:
// > long x = (1L << 32) - 1
// > x * x + x + x == -1 (all bits set, no overflow)
//
// The carry is a composed intermediate which will never overflow:
//
// byby byby
// + bxbx 0000
// + ayay ayay 0000
//
// + bxbx 0000 0000
// + axax axax 0000 0000
final long a = value1 >>> 32;
final long b = value1 & INT_TO_UNSIGNED_BYTE_MASK;
final long x = value2 >>> 32;
final long y = value2 & INT_TO_UNSIGNED_BYTE_MASK;
final long by = b * y;
final long bx = b * x;
final long ay = a * y;
final long ax = a * x;
// Cannot overflow
final long carry = (by >>> 32) +
(bx & INT_TO_UNSIGNED_BYTE_MASK) +
ay;
// Note:
// low = (carry << 32) | (by & INT_TO_UNSIGNED_BYTE_MASK)
return (bx >>> 32) + (carry >>> 32) + ax;
}
/**
* Multiply the two values as if unsigned 64-bit longs to produce the high
* 64-bits of the 128-bit unsigned result.
*
* @param value1 the first value
* @param value2 the second value
* @param low low 64-bits of the 128-bit result
* @return the high 64-bits of the 128-bit result
*/
static long unsignedMultiplyHigh(long value1, long value2, long[] low) {
final long a = value1 >>> 32;
final long b = value1 & INT_TO_UNSIGNED_BYTE_MASK;
final long x = value2 >>> 32;
final long y = value2 & INT_TO_UNSIGNED_BYTE_MASK;
final long by = b * y;
final long bx = b * x;
final long ay = a * y;
final long ax = a * x;
final long carry = (by >>> 32) +
(bx & INT_TO_UNSIGNED_BYTE_MASK) +
ay;
low[0] = (carry << 32) | (by & INT_TO_UNSIGNED_BYTE_MASK);
return (bx >>> 32) + (carry >>> 32) + ax;
}
/**
* Multiply the value as an unsigned 64-bit long by the constant
* {@code ML = 0xd605bbb58c8abbfdL} to produce the high 64-bits
* of the 128-bit unsigned result.
*
* <p>This is a specialised version of {@link #unsignedMultiplyHigh(long, long)}
* for use in the 128-bit LCG sub-generator of the LXM family.
*
* @param value the value
* @return the high 64-bits of the 128-bit result
*/
static long unsignedMultiplyHighML(long value) {
final long a = value >>> 32;
final long b = value & INT_TO_UNSIGNED_BYTE_MASK;
final long by = b * Y;
final long bx = b * X;
final long ay = a * Y;
final long ax = a * X;
// Cannot overflow
final long carry = (by >>> 32) +
(bx & INT_TO_UNSIGNED_BYTE_MASK) +
ay;
return (bx >>> 32) + (carry >>> 32) + ax;
}
}
/**
* Encapsulates a method to compute an unsigned multiply of two 128-bit values to create
* a truncated 128-bit result. The upper 128-bits of the 256-bit result are discarded.
* The upper and optionally low 64-bits of the truncated 128-bit result are computed.
*
* <p>This tests methods used during computation of jumps of size {@code 2^k} for a
* 128-bit linear congruential generator (LCG).
*/
@State(Scope.Benchmark)
public static class UnsignedMultiply128Source {
/** A mask to convert an {@code int} to an unsigned integer stored as a {@code long}. */
private static final long INT_TO_UNSIGNED_BYTE_MASK = 0xffffffffL;
/**
* The method to compute the value.
*/
@Param({BASELINE1,
"unsignedMultiplyHighPlusProducts",
"unsignedMultiply128AndLow",
"unsignedMultiplyHighPlusProducts (square)",
"unsignedSquareHighPlusProducts",
"unsignedMultiply128AndLow (square)",
"unsignedSquare128AndLow",
})
private String method;
/** Flag to indicate numbers should be precomputed.
* Note: The multiply method is extremely fast and number generation can take
* significant part of the overall generation time. */
@Param({"true", "false"})
private boolean precompute;
/** The generator of the next value. */
private LongSupplier gen;
/**
* Compute the next value.
*
* @return the value
*/
long next() {
return gen.getAsLong();
}
/**
* Create the generator of output values.
*/
@Setup
public void setup() {
final JumpableUniformRandomProvider rng =
(JumpableUniformRandomProvider) RandomSource.XO_RO_SHI_RO_128_PP.create();
LongSupplier ga;
LongSupplier gb;
LongSupplier gc;
LongSupplier gd;
// Optionally precompute numbers.
if (precompute) {
final long[] values = LongStream.generate(rng::nextLong).limit(1024).toArray();
class Gen implements LongSupplier {
private int i;
private final int inc;
Gen(int inc) {
this.inc = inc;
}
@Override
public long getAsLong() {
return values[(i += inc) & 1023];
}
}
// Using any odd increment will sample all values (after wrapping)
ga = new Gen(1);
gb = new Gen(3);
gc = new Gen(5);
gd = new Gen(7);
} else {
ga = rng::nextLong;
gb = rng.jump()::nextLong;
gc = rng.jump()::nextLong;
gd = rng.jump()::nextLong;
}
if (BASELINE2.equals(method)) {
gen = () -> ga.getAsLong() ^ gb.getAsLong();
} else if (BASELINE4.equals(method)) {
gen = () -> ga.getAsLong() ^ gb.getAsLong() ^ gc.getAsLong() ^ gd.getAsLong();
} else if ("unsignedMultiplyHighPlusProducts".equals(method)) {
gen = () -> {
final long a = ga.getAsLong();
final long b = gb.getAsLong();
final long c = gc.getAsLong();
final long d = gd.getAsLong();
final long hi = UnsignedMultiplyHighSource.unsignedMultiplyHigh(b, d) +
a * d + b * c;
final long lo = b * d;
return hi ^ lo;
};
} else if ("unsignedMultiply128AndLow".equals(method)) {
// Note:
// Running this benchmark should show this method has no
// benefit over the explicit computation using unsignedMultiplyHigh
// and may actually be slower.
final long[] lo = {0};
gen = () -> {
final long a = ga.getAsLong();
final long b = gb.getAsLong();
final long c = gc.getAsLong();
final long d = gd.getAsLong();
final long hi = unsignedMultiply128(a, b, c, d, lo);
return hi ^ lo[0];
};
} else if ("unsignedMultiplyHighPlusProducts (square)".equals(method)) {
gen = () -> {
final long a = ga.getAsLong();
final long b = gb.getAsLong();
final long hi = UnsignedMultiplyHighSource.unsignedMultiplyHigh(b, b) +
2 * a * b;
final long lo = b * b;
return hi ^ lo;
};
} else if ("unsignedSquareHighPlusProducts".equals(method)) {
gen = () -> {
final long a = ga.getAsLong();
final long b = gb.getAsLong();
final long hi = unsignedSquareHigh(b) +
2 * a * b;
final long lo = b * b;
return hi ^ lo;
};
} else if ("unsignedMultiply128AndLow (square)".equals(method)) {
final long[] lo = {0};
gen = () -> {
final long a = ga.getAsLong();
final long b = gb.getAsLong();
final long hi = unsignedMultiply128(a, b, a, b, lo);
return hi ^ lo[0];
};
} else if ("unsignedSquare128AndLow".equals(method)) {
// Note:
// Running this benchmark should show this method has no
// benefit over the computation using unsignedMultiply128.
// The dedicated square method saves only 1 shift, 1 mask
// and 1 multiply operation.
final long[] lo = {0};
gen = () -> {
final long a = ga.getAsLong();
final long b = gb.getAsLong();
final long hi = unsignedSquare128(a, b, lo);
return hi ^ lo[0];
};
} else {
throw new IllegalStateException("Unknown 128-bit method: " + method);
}
}
/**
* Multiply the two values as if unsigned 128-bit longs to produce the 128-bit unsigned result.
* Note the result is a truncation of the full 256-bit result.
*
* <p>This is a extended version of {@link UnsignedMultiplyHighSource#unsignedMultiplyHigh(long, long)}
* for use in the 128-bit LCG sub-generator of the LXM family. It computes the equivalent of:
* <pre>
* long hi = unsignedMultiplyHigh(value1l, value2l) +
* value1h * value2l + value1l * value2h;
* long lo = value1l * value2l;
* </pre>
*
* @param value1h the high bits of the first value
* @param value1l the low bits of the first value
* @param value2h the high bits of the second value
* @param value2l the low bits of the second value
* @param low the low bits of the 128-bit result (output to array index [0])
* @return the high 64-bits of the 128-bit result
*/
static long unsignedMultiply128(long value1h, long value1l, long value2h, long value2l,
long[] low) {
// Multiply the two low halves to compute an initial 128-bit result
final long a = value1l >>> 32;
final long b = value1l & INT_TO_UNSIGNED_BYTE_MASK;
final long x = value2l >>> 32;
final long y = value2l & INT_TO_UNSIGNED_BYTE_MASK;
final long by = b * y;
final long bx = b * x;
final long ay = a * y;
final long ax = a * x;
// Cannot overflow
final long carry = (by >>> 32) +
(bx & INT_TO_UNSIGNED_BYTE_MASK) +
ay;
low[0] = (carry << 32) | (by & INT_TO_UNSIGNED_BYTE_MASK);
final long high = (bx >>> 32) + (carry >>> 32) + ax;
// Incorporate the remaining high bits that do not overflow 128-bits
return high + value1h * value2l + value1l * value2h;
}
/**
* Square the value as if an unsigned 128-bit long to produce the 128-bit unsigned result.
*
* <p>This is a specialisation of {@link UnsignedMultiplyHighSource#unsignedMultiplyHigh(long, long)}
* for use in the 128-bit LCG sub-generator of the LXM family. It computes the equivalent of:
* <pre>
* unsignedMultiplyHigh(value, value);
* </pre>
*
* @param value the high bits of the value
* @return the high 64-bits of the 128-bit result
*/
static long unsignedSquareHigh(long value) {
final long a = value >>> 32;
final long b = value & INT_TO_UNSIGNED_BYTE_MASK;
final long by = b * b;
final long bx = b * a;
final long ax = a * a;
// Cannot overflow
final long carry = (by >>> 32) +
(bx & INT_TO_UNSIGNED_BYTE_MASK) +
bx;
return (bx >>> 32) + (carry >>> 32) + ax;
}
/**
* Square the value as if an unsigned 128-bit long to produce the 128-bit unsigned result.
*
* <p>This is a specialisation of {@link #unsignedMultiply128(long, long, long, long, long[])}
* for use in the 128-bit LCG sub-generator of the LXM family. It computes the equivalent of:
* <pre>
* long hi = unsignedMultiplyHigh(valueh, valuel, valueh, valuel) +
* 2 * valueh * valuel;
* long lo = valuel * valuel;
* </pre>
*
* @param valueh the high bits of the value
* @param valuel the low bits of the value
* @param low the low bits of the 128-bit result (output to array index [0])
* @return the high 64-bits of the 128-bit result
*/
static long unsignedSquare128(long valueh, long valuel, long[] low) {
// Multiply the two low halves to compute an initial 128-bit result
final long a = valuel >>> 32;
final long b = valuel & INT_TO_UNSIGNED_BYTE_MASK;
// x = a, y = b
final long by = b * b;
final long bx = b * a;
// ay = bx
final long ax = a * a;
// Cannot overflow
final long carry = (by >>> 32) +
(bx & INT_TO_UNSIGNED_BYTE_MASK) +
bx;
low[0] = (carry << 32) | (by & INT_TO_UNSIGNED_BYTE_MASK);
final long high = (bx >>> 32) + (carry >>> 32) + ax;
// Incorporate the remaining high bits that do not overflow 128-bits
return high + 2 * valueh * valuel;
}
}
/**
* Encapsulates a method to compute an update step on a 128-bit linear congruential
* generator (LCG). This benchmark source targets optimisation of the 128-bit LCG update
* step, in particular the branch to compute carry propagation from the low to high half.
*/
@State(Scope.Benchmark)
public static class LCG128Source {
/**
* The method to compute the value.
*
* <p>Notes:
* <ul>
* <li>Final LCG additive parameters make no significant difference.
* <li>Inlining the compareUnsigned operation is a marginal improvement.
* <li>Using the conditional load of the addition is of benefit when the add parameter
* is close to 2^63. When close to 0 or 2^64 then branch prediction is good and
* this path is fast.
* <li>Using the full branchless version creates code with a constant time cost which
* is fast. The branch code is faster when the branch is ~100% predictable, but can
* be much slower.
* <li>The branchless version assuming the add parameter is odd is constant time cost
* and fastest. The code is very small and putting it in a method will be inlined
* and allows code reuse.
* </ul>
*/
@Param({
REFERENCE,
//"referenceFinal",
//"compareUnsigned",
//"conditional",
//"conditionalFinal",
BRANCHLESS,
//"branchlessFull",
//"branchlessFullComposed",
})
private String method;
/**
* The low half of the additive parameter.
* This parameter determines how frequent the carry propagation
* must occur. The value is unsigned. When close to 0 then generation of a bit
* during carry propagation is unlikely; increasingly large additions will make
* a carry bit more likely. A value of -1 will (almost) always trigger a carry.
*/
@Param({
// Note: A small value is obtained from -1 + [0, range). Commented out
// to reduce benchmark run-time.
//"1",
// Uniformly spread in [0, 2^64)
// [1 .. 8] * 2^61 - 1
"2305843009213693951", "4611686018427387903", "6917529027641081855",
"9223372036854775807", "-6917529027641081857", "-4611686018427387905",
"-2305843009213693953", "-1",
})
private long add;
/**
* Range for a random addition to the additive parameter.
* <ul>
* <li>{@code range == 0}: no addition
* <li>{@code range == Long.MIN_VALUE}: random addition
* <li>{@code range > 0}: random in [0, range)
* <li>{@code range < 0}: random in [0, -range) + 2^63
* </ul>
*/
@Param({
// Zero is not useful for a realistic LCG which should have a random
// add parameter. It can be used to test a specific add value, e.g. 1L:
// java -jar target/examples-jmh.jar LXMBenchmark.lcg128 -p add=1 -p range=0
//"0",
// This is matched to the interval between successive 'add' parameters.
// 2^61
"2305843009213693952",
// This is useful only when the 'add' parameter is fixed, ideally to zero.
// Long.MIN_VALUE
//"-9223372036854775808",
})
private long range;
/** The generator of the next value. */
private LongSupplier gen;
/**
* Compute the next value.
*
* @return the value
*/
long next() {
return gen.getAsLong();
}
/**
* Create the generator of output values.
*/
@Setup(Level.Iteration)
public void setup() {
final long ah = ThreadLocalRandom.current().nextLong();
long al = add;
// Choose to randomise the add parameter
if (range == Long.MIN_VALUE) {
// random addition
al += ThreadLocalRandom.current().nextLong();
} else if (range > 0) {
// [0, range)
al += ThreadLocalRandom.current().nextLong(range);
} else if (range < 0) {
// [0, -range) + 2^63
al += ThreadLocalRandom.current().nextLong(-range) + Long.MIN_VALUE;
}
// else range == 0: no addition
if (REFERENCE.equals(method)) {
gen = new ReferenceLcg128(ah, al)::getAsLong;
} else if ("referenceFinal".equals(method)) {
gen = new ReferenceLcg128Final(ah, al)::getAsLong;
} else if ("compareUnsigned".equals(method)) {
gen = new CompareUnsignedLcg128(ah, al)::getAsLong;
} else if ("conditional".equals(method)) {
gen = new ConditionalLcg128(ah, al)::getAsLong;
} else if ("conditionalFinal".equals(method)) {
gen = new ConditionalLcg128Final(ah, al)::getAsLong;
} else if (BRANCHLESS.equals(method)) {
gen = new BranchlessLcg128(ah, al)::getAsLong;
} else if ("branchlessFull".equals(method)) {
gen = new BranchlessFullLcg128(ah, al)::getAsLong;
} else if ("branchlessFullComposed".equals(method)) {
gen = new BranchlessFullComposedLcg128(ah, al)::getAsLong;
} else {
throw new IllegalStateException("Unknown LCG method: " + method);
}
}
/**
* Base class for the 128-bit LCG. This holds the LCG state. It is initialised
* to 1 on construction. The value does not matter. The LCG additive parameter
* is what determines how frequent the carry propagation branch will be executed.
*/
abstract static class BaseLcg128 implements LongSupplier {
/** High half of the 128-bit state of the LCG. */
protected long lsh;
/** Low half of the 128-bit state of the LCG. */
protected long lsl = 1;
}
/**
* Implements the 128-bit LCG using the reference code in Steele & Vigna (2021).
*
* <p>Note: the additive parameter is not final. This is due to the requirement
* for the LXM generator to implement
* {@link org.apache.commons.rng.RestorableUniformRandomProvider}.
*/
static class ReferenceLcg128 extends BaseLcg128 {
/** High half of the 128-bit per-instance LCG additive parameter. */
private long lah;
/** Low half of the 128-bit per-instance LCG additive parameter (must be odd). */
private long lal;
/**
* @param ah High-half of add
* @param al Low-half of add
*/
ReferenceLcg128(long ah, long al) {
lah = ah;
lal = al | 1;
}
@Override
public long getAsLong() {
// LCG update
// The LCG is, in effect, "s = m * s + a" where m = ((1LL << 64) + ML)
final long sh = lsh;
final long sl = lsl;
final long u = ML * sl;
// High half
lsh = ML * sh + UnsignedMultiplyHighSource.unsignedMultiplyHigh(ML, sl) + sl + lah;
// Low half
lsl = u + lal;
// Carry propagation
if (Long.compareUnsigned(lsl, u) < 0) {
++lsh;
}
return sh;
}
}
/**
* Implements the 128-bit LCG using the reference code in Steele & Vigna (2021).
* This uses a final additive parameter allowing the JVM to optimise.
*/
static class ReferenceLcg128Final extends BaseLcg128 {
/** High half of the 128-bit per-instance LCG additive parameter. */
private final long lah;
/** Low half of the 128-bit per-instance LCG additive parameter (must be odd). */
private final long lal;
/**
* @param ah High-half of add
* @param al Low-half of add
*/
ReferenceLcg128Final(long ah, long al) {
lah = ah;
lal = al | 1;
}
@Override
public long getAsLong() {
final long sh = lsh;
final long sl = lsl;
final long u = ML * sl;
// High half
lsh = ML * sh + UnsignedMultiplyHighSource.unsignedMultiplyHigh(ML, sl) + sl + lah;
// Low half
lsl = u + lal;
// Carry propagation
if (Long.compareUnsigned(lsl, u) < 0) {
++lsh;
}
return sh;
}
}
/**
* Implements the 128-bit LCG using the reference code in Steele & Vigna (2021)
* but directly implements the {@link Long#compareUnsigned(long, long)}.
*
* <p>Note: the additive parameter is not final. This is due to the requirement
* for the LXM generator to implement
* {@link org.apache.commons.rng.RestorableUniformRandomProvider}.
*/
static class CompareUnsignedLcg128 extends BaseLcg128 {
/** High half of the 128-bit per-instance LCG additive parameter. */
private long lah;
/** Low half of the 128-bit per-instance LCG additive parameter (must be odd). */
private long lal;
/**
* @param ah High-half of add
* @param al Low-half of add
*/
CompareUnsignedLcg128(long ah, long al) {
lah = ah;
lal = al | 1;
}
@Override
public long getAsLong() {
final long sh = lsh;
final long sl = lsl;
final long u = ML * sl;
// High half
lsh = ML * sh + UnsignedMultiplyHighSource.unsignedMultiplyHigh(ML, sl) + sl + lah;
// Low half
lsl = u + lal;
// Carry propagation using an unsigned compare
if (lsl + Long.MIN_VALUE < u + Long.MIN_VALUE) {
++lsh;
}
return sh;
}
}
/**
* Implements the 128-bit LCG using a conditional load in place of a branch
* statement for the carry. Uses a non-final additive parameter.
*/
static class ConditionalLcg128 extends BaseLcg128 {
/** High half of the 128-bit per-instance LCG additive parameter. */
private long lah;
/** Low half of the 128-bit per-instance LCG additive parameter (must be odd). */
private long lal;
/**
* @param ah High-half of add
* @param al Low-half of add
*/
ConditionalLcg128(long ah, long al) {
lah = ah;
lal = al | 1;
}
@Override
public long getAsLong() {
long sh = lsh;
long sl = lsl;
final long z = sh;
final long u = ML * sl;
// High half
sh = ML * sh + UnsignedMultiplyHighSource.unsignedMultiplyHigh(ML, sl) + sl + lah;
// Low half
sl = u + lal;
// Carry propagation using a conditional add of 1 or 0
lsh = (sl + Long.MIN_VALUE < u + Long.MIN_VALUE ? 1 : 0) + sh;
lsl = sl;
return z;
}
}
/**
* Implements the 128-bit LCG using a conditional load in place of a branch
* statement for the carry. Uses a final additive parameter.
*/
static class ConditionalLcg128Final extends BaseLcg128 {
/** High half of the 128-bit per-instance LCG additive parameter. */
private final long lah;
/** Low half of the 128-bit per-instance LCG additive parameter (must be odd). */
private final long lal;
/**
* @param ah High-half of add
* @param al Low-half of add
*/
ConditionalLcg128Final(long ah, long al) {
lah = ah;
lal = al | 1;
}
@Override
public long getAsLong() {
long sh = lsh;
long sl = lsl;
final long z = sh;
final long u = ML * sl;
// High half
sh = ML * sh + UnsignedMultiplyHighSource.unsignedMultiplyHigh(ML, sl) + sl + lah;
// Low half
sl = u + lal;
// Carry propagation using a conditional add of 1 or 0
lsh = (sl + Long.MIN_VALUE < u + Long.MIN_VALUE ? 1 : 0) + sh;
lsl = sl;
return z;
}
}
/**
* Implements the 128-bit LCG using a branchless carry with a bit cascade.
* The low part is computed using simple addition {@code lsl = u + al} rather
* than composing the low part using bits from the carry computation.
* The carry propagation is put in a method. This tests code reusability for the
* carry part of the computation.
*/
static class BranchlessLcg128 extends BaseLcg128 {
/** High half of the 128-bit per-instance LCG additive parameter. */
private long lah;
/** Low half of the 128-bit per-instance LCG additive parameter (must be odd). */
private long lal;
/**
* @param ah High-half of add
* @param al Low-half of add
*/
BranchlessLcg128(long ah, long al) {
lah = ah;
lal = al | 1;
}
@Override
public long getAsLong() {
long sh = lsh;
final long sl = lsl;
final long z = sh;
final long u = ML * sl;
// High half
sh = ML * sh + UnsignedMultiplyHighSource.unsignedMultiplyHigh(ML, sl) + sl + lah;
// Low half.
final long al = lal;
lsl = u + al;
// Carry propagation using a branchless bit cascade
lsh = sh + unsignedAddHigh(u, al);
return z;
}
/**
* Add the two values as if unsigned 64-bit longs to produce the high 64-bits
* of the 128-bit unsigned result.
* <pre>
* left + right
* </pre>
* <p>This method is computing a carry bit.
*
* @param left the left argument
* @param right the right argument (assumed to have the lowest bit set to 1)
* @return the carry (either 0 or 1)
*/
static long unsignedAddHigh(long left, long right) {
// Method compiles to 13 bytes as Java byte code.
// This is below the default of 35 for code inlining.
return ((left >>> 1) + (right >>> 1) + (left & 1)) >>> -1;
}
}
/**
* Implements the 128-bit LCG using a branchless carry with a bit cascade.
* The low part is computed using simple addition {@code lsl = u + al} rather
* than composing the low part using bits from the carry computation.
* The carry propagation is put in a method. This tests code reusability for the
* carry part of the computation. This carry computation is a full
* unsignedAddHigh which does not assume the LCG addition is odd.
*/
static class BranchlessFullLcg128 extends BaseLcg128 {
/** High half of the 128-bit per-instance LCG additive parameter. */
private long lah;
/** Low half of the 128-bit per-instance LCG additive parameter (must be odd). */
private long lal;
/**
* @param ah High-half of add
* @param al Low-half of add
*/
BranchlessFullLcg128(long ah, long al) {
lah = ah;
lal = al | 1;
}
@Override
public long getAsLong() {
long sh = lsh;
final long sl = lsl;
final long z = sh;
final long u = ML * sl;
// High half
sh = ML * sh + UnsignedMultiplyHighSource.unsignedMultiplyHigh(ML, sl) + sl + lah;
// Low half.
final long al = lal;
lsl = u + al;
// Carry propagation using a branchless bit cascade
lsh = sh + unsignedAddHigh(u, al);
return z;
}
/**
* Add the two values as if unsigned 64-bit longs to produce the high 64-bits
* of the 128-bit unsigned result.
* <pre>
* left + right
* </pre>
* <p>This method is computing a carry bit.
*
* @param left the left argument
* @param right the right argument
* @return the carry (either 0 or 1)
*/
static long unsignedAddHigh(long left, long right) {
// Method compiles to 27 bytes as Java byte code.
// This is below the default of 35 for code inlining.
return ((left >>> 32) + (right >>> 32) +
(((left & 0xffff_ffffL) + (right & 0xffff_ffffL)) >>> 32)) >>> 32;
}
}
/**
* Implements the 128-bit LCG using a branchless carry with a bit cascade.
* The low part is composed from bits of the carry computation which requires
* the full computation. It cannot be put into a method as it requires more
* than 1 return variable.
*/
static class BranchlessFullComposedLcg128 extends BaseLcg128 {
/** High half of the 128-bit per-instance LCG additive parameter. */
private long lah;
/** Low half of the 128-bit per-instance LCG additive parameter (must be odd). */
private long lal;
/**
* @param ah High-half of add
* @param al Low-half of add
*/
BranchlessFullComposedLcg128(long ah, long al) {
lah = ah;
lal = al | 1;
}
@Override
public long getAsLong() {
long sh = lsh;
long sl = lsl;
final long z = sh;
final long u = ML * sl;
// High half
sh = ML * sh + UnsignedMultiplyHighSource.unsignedMultiplyHigh(ML, sl) + sl + lah;
// Low half.
// Carry propagation using a branchless bit cascade
final long leftLo = u & 0xffff_ffffL;
final long leftHi = u >>> 32;
final long rightLo = lal & 0xffff_ffffL;
final long rightHi = lal >>> 32;
final long lo = leftLo + rightLo;
final long hi = leftHi + rightHi + (lo >>> 32);
// sl = u + lal;
sl = (hi << 32) | lo & 0xffff_ffffL;
lsh = sh + (hi >>> 32);
lsl = sl;
return z;
}
}
}
/**
* Encapsulates a method to compute an update step on an LXM generator with a 128-bit
* Linear Congruential Generator.
*/
@State(Scope.Benchmark)
public static class LXM128Source {
/** Initial state1 of the XBG generator. */
static final long X0 = 0xdeadbeefdeadbeefL;
/** Initial state0 of the XBG generator. */
static final long X1 = lea64(0xdeadbeefdeadbeefL);
/** Initial state0 of the LCG generator. */
static final long S0 = 0;
/** Initial state1 of the LCG generator. */
static final long S1 = 1;
/**
* The method to compute the value.
*/
@Param({
REFERENCE,
// Use the best method from the LCG128Source
BRANCHLESS,
})
private String method;
/** The generator of the next value. */
private LongSupplier gen;
/**
* Compute the next value.
*
* @return the value
*/
long next() {
return gen.getAsLong();
}
/**
* Create the generator of output values.
*/
@Setup(Level.Iteration)
public void setup() {
final long ah = ThreadLocalRandom.current().nextLong();
final long al = ThreadLocalRandom.current().nextLong();
if (REFERENCE.equals(method)) {
gen = new ReferenceLxm128(ah, al)::getAsLong;
} else if (BRANCHLESS.equals(method)) {
gen = new BranchlessLxm128(ah, al)::getAsLong;
} else {
throw new IllegalStateException("Unknown L method: " + method);
}
}
/**
* Perform a 64-bit mixing function using Doug Lea's 64-bit mix constants and shifts.
*
* <p>This is based on the original 64-bit mix function of Austin Appleby's
* MurmurHash3 modified to use a single mix constant and 32-bit shifts, which may have
* a performance advantage on some processors. The code is provided in Steele and
* Vigna's paper.
*
* @param x the input value
* @return the output value
*/
static long lea64(long x) {
x = (x ^ (x >>> 32)) * 0xdaba0b6eb09322e3L;
x = (x ^ (x >>> 32)) * 0xdaba0b6eb09322e3L;
return x ^ (x >>> 32);
}
/**
* Base class for the LXM generator. This holds the 128-bit LCG state.
*
* <p>The XBG sub-generator is assumed to be XoRoShiRo128 with 128-bits of state.
* This is fast so the speed effect of changing the LCG implementation can be measured.
*
* <p>The initial state of the two generators should ne matter so they use constants.
* The LCG additive parameter is what determines how frequent the carry propagation
* branch will be executed.
*
* <p>Note: the additive parameter is not final. This is due to the requirement
* for the LXM generator to implement
* {@link org.apache.commons.rng.RestorableUniformRandomProvider}.
*/
abstract static class BaseLxm128 implements LongSupplier {
/** State0 of XBG. */
protected long state0 = X0;
/** State1 of XBG. */
protected long state1 = X1;
/** High half of the 128-bit state of the LCG. */
protected long lsh = S0;
/** Low half of the 128-bit state of the LCG. */
protected long lsl = S1;
/** High half of the 128-bit per-instance LCG additive parameter. */
protected long lah;
/** Low half of the 128-bit per-instance LCG additive parameter (must be odd). */
protected long lal;
/**
* @param ah High-half of add
* @param al Low-half of add
*/
BaseLxm128(long ah, long al) {
lah = ah;
lal = al | 1;
}
}
/**
* Implements the L128X128Mix using the reference code for the LCG in Steele & Vigna (2021).
*/
static class ReferenceLxm128 extends BaseLxm128 {
/**
* @param ah High-half of add
* @param al Low-half of add
*/
ReferenceLxm128(long ah, long al) {
super(ah, al);
}
@Override
public long getAsLong() {
// LXM generate.
// Old state is used for the output allowing parallel pipelining
// on processors that support multiple concurrent instructions.
final long s0 = state0;
final long sh = lsh;
// Mix
final long z = lea64(sh + s0);
// LCG update
// The LCG is, in effect, "s = m * s + a" where m = ((1LL << 64) + ML)
final long sl = lsl;
final long u = ML * sl;
// High half
lsh = ML * sh + UnsignedMultiplyHighSource.unsignedMultiplyHigh(ML, sl) + sl + lah;
// Low half
lsl = u + lal;
// Carry propagation
if (Long.compareUnsigned(lsl, u) < 0) {
++lsh;
}
// XBG update
long s1 = state1;
s1 ^= s0;
state0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b
state1 = Long.rotateLeft(s1, 37); // c
return z;
}
}
/**
* Implements the L128X128Mix using a branchless carry with a bit cascade.
* The low part is computed using simple addition {@code lsl = u + al} rather
* than composing the low part using bits from the carry computation.
*/
static class BranchlessLxm128 extends BaseLxm128 {
/**
* @param ah High-half of add
* @param al Low-half of add
*/
BranchlessLxm128(long ah, long al) {
super(ah, al);
}
@Override
public long getAsLong() {
final long s0 = state0;
long sh = lsh;
// Mix
final long z = lea64(sh + s0);
// LCG update
// The LCG is, in effect, "s = m * s + a" where m = ((1LL << 64) + ML)
final long sl = lsl;
final long u = ML * sl;
// High half
sh = ML * sh + UnsignedMultiplyHighSource.unsignedMultiplyHigh(ML, sl) + sl + lah;
// Low half
final long al = lal;
lsl = u + al;
// Carry propagation using a branchless bit cascade.
// This can be used in a method that will be inlined.
lsh = sh + LCG128Source.BranchlessLcg128.unsignedAddHigh(u, al);
// XBG update
long s1 = state1;
s1 ^= s0;
state0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b
state1 = Long.rotateLeft(s1, 37); // c
return z;
}
}
}
/**
* Benchmark an unsigned multiply.
*
* @param data the data
* @return the value
*/
@Benchmark
public long unsignedMultiply(UnsignedMultiplyHighSource data) {
return data.next();
}
/**
* Benchmark a 128-bit unsigned multiply.
*
* @param data the data
* @return the value
*/
@Benchmark
public long unsignedMultiply128(UnsignedMultiply128Source data) {
return data.next();
}
/**
* Benchmark a 128-bit linear congruential generator.
*
* @param data the data
* @return the value
*/
@Benchmark
public long lcg128(LCG128Source data) {
return data.next();
}
/**
* Benchmark a LXM generator with a 128-bit linear congruential generator.
*
* @param data the data
* @return the value
*/
@Benchmark
public long lxm128(LXM128Source data) {
return data.next();
}
}
| 2,766 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/BaselineSources.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
/**
* A benchmark state that can retrieve the various generators defined by {@link RandomSource}
* values.
*
* <p>The state will include only those that do not require additional constructor arguments.</p>
*
* <p>This class is abstract since it adds a special {@code RandomSource} named
* {@code BASELINE}. A baseline implementation for the {@link UniformRandomProvider}
* interface must be provided by implementing classes. For example to baseline methods
* using {@link UniformRandomProvider#nextInt()} use the following code:</p>
*
* <pre>
* @State(Scope.Benchmark)
* public static class Sources extends BaselineSources {
* @Override
* protected UniformRandomProvider createBaseline() {
* return BaselineUtils.getNextInt();
* }
* }
* </pre>
*
* <p>Note: It is left to the implementation to ensure the baseline is suitable for the method
* being tested.</p>
*/
@State(Scope.Benchmark)
public abstract class BaselineSources {
/** The keyword identifying the baseline implementation. */
private static final String BASELINE = "BASELINE";
/**
* RNG providers.
*
* <p>List all providers that do not require additional constructor arguments. This list
* is in the declared order of {@link RandomSource}.</p>
*/
@Param({BASELINE,
"JDK",
"WELL_512_A",
"WELL_1024_A",
"WELL_19937_A",
"WELL_19937_C",
"WELL_44497_A",
"WELL_44497_B",
"MT",
"ISAAC",
"SPLIT_MIX_64",
"XOR_SHIFT_1024_S",
"TWO_CMRES",
"MT_64",
"MWC_256",
"KISS",
"XOR_SHIFT_1024_S_PHI",
"XO_RO_SHI_RO_64_S",
"XO_RO_SHI_RO_64_SS",
"XO_SHI_RO_128_PLUS",
"XO_SHI_RO_128_SS",
"XO_RO_SHI_RO_128_PLUS",
"XO_RO_SHI_RO_128_SS",
"XO_SHI_RO_256_PLUS",
"XO_SHI_RO_256_SS",
"XO_SHI_RO_512_PLUS",
"XO_SHI_RO_512_SS",
"PCG_XSH_RR_32",
"PCG_XSH_RS_32",
"PCG_RXS_M_XS_64",
"PCG_MCG_XSH_RR_32",
"PCG_MCG_XSH_RS_32",
"MSWS",
"SFC_32",
"SFC_64",
"JSF_32",
"JSF_64",
"XO_SHI_RO_128_PP",
"XO_RO_SHI_RO_128_PP",
"XO_SHI_RO_256_PP",
"XO_SHI_RO_512_PP",
"XO_RO_SHI_RO_1024_PP",
"XO_RO_SHI_RO_1024_S",
"XO_RO_SHI_RO_1024_SS",
"PCG_XSH_RR_32_OS",
"PCG_XSH_RS_32_OS",
"PCG_RXS_M_XS_64_OS",
"L64_X128_SS",
"L64_X128_MIX",
"L64_X256_MIX",
"L64_X1024_MIX",
"L128_X128_MIX",
"L128_X256_MIX",
"L128_X1024_MIX",
"L32_X64_MIX"})
private String randomSourceName;
/** RNG. */
private UniformRandomProvider provider;
/**
* Gets the generator.
*
* @return the RNG.
*/
public UniformRandomProvider getGenerator() {
return provider;
}
/** Instantiates generator. This need only be done once per set of iterations. */
@Setup(Level.Trial)
public void setup() {
if (BASELINE.equals(randomSourceName)) {
provider = createBaseline();
} else {
final RandomSource randomSource = RandomSource.valueOf(randomSourceName);
provider = randomSource.create();
}
}
/**
* Creates the baseline {@link UniformRandomProvider}.
*
* <p>This should implement the method(s) that will be tested. The speed of this RNG is expected
* to create a baseline against which all other generators will be compared.</p>
*
* @return the baseline RNG.
*/
protected abstract UniformRandomProvider createBaseline();
}
| 2,767 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/BaselineUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import org.apache.commons.rng.UniformRandomProvider;
/**
* Defines baseline implementations for the {@link UniformRandomProvider}.
*/
public final class BaselineUtils {
/** No public construction. */
private BaselineUtils() {}
/**
* Default implementation of {@link UniformRandomProvider} that does nothing.
*
* <p>Note: This is not a good baseline as the JVM can optimise the predictable result
* of the method calls. This is here for convenience when implementing
* UniformRandomProvider.</p>
*/
private abstract static class DefaultProvider implements UniformRandomProvider {
@Override
public void nextBytes(byte[] bytes) {
// Do nothing
}
@Override
public void nextBytes(byte[] bytes, int start, int len) {
// Do nothing
}
@Override
public int nextInt() {
return 0;
}
@Override
public int nextInt(int n) {
return 0;
}
@Override
public long nextLong() {
return 0;
}
@Override
public long nextLong(long n) {
return 0;
}
@Override
public boolean nextBoolean() {
return false;
}
@Override
public float nextFloat() {
return 0;
}
@Override
public double nextDouble() {
return 0;
}
}
/**
* Baseline implementation for {@link UniformRandomProvider#nextBytes(byte[])} and
* {@link UniformRandomProvider#nextBytes(byte[], int, int)}.
*/
private static final class BaselineNextBytes extends DefaultProvider {
/**
* The fixed value to fill the byte array.
*
* <p><strong>DON'T</strong> make this final!
* This must be a viewed by the JVM as something that cannot be optimised away.</p>
*/
private byte value;
@Override
public void nextBytes(byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
bytes[i] = value;
}
}
@Override
public void nextBytes(byte[] bytes, int start, int len) {
for (int i = start; i < len; i++) {
bytes[i] = value;
}
}
}
/**
* Baseline implementation for {@link UniformRandomProvider#nextInt()} and
* {@link UniformRandomProvider#nextInt(int)}.
*/
private static final class BaselineNextInt extends DefaultProvider {
/**
* The fixed value to return.
*
* <p><strong>DON'T</strong> make this final!
* This must be a viewed by the JVM as something that cannot be optimised away.</p>
*/
private int value;
@Override
public int nextInt() {
return value;
}
@Override
public int nextInt(int n) {
return value;
}
}
/**
* Baseline implementation for {@link UniformRandomProvider#nextLong()} and
* {@link UniformRandomProvider#nextLong(long)}.
*/
private static final class BaselineNextLong extends DefaultProvider {
/**
* The fixed value to return.
*
* <p><strong>DON'T</strong> make this final!
* This must be a viewed by the JVM as something that cannot be optimised away.</p>
*/
private long value;
@Override
public long nextLong() {
return value;
}
@Override
public long nextLong(long n) {
return value;
}
}
/**
* Baseline implementation for {@link UniformRandomProvider#nextBoolean()}.
*/
private static final class BaselineNextBoolean extends DefaultProvider {
/**
* The fixed value to return.
*
* <p><strong>DON'T</strong> make this final!
* This must be a viewed by the JVM as something that cannot be optimised away.</p>
*/
private boolean value;
@Override
public boolean nextBoolean() {
return value;
}
}
/**
* Baseline implementation for {@link UniformRandomProvider#nextFloat()}.
*/
private static final class BaselineNextFloat extends DefaultProvider {
/**
* The fixed value to return.
*
* <p><strong>DON'T</strong> make this final!
* This must be a viewed by the JVM as something that cannot be optimised away.</p>
*/
private float value;
@Override
public float nextFloat() {
return value;
}
}
/**
* Baseline implementation for {@link UniformRandomProvider#nextDouble()}.
*/
private static final class BaselineNextDouble extends DefaultProvider {
/**
* The fixed value to return.
*
* <p><strong>DON'T</strong> make this final!
* This must be a viewed by the JVM as something that cannot be optimised away.</p>
*/
private double value;
@Override
public double nextDouble() {
return value;
}
}
/**
* Gets a baseline provider for {@link UniformRandomProvider#nextBytes(byte[])} and
* {@link UniformRandomProvider#nextBytes(byte[], int, int)}.
*
* @return The baseline provider.
*/
public static UniformRandomProvider getNextBytes() {
return new BaselineNextBytes();
}
/**
* Gets a baseline provider for {@link UniformRandomProvider#nextInt()} and
* {@link UniformRandomProvider#nextInt(int)}.
*
* @return The baseline provider.
*/
public static UniformRandomProvider getNextInt() {
return new BaselineNextInt();
}
/**
* Gets a baseline provider for {@link UniformRandomProvider#nextLong()} and
* {@link UniformRandomProvider#nextLong(long)}.
*
* @return The baseline provider.
*/
public static UniformRandomProvider getNextLong() {
return new BaselineNextLong();
}
/**
* Gets a baseline provider for {@link UniformRandomProvider#nextBoolean()}.
*
* @return The baseline provider.
*/
public static UniformRandomProvider getNextBoolean() {
return new BaselineNextBoolean();
}
/**
* Gets a baseline provider for {@link UniformRandomProvider#nextFloat()}.
*
* @return The baseline provider.
*/
public static UniformRandomProvider getNextFloat() {
return new BaselineNextFloat();
}
/**
* Gets a baseline provider for {@link UniformRandomProvider#nextDouble()}.
*
* @return The baseline provider.
*/
public static UniformRandomProvider getNextDouble() {
return new BaselineNextDouble();
}
}
| 2,768 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/NextLongGenerationPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import org.apache.commons.rng.UniformRandomProvider;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
/**
* Executes benchmark to compare the speed of generation of random numbers from the
* various source providers for {@link UniformRandomProvider#nextLong()} and
* {@link UniformRandomProvider#nextLong(long)}.
*/
public class NextLongGenerationPerformance extends AbstractBenchmark {
/** The value. Must NOT be final to prevent JVM optimisation! */
private long value;
/**
* The benchmark state (retrieve the various "RandomSource"s).
*/
@State(Scope.Benchmark)
public static class Sources extends BaselineSources {
/** {@inheritDoc} */
@Override
protected UniformRandomProvider createBaseline() {
return BaselineUtils.getNextLong();
}
}
/**
* Baseline for a JMH method call with no return value.
*/
@Benchmark
public void baselineVoid() {
// Do nothing, this is a baseline
}
/**
* Baseline for a JMH method call returning a {@code long}.
*
* @return the value
*/
@Benchmark
public long baselineLong() {
return value;
}
/**
* Exercise the {@link UniformRandomProvider#nextLong()} method.
*
* @param sources Source of randomness.
* @return the long
*/
@Benchmark
public long nextLong(Sources sources) {
return sources.getGenerator().nextLong();
}
/**
* Exercise the {@link UniformRandomProvider#nextLong(long)} method.
*
* @param sources Source of randomness.
* @return the long
*/
@Benchmark
public long nextLongN(Sources sources) {
return sources.getGenerator().nextLong(BaselineGenerationPerformance.NEXT_LONG_LIMIT);
}
}
| 2,769 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/NextBooleanGenerationPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.core;
import org.apache.commons.rng.UniformRandomProvider;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
/**
* Executes benchmark to compare the speed of generation of random numbers from the
* various source providers for {@link UniformRandomProvider#nextBoolean()}.
*/
public class NextBooleanGenerationPerformance extends AbstractBenchmark {
/** The value. Must NOT be final to prevent JVM optimisation! */
private boolean value;
/**
* The benchmark state (retrieve the various "RandomSource"s).
*/
@State(Scope.Benchmark)
public static class Sources extends BaselineSources {
/** {@inheritDoc} */
@Override
protected UniformRandomProvider createBaseline() {
return BaselineUtils.getNextBoolean();
}
}
/**
* Baseline for a JMH method call with no return value.
*/
@Benchmark
public void baselineVoid() {
// Do nothing, this is a baseline
}
/**
* Baseline for a JMH method call returning a {@code boolean}.
*
* @return the value
*/
@Benchmark
public boolean baselineBoolean() {
return value;
}
/**
* Exercise the {@link UniformRandomProvider#nextBoolean()} method.
*
* @param sources Source of randomness.
* @return the boolean
*/
@Benchmark
public boolean nextBoolean(Sources sources) {
return sources.getGenerator().nextBoolean();
}
}
| 2,770 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/core/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Benchmarks for the {@code org.apache.commons.rng.core} components.
*/
package org.apache.commons.rng.examples.jmh.core;
| 2,771 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/UnitSphereSamplerBenchmark.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.ObjectSampler;
import org.apache.commons.rng.sampling.distribution.NormalizedGaussianSampler;
import org.apache.commons.rng.sampling.distribution.ZigguratSampler;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import java.util.concurrent.TimeUnit;
/**
* Executes benchmark to compare the speed of generating samples on the surface of an
* N-dimension unit sphere.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = { "-server", "-Xms128M", "-Xmx128M" })
public class UnitSphereSamplerBenchmark {
/** Name for the baseline method. */
private static final String BASELINE = "Baseline";
/** Name for the non-array based method. */
private static final String NON_ARRAY = "NonArray";
/** Name for the array based method. */
private static final String ARRAY = "Array";
/** Error message for an unknown sampler type. */
private static final String UNKNOWN_SAMPLER = "Unknown sampler type: ";
/**
* Base class for the sampler data.
* Contains the source of randomness and the number of samples.
* The sampler should be created by a sub-class of the data.
*/
@State(Scope.Benchmark)
public abstract static class SamplerData {
/** The sampler. */
private ObjectSampler<double[]> sampler;
/** The number of samples. */
@Param({"100"})
private int size;
/**
* Gets the size.
*
* @return the size
*/
public int getSize() {
return size;
}
/**
* Gets the sampler.
*
* @return the sampler
*/
public ObjectSampler<double[]> getSampler() {
return sampler;
}
/**
* Create the source of randomness.
*/
@Setup
public void setup() {
// This could be configured using @Param
final UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create();
sampler = createSampler(rng);
}
/**
* Creates the sampler.
*
* @param rng the source of randomness
* @return the sampler
*/
protected abstract ObjectSampler<double[]> createSampler(UniformRandomProvider rng);
}
/**
* The 1D unit line sampler.
*/
@State(Scope.Benchmark)
public static class Sampler1D extends SamplerData {
/** Name for the signed double method. */
private static final String SIGNED_DOUBLE = "signedDouble";
/** Name for the masked int method. */
private static final String MASKED_INT = "maskedInt";
/** Name for the masked long method. */
private static final String MASKED_LONG = "maskedLong";
/** Name for the boolean method. */
private static final String BOOLEAN = "boolean";
/** The value 1.0 in raw long bits. */
private static final long ONE = Double.doubleToRawLongBits(1.0);
/** Mask to extract the sign bit from an integer (as a long). */
private static final long SIGN_BIT = 1L << 31;
/** The sampler type. */
@Param({BASELINE, SIGNED_DOUBLE, MASKED_INT, MASKED_LONG, BOOLEAN, ARRAY})
private String type;
/** {@inheritDoc} */
@Override
protected ObjectSampler<double[]> createSampler(final UniformRandomProvider rng) {
if (BASELINE.equals(type)) {
return () -> {
return new double[] {1.0};
};
} else if (SIGNED_DOUBLE.equals(type)) {
return () -> {
// (1 - 0) or (1 - 2)
// Use the sign bit
return new double[] {1.0 - ((rng.nextInt() >>> 30) & 0x2)};
};
} else if (MASKED_INT.equals(type)) {
return () -> {
// Shift the sign bit and combine with the bits for a double of 1.0
return new double[] {Double.longBitsToDouble(ONE | ((rng.nextInt() & SIGN_BIT) << 32))};
};
} else if (MASKED_LONG.equals(type)) {
return () -> {
// Combine the sign bit with the bits for a double of 1.0
return new double[] {Double.longBitsToDouble(ONE | (rng.nextLong() & Long.MIN_VALUE))};
};
} else if (BOOLEAN.equals(type)) {
return () -> {
return new double[] {rng.nextBoolean() ? -1.0 : 1.0};
};
} else if (ARRAY.equals(type)) {
return new ArrayBasedUnitSphereSampler(1, rng);
}
throw new IllegalStateException(UNKNOWN_SAMPLER + type);
}
}
/**
* The 2D unit circle sampler.
*/
@State(Scope.Benchmark)
public static class Sampler2D extends SamplerData {
/** The sampler type. */
@Param({BASELINE, ARRAY, NON_ARRAY})
private String type;
/** {@inheritDoc} */
@Override
protected ObjectSampler<double[]> createSampler(final UniformRandomProvider rng) {
if (BASELINE.equals(type)) {
return () -> new double[] {1.0, 0.0};
} else if (ARRAY.equals(type)) {
return new ArrayBasedUnitSphereSampler(2, rng);
} else if (NON_ARRAY.equals(type)) {
return new UnitSphereSampler2D(rng);
}
throw new IllegalStateException(UNKNOWN_SAMPLER + type);
}
/**
* Sample from a 2D unit sphere.
*/
private static class UnitSphereSampler2D implements ObjectSampler<double[]> {
/** Sampler used for generating the individual components of the vectors. */
private final NormalizedGaussianSampler sampler;
/**
* @param rng the source of randomness
*/
UnitSphereSampler2D(UniformRandomProvider rng) {
sampler = ZigguratSampler.NormalizedGaussian.of(rng);
}
@Override
public double[] sample() {
final double x = sampler.sample();
final double y = sampler.sample();
final double sum = x * x + y * y;
if (sum == 0) {
// Zero-norm vector is discarded.
return sample();
}
final double f = 1.0 / Math.sqrt(sum);
return new double[] {x * f, y * f};
}
}
}
/**
* The 3D unit sphere sampler.
*/
@State(Scope.Benchmark)
public static class Sampler3D extends SamplerData {
/** The sampler type. */
@Param({BASELINE, ARRAY, NON_ARRAY})
private String type;
/** {@inheritDoc} */
@Override
protected ObjectSampler<double[]> createSampler(final UniformRandomProvider rng) {
if (BASELINE.equals(type)) {
return () -> new double[] {1.0, 0.0, 0.0};
} else if (ARRAY.equals(type)) {
return new ArrayBasedUnitSphereSampler(3, rng);
} else if (NON_ARRAY.equals(type)) {
return new UnitSphereSampler3D(rng);
}
throw new IllegalStateException(UNKNOWN_SAMPLER + type);
}
/**
* Sample from a 3D unit sphere.
*/
private static class UnitSphereSampler3D implements ObjectSampler<double[]> {
/** Sampler used for generating the individual components of the vectors. */
private final NormalizedGaussianSampler sampler;
/**
* @param rng the source of randomness
*/
UnitSphereSampler3D(UniformRandomProvider rng) {
sampler = ZigguratSampler.NormalizedGaussian.of(rng);
}
@Override
public double[] sample() {
final double x = sampler.sample();
final double y = sampler.sample();
final double z = sampler.sample();
final double sum = x * x + y * y + z * z;
if (sum == 0) {
// Zero-norm vector is discarded.
return sample();
}
final double f = 1.0 / Math.sqrt(sum);
return new double[] {x * f, y * f, z * f};
}
}
}
/**
* The 4D unit hypersphere sampler.
*/
@State(Scope.Benchmark)
public static class Sampler4D extends SamplerData {
/** The sampler type. */
@Param({BASELINE, ARRAY, NON_ARRAY})
private String type;
/** {@inheritDoc} */
@Override
protected ObjectSampler<double[]> createSampler(final UniformRandomProvider rng) {
if (BASELINE.equals(type)) {
return () -> new double[] {1.0, 0.0, 0.0, 0.0};
} else if (ARRAY.equals(type)) {
return new ArrayBasedUnitSphereSampler(4, rng);
} else if (NON_ARRAY.equals(type)) {
return new UnitSphereSampler4D(rng);
}
throw new IllegalStateException(UNKNOWN_SAMPLER + type);
}
/**
* Sample from a 4D unit hypersphere.
*/
private static class UnitSphereSampler4D implements ObjectSampler<double[]> {
/** Sampler used for generating the individual components of the vectors. */
private final NormalizedGaussianSampler sampler;
/**
* @param rng the source of randomness
*/
UnitSphereSampler4D(UniformRandomProvider rng) {
sampler = ZigguratSampler.NormalizedGaussian.of(rng);
}
@Override
public double[] sample() {
final double x = sampler.sample();
final double y = sampler.sample();
final double z = sampler.sample();
final double a = sampler.sample();
final double sum = x * x + y * y + z * z + a * a;
if (sum == 0) {
// Zero-norm vector is discarded.
return sample();
}
final double f = 1.0 / Math.sqrt(sum);
return new double[] {x * f, y * f, z * f, a * f};
}
}
}
/**
* Sample from a unit sphere using an array based method.
*/
private static class ArrayBasedUnitSphereSampler implements ObjectSampler<double[]> {
/** Space dimension. */
private final int dimension;
/** Sampler used for generating the individual components of the vectors. */
private final NormalizedGaussianSampler sampler;
/**
* @param dimension space dimension
* @param rng the source of randomness
*/
ArrayBasedUnitSphereSampler(int dimension, UniformRandomProvider rng) {
this.dimension = dimension;
sampler = ZigguratSampler.NormalizedGaussian.of(rng);
}
@Override
public double[] sample() {
final double[] v = new double[dimension];
// Pick a point by choosing a standard Gaussian for each element,
// and then normalize to unit length.
double sum = 0;
for (int i = 0; i < dimension; i++) {
final double x = sampler.sample();
v[i] = x;
sum += x * x;
}
if (sum == 0) {
// Zero-norm vector is discarded.
return sample();
}
final double f = 1 / Math.sqrt(sum);
for (int i = 0; i < dimension; i++) {
v[i] *= f;
}
return v;
}
}
/**
* Run the sampler for the configured number of samples.
*
* @param bh Data sink
* @param data Input data.
*/
private static void runSampler(Blackhole bh, SamplerData data) {
final ObjectSampler<double[]> sampler = data.getSampler();
for (int i = data.getSize() - 1; i >= 0; i--) {
bh.consume(sampler.sample());
}
}
/**
* Generation of uniform samples on a 1D unit line.
*
* @param bh Data sink
* @param data Input data.
*/
@Benchmark
public void create1D(Blackhole bh, Sampler1D data) {
runSampler(bh, data);
}
/**
* Generation of uniform samples from a 2D unit circle.
*
* @param bh Data sink
* @param data Input data.
*/
@Benchmark
public void create2D(Blackhole bh, Sampler2D data) {
runSampler(bh, data);
}
/**
* Generation of uniform samples from a 3D unit sphere.
*
* @param bh Data sink
* @param data Input data.
*/
@Benchmark
public void create3D(Blackhole bh, Sampler3D data) {
runSampler(bh, data);
}
/**
* Generation of uniform samples from a 4D unit sphere.
*
* @param bh Data sink
* @param data Input data.
*/
@Benchmark
public void create4D(Blackhole bh, Sampler4D data) {
runSampler(bh, data);
}
}
| 2,772 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/ListShuffleBenchmark.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.source32.IntProvider;
import org.apache.commons.rng.sampling.ListSampler;
import org.apache.commons.rng.sampling.PermutationSampler;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
import java.util.RandomAccess;
import java.util.concurrent.TimeUnit;
/**
* Executes benchmark to compare the speed of shuffling a {@link List}.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = { "-server", "-Xms128M", "-Xmx128M" })
public class ListShuffleBenchmark {
/** 2^32. Used for the nextInt(int) algorithm. */
private static final long POW_32 = 1L << 32;
/**
* The size threshold for using the random access algorithm
* when the list does not implement RandomAccess.
*/
private static final int RANDOM_ACCESS_SIZE_THRESHOLD = 5;
/**
* The data for the shuffle. Contains the data size and the random generators.
*/
@State(Scope.Benchmark)
public static class ShuffleData {
/**
* The list size.
*/
@Param({"10", "100", "1000", "10000"})
private int size;
/** The UniformRandomProvider instance. */
private UniformRandomProvider rng;
/** The Random instance. */
private Random random;
/**
* Gets the size.
*
* @return the size
*/
public int getSize() {
return size;
}
/**
* Gets the uniform random provider.
*
* @return the uniform random provider
*/
public UniformRandomProvider getRNG() {
return rng;
}
/**
* Gets the random.
*
* @return the random
*/
public Random getRandom() {
return random;
}
/**
* Create the random generators.
*/
@Setup
public void setupGenerators() {
final long seed = System.currentTimeMillis();
rng = new SplitMix32RNG(seed);
random = new SplitMix32Random(seed);
}
}
/**
* The list to shuffle. Either an ArrayList or a LinkedList.
*/
@State(Scope.Benchmark)
public static class ListData extends ShuffleData {
/**
* The list type.
*/
@Param({"Array", "Linked"})
private String type;
/** The list. */
private List<Integer> list;
/**
* Gets the list.
*
* @return the list
*/
public List<Integer> getList() {
return list;
}
/**
* Create the list.
*/
@Setup
public void setupList() {
if ("Array".equals(type)) {
list = new ArrayList<>();
} else if ("Linked".equals(type)) {
list = new LinkedList<>();
}
for (int i = 0; i < getSize(); i++) {
list.add(i);
}
}
}
/**
* The LinkedList to shuffle.
*
* <p>This is used to determine the threshold to switch from the direct shuffle of a list
* without RandomAccess to the iterator based version.</p>
*/
@State(Scope.Benchmark)
public static class LinkedListData {
/**
* The list size. The java.utils.Collections.shuffle method switches at size 5.
*/
@Param({"3", "4", "5", "6", "7", "8"})
private int size;
/** The UniformRandomProvider instance. */
private UniformRandomProvider rng;
/** The list. */
private List<Integer> list;
/**
* Gets the uniform random provider.
*
* @return the uniform random provider
*/
public UniformRandomProvider getRNG() {
return rng;
}
/**
* Gets the list.
*
* @return the list
*/
public List<Integer> getList() {
return list;
}
/**
* Create the list.
*/
@Setup
public void setup() {
rng = new SplitMix32RNG(System.currentTimeMillis());
list = new LinkedList<>();
for (int i = 0; i < size; i++) {
list.add(i);
}
}
}
/**
* Implement the SplitMix algorithm from {@link java.util.SplittableRandom
* SplittableRandom} to output 32-bit int values. Expose this through the
* {@link UniformRandomProvider} API.
*/
static final class SplitMix32RNG extends IntProvider {
/** The state. */
private long state;
/**
* Create a new instance.
*
* @param seed the seed
*/
SplitMix32RNG(long seed) {
state = seed;
}
@Override
public int next() {
long key = state += 0x9e3779b97f4a7c15L;
// 32 high bits of Stafford variant 4 mix64 function as int:
// http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
key = (key ^ (key >>> 33)) * 0x62a9d9ed799705f5L;
return (int) (((key ^ (key >>> 28)) * 0xcb24d0a5c88c35b3L) >>> 32);
}
@Override
public int nextInt(int n) {
// No check for positive n.
// Implement the Lemire method to create an integer in a range.
long m = (next() & 0xffffffffL) * n;
long l = m & 0xffffffffL;
if (l < n) {
// 2^32 % n
final long t = POW_32 % n;
while (l < t) {
m = (next() & 0xffffffffL) * n;
l = m & 0xffffffffL;
}
}
return (int) (m >>> 32);
}
}
/**
* Implement the SplitMix algorithm from {@link java.util.SplittableRandom
* SplittableRandom} to output 32-bit int values. Expose this through the
* {@link java.util.Random} API.
*/
static final class SplitMix32Random extends Random {
private static final long serialVersionUID = 1L;
/** The state. */
private long state;
/**
* Create a new instance.
*
* @param seed the seed
*/
SplitMix32Random(long seed) {
state = seed;
}
/**
* Return the next value.
*
* @return the value
*/
private int next() {
long key = state += 0x9e3779b97f4a7c15L;
// 32 high bits of Stafford variant 4 mix64 function as int:
// http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
key = (key ^ (key >>> 33)) * 0x62a9d9ed799705f5L;
return (int) (((key ^ (key >>> 28)) * 0xcb24d0a5c88c35b3L) >>> 32);
}
@Override
public int nextInt(int n) {
// No check for positive n.
// Implement the Lemire method to create an integer in a range.
long m = (next() & 0xffffffffL) * n;
long l = m & 0xffffffffL;
if (l < n) {
// 2^32 % n
final long t = POW_32 % n;
while (l < t) {
m = (next() & 0xffffffffL) * n;
l = m & 0xffffffffL;
}
}
return (int) (m >>> 32);
}
@Override
protected int next(int n) {
// For the Random implementation. This is unused.
return next() >>> (32 - n);
}
}
/**
* ListSampler shuffle from version 1.2 delegates to the PermutationSampler.
*
* @param <T> Type of the list items.
* @param rng Random number generator.
* @param list List.
* @param start Index at which shuffling begins.
* @param towardHead Shuffling is performed to the beginning or end of the list.
*/
private static <T> void shuffleUsingPermutationSampler(UniformRandomProvider rng, List<T> list,
int start, boolean towardHead) {
final int len = list.size();
final int[] indices = PermutationSampler.natural(len);
PermutationSampler.shuffle(rng, indices, start, towardHead);
final ArrayList<T> items = new ArrayList<>(list);
for (int i = 0; i < len; i++) {
list.set(i, items.get(indices[i]));
}
}
/**
* ListSampler shuffle from version 1.2 delegates to the PermutationSampler.
* Modified for RandomAccess lists.
*
* @param <T> Type of the list items.
* @param rng Random number generator.
* @param list List.
* @param start Index at which shuffling begins.
* @param towardHead Shuffling is performed to the beginning or end of the list.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
private static <T> void shuffleUsingPermutationSamplerRandomAccess(UniformRandomProvider rng, List<T> list,
int start, boolean towardHead) {
final int len = list.size();
final int[] indices = PermutationSampler.natural(len);
PermutationSampler.shuffle(rng, indices, start, towardHead);
// Copy back.
final ArrayList<T> items = new ArrayList<>(list);
final int low = towardHead ? 0 : start;
final int high = towardHead ? start + 1 : len;
if (list instanceof RandomAccess) {
for (int i = low; i < high; i++) {
list.set(i, items.get(indices[i]));
}
} else {
// Copy back. Use raw types.
final ListIterator it = list.listIterator(low);
for (int i = low; i < high; i++) {
it.next();
it.set(items.get(indices[i]));
}
}
}
/**
* Direct shuffle on the list adapted from JDK java.util.Collections.
* This handles RandomAccess lists.
*
* @param rng Random number generator.
* @param list List.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
private static void shuffleDirectRandomAccess(UniformRandomProvider rng, List<?> list) {
if (list instanceof RandomAccess || list.size() < RANDOM_ACCESS_SIZE_THRESHOLD) {
// Shuffle list in-place
for (int i = list.size(); i > 1; i--) {
swap(list, i - 1, rng.nextInt(i));
}
} else {
// Shuffle as an array
final Object[] array = list.toArray();
for (int i = array.length; i > 1; i--) {
swap(array, i - 1, rng.nextInt(i));
}
// Copy back. Use raw types.
final ListIterator it = list.listIterator();
for (final Object value : array) {
it.next();
it.set(value);
}
}
}
/**
* A direct list shuffle.
*
* @param rng Random number generator.
* @param list List.
*/
private static void shuffleDirect(UniformRandomProvider rng, List<?> list) {
for (int i = list.size(); i > 1; i--) {
swap(list, i - 1, rng.nextInt(i));
}
}
/**
* A list shuffle using an iterator.
*
* @param rng Random number generator.
* @param list List.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
private static void shuffleIterator(UniformRandomProvider rng, List<?> list) {
final Object[] array = list.toArray();
// Shuffle array
for (int i = array.length; i > 1; i--) {
swap(array, i - 1, rng.nextInt(i));
}
// Copy back. Use raw types.
final ListIterator it = list.listIterator();
for (final Object value : array) {
it.next();
it.set(value);
}
}
/**
* Direct shuffle on the list adapted from JDK java.util.Collections.
* This has been modified to handle the directional shuffle from a start index.
*
* @param rng Random number generator.
* @param list List.
* @param start Index at which shuffling begins.
* @param towardHead Shuffling is performed to the beginning or end of the list.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
private static void shuffleDirectRandomAccessDirectional(UniformRandomProvider rng, List<?> list,
int start, boolean towardHead) {
final int size = list.size();
if (list instanceof RandomAccess || size < RANDOM_ACCESS_SIZE_THRESHOLD) {
if (towardHead) {
for (int i = start; i > 0; i--) {
swap(list, i, rng.nextInt(i + 1));
}
} else {
for (int i = size - 1; i > start; i--) {
swap(list, i, start + rng.nextInt(i + 1 - start));
}
}
} else {
final Object[] array = list.toArray();
// Shuffle array
if (towardHead) {
for (int i = start; i > 0; i--) {
swap(array, i, rng.nextInt(i + 1));
}
// Copy back. Use raw types.
final ListIterator it = list.listIterator();
for (int i = 0; i <= start; i++) {
it.next();
it.set(array[i]);
}
} else {
for (int i = size - 1; i > start; i--) {
swap(array, i, start + rng.nextInt(i + 1 - start));
}
// Copy back. Use raw types.
final ListIterator it = list.listIterator(start);
for (int i = start; i < array.length; i++) {
it.next();
it.set(array[i]);
}
}
}
}
/**
* Direct shuffle on the list using the JDK java.util.Collections method with a sub-list
* to handle the directional shuffle from a start index.
*
* @param rng Random number generator.
* @param list List.
* @param start Index at which shuffling begins.
* @param towardHead Shuffling is performed to the beginning or end of the list.
*/
private static void shuffleDirectRandomAccessSubList(UniformRandomProvider rng, List<?> list,
int start, boolean towardHead) {
if (towardHead) {
shuffleDirectRandomAccess(rng, list.subList(0, start + 1));
} else {
shuffleDirectRandomAccess(rng, list.subList(start, list.size()));
}
}
/**
* Swaps the two specified elements in the specified list.
*
* @param list List.
* @param i First index.
* @param j Second index.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
private static void swap(List<?> list, int i, int j) {
// Use raw type
final List l = list;
l.set(i, l.set(j, l.get(i)));
}
/**
* Swaps the two specified elements in the specified array.
*
* @param array Array.
* @param i First index.
* @param j Second index.
*/
private static void swap(Object[] array, int i, int j) {
final Object tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
/**
* Baseline a shuffle using the Random.
* This is the in java.util.Collections that decrements to above one.
* This should be the same speed as the benchmark using UniformRandomProvider.
*
* @param data Shuffle data.
* @return the sum
*/
@Benchmark
public int baselineRandom(ShuffleData data) {
int sum = 0;
for (int i = data.getSize(); i > 1; i--) {
// A shuffle would swap (i-1) and j=nextInt(i)
sum += (i - 1) * data.getRandom().nextInt(i);
}
return sum;
}
/**
* Baseline a shuffle using the UniformRandomProvider.
* This should be the same speed as the benchmark using Random.
*
* @param data Shuffle data.
* @return the sum
*/
@Benchmark
public int baselineRNG(ShuffleData data) {
int sum = 0;
for (int i = data.getSize(); i > 1; i--) {
// A shuffle would swap (i-1) and j=nextInt(i)
sum += (i - 1) * data.getRNG().nextInt(i);
}
return sum;
}
/**
* Baseline a shuffle using the UniformRandomProvider.
* This should be the same speed as the benchmark using Random.
*
* @param data Shuffle data.
* @return the sum
*/
@Benchmark
public int baselineRNG2(ShuffleData data) {
int sum = 0;
for (int i = data.getSize(); i > 1; i--) {
// A shuffle would swap j=nextInt(i) and (i-1)
sum += data.getRNG().nextInt(i) * (i - 1);
}
return sum;
}
/**
* Baseline a shuffle using the UniformRandomProvider.
* This should be the same speed as the benchmark using Random.
* This uses a variant that decrements to above zero so that the index i is one
* of the indices to swap. This is included to determine if there is a difference.
*
* @param data Shuffle data.
* @return the sum
*/
@Benchmark
public int baselineRNG3(ShuffleData data) {
int sum = 0;
for (int i = data.getSize() - 1; i > 0; i--) {
// A shuffle would swap i and j=nextInt(i+1)
sum += i * data.getRNG().nextInt(i + 1);
}
return sum;
}
/**
* Performs a shuffle using java.utils.Collections.
*
* @param data Shuffle data.
* @return the list
*/
@Benchmark
public Object usingCollections(ListData data) {
Collections.shuffle(data.getList(), data.getRandom());
return data.getList();
}
/**
* Performs a shuffle using ListSampler shuffle method from version 1.2 which delegates
* to the PermuationSampler.
*
* @param data Shuffle data.
* @return the list
*/
@Benchmark
public Object usingPermutationSampler(ListData data) {
shuffleUsingPermutationSampler(data.getRNG(), data.getList(), data.getSize() - 1, true);
return data.getList();
}
/**
* Performs a shuffle using ListSampler shuffle method from version 1.2 which delegates
* to the PermuationSampler.
* This performs two part shuffles from the middle
* towards the head and then towards the end.
*
* @param data Shuffle data.
* @return the list
*/
@Benchmark
public Object usingPermutationSamplerBidirectional(ListData data) {
final int start = data.getSize() / 2;
shuffleUsingPermutationSampler(data.getRNG(), data.getList(), start, true);
shuffleUsingPermutationSampler(data.getRNG(), data.getList(), start + 1, false);
return data.getList();
}
/**
* Performs a shuffle using ListSampler shuffle method from version 1.2 which delegates
* to the PermuationSampler. The method has been modified to detect RandomAccess lists.
*
* @param data Shuffle data.
* @return the list
*/
@Benchmark
public Object usingPermutationSamplerRandomAccess(ListData data) {
shuffleUsingPermutationSamplerRandomAccess(data.getRNG(), data.getList(), data.getSize() - 1, true);
return data.getList();
}
/**
* Performs a shuffle using ListSampler shuffle method from version 1.2 which delegates
* to the PermuationSampler. The method has been modified to detect RandomAccess lists.
* This performs two part shuffles from the middle
* towards the head and then towards the end.
*
* @param data Shuffle data.
* @return the list
*/
@Benchmark
public Object usingPermutationSamplerRandomAccessBidirectional(ListData data) {
final int start = data.getSize() / 2;
shuffleUsingPermutationSamplerRandomAccess(data.getRNG(), data.getList(), start, true);
shuffleUsingPermutationSamplerRandomAccess(data.getRNG(), data.getList(), start + 1, false);
return data.getList();
}
/**
* Performs a direct shuffle on the list using JDK Collections method.
*
* @param data Shuffle data.
* @return the list
*/
@Benchmark
public Object usingDirectRandomAccess(ListData data) {
shuffleDirectRandomAccess(data.getRNG(), data.getList());
return data.getList();
}
/**
* Performs a direct shuffle on the list using JDK Collections method modified to handle
* a directional shuffle from a start index.
* This performs two part shuffles from the middle
* towards the head and then towards the end.
*
* @param data Shuffle data.
* @return the list
*/
@Benchmark
public Object usingDirectRandomAccessDirectionalBidirectional(ListData data) {
final int start = data.getSize() / 2;
shuffleDirectRandomAccessDirectional(data.getRNG(), data.getList(), start, true);
shuffleDirectRandomAccessDirectional(data.getRNG(), data.getList(), start + 1, false);
return data.getList();
}
/**
* Performs a direct shuffle on the list using JDK Collections method modified to handle
* a directional shuffle from a start index by extracting a sub-list.
* This performs two part shuffles from the middle
* towards the head and then towards the end.
*
* @param data Shuffle data.
* @return the list
*/
@Benchmark
public Object usingDirectRandomAccessSublistBidirectional(ListData data) {
final int start = data.getSize() / 2;
shuffleDirectRandomAccessSubList(data.getRNG(), data.getList(), start, true);
shuffleDirectRandomAccessSubList(data.getRNG(), data.getList(), start + 1, false);
return data.getList();
}
/**
* Performs a shuffle using the current ListSampler shuffle.
*
* @param data Shuffle data.
* @return the list
*/
@Benchmark
public Object usingListSampler(ListData data) {
ListSampler.shuffle(data.getRNG(), data.getList());
return data.getList();
}
/**
* Performs a shuffle using the current ListSampler shuffle.
* This performs two part shuffles from the middle
* towards the head and then towards the end.
*
* @param data Shuffle data.
* @return the list
*/
@Benchmark
public Object usingListSamplerBidirectional(ListData data) {
final int start = data.getSize() / 2;
ListSampler.shuffle(data.getRNG(), data.getList(), start, true);
ListSampler.shuffle(data.getRNG(), data.getList(), start + 1, false);
return data.getList();
}
/**
* Performs a direct shuffle on a LinkedList.
*
* @param data Shuffle data.
* @return the list
*/
@Benchmark
public Object shuffleDirect(LinkedListData data) {
shuffleDirect(data.getRNG(), data.getList());
return data.getList();
}
/**
* Performs a shuffle on a LinkedList using an iterator.
*
* @param data Shuffle data.
* @return the list
*/
@Benchmark
public Object shuffleIterator(LinkedListData data) {
shuffleIterator(data.getRNG(), data.getList());
return data.getList();
}
}
| 2,773 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Benchmarks for the {@code org.apache.commons.rng.sampling} components.
*/
package org.apache.commons.rng.examples.jmh.sampling;
| 2,774 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/shape/UnitBallSamplerBenchmark.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.shape;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.ObjectSampler;
import org.apache.commons.rng.sampling.distribution.ContinuousSampler;
import org.apache.commons.rng.sampling.distribution.NormalizedGaussianSampler;
import org.apache.commons.rng.sampling.distribution.ZigguratSampler;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import java.util.concurrent.TimeUnit;
/**
* Executes benchmark to compare the speed of generating samples within an N-dimension unit ball.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = { "-server", "-Xms128M", "-Xmx128M" })
public class UnitBallSamplerBenchmark {
/** Name for the baseline method. */
private static final String BASELINE = "Baseline";
/** Name for the rejection method. */
private static final String REJECTION = "Rejection";
/** Name for the disk-point picking method. */
private static final String DISK_POINT = "DiskPoint";
/** Name for the ball-point picking method. */
private static final String BALL_POINT = "BallPoint";
/** Name for the method moving from the surface of the hypersphere to an internal point. */
private static final String HYPERSPHERE_INTERNAL = "HypersphereInternal";
/** Name for the picking from the surface of a greater dimension hypersphere and discarding 2 points. */
private static final String HYPERSPHERE_DISCARD = "HypersphereDiscard";
/** Error message for an unknown sampler type. */
private static final String UNKNOWN_SAMPLER = "Unknown sampler type: ";
/** The mask to extract the lower 53-bits from a long. */
private static final long LOWER_53_BITS = -1L >>> 11;
/**
* Base class for a sampler using a provided source of randomness.
*/
private abstract static class BaseSampler implements ObjectSampler<double[]> {
/** The source of randomness. */
protected UniformRandomProvider rng;
/**
* Create an instance.
*
* @param rng the source of randomness
*/
BaseSampler(UniformRandomProvider rng) {
this.rng = rng;
}
}
/**
* Base class for the sampler data.
* Contains the source of randomness and the number of samples.
* The sampler should be created by a sub-class of the data.
*/
@State(Scope.Benchmark)
public abstract static class SamplerData {
/** The sampler. */
private ObjectSampler<double[]> sampler;
/** The number of samples. */
@Param({//"1",
"100"})
private int size;
/**
* Gets the size.
*
* @return the size
*/
public int getSize() {
return size;
}
/**
* Gets the sampler.
*
* @return the sampler
*/
public ObjectSampler<double[]> getSampler() {
return sampler;
}
/**
* Create the source of randomness.
*/
@Setup
public void setup() {
// This could be configured using @Param
final UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create();
sampler = createSampler(rng);
}
/**
* Creates the sampler.
*
* @param rng the source of randomness
* @return the sampler
*/
protected abstract ObjectSampler<double[]> createSampler(UniformRandomProvider rng);
}
/**
* The 1D unit line sampler.
*/
@State(Scope.Benchmark)
public static class Sampler1D extends SamplerData {
/** Name for the signed double method. */
private static final String SIGNED_DOUBLE = "signedDouble";
/** Name for the signed double method, version 2. */
private static final String SIGNED_DOUBLE2 = "signedDouble2";
/** Name for the two doubles method. */
private static final String TWO_DOUBLES = "twoDoubles";
/** Name for the boolean double method. */
private static final String BOOLEAN_DOUBLE = "booleanDouble";
/** The sampler type. */
@Param({BASELINE, SIGNED_DOUBLE, SIGNED_DOUBLE2, TWO_DOUBLES, BOOLEAN_DOUBLE})
private String type;
/** {@inheritDoc} */
@Override
protected ObjectSampler<double[]> createSampler(final UniformRandomProvider rng) {
if (BASELINE.equals(type)) {
return () -> new double[] {0.5};
} else if (SIGNED_DOUBLE.equals(type)) {
// Sample [-1, 1) uniformly
return () -> new double[] {makeSignedDouble(rng.nextLong())};
} else if (SIGNED_DOUBLE2.equals(type)) {
// Sample [-1, 1) uniformly
return () -> new double[] {makeSignedDouble2(rng.nextLong())};
} else if (TWO_DOUBLES.equals(type)) {
// Sample [-1, 1) excluding -0.0 but also missing the final 1.0 - 2^-53.
// The 1.0 could be adjusted to 1.0 - 2^-53 to create the interval (-1, 1).
return () -> new double[] {rng.nextDouble() + rng.nextDouble() - 1.0};
} else if (BOOLEAN_DOUBLE.equals(type)) {
// This will sample (-1, 1) including -0.0 and 0.0
return () -> new double[] {rng.nextBoolean() ? -rng.nextDouble() : rng.nextDouble()};
}
throw new IllegalStateException(UNKNOWN_SAMPLER + type);
}
}
/**
* The 2D unit disk sampler.
*/
@State(Scope.Benchmark)
public static class Sampler2D extends SamplerData {
/** The sampler type. */
@Param({BASELINE, REJECTION, DISK_POINT, HYPERSPHERE_INTERNAL, HYPERSPHERE_DISCARD})
private String type;
/** {@inheritDoc} */
@Override
protected ObjectSampler<double[]> createSampler(final UniformRandomProvider rng) {
if (BASELINE.equals(type)) {
return () -> new double[] {0.5, 0};
} else if (REJECTION.equals(type)) {
return new RejectionSampler(rng);
} else if (DISK_POINT.equals(type)) {
return new DiskPointSampler(rng);
} else if (HYPERSPHERE_INTERNAL.equals(type)) {
return new HypersphereInternalSampler(rng);
} else if (HYPERSPHERE_DISCARD.equals(type)) {
return new HypersphereDiscardSampler(rng);
}
throw new IllegalStateException(UNKNOWN_SAMPLER + type);
}
/**
* Sample using a simple rejection method.
*/
private static class RejectionSampler extends BaseSampler {
/**
* @param rng the source of randomness
*/
RejectionSampler(UniformRandomProvider rng) {
super(rng);
}
@Override
public double[] sample() {
// Generate via rejection method of a circle inside a square of edge length 2.
// This should compute approximately 2^2 / pi = 1.27 square positions per sample.
double x;
double y;
do {
x = makeSignedDouble(rng.nextLong());
y = makeSignedDouble(rng.nextLong());
} while (x * x + y * y > 1.0);
return new double[] {x, y};
}
}
/**
* Sample using disk point picking.
* @see <a href="https://mathworld.wolfram.com/DiskPointPicking.html">Disk point picking</a>
*/
private static class DiskPointSampler extends BaseSampler {
/** 2 pi. */
private static final double TWO_PI = 2 * Math.PI;
/**
* @param rng the source of randomness
*/
DiskPointSampler(UniformRandomProvider rng) {
super(rng);
}
@Override
public double[] sample() {
final double t = TWO_PI * rng.nextDouble();
final double r = Math.sqrt(rng.nextDouble());
final double x = r * Math.cos(t);
final double y = r * Math.sin(t);
return new double[] {x, y};
}
}
/**
* Choose a uniform point X on the unit hypersphere, then multiply it by U<sup>1/n</sup>
* where U in [0, 1].
* @see <a href="https://mathoverflow.net/questions/309567/sampling-a-uniformly-distributed-point-inside-a-hypersphere">
* Sampling a uniformly distributed point INSIDE a hypersphere?</a>
*/
private static class HypersphereInternalSampler extends BaseSampler {
/** The normal distribution. */
private final NormalizedGaussianSampler normal;
/**
* @param rng the source of randomness
*/
HypersphereInternalSampler(UniformRandomProvider rng) {
super(rng);
normal = ZigguratSampler.NormalizedGaussian.of(rng);
}
@Override
public double[] sample() {
final double x = normal.sample();
final double y = normal.sample();
final double sum = x * x + y * y;
// Note: Handle the possibility of a zero sum and invalid inverse
if (sum == 0) {
return sample();
}
// Take a point on the unit hypersphere then multiply it by U^1/n
final double f = Math.sqrt(rng.nextDouble()) / Math.sqrt(sum);
return new double[] {x * f, y * f};
}
}
/**
* Take a random point on the (n+1)-dimensional hypersphere and drop two coordinates.
* Remember that the (n+1)-hypersphere is the unit sphere of R^(n+2).
* @see <a href="https://mathoverflow.net/questions/309567/sampling-a-uniformly-distributed-point-inside-a-hypersphere">
* Sampling a uniformly distributed point INSIDE a hypersphere?</a>
*/
private static class HypersphereDiscardSampler extends BaseSampler {
/** The normal distribution. */
private final NormalizedGaussianSampler normal;
/**
* @param rng the source of randomness
*/
HypersphereDiscardSampler(UniformRandomProvider rng) {
super(rng);
normal = ZigguratSampler.NormalizedGaussian.of(rng);
}
@Override
public double[] sample() {
// Discard 2 samples from the coordinate but include in the sum
final double x0 = normal.sample();
final double x1 = normal.sample();
final double x = normal.sample();
final double y = normal.sample();
final double sum = x0 * x0 + x1 * x1 + x * x + y * y;
// Note: Handle the possibility of a zero sum and invalid inverse
if (sum == 0) {
return sample();
}
final double f = 1.0 / Math.sqrt(sum);
return new double[] {x * f, y * f};
}
}
}
/**
* The 3D unit ball sampler.
*/
@State(Scope.Benchmark)
public static class Sampler3D extends SamplerData {
/** The sampler type. */
@Param({BASELINE, REJECTION, BALL_POINT, HYPERSPHERE_INTERNAL, HYPERSPHERE_DISCARD})
private String type;
/** {@inheritDoc} */
@Override
protected ObjectSampler<double[]> createSampler(final UniformRandomProvider rng) {
if (BASELINE.equals(type)) {
return () -> new double[] {0.5, 0, 0};
} else if (REJECTION.equals(type)) {
return new RejectionSampler(rng);
} else if (BALL_POINT.equals(type)) {
return new BallPointSampler(rng);
} else if (HYPERSPHERE_INTERNAL.equals(type)) {
return new HypersphereInternalSampler(rng);
} else if (HYPERSPHERE_DISCARD.equals(type)) {
return new HypersphereDiscardSampler(rng);
}
throw new IllegalStateException(UNKNOWN_SAMPLER + type);
}
/**
* Sample using a simple rejection method.
*/
private static class RejectionSampler extends BaseSampler {
/**
* @param rng the source of randomness
*/
RejectionSampler(UniformRandomProvider rng) {
super(rng);
}
@Override
public double[] sample() {
// Generate via rejection method of a ball inside a cube of edge length 2.
// This should compute approximately 2^3 / (4pi/3) = 1.91 cube positions per sample.
double x;
double y;
double z;
do {
x = makeSignedDouble(rng.nextLong());
y = makeSignedDouble(rng.nextLong());
z = makeSignedDouble(rng.nextLong());
} while (x * x + y * y + z * z > 1.0);
return new double[] {x, y, z};
}
}
/**
* Sample using ball point picking.
* @see <a href="https://mathworld.wolfram.com/BallPointPicking.html">Ball point picking</a>
*/
private static class BallPointSampler extends BaseSampler {
/** The normal distribution. */
private final NormalizedGaussianSampler normal;
/** The exponential distribution. */
private final ContinuousSampler exp;
/**
* @param rng the source of randomness
*/
BallPointSampler(UniformRandomProvider rng) {
super(rng);
normal = ZigguratSampler.NormalizedGaussian.of(rng);
// Exponential(mean=2) == Chi-squared distribution(degrees freedom=2)
// thus is the equivalent of the HypersphereDiscardSampler.
// Here we use mean = 1 and scale the output later.
exp = ZigguratSampler.Exponential.of(rng);
}
@Override
public double[] sample() {
final double x = normal.sample();
final double y = normal.sample();
final double z = normal.sample();
// Include the exponential sample. It has mean 1 so multiply by 2.
final double sum = exp.sample() * 2 + x * x + y * y + z * z;
// Note: Handle the possibility of a zero sum and invalid inverse
if (sum == 0) {
return sample();
}
final double f = 1.0 / Math.sqrt(sum);
return new double[] {x * f, y * f, z * f};
}
}
/**
* Choose a uniform point X on the unit hypersphere, then multiply it by U<sup>1/n</sup>
* where U in [0, 1].
* @see <a href="https://mathoverflow.net/questions/309567/sampling-a-uniformly-distributed-point-inside-a-hypersphere">
* Sampling a uniformly distributed point INSIDE a hypersphere?</a>
*/
private static class HypersphereInternalSampler extends BaseSampler {
/** The normal distribution. */
private final NormalizedGaussianSampler normal;
/**
* @param rng the source of randomness
*/
HypersphereInternalSampler(UniformRandomProvider rng) {
super(rng);
normal = ZigguratSampler.NormalizedGaussian.of(rng);
}
@Override
public double[] sample() {
final double x = normal.sample();
final double y = normal.sample();
final double z = normal.sample();
final double sum = x * x + y * y + z * z;
// Note: Handle the possibility of a zero sum and invalid inverse
if (sum == 0) {
return sample();
}
// Take a point on the unit hypersphere then multiply it by U^1/n
final double f = Math.cbrt(rng.nextDouble()) / Math.sqrt(sum);
return new double[] {x * f, y * f, z * f};
}
}
/**
* Take a random point on the (n+1)-dimensional hypersphere and drop two coordinates.
* Remember that the (n+1)-hypersphere is the unit sphere of R^(n+2).
* @see <a href="https://mathoverflow.net/questions/309567/sampling-a-uniformly-distributed-point-inside-a-hypersphere">
* Sampling a uniformly distributed point INSIDE a hypersphere?</a>
*/
private static class HypersphereDiscardSampler extends BaseSampler {
/** The normal distribution. */
private final NormalizedGaussianSampler normal;
/**
* @param rng the source of randomness
*/
HypersphereDiscardSampler(UniformRandomProvider rng) {
super(rng);
normal = ZigguratSampler.NormalizedGaussian.of(rng);
}
@Override
public double[] sample() {
// Discard 2 samples from the coordinate but include in the sum
final double x0 = normal.sample();
final double x1 = normal.sample();
final double x = normal.sample();
final double y = normal.sample();
final double z = normal.sample();
final double sum = x0 * x0 + x1 * x1 + x * x + y * y + z * z;
// Note: Handle the possibility of a zero sum and invalid inverse
if (sum == 0) {
return sample();
}
final double f = 1.0 / Math.sqrt(sum);
return new double[] {x * f, y * f, z * f};
}
}
}
/**
* The ND unit ball sampler.
*/
@State(Scope.Benchmark)
public static class SamplerND extends SamplerData {
/** The sampler type. */
@Param({BASELINE, REJECTION, BALL_POINT, HYPERSPHERE_INTERNAL, HYPERSPHERE_DISCARD})
private String type;
/** The number of dimensions. */
@Param({"3", "4", "5"})
private int dimension;
/** {@inheritDoc} */
@Override
protected ObjectSampler<double[]> createSampler(final UniformRandomProvider rng) {
if (BASELINE.equals(type)) {
return new ObjectSampler<double[]>() {
private final int dim = dimension;
@Override
public double[] sample() {
final double[] sample = new double[dim];
for (int i = 0; i < dim; i++) {
sample[i] = 0.01;
}
return sample;
}
};
} else if (REJECTION.equals(type)) {
return new RejectionSampler(rng, dimension);
} else if (BALL_POINT.equals(type)) {
return new BallPointSampler(rng, dimension);
} else if (HYPERSPHERE_INTERNAL.equals(type)) {
return new HypersphereInternalSampler(rng, dimension);
} else if (HYPERSPHERE_DISCARD.equals(type)) {
return new HypersphereDiscardSampler(rng, dimension);
}
throw new IllegalStateException(UNKNOWN_SAMPLER + type);
}
/**
* Sample using a simple rejection method.
*/
private static class RejectionSampler extends BaseSampler {
/** The dimension. */
private final int dimension;
/**
* @param rng the source of randomness
* @param dimension the dimension
*/
RejectionSampler(UniformRandomProvider rng, int dimension) {
super(rng);
this.dimension = dimension;
}
@Override
public double[] sample() {
// Generate via rejection method of a ball inside a hypercube of edge length 2.
final double[] sample = new double[dimension];
double sum;
do {
sum = 0;
for (int i = 0; i < dimension; i++) {
final double x = makeSignedDouble(rng.nextLong());
sum += x * x;
sample[i] = x;
}
} while (sum > 1.0);
return sample;
}
}
/**
* Sample using ball point picking.
* @see <a href="https://mathworld.wolfram.com/BallPointPicking.html">Ball point picking</a>
*/
private static class BallPointSampler extends BaseSampler {
/** The dimension. */
private final int dimension;
/** The normal distribution. */
private final NormalizedGaussianSampler normal;
/** The exponential distribution. */
private final ContinuousSampler exp;
/**
* @param rng the source of randomness
* @param dimension the dimension
*/
BallPointSampler(UniformRandomProvider rng, int dimension) {
super(rng);
this.dimension = dimension;
normal = ZigguratSampler.NormalizedGaussian.of(rng);
// Exponential(mean=2) == Chi-squared distribution(degrees freedom=2)
// thus is the equivalent of the HypersphereDiscardSampler.
// Here we use mean = 1 and scale the output later.
exp = ZigguratSampler.Exponential.of(rng);
}
@Override
public double[] sample() {
final double[] sample = new double[dimension];
// Include the exponential sample. It has mean 1 so multiply by 2.
double sum = exp.sample() * 2;
for (int i = 0; i < dimension; i++) {
final double x = normal.sample();
sum += x * x;
sample[i] = x;
}
// Note: Handle the possibility of a zero sum and invalid inverse
if (sum == 0) {
return sample();
}
final double f = 1.0 / Math.sqrt(sum);
for (int i = 0; i < dimension; i++) {
sample[i] *= f;
}
return sample;
}
}
/**
* Choose a uniform point X on the unit hypersphere, then multiply it by U<sup>1/n</sup>
* where U in [0, 1].
* @see <a href="https://mathoverflow.net/questions/309567/sampling-a-uniformly-distributed-point-inside-a-hypersphere">
* Sampling a uniformly distributed point INSIDE a hypersphere?</a>
*/
private static class HypersphereInternalSampler extends BaseSampler {
/** The dimension. */
private final int dimension;
/** The normal distribution. */
private final NormalizedGaussianSampler normal;
/** Reciprocal of the dimension. */
private final double power;
/**
* @param rng the source of randomness
* @param dimension the dimension
*/
HypersphereInternalSampler(UniformRandomProvider rng, int dimension) {
super(rng);
this.dimension = dimension;
power = 1.0 / dimension;
normal = ZigguratSampler.NormalizedGaussian.of(rng);
}
@Override
public double[] sample() {
final double[] sample = new double[dimension];
double sum = 0;
for (int i = 0; i < dimension; i++) {
final double x = normal.sample();
sum += x * x;
sample[i] = x;
}
// Note: Handle the possibility of a zero sum and invalid inverse
if (sum == 0) {
return sample();
}
// Take a point on the unit hypersphere then multiply it by U^1/n
final double f = Math.pow(rng.nextDouble(), power) / Math.sqrt(sum);
for (int i = 0; i < dimension; i++) {
sample[i] *= f;
}
return sample;
}
}
/**
* Take a random point on the (n+1)-dimensional hypersphere and drop two coordinates.
* Remember that the (n+1)-hypersphere is the unit sphere of R^(n+2).
* @see <a href="https://mathoverflow.net/questions/309567/sampling-a-uniformly-distributed-point-inside-a-hypersphere">
* Sampling a uniformly distributed point INSIDE a hypersphere?</a>
*/
private static class HypersphereDiscardSampler extends BaseSampler {
/** The dimension. */
private final int dimension;
/** The normal distribution. */
private final NormalizedGaussianSampler normal;
/**
* @param rng the source of randomness
* @param dimension the dimension
*/
HypersphereDiscardSampler(UniformRandomProvider rng, int dimension) {
super(rng);
this.dimension = dimension;
normal = ZigguratSampler.NormalizedGaussian.of(rng);
}
@Override
public double[] sample() {
final double[] sample = new double[dimension];
// Discard 2 samples from the coordinate but include in the sum
final double x0 = normal.sample();
final double x1 = normal.sample();
double sum = x0 * x0 + x1 * x1;
for (int i = 0; i < dimension; i++) {
final double x = normal.sample();
sum += x * x;
sample[i] = x;
}
// Note: Handle the possibility of a zero sum and invalid inverse
if (sum == 0) {
return sample();
}
final double f = 1.0 / Math.sqrt(sum);
for (int i = 0; i < dimension; i++) {
sample[i] *= f;
}
return sample;
}
}
}
/**
* Creates a signed double in the range {@code [-1, 1)}. The magnitude is sampled evenly
* from the 2<sup>54</sup> dyadic rationals in the range.
*
* <p>Note: This method will not return samples for both -0.0 and 0.0.
*
* @param bits the bits
* @return the double
*/
private static double makeSignedDouble(long bits) {
// As per o.a.c.rng.core.utils.NumberFactory.makeDouble(long) but using a signed
// shift of 10 in place of an unsigned shift of 11.
return (bits >> 10) * 0x1.0p-53d;
}
/**
* Creates a signed double in the range {@code [-1, 1)}. The magnitude is sampled evenly
* from the 2<sup>54</sup> dyadic rationals in the range.
*
* <p>Note: This method will not return samples for both -0.0 and 0.0.
*
* @param bits the bits
* @return the double
*/
private static double makeSignedDouble2(long bits) {
// Use the upper 54 bits on the assumption they are more random.
// The sign bit generates a value of 0 or 1 for subtraction.
// The next 53 bits generates a positive number in the range [0, 1).
// [0, 1) - (0 or 1) => [-1, 1)
return (((bits >>> 10) & LOWER_53_BITS) * 0x1.0p-53d) - (bits >>> 63);
}
/**
* Run the sampler for the configured number of samples.
*
* @param bh Data sink
* @param data Input data.
*/
private static void runSampler(Blackhole bh, SamplerData data) {
final ObjectSampler<double[]> sampler = data.getSampler();
for (int i = data.getSize() - 1; i >= 0; i--) {
bh.consume(sampler.sample());
}
}
/**
* Generation of uniform samples on a 1D unit line.
*
* @param bh Data sink
* @param data Input data.
*/
@Benchmark
public void create1D(Blackhole bh, Sampler1D data) {
runSampler(bh, data);
}
/**
* Generation of uniform samples from a 2D unit disk.
*
* @param bh Data sink
* @param data Input data.
*/
@Benchmark
public void create2D(Blackhole bh, Sampler2D data) {
runSampler(bh, data);
}
/**
* Generation of uniform samples from a 3D unit ball.
*
* @param bh Data sink
* @param data Input data.
*/
@Benchmark
public void create3D(Blackhole bh, Sampler3D data) {
runSampler(bh, data);
}
/**
* Generation of uniform samples from an ND unit ball.
*
* @param bh Data sink
* @param data Input data.
*/
@Benchmark
public void createND(Blackhole bh, SamplerND data) {
runSampler(bh, data);
}
}
| 2,775 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/shape/TetrahedronSamplerBenchmark.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.shape;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.ObjectSampler;
import org.apache.commons.rng.sampling.UnitSphereSampler;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import java.util.concurrent.TimeUnit;
/**
* Executes benchmark to compare the speed of generating samples within a tetrahedron.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = { "-server", "-Xms512M", "-Xmx512M" })
public class TetrahedronSamplerBenchmark {
/** Name for the baseline method. */
private static final String BASELINE = "Baseline";
/** Name for the method using array coordinates. */
private static final String ARRAY = "Array";
/** Name for the method using non-array (primitive) coordinates. */
private static final String NON_ARRAY = "NonArray";
/** Name for the method using array coordinates and inline sample algorithm. */
private static final String ARRAY_INLINE = "ArrayInline";
/** Name for the method using non-array (primitive) coordinates and inline sample algorithm. */
private static final String NON_ARRAY_INLINE = "NonArrayInline";
/** Error message for an unknown sampler type. */
private static final String UNKNOWN_SAMPLER = "Unknown sampler type: ";
/**
* The base class for sampling from a tetrahedron.
*
* <ul>
* <li>
* Uses the algorithm described in:
* <blockquote>
* Rocchini, C. and Cignoni, P. (2001)<br>
* <i>Generating Random Points in a Tetrahedron</i>.<br>
* <strong>Journal of Graphics Tools</strong> 5(4), pp. 9-12.
* </blockquote>
* </li>
* </ul>
*
* @see <a href="https://doi.org/10.1080/10867651.2000.10487528">
* Rocchini, C. & Cignoni, P. (2001) Journal of Graphics Tools 5, pp. 9-12</a>
*/
private abstract static class TetrahedronSampler implements ObjectSampler<double[]> {
/** The source of randomness. */
private final UniformRandomProvider rng;
/**
* @param rng Source of randomness.
*/
TetrahedronSampler(UniformRandomProvider rng) {
this.rng = rng;
}
@Override
public double[] sample() {
double s = rng.nextDouble();
double t = rng.nextDouble();
final double u = rng.nextDouble();
// Care is taken to ensure the 3 deviates remain in the 2^53 dyadic rationals in [0, 1).
// The following are exact for all the 2^53 dyadic rationals:
// 1 - u; u in [0, 1]
// u - 1; u in [0, 1]
// u + 1; u in [-1, 0]
// u + v; u in [-1, 0], v in [0, 1]
// u + v; u, v in [0, 1], u + v <= 1
// Cut and fold with the plane s + t = 1
if (s + t > 1) {
// (s, t, u) = (1 - s, 1 - t, u) if s + t > 1
s = 1 - s;
t = 1 - t;
}
// Now s + t <= 1.
// Cut and fold with the planes t + u = 1 and s + t + u = 1.
final double tpu = t + u;
final double sptpu = s + tpu;
if (sptpu > 1) {
if (tpu > 1) {
// (s, t, u) = (s, 1 - u, 1 - s - t) if t + u > 1
// 1 - s - (1-u) - (1-s-t) == u - 1 + t
return createSample(u - 1 + t, s, 1 - u, 1 - s - t);
}
// (s, t, u) = (1 - t - u, t, s + t + u - 1) if t + u <= 1
// 1 - (1-t-u) - t - (s+t+u-1) == 1 - s - t
return createSample(1 - s - t, 1 - tpu, t, s - 1 + tpu);
}
return createSample(1 - sptpu, s, t, u);
}
/**
* Creates the sample given the random variates {@code s}, {@code t} and {@code u} in the
* interval {@code [0, 1]} and {@code s + t + u <= 1}. The sum {@code 1 - s - t - u} is
* provided. The sample can be obtained from the tetrahedron {@code abcd} using:
*
* <pre>
* p = (1 - s - t - u)a + sb + tc + ud
* </pre>
*
* @param p1msmtmu plus 1 minus s minus t minus u (1 - s - t - u)
* @param s the first variate s
* @param t the second variate t
* @param u the third variate u
* @return the sample
*/
protected abstract double[] createSample(double p1msmtmu, double s, double t, double u);
}
/**
* Sample from a tetrahedron using array coordinates.
*/
private static class ArrayTetrahedronSampler extends TetrahedronSampler {
// CHECKSTYLE: stop JavadocVariableCheck
private final double[] a;
private final double[] b;
private final double[] c;
private final double[] d;
// CHECKSTYLE: resume JavadocVariableCheck
/**
* @param rng the source of randomness
* @param a The first vertex.
* @param b The second vertex.
* @param c The third vertex.
* @param d The fourth vertex.
*/
ArrayTetrahedronSampler(UniformRandomProvider rng,
double[] a, double[] b, double[] c, double[] d) {
super(rng);
this.a = a.clone();
this.b = b.clone();
this.c = c.clone();
this.d = d.clone();
}
@Override
protected double[] createSample(double p1msmtmu, double s, double t, double u) {
return new double[] {p1msmtmu * a[0] + s * b[0] + t * c[0] + u * d[0],
p1msmtmu * a[1] + s * b[1] + t * c[1] + u * d[1],
p1msmtmu * a[2] + s * b[2] + t * c[2] + u * d[2]};
}
}
/**
* Sample from a tetrahedron using non-array coordinates.
*/
private static class NonArrayTetrahedronSampler extends TetrahedronSampler {
// CHECKSTYLE: stop JavadocVariableCheck
private final double ax;
private final double bx;
private final double cx;
private final double dx;
private final double ay;
private final double by;
private final double cy;
private final double dy;
private final double az;
private final double bz;
private final double cz;
private final double dz;
// CHECKSTYLE: resume JavadocVariableCheck
/**
* @param rng the source of randomness
* @param a The first vertex.
* @param b The second vertex.
* @param c The third vertex.
* @param d The fourth vertex.
*/
NonArrayTetrahedronSampler(UniformRandomProvider rng,
double[] a, double[] b, double[] c, double[] d) {
super(rng);
ax = a[0];
ay = a[1];
az = a[2];
bx = b[0];
by = b[1];
bz = b[2];
cx = c[0];
cy = c[1];
cz = c[2];
dx = d[0];
dy = d[1];
dz = d[2];
}
@Override
protected double[] createSample(double p1msmtmu, double s, double t, double u) {
return new double[] {p1msmtmu * ax + s * bx + t * cx + u * dx,
p1msmtmu * ay + s * by + t * cy + u * dy,
p1msmtmu * az + s * bz + t * cz + u * dz};
}
}
/**
* Sample from a tetrahedron using array coordinates with an inline sample algorithm
* in-place of a method call.
*/
private static class ArrayInlineTetrahedronSampler implements ObjectSampler<double[]> {
// CHECKSTYLE: stop JavadocVariableCheck
private final double[] a;
private final double[] b;
private final double[] c;
private final double[] d;
private final UniformRandomProvider rng;
// CHECKSTYLE: resume JavadocVariableCheck
/**
* @param rng the source of randomness
* @param a The first vertex.
* @param b The second vertex.
* @param c The third vertex.
* @param d The fourth vertex.
*/
ArrayInlineTetrahedronSampler(UniformRandomProvider rng,
double[] a, double[] b, double[] c, double[] d) {
this.a = a.clone();
this.b = b.clone();
this.c = c.clone();
this.d = d.clone();
this.rng = rng;
}
@Override
public double[] sample() {
double s = rng.nextDouble();
double t = rng.nextDouble();
double u = rng.nextDouble();
if (s + t > 1) {
// (s, t, u) = (1 - s, 1 - t, u) if s + t > 1
s = 1 - s;
t = 1 - t;
}
double p1msmtmu;
final double tpu = t + u;
final double sptpu = s + tpu;
if (sptpu > 1) {
if (tpu > 1) {
// (s, t, u) = (s, 1 - u, 1 - s - t) if t + u > 1
final double tt = t;
p1msmtmu = u - 1 + t;
t = 1 - u;
u = 1 - s - tt;
} else {
// (s, t, u) = (1 - t - u, t, s + t + u - 1) if t + u <= 1
final double ss = s;
p1msmtmu = 1 - s - t;
s = 1 - tpu;
u = ss - 1 + tpu;
}
} else {
p1msmtmu = 1 - sptpu;
}
return new double[] {p1msmtmu * a[0] + s * b[0] + t * c[0] + u * d[0],
p1msmtmu * a[1] + s * b[1] + t * c[1] + u * d[1],
p1msmtmu * a[2] + s * b[2] + t * c[2] + u * d[2]};
}
}
/**
* Sample from a tetrahedron using non-array coordinates with an inline sample algorithm
* in-place of a method call.
*/
private static class NonArrayInlineTetrahedronSampler implements ObjectSampler<double[]> {
// CHECKSTYLE: stop JavadocVariableCheck
private final double ax;
private final double bx;
private final double cx;
private final double dx;
private final double ay;
private final double by;
private final double cy;
private final double dy;
private final double az;
private final double bz;
private final double cz;
private final double dz;
private final UniformRandomProvider rng;
// CHECKSTYLE: resume JavadocVariableCheck
/**
* @param rng the source of randomness
* @param a The first vertex.
* @param b The second vertex.
* @param c The third vertex.
* @param d The fourth vertex.
*/
NonArrayInlineTetrahedronSampler(UniformRandomProvider rng,
double[] a, double[] b, double[] c, double[] d) {
ax = a[0];
ay = a[1];
az = a[2];
bx = b[0];
by = b[1];
bz = b[2];
cx = c[0];
cy = c[1];
cz = c[2];
dx = d[0];
dy = d[1];
dz = d[2];
this.rng = rng;
}
@Override
public double[] sample() {
double s = rng.nextDouble();
double t = rng.nextDouble();
double u = rng.nextDouble();
if (s + t > 1) {
// (s, t, u) = (1 - s, 1 - t, u) if s + t > 1
s = 1 - s;
t = 1 - t;
}
double p1msmtmu;
final double tpu = t + u;
final double sptpu = s + tpu;
if (sptpu > 1) {
if (tpu > 1) {
// (s, t, u) = (s, 1 - u, 1 - s - t) if t + u > 1
final double tt = t;
p1msmtmu = u - 1 + t;
t = 1 - u;
u = 1 - s - tt;
} else {
// (s, t, u) = (1 - t - u, t, s + t + u - 1) if t + u <= 1
final double ss = s;
p1msmtmu = 1 - s - t;
s = 1 - tpu;
u = ss - 1 + tpu;
}
} else {
p1msmtmu = 1 - sptpu;
}
return new double[] {p1msmtmu * ax + s * bx + t * cx + u * dx,
p1msmtmu * ay + s * by + t * cy + u * dy,
p1msmtmu * az + s * bz + t * cz + u * dz};
}
}
/**
* Contains the sampler and the number of samples.
*/
@State(Scope.Benchmark)
public static class SamplerData {
/** The sampler. */
private ObjectSampler<double[]> sampler;
/** The number of samples. */
@Param({"1", "10", "100", "1000", "10000"})
private int size;
/** The sampler type. */
@Param({BASELINE, ARRAY, NON_ARRAY, ARRAY_INLINE, NON_ARRAY_INLINE})
private String type;
/**
* Gets the size.
*
* @return the size
*/
public int getSize() {
return size;
}
/**
* Gets the sampler.
*
* @return the sampler
*/
public ObjectSampler<double[]> getSampler() {
return sampler;
}
/**
* Create the source of randomness and the sampler.
*/
@Setup(Level.Iteration)
public void setup() {
// This could be configured using @Param
final UniformRandomProvider rng = RandomSource.XO_SHI_RO_256_PP.create();
final UnitSphereSampler s = UnitSphereSampler.of(rng, 3);
final double[] a = s.sample();
final double[] b = s.sample();
final double[] c = s.sample();
final double[] d = s.sample();
sampler = createSampler(rng, a, b, c, d);
}
/**
* Creates the tetrahedron sampler.
*
* @param a The first vertex.
* @param b The second vertex.
* @param c The third vertex.
* @param d The fourth vertex.
* @param rng the source of randomness
* @return the sampler
*/
private ObjectSampler<double[]> createSampler(final UniformRandomProvider rng,
double[] a, double[] b, double[] c, double[] d) {
if (BASELINE.equals(type)) {
return () -> {
final double s = rng.nextDouble();
final double t = rng.nextDouble();
final double u = rng.nextDouble();
return new double[] {s, t, u};
};
} else if (ARRAY.equals(type)) {
return new ArrayTetrahedronSampler(rng, a, b, c, d);
} else if (NON_ARRAY.equals(type)) {
return new NonArrayTetrahedronSampler(rng, a, b, c, d);
} else if (ARRAY_INLINE.equals(type)) {
return new ArrayInlineTetrahedronSampler(rng, a, b, c, d);
} else if (NON_ARRAY_INLINE.equals(type)) {
return new NonArrayInlineTetrahedronSampler(rng, a, b, c, d);
}
throw new IllegalStateException(UNKNOWN_SAMPLER + type);
}
}
/**
* Run the sampler for the configured number of samples.
*
* @param bh Data sink
* @param data Input data.
*/
@Benchmark
public void sample(Blackhole bh, SamplerData data) {
final ObjectSampler<double[]> sampler = data.getSampler();
for (int i = data.getSize() - 1; i >= 0; i--) {
bh.consume(sampler.sample());
}
}
}
| 2,776 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/shape/TriangleSamplerBenchmark.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.shape;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.ObjectSampler;
import org.apache.commons.rng.sampling.UnitSphereSampler;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import java.util.concurrent.TimeUnit;
/**
* Executes benchmark to compare the speed of generating samples within an N-dimension triangle.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = { "-server", "-Xms512M", "-Xmx512M" })
public class TriangleSamplerBenchmark {
/** Name for the baseline method. */
private static final String BASELINE = "Baseline";
/** Name for the baseline method including a 50:50 if statement. */
private static final String BASELINE_IF = "BaselineIf";
/** Name for the method using vectors. */
private static final String VECTORS = "Vectors";
/** Name for the method using the coordinates. */
private static final String COORDINATES = "Coordinates";
/** Error message for an unknown sampler type. */
private static final String UNKNOWN_SAMPLER = "Unknown sampler type: ";
/**
* Base class for a sampler using vectors: {@code p = a + sv + tw}.
*/
private abstract static class VectorTriangleSampler implements ObjectSampler<double[]> {
/** The source of randomness. */
private final UniformRandomProvider rng;
/**
* Create an instance.
*
* @param rng the source of randomness
*/
VectorTriangleSampler(UniformRandomProvider rng) {
this.rng = rng;
}
/**
* @return a random Cartesian point inside the triangle.
*/
@Override
public double[] sample() {
final double s = rng.nextDouble();
final double t = rng.nextDouble();
if (s + t > 1) {
return createSample(1.0 - s, 1.0 - t);
}
return createSample(s, t);
}
/**
* Creates the sample given the random variates {@code s} and {@code t} in the
* interval {@code [0, 1]} and {@code s + t <= 1}.
* The sample can be obtained from the triangle abc with v = b-a and w = c-a using:
* <pre>
* p = a + sv + tw
* </pre>
*
* @param s the first variate s
* @param t the second variate t
* @return the sample
*/
protected abstract double[] createSample(double s, double t);
}
/**
* Base class for a sampler using coordinates: {@code a(1 - s - t) + sb + tc}.
*/
private abstract static class CoordinateTriangleSampler implements ObjectSampler<double[]> {
/** The source of randomness. */
private final UniformRandomProvider rng;
/**
* Create an instance.
*
* @param rng the source of randomness
*/
CoordinateTriangleSampler(UniformRandomProvider rng) {
this.rng = rng;
}
/**
* @return a random Cartesian point inside the triangle.
*/
@Override
public double[] sample() {
final double s = rng.nextDouble();
final double t = rng.nextDouble();
final double spt = s + t;
if (spt > 1) {
// Transform: s1 = 1 - s; t1 = 1 - t.
// Compute: 1 - s1 - t1
// Do not assume (1 - (1-s) - (1-t)) is (s + t - 1), i.e. (spt - 1.0),
// to avoid loss of a random bit due to rounding when s + t > 1.
// An exact sum is (s - 1 + t).
return createSample(s - 1.0 + t, 1.0 - s, 1.0 - t);
}
// Here s + t is exact so can be subtracted to make 1 - s - t
return createSample(1.0 - spt, s, t);
}
/**
* Creates the sample given the random variates {@code s} and {@code t} in the
* interval {@code [0, 1]} and {@code s + t <= 1}. The sum {@code 1 - s - t} is provided.
* The sample can be obtained from the triangle abc using:
* <pre>
* p = a(1 - s - t) + sb + tc
* </pre>
*
* @param p1msmt plus 1 minus s minus t (1 - s - t)
* @param s the first variate s
* @param t the second variate t
* @return the sample
*/
protected abstract double[] createSample(double p1msmt, double s, double t);
}
/**
* Base class for the sampler data.
* Contains the source of randomness and the number of samples.
* The sampler should be created by a sub-class of the data.
*/
@State(Scope.Benchmark)
public abstract static class SamplerData {
/** The sampler. */
private ObjectSampler<double[]> sampler;
/** The number of samples. */
@Param({"1000"})
private int size;
/**
* Gets the size.
*
* @return the size
*/
public int getSize() {
return size;
}
/**
* Gets the sampler.
*
* @return the sampler
*/
public ObjectSampler<double[]> getSampler() {
return sampler;
}
/**
* Create the source of randomness and the sampler.
*/
@Setup(Level.Iteration)
public void setup() {
// This could be configured using @Param
final UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create();
final int dimension = getDimension();
final UnitSphereSampler s = UnitSphereSampler.of(rng, dimension);
final double[] a = s.sample();
final double[] b = s.sample();
final double[] c = s.sample();
sampler = createSampler(rng, a, b, c);
}
/**
* Gets the dimension of the triangle vertices.
*
* @return the dimension
*/
protected abstract int getDimension();
/**
* Creates the triangle sampler.
*
* @param rng the source of randomness
* @param a The first vertex.
* @param b The second vertex.
* @param c The third vertex.
* @return the sampler
*/
protected abstract ObjectSampler<double[]> createSampler(UniformRandomProvider rng,
double[] a, double[] b, double[] c);
}
/**
* The 2D triangle sampler.
*/
@State(Scope.Benchmark)
public static class Sampler2D extends SamplerData {
/** The sampler type. */
@Param({BASELINE, BASELINE_IF, VECTORS, COORDINATES})
private String type;
/** {@inheritDoc} */
@Override
protected int getDimension() {
return 2;
}
/** {@inheritDoc} */
@Override
protected ObjectSampler<double[]> createSampler(final UniformRandomProvider rng,
final double[] a, final double[] b, final double[] c) {
if (BASELINE.equals(type)) {
return () -> {
final double s = rng.nextDouble();
final double t = rng.nextDouble();
return new double[] {s, t};
};
} else if (BASELINE_IF.equals(type)) {
return () -> {
final double s = rng.nextDouble();
final double t = rng.nextDouble();
if (s + t > 1) {
return new double[] {s, t};
}
return new double[] {t, s};
};
} else if (VECTORS.equals(type)) {
return new VectorTriangleSampler2D(rng, a, b, c);
} else if (COORDINATES.equals(type)) {
return new CoordinateTriangleSampler2D(rng, a, b, c);
}
throw new IllegalStateException(UNKNOWN_SAMPLER + type);
}
/**
* Sample vectors in 2D.
*/
private static class VectorTriangleSampler2D extends VectorTriangleSampler {
// CHECKSTYLE: stop JavadocVariableCheck
private final double ax;
private final double ay;
private final double vx;
private final double vy;
private final double wx;
private final double wy;
// CHECKSTYLE: resume JavadocVariableCheck
/**
* @param rng the source of randomness
* @param a The first vertex.
* @param b The second vertex.
* @param c The third vertex.
*/
VectorTriangleSampler2D(UniformRandomProvider rng, double[] a, double[] b, double[] c) {
super(rng);
ax = a[0];
ay = a[1];
vx = b[0] - ax;
vy = b[1] - ay;
wx = c[0] - ax;
wy = c[1] - ay;
}
@Override
protected double[] createSample(double s, double t) {
return new double[] {ax + s * vx + t * wx,
ay + s * vy + t * wy};
}
}
/**
* Sample using coordinates in 2D.
*/
private static class CoordinateTriangleSampler2D extends CoordinateTriangleSampler {
// CHECKSTYLE: stop JavadocVariableCheck
private final double ax;
private final double ay;
private final double bx;
private final double by;
private final double cx;
private final double cy;
// CHECKSTYLE: resume JavadocVariableCheck
/**
* @param rng the source of randomness
* @param a The first vertex.
* @param b The second vertex.
* @param c The third vertex.
*/
CoordinateTriangleSampler2D(UniformRandomProvider rng, double[] a, double[] b, double[] c) {
super(rng);
ax = a[0];
ay = a[1];
bx = b[0];
by = b[1];
cx = c[0];
cy = c[1];
}
@Override
protected double[] createSample(double p1msmt, double s, double t) {
return new double[] {p1msmt * ax + s * bx + t * cx,
p1msmt * ay + s * by + t * cy};
}
} }
/**
* The 3D triangle sampler.
*/
@State(Scope.Benchmark)
public static class Sampler3D extends SamplerData {
/** The sampler type. */
@Param({BASELINE, BASELINE_IF, VECTORS, COORDINATES})
private String type;
/** {@inheritDoc} */
@Override
protected int getDimension() {
return 3;
}
/** {@inheritDoc} */
@Override
protected ObjectSampler<double[]> createSampler(final UniformRandomProvider rng,
final double[] a, final double[] b, final double[] c) {
if (BASELINE.equals(type)) {
return () -> {
final double s = rng.nextDouble();
final double t = rng.nextDouble();
return new double[] {s, t, s};
};
} else if (BASELINE_IF.equals(type)) {
return () -> {
final double s = rng.nextDouble();
final double t = rng.nextDouble();
if (s + t > 1) {
return new double[] {s, t, s};
}
return new double[] {t, s, t};
};
} else if (VECTORS.equals(type)) {
return new VectorTriangleSampler3D(rng, a, b, c);
} else if (COORDINATES.equals(type)) {
return new CoordinateTriangleSampler3D(rng, a, b, c);
}
throw new IllegalStateException(UNKNOWN_SAMPLER + type);
}
/**
* Sample vectors in 3D.
*/
private static class VectorTriangleSampler3D extends VectorTriangleSampler {
// CHECKSTYLE: stop JavadocVariableCheck
private final double ax;
private final double ay;
private final double az;
private final double vx;
private final double vy;
private final double vz;
private final double wx;
private final double wy;
private final double wz;
// CHECKSTYLE: resume JavadocVariableCheck
/**
* @param rng the source of randomness
* @param a The first vertex.
* @param b The second vertex.
* @param c The third vertex.
*/
VectorTriangleSampler3D(UniformRandomProvider rng, double[] a, double[] b, double[] c) {
super(rng);
ax = a[0];
ay = a[1];
az = a[2];
vx = b[0] - ax;
vy = b[1] - ay;
vz = b[2] - az;
wx = c[0] - ax;
wy = c[1] - ay;
wz = c[2] - az;
}
@Override
protected double[] createSample(double s, double t) {
return new double[] {ax + s * vx + t * wx,
ay + s * vy + t * wy,
az + s * vz + t * wz};
}
}
/**
* Sample using coordinates in 3D.
*/
private static class CoordinateTriangleSampler3D extends CoordinateTriangleSampler {
// CHECKSTYLE: stop JavadocVariableCheck
private final double ax;
private final double ay;
private final double az;
private final double bx;
private final double by;
private final double bz;
private final double cx;
private final double cy;
private final double cz;
// CHECKSTYLE: resume JavadocVariableCheck
/**
* @param rng the source of randomness
* @param a The first vertex.
* @param b The second vertex.
* @param c The third vertex.
*/
CoordinateTriangleSampler3D(UniformRandomProvider rng, double[] a, double[] b, double[] c) {
super(rng);
ax = a[0];
ay = a[1];
az = a[2];
bx = b[0];
by = b[1];
bz = b[2];
cx = c[0];
cy = c[1];
cz = c[2];
}
@Override
protected double[] createSample(double p1msmt, double s, double t) {
return new double[] {p1msmt * ax + s * bx + t * cx,
p1msmt * ay + s * by + t * cy,
p1msmt * az + s * bz + t * cz};
}
}
}
/**
* The ND triangle sampler.
*/
@State(Scope.Benchmark)
public static class SamplerND extends SamplerData {
/** The number of dimensions. */
@Param({"2", "3", "4", "8", "16", "32"})
private int dimension;
/** The sampler type. */
@Param({BASELINE, BASELINE_IF, VECTORS, COORDINATES})
private String type;
/** {@inheritDoc} */
@Override
protected int getDimension() {
return dimension;
}
/** {@inheritDoc} */
@Override
protected ObjectSampler<double[]> createSampler(final UniformRandomProvider rng,
final double[] a, final double[] b, final double[] c) {
if (BASELINE.equals(type)) {
return () -> {
double s = rng.nextDouble();
double t = rng.nextDouble();
final double[] x = new double[a.length];
for (int i = 0; i < x.length; i++) {
x[i] = s;
s = t;
t = x[i];
}
return x;
};
} else if (BASELINE_IF.equals(type)) {
return () -> {
double s = rng.nextDouble();
double t = rng.nextDouble();
final double[] x = new double[a.length];
if (s + t > 1) {
for (int i = 0; i < x.length; i++) {
x[i] = t;
t = s;
s = x[i];
}
return x;
}
for (int i = 0; i < x.length; i++) {
x[i] = s;
s = t;
t = x[i];
}
return x;
};
} else if (VECTORS.equals(type)) {
return new VectorTriangleSamplerND(rng, a, b, c);
} else if (COORDINATES.equals(type)) {
return new CoordinateTriangleSamplerND(rng, a, b, c);
}
throw new IllegalStateException(UNKNOWN_SAMPLER + type);
}
/**
* Sample vectors in ND.
*/
private static class VectorTriangleSamplerND extends VectorTriangleSampler {
// CHECKSTYLE: stop JavadocVariableCheck
private final double[] a;
private final double[] v;
private final double[] w;
// CHECKSTYLE: resume JavadocVariableCheck
/**
* @param rng the source of randomness
* @param a The first vertex.
* @param b The second vertex.
* @param c The third vertex.
*/
VectorTriangleSamplerND(UniformRandomProvider rng, double[] a, double[] b, double[] c) {
super(rng);
this.a = a.clone();
v = new double[a.length];
w = new double[a.length];
for (int i = 0; i < a.length; i++) {
v[i] = b[i] - a[i];
w[i] = c[i] - a[i];
}
}
@Override
protected double[] createSample(double s, double t) {
final double[] x = new double[a.length];
for (int i = 0; i < x.length; i++) {
x[i] = a[i] + s * v[i] + t * w[i];
}
return x;
}
}
/**
* Sample using coordinates in ND.
*/
private static class CoordinateTriangleSamplerND extends CoordinateTriangleSampler {
// CHECKSTYLE: stop JavadocVariableCheck
private final double[] a;
private final double[] b;
private final double[] c;
// CHECKSTYLE: resume JavadocVariableCheck
/**
* @param rng the source of randomness
* @param a The first vertex.
* @param b The second vertex.
* @param c The third vertex.
*/
CoordinateTriangleSamplerND(UniformRandomProvider rng, double[] a, double[] b, double[] c) {
super(rng);
this.a = a.clone();
this.b = b.clone();
this.c = c.clone();
}
@Override
protected double[] createSample(double p1msmt, double s, double t) {
final double[] x = new double[a.length];
for (int i = 0; i < x.length; i++) {
x[i] = p1msmt * a[i] + s * b[i] + t * c[i];
}
return x;
}
}
}
/**
* Run the sampler for the configured number of samples.
*
* @param bh Data sink
* @param data Input data.
*/
private static void runSampler(Blackhole bh, SamplerData data) {
final ObjectSampler<double[]> sampler = data.getSampler();
for (int i = data.getSize() - 1; i >= 0; i--) {
bh.consume(sampler.sample());
}
}
/**
* Generation of uniform samples from a 2D triangle.
*
* @param bh Data sink
* @param data Input data.
*/
@Benchmark
public void create2D(Blackhole bh, Sampler2D data) {
runSampler(bh, data);
}
/**
* Generation of uniform samples from a 3D triangle.
*
* @param bh Data sink
* @param data Input data.
*/
@Benchmark
public void create3D(Blackhole bh, Sampler3D data) {
runSampler(bh, data);
}
/**
* Generation of uniform samples from an ND triangle.
*
* @param bh Data sink
* @param data Input data.
*/
@Benchmark
public void createND(Blackhole bh, SamplerND data) {
runSampler(bh, data);
}
}
| 2,777 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/shape/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Benchmarks for the {@code org.apache.commons.rng.sampling.shape} components.
*/
package org.apache.commons.rng.examples.jmh.sampling.shape;
| 2,778 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/distribution/GeometricSamplersPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.distribution;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.distribution.DiscreteInverseCumulativeProbabilityFunction;
import org.apache.commons.rng.sampling.distribution.DiscreteSampler;
import org.apache.commons.rng.sampling.distribution.GeometricSampler;
import org.apache.commons.rng.sampling.distribution.InverseTransformDiscreteSampler;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
/**
* Executes a benchmark to compare the speed of generation of Geometric random numbers
* using different methods.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = {"-server", "-Xms128M", "-Xmx128M"})
public class GeometricSamplersPerformance {
/**
* The value.
*
* <p>This must NOT be final!</p>
*/
private int value;
/**
* The samplers's to use for testing. Defines the RandomSource, probability of success
* and the type of Geometric sampler.
*/
@State(Scope.Benchmark)
public static class Sources {
/**
* RNG providers.
*
* <p>Use different speeds.</p>
*
* @see <a href="https://commons.apache.org/proper/commons-rng/userguide/rng.html">
* Commons RNG user guide</a>
*/
@Param({"SPLIT_MIX_64",
"MWC_256",
"JDK"})
private String randomSourceName;
/**
* The probability of success.
*/
@Param({"0.1", "0.3"})
private double probabilityOfSuccess;
/**
* The sampler type.
*/
@Param({"GeometricSampler", "InverseTransformDiscreteSampler"})
private String samplerType;
/** The sampler. */
private DiscreteSampler sampler;
/**
* @return the sampler.
*/
public DiscreteSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
final RandomSource randomSource = RandomSource.valueOf(randomSourceName);
final UniformRandomProvider rng = randomSource.create();
if ("GeometricSampler".equals(samplerType)) {
sampler = GeometricSampler.of(rng, probabilityOfSuccess);
} else {
final DiscreteInverseCumulativeProbabilityFunction geometricFunction =
new GeometricDiscreteInverseCumulativeProbabilityFunction(probabilityOfSuccess);
sampler = InverseTransformDiscreteSampler.of(rng, geometricFunction);
}
}
}
/**
* Define the inverse cumulative probability function for the Geometric distribution.
*
* <p>Adapted from org.apache.commons.math3.distribution.GeometricDistribution.
*/
private static class GeometricDiscreteInverseCumulativeProbabilityFunction
implements DiscreteInverseCumulativeProbabilityFunction {
/**
* {@code log(1 - p)} where p is the probability of success.
*/
private final double log1mProbabilityOfSuccess;
/**
* @param probabilityOfSuccess the probability of success
*/
GeometricDiscreteInverseCumulativeProbabilityFunction(double probabilityOfSuccess) {
// No validation that 0 < p <= 1
log1mProbabilityOfSuccess = Math.log1p(-probabilityOfSuccess);
}
@Override
public int inverseCumulativeProbability(double cumulativeProbability) {
// This is the equivalent of floor(log(u)/ln(1-p))
// where:
// u = cumulative probability
// p = probability of success
// See: https://en.wikipedia.org/wiki/Geometric_distribution#Related_distributions
// ---
// Note: if cumulativeProbability == 0 then log1p(-0) is zero and the result
// after the range check is 0.
// Note: if cumulativeProbability == 1 then log1p(-1) is negative infinity, the result
// of the divide is positive infinity and the result after the range check is
// Integer.MAX_VALUE.
return Math.max(0, (int) Math.ceil(Math.log1p(-cumulativeProbability) / log1mProbabilityOfSuccess - 1));
}
}
/**
* Baseline for the JMH timing overhead for production of an {@code int} value.
*
* @return the {@code int} value
*/
@Benchmark
public int baseline() {
return value;
}
/**
* Run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public int sample(Sources sources) {
return sources.getSampler().sample();
}
}
| 2,779 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/distribution/PoissonSamplersPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.distribution;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.distribution.DiscreteSampler;
import org.apache.commons.rng.sampling.distribution.KempSmallMeanPoissonSampler;
import org.apache.commons.rng.sampling.distribution.LargeMeanPoissonSampler;
import org.apache.commons.rng.sampling.distribution.SmallMeanPoissonSampler;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
/**
* Executes benchmark to compare the speed of generation of Poisson distributed random numbers.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = {"-server", "-Xms128M", "-Xmx128M"})
public class PoissonSamplersPerformance {
/**
* The value for the baseline generation of an {@code int} value.
*
* <p>This must NOT be final!</p>
*/
private int value;
/**
* The mean for the call to {@link Math#exp(double)}.
*/
@State(Scope.Benchmark)
public static class Means {
/**
* The Poisson mean. This is set at a level where the small mean sampler is to be used
* in preference to the large mean sampler.
*/
@Param({"0.25",
"0.5",
"1",
"2",
"4",
"8",
"16",
"32"})
private double mean;
/**
* Gets the mean.
*
* @return the mean
*/
public double getMean() {
return mean;
}
}
/**
* The {@link DiscreteSampler} samplers to use for testing. Creates the sampler for each
* {@link RandomSource} in the default
* {@link org.apache.commons.rng.examples.jmh.RandomSources RandomSources}.
*/
@State(Scope.Benchmark)
public static class Sources {
/**
* RNG providers.
*
* <p>Use different speeds.</p>
*
* @see <a href="https://commons.apache.org/proper/commons-rng/userguide/rng.html">
* Commons RNG user guide</a>
*/
@Param({"WELL_44497_B",
//"ISAAC",
"XO_RO_SHI_RO_128_PLUS"})
private String randomSourceName;
/**
* The sampler type.
*/
@Param({"SmallMeanPoissonSampler",
"KempSmallMeanPoissonSampler",
"BoundedKempSmallMeanPoissonSampler",
"KempSmallMeanPoissonSamplerP50",
"KempSmallMeanPoissonSamplerBinarySearch",
"KempSmallMeanPoissonSamplerGuideTable",
"LargeMeanPoissonSampler",
"TinyMeanPoissonSampler"})
private String samplerType;
/**
* The Poisson mean. This is set at a level where the small mean sampler is to be used
* in preference to the large mean sampler.
*/
@Param({"0.25",
"0.5",
"1",
"2",
"4",
"8",
"16",
"32",
"64"})
private double mean;
/** RNG. */
private UniformRandomProvider generator;
/** The factory. */
private Supplier<DiscreteSampler> factory;
/** The sampler. */
private DiscreteSampler sampler;
/**
* @return The RNG.
*/
public UniformRandomProvider getGenerator() {
return generator;
}
/**
* Gets the sampler.
*
* @return The sampler.
*/
public DiscreteSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
final RandomSource randomSource = RandomSource.valueOf(randomSourceName);
generator = randomSource.create();
if ("SmallMeanPoissonSampler".equals(samplerType)) {
factory = () -> SmallMeanPoissonSampler.of(generator, mean);
} else if ("KempSmallMeanPoissonSampler".equals(samplerType)) {
factory = () -> KempSmallMeanPoissonSampler.of(generator, mean);
} else if ("BoundedKempSmallMeanPoissonSampler".equals(samplerType)) {
factory = () -> new BoundedKempSmallMeanPoissonSampler(generator, mean);
} else if ("KempSmallMeanPoissonSamplerP50".equals(samplerType)) {
factory = () -> new KempSmallMeanPoissonSamplerP50(generator, mean);
} else if ("KempSmallMeanPoissonSamplerBinarySearch".equals(samplerType)) {
factory = () -> new KempSmallMeanPoissonSamplerBinarySearch(generator, mean);
} else if ("KempSmallMeanPoissonSamplerGuideTable".equals(samplerType)) {
factory = () -> new KempSmallMeanPoissonSamplerGuideTable(generator, mean);
} else if ("LargeMeanPoissonSampler".equals(samplerType)) {
factory = () -> LargeMeanPoissonSampler.of(generator, mean);
} else if ("TinyMeanPoissonSampler".equals(samplerType)) {
factory = () -> new TinyMeanPoissonSampler(generator, mean);
}
sampler = factory.get();
}
/**
* Creates a new instance of the sampler.
*
* @return The sampler.
*/
public DiscreteSampler createSampler() {
return factory.get();
}
}
/**
* Kemp sampler for the <a href="http://mathworld.wolfram.com/PoissonDistribution.html">Poisson
* distribution</a>.
*
* <ul>
* <li>
* For small means, a Poisson process is simulated using uniform deviates, as
* described in Kemp, A, W, (1981) Efficient Generation of Logarithmically Distributed
* Pseudo-Random Variables. Journal of the Royal Statistical Society. Vol. 30, No. 3, pp. 249-253.
* </li>
* </ul>
*
* <p>Note: This is similar to {@link KempSmallMeanPoissonSampler} but the sample is
* bounded by 1000 * mean.</p>
*
* @see <a href="https://www.jstor.org/stable/2346348">Kemp, A.W. (1981) JRSS Vol. 30, pp. 249-253</a>
*/
static class BoundedKempSmallMeanPoissonSampler
implements DiscreteSampler {
/** Underlying source of randomness. */
private final UniformRandomProvider rng;
/**
* Pre-compute {@code Math.exp(-mean)}.
* Note: This is the probability of the Poisson sample {@code p(x=0)}.
*/
private final double p0;
/** Pre-compute {@code 1000 * mean} as the upper limit of the sample. */
private final int limit;
/**
* The mean of the Poisson sample.
*/
private final double mean;
/**
* @param rng Generator of uniformly distributed random numbers.
* @param mean Mean.
* @throws IllegalArgumentException if {@code mean <= 0} or {@code mean > 700}.
*/
BoundedKempSmallMeanPoissonSampler(UniformRandomProvider rng,
double mean) {
if (mean <= 0) {
throw new IllegalArgumentException();
}
p0 = Math.exp(-mean);
if (p0 == 0) {
throw new IllegalArgumentException();
}
// The returned sample is bounded by 1000 * mean
limit = (int) Math.ceil(1000 * mean);
this.rng = rng;
this.mean = mean;
}
/** {@inheritDoc} */
@Override
public int sample() {
// Note on the algorithm:
// - X is the unknown sample deviate (the output of the algorithm)
// - x is the current value from the distribution
// - p is the probability of the current value x, p(X=x)
// - u is effectively the cumulative probability that the sample X
// is equal or above the current value x, p(X>=x)
// So if p(X>=x) > p(X=x) the sample must be above x, otherwise it is x
double u = rng.nextDouble();
int x = 0;
double p = p0;
while (u > p) {
u -= p;
// Compute the next probability using a recurrence relation.
// p(x+1) = p(x) * mean / (x+1)
p *= mean / ++x;
// The algorithm listed in Kemp (1981) does not check that the rolling probability
// is positive. This check is added to ensure a simple bounds in the event that
// p == 0
if (x == limit) {
return x;
}
}
return x;
}
}
/**
* Kemp sampler for the Poisson distribution.
*
* <p>Note: This is a modification of the original algorithm by Kemp. It implements a hedge
* on the cumulative probability set at 50%. This saves computation in half of the samples.</p>
*/
static class KempSmallMeanPoissonSamplerP50
implements DiscreteSampler {
/** The value of p=0.5. */
private static final double ONE_HALF = 0.5;
/**
* The threshold that defines the cumulative probability for the long tail of the
* Poisson distribution. Above this threshold the recurrence relation that computes the
* next probability must check that the p-value is not zero.
*/
private static final double LONG_TAIL_THRESHOLD = 0.999;
/** Underlying source of randomness. */
private final UniformRandomProvider rng;
/**
* Pre-compute {@code Math.exp(-mean)}.
* Note: This is the probability of the Poisson sample {@code p(x=0)}.
*/
private final double p0;
/**
* The mean of the Poisson sample.
*/
private final double mean;
/**
* Pre-compute the cumulative probability for all samples up to and including x.
* This is F(x) = sum of {@code p(X<=x)}.
*
* <p>The value is computed at approximately 50% allowing the algorithm to choose to start
* at value (x+1) approximately half of the time.
*/
private final double fx;
/**
* Store the value (x+1) corresponding to the next value after the cumulative probability is
* above 50%.
*/
private final int x1;
/**
* Store the probability value p(x+1), allowing the algorithm to start from the point x+1.
*/
private final double px1;
/**
* Create a new instance.
*
* <p>This is valid for means as large as approximately {@code 744}.</p>
*
* @param rng Generator of uniformly distributed random numbers.
* @param mean Mean.
* @throws IllegalArgumentException if {@code mean <= 0} or {@code Math.exp(-mean) == 0}.
*/
KempSmallMeanPoissonSamplerP50(UniformRandomProvider rng,
double mean) {
if (mean <= 0) {
throw new IllegalArgumentException();
}
this.rng = rng;
p0 = Math.exp(-mean);
this.mean = mean;
// Pre-compute a hedge value for the cumulative probability at approximately 50%.
// This is only done when p0 is less than the long tail threshold.
// The result is that the rolling probability computation should never hit the
// long tail where p reaches zero.
if (p0 <= LONG_TAIL_THRESHOLD) {
// Check the edge case for no probability
if (p0 == 0) {
throw new IllegalArgumentException();
}
double p = p0;
int x = 0;
// Sum is cumulative probability F(x) = sum p(X<=x)
double sum = p;
while (sum < ONE_HALF) {
// Compute the next probability using a recurrence relation.
// p(x+1) = p(x) * mean / (x+1)
p *= mean / ++x;
sum += p;
}
fx = sum;
x1 = x + 1;
px1 = p * mean / x1;
} else {
// Always start at zero.
// Note: If NaN is input as the mean this path is executed and the sample is always zero.
fx = 0;
x1 = 0;
px1 = p0;
}
}
/** {@inheritDoc} */
@Override
public int sample() {
// Note on the algorithm:
// - X is the unknown sample deviate (the output of the algorithm)
// - x is the current value from the distribution
// - p is the probability of the current value x, p(X=x)
// - u is effectively the cumulative probability that the sample X
// is equal or above the current value x, p(X>=x)
// So if p(X>=x) > p(X=x) the sample must be above x, otherwise it is x
final double u = rng.nextDouble();
if (u <= fx) {
// Sample from the lower half of the distribution starting at zero
return sampleBeforeLongTail(u, 0, p0);
}
// Sample from the upper half of the distribution starting at cumulative probability fx.
// This is reached when u > fx and sample X > x.
// If below the long tail threshold then omit the check on the asymptote of p -> zero
if (u <= LONG_TAIL_THRESHOLD) {
return sampleBeforeLongTail(u - fx, x1, px1);
}
return sampleWithinLongTail(u - fx, x1, px1);
}
/**
* Compute the sample assuming it is <strong>not</strong> in the long tail of the distribution.
*
* <p>This avoids a check on the next probability value assuming that the cumulative probability
* is at a level where the long tail of the Poisson distribution will not be reached.
*
* @param u the remaining cumulative probability ({@code p(X>x)})
* @param x the current sample value X
* @param p the current probability of the sample (p(X=x))
* @return the sample X
*/
private int sampleBeforeLongTail(double u, int x, double p) {
while (u > p) {
// Update the remaining cumulative probability
u -= p;
// Compute the next probability using a recurrence relation.
// p(x+1) = p(x) * mean / (x+1)
p *= mean / ++x;
// The algorithm listed in Kemp (1981) does not check that the rolling probability
// is positive (non-zero). This is omitted here on the assumption that the cumulative
// probability will not be in the long tail where the probability asymptotes to zero.
}
return x;
}
/**
* Compute the sample assuming it is in the long tail of the distribution.
*
* <p>This requires a check on the next probability value which is expected to asymptote to zero.
*
* @param u the remaining cumulative probability
* @param x the current sample value X
* @param p the current probability of the sample (p(X=x))
* @return the sample X
*/
private int sampleWithinLongTail(double u, int x, double p) {
while (u > p) {
// Update the remaining cumulative probability
u -= p;
// Compute the next probability using a recurrence relation.
// p(x+1) = p(x) * mean / (x+1)
p *= mean / ++x;
// The algorithm listed in Kemp (1981) does not check that the rolling probability
// is positive. This check is added to ensure no errors when the limit of the summation
// 1 - sum(p(x)) is above 0 due to cumulative error in floating point arithmetic when
// in the long tail of the distribution.
if (p == 0) {
return x;
}
}
return x;
}
}
/**
* Kemp sampler for the Poisson distribution.
*
* <p>Note: This is a modification of the original algorithm by Kemp. It stores the
* cumulative probability table for repeat use. The table is searched using a binary
* search algorithm.</p>
*/
static class KempSmallMeanPoissonSamplerBinarySearch
implements DiscreteSampler {
/**
* Store the cumulative probability table size for integer means so that 99.99%
* of the Poisson distribution is covered. This is done until the table size is
* 2 * mean.
*
* <p>At higher mean the expected range is mean + 4 * sqrt(mean). To avoid the sqrt
* the conservative limit of 2 * mean is used.
*/
private static final int[] TABLE_SIZE = {
/* mean 1 to 10. */
8, 10, 12, 14, 16, 18, 20, 22, 24, 25,
/* mean 11 to 20. */
27, 29, 30, 32, 33, 35, 36, 38, 39, 41,
};
/** Underlying source of randomness. */
private final UniformRandomProvider rng;
/**
* The mean of the Poisson sample.
*/
private final double mean;
/**
* Store the cumulative probability for all samples up to and including x.
* This is F(x) = sum of {@code p(X<=x)}.
*
* <p>This table is initialized to store cumulative probabilities for x up to 2 * mean
* or 99.99% (whichever is larger).
*/
private final double[] fx;
/**
* Store the value x corresponding to the last stored cumulative probability.
*/
private int lastX;
/**
* Store the probability value p(x) corresponding to last stored cumulative probability,
* allowing the algorithm to start from the point x.
*/
private double px;
/**
* Create a new instance.
*
* <p>This is valid for means as large as approximately {@code 744}.</p>
*
* @param rng Generator of uniformly distributed random numbers.
* @param mean Mean.
* @throws IllegalArgumentException if {@code mean <= 0} or {@code Math.exp(-mean) == 0}.
*/
KempSmallMeanPoissonSamplerBinarySearch(UniformRandomProvider rng,
double mean) {
if (mean <= 0) {
throw new IllegalArgumentException();
}
px = Math.exp(-mean);
if (px > 0) {
this.rng = rng;
this.mean = mean;
// Initialise the cumulative probability table.
// The supported mean where p(x=0) > 0 sets a limit of around 744 so this will always be
// possible.
final int upperMean = (int) Math.ceil(mean);
fx = new double[(upperMean < TABLE_SIZE.length) ? TABLE_SIZE[upperMean] : upperMean * 2];
fx[0] = px;
} else {
// This will catch NaN mean values
throw new IllegalArgumentException();
}
}
/** {@inheritDoc} */
@Override
public int sample() {
// Note on the algorithm:
// - X is the unknown sample deviate (the output of the algorithm)
// - x is the current value from the distribution
// - p is the probability of the current value x, p(X=x)
// - u is effectively the cumulative probability that the sample X
// is equal or above the current value x, p(X>=x)
// So if p(X>=x) > p(X=x) the sample must be above x, otherwise it is x
final double u = rng.nextDouble();
if (u <= fx[lastX]) {
// Binary search within known cumulative probability table.
// Find x so that u > f[x-1] and u <= f[x].
// This is a looser search than Arrays.binarySearch:
// - The output is x = upper.
// - The pre-condition check ensures u <= f[upper] at the start.
// - The table stores probabilities where f[0] is non-zero.
// - u should be >= 0 (or the random generator is broken).
// - It avoids comparisons using Double.doubleToLongBits.
// - It avoids the low likelihood of equality between two doubles so uses
// only 1 compare per loop.
// - It uses a weighted middle anticipating that the cumulative distribution
// is skewed as the expected use case is a small mean.
int lower = 0;
int upper = lastX;
while (lower < upper) {
// Weighted middle is 1/4 of the range between lower and upper
final int mid = (3 * lower + upper) >>> 2;
final double midVal = fx[mid];
if (u > midVal) {
// Change lower such that
// u > f[lower - 1]
lower = mid + 1;
} else {
// Change upper such that
// u <= f[upper]
upper = mid;
}
}
return upper;
}
// The sample is above x
int x1 = lastX + 1;
// Fill the cumulative probability table if possible
while (x1 < fx.length) {
// Compute the next probability using a recurrence relation.
// p(x+1) = p(x) * mean / (x+1)
px = nextProbability(px, x1);
// Compute the next cumulative probability f(x+1) and update
final double sum = fx[lastX] + px;
fx[++lastX] = sum;
// Check if this is the correct sample
if (u <= sum) {
return lastX;
}
x1 = lastX + 1;
}
// The sample is above the range of the cumulative probability table.
// Compute using the Kemp method.
// This requires the remaining cumulative probability and the probability for x+1.
return sampleWithinLongTail(u - fx[lastX], x1, nextProbability(px, x1));
}
/**
* Compute the next probability using a recurrence relation.
*
* <pre>
* p(x + 1) = p(x) * mean / (x + 1)
* </pre>
*
* @param p the probability of x
* @param x1 the value of x+1
* @return the probability of x+1
*/
private double nextProbability(double p, int x1) {
return p * mean / x1;
}
/**
* Compute the sample assuming it is in the long tail of the distribution.
*
* <p>This requires a check on the next probability value which is expected to asymptote to zero.
*
* @param u the remaining cumulative probability
* @param x the current sample value X
* @param p the current probability of the sample (p(X=x))
* @return the sample X
*/
private int sampleWithinLongTail(double u, int x, double p) {
while (u > p) {
// Update the remaining cumulative probability
u -= p;
p = nextProbability(p, ++x);
// The algorithm listed in Kemp (1981) does not check that the rolling probability
// is positive. This check is added to ensure no errors when the limit of the summation
// 1 - sum(p(x)) is above 0 due to cumulative error in floating point arithmetic when
// in the long tail of the distribution.
if (p == 0) {
return x;
}
}
return x;
}
}
/**
* Sampler for the <a href="http://mathworld.wolfram.com/PoissonDistribution.html">Poisson
* distribution</a>.
*
* <p>Note: This is a modification of the original algorithm by Kemp. It stores the
* cumulative probability table for repeat use. The table is computed dynamically and
* searched using a guide table.</p>
*/
static class KempSmallMeanPoissonSamplerGuideTable implements DiscreteSampler {
/**
* Store the cumulative probability table size for integer means so that 99.99% of the
* Poisson distribution is covered. This is done until the table size is 2 * mean.
*
* <p>At higher mean the expected range is mean + 4 * sqrt(mean). To avoid the sqrt
* the conservative limit of 2 * mean is used.
*/
private static final int[] TABLE_SIZE = {
/* mean 1 to 10. */
8, 10, 12, 14, 16, 18, 20, 22, 24, 25,
/* mean 11 to 20. */
27, 29, 30, 32, 33, 35, 36, 38, 39, 41, };
/** Underlying source of randomness. */
private final UniformRandomProvider rng;
/**
* The mean of the Poisson sample.
*/
private final double mean;
/**
* Store the cumulative probability for all samples up to and including x. This is
* F(x) = sum of {@code p(X<=x)}.
*
* <p>This table is initialized to store cumulative probabilities for x up to 2 * mean
* or 99.99% (whichever is larger).
*/
private final double[] cumulativeProbability;
/**
* Store the value x corresponding to the last stored cumulative probability.
*/
private int tabulatedX;
/**
* Store the probability value p(x), allowing the algorithm to start from the point x.
*/
private double probabilityX;
/**
* The inverse cumulative probability guide table. This is a map between the cumulative
* probability (f(x)) and the value x. It is used to set the initial point for search
* of the cumulative probability table.
*
* <p>The index into the table is obtained using {@code f(x) * guideTable.length}. The value
* stored at the index is value {@code x+1} such that it is the exclusive upper bound
* on the sample value for searching the cumulative probability table. It requires the
* table search is towards zero.</p>
*
* <p>Note: Using x+1 ensures that the table can be zero filled upon initialisation and
* any index with zero has yet to be allocated.</p>
*
* <p>The guide table should never be used when the input f(x) is above the current range of
* the cumulative probability table. This would create an index that has not been
* allocated a mapping.
*/
private final int[] guideTable;
/**
* Create a new instance.
*
* <p>This is valid for means as large as approximately {@code 744}.</p>
*
* @param rng Generator of uniformly distributed random numbers.
* @param mean Mean.
* @throws IllegalArgumentException if {@code mean <= 0} or
* {@code Math.exp(-mean) == 0}.
*/
KempSmallMeanPoissonSamplerGuideTable(UniformRandomProvider rng, double mean) {
if (mean <= 0) {
throw new IllegalArgumentException("mean is not strictly positive: " + mean);
}
probabilityX = Math.exp(-mean);
if (probabilityX > 0) {
this.rng = rng;
this.mean = mean;
// Initialise the cumulative probability table.
// The supported mean where p(x=0) > 0 sets a limit of around 744 so the cast to int
// will always be possible.
final int upperMean = (int) Math.ceil(mean);
final int size = (upperMean < TABLE_SIZE.length) ? TABLE_SIZE[upperMean] : upperMean * 2;
cumulativeProbability = new double[size];
cumulativeProbability[0] = probabilityX;
guideTable = new int[cumulativeProbability.length + 1];
initializeGuideTable(probabilityX);
} else {
// This will catch NaN mean values
throw new IllegalArgumentException("No probability for mean " + mean);
}
}
/**
* Initialise the cumulative probability guide table. All guide indices at or below the
* index corresponding to the given probability will be set to 1.
*
* @param p0 the probability for x=0
*/
private void initializeGuideTable(double p0) {
for (int index = getGuideTableIndex(p0); index >= 0; index--) {
guideTable[index] = 1;
}
}
/**
* Fill the inverse cumulative probability guide table. Set the index corresponding to the
* given probability to x+1 establishing an exclusive upper bound on x for the probability.
* All unused guide indices below the index will also be set to x+1.
*
* @param p the cumulative probability
* @param x the sample value x
*/
private void updateGuideTable(double p, int x) {
// Always set the current index as the guide table is the exclusive upper bound
// for searching the cumulative probability table for any value p.
// Then fill any lower positions that are not allocated.
final int x1 = x + 1;
int index = getGuideTableIndex(p);
do {
guideTable[index--] = x1;
} while (index > 0 && guideTable[index] == 0);
}
/**
* Gets the guide table index for the probability. This is obtained using
* {@code p * (guideTable.length - 1)} so is inside the length of the table.
*
* @param p the cumulative probability
* @return the guide table index
*/
private int getGuideTableIndex(double p) {
// Note: This is only ever called when p is in the range of the cumulative
// probability table. So assume 0 <= p <= 1.
return (int) (p * (guideTable.length - 1));
}
/** {@inheritDoc} */
@Override
public int sample() {
// Note on the algorithm:
// 1. Compute a cumulative probability with a uniform deviate (u).
// 2. If the probability lies within the tabulated cumulative probabilities
// then find the sample value.
// 3. If possible expand the tabulated cumulative probabilities up to the value u.
// 4. If value u exceeds the capacity for the tabulated cumulative probabilities
// then compute the sample value dynamically without storing the probabilities.
// Compute a probability
final double u = rng.nextDouble();
// Check the tabulated cumulative probability table
if (u <= cumulativeProbability[tabulatedX]) {
// Initialise the search using a guide table to find an initial guess.
// The table provides an upper bound on the sample for a known cumulative probability.
int sample = guideTable[getGuideTableIndex(u)] - 1;
// If u is above the sample probability (this occurs due to truncation)
// then return the next value up.
if (u > cumulativeProbability[sample]) {
return sample + 1;
}
// Search down
while (sample != 0 && u <= cumulativeProbability[sample - 1]) {
sample--;
}
return sample;
}
// The sample is above the tabulated cumulative probability for x
int x1 = tabulatedX + 1;
// Fill the cumulative probability table if possible
while (x1 < cumulativeProbability.length) {
probabilityX = nextProbability(probabilityX, x1);
// Compute the next cumulative probability f(x+1) and update
final double sum = cumulativeProbability[tabulatedX] + probabilityX;
cumulativeProbability[++tabulatedX] = sum;
updateGuideTable(sum, tabulatedX);
// Check if this is the correct sample
if (u <= sum) {
return tabulatedX;
}
x1 = tabulatedX + 1;
}
// The sample is above the range of the cumulative probability table.
// Compute using the Kemp method.
// This requires the remaining cumulative probability and the probability for x+1.
return sampleWithinLongTail(u - cumulativeProbability[tabulatedX], x1, nextProbability(probabilityX, x1));
}
/**
* Compute the next probability using a recurrence relation.
*
* <pre>
* p(x + 1) = p(x) * mean / (x + 1)
* </pre>
*
* @param px the probability of x
* @param x1 the value of x+1
* @return the probability of x+1
*/
private double nextProbability(double px, int x1) {
return px * mean / x1;
}
/**
* Compute the sample assuming it is in the long tail of the distribution.
*
* <p>This requires a check on the next probability value which is expected to
* asymptote to zero.
*
* @param u the remaining cumulative probability
* @param x the current sample value X
* @param p the current probability of the sample (p(X=x))
* @return the sample X
*/
private int sampleWithinLongTail(double u, int x, double p) {
// Note on the algorithm:
// - X is the unknown sample deviate (the output of the algorithm)
// - x is the current value from the distribution
// - p is the probability of the current value x, p(X=x)
// - u is effectively the cumulative probability that the sample X
// is equal or above the current value x, p(X>=x)
// So if p(X>=x) > p(X=x) the sample must be above x, otherwise it is x
while (u > p) {
// Update the remaining cumulative probability
u -= p;
p = nextProbability(p, ++x);
// The algorithm listed in Kemp (1981) does not check that the rolling
// probability is positive. This check is added to ensure no errors when the
// limit of the summation 1 - sum(p(x)) is above 0 due to cumulative error in
// floating point arithmetic when in the long tail of the distribution.
if (p == 0) {
break;
}
}
return x;
}
}
/**
* Sampler for the <a href="http://mathworld.wolfram.com/PoissonDistribution.html">Poisson distribution</a>.
*
* <ul>
* <li>
* For small means, a Poisson process is simulated using uniform deviates, as
* described in Knuth (1969). Seminumerical Algorithms. The Art of Computer Programming,
* Volume 2. Addison Wesley.
* </li>
* </ul>
*
* <p>This sampler is suitable for {@code mean < 20}.</p>
*
* <p>Sampling uses {@link UniformRandomProvider#nextInt()} and 32-bit integer arithmetic.</p>
*
* @see <a href="https://en.wikipedia.org/wiki/Poisson_distribution#Generating_Poisson-distributed_random_variables">
* Poisson random variables</a>
*/
static class TinyMeanPoissonSampler
implements DiscreteSampler {
/** Pre-compute Poisson probability p(n=0) mapped to the range of a 32-bit unsigned fraction. */
private final long p0;
/** Underlying source of randomness. */
private final UniformRandomProvider rng;
/**
* @param rng Generator of uniformly distributed random numbers.
* @param mean Mean.
* @throws IllegalArgumentException if {@code mean <= 0} or {@code Math.exp(-mean) * (1L << 32)}
* is not positive.
*/
TinyMeanPoissonSampler(UniformRandomProvider rng,
double mean) {
this.rng = rng;
if (mean <= 0) {
throw new IllegalArgumentException();
}
// Math.exp(-mean) is the probability of a Poisson distribution for n=0 (p(n=0)).
// This is mapped to a 32-bit range as the numerator of a 32-bit fraction
// for use in optimised 32-bit arithmetic.
p0 = (long) (Math.exp(-mean) * 0x100000000L);
if (p0 == 0) {
throw new IllegalArgumentException("No p(x=0) probability for mean: " + mean);
}
}
/** {@inheritDoc} */
@Override
public int sample() {
int n = 0;
// The unsigned 32-bit sample represents the fraction x / 2^32 where x is [0,2^32-1].
// The upper bound is exclusive hence the fraction is a uniform deviate from [0,1).
long r = nextUnsigned32();
// The limit is the probability p(n=0) converted to an unsigned fraction.
while (r >= p0) {
// Compute the fraction:
// r [0,2^32) 2^32
// ---- * -------- / ----
// 2^32 2^32 2^32
// This rounds down the fraction numerator when the lower 32-bits are discarded.
r = (r * nextUnsigned32()) >>> 32;
n++;
}
// Ensure the value is positive in the worst case scenario of a broken
// generator that returns 0xffffffff for each sample. This will cause
// the integer counter to overflow 2^31-1 but not exceed 2^32. The fraction
// multiplication effectively turns r into a counter decrementing from 2^32-1
// to zero.
return (n >= 0) ? n : Integer.MAX_VALUE;
}
/**
* Get the next unsigned 32-bit random integer.
*
* @return the random integer
*/
private long nextUnsigned32() {
return rng.nextInt() & 0xffffffffL;
}
}
// Benchmarks methods below.
/**
* Baseline for the JMH timing overhead for production of an {@code int} value.
*
* @return the {@code int} value
*/
@Benchmark
public int baselineInt() {
return value;
}
/**
* Baseline for {@link Math#exp(double)}.
*
* @param mean the mean
* @return the value
*/
@Benchmark
public double baselineExp(Means mean) {
return Math.exp(-mean.getMean());
}
/**
* Run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public int sample(Sources sources) {
return sources.getSampler().sample();
}
/**
* Run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public int singleSample(Sources sources) {
return sources.createSampler().sample();
}
}
| 2,780 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/distribution/ContinuousSamplersPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.distribution;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.examples.jmh.RandomSources;
import org.apache.commons.rng.sampling.distribution.AhrensDieterExponentialSampler;
import org.apache.commons.rng.sampling.distribution.AhrensDieterMarsagliaTsangGammaSampler;
import org.apache.commons.rng.sampling.distribution.BoxMullerNormalizedGaussianSampler;
import org.apache.commons.rng.sampling.distribution.ChengBetaSampler;
import org.apache.commons.rng.sampling.distribution.ContinuousSampler;
import org.apache.commons.rng.sampling.distribution.ContinuousUniformSampler;
import org.apache.commons.rng.sampling.distribution.InverseTransformParetoSampler;
import org.apache.commons.rng.sampling.distribution.LevySampler;
import org.apache.commons.rng.sampling.distribution.LogNormalSampler;
import org.apache.commons.rng.sampling.distribution.MarsagliaNormalizedGaussianSampler;
import org.apache.commons.rng.sampling.distribution.StableSampler;
import org.apache.commons.rng.sampling.distribution.TSampler;
import org.apache.commons.rng.sampling.distribution.ZigguratSampler;
import org.apache.commons.rng.sampling.distribution.ZigguratNormalizedGaussianSampler;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
/**
* Executes benchmark to compare the speed of generation of random numbers
* from the various source providers for different types of {@link ContinuousSampler}.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = {"-server", "-Xms128M", "-Xmx128M"})
public class ContinuousSamplersPerformance {
/**
* The value.
*
* <p>This must NOT be final!</p>
*/
private double value;
/**
* The {@link ContinuousSampler} samplers to use for testing. Creates the sampler for each
* {@link org.apache.commons.rng.simple.RandomSource RandomSource} in the default
* {@link RandomSources}.
*/
@State(Scope.Benchmark)
public static class Sources extends RandomSources {
/**
* The sampler type.
*/
@Param({"BoxMullerNormalizedGaussianSampler",
"MarsagliaNormalizedGaussianSampler",
"ZigguratNormalizedGaussianSampler",
"ZigguratSampler.NormalizedGaussian",
"AhrensDieterExponentialSampler",
"ZigguratSampler.Exponential",
"AhrensDieterGammaSampler",
"MarsagliaTsangGammaSampler",
"LevySampler",
"LogNormalBoxMullerNormalizedGaussianSampler",
"LogNormalMarsagliaNormalizedGaussianSampler",
"LogNormalZigguratNormalizedGaussianSampler",
"LogNormalSampler.ZigguratSampler.NormalizedGaussian",
"ChengBetaSampler",
"ContinuousUniformSampler",
"InverseTransformParetoSampler",
"StableSampler",
"TSampler"})
private String samplerType;
/** The sampler. */
private ContinuousSampler sampler;
/**
* @return the sampler.
*/
public ContinuousSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Override
@Setup
public void setup() {
super.setup();
final UniformRandomProvider rng = getGenerator();
if ("BoxMullerNormalizedGaussianSampler".equals(samplerType)) {
sampler = BoxMullerNormalizedGaussianSampler.of(rng);
} else if ("MarsagliaNormalizedGaussianSampler".equals(samplerType)) {
sampler = MarsagliaNormalizedGaussianSampler.of(rng);
} else if ("ZigguratNormalizedGaussianSampler".equals(samplerType)) {
sampler = ZigguratNormalizedGaussianSampler.of(rng);
} else if ("ZigguratSampler.NormalizedGaussian".equals(samplerType)) {
sampler = ZigguratSampler.NormalizedGaussian.of(rng);
} else if ("AhrensDieterExponentialSampler".equals(samplerType)) {
sampler = AhrensDieterExponentialSampler.of(rng, 4.56);
} else if ("ZigguratSampler.Exponential".equals(samplerType)) {
sampler = ZigguratSampler.Exponential.of(rng, 4.56);
} else if ("AhrensDieterGammaSampler".equals(samplerType)) {
// This tests the Ahrens-Dieter algorithm since alpha < 1
sampler = AhrensDieterMarsagliaTsangGammaSampler.of(rng, 0.76, 9.8);
} else if ("MarsagliaTsangGammaSampler".equals(samplerType)) {
// This tests the Marsaglia-Tsang algorithm since alpha > 1
sampler = AhrensDieterMarsagliaTsangGammaSampler.of(rng, 12.34, 9.8);
} else if ("LevySampler".equals(samplerType)) {
sampler = LevySampler.of(rng, 1.23, 4.56);
} else if ("LogNormalBoxMullerNormalizedGaussianSampler".equals(samplerType)) {
sampler = LogNormalSampler.of(BoxMullerNormalizedGaussianSampler.of(rng), 12.3, 4.6);
} else if ("LogNormalMarsagliaNormalizedGaussianSampler".equals(samplerType)) {
sampler = LogNormalSampler.of(MarsagliaNormalizedGaussianSampler.of(rng), 12.3, 4.6);
} else if ("LogNormalZigguratNormalizedGaussianSampler".equals(samplerType)) {
sampler = LogNormalSampler.of(ZigguratNormalizedGaussianSampler.of(rng), 12.3, 4.6);
} else if ("LogNormalSampler.ZigguratSampler.NormalizedGaussian".equals(samplerType)) {
sampler = LogNormalSampler.of(ZigguratSampler.NormalizedGaussian.of(rng), 12.3, 4.6);
} else if ("ChengBetaSampler".equals(samplerType)) {
sampler = ChengBetaSampler.of(rng, 0.45, 6.7);
} else if ("ContinuousUniformSampler".equals(samplerType)) {
sampler = ContinuousUniformSampler.of(rng, 123.4, 5678.9);
} else if ("InverseTransformParetoSampler".equals(samplerType)) {
sampler = InverseTransformParetoSampler.of(rng, 23.45, 0.1234);
} else if ("StableSampler".equals(samplerType)) {
sampler = StableSampler.of(rng, 1.3, 0.2);
} else if ("TSampler".equals(samplerType)) {
sampler = TSampler.of(rng, 1.23);
}
}
}
// Benchmarks methods below.
/**
* Baseline for the JMH timing overhead for production of an {@code double} value.
*
* @return the {@code double} value
*/
@Benchmark
public double baseline() {
return value;
}
/**
* Run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public double sample(Sources sources) {
return sources.getSampler().sample();
}
}
| 2,781 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/distribution/NextGaussianPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.distribution;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.examples.jmh.RandomSources;
import org.apache.commons.rng.sampling.distribution.BoxMullerNormalizedGaussianSampler;
import org.apache.commons.rng.sampling.distribution.MarsagliaNormalizedGaussianSampler;
import org.apache.commons.rng.sampling.distribution.NormalizedGaussianSampler;
import org.apache.commons.rng.sampling.distribution.ZigguratNormalizedGaussianSampler;
import org.apache.commons.rng.sampling.distribution.ZigguratSampler;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import java.util.concurrent.TimeUnit;
import java.util.Random;
/**
* Benchmark to compare the speed of generation of normally-distributed random
* numbers of {@link Random#nextGaussian()} against implementations of
* {@link NormalizedGaussianSampler}.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = {"-server", "-Xms128M", "-Xmx128M"})
public class NextGaussianPerformance {
/**
* The value.
*
* <p>This must NOT be final!</p>
*/
private double value;
/**
* The {@link Random} to use for testing.
* This uses a non-final instance created for the benchmark to make a fair comparison
* to the other Gaussian samplers by using the same setup and sampler access.
*/
@State(Scope.Benchmark)
public static class JDKSource {
/** JDK's generator. */
private Random random;
/**
* @return the sampler.
*/
public Random getSampler() {
return random;
}
/** Instantiates sampler. */
@Setup
public void setup() {
random = new Random();
}
}
/**
* The {@link NormalizedGaussianSampler} samplers to use for testing. Creates the sampler for each
* {@link org.apache.commons.rng.simple.RandomSource RandomSource} in the default
* {@link RandomSources}.
*/
@State(Scope.Benchmark)
public static class Sources extends RandomSources {
/** The sampler type. */
@Param({"BoxMullerNormalizedGaussianSampler",
"MarsagliaNormalizedGaussianSampler",
"ZigguratNormalizedGaussianSampler",
"ZigguratSampler.NormalizedGaussian"})
private String samplerType;
/** The sampler. */
private NormalizedGaussianSampler sampler;
/**
* @return the sampler.
*/
public NormalizedGaussianSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Override
@Setup
public void setup() {
super.setup();
final UniformRandomProvider rng = getGenerator();
if ("BoxMullerNormalizedGaussianSampler".equals(samplerType)) {
sampler = BoxMullerNormalizedGaussianSampler.of(rng);
} else if ("MarsagliaNormalizedGaussianSampler".equals(samplerType)) {
sampler = MarsagliaNormalizedGaussianSampler.of(rng);
} else if ("ZigguratNormalizedGaussianSampler".equals(samplerType)) {
sampler = ZigguratNormalizedGaussianSampler.of(rng);
} else if ("ZigguratSampler.NormalizedGaussian".equals(samplerType)) {
sampler = ZigguratSampler.NormalizedGaussian.of(rng);
} else {
throw new IllegalStateException("Unknown sampler type: " + samplerType);
}
}
}
/**
* Baseline for the JMH timing overhead for production of an {@code double} value.
*
* @return the {@code double} value
*/
@Benchmark
public double baseline() {
return value;
}
/**
* Run JDK {@link Random} gaussian sampler.
*
* @param source Source of randomness.
* @return the sample value
*/
@Benchmark
public double sampleJDK(JDKSource source) {
return source.getSampler().nextGaussian();
}
/**
* Run the {@link NormalizedGaussianSampler} sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public double sample(Sources sources) {
return sources.getSampler().sample();
}
}
| 2,782 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/distribution/EnumeratedDistributionSamplersPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.distribution;
import org.apache.commons.math3.distribution.BinomialDistribution;
import org.apache.commons.math3.distribution.IntegerDistribution;
import org.apache.commons.math3.distribution.PoissonDistribution;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.distribution.AliasMethodDiscreteSampler;
import org.apache.commons.rng.sampling.distribution.DirichletSampler;
import org.apache.commons.rng.sampling.distribution.DiscreteSampler;
import org.apache.commons.rng.sampling.distribution.FastLoadedDiceRollerDiscreteSampler;
import org.apache.commons.rng.sampling.distribution.GuideTableDiscreteSampler;
import org.apache.commons.rng.sampling.distribution.MarsagliaTsangWangDiscreteSampler;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
/**
* Executes benchmark to compare the speed of generation of random numbers from an enumerated
* discrete probability distribution.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = {"-server", "-Xms128M", "-Xmx128M"})
public class EnumeratedDistributionSamplersPerformance {
/**
* The value for the baseline generation of an {@code int} value.
*
* <p>This must NOT be final!</p>
*/
private int value;
/**
* The random sources to use for testing. This is a smaller list than all the possible
* random sources; the list is composed of generators of different speeds.
*/
@State(Scope.Benchmark)
public static class LocalRandomSources {
/**
* RNG providers.
*
* <p>Use different speeds.</p>
*
* @see <a href="https://commons.apache.org/proper/commons-rng/userguide/rng.html">
* Commons RNG user guide</a>
*/
@Param({"WELL_44497_B",
"ISAAC",
"XO_RO_SHI_RO_128_PLUS"})
private String randomSourceName;
/** RNG. */
private UniformRandomProvider generator;
/**
* @return the RNG.
*/
public UniformRandomProvider getGenerator() {
return generator;
}
/** Create the random source. */
@Setup
public void setup() {
final RandomSource randomSource = RandomSource.valueOf(randomSourceName);
generator = randomSource.create();
}
}
/**
* The {@link DiscreteSampler} samplers to use for testing. Creates the sampler for each
* random source.
*
* <p>This class is abstract. The probability distribution is created by implementations.</p>
*/
@State(Scope.Benchmark)
public abstract static class SamplerSources extends LocalRandomSources {
/**
* The sampler type.
*/
@Param({"BinarySearchDiscreteSampler",
"AliasMethodDiscreteSampler",
"GuideTableDiscreteSampler",
"MarsagliaTsangWangDiscreteSampler",
"FastLoadedDiceRollerDiscreteSampler",
"FastLoadedDiceRollerDiscreteSamplerLong",
"FastLoadedDiceRollerDiscreteSampler53",
// Uncomment to test non-default parameters
//"AliasMethodDiscreteSamplerNoPad", // Not optimal for sampling
//"AliasMethodDiscreteSamplerAlpha1",
//"AliasMethodDiscreteSamplerAlpha2",
// The AliasMethod memory requirement doubles for each alpha increment.
// A fair comparison is to use 2^alpha for the equivalent guide table method.
//"GuideTableDiscreteSamplerAlpha2",
//"GuideTableDiscreteSamplerAlpha4",
})
private String samplerType;
/** The factory. */
private Supplier<DiscreteSampler> factory;
/** The sampler. */
private DiscreteSampler sampler;
/**
* Gets the sampler.
*
* @return the sampler.
*/
public DiscreteSampler getSampler() {
return sampler;
}
/** Create the distribution (per iteration as it may vary) and instantiates sampler. */
@Override
@Setup(Level.Iteration)
public void setup() {
super.setup();
final double[] probabilities = createProbabilities();
createSamplerFactory(getGenerator(), probabilities);
sampler = factory.get();
}
/**
* Creates the probabilities for the distribution.
*
* @return The probabilities.
*/
protected abstract double[] createProbabilities();
/**
* Creates the sampler factory.
*
* @param rng The random generator.
* @param probabilities The probabilities.
*/
private void createSamplerFactory(final UniformRandomProvider rng,
final double[] probabilities) {
if ("BinarySearchDiscreteSampler".equals(samplerType)) {
factory = () -> new BinarySearchDiscreteSampler(rng, probabilities);
} else if ("AliasMethodDiscreteSampler".equals(samplerType)) {
factory = () -> AliasMethodDiscreteSampler.of(rng, probabilities);
} else if ("AliasMethodDiscreteSamplerNoPad".equals(samplerType)) {
factory = () -> AliasMethodDiscreteSampler.of(rng, probabilities, -1);
} else if ("AliasMethodDiscreteSamplerAlpha1".equals(samplerType)) {
factory = () -> AliasMethodDiscreteSampler.of(rng, probabilities, 1);
} else if ("AliasMethodDiscreteSamplerAlpha2".equals(samplerType)) {
factory = () -> AliasMethodDiscreteSampler.of(rng, probabilities, 2);
} else if ("GuideTableDiscreteSampler".equals(samplerType)) {
factory = () -> GuideTableDiscreteSampler.of(rng, probabilities);
} else if ("GuideTableDiscreteSamplerAlpha2".equals(samplerType)) {
factory = () -> GuideTableDiscreteSampler.of(rng, probabilities, 2);
} else if ("GuideTableDiscreteSamplerAlpha8".equals(samplerType)) {
factory = () -> GuideTableDiscreteSampler.of(rng, probabilities, 8);
} else if ("MarsagliaTsangWangDiscreteSampler".equals(samplerType)) {
factory = () -> MarsagliaTsangWangDiscreteSampler.Enumerated.of(rng, probabilities);
} else if ("FastLoadedDiceRollerDiscreteSampler".equals(samplerType)) {
factory = () -> FastLoadedDiceRollerDiscreteSampler.of(rng, probabilities);
} else if ("FastLoadedDiceRollerDiscreteSamplerLong".equals(samplerType)) {
// Avoid exact floating-point arithmetic in construction.
// Frequencies must sum to less than 2^63; here the sum is ~2^62.
// This conversion may omit very small probabilities.
final double sum = Arrays.stream(probabilities).sum();
final long[] frequencies = Arrays.stream(probabilities)
.mapToLong(x -> Math.round(0x1.0p62 * x / sum))
.toArray();
factory = () -> FastLoadedDiceRollerDiscreteSampler.of(rng, frequencies);
} else if ("FastLoadedDiceRollerDiscreteSampler53".equals(samplerType)) {
factory = () -> FastLoadedDiceRollerDiscreteSampler.of(rng, probabilities, 53);
} else {
throw new IllegalStateException();
}
}
/**
* Creates a new instance of the sampler.
*
* @return The sampler.
*/
public DiscreteSampler createSampler() {
return factory.get();
}
}
/**
* Define known probability distributions for testing. These are expected to have well
* behaved cumulative probability functions.
*/
@State(Scope.Benchmark)
public static class KnownDistributionSources extends SamplerSources {
/** The cumulative probability limit for unbounded distributions. */
private static final double CUMULATIVE_PROBABILITY_LIMIT = 1 - 1e-9;
/** Binomial distribution number of trials. */
private static final int BINOM_N = 67;
/** Binomial distribution probability of success. */
private static final double BINOM_P = 0.7;
/** Geometric distribution probability of success. */
private static final double GEO_P = 0.2;
/** Poisson distribution mean. */
private static final double POISS_MEAN = 3.22;
/** Bimodal distribution mean 1. */
private static final double BIMOD_MEAN1 = 10;
/** Bimodal distribution mean 1. */
private static final double BIMOD_MEAN2 = 20;
/**
* The distribution.
*/
@Param({"Binomial_N67_P0.7",
"Geometric_P0.2",
"4SidedLoadedDie",
"Poisson_Mean3.22",
"Poisson_Mean10_Mean20"})
private String distribution;
/** {@inheritDoc} */
@Override
protected double[] createProbabilities() {
if ("Binomial_N67_P0.7".equals(distribution)) {
final BinomialDistribution dist = new BinomialDistribution(null, BINOM_N, BINOM_P);
return createProbabilities(dist, 0, BINOM_N);
} else if ("Geometric_P0.2".equals(distribution)) {
final double probabilityOfFailure = 1 - GEO_P;
// https://en.wikipedia.org/wiki/Geometric_distribution
// PMF = (1-p)^k * p
// k is number of failures before a success
double p = 1.0; // (1-p)^0
// Build until the cumulative function is big
double[] probabilities = new double[100];
double sum = 0;
int k = 0;
while (k < probabilities.length) {
probabilities[k] = p * GEO_P;
sum += probabilities[k++];
if (sum > CUMULATIVE_PROBABILITY_LIMIT) {
break;
}
// For the next PMF
p *= probabilityOfFailure;
}
return Arrays.copyOf(probabilities, k);
} else if ("4SidedLoadedDie".equals(distribution)) {
return new double[] {1.0 / 2, 1.0 / 3, 1.0 / 12, 1.0 / 12};
} else if ("Poisson_Mean3.22".equals(distribution)) {
final IntegerDistribution dist = createPoissonDistribution(POISS_MEAN);
final int max = dist.inverseCumulativeProbability(CUMULATIVE_PROBABILITY_LIMIT);
return createProbabilities(dist, 0, max);
} else if ("Poisson_Mean10_Mean20".equals(distribution)) {
// Create a Bimodel using two Poisson distributions
final IntegerDistribution dist1 = createPoissonDistribution(BIMOD_MEAN2);
final int max = dist1.inverseCumulativeProbability(CUMULATIVE_PROBABILITY_LIMIT);
final double[] p1 = createProbabilities(dist1, 0, max);
final double[] p2 = createProbabilities(createPoissonDistribution(BIMOD_MEAN1), 0, max);
for (int i = 0; i < p1.length; i++) {
p1[i] += p2[i];
}
// Leave to the distribution to normalise the sum
return p1;
}
throw new IllegalStateException();
}
/**
* Creates the poisson distribution.
*
* @param mean the mean
* @return the distribution
*/
private static IntegerDistribution createPoissonDistribution(double mean) {
return new PoissonDistribution(null, mean,
PoissonDistribution.DEFAULT_EPSILON, PoissonDistribution.DEFAULT_MAX_ITERATIONS);
}
/**
* Creates the probabilities from the distribution.
*
* @param dist the distribution
* @param lower the lower bounds (inclusive)
* @param upper the upper bounds (inclusive)
* @return the probabilities
*/
private static double[] createProbabilities(IntegerDistribution dist, int lower, int upper) {
double[] probabilities = new double[upper - lower + 1];
int index = 0;
for (int x = lower; x <= upper; x++) {
probabilities[index++] = dist.probability(x);
}
return probabilities;
}
}
/**
* Define random probability distributions of known size for testing. These are random but
* the average cumulative probability function will be a straight line given the increment
* average is 0.5.
*/
@State(Scope.Benchmark)
public static class RandomDistributionSources extends SamplerSources {
/**
* The distribution size.
* These are spaced half-way between powers-of-2 to minimise the advantage of
* padding by the Alias method sampler.
*/
@Param({"6",
//"12",
//"24",
//"48",
"96",
//"192",
//"384",
// Above 2048 forces the Alias method to use more than 64-bits for sampling
"3072"})
private int randomNonUniformSize;
/** {@inheritDoc} */
@Override
protected double[] createProbabilities() {
return RandomSource.XO_RO_SHI_RO_128_PP.create()
.doubles(randomNonUniformSize).toArray();
}
}
/**
* Sample random probability arrays from a Dirichlet distribution.
*
* <p>The distribution ensures the probabilities sum to 1.
* The <a href="https://en.wikipedia.org/wiki/Entropy_(information_theory)">entropy</a>
* of the probabilities increases with parameters k and alpha.
* The following shows the mean and sd of the entropy from 100 samples
* for a range of parameters.
* <pre>
* k alpha mean sd
* 4 0.500 1.299 0.374
* 4 1.000 1.531 0.294
* 4 2.000 1.754 0.172
* 8 0.500 2.087 0.348
* 8 1.000 2.490 0.266
* 8 2.000 2.707 0.142
* 16 0.500 3.023 0.287
* 16 1.000 3.454 0.166
* 16 2.000 3.693 0.095
* 32 0.500 4.008 0.182
* 32 1.000 4.406 0.125
* 32 2.000 4.692 0.075
* 64 0.500 4.986 0.151
* 64 1.000 5.392 0.115
* 64 2.000 5.680 0.048
* </pre>
*/
@State(Scope.Benchmark)
public static class DirichletDistributionSources extends SamplerSources {
/** Number of categories. */
@Param({"4", "8", "16"})
private int k;
/** Concentration parameter. */
@Param({"0.5", "1", "2"})
private double alpha;
/** {@inheritDoc} */
@Override
protected double[] createProbabilities() {
return DirichletSampler.symmetric(RandomSource.XO_RO_SHI_RO_128_PP.create(),
k, alpha).sample();
}
}
/**
* The {@link FastLoadedDiceRollerDiscreteSampler} samplers to use for testing.
* Creates the sampler for each random source and the probabilities using
* a Dirichlet distribution.
*
* <p>This class is a specialized source to allow examination of the effect of the
* {@link FastLoadedDiceRollerDiscreteSampler} {@code alpha} parameter.
*/
@State(Scope.Benchmark)
public static class FastLoadedDiceRollerDiscreteSamplerSources extends LocalRandomSources {
/** Number of categories. */
@Param({"4", "8", "16"})
private int k;
/** Concentration parameter. */
@Param({"0.5", "1", "2"})
private double concentration;
/** The constructor {@code alpha} parameter. */
@Param({"0", "30", "53"})
private int alpha;
/** The factory. */
private Supplier<DiscreteSampler> factory;
/** The sampler. */
private DiscreteSampler sampler;
/**
* Gets the sampler.
*
* @return the sampler.
*/
public DiscreteSampler getSampler() {
return sampler;
}
/** Create the distribution probabilities (per iteration as it may vary), the sampler
* factory and instantiates sampler. */
@Override
@Setup(Level.Iteration)
public void setup() {
super.setup();
final double[] probabilities =
DirichletSampler.symmetric(RandomSource.XO_RO_SHI_RO_128_PP.create(),
k, concentration).sample();
final UniformRandomProvider rng = getGenerator();
factory = () -> FastLoadedDiceRollerDiscreteSampler.of(rng, probabilities, alpha);
sampler = factory.get();
}
/**
* Creates a new instance of the sampler.
*
* @return The sampler.
*/
public DiscreteSampler createSampler() {
return factory.get();
}
}
/**
* Compute a sample by binary search of the cumulative probability distribution.
*/
static final class BinarySearchDiscreteSampler
implements DiscreteSampler {
/** Underlying source of randomness. */
private final UniformRandomProvider rng;
/**
* The cumulative probability table.
*/
private final double[] cumulativeProbabilities;
/**
* @param rng Generator of uniformly distributed random numbers.
* @param probabilities The probabilities.
* @throws IllegalArgumentException if {@code probabilities} is null or empty, a
* probability is negative, infinite or {@code NaN}, or the sum of all
* probabilities is not strictly positive.
*/
BinarySearchDiscreteSampler(UniformRandomProvider rng,
double[] probabilities) {
// Minimal set-up validation
if (probabilities == null || probabilities.length == 0) {
throw new IllegalArgumentException("Probabilities must not be empty.");
}
final int size = probabilities.length;
cumulativeProbabilities = new double[size];
double sumProb = 0;
int count = 0;
for (final double prob : probabilities) {
if (prob < 0 ||
Double.isInfinite(prob) ||
Double.isNaN(prob)) {
throw new IllegalArgumentException("Invalid probability: " +
prob);
}
// Compute and store cumulative probability.
sumProb += prob;
cumulativeProbabilities[count++] = sumProb;
}
if (Double.isInfinite(sumProb) || sumProb <= 0) {
throw new IllegalArgumentException("Invalid sum of probabilities: " + sumProb);
}
this.rng = rng;
// Normalise cumulative probability.
for (int i = 0; i < size; i++) {
final double norm = cumulativeProbabilities[i] / sumProb;
cumulativeProbabilities[i] = (norm < 1) ? norm : 1.0;
}
}
/** {@inheritDoc} */
@Override
public int sample() {
final double u = rng.nextDouble();
// Java binary search
//int index = Arrays.binarySearch(cumulativeProbabilities, u);
//if (index < 0) {
// index = -index - 1;
//}
//
//return index < cumulativeProbabilities.length ?
// index :
// cumulativeProbabilities.length - 1;
// Binary search within known cumulative probability table.
// Find x so that u > f[x-1] and u <= f[x].
// This is a looser search than Arrays.binarySearch:
// - The output is x = upper.
// - The table stores probabilities where f[0] is >= 0 and the max == 1.0.
// - u should be >= 0 and <= 1 (or the random generator is broken).
// - It avoids comparisons using Double.doubleToLongBits.
// - It avoids the low likelihood of equality between two doubles for fast exit
// so uses only 1 compare per loop.
int lower = 0;
int upper = cumulativeProbabilities.length - 1;
while (lower < upper) {
final int mid = (lower + upper) >>> 1;
final double midVal = cumulativeProbabilities[mid];
if (u > midVal) {
// Change lower such that
// u > f[lower - 1]
lower = mid + 1;
} else {
// Change upper such that
// u <= f[upper]
upper = mid;
}
}
return upper;
}
}
// Benchmarks methods below.
/**
* Baseline for the JMH timing overhead for production of an {@code int} value.
*
* @return the {@code int} value
*/
@Benchmark
public int baselineInt() {
return value;
}
/**
* Baseline for the production of a {@code double} value.
* This is used to assess the performance of the underlying random source.
*
* @param sources Source of randomness.
* @return the {@code int} value
*/
@Benchmark
public int baselineNextDouble(LocalRandomSources sources) {
return sources.getGenerator().nextDouble() < 0.5 ? 1 : 0;
}
/**
* Run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public int sampleKnown(KnownDistributionSources sources) {
return sources.getSampler().sample();
}
/**
* Create and run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public int singleSampleKnown(KnownDistributionSources sources) {
return sources.createSampler().sample();
}
/**
* Run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public int sampleRandom(RandomDistributionSources sources) {
return sources.getSampler().sample();
}
/**
* Create and run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public int singleSampleRandom(RandomDistributionSources sources) {
return sources.createSampler().sample();
}
/**
* Run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public int sampleDirichlet(DirichletDistributionSources sources) {
return sources.getSampler().sample();
}
/**
* Create and run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public int singleSampleDirichlet(DirichletDistributionSources sources) {
return sources.createSampler().sample();
}
/**
* Run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public int sampleFast(FastLoadedDiceRollerDiscreteSamplerSources sources) {
return sources.getSampler().sample();
}
/**
* Create and run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public int singleSampleFast(FastLoadedDiceRollerDiscreteSamplerSources sources) {
return sources.createSampler().sample();
}
}
| 2,783 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/distribution/AliasMethodDiscreteSamplerPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.distribution;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.distribution.AliasMethodDiscreteSampler;
import org.apache.commons.rng.sampling.distribution.DiscreteSampler;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
/**
* Executes benchmark to test the {@link AliasMethodDiscreteSampler} using different
* zero padding on the input probability distribution.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = {"-server", "-Xms128M", "-Xmx128M"})
public class AliasMethodDiscreteSamplerPerformance {
/**
* The value.
*
* <p>This must NOT be final!</p>
*/
private int value;
/**
* The discrete probability distribution and a sampler. Used to test the sample speed and
* construction speed of different sized distributions.
*/
@State(Scope.Benchmark)
public static class DistributionData {
/**
* The distribution size.
*/
@Param({"7", "8", "9", "15", "16", "17", "31", "32", "33", "63", "64", "65"})
private int size;
/**
* The sampler alpha parameter.
*/
@Param({"-1", "0", "1", "2"})
private int alpha;
/** The probabilities. */
private double[] probabilities;
/** The sampler. */
private DiscreteSampler sampler;
/**
* @return the alpha.
*/
public int getAlpha() {
return alpha;
}
/**
* @return the probabilities.
*/
public double[] getProbabilities() {
return probabilities;
}
/**
* @return the sampler.
*/
public DiscreteSampler getSampler() {
return sampler;
}
/** Create the distribution and sampler. */
@Setup
public void setup() {
probabilities = createProbabilities(size);
final UniformRandomProvider rng = RandomSource.SPLIT_MIX_64.create();
sampler = AliasMethodDiscreteSampler.of(rng, probabilities, alpha);
}
/**
* Creates the probabilities for a discrete distribution of the given size.
*
* <p>This is not normalised to sum to 1. The sampler should handle this.</p>
*
* @param size Size of the distribution.
* @return the probabilities
*/
private static double[] createProbabilities(int size) {
final double[] probabilities = new double[size];
for (int i = 0; i < size; i++) {
probabilities[i] = (i + 1.0) / size;
}
return probabilities;
}
}
// Benchmarks methods below.
/**
* Baseline for the JMH timing overhead for production of an {@code int} value.
*
* @return the {@code int} value
*/
@Benchmark
public int baseline() {
return value;
}
/**
* Run the sampler.
*
* @param data Contains the distribution sampler.
* @return the sample value
*/
@Benchmark
public int sample(DistributionData data) {
return data.getSampler().sample();
}
/**
* Create the sampler.
*
* @param dist Contains the sampler constructor parameters.
* @return the sampler
*/
@Benchmark
public Object createSampler(DistributionData dist) {
// For the construction the RNG can be null
return AliasMethodDiscreteSampler.of(null, dist.getProbabilities(), dist.getAlpha());
}
}
| 2,784 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/distribution/StableSamplerPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.distribution;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.distribution.ContinuousSampler;
import org.apache.commons.rng.sampling.distribution.StableSampler;
import org.apache.commons.rng.sampling.distribution.ZigguratSampler;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
/**
* Executes a benchmark to compare the speed of generation of stable random numbers
* using different methods.
*
* <p>The test specifically includes a test of different versions of the sampler
* when {@code beta=0}; {@code alpha=1}; or the generic case {@code alpha != 1} and
* {@code beta != 0}.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = {"-server", "-Xms128M", "-Xmx128M"})
public class StableSamplerPerformance {
/** The name of the baseline method. */
static final String BASELINE = "baseline";
/**
* Samples from a stable distribution with zero location and unit scale.
* Two implementations are available:
*
* <ol>
* <li>Implements the Chambers-Mallows-Stuck (CMS) method from Chambers, et al
* (1976) A Method for Simulating Stable Random Variables. Journal of the
* American Statistical Association Vol. 71, No. 354, pp. 340-344.
* This is a translation of the FORTRAN routine RSTAB; it computes a rearrangement
* of the original formula to use double-angle identities and output a 0-parameterization
* stable deviate.
*
* <li>The implementation uses the Chambers-Mallows-Stuck (CMS) method using
* the formula proven in Weron (1996) "On the Chambers-Mallows-Stuck method for
* simulating skewed stable random variables". Statistics & Probability
* Letters. 28 (2): 165–171. This outputs a 1-parameterization stable deviate and
* has been modified to the 0-parameterization using a translation.
* </ol>
*
* <p>The code has been copied from o.a.c.rng.sampling.distributions.StableSampler.
* The classes have been renamed to StableRandomGenerator to distinguish them.
* The copy implementation of the CMS algorithm RSTAB uses Math.tan to compute
* tan(x) / x. The main StableSampler implements the CMS RSTAB algorithm using
* fast approximation to the Math.tan function.
* The implementation of the Weron formula has been copied as it is not possible
* to instantiate these samplers directly. They are used for edge case computations.
*
* @see <a href="https://en.wikipedia.org/wiki/Stable_distribution">Stable
* distribution (Wikipedia)</a>
* @see <a href="https://doi.org/10.1080%2F01621459.1976.10480344">Chambers et
* al (1976) JOASA 71: 340-344</a>
* @see <a
* href="https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.3280">Weron
* (1996) Statistics & Probability Letters. 28: 165–171</a>
*/
abstract static class StableRandomGenerator implements ContinuousSampler {
/** The lower support for the distribution. This is the lower bound of {@code (-inf, +inf)}. */
static final double LOWER = Double.NEGATIVE_INFINITY;
/** The upper support for the distribution. This is the upper bound of {@code (-inf, +inf)}. */
static final double UPPER = Double.POSITIVE_INFINITY;
/** pi / 2. */
static final double PI_2 = Math.PI / 2;
/** pi / 4. */
static final double PI_4 = Math.PI / 4;
/** pi/2 scaled by 2^-53. */
static final double PI_2_SCALED = 0x1.0p-54 * Math.PI;
/** pi/4 scaled by 2^-53. */
static final double PI_4_SCALED = 0x1.0p-55 * Math.PI;
/** Underlying source of randomness. */
private final UniformRandomProvider rng;
/** The exponential sampler. */
private final ContinuousSampler expSampler;
/**
* @param rng Underlying source of randomness
*/
StableRandomGenerator(final UniformRandomProvider rng) {
this.rng = rng;
expSampler = ZigguratSampler.Exponential.of(rng);
}
/**
* Gets a random value for the omega parameter.
* This is an exponential random variable with mean 1.
*
* @return omega
*/
double getOmega() {
return expSampler.sample();
}
/**
* Gets a random value for the phi parameter.
* This is a uniform random variable in {@code (-pi/2, pi/2)}.
*
* @return phi
*/
double getPhi() {
final double x = (rng.nextLong() >> 10) * PI_2_SCALED;
if (x == -PI_2) {
return getPhi();
}
return x;
}
/**
* Gets a random value for the phi/2 parameter.
* This is a uniform random variable in {@code (-pi/4, pi/4)}.
*
* @return phi/2
*/
double getPhiBy2() {
final double x = (rng.nextLong() >> 10) * PI_4_SCALED;
if (x == -PI_4) {
return getPhiBy2();
}
return x;
}
/**
* Creates a sampler of a stable distribution with zero location and unit scale.
*
* <p>WARNING: Parameters are not validated.
*
* @param rng Generator of uniformly distributed random numbers.
* @param alpha Stability parameter. Must be in range {@code (0, 2]}.
* @param beta Skewness parameter. Must be in range {@code [-1, 1]}.
* @param weron Set to true to use the Weron formulas. Default is CMS.
* @return the sampler
*/
static ContinuousSampler of(UniformRandomProvider rng,
double alpha,
double beta,
boolean weron) {
// WARNING:
// No parameter validation
// No Alpha=2 case
// No Alpha=1, beta=0 case
if (weron) {
if (beta == 0.0) {
return new Beta0WeronStableRandomGenerator(rng, alpha);
}
if (alpha == 1.0) {
return new Alpha1WeronStableRandomGenerator(rng, alpha);
}
return new WeronStableRandomGenerator(rng, alpha, beta);
}
if (beta == 0.0) {
return new Beta0CMSStableRandomGenerator(rng, alpha);
}
if (alpha == 1.0) {
return new Alpha1CMSStableRandomGenerator(rng, alpha);
}
return new CMSStableRandomGenerator(rng, alpha, beta);
}
/**
* Clip the sample {@code x} to the inclusive limits of the support.
*
* @param x Sample x.
* @param lower Lower bound.
* @param upper Upper bound.
* @return x in [lower, upper]
*/
static double clipToSupport(double x, double lower, double upper) {
if (x < lower) {
return lower;
}
return x < upper ? x : upper;
}
}
/**
* A baseline for a generator that uses an exponential sample and a uniform deviate in the
* range {@code [-pi/2, pi/2]}.
*/
private static class BaselineStableRandomGenerator extends StableRandomGenerator {
/**
* @param rng Underlying source of randomness
*/
BaselineStableRandomGenerator(UniformRandomProvider rng) {
super(rng);
}
@Override
public double sample() {
return getOmega() * getPhi();
}
}
/**
* Implement the generic stable distribution case: {@code alpha < 2} and {@code beta != 0},
* and {@code alpha != 0}.
*
* <p>Implements the Weron formula.
*/
private static class WeronStableRandomGenerator extends StableRandomGenerator {
/** The lower support for the distribution. */
protected final double lower;
/** The upper support for the distribution. */
protected final double upper;
/** Epsilon (1 - alpha). */
protected final double eps;
/** Epsilon (1 - alpha). */
protected final double meps1;
/** Cache of expression value used in generation. */
protected final double zeta;
/** Cache of expression value used in generation. */
protected final double atanZeta;
/** Cache of expression value used in generation. */
protected final double scale;
/** 1 / alpha = 1 / (1 - eps). */
protected final double inv1mEps;
/** (1 / alpha) - 1 = eps / (1 - eps). */
protected final double epsDiv1mEps;
/**
* @param rng Underlying source of randomness
* @param alpha Stability parameter. Must be in range {@code (0, 2]}.
* @param beta Skewness parameter. Must be in range {@code [-1, 1]}.
*/
WeronStableRandomGenerator(UniformRandomProvider rng, double alpha, double beta) {
super(rng);
eps = 1 - alpha;
// When alpha < 0.5, 1 - eps == alpha is not always true as the reverse is not exact.
// Here we store 1 - eps in place of alpha. Thus eps + (1 - eps) = 1.
meps1 = 1 - eps;
// Compute pre-factors for the Weron formula used during error correction.
if (meps1 > 1) {
// Avoid calling tan outside the domain limit [-pi/2, pi/2].
zeta = beta * Math.tan((2 - meps1) * PI_2);
} else {
zeta = -beta * Math.tan(meps1 * PI_2);
}
// Do not store xi = Math.atan(-zeta) / meps1 due to floating-point division errors.
// Directly store Math.atan(-zeta).
atanZeta = Math.atan(-zeta);
scale = Math.pow(1 + zeta * zeta, 0.5 / meps1);
inv1mEps = 1.0 / meps1;
epsDiv1mEps = inv1mEps - 1;
// Compute the support. This applies when alpha < 1 and beta = +/-1
if (alpha < 1 && Math.abs(beta) == 1) {
if (beta == 1) {
// alpha < 0, beta = 1
lower = zeta;
upper = UPPER;
} else {
// alpha < 0, beta = -1
lower = LOWER;
upper = zeta;
}
} else {
lower = LOWER;
upper = UPPER;
}
}
@Override
public double sample() {
final double w = getOmega();
final double phi = getPhi();
// Add back zeta
// This creates the parameterization defined in Nolan (1998):
// X ~ S0_alpha(s,beta,u0) with s=1, u0=0 for a standard random variable.
double t1 = Math.sin(meps1 * phi + atanZeta) / Math.pow(Math.cos(phi), inv1mEps);
double t2 = Math.pow(Math.cos(eps * phi - atanZeta) / w, epsDiv1mEps);
// Term t1 and t2 can be zero or infinite.
// Used a boxed infinity to avoid inf * 0.
double unbox1 = 1;
double unbox2 = 1;
if (Double.isInfinite(t1)) {
t1 = Math.copySign(Double.MAX_VALUE, t1);
unbox1 = unbox2 = Double.MAX_VALUE;
}
if (Double.isInfinite(t2)) {
t2 = Math.copySign(Double.MAX_VALUE, t2);
unbox1 = unbox2 = Double.MAX_VALUE;
}
// Note: The order of the product must be maintained to unbox the infinity
return clipToSupport(t1 * t2 * unbox1 * unbox2 * scale + zeta, lower, upper);
}
}
/**
* Implement the {@code alpha == 1} and {@code beta != 0} stable distribution
* case.
*
* <p>Implements the Weron formula.
*/
private static class Alpha1WeronStableRandomGenerator extends StableRandomGenerator {
/** Skewness parameter. */
private final double beta;
/**
* @param rng Underlying source of randomness
* @param beta Skewness parameter. Must be in range {@code [-1, 1]}.
*/
Alpha1WeronStableRandomGenerator(UniformRandomProvider rng, double beta) {
super(rng);
this.beta = beta;
}
@Override
public double sample() {
final double w = getOmega();
final double phi = getPhi();
// Generic stable distribution with alpha = 1.
// Note: betaPhi cannot be zero when phi is limited to < pi/2.
// This eliminates divide by 0 errors.
final double betaPhi = PI_2 + beta * phi;
final double x = (betaPhi * Math.tan(phi) -
beta * Math.log(PI_2 * w * Math.cos(phi) / betaPhi)) / PI_2;
// When w -> 0 this computes +/- infinity.
return x;
}
}
/**
* Implement the {@code alpha < 2} and {@code beta = 0} stable distribution case.
*
* <p>Implements the Weron formula.
*/
private static class Beta0WeronStableRandomGenerator extends StableRandomGenerator {
/** Epsilon (1 - alpha). */
protected final double eps;
/** Epsilon (1 - alpha). */
protected final double meps1;
/** 1 / alpha = 1 / (1 - eps). */
protected final double inv1mEps;
/** (1 / alpha) - 1 = eps / (1 - eps). */
protected final double epsDiv1mEps;
/**
* @param rng Underlying source of randomness
* @param alpha Stability parameter. Must be in range {@code (0, 2]}.
*/
Beta0WeronStableRandomGenerator(UniformRandomProvider rng, double alpha) {
super(rng);
eps = 1 - alpha;
meps1 = 1 - eps;
inv1mEps = 1.0 / meps1;
epsDiv1mEps = inv1mEps - 1;
}
@Override
public double sample() {
final double w = getOmega();
final double phi = getPhi();
// Compute terms
double t1 = Math.sin(meps1 * phi) / Math.pow(Math.cos(phi), inv1mEps);
double t2 = Math.pow(Math.cos(eps * phi) / w, epsDiv1mEps);
double unbox1 = 1;
double unbox2 = 1;
if (Double.isInfinite(t1)) {
t1 = Math.copySign(Double.MAX_VALUE, t1);
unbox1 = unbox2 = Double.MAX_VALUE;
}
if (Double.isInfinite(t2)) {
t2 = Math.copySign(Double.MAX_VALUE, t2);
unbox1 = unbox2 = Double.MAX_VALUE;
}
// Note: The order of the product must be maintained to unbox the infinity
return t1 * t2 * unbox1 * unbox2;
}
}
/**
* Implement the generic stable distribution case: {@code alpha < 2} and
* {@code beta != 0}. This routine assumes {@code alpha != 1}.
*
* <p>Implements the CMS formula using the RSTAB algorithm.
*/
static class CMSStableRandomGenerator extends WeronStableRandomGenerator {
/** 1/2. */
private static final double HALF = 0.5;
/** Cache of expression value used in generation. */
private final double tau;
/**
* @param rng Underlying source of randomness
* @param alpha Stability parameter. Must be in the interval {@code (0, 2]}.
* @param beta Skewness parameter. Must be in the interval {@code [-1, 1]}.
*/
CMSStableRandomGenerator(UniformRandomProvider rng, double alpha, double beta) {
super(rng, alpha, beta);
// Compute the RSTAB pre-factors.
// tau = -eps * tan(alpha * Phi0)
// with Phi0 = alpha^-1 * arctan(beta * tan(pi alpha / 2)).
// tau is symmetric around alpha=1
// tau -> beta / pi/2 as alpha -> 1
// tau -> 0 as alpha -> 2 or 0
// Avoid calling tan as the value approaches the domain limit [-pi/2, pi/2].
if (eps == 0) {
// alpha == 1
tau = beta / PI_2;
} else if (Math.abs(eps) < HALF) {
// 0.5 < alpha < 1.5
tau = eps * beta / Math.tan(eps * PI_2);
} else {
// alpha >= 1.5 or alpha <= 0.5.
// Do not call tan with alpha > 1 as it wraps in the domain [-pi/2, pi/2].
// Since pi is approximate the symmetry is lost by wrapping.
// Keep within the domain using (2-alpha).
if (meps1 > 1) {
tau = eps * beta * -Math.tan((2 - meps1) * PI_2);
} else {
tau = eps * beta * Math.tan(meps1 * PI_2);
}
}
}
@Override
public double sample() {
final double phiby2 = getPhiBy2();
final double w = getOmega();
// Compute as per the RSTAB routine.
// Generic stable distribution that is continuous as alpha -> 1.
// This is a trigonomic rearrangement of equation 4.1 from Chambers et al (1976)
// as implemented in the Fortran program RSTAB.
// Uses the special functions:
// tan2 = tan(x) / x
// d2 = (exp(x) - 1) / x
// The method is implemented as per the RSTAB routine but using Math.tan
// for the tan2 function
// Compute some tangents
final double a = Math.tan(phiby2);
final double b = Math.tan(eps * phiby2);
final double bb = b == 0 ? 1 : b / (eps * phiby2);
// Compute some necessary subexpressions
final double da = a * a;
final double db = b * b;
final double a2 = 1 - da;
final double a2p = 1 + da;
final double b2 = 1 - db;
final double b2p = 1 + db;
// Compute coefficient.
final double numerator = b2 + 2 * phiby2 * bb * tau;
final double z = a2p * numerator / (w * a2 * b2p);
// Compute the exponential-type expression
final double alogz = Math.log(z);
final double d = D2Source.d2(epsDiv1mEps * alogz) * (alogz * inv1mEps);
// Pre-compute the multiplication factor.
final double f = (2 * ((a - b) * (1 + a * b) - phiby2 * tau * bb * (b * a2 - 2 * a))) /
(a2 * b2p);
// Compute the stable deviate:
final double x = (1 + eps * d) * f + tau * d;
// Test the support
if (lower < x && x < upper) {
return x;
}
// No error correction path here!
// Return something so that the test for the support is not optimised away.
return 0;
}
}
/**
* Implement the stable distribution case: {@code alpha == 1} and {@code beta != 0}.
*
* <p>Implements the same algorithm as the {@link CMSStableRandomGenerator} with
* the {@code alpha} assumed to be 1.
*
* <p>This routine assumes {@code beta != 0}; {@code alpha=1, beta=0} is the Cauchy
* distribution case.
*/
static class Alpha1CMSStableRandomGenerator extends StableRandomGenerator {
/** Cache of expression value used in generation. */
private final double tau;
/**
* @param rng Underlying source of randomness
* @param beta Skewness parameter. Must be in the interval {@code [-1, 1]}.
*/
Alpha1CMSStableRandomGenerator(UniformRandomProvider rng, double beta) {
super(rng);
tau = beta / PI_2;
}
@Override
public double sample() {
final double phiby2 = getPhiBy2();
final double w = getOmega();
// Compute some tangents
final double a = Math.tan(phiby2);
// Compute some necessary subexpressions
final double da = a * a;
final double a2 = 1 - da;
final double a2p = 1 + da;
// Compute coefficient.
final double z = a2p * (1 + 2 * phiby2 * tau) / (w * a2);
// Compute the exponential-type expression
final double d = Math.log(z);
// Pre-compute the multiplication factor.
final double f = (2 * (a - phiby2 * tau * (-2 * a))) / a2;
// Compute the stable deviate:
return f + tau * d;
}
}
/**
* Implement the generic stable distribution case: {@code alpha < 2} and {@code beta == 0}.
*
* <p>Implements the same algorithm as the {@link CMSStableRandomGenerator} with
* the {@code beta} assumed to be 0.
*
* <p>This routine assumes {@code alpha != 1}; {@code alpha=1, beta=0} is the Cauchy
* distribution case.
*/
static class Beta0CMSStableRandomGenerator extends Beta0WeronStableRandomGenerator {
/**
* @param rng Underlying source of randomness
* @param alpha Stability parameter. Must be in the interval {@code (0, 2]}.
*/
Beta0CMSStableRandomGenerator(UniformRandomProvider rng, double alpha) {
super(rng, alpha);
}
@Override
public double sample() {
final double phiby2 = getPhiBy2();
final double w = getOmega();
// Compute some tangents
final double a = Math.tan(phiby2);
final double b = Math.tan(eps * phiby2);
// Compute some necessary subexpressions
final double da = a * a;
final double db = b * b;
final double a2 = 1 - da;
final double a2p = 1 + da;
final double b2 = 1 - db;
final double b2p = 1 + db;
// Compute coefficient.
final double z = a2p * b2 / (w * a2 * b2p);
// Compute the exponential-type expression
final double alogz = Math.log(z);
final double d = D2Source.d2(epsDiv1mEps * alogz) * (alogz * inv1mEps);
// Pre-compute the multiplication factor.
final double f = (2 * ((a - b) * (1 + a * b))) / (a2 * b2p);
// Compute the stable deviate:
final double x = (1 + eps * d) * f;
// Test the support
if (LOWER < x && x < UPPER) {
return x;
}
// No error correction path here!
// Return something so that the test for the support is not optimised away.
return 0;
}
}
/**
* Defines the {@link RandomSource} for testing a {@link ContinuousSampler}.
*/
public abstract static class SamplerSource {
/**
* RNG providers.
*
* <p>Use different speeds.</p>
*
* @see <a href="https://commons.apache.org/proper/commons-rng/userguide/rng.html">
* Commons RNG user guide</a>
*/
@Param({"XO_RO_SHI_RO_128_PP",
"MWC_256",
"JDK"})
private String randomSourceName;
/**
* Gets the source of randomness.
*
* @return RNG
*/
public UniformRandomProvider getRNG() {
return RandomSource.valueOf(randomSourceName).create();
}
/**
* @return the sampler.
*/
public abstract ContinuousSampler getSampler();
}
/**
* Source for a uniform random deviate in an open interval, e.g. {@code (-0.5, 0.5)}.
*/
@State(Scope.Benchmark)
public static class UniformRandomSource extends SamplerSource {
/** The lower limit of (-pi/4, pi/4). */
private static final double NEG_PI_4 = -Math.PI / 4;
/** pi/4 scaled by 2^-53. */
private static final double PI_4_SCALED = 0x1.0p-55 * Math.PI;
/** Method to generate the uniform deviate. */
@Param({BASELINE, "nextDoubleNot0", "nextDoubleNot0Recurse",
"nextLongNot0", "nextDoubleShifted", "nextLongShifted",
"signedShift", "signedShiftPi4", "signedShiftPi4b"})
private String method;
/** The sampler. */
private ContinuousSampler sampler;
/** {@inheritDoc} */
@Override
public ContinuousSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
final UniformRandomProvider rng = getRNG();
if (BASELINE.equals(method)) {
sampler = rng::nextDouble;
} else if ("nextDoubleNot0".equals(method)) {
sampler = () -> {
// Sample the 2^53 dyadic rationals in [0, 1) with zero excluded
double x;
do {
x = rng.nextDouble();
} while (x == 0);
return x - 0.5;
};
} else if ("nextDoubleNot0Recurse".equals(method)) {
sampler = new ContinuousSampler() {
@Override
public double sample() {
// Sample the 2^53 dyadic rationals in [0, 1) with zero excluded.
// Use recursion to generate a stack overflow with a bad provider.
// This is better than an infinite loop.
final double x = rng.nextDouble();
if (x == 0) {
return sample();
}
return x - 0.5;
}
};
} else if ("nextLongNot0".equals(method)) {
sampler = () -> {
// Sample the 2^53 dyadic rationals in [0, 1) with zero excluded
long x;
do {
x = rng.nextLong() >>> 11;
} while (x == 0);
return x * 0x1.0p-53 - 0.5;
};
} else if ("nextDoubleShifted".equals(method)) {
sampler = () -> {
// Sample the 2^52 dyadic rationals in [0, 1) and shift by 2^-53.
// No infinite loop but the deviate loses 1 bit of randomness.
return 0x1.0p-53 + (rng.nextLong() >>> 12) * 0x1.0p-52 - 0.5;
};
} else if ("nextLongShifted".equals(method)) {
sampler = () -> {
// Sample the 2^53 dyadic rationals in [0, 1) but set the lowest
// bit. This result in 2^52 dyadic rationals in (0, 1) to avoid 0.
return ((rng.nextLong() >>> 11) | 0x1L) * 0x1.0p-53 - 0.5;
};
} else if ("signedShift".equals(method)) {
sampler = new ContinuousSampler() {
@Override
public double sample() {
// As per o.a.c.rng.core.utils.NumberFactory.makeDouble(long) but using a
// signed shift of 10 in place of an unsigned shift of 11, and updating the
// multiplication factor to 2^-54.
final double x = (rng.nextLong() >> 10) * 0x1.0p-54;
if (x == -0.5) {
// Avoid the extreme of the bounds
return sample();
}
return x;
}
};
} else if ("signedShiftPi4".equals(method)) {
// Note: This does generate u in (-0.5, 0.5) which must be scaled by pi
// or pi/2 for the CMS algorithm but directly generates in (-pi/4, pi/4).
sampler = new ContinuousSampler() {
@Override
public double sample() {
// As per o.a.c.rng.core.utils.NumberFactory.makeDouble(long) but using a
// signed shift of 10 in place of an unsigned shift of 11, and updating the
// multiplication factor to 2^-54 * pi/2
final double x = (rng.nextLong() >> 10) * PI_4_SCALED;
if (x == NEG_PI_4) {
// Avoid the extreme of the bounds
return sample();
}
return x;
}
};
} else if ("signedShiftPi4b".equals(method)) {
// Note: This does generate u in (-0.5, 0.5) which must be scaled by pi
// or pi/2 for the CMS algorithm but directly generates in (-pi/4, pi/4).
sampler = new ContinuousSampler() {
@Override
public double sample() {
final long x = rng.nextLong();
if (x == Long.MIN_VALUE) {
// Avoid the extreme of the bounds
return sample();
}
// As per o.a.c.rng.core.utils.NumberFactory.makeDouble(long) but using a
// signed shift of 10 in place of an unsigned shift of 11, and updating the
// multiplication factor to 2^-54 * pi/2
return (x >> 10) * PI_4_SCALED;
}
};
} else {
throw new IllegalStateException("Unknown method: " + method);
}
}
}
/**
* Source for testing implementations of tan(x) / x. The function must work on a value
* in the range {@code [0, pi/4]}.
*
* <p>The tan(x) / x function is required for the trigonomic rearrangement of the CMS
* formula to create a stable random variate.
*/
@State(Scope.Benchmark)
public static class TanSource extends SamplerSource {
/** pi / 2. */
private static final double PI_2 = Math.PI / 2;
/** pi / 4. */
private static final double PI_4 = Math.PI / 4;
/** 4 / pi. */
private static final double FOUR_PI = 4 / Math.PI;
/** Method to generate tan(x) / x. */
@Param({BASELINE, "tan", "tan4283", "tan4288", "tan4288b", "tan4288c"})
private String method;
/** The sampler. */
private ContinuousSampler sampler;
/** {@inheritDoc} */
@Override
public ContinuousSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
final UniformRandomProvider rng = getRNG();
if (BASELINE.equals(method)) {
sampler = () -> {
// A value in [-pi/4, pi/4]
return PI_2 * (rng.nextDouble() - 0.5);
};
} else if ("tan".equals(method)) {
sampler = () -> {
final double x = PI_2 * (rng.nextDouble() - 0.5);
// Require tan(0) / 0 = 1 and not NaN
return x == 0 ? 1.0 : Math.tan(x) / x;
};
} else if ("tan4283".equals(method)) {
sampler = () -> {
final double x = PI_2 * (rng.nextDouble() - 0.5);
return x * tan4283(x);
};
} else if ("tan4288".equals(method)) {
sampler = () -> {
final double x = PI_2 * (rng.nextDouble() - 0.5);
return x * tan4288(x);
};
} else if ("tan4288b".equals(method)) {
sampler = () -> {
final double x = PI_2 * (rng.nextDouble() - 0.5);
return x * tan4288b(x);
};
} else if ("tan4288c".equals(method)) {
sampler = () -> {
final double x = PI_2 * (rng.nextDouble() - 0.5);
return x * tan4288c(x);
};
} else {
throw new IllegalStateException("Unknown tan method: " + method);
}
}
// Mean (max) ULP is very low
// 2^30 random samples in [0, pi / 4)
// tan(x) tan(x) / x
// tan4283 93436.25534446817 201185 : 68313.16171793547 128079
// tan4288 0.5898815048858523 4 : 0.40416045393794775 3
// tan4288b 0.8608690425753593 8 : 0.6117749745026231 5
// tan4288c 0.5905972588807344 4 : 0.4047176940366626 3
/**
* Evaluate {@code tan(x) / x}.
*
* <p>For {@code x} in the range {@code [0, pi/4]} this ideally should return
* a value in the range {@code [1, 4 / pi]}. However due to lack of precision
* this is not the case for the extremes of the interval. It is not recommended
* to use this function in the CMS algorithm when computing the routine with
* double precision. The original RSTAB routine is for single precision floats.
*
* <p>Uses tan 4283 from Hart, JF et al (1968) Computer Approximations,
* New York: John Wiley & Sons, Inc.
*
* <p>This is the original method used in the RSTAB function by Chambers et al (1976).
* It has been updated to use the full precision constants provided in Hart.
*
* @param x the x
* @return {@code tan(x) / x}.
*/
static double tan4283(double x) {
double xa = Math.abs(x);
if (xa > PI_4) {
return Math.tan(x) / x;
}
// Approximation 4283 from Hart et al (1968, P. 251).
// Max relative error = 1e-10.66.
// When testing verses Math.tan(x) the mean ULP difference was 93436.3
final double p0 = 0.129221035031569917e3;
final double p1 = -0.8876623770211723e1;
final double p2 = 0.52864445522248e-1;
final double q0 = 0.164529331810168605e3;
final double q1 = -0.45132056100598961e2;
// q2 = 1.0
xa = xa / PI_4;
final double xx = xa * xa;
// Polynomial implemented as per Chambers (1976) using the nested form.
return (p0 + xx * (p1 + xx * p2)) / (PI_4 * (q0 + xx * (q1 + xx /* * q2 */)));
}
/**
* Evaluate {@code tan(x) / x}.
*
* <p>For {@code x} in the range {@code [0, pi/4]} this returns
* a value in the range {@code [1, 4 / pi]}.
*
* <p>Uses tan 4288 from Hart, JF et al (1968) Computer Approximations,
* New York: John Wiley & Sons, Inc.
*
* <p>This is a higher precision method provided in Hart.
* It has the properties that {@code tan(x) / x = 1, x = 0} and
* {@code tan(x) = 1, x = pi / 4}.
*
* @param x the x
* @return {@code tan(x) / x}.
*/
static double tan4288(double x) {
double xa = Math.abs(x);
if (xa > PI_4) {
return Math.tan(x) / x;
}
// Approximation 4288 from Hart et al (1968, P. 252).
// Max relative error = 1e-26.68 (for tan(x))
// When testing verses Math.tan(x) the mean ULP difference was 0.589882
final double p0 = -0.5712939549476836914932149599e+10;
final double p1 = +0.4946855977542506692946040594e+9;
final double p2 = -0.9429037070546336747758930844e+7;
final double p3 = +0.5282725819868891894772108334e+5;
final double p4 = -0.6983913274721550913090621370e+2;
final double q0 = -0.7273940551075393257142652672e+10;
final double q1 = +0.2125497341858248436051062591e+10;
final double q2 = -0.8000791217568674135274814656e+8;
final double q3 = +0.8232855955751828560307269007e+6;
final double q4 = -0.2396576810261093558391373322e+4;
// q5 = 1.0
xa = xa * FOUR_PI;
final double xx = xa * xa;
// Polynomial implemented as per Chambers (1976) using the nested form.
return (p0 + xx * (p1 + xx * (p2 + xx * (p3 + xx * p4)))) /
(PI_4 * (q0 + xx * (q1 + xx * (q2 + xx * (q3 + xx * (q4 + xx /* * q5 */))))));
}
/**
* Evaluate {@code tan(x) / x}.
*
* <p>For {@code x} in the range {@code [0, pi/4]} this returns
* a value in the range {@code [1, 4 / pi]}.
*
* <p>Uses tan 4288 from Hart, JF et al (1968) Computer Approximations,
* New York: John Wiley & Sons, Inc.
*
* @param x the x
* @return {@code tan(x) / x}.
*/
static double tan4288b(double x) {
double xa = Math.abs(x);
if (xa > PI_4) {
return Math.tan(x) / x;
}
final double p0 = -0.5712939549476836914932149599e+10;
final double p1 = +0.4946855977542506692946040594e+9;
final double p2 = -0.9429037070546336747758930844e+7;
final double p3 = +0.5282725819868891894772108334e+5;
final double p4 = -0.6983913274721550913090621370e+2;
final double q0 = -0.7273940551075393257142652672e+10;
final double q1 = +0.2125497341858248436051062591e+10;
final double q2 = -0.8000791217568674135274814656e+8;
final double q3 = +0.8232855955751828560307269007e+6;
final double q4 = -0.2396576810261093558391373322e+4;
// q5 = 1.0
xa = xa * FOUR_PI;
// Rearrange the polynomial to the power form.
// Allows parallel computation of terms.
// This is faster but has been tested to have lower accuracy verses Math.tan.
// When testing verses Math.tan(x) the mean ULP difference was 0.860869
final double x2 = xa * xa;
final double x4 = x2 * x2;
final double x6 = x4 * x2;
final double x8 = x4 * x4;
return (p0 + x2 * p1 + x4 * p2 + x6 * p3 + x8 * p4) /
(PI_4 * (q0 + x2 * q1 + x4 * q2 + x6 * q3 + x8 * q4 + x8 * x2));
}
/**
* Evaluate {@code tan(x) / x}.
*
* <p>For {@code x} in the range {@code [0, pi/4]} this returns
* a value in the range {@code [1, 4 / pi]}.
*
* <p>Uses tan 4288 from Hart, JF et al (1968) Computer Approximations,
* New York: John Wiley & Sons, Inc.
*
* @param x the x
* @return {@code tan(x) / x}.
*/
static double tan4288c(double x) {
if (Math.abs(x) > PI_4) {
return Math.tan(x) / x;
}
final double p0 = -0.5712939549476836914932149599e+10;
final double p1 = +0.4946855977542506692946040594e+9;
final double p2 = -0.9429037070546336747758930844e+7;
final double p3 = +0.5282725819868891894772108334e+5;
final double p4 = -0.6983913274721550913090621370e+2;
final double q0 = -0.7273940551075393257142652672e+10;
final double q1 = +0.2125497341858248436051062591e+10;
final double q2 = -0.8000791217568674135274814656e+8;
final double q3 = +0.8232855955751828560307269007e+6;
final double q4 = -0.2396576810261093558391373322e+4;
// q5 = 1.0
final double xi = x * FOUR_PI;
// Rearrange the polynomial to the power form.
// Allows parallel computation of terms.
// This is faster and has been tested to have accuracy similar to the nested form.
// When testing verses Math.tan(x) the mean ULP difference was 0.590597
final double x2 = xi * xi;
final double x4 = x2 * x2;
final double x6 = x4 * x2;
final double x8 = x4 * x4;
// Reverse summation order to have least significant terms first.
return (x8 * p4 + x6 * p3 + x4 * p2 + x2 * p1 + p0) /
(PI_4 * (x8 * x2 + x8 * q4 + x6 * q3 + x4 * q2 + x2 * q1 + q0));
}
}
/**
* Source for testing implementations of {@code (exp(x) - 1) / x}. The function must
* work on a value in the range {@code [-inf, +inf]}.
*
* <p>The d2 function is required for the trigonomic rearrangement of the CMS
* formula to create a stable random variate.
*
* <p>For testing the value x is generated as a uniform deviate with a range around
* zero ({@code [-scale/2, +scale/2]}) using a configurable scale parameter.
*/
@State(Scope.Benchmark)
public static class D2Source extends SamplerSource {
/** Method to generate (exp(x) - 1) / x. */
@Param({BASELINE, "expm1", "expm1b", "exp", "hybrid"})
private String method;
/** Scale for the random value x. */
@Param({"0.12345", "1.2345", "12.345", "123.45"})
private double scale;
/** The sampler. */
private ContinuousSampler sampler;
/** {@inheritDoc} */
@Override
public ContinuousSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
final double s = scale;
final UniformRandomProvider rng = getRNG();
if (BASELINE.equals(method)) {
sampler = () -> s * (rng.nextDouble() - 0.5);
} else if ("expm1".equals(method)) {
sampler = () -> expm1(s * (rng.nextDouble() - 0.5));
} else if ("expm1b".equals(method)) {
sampler = () -> expm1b(s * (rng.nextDouble() - 0.5));
} else if ("exp".equals(method)) {
sampler = () -> exp(s * (rng.nextDouble() - 0.5));
} else if ("hybrid".equals(method)) {
sampler = () -> hybrid(s * (rng.nextDouble() - 0.5));
} else {
throw new IllegalStateException("Unknown d2 method: " + method);
}
}
/**
* Evaluate {@code (exp(x) - 1) / x}. For {@code x} in the range {@code [-inf, inf]} returns
* a result in {@code [0, inf]}.
*
* <ul>
* <li>For {@code x=-inf} this returns {@code 0}.
* <li>For {@code x=0} this returns {@code 1}.
* <li>For {@code x=inf} this returns {@code inf}.
* </ul>
*
* <p> This corrects {@code 0 / 0} and {@code inf / inf} division from
* {@code NaN} to either {@code 1} or the upper bound respectively.
*
* @param x value to evaluate
* @return {@code (exp(x) - 1) / x}.
*/
static double d2(double x) {
return hybrid(x);
}
/**
* Evaluate {@code (exp(x) - 1) / x}.
*
* @param x value to evaluate
* @return {@code (exp(x) - 1) / x}.
*/
static double expm1(double x) {
// Here we use a conditional to detect both edge cases, which are then corrected.
final double d2 = Math.expm1(x) / x;
if (Double.isNaN(d2)) {
// Correct edge cases.
if (x == 0) {
return 1.0;
}
// x must have been +infinite or NaN
return x;
}
return d2;
}
/**
* Evaluate {@code (exp(x) - 1) / x}.
*
* @param x value to evaluate
* @return {@code (exp(x) - 1) / x}.
*/
static double expm1b(double x) {
// Edge cases
if (x == 0) {
return 1;
}
if (x == Double.POSITIVE_INFINITY) {
return x;
}
return Math.expm1(x) / x;
}
/**
* Evaluate {@code (exp(x) - 1) / x}.
*
* @param x value to evaluate
* @return {@code (exp(x) - 1) / x}.
*/
static double exp(double x) {
// No use of expm1.
// Here we use a conditional to detect both edge cases, which are then corrected.
final double d2 = (Math.exp(x) - 1) / x;
if (Double.isNaN(d2)) {
// Correct edge cases.
if (x == 0) {
return 1.0;
}
// x must have been +infinite or NaN
return x;
}
return d2;
}
/**
* Evaluate {@code (exp(x) - 1) / x}.
*
* @param x value to evaluate
* @return {@code (exp(x) - 1) / x}.
*/
static double hybrid(double x) {
// This is the threshold where use of expm1 and exp consistently
// compute different results by more than 0.5 ULP.
if (Math.abs(x) < 0.5) {
if (x == 0) {
return 1;
}
return Math.expm1(x) / x;
}
// No use of expm1. Accuracy as x moves away from 0 is not required as the result
// is divided by x and the accuracy of the final result is the same.
if (x == Double.POSITIVE_INFINITY) {
return x;
}
return (Math.exp(x) - 1) / x;
}
}
/**
* Baseline with an exponential deviate and a uniform deviate.
*/
@State(Scope.Benchmark)
public static class BaselineSamplerSource extends SamplerSource {
/** The sampler. */
private ContinuousSampler sampler;
/** {@inheritDoc} */
@Override
public ContinuousSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
sampler = new BaselineStableRandomGenerator(getRNG());
}
}
/**
* The sampler to use for testing. Defines the RandomSource and the type of
* stable distribution sampler.
*/
public abstract static class StableSamplerSource extends SamplerSource {
/** The sampler type. */
@Param({"CMS", "CMS_weron", "CMS_tan"})
private String samplerType;
/** The sampler. */
private ContinuousSampler sampler;
/**
* The alpha value.
*
* @return alpha
*/
abstract double getAlpha();
/**
* The beta value.
*
* @return beta
*/
abstract double getBeta();
/** {@inheritDoc} */
@Override
public ContinuousSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
final UniformRandomProvider rng = getRNG();
if ("CMS".equals(samplerType)) {
sampler = StableSampler.of(rng, getAlpha(), getBeta());
} else if ("CMS_weron".equals(samplerType)) {
sampler = StableRandomGenerator.of(rng, getAlpha(), getBeta(), true);
} else if ("CMS_tan".equals(samplerType)) {
sampler = StableRandomGenerator.of(rng, getAlpha(), getBeta(), false);
} else {
throw new IllegalStateException("Unknown sampler: " + samplerType);
}
}
}
/**
* Sampling with {@code alpha = 1} and {@code beta != 0}.
*/
@State(Scope.Benchmark)
public static class Alpha1StableSamplerSource extends StableSamplerSource {
/** The beta value. */
@Param({"0.1", "0.4", "0.7"})
private double beta;
/** {@inheritDoc} */
@Override
double getAlpha() {
return 1;
}
/** {@inheritDoc} */
@Override
double getBeta() {
return beta;
}
}
/**
* Sampling with {@code alpha != 1} and {@code beta = 0}.
*/
@State(Scope.Benchmark)
public static class Beta0StableSamplerSource extends StableSamplerSource {
/** The alpha value. Use a range around 1. */
@Param({
//"0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "0.99", "1.1", "1.2", "1.3", "1.4", "1.5"
// The Weron formula is fast at alpha=0.5; possibly due to the two power
// functions using a power of 1 and 2 respectively.
//"0.45", "0.48", "0.5", "0.52", "0.55"
"0.3", "0.5", "0.7", "0.9", "1.1", "1.3", "1.5", "1.7"
})
private double alpha;
/** {@inheritDoc} */
@Override
double getAlpha() {
return alpha;
}
/** {@inheritDoc} */
@Override
double getBeta() {
return 0;
}
}
/**
* Sampling with {@code alpha != 1} and {@code beta != 0}.
*/
@State(Scope.Benchmark)
public static class GeneralStableSamplerSource extends Beta0StableSamplerSource {
/** The beta value. */
@Param({"0.1", "0.4", "0.7"})
private double beta;
/** {@inheritDoc} */
@Override
double getBeta() {
return beta;
}
}
/**
* Test methods for producing a uniform deviate in an open interval, e.g. {@code (-0.5, 0.5)}.
* This is a requirement of the stable distribution CMS algorithm.
*
* @param source Source of randomness.
* @return the {@code double} value
*/
@Benchmark
public double nextUniformDeviate(UniformRandomSource source) {
return source.getSampler().sample();
}
/**
* Test methods for producing {@code tan(x) / x} in the range {@code [0, pi/4]}.
* This is a requirement of the stable distribution CMS algorithm.
*
* @param source Source of randomness.
* @return the {@code tan(x)} value
*/
@Benchmark
public double nextTan(TanSource source) {
return source.getSampler().sample();
}
/**
* Test methods for producing {@code (exp(x) - 1) / x}.
* This is a requirement of the stable distribution CMS algorithm.
*
* @param source Source of randomness.
* @return the {@code (exp(x) - 1) / x} value
*/
@Benchmark
public double nextD2(D2Source source) {
return source.getSampler().sample();
}
/**
* Baseline for any sampler that uses an exponential deviate and a uniform deviate.
*
* @param source Source of randomness.
* @return the {@code double} value
*/
@Benchmark
public double sampleBaseline(BaselineSamplerSource source) {
return source.getSampler().sample();
}
/**
* Run the stable sampler with {@code alpha = 1}.
*
* @param source Source of randomness.
* @return the sample value
*/
@Benchmark
public double sampleAlpha1(Alpha1StableSamplerSource source) {
return source.getSampler().sample();
}
/**
* Run the stable sampler with {@code beta = 0}.
*
* @param source Source of randomness.
* @return the sample value
*/
@Benchmark
public double sampleBeta0(Beta0StableSamplerSource source) {
return source.getSampler().sample();
}
/**
* Run the stable sampler.
*
* @param source Source of randomness.
* @return the sample value
*/
@Benchmark
public double sample(GeneralStableSamplerSource source) {
return source.getSampler().sample();
}
}
| 2,785 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/distribution/ZigguratSamplerPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.distribution;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.ObjectSampler;
import org.apache.commons.rng.sampling.distribution.ContinuousSampler;
import org.apache.commons.rng.sampling.distribution.DiscreteSampler;
import org.apache.commons.rng.sampling.distribution.LongSampler;
import org.apache.commons.rng.sampling.distribution.ZigguratSampler;
import org.apache.commons.rng.sampling.distribution.ZigguratNormalizedGaussianSampler;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
/**
* Executes a benchmark to compare the speed of generation of random numbers
* using variations of the ziggurat method.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = {"-server", "-Xms128M", "-Xmx128M"})
public class ZigguratSamplerPerformance {
// Production versions
/** The name for a copy of the {@link ZigguratNormalizedGaussianSampler} with a table of size 128.
* This matches the version in Commons RNG release v1.1 to 1.3. */
static final String GAUSSIAN_128 = "Gaussian128";
/** The name for the {@link ZigguratNormalizedGaussianSampler} (table of size 256).
* This is the version in Commons RNG release v1.4+. */
static final String GAUSSIAN_256 = "Gaussian256";
/** The name for the {@link org.apache.commons.rng.sampling.distribution.ZigguratSampler.NormalizedGaussian}. */
static final String MOD_GAUSSIAN = "ModGaussian";
/** The name for the {@link org.apache.commons.rng.sampling.distribution.ZigguratSampler.Exponential}. */
static final String MOD_EXPONENTIAL = "ModExponential";
// Testing versions
/** The name for the {@link ZigguratExponentialSampler} with a table of size 256.
* This is an exponential sampler using Marsaglia's ziggurat method. */
static final String EXPONENTIAL = "Exponential";
/** The name for the {@link ModifiedZigguratNormalizedGaussianSampler}.
* This is a base implementation of McFarland's ziggurat method. */
static final String MOD_GAUSSIAN2 = "ModGaussian2";
/** The name for the {@link ModifiedZigguratNormalizedGaussianSamplerSimpleOverhangs}. */
static final String MOD_GAUSSIAN_SIMPLE_OVERHANGS = "ModGaussianSimpleOverhangs";
/** The name for the {@link ModifiedZigguratNormalizedGaussianSamplerInlining}. */
static final String MOD_GAUSSIAN_INLINING = "ModGaussianInlining";
/** The name for the {@link ModifiedZigguratNormalizedGaussianSamplerInliningShift}. */
static final String MOD_GAUSSIAN_INLINING_SHIFT = "ModGaussianInliningShift";
/** The name for the {@link ModifiedZigguratNormalizedGaussianSamplerInliningSimpleOverhangs}. */
static final String MOD_GAUSSIAN_INLINING_SIMPLE_OVERHANGS = "ModGaussianInliningSimpleOverhangs";
/** The name for the {@link ModifiedZigguratNormalizedGaussianSamplerIntMap}. */
static final String MOD_GAUSSIAN_INT_MAP = "ModGaussianIntMap";
/** The name for the {@link ModifiedZigguratNormalizedGaussianSamplerEMaxTable}. */
static final String MOD_GAUSSIAN_E_MAX_TABLE = "ModGaussianEMaxTable";
/** The name for the {@link ModifiedZigguratNormalizedGaussianSamplerEMax2}. */
static final String MOD_GAUSSIAN_E_MAX_2 = "ModGaussianEMax2";
/** The name for the {@link ModifiedZigguratNormalizedGaussianSamplerTernary}. */
static final String MOD_GAUSSIAN_TERNARY = "ModGaussianTernary";
/** The name for the {@link ModifiedZigguratNormalizedGaussianSampler512} using a table size of 512. */
static final String MOD_GAUSSIAN_512 = "ModGaussian512";
/** The name for the {@link ModifiedZigguratExponentialSampler}.
* This is a base implementation of McFarland's ziggurat method. */
static final String MOD_EXPONENTIAL2 = "ModExponential2";
/** The name for the {@link ModifiedZigguratExponentialSamplerSimpleOverhangs}. */
static final String MOD_EXPONENTIAL_SIMPLE_OVERHANGS = "ModExponentialSimpleOverhangs";
/** The name for the {@link ModifiedZigguratExponentialSamplerInlining}. */
static final String MOD_EXPONENTIAL_INLINING = "ModExponentialInlining";
/** The name for the {@link ModifiedZigguratExponentialSamplerLoop}. */
static final String MOD_EXPONENTIAL_LOOP = "ModExponentialLoop";
/** The name for the {@link ModifiedZigguratExponentialSamplerLoop2}. */
static final String MOD_EXPONENTIAL_LOOP2 = "ModExponentialLoop2";
/** The name for the {@link ModifiedZigguratExponentialSamplerRecursion}. */
static final String MOD_EXPONENTIAL_RECURSION = "ModExponentialRecursion";
/** The name for the {@link ModifiedZigguratExponentialSamplerIntMap}. */
static final String MOD_EXPONENTIAL_INT_MAP = "ModExponentialIntMap";
/** The name for the {@link ModifiedZigguratExponentialSamplerEMaxTable}. */
static final String MOD_EXPONENTIAL_E_MAX_TABLE = "ModExponentialEmaxTable";
/** The name for the {@link ModifiedZigguratExponentialSamplerEMax2}. */
static final String MOD_EXPONENTIAL_E_MAX_2 = "ModExponentialEmax2";
/** The name for the {@link ModifiedZigguratExponentialSamplerTernary}. */
static final String MOD_EXPONENTIAL_TERNARY = "ModExponentialTernary";
/** The name for the {@link ModifiedZigguratExponentialSamplerTernarySubtract}. */
static final String MOD_EXPONENTIAL_TERNARY_SUBTRACT = "ModExponentialTernarySubtract";
/** The name for the {@link ModifiedZigguratExponentialSampler512} using a table size of 512. */
static final String MOD_EXPONENTIAL_512 = "ModExponential512";
/** Mask to create an unsigned long from a signed long. */
private static final long MAX_INT64 = 0x7fffffffffffffffL;
/** 2^53. */
private static final double TWO_POW_63 = 0x1.0p63;
/**
* The value.
*
* <p>This must NOT be final!</p>
*/
private double value;
/**
* Defines method to use for creating {@code int} index values from a random long.
*/
@State(Scope.Benchmark)
public static class IndexSources {
/** The method to obtain the index. */
@Param({"CastMask", "MaskCast"})
private String method;
/** The sampler. */
private DiscreteSampler sampler;
/**
* @return the sampler.
*/
public DiscreteSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
// Use a fast generator
final UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create();
if ("CastMask".equals(method)) {
sampler = () -> {
final long x = rng.nextLong();
return ((int) x) & 0xff;
};
} else if ("MaskCast".equals(method)) {
sampler = () -> {
final long x = rng.nextLong();
return (int) (x & 0xff);
};
} else {
throwIllegalStateException(method);
}
}
}
/**
* Defines method to use for creating an index values from a random long and comparing
* it to an {@code int} limit.
*/
@State(Scope.Benchmark)
public static class IndexCompareSources {
/** The method to compare the index against the limit. */
@Param({"CastMaskIntCompare", "MaskCastIntCompare", "MaskLongCompareCast"})
private String method;
/** The sampler. */
private DiscreteSampler sampler;
/**
* @return the sampler.
*/
public DiscreteSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
// The limit:
// exponential = 252
// gaussian = 253
final int limit = 253;
// Use a fast generator:
final UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create();
if ("CastMaskIntCompare".equals(method)) {
sampler = () -> {
final long x = rng.nextLong();
final int i = ((int) x) & 0xff;
if (i < limit) {
return i;
}
return 0;
};
} else if ("MaskCastIntCompare".equals(method)) {
sampler = () -> {
final long x = rng.nextLong();
final int i = (int) (x & 0xff);
if (i < limit) {
return i;
}
return 0;
};
} else if ("MaskLongCompareCast".equals(method)) {
sampler = () -> {
final long x = rng.nextLong();
final long i = x & 0xff;
if (i < limit) {
return (int) i;
}
return 0;
};
} else {
throwIllegalStateException(method);
}
}
}
/**
* Defines method to use for creating unsigned {@code long} values.
*/
@State(Scope.Benchmark)
public static class LongSources {
/** The method to obtain the long. */
@Param({"Mask", "Shift"})
private String method;
/** The sampler. */
private LongSampler sampler;
/**
* @return the sampler.
*/
public LongSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
// Use a fast generator:
// Here we use a simple linear congruential generator
// which should have constant speed and a random upper bit.
final long[] s = {ThreadLocalRandom.current().nextLong()};
if ("Mask".equals(method)) {
sampler = () -> {
final long x = s[0];
s[0] = updateLCG(x);
return x & Long.MAX_VALUE;
};
} else if ("Shift".equals(method)) {
sampler = () -> {
final long x = s[0];
s[0] = updateLCG(x);
return x >>> 1;
};
} else {
throwIllegalStateException(method);
}
}
}
/**
* Defines method to use for interpolating the X or Y tables from unsigned {@code long} values.
*/
@State(Scope.Benchmark)
public static class InterpolationSources {
/** The method to perform interpolation. */
@Param({"U1", "1minusU2", "U_1minusU"})
private String method;
/** The sampler. */
private ContinuousSampler sampler;
/**
* @return the sampler.
*/
public ContinuousSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
// Use a fast generator:
final UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create();
// Get an x table. This is length 254.
// We will sample from this internally to avoid index out-of-bounds issues.
final int start = 42;
final double[] x = Arrays.copyOfRange(
ModifiedZigguratNormalizedGaussianSampler.getX(), start, start + 129);
final int mask = 127;
if ("U1".equals(method)) {
sampler = () -> {
final long u = rng.nextLong();
final int j = 1 + (((int) u) & mask);
// double multiply
// double add
// double subtract
// long convert to double
// double multiply
// int subtract
// three index loads
// Same as sampleX(x, j, u)
return x[j] * TWO_POW_63 + (x[j - 1] - x[j]) * u;
};
} else if ("1minusU2".equals(method)) {
sampler = () -> {
final long u = rng.nextLong();
final int j = 1 + (((int) u) & mask);
// Since u is in [0, 2^63) to create (1 - u) using Long.MIN_VALUE
// as an unsigned integer of 2^63.
// double multiply
// double add
// double subtract
// long subtract
// long convert to double
// double multiply
// int subtract * 2
// three index loads
// Same as sampleY(x, j, u)
return x[j - 1] * TWO_POW_63 + (x[j] - x[j - 1]) * (Long.MIN_VALUE - u);
};
} else if ("U_1minusU".equals(method)) {
sampler = () -> {
final long u = rng.nextLong();
final int j = 1 + (((int) u) & mask);
// Interpolation between bounds a and b using:
// a * u + b * (1 - u) == b + u * (a - b)
// long convert to double
// double multiply
// double add
// long subtract
// long convert to double
// double multiply
// int subtract
// two index loads
return x[j - 1] * u + x[j] * (Long.MIN_VALUE - u);
};
} else {
throwIllegalStateException(method);
}
}
}
/**
* Defines method to extract a sign bit from a {@code long} value.
*/
@State(Scope.Benchmark)
public static class SignBitSources {
/** The method to obtain the sign bit. */
@Param({"ifNegative", "ifSignBit", "ifBit", "bitSubtract", "signBitSubtract"})
private String method;
/** The sampler. */
private ContinuousSampler sampler;
/**
* @return the sampler.
*/
public ContinuousSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
// Use a fast generator:
final UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create();
if ("ifNegative".equals(method)) {
sampler = () -> {
final long x = rng.nextLong();
return x < 0 ? -1.0 : 1.0;
};
} else if ("ifSignBit".equals(method)) {
sampler = () -> {
final long x = rng.nextLong();
return (x >>> 63) == 0 ? -1.0 : 1.0;
};
} else if ("ifBit".equals(method)) {
sampler = () -> {
final long x = rng.nextLong();
return (x & 0x100) == 0 ? -1.0 : 1.0;
};
} else if ("bitSubtract".equals(method)) {
sampler = () -> {
final long x = rng.nextLong();
return ((x >>> 7) & 0x2) - 1.0;
};
} else if ("signBitSubtract".equals(method)) {
sampler = () -> {
final long x = rng.nextLong();
return ((x >>> 62) & 0x2) - 1.0;
};
} else {
throwIllegalStateException(method);
}
}
}
/**
* Defines method to use for computing {@code exp(x)} when {@code -8 <= x <= 0}.
*/
@State(Scope.Benchmark)
public static class ExpSources {
/** The method to compute exp(x). */
@Param({"noop", "Math.exp", "FastMath.exp"})
private String method;
/** The sampler. */
private ContinuousSampler sampler;
/**
* @return the sampler.
*/
public ContinuousSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
// Use a fast generator:
// Here we use a simple linear congruential generator
// which should have constant speed and a random upper bit.
final long[] s = {ThreadLocalRandom.current().nextLong()};
// From a random long we create a value in (-8, 0] by using the
// method to generate [0, 1) and then multiplying by -8:
// (x >>> 11) * 0x1.0p-53 * -0x1.0p3
if ("noop".equals(method)) {
sampler = () -> {
final long x = s[0];
s[0] = updateLCG(x);
return (x >>> 11) * -0x1.0p-50;
};
} else if ("Math.exp".equals(method)) {
sampler = () -> {
final long x = s[0];
s[0] = updateLCG(x);
return Math.exp((x >>> 11) * -0x1.0p-50);
};
} else if ("FastMath.exp".equals(method)) {
sampler = () -> {
final long x = s[0];
s[0] = updateLCG(x);
return FastMath.exp((x >>> 11) * -0x1.0p-50);
};
} else {
throwIllegalStateException(method);
}
}
}
/**
* Defines method to use for creating two random {@code long} values in ascending order.
*/
@State(Scope.Benchmark)
public static class DiffSources {
/** The method to obtain the long. */
@Param({"None", "Branch", "Ternary", "TernarySubtract"})
private String method;
/** The sampler. */
private ObjectSampler<long[]> sampler;
/**
* @return the sampler.
*/
public ObjectSampler<long[]> getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
// Use a fast generator:
final UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create();
final long[] tmp = new long[2];
if ("None".equals(method)) {
sampler = () -> {
tmp[0] = rng.nextLong() >>> 1;
tmp[1] = rng.nextLong() >>> 1;
return tmp;
};
} else if ("Branch".equals(method)) {
sampler = () -> {
long u1 = rng.nextLong() >>> 1;
long uDistance = (rng.nextLong() >>> 1) - u1;
if (uDistance < 0) {
// Upper-right triangle. Reflect in hypotenuse.
uDistance = -uDistance;
// Update u1 to be min(u1, u2) by subtracting the distance between them
u1 -= uDistance;
}
tmp[0] = u1;
tmp[1] = uDistance;
return tmp;
};
} else if ("Ternary".equals(method)) {
sampler = () -> {
long u1 = rng.nextLong() >>> 1;
long u2 = rng.nextLong() >>> 1;
tmp[0] = u1 < u2 ? u1 : u2;
tmp[1] = u1 < u2 ? u2 : u1;
return tmp;
};
} else if ("TernarySubtract".equals(method)) {
sampler = () -> {
long u1 = rng.nextLong() >>> 1;
long u2 = rng.nextLong() >>> 1;
long u = u1 < u2 ? u1 : u2;
tmp[0] = u;
tmp[1] = u1 + u2 - u;
return tmp;
};
} else {
throwIllegalStateException(method);
}
}
}
/**
* Update the state of the linear congruential generator.
* <pre>
* s = m*s + a
* </pre>
*
* <p>This can be used when the upper bits of the long are important.
* The lower bits will not be very random. Each bit has a period of
* 2^p where p is the bit significance.
*
* @param state the state
* @return the new state
*/
private static long updateLCG(long state) {
// m is the multiplier used for the LCG component of the JDK 17 generators.
// a can be any odd number.
// Use the golden ratio from a SplitMix64 generator.
return 0xd1342543de82ef95L * state + 0x9e3779b97f4a7c15L;
}
/**
* The samplers to use for testing the ziggurat method.
*/
@State(Scope.Benchmark)
public abstract static class Sources {
/**
* The sampler type.
*/
@Param({// Production versions
GAUSSIAN_128, GAUSSIAN_256, MOD_GAUSSIAN, MOD_EXPONENTIAL,
// Experimental Marsaglia exponential ziggurat sampler
EXPONENTIAL,
// Experimental McFarland Gaussian ziggurat samplers
MOD_GAUSSIAN2, MOD_GAUSSIAN_SIMPLE_OVERHANGS,
MOD_GAUSSIAN_INLINING, MOD_GAUSSIAN_INLINING_SHIFT,
MOD_GAUSSIAN_INLINING_SIMPLE_OVERHANGS, MOD_GAUSSIAN_INT_MAP,
MOD_GAUSSIAN_E_MAX_TABLE, MOD_GAUSSIAN_E_MAX_2,
MOD_GAUSSIAN_TERNARY, MOD_GAUSSIAN_512,
// Experimental McFarland Gaussian ziggurat samplers
MOD_EXPONENTIAL2, MOD_EXPONENTIAL_SIMPLE_OVERHANGS, MOD_EXPONENTIAL_INLINING,
MOD_EXPONENTIAL_LOOP, MOD_EXPONENTIAL_LOOP2,
MOD_EXPONENTIAL_RECURSION, MOD_EXPONENTIAL_INT_MAP,
MOD_EXPONENTIAL_E_MAX_TABLE, MOD_EXPONENTIAL_E_MAX_2,
MOD_EXPONENTIAL_TERNARY, MOD_EXPONENTIAL_TERNARY_SUBTRACT, MOD_EXPONENTIAL_512})
private String type;
/** Flag to indicate that the sample targets the overhangs.
* This is applicable to the McFarland Ziggurat sampler and
* requires manipulation of the final bits of the RNG. */
@Param({"true", "false"})
private boolean overhang;
/**
* Creates the sampler.
*
* <p>This may return a specialisation for the McFarland sampler that only samples
* from overhangs.
*
* @param rng RNG
* @return the sampler
*/
protected ContinuousSampler createSampler(UniformRandomProvider rng) {
if (!overhang) {
return createSampler(type, rng);
}
// For the Marsaglia Ziggurat sampler overhangs are only tested once then
// the method recurses the entire sample method. Overhang sampling cannot be forced
// for this sampler.
if (GAUSSIAN_128.equals(type) ||
GAUSSIAN_256.equals(type) ||
EXPONENTIAL.equals(type)) {
return createSampler(type, rng);
}
// Assume the sampler is a McFarland Ziggurat sampler.
// Manipulate the final bits of the long from the RNG to force sampling
// from the overhang. Assume most of the samplers use an 8-bit look-up table.
int numberOfBits = 8;
if (type.contains("512")) {
// 9-bit look-up table
numberOfBits = 9;
}
// Use an RNG that can set the lower bits of the long.
final ModifiedRNG modRNG = new ModifiedRNG(rng, numberOfBits);
final ContinuousSampler sampler = createSampler(type, modRNG);
// Create a sampler where each call should force overhangs/tail sampling
return new ContinuousSampler() {
@Override
public double sample() {
modRNG.modifyNextLong();
return sampler.sample();
}
};
}
/**
* Creates the sampler.
*
* @param type Type of sampler
* @param rng RNG
* @return the sampler
*/
static ContinuousSampler createSampler(String type, UniformRandomProvider rng) {
if (GAUSSIAN_128.equals(type)) {
return new ZigguratNormalizedGaussianSampler128(rng);
} else if (GAUSSIAN_256.equals(type)) {
return ZigguratNormalizedGaussianSampler.of(rng);
} else if (MOD_GAUSSIAN.equals(type)) {
return ZigguratSampler.NormalizedGaussian.of(rng);
} else if (MOD_EXPONENTIAL.equals(type)) {
return ZigguratSampler.Exponential.of(rng);
} else if (EXPONENTIAL.equals(type)) {
return new ZigguratExponentialSampler(rng);
} else if (MOD_GAUSSIAN2.equals(type)) {
return new ModifiedZigguratNormalizedGaussianSampler(rng);
} else if (MOD_GAUSSIAN_SIMPLE_OVERHANGS.equals(type)) {
return new ModifiedZigguratNormalizedGaussianSamplerSimpleOverhangs(rng);
} else if (MOD_GAUSSIAN_INLINING.equals(type)) {
return new ModifiedZigguratNormalizedGaussianSamplerInlining(rng);
} else if (MOD_GAUSSIAN_INLINING_SHIFT.equals(type)) {
return new ModifiedZigguratNormalizedGaussianSamplerInliningShift(rng);
} else if (MOD_GAUSSIAN_INLINING_SIMPLE_OVERHANGS.equals(type)) {
return new ModifiedZigguratNormalizedGaussianSamplerInliningSimpleOverhangs(rng);
} else if (MOD_GAUSSIAN_INT_MAP.equals(type)) {
return new ModifiedZigguratNormalizedGaussianSamplerIntMap(rng);
} else if (MOD_GAUSSIAN_E_MAX_TABLE.equals(type)) {
return new ModifiedZigguratNormalizedGaussianSamplerEMaxTable(rng);
} else if (MOD_GAUSSIAN_E_MAX_2.equals(type)) {
return new ModifiedZigguratNormalizedGaussianSamplerEMax2(rng);
} else if (MOD_GAUSSIAN_TERNARY.equals(type)) {
return new ModifiedZigguratNormalizedGaussianSamplerTernary(rng);
} else if (MOD_GAUSSIAN_512.equals(type)) {
return new ModifiedZigguratNormalizedGaussianSampler512(rng);
} else if (MOD_EXPONENTIAL2.equals(type)) {
return new ModifiedZigguratExponentialSampler(rng);
} else if (MOD_EXPONENTIAL_SIMPLE_OVERHANGS.equals(type)) {
return new ModifiedZigguratExponentialSamplerSimpleOverhangs(rng);
} else if (MOD_EXPONENTIAL_INLINING.equals(type)) {
return new ModifiedZigguratExponentialSamplerInlining(rng);
} else if (MOD_EXPONENTIAL_LOOP.equals(type)) {
return new ModifiedZigguratExponentialSamplerLoop(rng);
} else if (MOD_EXPONENTIAL_LOOP2.equals(type)) {
return new ModifiedZigguratExponentialSamplerLoop2(rng);
} else if (MOD_EXPONENTIAL_RECURSION.equals(type)) {
return new ModifiedZigguratExponentialSamplerRecursion(rng);
} else if (MOD_EXPONENTIAL_INT_MAP.equals(type)) {
return new ModifiedZigguratExponentialSamplerIntMap(rng);
} else if (MOD_EXPONENTIAL_E_MAX_TABLE.equals(type)) {
return new ModifiedZigguratExponentialSamplerEMaxTable(rng);
} else if (MOD_EXPONENTIAL_E_MAX_2.equals(type)) {
return new ModifiedZigguratExponentialSamplerEMax2(rng);
} else if (MOD_EXPONENTIAL_TERNARY.equals(type)) {
return new ModifiedZigguratExponentialSamplerTernary(rng);
} else if (MOD_EXPONENTIAL_TERNARY_SUBTRACT.equals(type)) {
return new ModifiedZigguratExponentialSamplerTernarySubtract(rng);
} else if (MOD_EXPONENTIAL_512.equals(type)) {
return new ModifiedZigguratExponentialSampler512(rng);
} else {
throw new IllegalStateException("Unknown type: " + type);
}
}
/**
* A class that can modify the lower bits to be all set for the next invocation of
* {@link UniformRandomProvider#nextLong()}.
*/
private static class ModifiedRNG implements UniformRandomProvider {
/** Underlying source of randomness. */
private final UniformRandomProvider rng;
/** The bits to set in the output long using a bitwise or ('|'). */
private final long bits;
/** The next bits to set in the output long using a bitwise or ('|'). */
private long nextBits;
/**
* @param rng Underlying source of randomness
* @param numberOfBits Number of least significant bits to set for a call to nextLong()
*/
ModifiedRNG(UniformRandomProvider rng, int numberOfBits) {
this.rng = rng;
bits = (1L << numberOfBits) - 1;
}
/**
* Set the state to modify the lower bits on the next call to nextLong().
*/
void modifyNextLong() {
nextBits = bits;
}
@Override
public long nextLong() {
final long x = rng.nextLong() | nextBits;
nextBits = 0;
return x;
}
// The following methods should not be used.
@Override
public void nextBytes(byte[] bytes) {
throw new IllegalStateException();
}
@Override
public void nextBytes(byte[] bytes, int start, int len) {
throw new IllegalStateException();
}
@Override
public int nextInt() {
throw new IllegalStateException();
}
@Override
public int nextInt(int n) {
throw new IllegalStateException();
}
@Override
public long nextLong(long n) {
throw new IllegalStateException();
}
@Override
public boolean nextBoolean() {
throw new IllegalStateException();
}
@Override
public float nextFloat() {
throw new IllegalStateException();
}
@Override
public double nextDouble() {
throw new IllegalStateException();
}
}
}
/**
* The samplers to use for testing the ziggurat method with single sample generation.
* Defines the RandomSource and the sampler type.
*/
@State(Scope.Benchmark)
public static class SingleSources extends Sources {
/**
* RNG providers.
*
* <p>Use different speeds.</p>
*
* @see <a href="https://commons.apache.org/proper/commons-rng/userguide/rng.html">
* Commons RNG user guide</a>
*/
@Param({"XO_RO_SHI_RO_128_PP",
"MWC_256",
"JDK"})
private String randomSourceName;
/** The sampler. */
private ContinuousSampler sampler;
/**
* @return the sampler.
*/
public ContinuousSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
final RandomSource randomSource = RandomSource.valueOf(randomSourceName);
final UniformRandomProvider rng = randomSource.create();
sampler = createSampler(rng);
}
}
/**
* The samplers to use for testing the ziggurat method with sequential sample generation.
* Defines the RandomSource and the sampler type.
*
* <p>This specifically targets repeat calls to the same sampler.
* Performance should scale linearly with the size. A plot of size against time
* can identify outliers and should allow ranking of different methods.
*
* <p>Note: Testing using a single call to the sampler may return different relative
* performance of the samplers than when testing using multiple calls. This is due to the
* single calls being performed multiple times by the JMH framework rather than a
* single block of code. Rankings should be consistent and the optimal sampler method
* chosen using both sets of results.
*/
@State(Scope.Benchmark)
public static class SequentialSources extends Sources {
/**
* RNG providers.
*
* <p>Use different speeds.</p>
*
* @see <a href="https://commons.apache.org/proper/commons-rng/userguide/rng.html">
* Commons RNG user guide</a>
*/
@Param({"XO_RO_SHI_RO_128_PP",
//"MWC_256",
//"JDK"
})
private String randomSourceName;
/** The size. */
@Param({"1", "2", "4", "8", "16", "32", "64"})
private int size;
/** The sampler. */
private ContinuousSampler sampler;
/**
* @return the sampler.
*/
public ContinuousSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
final RandomSource randomSource = RandomSource.valueOf(randomSourceName);
final UniformRandomProvider rng = randomSource.create();
final ContinuousSampler s = createSampler(rng);
sampler = createSequentialSampler(size, s);
}
/**
* Creates the sampler for the specified number of samples.
*
* @param size the size
* @param s the sampler to create the samples
* @return the sampler
*/
private static ContinuousSampler createSequentialSampler(int size, ContinuousSampler s) {
// Create size samples
switch (size) {
case 1:
return new Size1Sampler(s);
case 2:
return new Size2Sampler(s);
case 3:
return new Size3Sampler(s);
case 4:
return new Size4Sampler(s);
case 5:
return new Size5Sampler(s);
default:
return new SizeNSampler(s, size);
}
}
/**
* Create a specified number of samples from an underlying sampler.
*/
abstract static class SizeSampler implements ContinuousSampler {
/** The sampler. */
protected ContinuousSampler delegate;
/**
* @param delegate the sampler to create the samples
*/
SizeSampler(ContinuousSampler delegate) {
this.delegate = delegate;
}
}
/**
* Create 1 sample from the sampler.
*/
static class Size1Sampler extends SizeSampler {
/**
* @param delegate the sampler to create the samples
*/
Size1Sampler(ContinuousSampler delegate) {
super(delegate);
}
@Override
public double sample() {
return delegate.sample();
}
}
/**
* Create 2 samples from the sampler.
*/
static class Size2Sampler extends SizeSampler {
/**
* @param delegate the sampler to create the samples
*/
Size2Sampler(ContinuousSampler delegate) {
super(delegate);
}
@Override
public double sample() {
delegate.sample();
return delegate.sample();
}
}
/**
* Create 3 samples from the sampler.
*/
static class Size3Sampler extends SizeSampler {
/**
* @param delegate the sampler to create the samples
*/
Size3Sampler(ContinuousSampler delegate) {
super(delegate);
}
@Override
public double sample() {
delegate.sample();
delegate.sample();
return delegate.sample();
}
}
/**
* Create 4 samples from the sampler.
*/
static class Size4Sampler extends SizeSampler {
/**
* @param delegate the sampler to create the samples
*/
Size4Sampler(ContinuousSampler delegate) {
super(delegate);
}
@Override
public double sample() {
delegate.sample();
delegate.sample();
delegate.sample();
return delegate.sample();
}
}
/**
* Create 5 samples from the sampler.
*/
static class Size5Sampler extends SizeSampler {
/**
* @param delegate the sampler to create the samples
*/
Size5Sampler(ContinuousSampler delegate) {
super(delegate);
}
@Override
public double sample() {
delegate.sample();
delegate.sample();
delegate.sample();
delegate.sample();
return delegate.sample();
}
}
/**
* Create N samples from the sampler.
*/
static class SizeNSampler extends SizeSampler {
/** The number of samples minus 1. */
private final int sizeM1;
/**
* @param delegate the sampler to create the samples
* @param size the size
*/
SizeNSampler(ContinuousSampler delegate, int size) {
super(delegate);
if (size < 1) {
throw new IllegalArgumentException("Size must be above zero: " + size);
}
this.sizeM1 = size - 1;
}
@Override
public double sample() {
for (int i = sizeM1; i != 0; i--) {
delegate.sample();
}
return delegate.sample();
}
}
}
/**
* <a href="https://en.wikipedia.org/wiki/Ziggurat_algorithm">
* Marsaglia and Tsang "Ziggurat" method</a> for sampling from a NormalizedGaussian
* distribution with mean 0 and standard deviation 1.
*
* <p>This is a copy of {@link ZigguratNormalizedGaussianSampler} using a table size of 256.
*/
static class ZigguratNormalizedGaussianSampler128 implements ContinuousSampler {
/** Start of tail. */
private static final double R = 3.442619855899;
/** Inverse of R. */
private static final double ONE_OVER_R = 1 / R;
/** Index of last entry in the tables (which have a size that is a power of 2). */
private static final int LAST = 127;
/** Auxiliary table. */
private static final long[] K;
/** Auxiliary table. */
private static final double[] W;
/** Auxiliary table. */
private static final double[] F;
/**
* The multiplier to convert the least significant 53-bits of a {@code long} to a {@code double}.
* Taken from org.apache.commons.rng.core.util.NumberFactory.
*/
private static final double DOUBLE_MULTIPLIER = 0x1.0p-53d;
/** Underlying source of randomness. */
private final UniformRandomProvider rng;
static {
// Filling the tables.
// Rectangle area.
final double v = 9.91256303526217e-3;
// Direction support uses the sign bit so the maximum magnitude from the long is 2^63
final double max = Math.pow(2, 63);
final double oneOverMax = 1d / max;
K = new long[LAST + 1];
W = new double[LAST + 1];
F = new double[LAST + 1];
double d = R;
double t = d;
double fd = pdf(d);
final double q = v / fd;
K[0] = (long) ((d / q) * max);
K[1] = 0;
W[0] = q * oneOverMax;
W[LAST] = d * oneOverMax;
F[0] = 1;
F[LAST] = fd;
for (int i = LAST - 1; i >= 1; i--) {
d = Math.sqrt(-2 * Math.log(v / d + fd));
fd = pdf(d);
K[i + 1] = (long) ((d / t) * max);
t = d;
F[i] = fd;
W[i] = d * oneOverMax;
}
}
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ZigguratNormalizedGaussianSampler128(UniformRandomProvider rng) {
this.rng = rng;
}
/** {@inheritDoc} */
@Override
public double sample() {
final long j = rng.nextLong();
final int i = ((int) j) & LAST;
if (Math.abs(j) < K[i]) {
// This branch is called about 0.972101 times per sample.
return j * W[i];
}
return fix(j, i);
}
/**
* Gets the value from the tail of the distribution.
*
* @param hz Start random integer.
* @param iz Index of cell corresponding to {@code hz}.
* @return the requested random value.
*/
private double fix(long hz,
int iz) {
if (iz == 0) {
// Base strip.
// This branch is called about 5.7624515E-4 times per sample.
double y;
double x;
do {
// Avoid infinity by creating a non-zero double.
y = -Math.log(makeNonZeroDouble(rng.nextLong()));
x = -Math.log(makeNonZeroDouble(rng.nextLong())) * ONE_OVER_R;
} while (y + y < x * x);
final double out = R + x;
return hz > 0 ? out : -out;
}
// Wedge of other strips.
// This branch is called about 0.027323 times per sample.
final double x = hz * W[iz];
if (F[iz] + rng.nextDouble() * (F[iz - 1] - F[iz]) < pdf(x)) {
// This branch is called about 0.014961 times per sample.
return x;
}
// Try again.
// This branch is called about 0.012362 times per sample.
return sample();
}
/**
* Creates a {@code double} in the interval {@code (0, 1]} from a {@code long} value.
*
* @param v Number.
* @return a {@code double} value in the interval {@code (0, 1]}.
*/
private static double makeNonZeroDouble(long v) {
// This matches the method in o.a.c.rng.core.util.NumberFactory.makeDouble(long)
// but shifts the range from [0, 1) to (0, 1].
return ((v >>> 11) + 1L) * DOUBLE_MULTIPLIER;
}
/**
* Compute the Gaussian probability density function {@code f(x) = e^-0.5x^2}.
*
* @param x Argument.
* @return \( e^{-\frac{x^2}{2}} \)
*/
private static double pdf(double x) {
return Math.exp(-0.5 * x * x);
}
}
/**
* <a href="https://en.wikipedia.org/wiki/Ziggurat_algorithm">
* Marsaglia and Tsang "Ziggurat" method</a> for sampling from an exponential
* distribution.
*
* <p>The algorithm is explained in this
* <a href="http://www.jstatsoft.org/article/view/v005i08/ziggurat.pdf">paper</a>
* and this implementation has been adapted from the C code provided therein.</p>
*/
static class ZigguratExponentialSampler implements ContinuousSampler {
/** Start of tail. */
private static final double R = 7.69711747013104972;
/** Index of last entry in the tables (which have a size that is a power of 2). */
private static final int LAST = 255;
/** Auxiliary table. */
private static final long[] K;
/** Auxiliary table. */
private static final double[] W;
/** Auxiliary table. */
private static final double[] F;
/** Underlying source of randomness. */
private final UniformRandomProvider rng;
static {
// Filling the tables.
// Rectangle area.
final double v = 0.0039496598225815571993;
// No support for unsigned long so the upper bound is 2^63
final double max = Math.pow(2, 63);
final double oneOverMax = 1d / max;
K = new long[LAST + 1];
W = new double[LAST + 1];
F = new double[LAST + 1];
double d = R;
double t = d;
double fd = pdf(d);
final double q = v / fd;
K[0] = (long) ((d / q) * max);
K[1] = 0;
W[0] = q * oneOverMax;
W[LAST] = d * oneOverMax;
F[0] = 1;
F[LAST] = fd;
for (int i = LAST - 1; i >= 1; i--) {
d = -Math.log(v / d + fd);
fd = pdf(d);
K[i + 1] = (long) ((d / t) * max);
t = d;
F[i] = fd;
W[i] = d * oneOverMax;
}
}
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ZigguratExponentialSampler(UniformRandomProvider rng) {
this.rng = rng;
}
/** {@inheritDoc} */
@Override
public double sample() {
// An unsigned long in [0, 2^63)
final long j = rng.nextLong() >>> 1;
final int i = ((int) j) & LAST;
if (j < K[i]) {
// This branch is called about 0.977777 times per call into createSample.
// Note: Frequencies have been empirically measured for the first call to
// createSample; recursion due to retries have been ignored. Frequencies sum to 1.
return j * W[i];
}
return fix(j, i);
}
/**
* Gets the value from the tail of the distribution.
*
* @param jz Start random integer.
* @param iz Index of cell corresponding to {@code jz}.
* @return the requested random value.
*/
private double fix(long jz,
int iz) {
if (iz == 0) {
// Base strip.
// This branch is called about 0.000448867 times per call into createSample.
return R - Math.log(rng.nextDouble());
}
// Wedge of other strips.
final double x = jz * W[iz];
if (F[iz] + rng.nextDouble() * (F[iz - 1] - F[iz]) < pdf(x)) {
// This branch is called about 0.0107820 times per call into createSample.
return x;
}
// Try again.
// This branch is called about 0.0109920 times per call into createSample
// i.e. this is the recursion frequency.
return sample();
}
/**
* Compute the exponential probability density function {@code f(x) = e^-x}.
*
* @param x Argument.
* @return {@code e^-x}
*/
private static double pdf(double x) {
return Math.exp(-x);
}
}
/**
* Modified Ziggurat method for sampling from a Gaussian distribution with mean 0 and standard deviation 1.
*
* <p>Uses the algorithm from:
*
* <blockquote>
* McFarland, C.D. (2016)<br>
* "A modified ziggurat algorithm for generating exponentially and normally distributed pseudorandom numbers".<br>
* <i>Journal of Statistical Computation and Simulation</i> <b>86</b>, 1281-1294.
* </blockquote>
*
* <p>This class uses the same tables as the production version
* {@link org.apache.commons.rng.sampling.distribution.ZigguratSampler.NormalizedGaussian}
* with the overhang sampling matching the reference c implementation. Methods and members
* are protected to allow the implementation to be modified in sub-classes.
*
* @see <a href="https://www.tandfonline.com/doi/abs/10.1080/00949655.2015.1060234">
* McFarland (2016) JSCS 86, 1281-1294</a>
*/
static class ModifiedZigguratNormalizedGaussianSampler implements ContinuousSampler {
// Ziggurat volumes:
// Inside the layers = 98.8281% (253/256)
// Fraction outside the layers:
// convex overhangs = 76.1941%
// inflection overhang = 0.1358%
// concave overhangs = 21.3072%
// tail = 2.3629%
/** The number of layers in the ziggurat. Maximum i value for early exit. */
protected static final int I_MAX = 253;
/** The point where the Gaussian switches from convex to concave.
* This is the largest value of X[j] below 1. */
protected static final int J_INFLECTION = 204;
/** Maximum epsilon distance of convex pdf(x) above the hypotenuse value for early rejection.
* Equal to approximately 0.2460 scaled by 2^63. This is negated on purpose as the
* distance for a point (x,y) above the hypotenuse is negative:
* {@code (|d| < max) == (d >= -max)}. */
protected static final long CONVEX_E_MAX = -2269182951627976004L;
/** Maximum distance of concave pdf(x) below the hypotenuse value for early exit.
* Equal to approximately 0.08244 scaled by 2^63. */
protected static final long CONCAVE_E_MAX = 760463704284035184L;
/** Beginning of tail. Equal to X[0] * 2^63. */
protected static final double X_0 = 3.6360066255009455861;
/** 1/X_0. Used for tail sampling. */
protected static final double ONE_OVER_X_0 = 1.0 / X_0;
/** The alias map. An integer in [0, 255] stored as a byte to save space. */
protected static final byte[] MAP = {
/* [ 0] */ (byte) 0, (byte) 0, (byte) 239, (byte) 2, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
/* [ 8] */ (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 1, (byte) 1, (byte) 1, (byte) 253,
/* [ 16] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [ 24] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [ 32] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [ 40] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [ 48] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [ 56] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [ 64] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [ 72] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [ 80] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [ 88] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [ 96] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [104] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [112] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [120] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [128] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [136] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [144] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [152] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [160] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [168] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [176] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [184] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253,
/* [192] */ (byte) 253, (byte) 253, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [200] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 251, (byte) 251, (byte) 251, (byte) 251,
/* [208] */ (byte) 251, (byte) 251, (byte) 251, (byte) 250, (byte) 250, (byte) 250, (byte) 250, (byte) 250,
/* [216] */ (byte) 249, (byte) 249, (byte) 249, (byte) 248, (byte) 248, (byte) 248, (byte) 247, (byte) 247,
/* [224] */ (byte) 247, (byte) 246, (byte) 246, (byte) 245, (byte) 244, (byte) 244, (byte) 243, (byte) 242,
/* [232] */ (byte) 240, (byte) 2, (byte) 2, (byte) 3, (byte) 3, (byte) 0, (byte) 0, (byte) 240,
/* [240] */ (byte) 241, (byte) 242, (byte) 243, (byte) 244, (byte) 245, (byte) 246, (byte) 247, (byte) 248,
/* [248] */ (byte) 249, (byte) 250, (byte) 251, (byte) 252, (byte) 253, (byte) 1, (byte) 0, (byte) 0,
};
/** The alias inverse PMF. */
protected static final long[] IPMF = {
/* [ 0] */ 9223372036854775296L, 1100243796534090752L, 7866600928998383104L, 6788754710675124736L,
/* [ 4] */ 9022865200181688320L, 6522434035205502208L, 4723064097360024576L, 3360495653216416000L,
/* [ 8] */ 2289663232373870848L, 1423968905551920384L, 708364817827798016L, 106102487305601280L,
/* [ 12] */ -408333464665794560L, -853239722779025152L, -1242095211825521408L, -1585059631105762048L,
/* [ 16] */ -1889943050287169024L, -2162852901990669824L, -2408637386594511104L, -2631196530262954496L,
/* [ 20] */ -2833704942520925696L, -3018774289025787392L, -3188573753472222208L, -3344920681707410944L,
/* [ 24] */ -3489349705062150656L, -3623166100042179584L, -3747487436868335360L, -3863276422712173824L,
/* [ 28] */ -3971367044063130880L, -4072485557029824000L, -4167267476830916608L, -4256271432240159744L,
/* [ 32] */ -4339990541927306752L, -4418861817133802240L, -4493273980372377088L, -4563574004462246656L,
/* [ 36] */ -4630072609770453760L, -4693048910430964992L, -4752754358862894848L, -4809416110052769536L,
/* [ 40] */ -4863239903586985984L, -4914412541515875840L, -4963104028439161088L, -5009469424769119232L,
/* [ 44] */ -5053650458856559360L, -5095776932695077632L, -5135967952544929024L, -5174333008451230720L,
/* [ 48] */ -5210972924952654336L, -5245980700100460288L, -5279442247516297472L, -5311437055462369280L,
/* [ 52] */ -5342038772315650560L, -5371315728843297024L, -5399331404632512768L, -5426144845448965120L,
/* [ 56] */ -5451811038519422464L, -5476381248265593088L, -5499903320558339072L, -5522421955752311296L,
/* [ 60] */ -5543978956085263616L, -5564613449659060480L, -5584362093436146432L, -5603259257517428736L,
/* [ 64] */ -5621337193070986240L, -5638626184974132224L, -5655154691220933888L, -5670949470294763008L,
/* [ 68] */ -5686035697601807872L, -5700437072199152384L, -5714175914219812352L, -5727273255295220992L,
/* [ 72] */ -5739748920271997440L, -5751621603810412032L, -5762908939773946112L, -5773627565915007744L,
/* [ 76] */ -5783793183152377600L, -5793420610475628544L, -5802523835894661376L, -5811116062947570176L,
/* [ 80] */ -5819209754516120832L, -5826816672854571776L, -5833947916825278208L, -5840613956570608128L,
/* [ 84] */ -5846824665591763456L, -5852589350491075328L, -5857916778480726528L, -5862815203334800384L,
/* [ 88] */ -5867292388935742464L, -5871355631762284032L, -5875011781262890752L, -5878267259039093760L,
/* [ 92] */ -5881128076579883520L, -5883599852028851456L, -5885687825288565248L, -5887396872144963840L,
/* [ 96] */ -5888731517955042304L, -5889695949247728384L, -5890294025706689792L, -5890529289910829568L,
/* [100] */ -5890404977675987456L, -5889924026487208448L, -5889089083913555968L, -5887902514965209344L,
/* [104] */ -5886366408898372096L, -5884482585690639872L, -5882252601321090304L, -5879677752995027712L,
/* [108] */ -5876759083794175232L, -5873497386318840832L, -5869893206505510144L, -5865946846617024256L,
/* [112] */ -5861658367354159104L, -5857027590486131456L, -5852054100063428352L, -5846737243971504640L,
/* [116] */ -5841076134082373632L, -5835069647234580480L, -5828716424754549248L, -5822014871949021952L,
/* [120] */ -5814963157357531648L, -5807559211080072192L, -5799800723447229952L, -5791685142338073344L,
/* [124] */ -5783209670985158912L, -5774371264582489344L, -5765166627072226560L, -5755592207057667840L,
/* [128] */ -5745644193442049280L, -5735318510777133824L, -5724610813433666560L, -5713516480340333056L,
/* [132] */ -5702030608556698112L, -5690148005851018752L, -5677863184109371904L, -5665170350903313408L,
/* [136] */ -5652063400924580608L, -5638535907000141312L, -5624581109999480320L, -5610191908627599872L,
/* [140] */ -5595360848093632768L, -5580080108034218752L, -5564341489875549952L, -5548136403221394688L,
/* [144] */ -5531455851545399296L, -5514290416593586944L, -5496630242226406656L, -5478465016761742848L,
/* [148] */ -5459783954986665216L, -5440575777891777024L, -5420828692432397824L, -5400530368638773504L,
/* [152] */ -5379667916699401728L, -5358227861294116864L, -5336196115274292224L, -5313557951078385920L,
/* [156] */ -5290297970633451520L, -5266400072915222272L, -5241847420214015744L, -5216622401043726592L,
/* [160] */ -5190706591719534080L, -5164080714589203200L, -5136724594099067136L, -5108617109269313024L,
/* [164] */ -5079736143458214912L, -5050058530461741312L, -5019559997031891968L, -4988215100963582976L,
/* [168] */ -4955997165645491968L, -4922878208652041728L, -4888828866780320000L, -4853818314258475776L,
/* [172] */ -4817814175855180032L, -4780782432601701888L, -4742687321746719232L, -4703491227581444608L,
/* [176] */ -4663154564978699264L, -4621635653358766336L, -4578890580370785792L, -4534873055659683584L,
/* [180] */ -4489534251700611840L, -4442822631898829568L, -4394683764809104128L, -4345060121983362560L,
/* [184] */ -4293890858708922880L, -4241111576153830144L, -4186654061692619008L, -4130446006804747776L,
/* [188] */ -4072410698657718784L, -4012466683838401024L, -3950527400305017856L, -3886500774061896704L,
/* [192] */ -3820288777467837184L, -3751786943594897664L, -3680883832433527808L, -3607460442623922176L,
/* [196] */ -3531389562483324160L, -3452535052891361792L, -3370751053395887872L, -3285881101633968128L,
/* [200] */ -3197757155301365504L, -3106198503156485376L, -3011010550911937280L, -2911983463883580928L,
/* [204] */ -2808890647470271744L, -2701487041141149952L, -2589507199690603520L, -2472663129329160192L,
/* [208] */ -2350641842139870464L, -2223102583770035200L, -2089673683684728576L, -1949948966090106880L,
/* [212] */ -1803483646855993856L, -1649789631480328192L, -1488330106139747584L, -1318513295725618176L,
/* [216] */ -1139685236927327232L, -951121376596854784L, -752016768184775936L, -541474585642866432L,
/* [220] */ -318492605725778432L, -81947227249193216L, 169425512612864512L, 437052607232193536L,
/* [224] */ 722551297568809984L, 1027761939299714304L, 1354787941622770432L, 1706044619203941632L,
/* [228] */ 2084319374409574144L, 2492846399593711360L, 2935400169348532480L, 3416413484613111552L,
/* [232] */ 3941127949860576256L, 4515787798793437952L, 5147892401439714304L, 5846529325380406016L,
/* [236] */ 6622819682216655360L, 7490522659874166016L, 8466869998277892096L, 8216968526387345408L,
/* [240] */ 4550693915488934656L, 7628019504138977280L, 6605080500908005888L, 7121156327650272512L,
/* [244] */ 2484871780331574272L, 7179104797032803328L, 7066086283830045440L, 1516500120817362944L,
/* [248] */ 216305945438803456L, 6295963418525324544L, 2889316805630113280L, -2712587580533804032L,
/* [252] */ 6562498853538167040L, 7975754821147501312L, -9223372036854775808L, -9223372036854775808L,
};
/**
* The precomputed ziggurat lengths, denoted X_i in the main text. X_i = length of
* ziggurat layer i. Values have been scaled by 2^-63.
*/
protected static final double[] X = {
/* [ 0] */ 3.9421662825398133e-19, 3.7204945004119012e-19, 3.5827024480628678e-19, 3.4807476236540249e-19,
/* [ 4] */ 3.3990177171882136e-19, 3.3303778360340139e-19, 3.270943881761755e-19, 3.21835771324951e-19,
/* [ 8] */ 3.1710758541840432e-19, 3.1280307407034065e-19, 3.0884520655804019e-19, 3.0517650624107352e-19,
/* [ 12] */ 3.01752902925846e-19, 2.985398344070532e-19, 2.9550967462801797e-19, 2.9263997988491663e-19,
/* [ 16] */ 2.8991225869977476e-19, 2.8731108780226291e-19, 2.8482346327101335e-19, 2.8243831535194389e-19,
/* [ 20] */ 2.8014613964727031e-19, 2.7793871261807797e-19, 2.7580886921411212e-19, 2.7375032698308758e-19,
/* [ 24] */ 2.7175754543391047e-19, 2.6982561247538484e-19, 2.6795015188771505e-19, 2.6612724730440033e-19,
/* [ 28] */ 2.6435337927976633e-19, 2.6262537282028438e-19, 2.6094035335224142e-19, 2.5929570954331002e-19,
/* [ 32] */ 2.5768906173214726e-19, 2.5611823497719608e-19, 2.5458123593393361e-19, 2.5307623292372459e-19,
/* [ 36] */ 2.51601538677984e-19, 2.5015559533646191e-19, 2.4873696135403158e-19, 2.4734430003079206e-19,
/* [ 40] */ 2.4597636942892726e-19, 2.446320134791245e-19, 2.4331015411139206e-19, 2.4200978427132955e-19,
/* [ 44] */ 2.4072996170445879e-19, 2.3946980340903347e-19, 2.3822848067252674e-19, 2.3700521461931801e-19,
/* [ 48] */ 2.357992722074133e-19, 2.3460996262069972e-19, 2.3343663401054455e-19, 2.322786705467384e-19,
/* [ 52] */ 2.3113548974303765e-19, 2.3000654002704238e-19, 2.2889129852797606e-19, 2.2778926905921897e-19,
/* [ 56] */ 2.2669998027527321e-19, 2.2562298398527416e-19, 2.245578536072726e-19, 2.2350418274933911e-19,
/* [ 60] */ 2.2246158390513294e-19, 2.2142968725296249e-19, 2.2040813954857555e-19, 2.1939660310297601e-19,
/* [ 64] */ 2.1839475483749618e-19, 2.1740228540916853e-19, 2.1641889840016519e-19, 2.1544430956570613e-19,
/* [ 68] */ 2.1447824613540345e-19, 2.1352044616350571e-19, 2.1257065792395107e-19, 2.1162863934653125e-19,
/* [ 72] */ 2.1069415749082026e-19, 2.0976698805483467e-19, 2.0884691491567363e-19, 2.0793372969963634e-19,
/* [ 76] */ 2.0702723137954107e-19, 2.0612722589717129e-19, 2.0523352580895635e-19, 2.0434594995315797e-19,
/* [ 80] */ 2.0346432313698148e-19, 2.0258847584216418e-19, 2.0171824394771313e-19, 2.0085346846857531e-19,
/* [ 84] */ 1.9999399530912015e-19, 1.9913967503040585e-19, 1.9829036263028144e-19, 1.9744591733545175e-19,
/* [ 88] */ 1.9660620240469857e-19, 1.9577108494251485e-19, 1.9494043572246307e-19, 1.9411412901962161e-19,
/* [ 92] */ 1.9329204245152935e-19, 1.9247405682708168e-19, 1.9166005600287074e-19, 1.9084992674649826e-19,
/* [ 96] */ 1.900435586064234e-19, 1.8924084378793725e-19, 1.8844167703488436e-19, 1.8764595551677749e-19,
/* [100] */ 1.868535787209745e-19, 1.8606444834960934e-19, 1.8527846822098793e-19, 1.8449554417517928e-19,
/* [104] */ 1.8371558398354868e-19, 1.8293849726199566e-19, 1.8216419538767393e-19, 1.8139259141898448e-19,
/* [108] */ 1.8062360001864453e-19, 1.7985713737964743e-19, 1.7909312115393845e-19, 1.78331470383642e-19,
/* [112] */ 1.7757210543468428e-19, 1.7681494793266395e-19, 1.760599207008314e-19, 1.7530694770004409e-19,
/* [116] */ 1.7455595397057217e-19, 1.7380686557563475e-19, 1.7305960954655264e-19, 1.7231411382940904e-19,
/* [120] */ 1.7157030723311378e-19, 1.7082811937877138e-19, 1.7008748065025788e-19, 1.6934832214591352e-19,
/* [124] */ 1.6861057563126349e-19, 1.6787417349268046e-19, 1.6713904869190636e-19, 1.6640513472135291e-19,
/* [128] */ 1.6567236556010242e-19, 1.6494067563053266e-19, 1.6420999975549115e-19, 1.6348027311594532e-19,
/* [132] */ 1.6275143120903661e-19, 1.6202340980646725e-19, 1.6129614491314931e-19, 1.6056957272604589e-19,
/* [136] */ 1.5984362959313479e-19, 1.5911825197242491e-19, 1.5839337639095554e-19, 1.57668939403708e-19,
/* [140] */ 1.5694487755235889e-19, 1.5622112732380261e-19, 1.554976251083707e-19, 1.5477430715767271e-19,
/* [144] */ 1.540511095419833e-19, 1.5332796810709688e-19, 1.5260481843056974e-19, 1.5188159577726683e-19,
/* [148] */ 1.5115823505412761e-19, 1.5043467076406199e-19, 1.4971083695888395e-19, 1.4898666719118714e-19,
/* [152] */ 1.4826209446506113e-19, 1.4753705118554365e-19, 1.468114691066983e-19, 1.4608527927820112e-19,
/* [156] */ 1.4535841199031451e-19, 1.4463079671711862e-19, 1.4390236205786415e-19, 1.4317303567630177e-19,
/* [160] */ 1.4244274423783481e-19, 1.4171141334433217e-19, 1.4097896746642792e-19, 1.4024532987312287e-19,
/* [164] */ 1.3951042255849034e-19, 1.3877416616527576e-19, 1.3803647990516385e-19, 1.3729728147547174e-19,
/* [168] */ 1.3655648697200824e-19, 1.3581401079782068e-19, 1.3506976556752901e-19, 1.3432366200692418e-19,
/* [172] */ 1.3357560884748263e-19, 1.3282551271542047e-19, 1.3207327801488087e-19, 1.3131880680481524e-19,
/* [176] */ 1.3056199866908076e-19, 1.2980275057923788e-19, 1.2904095674948608e-19, 1.2827650848312727e-19,
/* [180] */ 1.2750929400989213e-19, 1.2673919831340482e-19, 1.2596610294799512e-19, 1.2518988584399374e-19,
/* [184] */ 1.2441042110056523e-19, 1.2362757876504165e-19, 1.2284122459762072e-19, 1.2205121982017852e-19,
/* [188] */ 1.2125742084782245e-19, 1.2045967900166973e-19, 1.196578402011802e-19, 1.1885174463419555e-19,
/* [192] */ 1.1804122640264091e-19, 1.1722611314162064e-19, 1.1640622560939109e-19, 1.1558137724540874e-19,
/* [196] */ 1.1475137369333185e-19, 1.1391601228549047e-19, 1.1307508148492592e-19, 1.1222836028063025e-19,
/* [200] */ 1.1137561753107903e-19, 1.1051661125053526e-19, 1.0965108783189755e-19, 1.0877878119905372e-19,
/* [204] */ 1.0789941188076655e-19, 1.070126859970364e-19, 1.0611829414763286e-19, 1.0521591019102928e-19,
/* [208] */ 1.0430518990027552e-19, 1.0338576948035472e-19, 1.0245726392923699e-19, 1.015192652220931e-19,
/* [212] */ 1.0057134029488235e-19, 9.9613028799672809e-20, 9.8643840599459914e-20, 9.7663252964755816e-20,
/* [216] */ 9.6670707427623454e-20, 9.566560624086667e-20, 9.4647308380433213e-20, 9.3615125017323508e-20,
/* [220] */ 9.2568314370887282e-20, 9.1506075837638774e-20, 9.0427543267725716e-20, 8.933177723376368e-20,
/* [224] */ 8.8217756102327883e-20, 8.7084365674892319e-20, 8.5930387109612162e-20, 8.4754482764244349e-20,
/* [228] */ 8.3555179508462343e-20, 8.2330848933585364e-20, 8.1079683729129853e-20, 7.9799669284133864e-20,
/* [232] */ 7.8488549286072745e-20, 7.7143783700934692e-20, 7.5762496979467566e-20, 7.4341413578485329e-20,
/* [236] */ 7.2876776807378431e-20, 7.1364245443525374e-20, 6.9798760240761066e-20, 6.8174368944799054e-20,
/* [240] */ 6.6483992986198539e-20, 6.4719110345162767e-20, 6.2869314813103699e-20, 6.0921687548281263e-20,
/* [244] */ 5.8859873575576818e-20, 5.6662675116090981e-20, 5.4301813630894571e-20, 5.173817174449422e-20,
/* [248] */ 4.8915031722398545e-20, 4.5744741890755301e-20, 4.2078802568583416e-20, 3.7625986722404761e-20,
/* [252] */ 3.1628589805881879e-20, 0,
};
/** The precomputed ziggurat heights, denoted Y_i in the main text. Y_i = f(X_i).
* Values have been scaled by 2^-63. */
protected static final double[] Y = {
/* [ 0] */ 1.4598410796619063e-22, 3.0066613427942797e-22, 4.6129728815103466e-22, 6.2663350049234362e-22,
/* [ 4] */ 7.9594524761881544e-22, 9.6874655021705039e-22, 1.1446877002379439e-21, 1.3235036304379167e-21,
/* [ 8] */ 1.5049857692053131e-21, 1.6889653000719298e-21, 1.8753025382711626e-21, 2.0638798423695191e-21,
/* [ 12] */ 2.2545966913644708e-21, 2.4473661518801799e-21, 2.6421122727763533e-21, 2.8387681187879908e-21,
/* [ 16] */ 3.0372742567457284e-21, 3.2375775699986589e-21, 3.439630315794878e-21, 3.6433893657997798e-21,
/* [ 20] */ 3.8488155868912312e-21, 4.0558733309492775e-21, 4.264530010428359e-21, 4.4747557422305067e-21,
/* [ 24] */ 4.6865230465355582e-21, 4.8998065902775257e-21, 5.1145829672105489e-21, 5.3308305082046173e-21,
/* [ 28] */ 5.5485291167031758e-21, 5.7676601252690476e-21, 5.9882061699178461e-21, 6.2101510795442221e-21,
/* [ 32] */ 6.4334797782257209e-21, 6.6581781985713897e-21, 6.8842332045893181e-21, 7.1116325227957095e-21,
/* [ 36] */ 7.3403646804903092e-21, 7.5704189502886418e-21, 7.8017853001379744e-21, 8.0344543481570017e-21,
/* [ 40] */ 8.2684173217333118e-21, 8.5036660203915022e-21, 8.7401927820109521e-21, 8.9779904520281901e-21,
/* [ 44] */ 9.2170523553061439e-21, 9.457372270392882e-21, 9.698944405926943e-21, 9.9417633789758424e-21,
/* [ 48] */ 1.0185824195119818e-20, 1.043112223011477e-20, 1.0677653212987396e-20, 1.0925413210432004e-20,
/* [ 52] */ 1.1174398612392891e-20, 1.1424606118728715e-20, 1.1676032726866302e-20, 1.1928675720361027e-20,
/* [ 56] */ 1.2182532658289373e-20, 1.2437601365406785e-20, 1.2693879923010674e-20, 1.2951366660454145e-20,
/* [ 60] */ 1.3210060147261461e-20, 1.3469959185800733e-20, 1.3731062804473644e-20, 1.3993370251385596e-20,
/* [ 64] */ 1.4256880988463136e-20, 1.4521594685988369e-20, 1.4787511217522902e-20, 1.505463065519617e-20,
/* [ 68] */ 1.5322953265335218e-20, 1.5592479504415048e-20, 1.5863210015310328e-20, 1.6135145623830982e-20,
/* [ 72] */ 1.6408287335525592e-20, 1.6682636332737932e-20, 1.6958193971903124e-20, 1.7234961781071113e-20,
/* [ 76] */ 1.7512941457646084e-20, 1.7792134866331487e-20, 1.807254403727107e-20, 1.8354171164377277e-20,
/* [ 80] */ 1.8637018603838945e-20, 1.8921088872801004e-20, 1.9206384648209468e-20, 1.9492908765815636e-20,
/* [ 84] */ 1.9780664219333857e-20, 2.0069654159747839e-20, 2.0359881894760859e-20, 2.0651350888385696e-20,
/* [ 88] */ 2.0944064760670539e-20, 2.1238027287557466e-20, 2.1533242400870487e-20, 2.1829714188430474e-20,
/* [ 92] */ 2.2127446894294597e-20, 2.242644491911827e-20, 2.2726712820637798e-20, 2.3028255314272276e-20,
/* [ 96] */ 2.3331077273843558e-20, 2.3635183732413286e-20, 2.3940579883236352e-20, 2.4247271080830277e-20,
/* [100] */ 2.455526284216033e-20, 2.4864560847940368e-20, 2.5175170944049622e-20, 2.5487099143065929e-20,
/* [104] */ 2.5800351625915997e-20, 2.6114934743643687e-20, 2.6430855019297323e-20, 2.6748119149937411e-20,
/* [108] */ 2.7066734008766247e-20, 2.7386706647381193e-20, 2.7708044298153558e-20, 2.8030754376735269e-20,
/* [112] */ 2.8354844484695747e-20, 2.8680322412291631e-20, 2.9007196141372126e-20, 2.9335473848423219e-20,
/* [116] */ 2.9665163907753988e-20, 2.9996274894828624e-20, 3.0328815589748056e-20, 3.0662794980885287e-20,
/* [120] */ 3.099822226867876e-20, 3.1335106869588609e-20, 3.1673458420220558e-20, 3.2013286781622988e-20,
/* [124] */ 3.2354602043762612e-20, 3.2697414530184806e-20, 3.304173480286495e-20, 3.3387573667257349e-20,
/* [128] */ 3.3734942177548938e-20, 3.4083851642125208e-20, 3.4434313629256243e-20, 3.4786339973011376e-20,
/* [132] */ 3.5139942779411164e-20, 3.5495134432826171e-20, 3.585192760263246e-20, 3.6210335250134172e-20,
/* [136] */ 3.6570370635764384e-20, 3.6932047326575882e-20, 3.7295379204034252e-20, 3.7660380472126401e-20,
/* [140] */ 3.8027065665798284e-20, 3.8395449659736649e-20, 3.8765547677510167e-20, 3.9137375301086406e-20,
/* [144] */ 3.9510948480742172e-20, 3.988628354538543e-20, 4.0263397213308566e-20, 4.0642306603393541e-20,
/* [148] */ 4.1023029246790967e-20, 4.1405583099096438e-20, 4.1789986553048817e-20, 4.2176258451776819e-20,
/* [152] */ 4.2564418102621759e-20, 4.2954485291566197e-20, 4.3346480298300118e-20, 4.3740423911958146e-20,
/* [156] */ 4.4136337447563716e-20, 4.4534242763218286e-20, 4.4934162278076256e-20, 4.5336118991149025e-20,
/* [160] */ 4.5740136500984466e-20, 4.6146239026271279e-20, 4.6554451427421133e-20, 4.6964799229185088e-20,
/* [164] */ 4.7377308644364938e-20, 4.7792006598684169e-20, 4.8208920756888113e-20, 4.8628079550147814e-20,
/* [168] */ 4.9049512204847653e-20, 4.9473248772842596e-20, 4.9899320163277674e-20, 5.0327758176068971e-20,
/* [172] */ 5.0758595537153414e-20, 5.1191865935622696e-20, 5.1627604062866059e-20, 5.2065845653856416e-20,
/* [176] */ 5.2506627530725194e-20, 5.2949987648783448e-20, 5.3395965145159426e-20, 5.3844600390237576e-20,
/* [180] */ 5.4295935042099358e-20, 5.4750012104183868e-20, 5.5206875986405073e-20, 5.5666572569983821e-20,
/* [184] */ 5.6129149276275792e-20, 5.6594655139902476e-20, 5.7063140886520563e-20, 5.7534659015596918e-20,
/* [188] */ 5.8009263888591218e-20, 5.8487011822987583e-20, 5.8967961192659803e-20, 5.9452172535103471e-20,
/* [192] */ 5.9939708666122605e-20, 6.0430634802618929e-20, 6.0925018694200531e-20, 6.142293076440286e-20,
/* [196] */ 6.1924444262401531e-20, 6.2429635426193939e-20, 6.2938583658336214e-20, 6.3451371715447563e-20,
/* [200] */ 6.3968085912834963e-20, 6.4488816345752736e-20, 6.5013657128995346e-20, 6.5542706656731714e-20,
/* [204] */ 6.6076067884730717e-20, 6.6613848637404196e-20, 6.715616194241298e-20, 6.770312639595058e-20,
/* [208] */ 6.8254866562246408e-20, 6.8811513411327825e-20, 6.9373204799659681e-20, 6.9940085998959109e-20,
/* [212] */ 7.0512310279279503e-20, 7.1090039553397167e-20, 7.1673445090644796e-20, 7.2262708309655784e-20,
/* [216] */ 7.2858021661057338e-20, 7.34595896130358e-20, 7.4067629754967553e-20, 7.4682374037052817e-20,
/* [220] */ 7.5304070167226666e-20, 7.5932983190698547e-20, 7.6569397282483754e-20, 7.7213617789487678e-20,
/* [224] */ 7.7865973566417016e-20, 7.8526819659456755e-20, 7.919654040385056e-20, 7.9875553017037968e-20,
/* [228] */ 8.056431178890163e-20, 8.1263312996426176e-20, 8.1973100703706304e-20, 8.2694273652634034e-20,
/* [232] */ 8.3427493508836792e-20, 8.4173494807453416e-20, 8.4933097052832066e-20, 8.5707219578230905e-20,
/* [236] */ 8.6496899985930695e-20, 8.7303317295655327e-20, 8.8127821378859504e-20, 8.8971970928196666e-20,
/* [240] */ 8.9837583239314064e-20, 9.0726800697869543e-20, 9.1642181484063544e-20, 9.2586826406702765e-20,
/* [244] */ 9.3564561480278864e-20, 9.4580210012636175e-20, 9.5640015550850358e-20, 9.675233477050313e-20,
/* [248] */ 9.7928851697808831e-20, 9.9186905857531331e-20, 1.0055456271343397e-19, 1.0208407377305566e-19,
/* [252] */ 1.0390360993240711e-19, 1.0842021724855044e-19,
};
/** Underlying source of randomness. */
protected final UniformRandomProvider rng;
/** Exponential sampler used for the long tail. */
protected final ContinuousSampler exponential;
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratNormalizedGaussianSampler(UniformRandomProvider rng) {
this.rng = rng;
exponential = new ModifiedZigguratExponentialSampler(rng);
}
/**
* Provide access to the precomputed ziggurat lengths.
*
* <p>This is package-private to allow usage in the interpolation test.
*
* @return x
*/
static double[] getX() {
return X;
}
/** {@inheritDoc} */
@Override
public double sample() {
final long xx = nextLong();
// Float multiplication squashes these last 8 bits, so they can be used to sample i
final int i = ((int) xx) & 0xff;
if (i < I_MAX) {
// Early exit.
return X[i] * xx;
}
// Recycle bits then advance RNG:
long u1 = xx & MAX_INT64;
// Another squashed, recyclable bit
// double sign_bit = u1 & 0x100 ? 1. : -1.
// Use 2 - 1 or 0 - 1
final double signBit = ((u1 >>> 7) & 0x2) - 1.0;
final int j = selectRegion();
// Four kinds of overhangs:
// j = 0 : Sample from tail
// 0 < j < J_INFLECTION : Overhang is concave; only sample from Lower-Left triangle
// j = J_INFLECTION : Must sample from entire overhang rectangle
// j > J_INFLECTION : Overhangs are convex; implicitly accept point in Lower-Left triangle
//
// Conditional statements are arranged such that the more likely outcomes are first.
double x;
if (j > J_INFLECTION) {
// Convex overhang
for (;;) {
x = sampleX(X, j, u1);
final long uDistance = randomInt63() - u1;
if (uDistance >= 0) {
// Lower-left triangle
break;
}
if (uDistance >= CONVEX_E_MAX &&
// Within maximum distance of f(x) from the triangle hypotenuse.
sampleY(Y, j, u1 + uDistance) < Math.exp(-0.5 * x * x)) {
break;
}
// uDistance < E_MAX (upper-right triangle) or rejected as above the curve
u1 = randomInt63();
}
} else if (j < J_INFLECTION) {
if (j == 0) {
// Tail
// Note: Although less frequent than the next branch, j == 0 is a subset of
// j < J_INFLECTION and must be first.
do {
x = ONE_OVER_X_0 * exponential.sample();
} while (exponential.sample() < 0.5 * x * x);
x += X_0;
} else {
// Concave overhang
for (;;) {
// U_x <- min(U_1, U_2)
// distance <- | U_1 - U_2 |
// U_y <- 1 - (U_x + distance)
long uDistance = randomInt63() - u1;
if (uDistance < 0) {
// Upper-right triangle. Reflect in hypotenuse.
uDistance = -uDistance;
u1 -= uDistance;
}
x = sampleX(X, j, u1);
if (uDistance > CONCAVE_E_MAX ||
sampleY(Y, j, u1 + uDistance) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = randomInt63();
}
}
} else {
// Inflection point
for (;;) {
x = sampleX(X, j, u1);
if (sampleY(Y, j, randomInt63()) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = randomInt63();
}
}
return signBit * x;
}
/**
* Select the overhang region or the tail using alias sampling.
*
* @return the region
*/
protected int selectRegion() {
final long x = nextLong();
// j in [0, 256)
final int j = ((int) x) & 0xff;
// map to j in [0, N] with N the number of layers of the ziggurat
return x >= IPMF[j] ? MAP[j] & 0xff : j;
}
/**
* Generates a {@code long}.
*
* @return the long
*/
protected long nextLong() {
return rng.nextLong();
}
/**
* Return a positive long in {@code [0, 2^63)}.
*
* @return the long
*/
protected long randomInt63() {
return rng.nextLong() & MAX_INT64;
}
}
/**
* Modified Ziggurat method for sampling from a Gaussian distribution with mean 0 and standard deviation 1.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This implementation uses simple overhangs and does not exploit the precomputed
* distances of the concave and convex overhangs. The implementation matches the c-reference
* compiled using -DSIMPLE_OVERHANGS for the non-tail overhangs.
*
* <p>Note: The tail exponential sampler does not use simple overhangs. This facilitates
* performance comparison to the fast overhang method by keeping tail sampling the same.
*/
static class ModifiedZigguratNormalizedGaussianSamplerSimpleOverhangs
extends ModifiedZigguratNormalizedGaussianSampler {
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratNormalizedGaussianSamplerSimpleOverhangs(UniformRandomProvider rng) {
super(rng);
}
/** {@inheritDoc} */
@Override
public double sample() {
final long xx = nextLong();
// Float multiplication squashes these last 8 bits, so they can be used to sample i
final int i = ((int) xx) & 0xff;
if (i < I_MAX) {
// Early exit.
return X[i] * xx;
}
// Another squashed, recyclable bit
// double sign_bit = u1 & 0x100 ? 1. : -1.
// Use 2 - 1 or 0 - 1
final double signBit = ((xx >>> 7) & 0x2) - 1.0;
final int j = selectRegion();
// Simple overhangs
double x;
if (j == 0) {
// Tail
do {
x = ONE_OVER_X_0 * exponential.sample();
} while (exponential.sample() < 0.5 * x * x);
x += X_0;
} else {
// Rejection sampling
// Recycle bits then advance RNG:
long u1 = xx & MAX_INT64;
for (;;) {
x = sampleX(X, j, u1);
if (sampleY(Y, j, randomInt63()) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = randomInt63();
}
}
return signBit * x;
}
}
/**
* Modified Ziggurat method for sampling from a Gaussian distribution with mean 0 and standard deviation 1.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This implementation separates sampling of the main ziggurat and sampling from the edge
* into different methods. This allows inlining of the main sample method.
*/
static class ModifiedZigguratNormalizedGaussianSamplerInlining
extends ModifiedZigguratNormalizedGaussianSampler {
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratNormalizedGaussianSamplerInlining(UniformRandomProvider rng) {
super(rng);
}
/** {@inheritDoc} */
@Override
public double sample() {
// Ideally this method byte code size should be below -XX:MaxInlineSize
// (which defaults to 35 bytes). This compiles to 33 bytes.
final long xx = nextLong();
// Float multiplication squashes these last 8 bits, so they can be used to sample i
final int i = ((int) xx) & 0xff;
if (i < I_MAX) {
// Early exit.
return X[i] * xx;
}
return edgeSample(xx);
}
/**
* Create the sample from the edge of the ziggurat.
*
* <p>This method has been extracted to fit the main sample method within 35 bytes (the
* default size for a JVM to inline a method).
*
* @param xx Initial random deviate
* @return a sample
*/
private double edgeSample(long xx) {
// Recycle bits then advance RNG:
long u1 = xx & MAX_INT64;
// Another squashed, recyclable bit
// double sign_bit = u1 & 0x100 ? 1. : -1.
// Use 2 - 1 or 0 - 1
final double signBit = ((u1 >>> 7) & 0x2) - 1.0;
final int j = selectRegion();
// Four kinds of overhangs:
// j = 0 : Sample from tail
// 0 < j < J_INFLECTION : Overhang is concave; only sample from Lower-Left triangle
// j = J_INFLECTION : Must sample from entire overhang rectangle
// j > J_INFLECTION : Overhangs are convex; implicitly accept point in Lower-Left triangle
//
// Conditional statements are arranged such that the more likely outcomes are first.
double x;
if (j > J_INFLECTION) {
// Convex overhang
for (;;) {
x = sampleX(X, j, u1);
final long uDistance = randomInt63() - u1;
if (uDistance >= 0) {
// Lower-left triangle
break;
}
if (uDistance >= CONVEX_E_MAX &&
// Within maximum distance of f(x) from the triangle hypotenuse.
sampleY(Y, j, u1 + uDistance) < Math.exp(-0.5 * x * x)) {
break;
}
// uDistance < CONVEX_E_MAX (upper-right triangle) or rejected as above the curve
u1 = randomInt63();
}
} else if (j < J_INFLECTION) {
if (j == 0) {
// Tail
// Note: Although less frequent than the next branch, j == 0 is a subset of
// j < J_INFLECTION and must be first.
do {
x = ONE_OVER_X_0 * exponential.sample();
} while (exponential.sample() < 0.5 * x * x);
x += X_0;
} else {
// Concave overhang
for (;;) {
// U_x <- min(U_1, U_2)
// distance <- | U_1 - U_2 |
// U_y <- 1 - (U_x + distance)
long uDistance = randomInt63() - u1;
if (uDistance < 0) {
uDistance = -uDistance;
u1 -= uDistance;
}
x = sampleX(X, j, u1);
if (uDistance > CONCAVE_E_MAX ||
sampleY(Y, j, u1 + uDistance) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = randomInt63();
}
}
} else {
// Inflection point
for (;;) {
x = sampleX(X, j, u1);
if (sampleY(Y, j, randomInt63()) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = randomInt63();
}
}
return signBit * x;
}
}
/**
* Modified Ziggurat method for sampling from a Gaussian distribution with mean 0 and standard deviation 1.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This implementation separates sampling of the main ziggurat and sampling from the edge
* into different methods. This allows inlining of the main sample method.
*
* <p>Positive longs are created using bit shifts (not masking). The y coordinate is
* generated with u2 not (1-u2) which avoids a subtraction.
*/
static class ModifiedZigguratNormalizedGaussianSamplerInliningShift
extends ModifiedZigguratNormalizedGaussianSampler {
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratNormalizedGaussianSamplerInliningShift(UniformRandomProvider rng) {
super(rng);
}
/** {@inheritDoc} */
@Override
public double sample() {
// Ideally this method byte code size should be below -XX:MaxInlineSize
// (which defaults to 35 bytes). This compiles to 33 bytes.
final long xx = nextLong();
// Float multiplication squashes these last 8 bits, so they can be used to sample i
final int i = ((int) xx) & 0xff;
if (i < I_MAX) {
// Early exit.
return X[i] * xx;
}
return edgeSample(xx);
}
/**
* Create the sample from the edge of the ziggurat.
*
* <p>This method has been extracted to fit the main sample method within 35 bytes (the
* default size for a JVM to inline a method).
*
* @param xx Initial random deviate
* @return a sample
*/
private double edgeSample(long xx) {
// Recycle bits.
// Remove sign bit to create u1.
long u1 = (xx << 1) >>> 1;
// Extract the sign bit:
// Use 2 - 1 or 0 - 1
final double signBit = ((xx >>> 62) & 0x2) - 1.0;
final int j = selectRegion();
// Four kinds of overhangs:
// j = 0 : Sample from tail
// 0 < j < J_INFLECTION : Overhang is concave; only sample from Lower-Left triangle
// j = J_INFLECTION : Must sample from entire overhang rectangle
// j > J_INFLECTION : Overhangs are convex; implicitly accept point in Lower-Left triangle
//
// Conditional statements are arranged such that the more likely outcomes are first.
double x;
if (j > J_INFLECTION) {
// Convex overhang
for (;;) {
x = interpolateSample(X, j, u1);
final long uDistance = (nextLong() >>> 1) - u1;
if (uDistance >= 0) {
// Lower-left triangle
break;
}
if (uDistance >= CONVEX_E_MAX &&
// Within maximum distance of f(x) from the triangle hypotenuse.
// u2 = (u1 + uDistance)
interpolateSample(Y, j, u1 + uDistance) < Math.exp(-0.5 * x * x)) {
break;
}
// uDistance < CONVEX_E_MAX (upper-right triangle) or rejected as above the curve
u1 = nextLong() >>> 1;
}
} else if (j < J_INFLECTION) {
if (j == 0) {
// Tail
// Note: Although less frequent than the next branch, j == 0 is a subset of
// j < J_INFLECTION and must be first.
do {
x = ONE_OVER_X_0 * exponential.sample();
} while (exponential.sample() < 0.5 * x * x);
x += X_0;
} else {
// Concave overhang
for (;;) {
// U_x <- min(U_1, U_2)
// distance <- | U_1 - U_2 |
// U_y <- 1 - (U_x + distance)
long uDistance = (nextLong() >>> 1) - u1;
if (uDistance < 0) {
uDistance = -uDistance;
u1 -= uDistance;
}
x = interpolateSample(X, j, u1);
if (uDistance > CONCAVE_E_MAX ||
interpolateSample(Y, j, u1 + uDistance) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = nextLong() >>> 1;
}
}
} else {
// Inflection point
for (;;) {
x = interpolateSample(X, j, u1);
if (interpolateSample(Y, j, nextLong() >>> 1) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = nextLong() >>> 1;
}
}
return signBit * x;
}
/**
* Interpolate x from the uniform deviate.
* <pre>
* value = x[j] + u * (x[j-1] - x[j])
* </pre>
* <p>If x is the precomputed lengths of the ziggurat (X) then x[j-1] is larger and this adds
* a delta to x[j].
* <p>If x is the precomputed pdf for the lengths of the ziggurat (Y) then x[j-1] is smaller
* larger and this subtracts a delta from x[j].
*
* @param x x
* @param j j
* @param u uniform deviate
* @return the sample
*/
private static double interpolateSample(double[] x, int j, long u) {
return x[j] * TWO_POW_63 + (x[j - 1] - x[j]) * u;
}
}
/**
* Modified Ziggurat method for sampling from a Gaussian distribution with mean 0 and standard deviation 1.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This implementation extracts the separates the sample method for the main ziggurat
* from the edge sampling. This allows inlining of the main sample method.
*
* <p>This implementation uses simple overhangs and does not exploit the precomputed
* distances of the concave and convex overhangs. The implementation matches the c-reference
* compiled using -DSIMPLE_OVERHANGS for the non-tail overhangs.
*
* <p>Note: The tail exponential sampler does not use simple overhangs. This facilitates
* performance comparison to the fast overhang method by keeping tail sampling the same.
*/
static class ModifiedZigguratNormalizedGaussianSamplerInliningSimpleOverhangs
extends ModifiedZigguratNormalizedGaussianSampler {
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratNormalizedGaussianSamplerInliningSimpleOverhangs(UniformRandomProvider rng) {
super(rng);
}
/** {@inheritDoc} */
@Override
public double sample() {
// Ideally this method byte code size should be below -XX:MaxInlineSize
// (which defaults to 35 bytes). This compiles to 33 bytes.
final long xx = nextLong();
// Float multiplication squashes these last 8 bits, so they can be used to sample i
final int i = ((int) xx) & 0xff;
if (i < I_MAX) {
// Early exit.
return X[i] * xx;
}
return edgeSample(xx);
}
/**
* Create the sample from the edge of the ziggurat.
*
* <p>This method has been extracted to fit the main sample method within 35 bytes (the
* default size for a JVM to inline a method).
*
* @param xx Initial random deviate
* @return a sample
*/
private double edgeSample(long xx) {
// Another squashed, recyclable bit
// double sign_bit = u1 & 0x100 ? 1. : -1.
// Use 2 - 1 or 0 - 1
final double signBit = ((xx >>> 7) & 0x2) - 1.0;
final int j = selectRegion();
// Simple overhangs
double x;
if (j == 0) {
// Tail
do {
x = ONE_OVER_X_0 * exponential.sample();
} while (exponential.sample() < 0.5 * x * x);
x += X_0;
} else {
// Rejection sampling
// Recycle bits then advance RNG:
long u1 = xx & MAX_INT64;
for (;;) {
x = sampleX(X, j, u1);
if (sampleY(Y, j, randomInt63()) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = randomInt63();
}
}
return signBit * x;
}
}
/**
* Modified Ziggurat method for sampling from a Gaussian distribution with mean 0 and standard deviation 1.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This is a copy of {@link ModifiedZigguratNormalizedGaussianSampler} using
* an integer map in-place of a byte map look-up table. Note the underlying exponential
* sampler does not use an integer map. This sampler is used for the tail with a frequency
* of approximately 0.000276321 and should not impact performance comparisons.
*/
static class ModifiedZigguratNormalizedGaussianSamplerIntMap
extends ModifiedZigguratNormalizedGaussianSampler {
/** The alias map. An integer in [0, 255] stored as a byte to save space. */
private static final int[] INT_MAP = {
/* [ 0] */ 0, 0, 239, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 253,
/* [ 16] */ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
/* [ 32] */ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
/* [ 48] */ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
/* [ 64] */ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
/* [ 80] */ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
/* [ 96] */ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
/* [112] */ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
/* [128] */ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
/* [144] */ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
/* [160] */ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
/* [176] */ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
/* [192] */ 253, 253, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 251, 251, 251, 251,
/* [208] */ 251, 251, 251, 250, 250, 250, 250, 250, 249, 249, 249, 248, 248, 248, 247, 247,
/* [224] */ 247, 246, 246, 245, 244, 244, 243, 242, 240, 2, 2, 3, 3, 0, 0, 240,
/* [240] */ 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 1, 0, 0,
};
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratNormalizedGaussianSamplerIntMap(UniformRandomProvider rng) {
super(rng);
}
/** {@inheritDoc} */
@Override
protected int selectRegion() {
final long x = nextLong();
// j in [0, 256)
final int j = ((int) x) & 0xff;
// map to j in [0, N] with N the number of layers of the ziggurat
return x >= IPMF[j] ? INT_MAP[j] : j;
}
}
/**
* Modified Ziggurat method for sampling from a Gaussian distribution with mean 0 and standard deviation 1.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This is a copy of {@link ModifiedZigguratNormalizedGaussianSampler} using
* a table to store the maximum epsilon value for each overhang.
*/
static class ModifiedZigguratNormalizedGaussianSamplerEMaxTable
extends ModifiedZigguratNormalizedGaussianSampler {
/** The deviation of concave pdf(x) below the hypotenuse value for early exit scaled by 2^63.
* 253 entries with overhang {@code j} corresponding to entry {@code j-1}.
*
* <p>Stored as absolute distances. These are negated for the convex overhangs on initialization. */
private static final long[] E_MAX_TABLE = {
/* [ 0] */ 760463704284035184L, 448775940668074322L, 319432059030582634L, 248136886892509167L,
/* [ 4] */ 202879887821507213L, 171571664564813181L, 148614265661634224L, 131055242060438178L,
/* [ 8] */ 117188580518411866L, 105959220286966343L, 96679401617437000L, 88881528890695590L,
/* [ 12] */ 82236552845322455L, 76506171300171850L, 71513549901780258L, 67124696158442860L,
/* [ 16] */ 63236221616146940L, 59767073533081827L, 56652810532069337L, 53841553364303819L,
/* [ 20] */ 51291065360753073L, 48966611131444450L, 46839361730231995L, 44885190189779505L,
/* [ 24] */ 43083750299904955L, 41417763838249446L, 39872463215195657L, 38435151378929884L,
/* [ 28] */ 37094851170183015L, 35842023608135061L, 34668339797973811L, 33566494917490850L,
/* [ 32] */ 32530055495300595L, 31553333229961898L, 30631280119818406L, 29759400819129686L,
/* [ 36] */ 28933679006953617L, 28150515222628953L, 27406674137103216L, 26699239630262959L,
/* [ 40] */ 26025576358437882L, 25383296743791121L, 24770232513666098L, 24184410074620943L,
/* [ 44] */ 23624029131570806L, 23087444063833159L, 22573147652048958L, 22079756816885946L,
/* [ 48] */ 21606000085203013L, 21150706544370418L, 20712796082591192L, 20291270743857678L,
/* [ 52] */ 19885207051787867L, 19493749177966922L, 19116102848340569L, 18751529896268709L,
/* [ 56] */ 18399343383557859L, 18058903221544231L, 17729612233426885L, 17410912606822884L,
/* [ 60] */ 17102282692149351L, 16803234108116672L, 16513309120493202L, 16232078264496960L,
/* [ 64] */ 15959138184784472L, 15694109670143667L, 15436635862703561L, 15186380623831584L,
/* [ 68] */ 14943027040942155L, 14706276061226881L, 14475845239883253L, 14251467591786361L,
/* [ 72] */ 14032890536754294L, 13819874929609696L, 13612194167177793L, 13409633365176500L,
/* [ 76] */ 13211988598685834L, 13019066200522936L, 12830682112422215L, 12646661284424425L,
/* [ 80] */ 12466837118331739L, 12291050951483677L, 12119151577470956L, 11950994800721809L,
/* [ 84] */ 11786443022181594L, 11625364853565635L, 11467634757892067L, 11313132714210236L,
/* [ 88] */ 11161743904626184L, 11013358421893618L, 10867870995988906L, 10725180738227453L,
/* [ 92] */ 10585190901599062L, 10447808656112693L, 10312944878042918L, 10180513952058881L,
/* [ 96] */ 10050433585302955L, 9922624632558803L, 9797010931719358L, 9673519148825347L,
/* [100] */ 9552078632004422L, 9432621273689757L, 9315081380547200L, 9199395550580725L,
/* [104] */ 9085502556926974L, 8973343237884485L, 8862860392758412L, 8753998683127701L,
/* [108] */ 8646704539174329L, 8540926070735305L, 8436612982764049L, 8333716494908564L,
/* [112] */ 8232189264931586L, 8131985315719003L, 8033059965636513L, 7935369762012110L,
/* [116] */ 7838872417532931L, 7743526749360846L, 7649292620780855L, 7556130885207418L,
/* [120] */ 7464003332385685L, 7372872636629289L, 7282702306949403L, 7193456638934045L,
/* [124] */ 7105100668244386L, 7017600125602463L, 6930921393146734L, 6845031462041107L,
/* [128] */ 6759897891224838L, 6675488767195822L, 6591772664721566L, 6508718608380146L,
/* [132] */ 6426296034828168L, 6344474755702722L, 6263224921061057L, 6182516983265422L,
/* [136] */ 6102321661219813L, 6022609904868391L, 5943352859861905L, 5864521832301635L,
/* [140] */ 5786088253467533L, 5708023644436456L, 5630299580496017L, 5552887655255304L,
/* [144] */ 5475759444352708L, 5398886468659678L, 5322240156870143L, 5245791807368878L,
/* [148] */ 5169512549259789L, 5093373302437038L, 5017344736568650L, 4941397228861186L,
/* [152] */ 4865500820464432L, 4789625171364815L, 4713739513611018L, 4637812602700734L,
/* [156] */ 4561812666947717L, 4485707354637964L, 4409463678763447L, 4333047959114789L,
/* [160] */ 4256425761488008L, 4179561833749943L, 4102420038479365L, 4024963281881178L,
/* [164] */ 3947153438645186L, 3868951272390456L, 3790316351307711L, 3711206958575720L,
/* [168] */ 3631579997089249L, 3551390887994563L, 3470593462479259L, 3389139846213138L,
/* [172] */ 3306980335775941L, 3224063266344542L, 3140334869838942L, 3055739122646026L,
/* [176] */ 2970217581950400L, 2883709209602502L, 2796150182338912L, 2707473687051021L,
/* [180] */ 2617609699653324L, 2526484745953020L, 2434021642745634L, 2340139217177559L,
/* [184] */ 2244752002202266L, 2147769905731505L, 2049097850839701L, 1948635384132493L,
/* [188] */ 1846276249145715L, 1741907921439271L, 1635411101964517L, 1526659165422377L,
/* [192] */ 1415517561001961L, 1301843164664438L, 1185483586365029L, 1066276445521246L,
/* [196] */ 944048652015702L, 818615792062560L, 689781896027189L, 557340453963802L,
/* [200] */ 421079947136144L, 280810745547724L, 136572537955918L, 20305634136204L,
/* [204] */ 169472579551785L, 328795810543866L, 494085614296539L, 665530089254391L,
/* [208] */ 843517138081672L, 1028504363150172L, 1221002487033413L, 1421575123173034L,
/* [212] */ 1630842969010940L, 1849490036801539L, 2078271380701587L, 2318022280314205L,
/* [216] */ 2569669030578262L, 2834241595132002L, 3112888469933608L, 3406894199714926L,
/* [220] */ 3717700104287726L, 4046928914960108L, 4396414204558612L, 4768235732059441L,
/* [224] */ 5164762133803925L, 5588702804307930L, 6043171358058752L, 6531763802579722L,
/* [228] */ 7058655558989014L, 7628722851132691L, 8247695913715760L, 8922354192593482L,
/* [232] */ 9660777606582816L, 10472673600425443L, 11369808078043702L, 12366580875504986L,
/* [236] */ 13480805713009702L, 14734784789701036L, 16156816731707853L, 17783356724741365L,
/* [240] */ 19662183995497761L, 21857171972777613L, 24455696683167282L, 27580563854327149L,
/* [244] */ 31410046818804399L, 36213325371048583L, 42417257237736629L, 50742685211596715L,
/* [248] */ 62513643454971809L, 80469460944360062L, 111428640794724271L, 179355568638601057L,
/* [252] */ 2269182951627976004L,
};
static {
// Negate the E_MAX table for the convex overhangs
for (int j = J_INFLECTION; j < E_MAX_TABLE.length; j++) {
E_MAX_TABLE[j] = -E_MAX_TABLE[j];
}
}
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratNormalizedGaussianSamplerEMaxTable(UniformRandomProvider rng) {
super(rng);
}
/** {@inheritDoc} */
@Override
public double sample() {
final long xx = nextLong();
// Float multiplication squashes these last 8 bits, so they can be used to sample i
final int i = ((int) xx) & 0xff;
if (i < I_MAX) {
// Early exit.
return X[i] * xx;
}
// Recycle bits then advance RNG:
long u1 = xx & MAX_INT64;
// Another squashed, recyclable bit
// double sign_bit = u1 & 0x100 ? 1. : -1.
// Use 2 - 1 or 0 - 1
final double signBit = ((u1 >>> 7) & 0x2) - 1.0;
final int j = selectRegion();
// Four kinds of overhangs:
// j = 0 : Sample from tail
// 0 < j < J_INFLECTION : Overhang is concave; only sample from Lower-Left triangle
// j = J_INFLECTION : Must sample from entire overhang rectangle
// j > J_INFLECTION : Overhangs are convex; implicitly accept point in Lower-Left triangle
//
// Conditional statements are arranged such that the more likely outcomes are first.
double x;
if (j > J_INFLECTION) {
// Convex overhang
final long eMax = E_MAX_TABLE[j - 1];
for (;;) {
x = sampleX(X, j, u1);
final long uDistance = randomInt63() - u1;
if (uDistance >= 0) {
// Lower-left triangle
break;
}
if (uDistance >= eMax &&
// Within maximum distance of f(x) from the triangle hypotenuse.
sampleY(Y, j, u1 + uDistance) < Math.exp(-0.5 * x * x)) {
break;
}
// uDistance < E_MAX (upper-right triangle) or rejected as above the curve
u1 = randomInt63();
}
} else if (j < J_INFLECTION) {
if (j == 0) {
// Tail
// Note: Although less frequent than the next branch, j == 0 is a subset of
// j < J_INFLECTION and must be first.
do {
x = ONE_OVER_X_0 * exponential.sample();
} while (exponential.sample() < 0.5 * x * x);
x += X_0;
} else {
// Concave overhang
final long eMax = E_MAX_TABLE[j - 1];
for (;;) {
// U_x <- min(U_1, U_2)
// distance <- | U_1 - U_2 |
// U_y <- 1 - (U_x + distance)
long uDistance = randomInt63() - u1;
if (uDistance < 0) {
// Upper-right triangle. Reflect in hypotenuse.
uDistance = -uDistance;
u1 -= uDistance;
}
x = sampleX(X, j, u1);
if (uDistance > eMax ||
sampleY(Y, j, u1 + uDistance) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = randomInt63();
}
}
} else {
// Inflection point
for (;;) {
x = sampleX(X, j, u1);
if (sampleY(Y, j, randomInt63()) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = randomInt63();
}
}
return signBit * x;
}
}
/**
* Modified Ziggurat method for sampling from a Gaussian distribution with mean 0 and standard deviation 1.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This is a copy of {@link ModifiedZigguratNormalizedGaussianSampler} using
* two thresholds for the maximum epsilon value for convex and concave overhangs.
*
* <p>Note: The normal curve is very well approximated by the straight line of
* the triangle hypotenuse in the majority of cases. As the convex overhang approaches x=0
* the curve is significantly different. For the concave overhangs the curve is increasingly
* different approaching the tail. This can be exploited using two maximum deviation thresholds.
*/
static class ModifiedZigguratNormalizedGaussianSamplerEMax2
extends ModifiedZigguratNormalizedGaussianSampler {
// Ziggurat volumes:
// Inside the layers = 98.8281% (253/256)
// Fraction outside the layers:
// convex overhangs = 76.1941%
// inflection overhang = 0.1358%
// concave overhangs = 21.3072%
// tail = 2.3629%
// Separation of convex overhangs:
// (Cut made to separate large final overhang with a very different E max.)
// E_MAX
// j = 253 = 72.0882% 0.246
// 204 < j < 253 = 27.9118% 0.0194
// Separation of concave overhangs:
// (Cut made between overhangs requiring above or below 0.02 for E max.
// This choice is somewhat arbitrary. Increasing j will reduce the second E max but makes
// the branch less predictable as the major path is used less.)
// 1 <= j <= 5 = 12.5257% 0.0824
// 5 < j < 204 = 87.4743% 0.0186
/** The convex overhang region j below which the second maximum deviation constant is valid. */
private static final int CONVEX_J2 = 253;
/** The concave overhang region j above which the second maximum deviation constant is valid. */
private static final int CONCAVE_J2 = 5;
/** Maximum epsilon distance of convex pdf(x) above the hypotenuse value for early rejection
* for overhangs {@code 204 < j < 253}.
* Equal to approximately 0.0194 scaled by 2^63. This is negated on purpose.
*
* <p>This threshold increases the area of the early reject triangle by:
* (1-0.0194)^2 / (1-0.246)^2 = 69.1%. */
private static final long CONVEX_E_MAX_2 = -179355568638601057L;
/** Maximum deviation of concave pdf(x) below the hypotenuse value for early exit
* for overhangs {@code 5 < j < 204}.
* Equal to approximately 0.0186 scaled by 2^63.
*
* <p>This threshold increases the area of the early exit triangle by:
* (1-0.0186)^2 / (1-0.0824)^2 = 14.4%. */
private static final long CONCAVE_E_MAX_2 = 171571664564813181L;
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratNormalizedGaussianSamplerEMax2(UniformRandomProvider rng) {
super(rng);
}
/** {@inheritDoc} */
@Override
public double sample() {
final long xx = nextLong();
// Float multiplication squashes these last 8 bits, so they can be used to sample i
final int i = ((int) xx) & 0xff;
if (i < I_MAX) {
// Early exit.
return X[i] * xx;
}
// Recycle bits then advance RNG:
long u1 = xx & MAX_INT64;
// Another squashed, recyclable bit
// double sign_bit = u1 & 0x100 ? 1. : -1.
// Use 2 - 1 or 0 - 1
final double signBit = ((u1 >>> 7) & 0x2) - 1.0;
final int j = selectRegion();
// Four kinds of overhangs:
// j = 0 : Sample from tail
// 0 < j < J_INFLECTION : Overhang is concave; only sample from Lower-Left triangle
// j = J_INFLECTION : Must sample from entire overhang rectangle
// j > J_INFLECTION : Overhangs are convex; implicitly accept point in Lower-Left triangle
//
// Conditional statements are arranged such that the more likely outcomes are first.
double x;
if (j > J_INFLECTION) {
// Convex overhang:
// j < J2 frequency: 0.279118
final long eMax = j < CONVEX_J2 ? CONVEX_E_MAX_2 : CONVEX_E_MAX;
for (;;) {
x = sampleX(X, j, u1);
final long uDistance = randomInt63() - u1;
if (uDistance >= 0) {
// Lower-left triangle
break;
}
if (uDistance >= eMax &&
// Within maximum distance of f(x) from the triangle hypotenuse.
sampleY(Y, j, u1 + uDistance) < Math.exp(-0.5 * x * x)) {
break;
}
// uDistance < E_MAX (upper-right triangle) or rejected as above the curve
u1 = randomInt63();
}
} else if (j < J_INFLECTION) {
if (j == 0) {
// Tail
// Note: Although less frequent than the next branch, j == 0 is a subset of
// j < J_INFLECTION and must be first.
do {
x = ONE_OVER_X_0 * exponential.sample();
} while (exponential.sample() < 0.5 * x * x);
x += X_0;
} else {
// Concave overhang
// j > J2 frequency: 0.874743
final long eMax = j > CONCAVE_J2 ? CONCAVE_E_MAX_2 : CONCAVE_E_MAX;
for (;;) {
// U_x <- min(U_1, U_2)
// distance <- | U_1 - U_2 |
// U_y <- 1 - (U_x + distance)
long uDistance = randomInt63() - u1;
if (uDistance < 0) {
// Upper-right triangle. Reflect in hypotenuse.
uDistance = -uDistance;
u1 -= uDistance;
}
x = sampleX(X, j, u1);
if (uDistance > eMax ||
sampleY(Y, j, u1 + uDistance) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = randomInt63();
}
}
} else {
// Inflection point
for (;;) {
x = sampleX(X, j, u1);
if (sampleY(Y, j, randomInt63()) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = randomInt63();
}
}
return signBit * x;
}
}
/**
* Modified Ziggurat method for sampling from a Gaussian distribution with mean 0 and standard deviation 1.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This is a copy of {@link ModifiedZigguratNormalizedGaussianSampler} using
* a ternary operator to sort the two random long values.
*/
static class ModifiedZigguratNormalizedGaussianSamplerTernary
extends ModifiedZigguratNormalizedGaussianSampler {
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratNormalizedGaussianSamplerTernary(UniformRandomProvider rng) {
super(rng);
}
/** {@inheritDoc} */
@Override
public double sample() {
final long xx = nextLong();
// Float multiplication squashes these last 8 bits, so they can be used to sample i
final int i = ((int) xx) & 0xff;
if (i < I_MAX) {
// Early exit.
return X[i] * xx;
}
// Recycle bits then advance RNG:
long u1 = xx & MAX_INT64;
// Another squashed, recyclable bit
// double sign_bit = u1 & 0x100 ? 1. : -1.
// Use 2 - 1 or 0 - 1
final double signBit = ((u1 >>> 7) & 0x2) - 1.0;
final int j = selectRegion();
// Four kinds of overhangs:
// j = 0 : Sample from tail
// 0 < j < J_INFLECTION : Overhang is concave; only sample from Lower-Left triangle
// j = J_INFLECTION : Must sample from entire overhang rectangle
// j > J_INFLECTION : Overhangs are convex; implicitly accept point in Lower-Left triangle
//
// Conditional statements are arranged such that the more likely outcomes are first.
double x;
if (j > J_INFLECTION) {
// Convex overhang
for (;;) {
x = sampleX(X, j, u1);
final long uDistance = randomInt63() - u1;
if (uDistance >= 0) {
// Lower-left triangle
break;
}
if (uDistance >= CONVEX_E_MAX &&
// Within maximum distance of f(x) from the triangle hypotenuse.
sampleY(Y, j, u1 + uDistance) < Math.exp(-0.5 * x * x)) {
break;
}
// uDistance < E_MAX (upper-right triangle) or rejected as above the curve
u1 = randomInt63();
}
} else if (j < J_INFLECTION) {
if (j == 0) {
// Tail
// Note: Although less frequent than the next branch, j == 0 is a subset of
// j < J_INFLECTION and must be first.
do {
x = ONE_OVER_X_0 * exponential.sample();
} while (exponential.sample() < 0.5 * x * x);
x += X_0;
} else {
// Concave overhang
for (;;) {
// If u2 < u1 then reflect in the hypotenuse by swapping u1 and u2.
// Create a second uniform deviate (as u1 is recycled).
final long ua = u1;
final long ub = randomInt63();
// Sort u1 < u2 to sample the lower-left triangle.
// Use conditional ternary to avoid a 50/50 branch statement to swap the pair.
u1 = ua < ub ? ua : ub;
final long u2 = ua < ub ? ub : ua;
x = sampleX(X, j, u1);
if (u2 - u1 > CONCAVE_E_MAX ||
sampleY(Y, j, u2) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = randomInt63();
}
}
} else {
// Inflection point
for (;;) {
x = sampleX(X, j, u1);
if (sampleY(Y, j, randomInt63()) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = randomInt63();
}
}
return signBit * x;
}
}
/**
* Modified Ziggurat method for sampling from a Gaussian distribution with mean 0 and standard deviation 1.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This is a copy of {@link ModifiedZigguratNormalizedGaussianSampler} using
* a table size of 512.
*/
static class ModifiedZigguratNormalizedGaussianSampler512 implements ContinuousSampler {
// Ziggurat volumes:
// Inside the layers = 99.4141% (509/512)
// Fraction outside the layers:
// convex overhangs = 75.5775%
// inflection overhang = 0.0675%
// concave overhangs = 22.2196%
// tail = 2.1354%
/** The number of layers in the ziggurat. Maximum i value for early exit. */
protected static final int I_MAX = 509;
/** The point where the Gaussian switches from convex to concave.
* This is the largest value of X[j] below 1. */
protected static final int J_INFLECTION = 409;
/** Maximum epsilon distance of convex pdf(x) above the hypotenuse value for early rejection.
* Equal to approximately 0.2477 scaled by 2^63. This is negated on purpose as the
* distance for a point (x,y) above the hypotenuse is negative:
* {@code (|d| < max) == (d >= -max)}. */
protected static final long CONVEX_E_MAX = -2284356979160975476L;
/** Maximum distance of concave pdf(x) below the hypotenuse value for early exit.
* Equal to approximately 0.08284 scaled by 2^63. */
protected static final long CONCAVE_E_MAX = 764138791244619676L;
/** Beginning of tail. Equal to X[0] * 2^63. */
protected static final double X_0 = 3.8358644648571882;
/** 1/X_0. Used for tail sampling. */
protected static final double ONE_OVER_X_0 = 1.0 / X_0;
/** The alias map. */
private static final int[] MAP = {
/* [ 0] */ 0, 0, 480, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0,
/* [ 16] */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
/* [ 32] */ 1, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [ 48] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [ 64] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [ 80] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [ 96] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [112] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [128] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [144] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [160] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [176] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [192] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [208] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [224] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [240] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [256] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [272] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [288] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [304] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [320] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [336] */ 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509,
/* [352] */ 509, 509, 509, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [368] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 507, 507, 507, 507, 507, 507,
/* [384] */ 507, 507, 507, 507, 507, 507, 507, 507, 506, 506, 506, 506, 506, 506, 506, 506,
/* [400] */ 506, 506, 505, 505, 505, 505, 505, 505, 505, 505, 504, 504, 504, 504, 504, 504,
/* [416] */ 503, 503, 503, 503, 503, 502, 502, 502, 502, 501, 501, 501, 501, 500, 500, 500,
/* [432] */ 500, 499, 499, 499, 498, 498, 498, 497, 497, 496, 496, 495, 495, 494, 494, 493,
/* [448] */ 493, 492, 491, 490, 489, 488, 487, 486, 484, 2, 2, 2, 2, 2, 3, 3,
/* [464] */ 3, 4, 4, 4, 5, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0,
/* [480] */ 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496,
/* [496] */ 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 1, 0, 0,
};
/** The alias inverse PMF. */
private static final long[] IPMF = {
/* [ 0] */ 9223372036854775296L, 3232176979959565312L, 2248424156373566976L, 5572490326155894272L,
/* [ 4] */ 3878549168685540352L, 6596558088755235840L, 7126388452799016960L, 5909258326277172224L,
/* [ 8] */ 6789036995587703808L, 8550801776550481920L, 7272880214327450112L, 6197723851568405504L,
/* [ 12] */ 5279475843641833984L, 4485290838628302848L, 3790998004182467072L, 3178396845257682944L,
/* [ 16] */ 2633509168847815680L, 2145413694861947904L, 1705448049989382144L, 1306649397437548544L,
/* [ 20] */ 943354160611131392L, 610906287013685760L, 305441095029422592L, 23722736478678016L,
/* [ 24] */ -236979677660888064L, -478987634076675072L, -704287768537463808L, -914590611781799424L,
/* [ 28] */ -1111377331889550848L, -1295937239757415424L, -1469398133880157184L, -1632751030331424768L,
/* [ 32] */ -1786870462753421312L, -1932531249141885952L, -2070422432472262144L, -2201158928905888256L,
/* [ 36] */ -2325291321647773696L, -2443314131355272192L, -2555672836734271488L, -2662769858897092096L,
/* [ 40] */ -2764969686945558528L, -2862603283332330496L, -2955971885350600192L, -3045350299719277056L,
/* [ 44] */ -3130989762881722368L, -3213120439420999168L, -3291953604062304256L, -3367683558060156416L,
/* [ 48] */ -3440489316130714624L, -3510536092827323904L, -3577976620246562816L, -3642952314681374720L,
/* [ 52] */ -3705594315191049216L, -3766024408614111744L, -3824355856527138304L, -3880694134271785472L,
/* [ 56] */ -3935137594960746496L, -3987778065544580608L, -4038701385199136256L, -4087987887601244160L,
/* [ 60] */ -4135712841168144384L, -4181946844655158784L, -4226756186527602176L, -4270203172038951424L,
/* [ 64] */ -4312346420932761088L, -4353241136943226880L, -4392939356053354496L, -4431490172784719360L,
/* [ 68] */ -4468939945001798656L, -4505332485123679232L, -4540709232733563392L, -4575109415088551424L,
/* [ 72] */ -4608570193416988672L, -4641126797904314880L, -4672812652574308352L, -4703659490673809920L,
/* [ 76] */ -4733697460624237568L, -4762955224068688384L, -4791460047779233792L, -4819237887169053184L,
/* [ 80] */ -4846313464821579264L, -4872710343112062464L, -4898450992673160192L, -4923556853979476992L,
/* [ 84] */ -4948048396148470272L, -4971945172796024320L, -4995265870892981248L, -5018028360085760000L,
/* [ 88] */ -5040249735872740864L, -5061946361747427840L, -5083133907806415360L, -5103827387715595776L,
/* [ 92] */ -5124041191022579712L, -5143789117574014464L, -5163084406061926400L, -5181939762086439936L,
/* [ 96] */ -5200367384806330368L, -5218378992989818368L, -5235985846759801344L, -5253198770233210880L,
/* [100] */ -5270028172706144256L, -5286484068673344512L, -5302576093914087424L, -5318313526819882496L,
/* [104] */ -5333705300501412864L, -5348760022140801536L, -5363485985612222976L, -5377891185738658816L,
/* [108] */ -5391983331261941760L, -5405769858949649408L, -5419257942659722240L, -5432454506730834944L,
/* [112] */ -5445366236058309120L, -5457999585571643392L, -5470360790218524160L, -5482455874386169344L,
/* [116] */ -5494290660050575872L, -5505870774716076032L, -5517201660378635264L, -5528288579187974144L,
/* [120] */ -5539136622578390528L, -5549750716118886400L, -5560135626660535808L, -5570295969034180608L,
/* [124] */ -5580236210799400960L, -5589960678379259904L, -5599473562706778112L, -5608778923054202880L,
/* [128] */ -5617880692891545088L, -5626782684460370944L, -5635488592684399104L, -5644001999389030912L,
/* [132] */ -5652326378260390400L, -5660465096501542912L, -5668421421481986048L, -5676198522069054464L,
/* [136] */ -5683799472034193408L, -5691227254524439552L, -5698484764964738048L, -5705574811911234048L,
/* [140] */ -5712500123062644224L, -5719263345561367040L, -5725867049400364032L, -5732313730758826496L,
/* [144] */ -5738605812086640640L, -5744745647569117184L, -5750735522378352640L, -5756577656307920896L,
/* [148] */ -5762274206097785856L, -5767827266307192832L, -5773238871631092224L, -5778510999439789056L,
/* [152] */ -5783645569528274432L, -5788644448981466624L, -5793509449834629120L, -5798242334409694208L,
/* [156] */ -5802844813858308096L, -5807318551213207040L, -5811665162349513216L, -5815886217028536832L,
/* [160] */ -5819983240762728448L, -5823957715198579712L, -5827811080259974144L, -5831544734136989696L,
/* [164] */ -5835160035614893056L, -5838658304467378688L, -5842040821904171520L, -5845308832880873984L,
/* [168] */ -5848463546172629504L, -5851506134738812416L, -5854437738541255168L, -5857259462674584064L,
/* [172] */ -5859972381032173568L, -5862577534420617216L, -5865075933349880320L, -5867468558168720896L,
/* [176] */ -5869756358001916928L, -5871940255655389696L, -5874021142765756416L, -5875999885243720704L,
/* [180] */ -5877877321138562048L, -5879654262030006784L, -5881331493491406336L, -5882909775710032384L,
/* [184] */ -5884389844282934784L, -5885772409590032896L, -5887058159412298240L, -5888247756760180736L,
/* [188] */ -5889341841868359680L, -5890341033726286848L, -5891245927036046336L, -5892057096967517184L,
/* [192] */ -5892775095254208000L, -5893400454293159424L, -5893933684945675776L, -5894375277894875136L,
/* [196] */ -5894725704281316864L, -5894985415097101824L, -5895154842211865088L, -5895234398367037440L,
/* [200] */ -5895224478119281152L, -5895125456527683584L, -5894937691150572032L, -5894661521100592128L,
/* [204] */ -5894297268546692608L, -5893845237129657344L, -5893305713928932352L, -5892678968199164928L,
/* [208] */ -5891965253512273920L, -5891164805272775680L, -5890277843462263808L, -5889304570970719232L,
/* [212] */ -5888245175227536896L, -5887099827242714112L, -5885868681480997376L, -5884551878016265728L,
/* [216] */ -5883149540187518976L, -5881661776186659840L, -5880088679051159040L, -5878430325617481216L,
/* [220] */ -5876686779113256448L, -5874858086097725440L, -5872944278695313920L, -5870945374625903616L,
/* [224] */ -5868861375946597376L, -5866692270114584576L, -5864438029808936448L, -5862098613329829376L,
/* [228] */ -5859673963988850688L, -5857164010304659456L, -5854568667030923264L, -5851887832571710976L,
/* [232] */ -5849121393007995904L, -5846269217914838016L, -5843331163565322752L, -5840307071023708160L,
/* [236] */ -5837196767034538496L, -5834000063619345920L, -5830716757850101760L, -5827346633080182272L,
/* [240] */ -5823889457015247872L, -5820344982925702656L, -5816712949734398464L, -5812993080309509120L,
/* [244] */ -5809185084612210688L, -5805288655397134848L, -5801303472071718912L, -5797229197542626816L,
/* [248] */ -5793065480979245568L, -5788811954902762496L, -5784468237204753408L, -5780033929729368064L,
/* [252] */ -5775508619016246784L, -5770891876025206272L, -5766183254901072896L, -5761382294937170432L,
/* [256] */ -5756488518102026240L, -5751501431126126080L, -5746420523619011584L, -5741245267817476608L,
/* [260] */ -5735975121281433088L, -5730609522034737152L, -5725147892326605312L, -5719589637112302080L,
/* [264] */ -5713934142693986816L, -5708180778990178816L, -5702328896016054784L, -5696377827537145856L,
/* [268] */ -5690326887295941632L, -5684175370772383744L, -5677922555045085184L, -5671567696296352256L,
/* [272] */ -5665110033102450176L, -5658548782530205696L, -5651883142913629696L, -5645112290875286016L,
/* [276] */ -5638235383069228544L, -5631251554336663040L, -5624159919711433728L, -5616959570005672448L,
/* [280] */ -5609649575759112704L, -5602228984633701376L, -5594696820961281536L, -5587052085776743936L,
/* [284] */ -5579293757104064512L, -5571420787942931456L, -5563432107812764160L, -5555326619765914112L,
/* [288] */ -5547103202855799296L, -5538760709287606272L, -5530297965182673920L, -5521713769559916032L,
/* [292] */ -5513006894391551488L, -5504176082674265088L, -5495220049712259584L, -5486137481881783808L,
/* [296] */ -5476927034862822400L, -5467587334392330752L, -5458116976167262720L, -5448514522422561280L,
/* [300] */ -5438778504885873664L, -5428907421454137344L, -5418899736307948032L, -5408753879414383104L,
/* [304] */ -5398468245670757888L, -5388041193950201856L, -5377471046142717440L, -5366756087011503104L,
/* [308] */ -5355894562291467776L, -5344884679094671360L, -5333724604104164352L, -5322412462390110720L,
/* [312] */ -5310946337190221824L, -5299324269391752192L, -5287544254227943936L, -5275604243076108288L,
/* [316] */ -5263502140384954880L, -5251235803114780672L, -5238803040260463616L, -5226201609860500992L,
/* [320] */ -5213429220396639232L, -5200483526689941504L, -5187362130814278656L, -5174062579249043456L,
/* [324] */ -5160582362536272384L, -5146918913003260928L, -5133069603645442048L, -5119031746455840768L,
/* [328] */ -5104802590846193664L, -5090379322288435200L, -5075759059905230848L, -5060938855168388608L,
/* [332] */ -5045915690136155648L, -5030686475123909120L, -5015248047351192576L, -4999597168201581568L,
/* [336] */ -4983730521429875200L, -4967644711103290880L, -4951336259902648320L, -4934801604331100672L,
/* [340] */ -4918037096313518080L, -4901038996556133376L, -4883803475152384512L, -4866326606521733120L,
/* [344] */ -4848604368549652480L, -4830632638500906496L, -4812407189788950016L, -4793923690356844544L,
/* [348] */ -4775177697581510656L, -4756164656502554112L, -4736879895545858048L, -4717318622225770496L,
/* [352] */ -4697475921931613696L, -4677346750468523008L, -4656925933129603072L, -4636208158837948416L,
/* [356] */ -4615187976257695744L, -4593859789223797248L, -4572217851458716672L, -4550256263721420288L,
/* [360] */ -4527968965738787328L, -4505349732602470400L, -4482392170596992000L, -4459089707595035648L,
/* [364] */ -4435435591206243840L, -4411422880135513088L, -4387044438367173632L, -4362292928394443264L,
/* [368] */ -4337160804216032256L, -4311640303794398208L, -4285723442340192768L, -4259402002490114048L,
/* [372] */ -4232667527557880832L, -4205511312870738944L, -4177924395156510720L, -4149897544928282624L,
/* [376] */ -4121421255517056000L, -4092485732978126848L, -4063080884857030656L, -4033196309983527424L,
/* [380] */ -4002821285452889600L, -3971944754955299840L, -3940555315053852672L, -3908641203541062144L,
/* [384] */ -3876190282046383616L, -3843190024121122816L, -3809627498134461952L, -3775489350771450880L,
/* [388] */ -3740761791237469184L, -3705430570995169280L, -3669480966726291456L, -3632897760460073472L,
/* [392] */ -3595665216111472128L, -3557767061510936064L, -3519186461826909184L, -3479905997291117056L,
/* [396] */ -3439907636209809920L, -3399172709277578752L, -3357681881315035136L, -3315415118925273600L,
/* [400] */ -3272351662607639040L, -3228469989824430592L, -3183747783206633472L, -3138161891189001728L,
/* [404] */ -3091688288710896128L, -3044302038074020352L, -2995977242912180224L, -2946687001898157056L,
/* [408] */ -2896403361643595776L, -2845097261899269632L, -2792738483041489920L, -2739295585832944128L,
/* [412] */ -2684735849802800128L, -2629025208318833152L, -2572128177407577088L, -2514007780971290112L,
/* [416] */ -2454625474210264064L, -2393941056301004288L, -2331912582463081472L, -2268496267820575232L,
/* [420] */ -2203646385063500288L, -2137315156805725696L, -2069452637212809728L, -2000006589650226176L,
/* [424] */ -1928922352643083264L, -1856142697389204480L, -1781607676495585792L, -1705254458055283200L,
/* [428] */ -1627017152968592896L, -1546826624346926592L, -1464610284716681216L, -1380291880647352832L,
/* [432] */ -1293791253775522304L, -1205024091744495104L, -1113901652592291328L, -1020330470192921600L,
/* [436] */ -924212036524504576L, -825442455107712512L, -723912067910252544L, -619505050467681792L,
/* [440] */ -512098970851033088L, -401564310549775872L, -287763946399309312L, -170552579279989760L,
/* [444] */ -49776119384483328L, 74728993660240384L, 203136528144344576L, 335631271254235136L,
/* [448] */ 472409917558910464L, 613682045009508352L, 759671188745830912L, 910616024566752768L,
/* [452] */ 1066771674457471488L, 1228411150191648768L, 1395826950915523584L, 1569332837797146112L,
/* [456] */ 1749265802232386560L, 1935988261896280064L, 2129890506883624960L, 2331393435927328256L,
/* [460] */ 2540951622664266752L, 2759056758111070720L, 2986241520688130560L, 3223083948864353280L,
/* [464] */ 3470212380253329408L, 3728311054271952896L, 3998126479196178432L, 4280474694750398976L,
/* [468] */ 4576249573583467520L, 4886432342140325376L, 5212102538692988928L, 5554450665570580992L,
/* [472] */ 5914792845058133504L, 6294587870200374272L, 6695457110790894080L, 7119207852916254720L,
/* [476] */ 7567860785399318528L, 8043682516018548736L, 8549224231795344384L, 9087367898325182976L,
/* [480] */ 2686433895585048064L, 3738049383351049728L, 5447119168340997632L, 7862383433967084544L,
/* [484] */ 3564125970404768256L, 7561510489765503488L, 4795007330430237184L, 2822776087249664512L,
/* [488] */ 1739199416312530432L, 1651067950292976640L, 2680178586723521024L, 4966620264299254784L,
/* [492] */ 8672981687287425024L, 5102073364374541824L, 2973953244697943040L, 2586847729538911744L,
/* [496] */ 4294392489026305536L, 8524338069805147648L, 5657549542711693824L, 6039225349920109568L,
/* [500] */ -188437589949716992L, -1600155058499635712L, 3512467924097231872L, 5888549710424099840L,
/* [504] */ 8328892371572499456L, 3607211374099356160L, 952847323024169472L, -3124063727137777664L,
/* [508] */ -844200026382571008L, 1173948101715934208L, -9223372036854775808L, -9223372036854775808L,
};
/**
* The precomputed ziggurat lengths, denoted X_i in the main text. X_i = length of
* ziggurat layer i. Values have been scaled by 2^-63.
*/
private static final double[] X = {
/* [ 0] */ 4.1588525861581104e-19, 3.9503459916661627e-19, 3.821680975424891e-19, 3.7270045721185492e-19,
/* [ 4] */ 3.6514605982514084e-19, 3.5882746800626676e-19, 3.533765597048754e-19, 3.4857018027109719e-19,
/* [ 8] */ 3.4426246437790343e-19, 3.4035264389553312e-19, 3.3676808841410688e-19, 3.3345465900442888e-19,
/* [ 12] */ 3.3037088331351658e-19, 3.2748426481115448e-19, 3.2476884984205335e-19, 3.2220356973333147e-19,
/* [ 16] */ 3.1977107871867837e-19, 3.1745691935586742e-19, 3.1524891032273018e-19, 3.1313668890638164e-19,
/* [ 20] */ 3.1111136341647712e-19, 3.0916524520018658e-19, 3.0729163928347323e-19, 3.0548467885197293e-19,
/* [ 24] */ 3.0373919296832198e-19, 3.0205059980435001e-19, 3.0041481968537306e-19, 2.9882820368030914e-19,
/* [ 28] */ 2.9728747450808126e-19, 2.9578967728884489e-19, 2.9433213822959269e-19, 2.9291242975352861e-19,
/* [ 32] */ 2.9152834090005319e-19, 2.9017785206455541e-19, 2.8885911333390034e-19, 2.8757042581852451e-19,
/* [ 36] */ 2.8631022549560207e-19, 2.8507706916730813e-19, 2.8386962220934334e-19, 2.8268664784176013e-19,
/* [ 40] */ 2.815269976998848e-19, 2.8038960352015381e-19, 2.7927346978580998e-19, 2.7817766720204774e-19,
/* [ 44] */ 2.7710132689045585e-19, 2.7604363520934134e-19, 2.7500382912040458e-19, 2.739811920338075e-19,
/* [ 48] */ 2.7297505007336127e-19, 2.7198476871169526e-19, 2.710097497321303e-19, 2.7004942847978509e-19,
/* [ 52] */ 2.6910327136937779e-19, 2.6817077362138452e-19, 2.6725145720181144e-19, 2.6634486894391515e-19,
/* [ 56] */ 2.6545057883285584e-19, 2.6456817843655206e-19, 2.636972794679811e-19, 2.6283751246588273e-19,
/* [ 60] */ 2.6198852558231173e-19, 2.6114998346678357e-19, 2.6032156623788965e-19, 2.5950296853425164e-19,
/* [ 64] */ 2.5869389863755409e-19, 2.5789407766116098e-19, 2.5710323879849453e-19, 2.5632112662595285e-19,
/* [ 68] */ 2.555474964556656e-19, 2.5478211373385828e-19, 2.5402475348100586e-19, 2.532751997703282e-19,
/* [ 72] */ 2.5253324524150594e-19, 2.5179869064679051e-19, 2.5107134442694197e-19, 2.503510223146645e-19,
/* [ 76] */ 2.4963754696341833e-19, 2.4893074759967754e-19, 2.4823045969687053e-19, 2.4753652466939529e-19,
/* [ 80] */ 2.4684878958523816e-19, 2.4616710689584975e-19, 2.4549133418204393e-19, 2.4482133391478862e-19,
/* [ 84] */ 2.4415697322984843e-19, 2.4349812371532436e-19, 2.4284466121121044e-19, 2.42196465620158e-19,
/* [ 88] */ 2.4155342072870043e-19, 2.4091541403824951e-19, 2.402823366052261e-19, 2.3965408288973736e-19,
/* [ 92] */ 2.3903055061225481e-19, 2.3841164061778912e-19, 2.3779725674709409e-19, 2.3718730571446517e-19,
/* [ 96] */ 2.3658169699173055e-19, 2.3598034269805933e-19, 2.3538315749523948e-19, 2.3479005848810095e-19,
/* [100] */ 2.3420096512978219e-19, 2.3361579913155922e-19, 2.3303448437697401e-19, 2.3245694684001817e-19,
/* [104] */ 2.3188311450714236e-19, 2.3131291730287861e-19, 2.3074628701887441e-19, 2.3018315724615257e-19,
/* [108] */ 2.2962346331042115e-19, 2.290671422102686e-19, 2.285141325580919e-19, 2.2796437452361119e-19,
/* [112] */ 2.2741780977983687e-19, 2.2687438145136136e-19, 2.2633403406485519e-19, 2.2579671350165625e-19,
/* [116] */ 2.2526236695234495e-19, 2.2473094287320652e-19, 2.2420239094448635e-19, 2.2367666203034958e-19,
/* [120] */ 2.231537081404625e-19, 2.2263348239311565e-19, 2.2211593897981584e-19, 2.2160103313127622e-19,
/* [124] */ 2.2108872108473813e-19, 2.2057896005256279e-19, 2.2007170819203281e-19, 2.1956692457630854e-19,
/* [128] */ 2.1906456916648504e-19, 2.1856460278470111e-19, 2.1806698708825153e-19, 2.1757168454465786e-19,
/* [132] */ 2.1707865840765572e-19, 2.1658787269405759e-19, 2.1609929216145222e-19, 2.1561288228670561e-19,
/* [136] */ 2.1512860924522763e-19, 2.1464643989097195e-19, 2.1416634173713822e-19, 2.1368828293754638e-19,
/* [140] */ 2.1321223226865536e-19, 2.1273815911219872e-19, 2.122660334384123e-19, 2.1179582578982903e-19,
/* [144] */ 2.1132750726561794e-19, 2.1086104950644545e-19, 2.103964246798376e-19, 2.0993360546602319e-19,
/* [148] */ 2.09472565044239e-19, 2.0901327707947851e-19, 2.0855571570966692e-19, 2.0809985553324565e-19,
/* [152] */ 2.0764567159715066e-19, 2.0719313938516928e-19, 2.0674223480666103e-19, 2.0629293418562883e-19,
/* [156] */ 2.0584521425012706e-19, 2.05399052121994e-19, 2.0495442530689639e-19, 2.0451131168467476e-19,
/* [160] */ 2.0406968949997815e-19, 2.0362953735317784e-19, 2.0319083419154967e-19, 2.027535593007156e-19,
/* [164] */ 2.0231769229633464e-19, 2.0188321311603464e-19, 2.0145010201157619e-19, 2.0101833954124038e-19,
/* [168] */ 2.0058790656243254e-19, 2.0015878422449446e-19, 1.9973095396171768e-19, 1.9930439748655098e-19,
/* [172] */ 1.9887909678299541e-19, 1.984550341001801e-19, 1.9803219194611336e-19, 1.9761055308160207e-19,
/* [176] */ 1.9719010051433485e-19, 1.967708174931225e-19, 1.9635268750229097e-19, 1.9593569425622174e-19,
/* [180] */ 1.955198216940345e-19, 1.9510505397440756e-19, 1.9469137547053159e-19, 1.9427877076519196e-19,
/* [184] */ 1.9386722464597592e-19, 1.9345672210060023e-19, 1.9304724831235547e-19, 1.9263878865566334e-19,
/* [188] */ 1.9223132869174325e-19, 1.9182485416438451e-19, 1.9141935099582133e-19, 1.9101480528270662e-19,
/* [192] */ 1.9061120329218205e-19, 1.9020853145804105e-19, 1.8980677637698202e-19, 1.8940592480494855e-19,
/* [196] */ 1.8900596365355448e-19, 1.8860687998659074e-19, 1.8820866101661152e-19, 1.8781129410159744e-19,
/* [200] */ 1.8741476674169321e-19, 1.8701906657601756e-19, 1.8662418137954315e-19, 1.8623009906004439e-19,
/* [204] */ 1.85836807655111e-19, 1.8544429532922543e-19, 1.8505255037090195e-19, 1.8466156118988594e-19,
/* [208] */ 1.8427131631441095e-19, 1.8388180438851245e-19, 1.8349301416939593e-19, 1.8310493452485817e-19,
/* [212] */ 1.8271755443075968e-19, 1.823308629685471e-19, 1.8194484932282376e-19, 1.8155950277896707e-19,
/* [216] */ 1.8117481272079125e-19, 1.8079076862825417e-19, 1.804073600752067e-19, 1.8002457672718337e-19,
/* [220] */ 1.7964240833923322e-19, 1.7926084475378945e-19, 1.7887987589857656e-19, 1.7849949178455405e-19,
/* [224] */ 1.7811968250389552e-19, 1.7774043822800183e-19, 1.773617492055474e-19, 1.7698360576055882e-19,
/* [228] */ 1.7660599829052424e-19, 1.7622891726453298e-19, 1.7585235322144435e-19, 1.754762967680843e-19,
/* [232] */ 1.751007385774697e-19, 1.7472566938705867e-19, 1.743510799970264e-19, 1.7397696126856576e-19,
/* [236] */ 1.7360330412221144e-19, 1.7323009953618705e-19, 1.7285733854477456e-19, 1.7248501223670475e-19,
/* [240] */ 1.7211311175356858e-19, 1.7174162828824813e-19, 1.7137055308336676e-19, 1.7099987742975751e-19,
/* [244] */ 1.7062959266494937e-19, 1.7025969017167022e-19, 1.6989016137636627e-19, 1.6952099774773704e-19,
/* [248] */ 1.6915219079528517e-19, 1.6878373206788065e-19, 1.6841561315233867e-19, 1.6804782567201046e-19,
/* [252] */ 1.6768036128538652e-19, 1.6731321168471171e-19, 1.6694636859461146e-19, 1.6657982377072854e-19,
/* [256] */ 1.6621356899836991e-19, 1.6584759609116298e-19, 1.6548189688972057e-19, 1.6511646326031438e-19,
/* [260] */ 1.6475128709355596e-19, 1.6438636030308492e-19, 1.6402167482426369e-19, 1.6365722261287829e-19,
/* [264] */ 1.632929956438448e-19, 1.6292898590992037e-19, 1.625651854204191e-19, 1.6220158619993133e-19,
/* [268] */ 1.618381802870466e-19, 1.6147495973307924e-19, 1.6111191660079618e-19, 1.6074904296314645e-19,
/* [272] */ 1.6038633090199211e-19, 1.600237725068394e-19, 1.5966135987357025e-19, 1.5929908510317342e-19,
/* [276] */ 1.5893694030047434e-19, 1.5857491757286376e-19, 1.5821300902902412e-19, 1.5785120677765333e-19,
/* [280] */ 1.5748950292618545e-19, 1.5712788957950753e-19, 1.5676635883867226e-19, 1.5640490279960565e-19,
/* [284] */ 1.560435135518094e-19, 1.5568218317705714e-19, 1.5532090374808409e-19, 1.5495966732726971e-19,
/* [288] */ 1.545984659653122e-19, 1.5423729169989499e-19, 1.5387613655434405e-19, 1.5351499253627542e-19,
/* [292] */ 1.531538516362328e-19, 1.5279270582631381e-19, 1.5243154705878517e-19, 1.5207036726468514e-19,
/* [296] */ 1.5170915835241339e-19, 1.5134791220630703e-19, 1.5098662068520251e-19, 1.5062527562098241e-19,
/* [300] */ 1.5026386881710618e-19, 1.499023920471249e-19, 1.4954083705317816e-19, 1.4917919554447328e-19,
/* [304] */ 1.4881745919574531e-19, 1.4845561964569755e-19, 1.4809366849542141e-19, 1.4773159730679478e-19,
/* [308] */ 1.4736939760085815e-19, 1.470070608561676e-19, 1.4664457850712328e-19, 1.4628194194227331e-19,
/* [312] */ 1.4591914250259098e-19, 1.4555617147972526e-19, 1.4519302011422298e-19, 1.4482967959372176e-19,
/* [316] */ 1.4446614105111258e-19, 1.4410239556267103e-19, 1.4373843414615571e-19, 1.4337424775887289e-19,
/* [320] */ 1.4300982729570602e-19, 1.4264516358710902e-19, 1.4228024739706157e-19, 1.4191506942098562e-19,
/* [324] */ 1.4154962028362133e-19, 1.4118389053686103e-19, 1.4081787065753974e-19, 1.4045155104518092e-19,
/* [328] */ 1.4008492201969533e-19, 1.3971797381903188e-19, 1.3935069659677833e-19, 1.3898308041971047e-19,
/* [332] */ 1.3861511526528749e-19, 1.3824679101909196e-19, 1.3787809747221246e-19, 1.3750902431856644e-19,
/* [336] */ 1.3713956115216185e-19, 1.3676969746429448e-19, 1.3639942264067964e-19, 1.3602872595851507e-19,
/* [340] */ 1.3565759658347313e-19, 1.3528602356661948e-19, 1.3491399584125558e-19, 1.3454150221968241e-19,
/* [344] */ 1.3416853138988266e-19, 1.3379507191211783e-19, 1.3342111221543818e-19, 1.3304664059410112e-19,
/* [348] */ 1.3267164520389587e-19, 1.3229611405836999e-19, 1.3192003502495473e-19, 1.3154339582098531e-19,
/* [352] */ 1.3116618400961209e-19, 1.3078838699559864e-19, 1.3040999202100255e-19, 1.3003098616073445e-19,
/* [356] */ 1.2965135631799062e-19, 1.2927108921955436e-19, 1.2889017141096131e-19, 1.2850858925152309e-19,
/* [360] */ 1.2812632890920429e-19, 1.2774337635534646e-19, 1.2735971735923388e-19, 1.2697533748249419e-19,
/* [364] */ 1.2659022207332785e-19, 1.262043562605593e-19, 1.2581772494750294e-19, 1.2543031280563616e-19,
/* [368] */ 1.250421042680721e-19, 1.2465308352282341e-19, 1.2426323450584884e-19, 1.238725408938736e-19,
/* [372] */ 1.2348098609697396e-19, 1.2308855325091651e-19, 1.2269522520924136e-19, 1.22300984535079e-19,
/* [376] */ 1.2190581349268875e-19, 1.2150969403870742e-19, 1.2111260781309555e-19, 1.2071453612976755e-19,
/* [380] */ 1.2031545996689279e-19, 1.1991535995685211e-19, 1.1951421637583513e-19, 1.191120091330619e-19,
/* [384] */ 1.1870871775961209e-19, 1.1830432139684355e-19, 1.1789879878438187e-19, 1.1749212824766058e-19,
/* [388] */ 1.1708428768499157e-19, 1.1667525455414306e-19, 1.1626500585840243e-19, 1.1585351813209874e-19,
/* [392] */ 1.1544076742555945e-19, 1.150267292894733e-19, 1.1461137875863088e-19, 1.1419469033501178e-19,
/* [396] */ 1.1377663797018575e-19, 1.1335719504699387e-19, 1.1293633436047259e-19, 1.1251402809798253e-19,
/* [400] */ 1.1209024781850075e-19, 1.1166496443103302e-19, 1.1123814817209981e-19, 1.1080976858224708e-19,
/* [404] */ 1.1037979448152952e-19, 1.0994819394391104e-19, 1.0951493427052315e-19, 1.0907998196171864e-19,
/* [408] */ 1.0864330268785362e-19, 1.0820486125872634e-19, 1.0776462159159718e-19, 1.0732254667770796e-19,
/* [412] */ 1.0687859854721439e-19, 1.0643273823243869e-19, 1.059849257293434e-19, 1.0553511995712021e-19,
/* [416] */ 1.0508327871578037e-19, 1.0462935864162494e-19, 1.0417331516046436e-19, 1.0371510243844727e-19,
/* [420] */ 1.0325467333034829e-19, 1.0279197932515293e-19, 1.0232697048876598e-19, 1.0185959540365581e-19,
/* [424] */ 1.013898011052333e-19, 1.009175330147477e-19, 1.0044273486846454e-19, 9.9965348642872442e-20,
/* [428] */ 9.9485314475644288e-20, 9.900257058205621e-20, 9.8517053166543133e-20, 9.8028696329042194e-20,
/* [432] */ 9.7537431965745965e-20, 9.7043189663854526e-20, 9.654589658987947e-20, 9.6045477371013195e-20,
/* [436] */ 9.5541853969033159e-20, 9.5034945546162292e-20, 9.4524668322253246e-20, 9.4010935422604966e-20,
/* [440] */ 9.3493656715654088e-20, 9.2972738639710746e-20, 9.2448084017826916e-20, 9.1919591859794958e-20,
/* [444] */ 9.1387157150172602e-20, 9.0850670621117885e-20, 9.0310018508690594e-20, 8.9765082291135159e-20,
/* [448] */ 8.9215738407499983e-20, 8.8661857954768974e-20, 8.8103306361478308e-20, 8.7539943035562694e-20,
/* [452] */ 8.6971620983916387e-20, 8.6398186400860379e-20, 8.5819478222373023e-20, 8.5235327642560774e-20,
/* [456] */ 8.4645557588411128e-20, 8.4049982148372247e-20, 8.3448405949733243e-20, 8.2840623479121996e-20,
/* [460] */ 8.2226418339680758e-20, 8.1605562437603462e-20, 8.0977815089703785e-20, 8.0342922042501121e-20,
/* [464] */ 7.9700614391933997e-20, 7.9050607391197453e-20, 7.8392599132306843e-20, 7.772626908475868e-20,
/* [468] */ 7.7051276472020123e-20, 7.6367258463445082e-20, 7.5673828155481347e-20, 7.497057231156425e-20,
/* [472] */ 7.4257048824721583e-20, 7.353278386042921e-20, 7.2797268629389381e-20, 7.2049955730309961e-20,
/* [476] */ 7.1290254991002794e-20, 7.0517528721622442e-20, 6.9731086275889195e-20, 6.8930177793707327e-20,
/* [480] */ 6.8113986970409562e-20, 6.7281622662207744e-20, 6.6432109091987626e-20, 6.5564374361194866e-20,
/* [484] */ 6.4677236897885373e-20, 6.3769389372032666e-20, 6.2839379478434802e-20, 6.1885586812998988e-20,
/* [488] */ 6.0906194832423162e-20, 5.9899156564895461e-20, 5.8862152292532516e-20, 5.7792536797552712e-20,
/* [492] */ 5.6687272865166578e-20, 5.5542846427447531e-20, 5.4355156789160883e-20, 5.3119372426547794e-20,
/* [496] */ 5.1829738259578428e-20, 5.047931295220812e-20, 4.9059602658819333e-20, 4.7560036835100967e-20,
/* [500] */ 4.5967194527575314e-20, 4.4263619567465964e-20, 4.2425923207137379e-20, 4.0421571557166738e-20,
/* [504] */ 3.820304293025196e-20, 3.5696135223547374e-20, 3.2773159946159168e-20, 2.9176892376585344e-20,
/* [508] */ 2.4195231151204545e-20, 0,
};
/** The precomputed ziggurat heights, denoted Y_i in the main text. Y_i = f(X_i).
* Values have been scaled by 2^-63. */
private static final double[] Y = {
/* [ 0] */ 6.9188990988329477e-23, 1.4202990535697683e-22, 2.1732316399259404e-22, 2.9452908326033447e-22,
/* [ 4] */ 3.7333229265092159e-22, 4.5352314752172509e-22, 5.3495096331850513e-22, 6.175015744699501e-22,
/* [ 8] */ 7.0108513174955496e-22, 7.8562885992867391e-22, 8.7107247053338667e-22, 9.5736510622922269e-22,
/* [ 12] */ 1.0444632219043918e-21, 1.1323290661676009e-21, 1.2209295628733119e-21, 1.3102354679393653e-21,
/* [ 16] */ 1.4002207209079843e-21, 1.4908619375774252e-21, 1.5821380069573031e-21, 1.6740297667860313e-21,
/* [ 20] */ 1.7665197391694204e-21, 1.8595919128929468e-21, 1.9532315624377367e-21, 2.0474250961975478e-21,
/* [ 24] */ 2.1421599281741028e-21, 2.2374243687320324e-21, 2.3332075309631245e-21, 2.4294992499379909e-21,
/* [ 28] */ 2.5262900126775297e-21, 2.6235708971028823e-21, 2.7213335185536967e-21, 2.8195699827241005e-21,
/* [ 32] */ 2.9182728440709958e-21, 3.0174350689128386e-21, 3.1170500025683573e-21, 3.2171113399908191e-21,
/* [ 36] */ 3.3176130994398206e-21, 3.4185495988032995e-21, 3.5199154342406966e-21, 3.6217054608664173e-21,
/* [ 40] */ 3.7239147752328608e-21, 3.8265386994058555e-21, 3.9295727664535323e-21, 4.0330127071934498e-21,
/* [ 44] */ 4.1368544380629805e-21, 4.2410940499950823e-21, 4.345727798196275e-21, 4.4507520927361638e-21,
/* [ 48] */ 4.5561634898686684e-21, 4.6619586840144468e-21, 4.7681345003420505e-21, 4.8746878878923688e-21,
/* [ 52] */ 4.9816159131970167e-21, 5.0889157543466486e-21, 5.1965846954698379e-21, 5.3046201215872733e-21,
/* [ 56] */ 5.413019513809608e-21, 5.5217804448504855e-21, 5.6309005748290817e-21, 5.7403776473389792e-21,
/* [ 60] */ 5.8502094857624066e-21, 5.9603939898108565e-21, 6.0709291322748242e-21, 6.1818129559670009e-21,
/* [ 64] */ 6.2930435708446384e-21, 6.4046191512980779e-21, 6.5165379335935457e-21, 6.6287982134593532e-21,
/* [ 68] */ 6.7413983438055354e-21, 6.8543367325678093e-21, 6.9676118406674612e-21, 7.0812221800794591e-21,
/* [ 72] */ 7.1951663120016937e-21, 7.3094428451188258e-21, 7.4240504339546813e-21, 7.5389877773076551e-21,
/* [ 76] */ 7.6542536167639494e-21, 7.7698467352838953e-21, 7.8857659558569342e-21, 8.0020101402211584e-21,
/* [ 80] */ 8.1185781876436157e-21, 8.235469033757848e-21, 8.3526816494553559e-21, 8.4702150398279595e-21,
/* [ 84] */ 8.5880682431581806e-21, 8.706240329954993e-21, 8.8247304020324768e-21, 8.9435375916290263e-21,
/* [ 88] */ 9.0626610605649797e-21, 9.1820999994366113e-21, 9.3018536268446223e-21, 9.4219211886553146e-21,
/* [ 92] */ 9.5423019572928162e-21, 9.6629952310607645e-21, 9.7840003334919972e-21, 9.905316612724868e-21,
/* [ 96] */ 1.0026943440904879e-20, 1.0148880213610417e-20, 1.0271126349301457e-20, 1.0393681288790118e-20,
/* [100] */ 1.0516544494732088e-20, 1.0639715451137926e-20, 1.076319366290336e-20, 1.088697865535769e-20,
/* [104] */ 1.1011069973829531e-20, 1.1135467183229089e-20, 1.1260169867646259e-20, 1.1385177629963887e-20,
/* [108] */ 1.1510490091485507e-20, 1.1636106891576963e-20, 1.176202768732133e-20, 1.1888252153186578e-20,
/* [112] */ 1.2014779980705474e-20, 1.2141610878167194e-20, 1.2268744570320195e-20, 1.2396180798085917e-20,
/* [116] */ 1.2523919318282839e-20, 1.2651959903360538e-20, 1.2780302341143342e-20, 1.2908946434583201e-20,
/* [120] */ 1.3037892001521468e-20, 1.3167138874459203e-20, 1.3296686900335739e-20, 1.342653594031518e-20,
/* [124] */ 1.3556685869580544e-20, 1.3687136577135297e-20, 1.3817887965612001e-20, 1.3948939951087837e-20,
/* [128] */ 1.4080292462906762e-20, 1.421194544350808e-20, 1.4343898848261192e-20, 1.447615264530638e-20,
/* [132] */ 1.4608706815401313e-20, 1.4741561351773229e-20, 1.4874716259976492e-20, 1.5008171557755435e-20,
/* [136] */ 1.5141927274912272e-20, 1.527598345317996e-20, 1.5410340146099826e-20, 1.5544997418903869e-20,
/* [140] */ 1.5679955348401513e-20, 1.5815214022870783e-20, 1.5950773541953694e-20, 1.6086634016555787e-20,
/* [144] */ 1.6222795568749659e-20, 1.6359258331682407e-20, 1.6496022449486859e-20, 1.6633088077196497e-20,
/* [148] */ 1.6770455380664001e-20, 1.690812453648326e-20, 1.7046095731914825e-20, 1.7184369164814694e-20,
/* [152] */ 1.7322945043566328e-20, 1.7461823587015858e-20, 1.7601005024410389e-20, 1.7740489595339301e-20,
/* [156] */ 1.7880277549678543e-20, 1.8020369147537807e-20, 1.8160764659210518e-20, 1.8301464365126615e-20,
/* [160] */ 1.8442468555808009e-20, 1.8583777531826755e-20, 1.8725391603765759e-20, 1.8867311092182093e-20,
/* [164] */ 1.9009536327572789e-20, 1.9152067650343099e-20, 1.9294905410777168e-20, 1.9438049969011095e-20,
/* [168] */ 1.9581501695008306e-20, 1.9725260968537243e-20, 1.9869328179151295e-20, 2.0013703726170975e-20,
/* [172] */ 2.0158388018668269e-20, 2.030338147545316e-20, 2.0448684525062275e-20, 2.0594297605749654e-20,
/* [176] */ 2.0740221165479551e-20, 2.0886455661921353e-20, 2.1033001562446463e-20, 2.1179859344127223e-20,
/* [180] */ 2.132702949373782e-20, 2.1474512507757144e-20, 2.1622308892373594e-20, 2.177041916349182e-20,
/* [184] */ 2.1918843846741371e-20, 2.2067583477487234e-20, 2.221663860084227e-20, 2.2366009771681506e-20,
/* [188] */ 2.2515697554658291e-20, 2.2665702524222297e-20, 2.2816025264639365e-20, 2.2966666370013165e-20,
/* [192] */ 2.3117626444308697e-20, 2.3268906101377579e-20, 2.3420505964985179e-20, 2.3572426668839511e-20,
/* [196] */ 2.3724668856621966e-20, 2.3877233182019821e-20, 2.4030120308760546e-20, 2.4183330910647897e-20,
/* [200] */ 2.4336865671599831e-20, 2.4490725285688176e-20, 2.4644910457180119e-20, 2.4799421900581494e-20,
/* [204] */ 2.4954260340681856e-20, 2.5109426512601375e-20, 2.5264921161839525e-20, 2.5420745044325602e-20,
/* [208] */ 2.5576898926471056e-20, 2.5733383585223655e-20, 2.5890199808123478e-20, 2.6047348393360769e-20,
/* [212] */ 2.620483014983564e-20, 2.6362645897219624e-20, 2.6520796466019148e-20, 2.6679282697640851e-20,
/* [216] */ 2.6838105444458826e-20, 2.6997265569883789e-20, 2.7156763948434162e-20, 2.7316601465809108e-20,
/* [220] */ 2.7476779018963542e-20, 2.7637297516185117e-20, 2.7798157877173203e-20, 2.7959361033119882e-20,
/* [224] */ 2.8120907926793008e-20, 2.8282799512621313e-20, 2.8445036756781554e-20, 2.8607620637287851e-20,
/* [228] */ 2.8770552144083069e-20, 2.8933832279132388e-20, 2.909746205651907e-20, 2.9261442502542373e-20,
/* [232] */ 2.9425774655817774e-20, 2.9590459567379366e-20, 2.975549830078463e-20, 2.9920891932221431e-20,
/* [236] */ 3.0086641550617475e-20, 3.0252748257752036e-20, 3.0419213168370193e-20, 3.0586037410299459e-20,
/* [240] */ 3.0753222124568922e-20, 3.0920768465530904e-20, 3.1088677600985173e-20, 3.1256950712305787e-20,
/* [244] */ 3.1425588994570519e-20, 3.1594593656693039e-20, 3.1763965921557762e-20, 3.1933707026157491e-20,
/* [248] */ 3.210381822173386e-20, 3.2274300773920679e-20, 3.2445155962890127e-20, 3.261638508350196e-20,
/* [252] */ 3.2787989445455682e-20, 3.2959970373445826e-20, 3.3132329207320317e-20, 3.3305067302242021e-20,
/* [256] */ 3.3478186028853508e-20, 3.3651686773445136e-20, 3.3825570938126452e-20, 3.3999839941001009e-20,
/* [260] */ 3.4174495216344673e-20, 3.434953821478746e-20, 3.4524970403498974e-20, 3.4700793266377521e-20,
/* [264] */ 3.4877008304243007e-20, 3.5053617035033593e-20, 3.5230620994006313e-20, 3.5408021733941619e-20,
/* [268] */ 3.5585820825352012e-20, 3.5764019856694792e-20, 3.5942620434589016e-20, 3.6121624184036813e-20,
/* [272] */ 3.6301032748649041e-20, 3.6480847790875463e-20, 3.6661070992239485e-20, 3.6841704053577609e-20,
/* [276] */ 3.7022748695283621e-20, 3.7204206657557678e-20, 3.7386079700660407e-20, 3.7568369605172066e-20,
/* [280] */ 3.7751078172256915e-20, 3.7934207223932926e-20, 3.8117758603346923e-20, 3.8301734175055289e-20,
/* [284] */ 3.8486135825310328e-20, 3.8670965462352503e-20, 3.8856225016708545e-20, 3.9041916441495727e-20,
/* [288] */ 3.9228041712732281e-20, 3.9414602829654225e-20, 3.9601601815038723e-20, 3.9789040715534053e-20,
/* [292] */ 3.9976921601996467e-20, 4.0165246569833989e-20, 4.0354017739357392e-20, 4.0543237256138495e-20,
/* [296] */ 4.0732907291375956e-20, 4.092303004226878e-20, 4.1113607732397641e-20, 4.1304642612114334e-20,
/* [300] */ 4.1496136958939466e-20, 4.1688093077968586e-20, 4.1880513302287083e-20, 4.2073399993393892e-20,
/* [304] */ 4.226675554163437e-20, 4.2460582366642555e-20, 4.2654882917792981e-20, 4.2849659674662346e-20,
/* [308] */ 4.3044915147501306e-20, 4.3240651877716606e-20, 4.3436872438363862e-20, 4.3633579434651235e-20,
/* [312] */ 4.3830775504454331e-20, 4.402846331884258e-20, 4.4226645582617465e-20, 4.44253250348628e-20,
/* [316] */ 4.4624504449507564e-20, 4.4824186635901433e-20, 4.502437443940352e-20, 4.5225070741984591e-20,
/* [320] */ 4.5426278462843173e-20, 4.5628000559035919e-20, 4.5830240026122638e-20, 4.6032999898826428e-20,
/* [324] */ 4.6236283251709275e-20, 4.6440093199863635e-20, 4.66444328996204e-20, 4.6849305549273747e-20,
/* [328] */ 4.7054714389823359e-20, 4.7260662705734508e-20, 4.7467153825716568e-20, 4.7674191123520394e-20,
/* [332] */ 4.7881778018755285e-20, 4.8089917977726014e-20, 4.8298614514290481e-20, 4.8507871190738755e-20,
/* [336] */ 4.8717691618694051e-20, 4.8928079460036324e-20, 4.9139038427849191e-20, 4.9350572287390917e-20,
/* [340] */ 4.9562684857090195e-20, 4.9775380009567483e-20, 4.9988661672682747e-20, 5.0202533830610375e-20,
/* [344] */ 5.0417000524942233e-20, 5.0632065855819656e-20, 5.0847733983095388e-20, 5.1064009127526389e-20,
/* [348] */ 5.1280895571998574e-20, 5.1498397662784496e-20, 5.1716519810835054e-20, 5.1935266493106415e-20,
/* [352] */ 5.2154642253923237e-20, 5.2374651706379573e-20, 5.2595299533778521e-20, 5.281659049111218e-20,
/* [356] */ 5.3038529406583093e-20, 5.3261121183168789e-20, 5.3484370800230758e-20, 5.3708283315169579e-20,
/* [360] */ 5.3932863865127733e-20, 5.4158117668741825e-20, 5.4384050027946003e-20, 5.4610666329828364e-20,
/* [364] */ 5.4837972048542409e-20, 5.5065972747275354e-20, 5.529467408027557e-20, 5.5524081794941295e-20,
/* [368] */ 5.5754201733972871e-20, 5.5985039837590894e-20, 5.6216602145822901e-20, 5.6448894800860957e-20,
/* [372] */ 5.6681924049493214e-20, 5.6915696245611979e-20, 5.7150217852801476e-20, 5.7385495447008377e-20,
/* [376] */ 5.7621535719298375e-20, 5.7858345478702286e-20, 5.8095931655155148e-20, 5.8334301302532288e-20,
/* [380] */ 5.8573461601786159e-20, 5.8813419864188086e-20, 5.9054183534679474e-20, 5.9295760195336789e-20,
/* [384] */ 5.9538157568955278e-20, 5.9781383522756458e-20, 6.00254460722246e-20, 6.0270353385077896e-20,
/* [388] */ 6.0516113785379988e-20, 6.0762735757798273e-20, 6.1010227952015272e-20, 6.1258599187299976e-20,
/* [392] */ 6.1507858457246388e-20, 6.1758014934686814e-20, 6.2009077976787964e-20, 6.2261057130338207e-20,
/* [396] */ 6.2513962137235034e-20, 6.2767802940182038e-20, 6.3022589688605306e-20, 6.3278332744799953e-20,
/* [400] */ 6.3535042690317614e-20, 6.3792730332606894e-20, 6.4051406711919054e-20, 6.4311083108492257e-20,
/* [404] */ 6.4571771050028178e-20, 6.4833482319475923e-20, 6.5096228963138882e-20, 6.5360023299121136e-20,
/* [408] */ 6.562487792613134e-20, 6.5890805732662563e-20, 6.6157819906568342e-20, 6.6425933945056075e-20,
/* [412] */ 6.669516166512051e-20, 6.6965517214441315e-20, 6.7237015082770543e-20, 6.7509670113837357e-20,
/* [416] */ 6.778349751779927e-20, 6.8058512884271187e-20, 6.8334732195965602e-20, 6.861217184297964e-20,
/* [420] */ 6.8890848637767307e-20, 6.9170779830837617e-20, 6.9451983127222779e-20, 6.973447670376329e-20,
/* [424] */ 7.0018279227260534e-20, 7.0303409873551134e-20, 7.0589888347561524e-20, 7.0877734904405408e-20,
/* [428] */ 7.1166970371591799e-20, 7.1457616172416729e-20, 7.1749694350617054e-20, 7.2043227596371579e-20,
/* [432] */ 7.2338239273741285e-20, 7.2634753449648124e-20, 7.2932794924500039e-20, 7.323238926457911e-20,
/* [436] */ 7.3533562836319459e-20, 7.3836342842612738e-20, 7.4140757361291078e-20, 7.4446835385950638e-20,
/* [440] */ 7.4754606869293753e-20, 7.5064102769183896e-20, 7.5375355097625875e-20, 7.5688396972903551e-20,
/* [444] */ 7.6003262675129782e-20, 7.6319987705488118e-20, 7.663860884947315e-20, 7.6959164244467646e-20,
/* [448] */ 7.7281693452028738e-20, 7.7606237535294258e-20, 7.7932839141963691e-20, 7.8261542593356837e-20,
/* [452] */ 7.8592393980108262e-20, 7.8925441265117724e-20, 7.9260734394446575e-20, 7.9598325416929843e-20,
/* [456] */ 7.9938268613363919e-20, 8.0280620636232317e-20, 8.0625440661049589e-20, 8.0972790550537079e-20,
/* [460] */ 8.132273503299865e-20, 8.1675341896440717e-20, 8.20306822001853e-20, 8.2388830505960473e-20,
/* [464] */ 8.2749865130725681e-20, 8.3113868423807933e-20, 8.3480927071295611e-20, 8.3851132431071348e-20,
/* [468] */ 8.4224580902376006e-20, 8.4601374334397956e-20, 8.498162047909447e-20, 8.5365433494299503e-20,
/* [472] */ 8.5752934504183006e-20, 8.6144252225339393e-20, 8.6539523668242568e-20, 8.6938894925572055e-20,
/* [476] */ 8.7342522061064557e-20, 8.7750572115174375e-20, 8.816322424706147e-20, 8.8580671036429462e-20,
/* [480] */ 8.9003119973724073e-20, 8.943079517345898e-20, 8.9863939353342e-20, 9.030281613194174e-20,
/* [484] */ 9.0747712710563048e-20, 9.1198943021750057e-20, 9.1656851448748822e-20, 9.2121817249226692e-20,
/* [488] */ 9.2594259855265681e-20, 9.3074645274038203e-20, 9.3563493885409803e-20, 9.4061390032646715e-20,
/* [492] */ 9.4568993943651402e-20, 9.5087056723313496e-20, 9.56164394555198e-20, 9.6158137899911961e-20,
/* [496] */ 9.6713314954182168e-20, 9.7283344135003048e-20, 9.7869869093443078e-20, 9.8474887157460046e-20,
/* [500] */ 9.9100870137415168e-20, 9.9750945338940223e-20, 1.004291788159128e-19, 1.0114104330564085e-19,
/* [504] */ 1.0189424721829993e-19, 1.0270034796927329e-19, 1.0357834330014222e-19, 1.0456455804293095e-19,
/* [508] */ 1.0575382882239675e-19, 1.0842021724855044e-19,
};
/** Underlying source of randomness. */
protected final UniformRandomProvider rng;
/** Exponential sampler used for the long tail. */
protected final ContinuousSampler exponential;
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratNormalizedGaussianSampler512(UniformRandomProvider rng) {
this.rng = rng;
exponential = new ModifiedZigguratExponentialSampler512(rng);
}
/** {@inheritDoc} */
@Override
public double sample() {
final long xx = nextLong();
// Float multiplication squashes these last 9 bits, so they can be used to sample i
final int i = ((int) xx) & 0x1ff;
if (i < I_MAX) {
// Early exit.
return X[i] * xx;
}
// Recycle bits then advance RNG:
long u1 = xx & MAX_INT64;
// Another squashed, recyclable bit
// Use 2 - 1 or 0 - 1
final double signBit = ((u1 >>> 8) & 0x2) - 1.0;
final int j = selectRegion();
// Four kinds of overhangs:
// j = 0 : Sample from tail
// 0 < j < J_INFLECTION : Overhang is concave; only sample from Lower-Left triangle
// j = J_INFLECTION : Must sample from entire overhang rectangle
// j > J_INFLECTION : Overhangs are convex; implicitly accept point in Lower-Left triangle
//
// Conditional statements are arranged such that the more likely outcomes are first.
double x;
if (j > J_INFLECTION) {
// Convex overhang
for (;;) {
x = sampleX(X, j, u1);
final long uDistance = randomInt63() - u1;
if (uDistance >= 0) {
// Lower-left triangle
break;
}
if (uDistance >= CONVEX_E_MAX &&
// Within maximum distance of f(x) from the triangle hypotenuse.
sampleY(Y, j, u1 + uDistance) < Math.exp(-0.5 * x * x)) {
break;
}
// uDistance < E_MAX (upper-right triangle) or rejected as above the curve
u1 = randomInt63();
}
} else if (j < J_INFLECTION) {
if (j == 0) {
// Tail
// Note: Although less frequent than the next branch, j == 0 is a subset of
// j < J_INFLECTION and must be first.
do {
x = ONE_OVER_X_0 * exponential.sample();
} while (exponential.sample() < 0.5 * x * x);
x += X_0;
} else {
// Concave overhang
for (;;) {
// U_x <- min(U_1, U_2)
// distance <- | U_1 - U_2 |
// U_y <- 1 - (U_x + distance)
long uDistance = randomInt63() - u1;
if (uDistance < 0) {
uDistance = -uDistance;
u1 -= uDistance;
}
x = sampleX(X, j, u1);
if (uDistance > CONCAVE_E_MAX ||
sampleY(Y, j, u1 + uDistance) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = randomInt63();
}
}
} else {
// Inflection point
for (;;) {
x = sampleX(X, j, u1);
if (sampleY(Y, j, randomInt63()) < Math.exp(-0.5 * x * x)) {
break;
}
u1 = randomInt63();
}
}
return signBit * x;
}
/**
* Select the overhang region or the tail using alias sampling.
*
* @return the region
*/
protected int selectRegion() {
final long x = nextLong();
// j in [0, 512)
final int j = ((int) x) & 0x1ff;
// map to j in [0, N] with N the number of layers of the ziggurat
return x >= IPMF[j] ? MAP[j] : j;
}
/**
* Generates a {@code long}.
*
* @return the long
*/
protected long nextLong() {
return rng.nextLong();
}
/**
* Return a positive long in {@code [0, 2^63)}.
*
* @return the long
*/
protected long randomInt63() {
return rng.nextLong() & MAX_INT64;
}
}
/**
* Modified Ziggurat method for sampling from an exponential distribution.
*
* <p>Uses the algorithm from:
*
* <blockquote>
* McFarland, C.D. (2016)<br>
* "A modified ziggurat algorithm for generating exponentially and normally distributed pseudorandom numbers".<br>
* <i>Journal of Statistical Computation and Simulation</i> <b>86</b>, 1281-1294.
* </blockquote>
*
* <p>This class uses the same tables as the production version
* {@link org.apache.commons.rng.sampling.distribution.ZigguratSampler.Exponential}
* with the overhang sampling matching the reference c implementation. Methods and members
* are protected to allow the implementation to be modified in sub-classes.
*
* @see <a href="https://www.tandfonline.com/doi/abs/10.1080/00949655.2015.1060234">
* McFarland (2016) JSCS 86, 1281-1294</a>
*/
static class ModifiedZigguratExponentialSampler implements ContinuousSampler {
// Ziggurat volumes:
// Inside the layers = 98.4375% (252/256)
// Fraction outside the layers:
// concave overhangs = 96.6972%
// tail = 3.3028%
/** The number of layers in the ziggurat. Maximum i value for early exit. */
protected static final int I_MAX = 252;
/** Maximum deviation of concave pdf(x) below the hypotenuse value for early exit.
* Equal to approximately 0.0926 scaled by 2^63. */
protected static final long E_MAX = 853965788476313646L;
/** Beginning of tail. Equal to X[0] * 2^63. */
protected static final double X_0 = 7.569274694148063;
/** The alias map. An integer in [0, 255] stored as a byte to save space. */
protected static final byte[] MAP = {
/* [ 0] */ (byte) 0, (byte) 0, (byte) 1, (byte) 235, (byte) 3, (byte) 4, (byte) 5, (byte) 0,
/* [ 8] */ (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
/* [ 16] */ (byte) 0, (byte) 0, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 2, (byte) 2,
/* [ 24] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [ 32] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [ 40] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [ 48] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [ 56] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [ 64] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [ 72] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [ 80] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [ 88] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [ 96] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [104] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [112] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [120] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [128] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [136] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [144] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [152] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [160] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [168] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252,
/* [176] */ (byte) 252, (byte) 251, (byte) 251, (byte) 251, (byte) 251, (byte) 251, (byte) 251, (byte) 251,
/* [184] */ (byte) 251, (byte) 251, (byte) 251, (byte) 251, (byte) 251, (byte) 251, (byte) 250, (byte) 250,
/* [192] */ (byte) 250, (byte) 250, (byte) 250, (byte) 250, (byte) 250, (byte) 249, (byte) 249, (byte) 249,
/* [200] */ (byte) 249, (byte) 249, (byte) 249, (byte) 248, (byte) 248, (byte) 248, (byte) 248, (byte) 247,
/* [208] */ (byte) 247, (byte) 247, (byte) 247, (byte) 246, (byte) 246, (byte) 246, (byte) 245, (byte) 245,
/* [216] */ (byte) 244, (byte) 244, (byte) 243, (byte) 243, (byte) 242, (byte) 241, (byte) 241, (byte) 240,
/* [224] */ (byte) 239, (byte) 237, (byte) 3, (byte) 3, (byte) 4, (byte) 4, (byte) 6, (byte) 0,
/* [232] */ (byte) 0, (byte) 0, (byte) 0, (byte) 236, (byte) 237, (byte) 238, (byte) 239, (byte) 240,
/* [240] */ (byte) 241, (byte) 242, (byte) 243, (byte) 244, (byte) 245, (byte) 246, (byte) 247, (byte) 248,
/* [248] */ (byte) 249, (byte) 250, (byte) 251, (byte) 252, (byte) 2, (byte) 0, (byte) 0, (byte) 0,
};
/** The alias inverse PMF. */
protected static final long[] IPMF = {
/* [ 0] */ 9223372036854774016L, 1623796909450834944L, 2664290944894291200L, 7387971354164060928L,
/* [ 4] */ 6515064486552723200L, 8840508362680718848L, 6099647593382936320L, 7673130333659513856L,
/* [ 8] */ 6220332867583438080L, 5045979640552813824L, 4075305837223955456L, 3258413672162525440L,
/* [ 12] */ 2560664887087762432L, 1957224924672899584L, 1429800935350577408L, 964606309710808320L,
/* [ 16] */ 551043923599587072L, 180827629096890368L, -152619738120023552L, -454588624410291456L,
/* [ 20] */ -729385126147774976L, -980551509819447040L, -1211029700667463936L, -1423284293868548352L,
/* [ 24] */ -1619396356369050368L, -1801135830956211712L, -1970018048575618048L, -2127348289059705344L,
/* [ 28] */ -2274257249303686400L, -2411729520096655360L, -2540626634159181056L, -2661705860113406464L,
/* [ 32] */ -2775635634532450560L, -2883008316030465280L, -2984350790383654912L, -3080133339198116352L,
/* [ 36] */ -3170777096303091200L, -3256660348483819008L, -3338123885075136256L, -3415475560473299200L,
/* [ 40] */ -3488994201966428160L, -3558932970354473216L, -3625522261068041216L, -3688972217741989376L,
/* [ 44] */ -3749474917563782656L, -3807206277531056128L, -3862327722496843520L, -3914987649156779776L,
/* [ 48] */ -3965322714631865344L, -4013458973776895488L, -4059512885612783360L, -4103592206186241024L,
/* [ 52] */ -4145796782586128128L, -4186219260694347008L, -4224945717447275264L, -4262056226866285568L,
/* [ 56] */ -4297625367836519680L, -4331722680528537344L, -4364413077437472512L, -4395757214229401600L,
/* [ 60] */ -4425811824915135744L, -4454630025296932608L, -4482261588141290496L, -4508753193105288192L,
/* [ 64] */ -4534148654077808896L, -4558489126279958272L, -4581813295192216576L, -4604157549138257664L,
/* [ 68] */ -4625556137145255168L, -4646041313519104512L, -4665643470413305856L, -4684391259530326528L,
/* [ 72] */ -4702311703971761664L, -4719430301145103360L, -4735771117539946240L, -4751356876102087168L,
/* [ 76] */ -4766209036859133952L, -4780347871386013440L, -4793792531638892032L, -4806561113635132672L,
/* [ 80] */ -4818670716409306624L, -4830137496634465536L, -4840976719260837888L, -4851202804490348800L,
/* [ 84] */ -4860829371376460032L, -4869869278311657472L, -4878334660640771072L, -4886236965617427200L,
/* [ 88] */ -4893586984900802560L, -4900394884772702720L, -4906670234238885376L, -4912422031164496896L,
/* [ 92] */ -4917658726580119808L, -4922388247283532288L, -4926618016851066624L, -4930354975163335168L,
/* [ 96] */ -4933605596540651264L, -4936375906575303936L, -4938671497741366016L, -4940497543854575616L,
/* [100] */ -4941858813449629440L, -4942759682136114944L, -4943204143989086720L, -4943195822025528064L,
/* [104] */ -4942737977813206528L, -4941833520255033344L, -4940485013586738944L, -4938694684624359424L,
/* [108] */ -4936464429291795968L, -4933795818458825728L, -4930690103114057984L, -4927148218896864000L,
/* [112] */ -4923170790008275968L, -4918758132519213568L, -4913910257091645696L, -4908626871126539264L,
/* [116] */ -4902907380349533952L, -4896750889844272896L, -4890156204540531200L, -4883121829162554368L,
/* [120] */ -4875645967641781248L, -4867726521994927104L, -4859361090668103424L, -4850546966345113600L,
/* [124] */ -4841281133215539200L, -4831560263698491904L, -4821380714613447424L, -4810738522790066176L,
/* [128] */ -4799629400105481984L, -4788048727936307200L, -4775991551010514944L, -4763452570642114304L,
/* [132] */ -4750426137329494528L, -4736906242696389120L, -4722886510751377664L, -4708360188440089088L,
/* [136] */ -4693320135461421056L, -4677758813316108032L, -4661668273553489152L, -4645040145179241472L,
/* [140] */ -4627865621182772224L, -4610135444140930048L, -4591839890849345536L, -4572968755929961472L,
/* [144] */ -4553511334358205696L, -4533456402849101568L, -4512792200036279040L, -4491506405372580864L,
/* [148] */ -4469586116675402496L, -4447017826233107968L, -4423787395382284800L, -4399880027458416384L,
/* [152] */ -4375280239014115072L, -4349971829190472192L, -4323937847117721856L, -4297160557210933504L,
/* [156] */ -4269621402214949888L, -4241300963840749312L, -4212178920821861632L, -4182234004204451584L,
/* [160] */ -4151443949668877312L, -4119785446662287616L, -4087234084103201536L, -4053764292396156928L,
/* [164] */ -4019349281473081856L, -3983960974549692672L, -3947569937258423296L, -3910145301787345664L,
/* [168] */ -3871654685619032064L, -3832064104425388800L, -3791337878631544832L, -3749438533114327552L,
/* [172] */ -3706326689447984384L, -3661960950051848192L, -3616297773528534784L, -3569291340409189376L,
/* [176] */ -3520893408440946176L, -3471053156460654336L, -3419717015797782528L, -3366828488034805504L,
/* [180] */ -3312327947826460416L, -3256152429334010368L, -3198235394669719040L, -3138506482563172864L,
/* [184] */ -3076891235255162880L, -3013310801389730816L, -2947681612411374848L, -2879915029671670784L,
/* [188] */ -2809916959107513856L, -2737587429961866240L, -2662820133571325696L, -2585501917733380096L,
/* [192] */ -2505512231579385344L, -2422722515205211648L, -2336995527534088448L, -2248184604988727552L,
/* [196] */ -2156132842510765056L, -2060672187261025536L, -1961622433929371904L, -1858790108950105600L,
/* [200] */ -1751967229002895616L, -1640929916937142784L, -1525436855617582592L, -1405227557075253248L,
/* [204] */ -1280020420662650112L, -1149510549536596224L, -1013367289578704896L, -871231448632104192L,
/* [208] */ -722712146453667840L, -567383236774436096L, -404779231966938368L, -234390647591545856L,
/* [212] */ -55658667960119296L, 132030985907841280L, 329355128892811776L, 537061298001085184L,
/* [216] */ 755977262693564160L, 987022116608033280L, 1231219266829431296L, 1489711711346518528L,
/* [220] */ 1763780090187553792L, 2054864117341795072L, 2364588157623768832L, 2694791916990503168L,
/* [224] */ 3047567482883476224L, 3425304305830816256L, 3830744187097297920L, 4267048975685830400L,
/* [228] */ 4737884547990017280L, 5247525842198998272L, 5800989391535355392L, 6404202162993295360L,
/* [232] */ 7064218894258540544L, 7789505049452331520L, 8590309807749444864L, 7643763810684489984L,
/* [236] */ 8891950541491446016L, 5457384281016206080L, 9083704440929284096L, 7976211653914433280L,
/* [240] */ 8178631350487117568L, 2821287825726744832L, 6322989683301709568L, 4309503753387611392L,
/* [244] */ 4685170734960170496L, 8404845967535199744L, 7330522972447554048L, 1960945799076992000L,
/* [248] */ 4742910674644899072L, -751799822533509888L, 7023456603741959936L, 3843116882594676224L,
/* [252] */ 3927231442413903104L, -9223372036854775808L, -9223372036854775808L, -9223372036854775808L,
};
/**
* The precomputed ziggurat lengths, denoted X_i in the main text. X_i = length of
* ziggurat layer i. Values have been scaled by 2^-63.
*/
protected static final double[] X = {
/* [ 0] */ 8.2066240675348816e-19, 7.3973732351607284e-19, 6.9133313377915293e-19, 6.5647358820964533e-19,
/* [ 4] */ 6.2912539959818508e-19, 6.0657224129604964e-19, 5.8735276103737269e-19, 5.7058850528536941e-19,
/* [ 8] */ 5.557094569162239e-19, 5.4232438903743953e-19, 5.3015297696508776e-19, 5.1898739257708062e-19,
/* [ 12] */ 5.086692261799833e-19, 4.9907492938796469e-19, 4.9010625894449536e-19, 4.8168379010649187e-19,
/* [ 16] */ 4.7374238653644714e-19, 4.6622795807196824e-19, 4.5909509017784048e-19, 4.5230527790658154e-19,
/* [ 20] */ 4.458255881635396e-19, 4.3962763126368381e-19, 4.336867596710647e-19, 4.2798143618469714e-19,
/* [ 24] */ 4.2249273027064889e-19, 4.172039125346411e-19, 4.1210012522465616e-19, 4.0716811225869233e-19,
/* [ 28] */ 4.0239599631006903e-19, 3.9777309342877357e-19, 3.9328975785334499e-19, 3.8893725129310323e-19,
/* [ 32] */ 3.8470763218720385e-19, 3.8059366138180143e-19, 3.765887213854473e-19, 3.7268674692030177e-19,
/* [ 36] */ 3.6888216492248162e-19, 3.6516984248800068e-19, 3.6154504153287473e-19, 3.5800337915318032e-19,
/* [ 40] */ 3.5454079284533432e-19, 3.5115350988784242e-19, 3.4783802030030962e-19, 3.4459105288907336e-19,
/* [ 44] */ 3.4140955396563316e-19, 3.3829066838741162e-19, 3.3523172262289001e-19, 3.3223020958685874e-19,
/* [ 48] */ 3.2928377502804472e-19, 3.2639020528202049e-19, 3.2354741622810815e-19, 3.2075344331080789e-19,
/* [ 52] */ 3.1800643250478609e-19, 3.1530463211820845e-19, 3.1264638534265134e-19, 3.1003012346934211e-19,
/* [ 56] */ 3.0745435970137301e-19, 3.0491768350005559e-19, 3.0241875541094565e-19, 2.999563023214455e-19,
/* [ 60] */ 2.9752911310742592e-19, 2.9513603463113224e-19, 2.9277596805684267e-19, 2.9044786545442563e-19,
/* [ 64] */ 2.8815072666416712e-19, 2.8588359639906928e-19, 2.8364556156331615e-19, 2.8143574876779799e-19,
/* [ 68] */ 2.7925332202553125e-19, 2.7709748061152879e-19, 2.7496745707320232e-19, 2.7286251537873397e-19,
/* [ 72] */ 2.7078194919206054e-19, 2.687250802641905e-19, 2.6669125693153442e-19, 2.6467985271278891e-19,
/* [ 76] */ 2.6269026499668434e-19, 2.6072191381359757e-19, 2.5877424068465143e-19, 2.5684670754248168e-19,
/* [ 80] */ 2.5493879571835479e-19, 2.5305000499077481e-19, 2.511798526911271e-19, 2.4932787286227806e-19,
/* [ 84] */ 2.474936154663866e-19, 2.4567664563848669e-19, 2.4387654298267842e-19, 2.4209290090801527e-19,
/* [ 88] */ 2.4032532600140538e-19, 2.3857343743505147e-19, 2.3683686640614648e-19, 2.3511525560671253e-19,
/* [ 92] */ 2.3340825872163284e-19, 2.3171553995306794e-19, 2.3003677356958333e-19, 2.2837164347843482e-19,
/* [ 96] */ 2.2671984281957174e-19, 2.2508107358001938e-19, 2.2345504622739592e-19, 2.2184147936140775e-19,
/* [100] */ 2.2024009938224424e-19, 2.1865064017486842e-19, 2.1707284280826716e-19, 2.1550645524878675e-19,
/* [104] */ 2.1395123208673778e-19, 2.124069342755064e-19, 2.1087332888245875e-19, 2.0935018885097035e-19,
/* [108] */ 2.0783729277295508e-19, 2.0633442467130712e-19, 2.0484137379170616e-19, 2.0335793440326865e-19,
/* [112] */ 2.018839056075609e-19, 2.0041909115551697e-19, 1.9896329927183254e-19, 1.975163424864309e-19,
/* [116] */ 1.9607803747261946e-19, 1.9464820489157862e-19, 1.9322666924284314e-19, 1.9181325872045647e-19,
/* [120] */ 1.9040780507449479e-19, 1.8901014347767504e-19, 1.8762011239677479e-19, 1.8623755346860768e-19,
/* [124] */ 1.8486231138030984e-19, 1.8349423375370566e-19, 1.8213317103353295e-19, 1.8077897637931708e-19,
/* [128] */ 1.7943150556069476e-19, 1.7809061685599652e-19, 1.7675617095390567e-19, 1.7542803085801941e-19,
/* [132] */ 1.7410606179414531e-19, 1.727901311201724e-19, 1.7148010823836362e-19, 1.7017586450992059e-19,
/* [136] */ 1.6887727317167824e-19, 1.6758420925479093e-19, 1.6629654950527621e-19, 1.6501417230628659e-19,
/* [140] */ 1.6373695760198277e-19, 1.624647868228856e-19, 1.6119754281258616e-19, 1.5993510975569615e-19,
/* [144] */ 1.5867737310692309e-19, 1.5742421952115544e-19, 1.5617553678444595e-19, 1.5493121374578016e-19,
/* [148] */ 1.5369114024951992e-19, 1.5245520706841019e-19, 1.5122330583703858e-19, 1.4999532898563561e-19,
/* [152] */ 1.4877116967410352e-19, 1.4755072172615974e-19, 1.4633387956347966e-19, 1.4512053813972103e-19,
/* [156] */ 1.4391059287430991e-19, 1.4270393958586506e-19, 1.4150047442513381e-19, 1.4030009380730888e-19,
/* [160] */ 1.3910269434359025e-19, 1.3790817277185197e-19, 1.3671642588626657e-19, 1.3552735046573446e-19,
/* [164] */ 1.3434084320095729e-19, 1.3315680061998685e-19, 1.3197511901207148e-19, 1.3079569434961214e-19,
/* [168] */ 1.2961842220802957e-19, 1.2844319768333099e-19, 1.2726991530715219e-19, 1.2609846895903523e-19,
/* [172] */ 1.2492875177568625e-19, 1.237606560569394e-19, 1.2259407316813331e-19, 1.2142889343858445e-19,
/* [176] */ 1.2026500605581765e-19, 1.1910229895518744e-19, 1.1794065870449425e-19, 1.1677997038316715e-19,
/* [180] */ 1.1562011745554883e-19, 1.1446098163777869e-19, 1.1330244275772562e-19, 1.1214437860737343e-19,
/* [184] */ 1.109866647870073e-19, 1.0982917454048923e-19, 1.0867177858084351e-19, 1.0751434490529747e-19,
/* [188] */ 1.0635673859884002e-19, 1.0519882162526621e-19, 1.0404045260457141e-19, 1.0288148657544097e-19,
/* [192] */ 1.0172177474144965e-19, 1.0056116419943559e-19, 9.9399497648346677e-20, 9.8236613076667446e-20,
/* [196] */ 9.7072343426320094e-20, 9.5906516230690634e-20, 9.4738953224154196e-20, 9.3569469920159036e-20,
/* [200] */ 9.2397875154569468e-20, 9.1223970590556472e-20, 9.0047550180852874e-20, 8.8868399582647627e-20,
/* [204] */ 8.768629551976745e-20, 8.6501005086071005e-20, 8.5312284983141187e-20, 8.4119880684385214e-20,
/* [208] */ 8.292352551651342e-20, 8.1722939648034506e-20, 8.0517828972839211e-20, 7.9307883875099226e-20,
/* [212] */ 7.8092777859524425e-20, 7.6872166028429042e-20, 7.5645683383965122e-20, 7.4412942930179128e-20,
/* [216] */ 7.3173533545093332e-20, 7.1927017587631075e-20, 7.0672928197666785e-20, 6.9410766239500362e-20,
/* [220] */ 6.8139996829256425e-20, 6.6860045374610234e-20, 6.5570293040210081e-20, 6.4270071533368528e-20,
/* [224] */ 6.2958657080923559e-20, 6.1635263438143136e-20, 6.02990337321517e-20, 5.8949030892850181e-20,
/* [228] */ 5.758422635988593e-20, 5.6203486669597397e-20, 5.4805557413499315e-20, 5.3389043909003295e-20,
/* [232] */ 5.1952387717989917e-20, 5.0493837866338355e-20, 4.9011415222629489e-20, 4.7502867933366117e-20,
/* [236] */ 4.5965615001265455e-20, 4.4396673897997565e-20, 4.2792566302148588e-20, 4.1149193273430015e-20,
/* [240] */ 3.9461666762606287e-20, 3.7724077131401685e-20, 3.592916408620436e-20, 3.4067836691100565e-20,
/* [244] */ 3.2128447641564046e-20, 3.0095646916399994e-20, 2.7948469455598328e-20, 2.5656913048718645e-20,
/* [248] */ 2.3175209756803909e-20, 2.0426695228251291e-20, 1.7261770330213488e-20, 1.3281889259442579e-20,
/* [252] */ 0,
};
/** The precomputed ziggurat heights, denoted Y_i in the main text. Y_i = f(X_i).
* Values have been scaled by 2^-63. */
protected static final double[] Y = {
/* [ 0] */ 5.595205495112736e-23, 1.1802509982703313e-22, 1.8444423386735829e-22, 2.5439030466698309e-22,
/* [ 4] */ 3.2737694311509334e-22, 4.0307732132706715e-22, 4.8125478319495115e-22, 5.6172914896583308e-22,
/* [ 8] */ 6.4435820540443526e-22, 7.2902662343463681e-22, 8.1563888456321941e-22, 9.0411453683482223e-22,
/* [ 12] */ 9.9438488486399206e-22, 1.0863906045969114e-21, 1.1800799775461269e-21, 1.2754075534831208e-21,
/* [ 16] */ 1.372333117637729e-21, 1.4708208794375214e-21, 1.5708388257440445e-21, 1.6723581984374566e-21,
/* [ 20] */ 1.7753530675030514e-21, 1.8797999785104595e-21, 1.9856776587832504e-21, 2.0929667704053244e-21,
/* [ 24] */ 2.201649700995824e-21, 2.3117103852306179e-21, 2.4231341516125464e-21, 2.5359075901420891e-21,
/* [ 28] */ 2.6500184374170538e-21, 2.7654554763660391e-21, 2.8822084483468604e-21, 3.0002679757547711e-21,
/* [ 32] */ 3.1196254936130377e-21, 3.2402731888801749e-21, 3.3622039464187092e-21, 3.4854113007409036e-21,
/* [ 36] */ 3.6098893927859475e-21, 3.7356329310971768e-21, 3.8626371568620053e-21, 3.9908978123552837e-21,
/* [ 40] */ 4.1204111123918948e-21, 4.2511737184488913e-21, 4.3831827151633737e-21, 4.5164355889510656e-21,
/* [ 44] */ 4.6509302085234806e-21, 4.7866648071096003e-21, 4.9236379662119969e-21, 5.0618486007478993e-21,
/* [ 48] */ 5.2012959454434732e-21, 5.3419795423648946e-21, 5.4838992294830959e-21, 5.6270551301806347e-21,
/* [ 52] */ 5.7714476436191935e-21, 5.9170774358950678e-21, 6.0639454319177027e-21, 6.2120528079531677e-21,
/* [ 56] */ 6.3614009847804375e-21, 6.5119916214136427e-21, 6.6638266093481696e-21, 6.8169080672926277e-21,
/* [ 60] */ 6.9712383363524377e-21, 7.1268199756340822e-21, 7.2836557582420336e-21, 7.4417486676430174e-21,
/* [ 64] */ 7.6011018943746355e-21, 7.7617188330775411e-21, 7.9236030798322572e-21, 8.0867584297834842e-21,
/* [ 68] */ 8.2511888750363333e-21, 8.4168986028103258e-21, 8.5838919938383098e-21, 8.7521736209986459e-21,
/* [ 72] */ 8.9217482481700712e-21, 9.0926208292996504e-21, 9.2647965076751277e-21, 9.4382806153938292e-21,
/* [ 76] */ 9.6130786730210328e-21, 9.7891963894314161e-21, 9.966639661827884e-21, 1.0145414575932636e-20,
/* [ 80] */ 1.0325527406345955e-20, 1.0506984617068672e-20, 1.0689792862184811e-20, 1.0873958986701341e-20,
/* [ 84] */ 1.10594900275424e-20, 1.1246393214695825e-20, 1.1434675972510121e-20, 1.1624345921140471e-20,
/* [ 88] */ 1.1815410878142659e-20, 1.2007878860214202e-20, 1.2201758085082226e-20, 1.239705697353804e-20,
/* [ 92] */ 1.2593784151618565e-20, 1.2791948452935152e-20, 1.29915589211506e-20, 1.3192624812605428e-20,
/* [ 96] */ 1.3395155599094805e-20, 1.3599160970797774e-20, 1.3804650839360727e-20, 1.4011635341137284e-20,
/* [100] */ 1.4220124840587164e-20, 1.4430129933836705e-20, 1.4641661452404201e-20, 1.485473046709328e-20,
/* [104] */ 1.5069348292058084e-20, 1.5285526489044053e-20, 1.5503276871808626e-20, 1.5722611510726402e-20,
/* [108] */ 1.5943542737583543e-20, 1.6166083150566702e-20, 1.6390245619451956e-20, 1.6616043290999594e-20,
/* [112] */ 1.6843489594561079e-20, 1.7072598247904713e-20, 1.7303383263267072e-20, 1.7535858953637607e-20,
/* [116] */ 1.7770039939284241e-20, 1.8005941154528286e-20, 1.8243577854777398e-20, 1.8482965623825808e-20,
/* [120] */ 1.8724120381431627e-20, 1.8967058391181452e-20, 1.9211796268653192e-20, 1.9458350989888484e-20,
/* [124] */ 1.9706739900186868e-20, 1.9956980723234356e-20, 2.0209091570579904e-20, 2.0463090951473895e-20,
/* [128] */ 2.0718997783083593e-20, 2.097683140110135e-20, 2.123661157076213e-20, 2.1498358498287976e-20,
/* [132] */ 2.1762092842777868e-20, 2.2027835728562592e-20, 2.2295608758045219e-20, 2.2565434025049041e-20,
/* [136] */ 2.2837334128696004e-20, 2.311133218784001e-20, 2.3387451856080863e-20, 2.3665717337386111e-20,
/* [140] */ 2.394615340234961e-20, 2.422878540511741e-20, 2.4513639301013211e-20, 2.4800741664897764e-20,
/* [144] */ 2.5090119710298442e-20, 2.5381801309347597e-20, 2.56758150135705e-20, 2.5972190075566336e-20,
/* [148] */ 2.6270956471628253e-20, 2.6572144925351523e-20, 2.6875786932281841e-20, 2.7181914785659148e-20,
/* [152] */ 2.7490561603315974e-20, 2.7801761355793055e-20, 2.8115548895739172e-20, 2.8431959988666534e-20,
/* [156] */ 2.8751031345137833e-20, 2.9072800654466307e-20, 2.9397306620015486e-20, 2.9724588996191657e-20,
/* [160] */ 3.0054688627228112e-20, 3.0387647487867642e-20, 3.0723508726057078e-20, 3.1062316707775905e-20,
/* [164] */ 3.1404117064129991e-20, 3.1748956740850969e-20, 3.2096884050352357e-20, 3.2447948726504914e-20,
/* [168] */ 3.2802201982306013e-20, 3.3159696570631373e-20, 3.352048684827223e-20, 3.3884628843476888e-20,
/* [172] */ 3.4252180327233346e-20, 3.4623200888548644e-20, 3.4997752014001677e-20, 3.537589717186906e-20,
/* [176] */ 3.5757701901149035e-20, 3.6143233905835799e-20, 3.65325631548274e-20, 3.6925761987883572e-20,
/* [180] */ 3.7322905228086981e-20, 3.7724070301302117e-20, 3.8129337363171041e-20, 3.8538789434235234e-20,
/* [184] */ 3.8952512543827862e-20, 3.9370595883442399e-20, 3.9793131970351439e-20, 4.0220216822325769e-20,
/* [188] */ 4.0651950144388133e-20, 4.1088435528630944e-20, 4.1529780668232712e-20, 4.1976097586926582e-20,
/* [192] */ 4.2427502885307452e-20, 4.2884118005513604e-20, 4.3346069515987453e-20, 4.3813489418210257e-20,
/* [196] */ 4.4286515477520838e-20, 4.4765291580372353e-20, 4.5249968120658306e-20, 4.5740702418054417e-20,
/* [200] */ 4.6237659171683015e-20, 4.6741010952818368e-20, 4.7250938740823415e-20, 4.7767632507051219e-20,
/* [204] */ 4.8291291852069895e-20, 4.8822126702292804e-20, 4.9360358072933852e-20, 4.9906218905182021e-20,
/* [208] */ 5.0459954986625539e-20, 5.1021825965285324e-20, 5.1592106469178258e-20, 5.2171087345169234e-20,
/* [212] */ 5.2759077033045284e-20, 5.3356403093325858e-20, 5.3963413910399511e-20, 5.4580480596259246e-20,
/* [216] */ 5.5207999124535584e-20, 5.584639272987383e-20, 5.649611461419377e-20, 5.7157651009290713e-20,
/* [220] */ 5.7831524654956632e-20, 5.8518298763794323e-20, 5.9218581558791713e-20, 5.99330314883387e-20,
/* [224] */ 6.0662363246796887e-20, 6.1407354758435e-20, 6.2168855320499763e-20, 6.2947795150103727e-20,
/* [228] */ 6.3745196643214394e-20, 6.4562187737537985e-20, 6.5400017881889097e-20, 6.6260077263309343e-20,
/* [232] */ 6.714392014514662e-20, 6.8053293447301698e-20, 6.8990172088133e-20, 6.9956803158564498e-20,
/* [236] */ 7.095576179487843e-20, 7.199002278894508e-20, 7.3063053739105458e-20, 7.4178938266266881e-20,
/* [240] */ 7.5342542134173124e-20, 7.6559742171142969e-20, 7.783774986341285e-20, 7.9185582674029512e-20,
/* [244] */ 8.06147755373533e-20, 8.2140502769818073e-20, 8.3783445978280519e-20, 8.5573129249678161e-20,
/* [248] */ 8.75544596695901e-20, 8.9802388057706877e-20, 9.2462471421151086e-20, 9.5919641344951721e-20,
/* [252] */ 1.0842021724855044e-19,
};
/** Underlying source of randomness. */
protected final UniformRandomProvider rng;
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratExponentialSampler(UniformRandomProvider rng) {
this.rng = rng;
}
/** {@inheritDoc} */
@Override
public double sample() {
return createSample();
}
/**
* Creates the exponential sample with {@code mean = 1}.
*
* <p>Note: This has been extracted to a separate method so that the recursive call
* when sampling tries again targets this function. This allows sub-classes
* to override the sample method to generate a sample with a different mean using:
* <pre>
* @Override
* public double sample() {
* return super.sample() * mean;
* }
* </pre>
* Otherwise the sub-class {@code sample()} method will recursively call
* the overloaded sample() method when trying again which creates a bad sample due
* to compound multiplication of the mean.
*
* @return the sample
*/
protected double createSample() {
final long x = nextLong();
// Float multiplication squashes these last 8 bits, so they can be used to sample i
final int i = ((int) x) & 0xff;
if (i < I_MAX) {
// Early exit.
return X[i] * (x & MAX_INT64);
}
final int j = selectRegion();
return j == 0 ? X_0 + createSample() : sampleOverhang(j);
}
/**
* Select the overhang region or the tail using alias sampling.
*
* @return the region
*/
protected int selectRegion() {
final long x = nextLong();
// j in [0, 256)
final int j = ((int) x) & 0xff;
// map to j in [0, N] with N the number of layers of the ziggurat
return x >= IPMF[j] ? MAP[j] & 0xff : j;
}
/**
* Sample from overhang region {@code j}.
*
* @param j Index j (must be {@code > 0})
* @return the sample
*/
protected double sampleOverhang(int j) {
// Sample from the triangle:
// X[j],Y[j]
// |\-->u1
// | \ |
// | \ |
// | \| Overhang j (with hypotenuse not pdf(x))
// | \
// | |\
// | | \
// | u2 \
// +-------- X[j-1],Y[j-1]
// u2 = u1 + (u2 - u1) = u1 + uDistance
// If u2 < u1 then reflect in the hypotenuse by swapping u1 and u2.
long u1 = randomInt63();
long uDistance = randomInt63() - u1;
if (uDistance < 0) {
uDistance = -uDistance;
u1 -= uDistance;
}
final double x = sampleX(X, j, u1);
if (uDistance >= E_MAX) {
// Early Exit: x < y - epsilon
return x;
}
return sampleY(Y, j, u1 + uDistance) <= Math.exp(-x) ? x : sampleOverhang(j);
}
/**
* Generates a {@code long}.
*
* @return the long
*/
protected long nextLong() {
return rng.nextLong();
}
/**
* Return a positive long in {@code [0, 2^63)}.
*
* @return the long
*/
protected long randomInt63() {
return rng.nextLong() & MAX_INT64;
}
}
/**
* Modified Ziggurat method for sampling from an exponential distribution.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This implementation uses simple overhangs and does not exploit the precomputed
* distances of the convex overhang.
*
* <p>Note: It is not expected that this method is faster as the simple overhangs do
* not exploit the property that the exponential PDF is always concave. Thus any upper-right
* triangle sample at the edge of the ziggurat can be reflected and tested against the
* lower-left triangle limit.
*/
static class ModifiedZigguratExponentialSamplerSimpleOverhangs
extends ModifiedZigguratExponentialSampler {
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratExponentialSamplerSimpleOverhangs(UniformRandomProvider rng) {
super(rng);
}
/** {@inheritDoc} */
@Override
protected double sampleOverhang(int j) {
final double x = sampleX(X, j, randomInt63());
return sampleY(Y, j, randomInt63()) <= Math.exp(-x) ? x : sampleOverhang(j);
}
}
/**
* Modified Ziggurat method for sampling from an exponential distribution.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This implementation separates sampling of the main ziggurat and sampling from the edge
* into different methods. This allows inlining of the main sample method.
*
* <p>The sampler will output different values due to the use of a bit shift to generate
* unsigned integers. This removes the requirement to load the mask MAX_INT64
* and ensures the method is under 35 bytes.
*/
static class ModifiedZigguratExponentialSamplerInlining
extends ModifiedZigguratExponentialSampler {
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratExponentialSamplerInlining(UniformRandomProvider rng) {
super(rng);
}
/** {@inheritDoc} */
@Override
public double sample() {
// Ideally this method byte code size should be below -XX:MaxInlineSize
// (which defaults to 35 bytes). This compiles to 34 bytes.
final long x = nextLong();
// Float multiplication squashes these last 8 bits, so they can be used to sample i
final int i = ((int) x) & 0xff;
if (i < I_MAX) {
// Early exit.
return X[i] * (x >>> 1);
}
return edgeSample();
}
/**
* Create the sample from the edge of the ziggurat.
*
* <p>This method has been extracted to fit the main sample method within 35 bytes (the
* default size for a JVM to inline a method).
*
* @return a sample
*/
private double edgeSample() {
final int j = selectRegion();
return j == 0 ? sampleAdd(X_0) : sampleOverhang(j);
}
/**
* Creates a sample and adds it to the current value. This exploits the memoryless
* exponential distribution by generating a sample and adding it to the existing end
* of the previous ziggurat.
*
* <p>The method will use recursion in the event of a new tail. Passing the
* existing value allows the potential to optimise the memory stack.
*
* @param x0 Current value
* @return the sample
*/
private double sampleAdd(double x0) {
final long x = nextLong();
final int i = ((int) x) & 0xff;
if (i < I_MAX) {
// Early exit.
return x0 + X[i] * (x >>> 1);
}
// Edge of the ziggurat
final int j = selectRegion();
return j == 0 ? sampleAdd(x0 + X_0) : x0 + sampleOverhang(j);
}
}
/**
* Modified Ziggurat method for sampling from an exponential distribution.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This implementation separates sampling of the main ziggurat and sampling from the edge
* into different methods. This allows inlining of the main sample method.
*
* <p>The sampler will output different values due to the use of a bit shift to generate
* unsigned integers. This removes the requirement to load the mask MAX_INT64
* and ensures the method is under 35 bytes.
*
* <p>Tail sampling outside of the main sample method is performed in a loop.
*/
static class ModifiedZigguratExponentialSamplerLoop
extends ModifiedZigguratExponentialSampler {
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratExponentialSamplerLoop(UniformRandomProvider rng) {
super(rng);
}
/** {@inheritDoc} */
@Override
public double sample() {
// Ideally this method byte code size should be below -XX:MaxInlineSize
// (which defaults to 35 bytes). This compiles to 34 bytes.
final long x = nextLong();
// Float multiplication squashes these last 8 bits, so they can be used to sample i
final int i = ((int) x) & 0xff;
if (i < I_MAX) {
// Early exit.
return X[i] * (x >>> 1);
}
return edgeSample();
}
/**
* Create the sample from the edge of the ziggurat.
*
* <p>This method has been extracted to fit the main sample method within 35 bytes (the
* default size for a JVM to inline a method).
*
* @return a sample
*/
private double edgeSample() {
int j = selectRegion();
if (j != 0) {
return sampleOverhang(j);
}
// Perform a new sample and add it to the start of the tail.
double x0 = X_0;
for (;;) {
final long x = nextLong();
final int i = ((int) x) & 0xff;
if (i < I_MAX) {
// Early exit.
return x0 + X[i] * (x >>> 1);
}
// Edge of the ziggurat
j = selectRegion();
if (j != 0) {
return x0 + sampleOverhang(j);
}
// Another tail sample
x0 += X_0;
}
}
}
/**
* Modified Ziggurat method for sampling from an exponential distribution.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This implementation separates sampling of the main ziggurat and sampling from the edge
* into different methods. This allows inlining of the main sample method.
*
* <p>The sampler will output different values due to the use of a bit shift to generate
* unsigned integers. This removes the requirement to load the mask MAX_INT64
* and ensures the method is under 35 bytes.
*
* <p>Tail sampling outside of the main sample method is performed in a loop. No recursion
* is used. The first random deviate is recycled if the sample if from the edge.
*/
static class ModifiedZigguratExponentialSamplerLoop2
extends ModifiedZigguratExponentialSampler {
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratExponentialSamplerLoop2(UniformRandomProvider rng) {
super(rng);
}
/** {@inheritDoc} */
@Override
public double sample() {
// Ideally this method byte code size should be below -XX:MaxInlineSize
// (which defaults to 35 bytes). This compiles to 35 bytes.
final long x = nextLong();
// Float multiplication squashes these last 8 bits, so they can be used to sample i
final int i = ((int) x) & 0xff;
if (i < I_MAX) {
// Early exit.
return X[i] * (x >>> 1);
}
// Recycle x as the upper 56 bits have not been used.
return edgeSample(x);
}
/**
* Create the sample from the edge of the ziggurat.
*
* <p>This method has been extracted to fit the main sample method within 35 bytes (the
* default size for a JVM to inline a method).
*
* @param xx Initial random deviate
* @return a sample
*/
private double edgeSample(long xx) {
int j = selectRegion();
if (j != 0) {
return sampleOverhang(j, xx);
}
// Perform a new sample and add it to the start of the tail.
double x0 = X_0;
for (;;) {
final long x = nextLong();
final int i = ((int) x) & 0xff;
if (i < I_MAX) {
// Early exit.
return x0 + X[i] * (x >>> 1);
}
// Edge of the ziggurat
j = selectRegion();
if (j != 0) {
return x0 + sampleOverhang(j, x);
}
// Another tail sample
x0 += X_0;
}
}
/**
* Sample from overhang region {@code j}.
*
* <p>This does not use recursion.
*
* @param j Index j (must be {@code > 0})
* @param xx Initial random deviate
* @return the sample
*/
protected double sampleOverhang(int j, long xx) {
// Recycle the initial random deviate.
// Shift right to make an unsigned long.
for (long u1 = xx >>> 1;; u1 = nextLong() >>> 1) {
// Sample from the triangle:
// X[j],Y[j]
// |\-->u1
// | \ |
// | \ |
// | \| Overhang j (with hypotenuse not pdf(x))
// | \
// | |\
// | | \
// | u2 \
// +-------- X[j-1],Y[j-1]
// u2 = u1 + (u2 - u1) = u1 + uDistance
// If u2 < u1 then reflect in the hypotenuse by swapping u1 and u2.
long uDistance = (nextLong() >>> 1) - u1;
if (uDistance < 0) {
uDistance = -uDistance;
u1 -= uDistance;
}
final double x = sampleX(X, j, u1);
if (uDistance >= E_MAX) {
// Early Exit: x < y - epsilon
return x;
}
if (sampleY(Y, j, u1 + uDistance) <= Math.exp(-x)) {
return x;
}
}
}
}
/**
* Modified Ziggurat method for sampling from an exponential distribution.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This implementation separates sampling of the main ziggurat and the recursive
* sampling from the edge into different methods.
*/
static class ModifiedZigguratExponentialSamplerRecursion
extends ModifiedZigguratExponentialSampler {
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratExponentialSamplerRecursion(UniformRandomProvider rng) {
super(rng);
}
/** {@inheritDoc} */
@Override
public double sample() {
final long x = nextLong();
// Float multiplication squashes these last 8 bits, so they can be used to sample i
final int i = ((int) x) & 0xff;
if (i < I_MAX) {
// Early exit.
return X[i] * (x & MAX_INT64);
}
final int j = selectRegion();
return j == 0 ? sampleAdd(X_0) : sampleOverhang(j);
}
/**
* Creates a sample and adds it to the current value. This exploits the memoryless
* exponential distribution by generating a sample and adding it to the existing end
* of the previous ziggurat.
*
* <p>The method will use recursion in the event of a new tail. Passing the
* existing value allows the potential to optimise the memory stack.
*
* @param x0 Current value
* @return the sample
*/
private double sampleAdd(double x0) {
final long x = nextLong();
final int i = ((int) x) & 0xff;
if (i < I_MAX) {
// Early exit.
return x0 + X[i] * (x & MAX_INT64);
}
// Edge of the ziggurat
final int j = selectRegion();
return j == 0 ? sampleAdd(x0 + X_0) : x0 + sampleOverhang(j);
}
}
/**
* Modified Ziggurat method for sampling from an exponential distribution.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This is a copy of {@link ModifiedZigguratExponentialSampler} using
* an integer map in-place of a byte map look-up table.
*/
static class ModifiedZigguratExponentialSamplerIntMap
extends ModifiedZigguratExponentialSampler {
/** The alias map. */
private static final int[] INT_MAP = {
/* [ 0] */ 0, 0, 1, 235, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* [ 16] */ 0, 0, 1, 1, 1, 1, 2, 2, 252, 252, 252, 252, 252, 252, 252, 252,
/* [ 32] */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
/* [ 48] */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
/* [ 64] */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
/* [ 80] */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
/* [ 96] */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
/* [112] */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
/* [128] */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
/* [144] */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
/* [160] */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
/* [176] */ 252, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 250, 250,
/* [192] */ 250, 250, 250, 250, 250, 249, 249, 249, 249, 249, 249, 248, 248, 248, 248, 247,
/* [208] */ 247, 247, 247, 246, 246, 246, 245, 245, 244, 244, 243, 243, 242, 241, 241, 240,
/* [224] */ 239, 237, 3, 3, 4, 4, 6, 0, 0, 0, 0, 236, 237, 238, 239, 240,
/* [240] */ 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 2, 0, 0, 0,
};
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratExponentialSamplerIntMap(UniformRandomProvider rng) {
super(rng);
}
/** {@inheritDoc} */
@Override
protected int selectRegion() {
final long x = nextLong();
// j in [0, 256)
final int j = ((int) x) & 0xff;
// map to j in [0, N] with N the number of layers of the ziggurat
return x >= IPMF[j] ? INT_MAP[j] : j;
}
}
/**
* Modified Ziggurat method for sampling from an exponential distribution.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This is a copy of {@link ModifiedZigguratExponentialSampler} using
* a table to store the maximum epsilon value for each overhang.
*/
static class ModifiedZigguratExponentialSamplerEMaxTable
extends ModifiedZigguratExponentialSampler {
/** The deviation of concave pdf(x) below the hypotenuse value for early exit scaled by 2^63.
* 252 entries with overhang {@code j} corresponding to entry {@code j-1}. */
private static final long[] E_MAX_TABLE = {
/* [ 0] */ 853965788476313647L, 513303011048449571L, 370159258027176883L, 290559192811411702L,
/* [ 4] */ 239682322342140259L, 204287432757591023L, 178208980447816578L, 158179811652601808L,
/* [ 8] */ 142304335868356315L, 129406004988661986L, 118715373346558305L, 109707765835789898L,
/* [ 12] */ 102012968856398207L, 95362200070363889L, 89555545194518719L, 84441195786718132L,
/* [ 16] */ 79901778875942314L, 75845102376072521L, 72197735928174183L, 68900462142397564L,
/* [ 20] */ 65904991388597543L, 63171548466382494L, 60667072432484929L, 58363855085733832L,
/* [ 24] */ 56238498180198598L, 54271105522401119L, 52444650416313533L, 50744475573288311L,
/* [ 28] */ 49157894191680121L, 47673869089531616L, 46282752622782375L, 44976074355904424L,
/* [ 32] */ 43746366552358124L, 42587019846569729L, 41492163173714974L, 40456563326820177L,
/* [ 36] */ 39475540494600872L, 38544896888152443L, 37660856147942019L, 36820011676708837L,
/* [ 40] */ 36019282399893713L, 35255874736108745L, 34527249783140581L, 33831094903027707L,
/* [ 44] */ 33165299032708110L, 32527931162123068L, 31917221515265728L, 31331545045961871L,
/* [ 48] */ 30769406922648640L, 30229429727799711L, 29710342140081525L, 29210968902516770L,
/* [ 52] */ 28730221909221458L, 28267092267755223L, 27820643214642802L, 27390003778888310L,
/* [ 56] */ 26974363102873684L, 26572965342371777L, 26185105077881714L, 25810123178421168L,
/* [ 60] */ 25447403066532673L, 25096367339794542L, 24756474709733050L, 24427217223862121L,
/* [ 64] */ 24108117740746397L, 23798727631587496L, 23498624684961198L, 23207411194051023L,
/* [ 68] */ 22924712208092083L, 22650173931802985L, 22383462258391643L, 22124261423306770L,
/* [ 72] */ 21872272767292587L, 21627213598531964L, 21388816144739113L, 21156826587012934L,
/* [ 76] */ 20931004168108672L, 20711120368524119L, 20496958144463729L, 20288311222329444L,
/* [ 80] */ 20084983444908931L, 19886788164900174L, 19693547681827322L, 19505092718772996L,
/* [ 84] */ 19321261935686425L, 19141901476327133L, 18966864546167569L, 18796011018823163L,
/* [ 88] */ 18629207068791541L, 18466324828481792L, 18307242067684946L, 18151841893803319L,
/* [ 92] */ 18000012471293326L, 17851646758910343L, 17706642263461846L, 17564900808880742L,
/* [ 96] */ 17426328319528561L, 17290834616728420L, 17158333227603225L, 17028741205374556L,
/* [100] */ 16901978960337609L, 16777970100794092L, 16656641283277552L, 16537922071455934L,
/* [104] */ 16421744803147429L, 16308044464921141L, 16196758573800601L, 16087827065618528L,
/* [108] */ 15981192189607877L, 15876798408841619L, 15774592306164744L, 15674522495285722L,
/* [112] */ 15576539536717537L, 15480595858282956L, 15386645679917351L, 15294644942520693L,
/* [116] */ 15204551240628355L, 15116323758686143L, 15029923210730485L, 14945311783286871L,
/* [120] */ 14862453081314005L, 14781312077032665L, 14701855061488253L, 14624049598708474L,
/* [124] */ 14547864482325100L, 14473269694538314L, 14400236367311981L, 14328736745694203L,
/* [128] */ 14258744153165819L, 14190232958926857L, 14123178547035436L, 14057557287324133L,
/* [132] */ 13993346508018831L, 13930524469996132L, 13869070342616606L, 13808964181079506L,
/* [136] */ 13750186905245534L, 13692720279883516L, 13636546896296650L, 13581650155291926L,
/* [140] */ 13528014251457894L, 13475624158722351L, 13424465617162582L, 13374525121048117L,
/* [144] */ 13325789908096374L, 13278247949928556L, 13231887943714024L, 13186699304997313L,
/* [148] */ 13142672161706220L, 13099797349339341L, 13058066407342105L, 13017471576677033L,
/* [152] */ 12978005798604683L, 12939662714691649L, 12902436668069432L, 12866322705969175L,
/* [156] */ 12831316583568516L, 12797414769185138L, 12764614450860914L, 12732913544387857L,
/* [160] */ 12702310702829356L, 12672805327602182L, 12644397581185285L, 12617088401539963L,
/* [164] */ 12590879518319943L, 12565773470976553L, 12541773628858256L, 12518884213426018L,
/* [168] */ 12497110322714335L, 12476457958178394L, 12456934054089150L, 12438546509646839L,
/* [172] */ 12421304224007330L, 12405217134429885L, 12390296257782254L, 12376553735658483L,
/* [176] */ 12364002883391013L, 12352658243275075L, 12342535642345809L, 12333652255094142L,
/* [180] */ 12326026671543609L, 12319678971157050L, 12314630803093705L, 12310905473395866L,
/* [184] */ 12308528039744429L, 12307525414502757L, 12307926476843287L, 12309762194847939L,
/* [188] */ 12313065758579233L, 12317872725234489L, 12324221177635088L, 12332151897455469L,
/* [192] */ 12341708554772055L, 12352937915715590L, 12365890070240929L, 12380618682293187L,
/* [196] */ 12397181264956129L, 12415639483521735L, 12436059489828363L, 12458512291688487L,
/* [200] */ 12483074161780576L, 12509827091021440L, 12538859292191186L, 12570265760462982L,
/* [204] */ 12604148898533980L, 12640619215280889L, 12679796108318231L, 12721808742570859L,
/* [208] */ 12766797039034927L, 12814912790376408L, 12866320922993068L, 12921200928753560L,
/* [212] */ 12979748493987873L, 13042177358607040L, 13108721444725108L, 13179637302147239L,
/* [216] */ 13255206927961732L, 13335741029756972L, 13421582817340701L, 13513112427153506L,
/* [220] */ 13610752108037106L, 13714972328197193L, 13826299003251241L, 13945322097066639L,
/* [224] */ 14072705914699465L, 14209201495705644L, 14355661634264763L, 14513059211087015L,
/* [228] */ 14682509737034964L, 14865299303251008L, 15062919542085557L, 15277111779554570L,
/* [232] */ 15509923383418374L, 15763780505978643L, 16041583185668067L, 16346831428994830L,
/* [236] */ 16683794981864260L, 17057745936956694L, 17475283735768697L, 17944799475531562L,
/* [240] */ 18477156350176671L, 19086716702655372L, 19792946841346963L, 20623030105811966L,
/* [244] */ 21616339529831424L, 22832582766564173L, 24367856249313960L, 26389803907514902L,
/* [248] */ 29226958795272911L, 33654855924781132L, 42320562697765039L, 141207843617418268L,
};
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratExponentialSamplerEMaxTable(UniformRandomProvider rng) {
super(rng);
}
@Override
protected double sampleOverhang(int j) {
// Look-up E_MAX
return sampleOverhang(j, E_MAX_TABLE[j - 1]);
}
/**
* Sample from overhang region {@code j}.
*
* @param j Index j (must be {@code > 0})
* @param eMax Maximum deviation of concave pdf(x) below the hypotenuse value for early exit
* @return the sample
*/
private double sampleOverhang(int j, long eMax) {
long u1 = randomInt63();
long uDistance = randomInt63() - u1;
if (uDistance < 0) {
uDistance = -uDistance;
u1 -= uDistance;
}
final double x = sampleX(X, j, u1);
if (uDistance >= eMax) {
// Early Exit: x < y - epsilon
return x;
}
return sampleY(Y, j, u1 + uDistance) <= Math.exp(-x) ? x : sampleOverhang(j, eMax);
}
}
/**
* Modified Ziggurat method for sampling from an exponential distribution.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This is a copy of {@link ModifiedZigguratExponentialSampler} using
* two values for the maximum epsilon value for the overhangs.
*
* <p>Note: The exponential curve is very well approximated by the straight line of
* the triangle hypotenuse in the majority of cases. Only as the overhang approaches the
* tail or close to x=0 does the curve differ more than 0.01 (expressed as a fraction of
* the triangle height). This can be exploited using two maximum deviation thresholds.
*/
static class ModifiedZigguratExponentialSamplerEMax2
extends ModifiedZigguratExponentialSampler {
// Ziggurat volumes:
// Inside the layers = 98.4375% (252/256)
// Fraction outside the layers:
// concave overhangs = 96.6972%
// tail (j=0) = 3.3028%
//
// Separation of tail with large maximum deviation from hypotenuse
// 0 <= j <= 8 = 7.9913%
// 1 <= j <= 8 = 4.6885%
// 9 <= j = 92.0087%
/** The overhang region j where the second maximum deviation constant is valid. */
private static final int J2 = 9;
/** Maximum deviation of concave pdf(x) below the hypotenuse value for early exit
* for overhangs {@code 9 <= j <= 253}.
* Equal to approximately 0.0154 scaled by 2^63.
*
* <p>This threshold increases the area of the early exit triangle by:
* (1-0.0154)^2 / (1-0.0926)^2 = 17.74%. */
private static final long E_MAX_2 = 142304335868356315L;
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratExponentialSamplerEMax2(UniformRandomProvider rng) {
super(rng);
}
@Override
protected double createSample() {
final long x = nextLong();
// Float multiplication squashes these last 8 bits, so they can be used to sample i
final int i = ((int) x) & 0xff;
if (i < I_MAX) {
// Early exit.
return X[i] * (x & MAX_INT64);
}
final int j = selectRegion();
if (j < J2) {
// Long tail frequency: 0.0799
// j==0 (tail) frequency: 0.033028
return j == 0 ? X_0 + createSample() : sampleOverhang(j, E_MAX);
}
// Majority of curve can use a smaller threshold.
// Frequency: 0.920087
return sampleOverhang(j, E_MAX_2);
}
/**
* Sample from overhang region {@code j}.
*
* @param j Index j (must be {@code > 0})
* @param eMax Maximum deviation of concave pdf(x) below the hypotenuse value for early exit
* @return the sample
*/
private double sampleOverhang(int j, long eMax) {
long u1 = randomInt63();
long uDistance = randomInt63() - u1;
if (uDistance < 0) {
uDistance = -uDistance;
u1 -= uDistance;
}
final double x = sampleX(X, j, u1);
if (uDistance >= eMax) {
// Early Exit: x < y - epsilon
return x;
}
return sampleY(Y, j, u1 + uDistance) <= Math.exp(-x) ? x : sampleOverhang(j, eMax);
}
}
/**
* Modified Ziggurat method for sampling from an exponential distribution.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This is a copy of {@link ModifiedZigguratExponentialSampler} using
* two ternary operators to sort the two random long values.
*/
static class ModifiedZigguratExponentialSamplerTernary
extends ModifiedZigguratExponentialSampler {
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratExponentialSamplerTernary(UniformRandomProvider rng) {
super(rng);
}
@Override
protected double sampleOverhang(int j) {
// Sample from the triangle:
// X[j],Y[j]
// |\-->u1
// | \ |
// | \ |
// | \| Overhang j (with hypotenuse not pdf(x))
// | \
// | |\
// | | \
// | u2 \
// +-------- X[j-1],Y[j-1]
// If u2 < u1 then reflect in the hypotenuse by swapping u1 and u2.
final long ua = randomInt63();
final long ub = randomInt63();
// Sort u1 < u2 to sample the lower-left triangle.
// Use conditional ternary to avoid a 50/50 branch statement to swap the pair.
final long u1 = ua < ub ? ua : ub;
final long u2 = ua < ub ? ub : ua;
final double x = sampleX(X, j, u1);
if (u2 - u1 >= E_MAX) {
// Early Exit: x < y - epsilon
return x;
}
return sampleY(Y, j, u2) <= Math.exp(-x) ? x : sampleOverhang(j);
}
}
/**
* Modified Ziggurat method for sampling from an exponential distribution.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This is a copy of {@link ModifiedZigguratExponentialSampler} using
* a ternary operator to sort the two random long values and a subtraction
* to get the difference.
*/
static class ModifiedZigguratExponentialSamplerTernarySubtract
extends ModifiedZigguratExponentialSampler {
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratExponentialSamplerTernarySubtract(UniformRandomProvider rng) {
super(rng);
}
@Override
protected double sampleOverhang(int j) {
// Sample from the triangle:
// X[j],Y[j]
// |\-->u1
// | \ |
// | \ |
// | \| Overhang j (with hypotenuse not pdf(x))
// | \
// | |\
// | | \
// | u2 \
// +-------- X[j-1],Y[j-1]
// If u2 < u1 then reflect in the hypotenuse by swapping u1 and u2.
final long ua = randomInt63();
final long ub = randomInt63();
// Sort u1 < u2 to sample the lower-left triangle.
// Use conditional ternary to avoid a 50/50 branch statement to swap the pair.
final long u1 = ua < ub ? ua : ub;
final double x = sampleX(X, j, u1);
// u2 = ua + ub - u1
// uDistance = ua + ub - u1 - u1
final long uDistance = ua + ub - (u1 << 1);
if (uDistance >= E_MAX) {
// Early Exit: x < y - epsilon
return x;
}
// u2 = u1 + uDistance
return sampleY(Y, j, u1 + uDistance) <= Math.exp(-x) ? x : sampleOverhang(j);
}
}
/**
* Modified Ziggurat method for sampling from an exponential distribution.
*
* <p>Uses the algorithm from McFarland, C.D. (2016).
*
* <p>This is a copy of {@link ModifiedZigguratExponentialSampler} using
* a table size of 512.
*/
static class ModifiedZigguratExponentialSampler512 implements ContinuousSampler {
// Ziggurat volumes:
// Inside the layers = 99.2188% (508/512)
// Fraction outside the layers:
// concave overhangs = 97.0103%
// tail = 2.9897%
/** The number of layers in the ziggurat. Maximum i value for early exit. */
protected static final int I_MAX = 508;
/** Maximum deviation of concave pdf(x) below the hypotenuse value for early exit.
* Equal to approximately 0.0919 scaled by 2^63. */
protected static final long E_MAX = 847415790149374213L;
/** Beginning of tail. Equal to X[0] * 2^63. */
protected static final double X_0 = 8.362025281328359;
/** The alias map. */
private static final int[] MAP = {
/* [ 0] */ 0, 0, 1, 473, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0,
/* [ 16] */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* [ 32] */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1,
/* [ 48] */ 1, 2, 2, 2, 2, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [ 64] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [ 80] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [ 96] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [112] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [128] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [144] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [160] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [176] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [192] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [208] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [224] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [240] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [256] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [272] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [288] */ 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508, 508,
/* [304] */ 508, 508, 508, 508, 508, 508, 508, 508, 507, 507, 507, 507, 507, 507, 507, 507,
/* [320] */ 507, 507, 507, 507, 507, 507, 507, 507, 507, 507, 507, 507, 507, 507, 507, 507,
/* [336] */ 507, 507, 507, 507, 507, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506,
/* [352] */ 506, 506, 506, 506, 506, 506, 505, 505, 505, 505, 505, 505, 505, 505, 505, 505,
/* [368] */ 505, 504, 504, 504, 504, 504, 504, 504, 504, 504, 503, 503, 503, 503, 503, 503,
/* [384] */ 503, 503, 502, 502, 502, 502, 502, 502, 501, 501, 501, 501, 501, 500, 500, 500,
/* [400] */ 500, 500, 499, 499, 499, 499, 498, 498, 498, 498, 497, 497, 497, 496, 496, 496,
/* [416] */ 495, 495, 495, 494, 494, 493, 493, 492, 492, 491, 491, 490, 490, 489, 489, 488,
/* [432] */ 487, 486, 485, 485, 484, 482, 481, 479, 477, 3, 3, 3, 3, 3, 4, 4,
/* [448] */ 4, 5, 5, 5, 6, 6, 6, 7, 7, 8, 9, 9, 10, 13, 0, 0,
/* [464] */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 474, 475, 476, 477, 478, 479, 480,
/* [480] */ 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496,
/* [496] */ 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 2, 0, 0, 0,
};
/** The alias inverse PMF. */
private static final long[] IPMF = {
/* [ 0] */ 9223372036854775296L, 2636146522269100032L, 3561072052814771200L, 3481882573634022912L,
/* [ 4] */ 7116525960784167936L, 3356999026233157120L, 4185343482988790272L, 7712945794725800960L,
/* [ 8] */ 7827282421678200832L, 5031524219672503296L, 8479703117927504896L, 8798557826262976512L,
/* [ 12] */ 6461753601163497984L, 5374576640182409216L, 8285209933846173696L, 7451775918468278784L,
/* [ 16] */ 6710527725555065344L, 6046590166603477504L, 5448165515863960576L, 4905771306157685248L,
/* [ 20] */ 4411694943948817408L, 3959596233157434880L, 3544212893101320192L, 3161139128795137536L,
/* [ 24] */ 2806656884941820416L, 2477605671376185344L, 2171281018524273664L, 1885354452557434880L,
/* [ 28] */ 1617809833614047744L, 1366892269237658112L, 1131066787615028736L, 908984654997058560L,
/* [ 32] */ 699455731348318720L, 501425633583915520L, 313956755007992832L, 136212399366961152L,
/* [ 36] */ -32556553021349888L, -193022908001625600L, -345792716399554560L, -491413423379838464L,
/* [ 40] */ -630380845888988672L, -763145170929260544L, -890116131912690176L, -1011667492054083072L,
/* [ 44] */ -1128140941080192000L, -1239849493252469760L, -1347080459893031424L, -1450098057542626304L,
/* [ 48] */ -1549145703018891776L, -1644448038535791104L, -1736212723361025536L, -1824632022940825600L,
/* [ 52] */ -1909884221816344064L, -1992134882804800512L, -2071537971688286208L, -2148236863947458560L,
/* [ 56] */ -2222365247780633088L, -2294047935714820096L, -2363401595468253696L, -2430535409323403776L,
/* [ 60] */ -2495551670069566976L, -2558546320552583680L, -2619609442985608192L, -2678825703417424896L,
/* [ 64] */ -2736274756101145600L, -2792031611938902016L, -2846166974686572544L, -2898747548177031680L,
/* [ 68] */ -2949836317447342592L, -2999492806329770496L, -3047773313785532928L, -3094731131006235648L,
/* [ 72] */ -3140416741094473728L, -3184878002938374144L, -3228160320727380992L, -3270306800406949376L,
/* [ 76] */ -3311358394234071552L, -3351354034484032512L, -3390330757247591424L, -3428323817169865728L,
/* [ 80] */ -3465366793898720256L, -3501491690934902784L, -3536729027513080832L, -3571107924081618944L,
/* [ 84] */ -3604656181899062784L, -3637400357214628352L, -3669365830461451264L, -3700576870849548288L,
/* [ 88] */ -3731056696714091520L, -3760827531940795392L, -3789910658766305792L, -3818326467220366848L,
/* [ 92] */ -3846094501460680704L, -3873233503224223232L, -3899761452604410880L, -3925695606345008640L,
/* [ 96] */ -3951052533825223680L, -3975848150898364416L, -4000097751731727360L, -4023816038786208256L,
/* [100] */ -4047017151058499584L, -4069714690707166208L, -4091921748165281792L, -4113650925843118592L,
/* [104] */ -4134914360510158336L, -4155723744443228160L, -4176090345419594752L, -4196025025626374656L,
/* [108] */ -4215538259557954560L, -4234640150960326144L, -4253340448884000768L, -4271648562898405376L,
/* [112] */ -4289573577519592448L, -4307124265897231872L, -4324309102806436352L, -4341136276983992320L,
/* [116] */ -4357613702847894016L, -4373749031636836352L, -4389549662001094144L, -4405022750077366784L,
/* [120] */ -4420175219077067264L, -4435013768413905920L, -4449544882397231104L, -4463774838515782144L,
/* [124] */ -4477709715332459008L, -4491355400012626944L, -4504717595505328640L, -4517801827395838976L,
/* [128] */ -4530613450446389760L, -4543157654842793472L, -4555439472160934400L, -4567463781068195840L,
/* [132] */ -4579235312773997568L, -4590758656240654848L, -4602038263168300032L, -4613078452764409856L,
/* [136] */ -4623883416308989952L, -4634457221524290048L, -4644803816761235456L, -4654927035008246784L,
/* [140] */ -4664830597734270976L, -4674518118570737664L, -4683993106843208704L, -4693258970957511168L,
/* [144] */ -4702319021648195072L, -4711176475095642112L, -4719834455917983232L, -4728296000042890240L,
/* [148] */ -4736564057465815040L, -4744641494898972160L, -4752531098316131328L, -4760235575398025216L,
/* [152] */ -4767757557883156992L, -4775099603826595840L, -4782264199773566464L, -4789253762848160256L,
/* [156] */ -4796070642763833856L, -4802717123757088768L, -4809195426448159744L, -4815507709632380416L,
/* [160] */ -4821656072004040192L, -4827642553816744448L, -4833469138481454080L, -4839137754106220032L,
/* [164] */ -4844650274978936320L, -4850008522996425728L, -4855214269039884288L, -4860269234302464000L,
/* [168] */ -4865175091566906368L, -4869933466437730816L, -4874545938529117696L, -4879014042609741312L,
/* [172] */ -4883339269707099136L, -4887523068171446784L, -4891566844702813184L, -4895471965340231168L,
/* [176] */ -4899239756417071616L, -4902871505481196544L, -4906368462183164928L, -4909731839132712448L,
/* [180] */ -4912962812724644864L, -4916062523935916544L, -4919032079093866496L, -4921872550617327616L,
/* [184] */ -4924584977732045824L, -4927170367159303168L, -4929629693781258752L, -4931963901281752576L,
/* [188] */ -4934173902764700160L, -4936260581349647360L, -4938224790746291200L, -4940067355807971840L,
/* [192] */ -4941789073065357824L, -4943390711239933952L, -4944873011739753984L, -4946236689135308800L,
/* [196] */ -4947482431619080192L, -4948610901446864896L, -4949622735363246080L, -4950518545009749504L,
/* [200] */ -4951298917317924864L, -4951964414887600640L, -4952515576348487168L, -4952952916709260288L,
/* [204] */ -4953276927691216384L, -4953488078048885760L, -4953586813876376064L, -4953573558902138368L,
/* [208] */ -4953448714769485312L, -4953212661305179136L, -4952865756776645632L, -4952408338136501760L,
/* [212] */ -4951840721255068672L, -4951163201143173120L, -4950376052162316800L, -4949479528224847360L,
/* [216] */ -4948473862982736384L, -4947359270007034368L, -4946135942956237312L, -4944804055734229504L,
/* [220] */ -4943363762640024064L, -4941815198506020352L, -4940158478827333120L, -4938393699882143232L,
/* [224] */ -4936520938842464768L, -4934540253875459072L, -4932451684236201472L, -4930255250350992896L,
/* [228] */ -4927950953893274112L, -4925538777848453632L, -4923018686572188672L, -4920390625839525888L,
/* [232] */ -4917654522885157888L, -4914810286435288576L, -4911857806732278272L, -4908796955549192192L,
/* [236] */ -4905627586197715456L, -4902349533527011840L, -4898962613914057216L, -4895466625247106560L,
/* [240] */ -4891861346899963904L, -4888146539697684992L, -4884321945875628032L, -4880387289029549568L,
/* [244] */ -4876342274056310272L, -4872186587089345536L, -4867919895422610944L, -4863541847428798464L,
/* [248] */ -4859052072467801600L, -4854450180787865088L, -4849735763417182208L, -4844908392047856128L,
/* [252] */ -4839967618911950848L, -4834912976647099392L, -4829743978155096576L, -4824460116451147776L,
/* [256] */ -4819060864504044544L, -4813545675067768320L, -4807913980504056832L, -4802165192594749952L,
/* [260] */ -4796298702346892288L, -4790313879785735168L, -4784210073740736512L, -4777986611619728896L,
/* [264] */ -4771642799174403072L, -4765177920255393792L, -4758591236556836352L, -4751881987350666752L,
/* [268] */ -4745049389210733568L, -4738092635724898304L, -4731010897197732864L, -4723803320339894784L,
/* [272] */ -4716469027948174336L, -4709007118571786240L, -4701416666168034304L, -4693696719744952320L,
/* [276] */ -4685846302991571968L, -4677864413895422464L, -4669750024346546688L, -4661502079728433664L,
/* [280] */ -4653119498494611968L, -4644601171731585024L, -4635945962706888192L, -4627152706402486784L,
/* [284] */ -4618220209032402944L, -4609147247545243136L, -4599932569110216704L, -4590574890586744832L,
/* [288] */ -4581072897977050112L, -4571425245860782592L, -4561630556812469760L, -4551687420800102912L,
/* [292] */ -4541594394564215808L, -4531350000978089984L, -4520952728387175936L, -4510401029928645120L,
/* [296] */ -4499693322828163584L, -4488827987675754496L, -4477803367678713856L, -4466617767890585600L,
/* [300] */ -4455269454416637440L, -4443756653594040832L, -4432077551146284544L, -4420230291311382528L,
/* [304] */ -4408212975942271488L, -4396023663579625472L, -4383660368494419456L, -4371121059701586432L,
/* [308] */ -4358403659940780544L, -4345506044627643904L, -4332426040768207872L, -4319161425842345472L,
/* [312] */ -4305709926649207296L, -4292069218116598784L, -4278236922073029120L, -4264210605978586624L,
/* [316] */ -4249987781616803840L, -4235565903742823424L, -4220942368688843264L, -4206114512923164672L,
/* [320] */ -4191079611563289088L, -4175834876839676928L, -4160377456508627456L, -4144704432214183936L,
/* [324] */ -4128812817794444800L, -4112699557531435520L, -4096361524344448000L, -4079795517919899648L,
/* [328] */ -4062998262780994048L, -4045966406289958912L, -4028696516583542784L, -4011185080437596160L,
/* [332] */ -3993428501058901504L, -3975423095799736320L, -3957165093794900480L, -3938650633514732032L,
/* [336] */ -3919875760234452992L, -3900836423412657152L, -3881528473978691584L, -3861947661522247168L,
/* [340] */ -3842089631384604160L, -3821949921642690048L, -3801523959987316736L, -3780807060485497856L,
/* [344] */ -3759794420226106880L, -3738481115842412032L, -3716862099905139200L, -3694932197183221248L,
/* [348] */ -3672686100763535872L, -3650118368025705472L, -3627223416464823808L, -3603995519354882048L,
/* [352] */ -3580428801247209472L, -3556517233294936064L, -3532254628397208576L, -3507634636153634816L,
/* [356] */ -3482650737621700608L, -3457296239866780160L, -3431564270296417792L, -3405447770767880704L,
/* [360] */ -3378939491458745856L, -3352031984490172416L, -3324717597289475072L, -3296988465680861184L,
/* [364] */ -3268836506691269120L, -3240253411056924672L, -3211230635415641088L, -3181759394171538432L,
/* [368] */ -3151830651013152256L, -3121435110069826048L, -3090563206687621632L, -3059205097804578816L,
/* [372] */ -3027350651907195904L, -2994989438544094720L, -2962110717375283712L, -2928703426733917184L,
/* [376] */ -2894756171672258048L, -2860257211467748352L, -2825194446557172224L, -2789555404872457216L,
/* [380] */ -2753327227540304896L, -2716496653917054464L, -2679050005916396544L, -2640973171596317184L,
/* [384] */ -2602251587958849024L, -2562870222922691584L, -2522813556418801152L, -2482065560560435712L,
/* [388] */ -2440609678833421312L, -2398428804250509824L, -2355505256407986688L, -2311820757381316608L,
/* [392] */ -2267356406388873216L, -2222092653150109696L, -2176009269860336640L, -2129085321695611904L,
/* [396] */ -2081299135757883392L, -2032628268363105280L, -1983049470568565760L, -1932538651826487296L,
/* [400] */ -1881070841645808640L, -1828620149131529728L, -1775159720264906752L, -1720661692774047744L,
/* [404] */ -1665097148437127680L, -1608436062642298880L, -1550647251022831104L, -1491698312963664384L,
/* [408] */ -1431555571764694528L, -1370184011228092416L, -1307547208415545344L, -1243607262304812544L,
/* [412] */ -1178324718048254976L, -1111658486516102144L, -1043565758774211584L, -974001915124345856L,
/* [416] */ -902920428295306752L, -830272760342546432L, -756008252773183488L, -680074009369660928L,
/* [420] */ -602414771142033408L, -522972782779506176L, -441687649923274752L, -358496186511785984L,
/* [424] */ -273332251384862720L, -186126573250838016L, -96806563039876096L, -5296112566262784L,
/* [428] */ 88484621680143872L, 184619450912608768L, 283196404027497984L, 384307996761360384L,
/* [432] */ 488051521767595008L, 594529361535797760L, 703849326283634688L, 816125019179379200L,
/* [436] */ 931476231515671552L, 1050029370739642368L, 1171917924579436544L, 1297282964870890496L,
/* [440] */ 1426273695110094848L, 1559048046230309888L, 1695773325638197760L, 1836626925155011584L,
/* [444] */ 1981797094206053888L, 2131483785391109632L, 2285899580478475776L, 2445270705902480384L,
/* [448] */ 2609838148036959744L, 2779858879886981120L, 2955607212425994240L, 3137376285625809920L,
/* [452] */ 3325479716351016448L, 3520253422737882112L, 3722057647546029568L, 3931279206301515776L,
/* [456] */ 4148333989964127232L, 4373669756431084544L, 4607769250590803968L, 4851153699010013696L,
/* [460] */ 5104386732888089088L, 5368078801878179840L, 5642892152071508992L, 5929546454235676672L,
/* [464] */ 6228825183767088640L, 6541582872345928704L, 6868753373709051392L, 7211359313221728768L,
/* [468] */ 7570522924211155456L, 7947478514849258496L, 8343586859683210240L, 8760351872223335936L,
/* [472] */ 9199439992591985152L, 3921213358161086464L, 4850044974529517568L, 6296921656268977664L,
/* [476] */ 8292973759562619904L, 3075143244722959872L, 6274953360832545280L, 2210268915646535680L,
/* [480] */ 6778561557392493568L, 4052431235721115136L, 2017158148825034240L, 9030121550070927872L,
/* [484] */ 8695700292397356032L, 749256839723897344L, 2212185722591297024L, 4780810392134832640L,
/* [488] */ 8573064486620626432L, 4685427019526152192L, 2026848442171050496L, 795427058175291392L,
/* [492] */ 1220057396927800832L, 3568726050706383360L, 8159594562977490432L, 5249819115171273728L,
/* [496] */ 5086123243830243840L, 8282283418103647744L, 4836310890809390080L, 6126145310249794560L,
/* [500] */ 2267629071146367488L, 5974727006028887552L, 8264939763687273472L, 608340989510339584L,
/* [504] */ 828635949469412864L, 8856898102852928512L, 1720475810403128832L, 3683415679219046400L,
/* [508] */ -1284830592014387712L, -9223372036854775808L, -9223372036854775808L, -9223372036854775808L,
};
/**
* The precomputed ziggurat lengths, denoted X_i in the main text. X_i = length of
* ziggurat layer i. Values have been scaled by 2^-63.
*/
private static final double[] X = {
/* [ 0] */ 9.0661259763949181e-19, 8.263176964596684e-19, 7.7842821042069184e-19, 7.4401381372447472e-19,
/* [ 4] */ 7.1706345512475669e-19, 6.9487349626981025e-19, 6.7599059941438532e-19, 6.5954173866761093e-19,
/* [ 8] */ 6.4496076486975596e-19, 6.3185931723986094e-19, 6.1995926140436088e-19, 6.0905448556085982e-19,
/* [ 12] */ 5.9898795313195317e-19, 5.8963723366494962e-19, 5.8090500779440151e-19, 5.727126242519077e-19,
/* [ 16] */ 5.6499560161437446e-19, 5.5770040980809757e-19, 5.5078211755959678e-19, 5.4420264022055456e-19,
/* [ 20] */ 5.3792941286269432e-19, 5.319343704005985e-19, 5.2619315318369782e-19, 5.2068448072048437e-19,
/* [ 24] */ 5.1538965252883907e-19, 5.1029214632636893e-19, 5.0537729161623905e-19, 5.0063200229055628e-19,
/* [ 28] */ 4.9604455588176776e-19, 4.9160441001706848e-19, 4.8730204879053506e-19, 4.8312885338060169e-19,
/* [ 32] */ 4.7907699245760014e-19, 4.7513932885346785e-19, 4.7130933967875306e-19, 4.6758104762491562e-19,
/* [ 36] */ 4.6394896162201668e-19, 4.6040802536211077e-19, 4.5695357246842147e-19, 4.5358128730569534e-19,
/* [ 40] */ 4.5028717060006086e-19, 4.4706750917642919e-19, 4.4391884923497501e-19, 4.4083797268094136e-19,
/* [ 44] */ 4.3782187609810469e-19, 4.3486775201900267e-19, 4.3197297219702936e-19, 4.2913507262878116e-19,
/* [ 48] */ 4.263517401111986e-19, 4.2362080014839232e-19, 4.2094020604858992e-19, 4.1830802907323973e-19,
/* [ 52] */ 4.1572244951862374e-19, 4.1318174862592063e-19, 4.1068430122896932e-19, 4.0822856906037985e-19,
/* [ 56] */ 4.058130946464292e-19, 4.0343649572961074e-19, 4.0109746016499096e-19, 3.9879474124283382e-19,
/* [ 60] */ 3.9652715339543132e-19, 3.9429356825084459e-19, 3.920929110004198e-19, 3.8992415705058057e-19,
/* [ 64] */ 3.8778632893258511e-19, 3.8567849344673741e-19, 3.8359975902000546e-19, 3.8154927325817224e-19,
/* [ 68] */ 3.7952622067556671e-19, 3.7752982058712154e-19, 3.7555932514901226e-19, 3.7361401753547253e-19,
/* [ 72] */ 3.7169321024057316e-19, 3.6979624349481498e-19, 3.6792248378733595e-19, 3.6607132248538204e-19,
/* [ 76] */ 3.6424217454345153e-19, 3.6243447729520606e-19, 3.6064768932185395e-19, 3.5888128939126416e-19,
/* [ 80] */ 3.5713477546256509e-19, 3.5540766375143278e-19, 3.5369948785167605e-19, 3.5200979790909461e-19,
/* [ 84] */ 3.5033815984391743e-19, 3.4868415461842876e-19, 3.4704737754666438e-19, 3.4542743764330739e-19,
/* [ 88] */ 3.4382395700913942e-19, 3.4223657025060954e-19, 3.4066492393126986e-19, 3.3910867605299972e-19,
/* [ 92] */ 3.3756749556509512e-19, 3.3604106189944498e-19, 3.3452906453014644e-19, 3.3303120255603112e-19,
/* [ 96] */ 3.3154718430468554e-19, 3.300767269566494e-19, 3.2861955618856956e-19, 3.2717540583417136e-19,
/* [100] */ 3.2574401756198997e-19, 3.2432514056887605e-19, 3.2291853128835623e-19, 3.2152395311299247e-19,
/* [104] */ 3.2014117612994074e-19, 3.1876997686896117e-19, 3.1741013806218296e-19, 3.1606144841497054e-19,
/* [108] */ 3.1472370238728068e-19, 3.1339669998493811e-19, 3.1208024656029448e-19, 3.1077415262176789e-19,
/* [112] */ 3.0947823365179181e-19, 3.0819230993273112e-19, 3.0691620638035022e-19, 3.0564975238444241e-19,
/* [116] */ 3.0439278165625384e-19, 3.0314513208235683e-19, 3.0190664558464783e-19, 3.0067716798616362e-19,
/* [120] */ 2.9945654888242782e-19, 2.9824464151805648e-19, 2.97041302668365e-19, 2.9584639252573667e-19,
/* [124] */ 2.9465977459052242e-19, 2.9348131556625803e-19, 2.9231088525899381e-19, 2.9114835648054477e-19,
/* [128] */ 2.8999360495547921e-19, 2.888465092316728e-19, 2.8770695059426596e-19, 2.8657481298286891e-19,
/* [132] */ 2.8544998291186936e-19, 2.8433234939370269e-19, 2.8322180386495424e-19, 2.8211824011516853e-19,
/* [136] */ 2.8102155421824659e-19, 2.7993164446631984e-19, 2.788484113059931e-19, 2.7777175727685546e-19,
/* [140] */ 2.7670158695216292e-19, 2.7563780688160088e-19, 2.7458032553603932e-19, 2.7352905325419784e-19,
/* [144] */ 2.7248390219114179e-19, 2.7144478626853394e-19, 2.7041162112657045e-19, 2.6938432407753285e-19,
/* [148] */ 2.6836281406089111e-19, 2.6734701159989559e-19, 2.6633683875959909e-19, 2.6533221910625232e-19,
/* [152] */ 2.6433307766801955e-19, 2.6333934089696193e-19, 2.6235093663224118e-19, 2.6136779406449473e-19,
/* [156] */ 2.6038984370133962e-19, 2.5941701733396064e-19, 2.5844924800474283e-19, 2.5748646997590919e-19,
/* [160] */ 2.5652861869912541e-19, 2.5557563078603673e-19, 2.5462744397970219e-19, 2.5368399712689353e-19,
/* [164] */ 2.5274523015122715e-19, 2.5181108402709945e-19, 2.5088150075439651e-19, 2.4995642333395008e-19,
/* [168] */ 2.4903579574371396e-19, 2.4811956291563531e-19, 2.4720767071319582e-19, 2.4630006590960037e-19,
/* [172] */ 2.4539669616659003e-19, 2.4449751001385796e-19, 2.4360245682904773e-19, 2.4271148681831419e-19,
/* [176] */ 2.4182455099742769e-19, 2.4094160117340305e-19, 2.4006258992663645e-19, 2.3918747059353259e-19,
/* [180] */ 2.3831619724960594e-19, 2.3744872469304068e-19, 2.3658500842869427e-19, 2.3572500465252978e-19,
/* [184] */ 2.3486867023646363e-19, 2.3401596271361442e-19, 2.3316684026394113e-19, 2.3232126170025724e-19,
/* [188] */ 2.3147918645460906e-19, 2.3064057456500724e-19, 2.298053866624993e-19, 2.2897358395857378e-19,
/* [192] */ 2.2814512823288434e-19, 2.2731998182128476e-19, 2.2649810760416509e-19, 2.2567946899507905e-19,
/* [196] */ 2.2486402992965488e-19, 2.2405175485477971e-19, 2.2324260871805039e-19, 2.2243655695748146e-19,
/* [200] */ 2.2163356549146385e-19, 2.2083360070896563e-19, 2.2003662945996843e-19, 2.1924261904613178e-19,
/* [204] */ 2.1845153721167946e-19, 2.1766335213450081e-19, 2.1687803241746032e-19, 2.1609554707991062e-19,
/* [208] */ 2.153158655494016e-19, 2.145389576535809e-19, 2.1376479361227967e-19, 2.1299334402977885e-19,
/* [212] */ 2.1222457988725017e-19, 2.1145847253536737e-19, 2.1069499368708242e-19, 2.0993411541056253e-19,
/* [216] */ 2.0917581012228278e-19, 2.0842005058027066e-19, 2.076668098774977e-19, 2.0691606143541438e-19,
/* [220] */ 2.061677789976242e-19, 2.0542193662369327e-19, 2.0467850868309113e-19, 2.0393746984925989e-19,
/* [224] */ 2.0319879509380751e-19, 2.0246245968082214e-19, 2.0172843916130424e-19, 2.0099670936771298e-19,
/* [228] */ 2.0026724640862402e-19, 1.9954002666349563e-19, 1.9881502677754006e-19, 1.9809222365669745e-19,
/* [232] */ 1.9737159446270942e-19, 1.966531166082896e-19, 1.9593676775238861e-19, 1.9522252579555087e-19,
/* [236] */ 1.9451036887536058e-19, 1.9380027536197503e-19, 1.9309222385374197e-19, 1.9238619317289982e-19,
/* [240] */ 1.9168216236135756e-19, 1.9098011067655294e-19, 1.9028001758738615e-19, 1.8958186277022764e-19,
/* [244] */ 1.8888562610499751e-19, 1.8819128767131499e-19, 1.8749882774471561e-19, 1.8680822679293485e-19,
/* [248] */ 1.8611946547225595e-19, 1.8543252462392036e-19, 1.8474738527059914e-19, 1.8406402861292351e-19,
/* [252] */ 1.833824360260732e-19, 1.8270258905642057e-19, 1.8202446941822951e-19, 1.8134805899040715e-19,
/* [256] */ 1.8067333981330703e-19, 1.8000029408558255e-19, 1.7932890416108891e-19, 1.786591525458323e-19,
/* [260] */ 1.7799102189496529e-19, 1.7732449500982641e-19, 1.7665955483502355e-19, 1.7599618445555899e-19,
/* [264] */ 1.7533436709399558e-19, 1.7467408610766236e-19, 1.7401532498589862e-19, 1.7335806734733532e-19,
/* [268] */ 1.7270229693721261e-19, 1.7204799762473213e-19, 1.7139515340044364e-19, 1.7074374837366399e-19,
/* [272] */ 1.7009376676992816e-19, 1.694451929284709e-19, 1.6879801129973803e-19, 1.6815220644292632e-19,
/* [276] */ 1.6750776302355125e-19, 1.6686466581104123e-19, 1.6622289967635762e-19, 1.655824495896394e-19,
/* [280] */ 1.6494330061787188e-19, 1.64305437922578e-19, 1.6366884675753161e-19, 1.6303351246649206e-19,
/* [284] */ 1.6239942048095857e-19, 1.6176655631794399e-19, 1.6113490557776692e-19, 1.6050445394186123e-19,
/* [288] */ 1.598751871706023e-19, 1.5924709110114872e-19, 1.5862015164529922e-19, 1.5799435478736328e-19,
/* [292] */ 1.5736968658204502e-19, 1.5674613315233954e-19, 1.5612368068744041e-19, 1.55502315440658e-19,
/* [296] */ 1.5488202372734756e-19, 1.5426279192284608e-19, 1.536446064604174e-19, 1.5302745382920442e-19,
/* [300] */ 1.5241132057218782e-19, 1.5179619328415014e-19, 1.5118205860964477e-19, 1.5056890324096861e-19,
/* [304] */ 1.4995671391613777e-19, 1.4934547741686533e-19, 1.4873518056654034e-19, 1.4812581022820734e-19,
/* [308] */ 1.4751735330254499e-19, 1.4690979672584366e-19, 1.4630312746798053e-19, 1.456973325303913e-19,
/* [312] */ 1.4509239894403808e-19, 1.4448831376737181e-19, 1.438850640842889e-19, 1.4328263700208072e-19,
/* [316] */ 1.4268101964937506e-19, 1.4208019917406874e-19, 1.4148016274125018e-19, 1.4088089753111074e-19,
/* [320] */ 1.4028239073684423e-19, 1.396846295625332e-19, 1.3908760122102091e-19, 1.3849129293176794e-19,
/* [324] */ 1.3789569191869245e-19, 1.3730078540799268e-19, 1.3670656062595043e-19, 1.3611300479671491e-19,
/* [328] */ 1.3552010514006475e-19, 1.3492784886914775e-19, 1.3433622318819671e-19, 1.3374521529021971e-19,
/* [332] */ 1.3315481235466403e-19, 1.3256500154505191e-19, 1.3197577000658667e-19, 1.3138710486372786e-19,
/* [336] */ 1.3079899321773381e-19, 1.3021142214417001e-19, 1.2962437869038141e-19, 1.2903784987292747e-19,
/* [340] */ 1.2845182267497766e-19, 1.2786628404366604e-19, 1.2728122088740255e-19, 1.2669662007313963e-19,
/* [344] */ 1.2611246842359178e-19, 1.2552875271440607e-19, 1.2494545967128163e-19, 1.2436257596703557e-19,
/* [348] */ 1.2378008821861334e-19, 1.231979829840411e-19, 1.2261624675931726e-19, 1.2203486597524123e-19,
/* [352] */ 1.2145382699417624e-19, 1.2087311610674357e-19, 1.2029271952844551e-19, 1.1971262339621383e-19,
/* [356] */ 1.1913281376488073e-19, 1.1855327660356906e-19, 1.1797399779199848e-19, 1.1739496311670397e-19,
/* [360] */ 1.1681615826716313e-19, 1.1623756883182844e-19, 1.1565918029406041e-19, 1.1508097802795774e-19,
/* [364] */ 1.1450294729408e-19, 1.1392507323505832e-19, 1.1334734087108959e-19, 1.1276973509530898e-19,
/* [368] */ 1.1219224066903596e-19, 1.1161484221688824e-19, 1.1103752422175824e-19, 1.1046027101964606e-19,
/* [372] */ 1.0988306679434292e-19, 1.0930589557195864e-19, 1.0872874121528646e-19, 1.0815158741799823e-19,
/* [376] */ 1.0757441769866241e-19, 1.0699721539457744e-19, 1.0641996365541205e-19, 1.0584264543664434e-19,
/* [380] */ 1.0526524349279041e-19, 1.0468774037041343e-19, 1.0411011840090299e-19, 1.0353235969301472e-19,
/* [384] */ 1.0295444612515902e-19, 1.0237635933742761e-19, 1.0179808072334579e-19, 1.0121959142133761e-19,
/* [388] */ 1.0064087230589085e-19, 1.0006190397840746e-19, 9.9482666757724647e-20, 9.890314067029116e-20,
/* [392] */ 9.8323305439981917e-20, 9.7743140477533696e-20, 9.7162624869583486e-20, 9.6581737367289816e-20,
/* [396] */ 9.6000456374516673e-20, 9.5418759935558063e-20, 9.4836625722380091e-20, 9.4254031021356359e-20,
/* [400] */ 9.3670952719470503e-20, 9.3087367289958548e-20, 9.2503250777362024e-20, 9.1918578781960824e-20,
/* [404] */ 9.1333326443553021e-20, 9.074746842454686e-20, 9.0160978892327756e-20, 8.9573831500860881e-20,
/* [408] */ 8.8985999371487523e-20, 8.8397455072870296e-20, 8.7808170600039778e-20, 8.7218117352491731e-20,
/* [412] */ 8.6627266111280592e-20, 8.6035587015051616e-20, 8.5443049534949641e-20, 8.4849622448338465e-20,
/* [416] */ 8.4255273811260126e-20, 8.3659970929558324e-20, 8.3063680328584881e-20, 8.246636772140225e-20,
/* [420] */ 8.186799797538864e-20, 8.1268535077145628e-20, 8.0667942095600287e-20, 8.0066181143186217e-20,
/* [424] */ 7.9463213334978367e-20, 7.885899874564743e-20, 7.8253496364088652e-20, 7.7646664045568686e-20,
/* [428] */ 7.7038458461221292e-20, 7.642883504470902e-20, 7.5817747935853203e-20, 7.5205149921017434e-20,
/* [432] */ 7.4590992370012353e-20, 7.3975225169269108e-20, 7.335779665100703e-20, 7.2738653518097223e-20,
/* [436] */ 7.2117740764296587e-20, 7.1495001589498138e-20, 7.0870377309610182e-20, 7.0243807260641471e-20,
/* [440] */ 6.96152286965294e-20, 6.8984576680203705e-20, 6.8351783967329228e-20, 6.771678088211617e-20,
/* [444] */ 6.7079495184524855e-20, 6.6439851928123895e-20, 6.5797773307783692e-20, 6.5153178496301541e-20,
/* [448] */ 6.4505983468957815e-20, 6.3856100814894436e-20, 6.320343953408397e-20, 6.2547904818519893e-20,
/* [452] */ 6.1889397816101516e-20, 6.1227815375509665e-20, 6.056304977016756e-20, 5.9894988399150965e-20,
/* [456] */ 5.9223513462649234e-20, 5.8548501609278489e-20, 5.7869823552202679e-20, 5.7187343650622052e-20,
/* [460] */ 5.6500919452730109e-20, 5.5810401195711026e-20, 5.5115631257734864e-20, 5.4416443556192869e-20,
/* [464] */ 5.3712662885580816e-20, 5.3004104187460606e-20, 5.2290571743781936e-20, 5.1571858283490972e-20,
/* [468] */ 5.0847743990749481e-20, 5.0117995401181822e-20, 4.9382364170293304e-20, 4.8640585695477616e-20,
/* [472] */ 4.7892377569750159e-20, 4.7137437841375266e-20, 4.6375443048730777e-20, 4.5606045993857614e-20,
/* [476] */ 4.4828873210896671e-20, 4.4043522076659498e-20, 4.3249557499439262e-20, 4.2446508108220653e-20,
/* [480] */ 4.1633861846859842e-20, 4.0811060855462851e-20, 3.997749549257881e-20, 3.9132497314870153e-20,
/* [484] */ 3.8275330782752969e-20, 3.7405183397092119e-20, 3.6521153887674253e-20, 3.5622237960646127e-20,
/* [488] */ 3.4707310957388568e-20, 3.3775106563577917e-20, 3.2824190407548451e-20, 3.1852926960062177e-20,
/* [492] */ 3.0859437528023669e-20, 2.9841546217580957e-20, 2.8796709353961079e-20, 2.772192169113539e-20,
/* [496] */ 2.6613589304954131e-20, 2.5467353391178318e-20, 2.4277839478989958e-20, 2.3038289202859939e-20,
/* [500] */ 2.1739999061414015e-20, 2.037142499071807e-20, 1.8916669455626665e-20, 1.7352728004959384e-20,
/* [504] */ 1.5643946691546401e-20, 1.3729109753658277e-20, 1.1483304366567183e-20, 8.5324113192621202e-21,
/* [508] */ 0,
};
/** The precomputed ziggurat heights, denoted Y_i in the main text. Y_i = f(X_i).
* Values have been scaled by 2^-63. */
private static final double[] Y = {
/* [ 0] */ 2.5323797727138181e-23, 5.3108358239232209e-23, 8.26022457065042e-23, 1.1346037443474311e-22,
/* [ 4] */ 1.4547828564666417e-22, 1.7851865078182134e-22, 2.1248195450141036e-22, 2.4729229734018009e-22,
/* [ 8] */ 2.8288961626257085e-22, 3.1922503684288075e-22, 3.5625791217647975e-22, 3.9395384018258527e-22,
/* [ 12] */ 4.3228328223471963e-22, 4.7122056897421988e-22, 5.1074316514991609e-22, 5.5083111339357016e-22,
/* [ 16] */ 5.914666050219951e-22, 6.3263364315882896e-22, 6.7431777433800354e-22, 7.1650587182719069e-22,
/* [ 20] */ 7.5918595863879997e-22, 8.0234706143087472e-22, 8.4597908875883711e-22, 8.9007272874543527e-22,
/* [ 24] */ 9.3461936239794752e-22, 9.7961098965456997e-22, 1.0250401658767016e-21, 1.0708999469822909e-21,
/* [ 28] */ 1.117183841780181e-21, 1.1638857703464862e-21, 1.2110000275027631e-21, 1.2585212506274999e-21,
/* [ 32] */ 1.3064443911684845e-21, 1.3547646893321801e-21, 1.4034776515135506e-21, 1.4525790301004666e-21,
/* [ 36] */ 1.5020648053444311e-21, 1.5519311690365945e-21, 1.60217450976698e-21, 1.6527913995771288e-21,
/* [ 40] */ 1.7037785818432865e-21, 1.7551329602497868e-21, 1.8068515887312395e-21, 1.858931662278158e-21,
/* [ 44] */ 1.9113705085142316e-21, 1.9641655799650449e-21, 2.0173144469479217e-21, 2.0708147910210758e-21,
/* [ 48] */ 2.1246643989375575e-21, 2.1788611570557979e-21, 2.2334030461640281e-21, 2.2882881366806101e-21,
/* [ 52] */ 2.3435145841964528e-21, 2.3990806253293198e-21, 2.4549845738630073e-21, 2.5112248171471613e-21,
/* [ 56] */ 2.5677998127359586e-21, 2.6247080852460518e-21, 2.6819482234160959e-21, 2.7395188773518701e-21,
/* [ 60] */ 2.7974187559425357e-21, 2.8556466244349068e-21, 2.9142013021538138e-21, 2.9730816603577289e-21,
/* [ 64] */ 3.0322866202197593e-21, 3.0918151509250072e-21, 3.1516662678760491e-21, 3.2118390309989992e-21,
/* [ 68] */ 3.2723325431432467e-21, 3.3331459485685267e-21, 3.3942784315135004e-21, 3.4557292148404881e-21,
/* [ 72] */ 3.5174975587514197e-21, 3.579582759570448e-21, 3.6419841485890333e-21, 3.7047010909696115e-21,
/* [ 76] */ 3.7677329847042535e-21, 3.8310792596249961e-21, 3.8947393764627574e-21, 3.9587128259519763e-21,
/* [ 80] */ 4.0229991279783226e-21, 4.0875978307670022e-21, 4.152508510109364e-21, 4.2177307686256654e-21,
/* [ 84] */ 4.2832642350619977e-21, 4.3491085636195201e-21, 4.4152634333142514e-21, 4.4817285473658032e-21,
/* [ 88] */ 4.5485036326135354e-21, 4.6155884389587065e-21, 4.6829827388312992e-21, 4.7506863266802562e-21,
/* [ 92] */ 4.8186990184859766e-21, 4.8870206512939572e-21, 4.955651082768556e-21, 5.0245901907659065e-21,
/* [ 96] */ 5.0938378729250747e-21, 5.1633940462765908e-21, 5.2332586468675656e-21, 5.3034316294026107e-21,
/* [100] */ 5.3739129668998646e-21, 5.4447026503614276e-21, 5.5158006884575949e-21, 5.5872071072242535e-21,
/* [104] */ 5.6589219497729013e-21, 5.7309452760127363e-21, 5.8032771623843054e-21, 5.875917701604242e-21,
/* [108] */ 5.9488670024206328e-21, 6.0221251893785718e-21, 6.0956924025955166e-21, 6.1695687975460331e-21,
/* [112] */ 6.2437545448555828e-21, 6.3182498301029956e-21, 6.3930548536312928e-21, 6.4681698303665609e-21,
/* [116] */ 6.5435949896445654e-21, 6.61933057504483e-21, 6.6953768442319073e-21, 6.7717340688035926e-21,
/* [120] */ 6.8484025341458281e-21, 6.9253825392940775e-21, 7.0026743968009459e-21, 7.0802784326098346e-21,
/* [124] */ 7.1581949859344372e-21, 7.2364244091438833e-21, 7.3149670676533519e-21, 7.3938233398199853e-21,
/* [128] */ 7.472993616843931e-21, 7.5524783026743669e-21, 7.6322778139203621e-21, 7.7123925797664099e-21,
/* [132] */ 7.7928230418925412e-21, 7.8735696543988364e-21, 7.9546328837342629e-21, 8.0360132086296871e-21,
/* [136] */ 8.1177111200349716e-21, 8.1997271210600361e-21, 8.2820617269197917e-21, 8.3647154648828443e-21,
/* [140] */ 8.4476888742238858e-21, 8.5309825061796779e-21, 8.614596923908543e-21, 8.6985327024532865e-21,
/* [144] */ 8.7827904287074878e-21, 8.8673707013850592e-21, 8.9522741309930325e-21, 9.0375013398074916e-21,
/* [148] */ 9.1230529618525954e-21, 9.2089296428826335e-21, 9.2951320403670488e-21, 9.3816608234783977e-21,
/* [152] */ 9.4685166730831613e-21, 9.5557002817353942e-21, 9.6432123536731481e-21, 9.7310536048176277e-21,
/* [156] */ 9.8192247627750442e-21, 9.9077265668411266e-21, 9.9965597680082532e-21, 1.0085725128975164e-20,
/* [160] */ 1.0175223424159242e-20, 1.0265055439711297e-20, 1.0355221973532876e-20, 1.0445723835296011e-20,
/* [164] */ 1.0536561846465444e-20, 1.0627736840323247e-20, 1.0719249661995874e-20, 1.0811101168483563e-20,
/* [168] */ 1.0903292228692131e-20, 1.0995823723467109e-20, 1.1088696545630196e-20, 1.118191160001806e-20,
/* [172] */ 1.1275469803523424e-20, 1.1369372085138467e-20, 1.14636193860005e-20, 1.155821265943994e-20,
/* [176] */ 1.1653152871030541e-20, 1.1748440998641906e-20, 1.1844078032494261e-20, 1.1940064975215492e-20,
/* [180] */ 1.2036402841900448e-20, 1.2133092660172487e-20, 1.2230135470247318e-20, 1.2327532324999065e-20,
/* [184] */ 1.2425284290028643e-20, 1.2523392443734356e-20, 1.2621857877384821e-20, 1.2720681695194142e-20,
/* [188] */ 1.2819865014399386e-20, 1.2919408965340364e-20, 1.3019314691541709e-20, 1.311958334979729e-20,
/* [192] */ 1.3220216110256947e-20, 1.3321214156515581e-20, 1.342257868570459e-20, 1.35243109085857e-20,
/* [196] */ 1.3626412049647167e-20, 1.3728883347202408e-20, 1.3831726053491038e-20, 1.3934941434782369e-20,
/* [200] */ 1.403853077148138e-20, 1.4142495358237157e-20, 1.4246836504053859e-20, 1.4351555532404212e-20,
/* [204] */ 1.4456653781345581e-20, 1.4562132603638601e-20, 1.4667993366868439e-20, 1.4774237453568695e-20,
/* [208] */ 1.4880866261347982e-20, 1.4987881203019181e-20, 1.5095283706731464e-20, 1.5203075216105051e-20,
/* [212] */ 1.5311257190368801e-20, 1.5419831104500607e-20, 1.5528798449370678e-20, 1.5638160731887733e-20,
/* [216] */ 1.5747919475148132e-20, 1.5858076218588015e-20, 1.5968632518138439e-20, 1.607958994638363e-20,
/* [220] */ 1.6190950092722321e-20, 1.6302714563532247e-20, 1.6414884982337896e-20, 1.6527462989981453e-20,
/* [224] */ 1.6640450244797108e-20, 1.6753848422788681e-20, 1.6867659217810695e-20, 1.6981884341752875e-20,
/* [228] */ 1.7096525524728213e-20, 1.721158451526456e-20, 1.7327063080499912e-20, 1.7442963006381335e-20,
/* [232] */ 1.7559286097867713e-20, 1.7676034179136259e-20, 1.7793209093792969e-20, 1.7910812705086994e-20,
/* [236] */ 1.8028846896129066e-20, 1.8147313570114001e-20, 1.82662146505474e-20, 1.8385552081476575e-20,
/* [240] */ 1.8505327827725806e-20, 1.8625543875136006e-20, 1.8746202230808869e-20, 1.8867304923355594e-20,
/* [244] */ 1.8988854003150238e-20, 1.9110851542587859e-20, 1.9233299636347447e-20, 1.9356200401659812e-20,
/* [248] */ 1.9479555978580487e-20, 1.9603368530267746e-20, 1.9727640243265847e-20, 1.9852373327793618e-20,
/* [252] */ 1.9977570018038445e-20, 2.010323257245582e-20, 2.0229363274074546e-20, 2.0355964430807701e-20,
/* [256] */ 2.0483038375769486e-20, 2.0610587467598089e-20, 2.0738614090784689e-20, 2.0867120656008704e-20,
/* [260] */ 2.099610960047943e-20, 2.1125583388284243e-20, 2.1255544510743418e-20, 2.1385995486771794e-20,
/* [264] */ 2.1516938863247379e-20, 2.1648377215387072e-20, 2.1780313147129627e-20, 2.1912749291526057e-20,
/* [268] */ 2.2045688311137619e-20, 2.2179132898441537e-20, 2.2313085776244664e-20, 2.2447549698105236e-20,
/* [272] */ 2.2582527448762922e-20, 2.2718021844577323e-20, 2.2854035733975161e-20, 2.2990571997906318e-20,
/* [276] */ 2.3127633550308938e-20, 2.3265223338583805e-20, 2.3403344344078233e-20, 2.3541999582579633e-20,
/* [280] */ 2.3681192104819063e-20, 2.3820924996984908e-20, 2.396120138124703e-20, 2.4102024416291538e-20,
/* [284] */ 2.4243397297866505e-20, 2.4385323259338871e-20, 2.452780557226279e-20, 2.4670847546959731e-20,
/* [288] */ 2.4814452533110573e-20, 2.4958623920360058e-20, 2.5103365138933835e-20, 2.5248679660268454e-20,
/* [292] */ 2.539457099765463e-20, 2.5541042706894083e-20, 2.5688098386970325e-20, 2.583574168073375e-20,
/* [296] */ 2.5983976275601352e-20, 2.6132805904271501e-20, 2.6282234345454126e-20, 2.6432265424616709e-20,
/* [300] */ 2.6582903014746527e-20, 2.6734151037129546e-20, 2.6886013462146377e-20, 2.7038494310085842e-20,
/* [304] */ 2.7191597651976473e-20, 2.7345327610436566e-20, 2.7499688360543205e-20, 2.7654684130720776e-20,
/* [308] */ 2.7810319203649531e-20, 2.7966597917194705e-20, 2.8123524665356816e-20, 2.8281103899243675e-20,
/* [312] */ 2.8439340128064684e-20, 2.8598237920148148e-20, 2.8757801903982133e-20, 2.8918036769279628e-20,
/* [316] */ 2.9078947268068582e-20, 2.9240538215807684e-20, 2.9402814492528446e-20, 2.9565781044004507e-20,
/* [320] */ 2.9729442882948833e-20, 2.9893805090239645e-20, 3.005887281617601e-20, 3.0224651281763803e-20,
/* [324] */ 3.0391145780033081e-20, 3.0558361677387748e-20, 3.072630441498844e-20, 3.0894979510169736e-20,
/* [328] */ 3.1064392557892572e-20, 3.1234549232233119e-20, 3.1405455287909063e-20, 3.1577116561844568e-20,
/* [332] */ 3.1749538974775062e-20, 3.1922728532893043e-20, 3.2096691329536337e-20, 3.2271433546919926e-20,
/* [336] */ 3.2446961457912936e-20, 3.26232814278621e-20, 3.2800399916463208e-20, 3.2978323479682113e-20,
/* [340] */ 3.3157058771726903e-20, 3.3336612547072853e-20, 3.3516991662541965e-20, 3.3698203079438833e-20,
/* [344] */ 3.3880253865744772e-20, 3.4063151198372078e-20, 3.4246902365480509e-20, 3.4431514768858065e-20,
/* [348] */ 3.4616995926368224e-20, 3.4803353474466002e-20, 3.4990595170785116e-20, 3.517872889679876e-20,
/* [352] */ 3.5367762660556557e-20, 3.5557704599500393e-20, 3.5748562983361843e-20, 3.5940346217144218e-20,
/* [356] */ 3.6133062844192156e-20, 3.6326721549351945e-20, 3.6521331162225938e-20, 3.6716900660524377e-20,
/* [360] */ 3.6913439173518358e-20, 3.7110955985597548e-20, 3.7309460539936645e-20, 3.7508962442274668e-20,
/* [364] */ 3.7709471464811288e-20, 3.7910997550224699e-20, 3.8113550815815718e-20, 3.8317141557782911e-20,
/* [368] */ 3.8521780255633917e-20, 3.8727477576738257e-20, 3.8934244381027282e-20, 3.914209172584698e-20,
/* [372] */ 3.935103087096993e-20, 3.9561073283772659e-20, 3.977223064458528e-20, 3.9984514852220283e-20,
/* [376] */ 4.0197938029688092e-20, 4.0412512530106928e-20, 4.0628250942815264e-20, 4.0845166099695399e-20,
/* [380] */ 4.1063271081717031e-20, 4.1282579225710425e-20, 4.1503104131378944e-20, 4.1724859668561458e-20,
/* [384] */ 4.1947859984755547e-20, 4.2172119512913083e-20, 4.2397652979520307e-20, 4.2624475412975199e-20,
/* [388] */ 4.2852602152275669e-20, 4.3082048856032696e-20, 4.3312831511823486e-20, 4.35449664459004e-20,
/* [392] */ 4.3778470333272371e-20, 4.4013360208176433e-20, 4.4249653474957918e-20, 4.4487367919379097e-20,
/* [396] */ 4.4726521720376992e-20, 4.4967133462292346e-20, 4.5209222147593173e-20, 4.5452807210117408e-20,
/* [400] */ 4.5697908528860855e-20, 4.5944546442338236e-20, 4.6192741763546519e-20, 4.6442515795561947e-20,
/* [404] */ 4.6693890347803697e-20, 4.6946887752999492e-20, 4.7201530884890459e-20, 4.7457843176715081e-20,
/* [408] */ 4.7715848640514521e-20, 4.797557188730451e-20, 4.8237038148161644e-20, 4.8500273296275537e-20,
/* [412] */ 4.8765303870021277e-20, 4.903215709711068e-20, 4.930086091988455e-20, 4.957144402181263e-20,
/* [416] */ 4.9843935855272545e-20, 5.0118366670684009e-20, 5.0394767547080008e-20, 5.0673170424202713e-20,
/* [420] */ 5.0953608136218094e-20, 5.1236114447150163e-20, 5.1520724088143471e-20, 5.1807472796670477e-20,
/* [424] */ 5.2096397357809406e-20, 5.2387535647727967e-20, 5.2680926679518772e-20, 5.2976610651543945e-20,
/* [428] */ 5.3274628998459006e-20, 5.3575024445099889e-20, 5.387784106343208e-20, 5.4183124332777464e-20,
/* [432] */ 5.4490921203552541e-20, 5.4801280164771845e-20, 5.5114251315592008e-20, 5.5429886441196666e-20,
/* [436] */ 5.5748239093348294e-20, 5.6069364675963432e-20, 5.6393320536099437e-20, 5.672016606077763e-20,
/* [440] */ 5.7049962780107257e-20, 5.7382774477219359e-20, 5.7718667305568524e-20, 5.805770991421623e-20,
/* [444] */ 5.839997358176981e-20, 5.8745532359720356e-20, 5.9094463225999108e-20, 5.9446846249657746e-20,
/* [448] */ 5.9802764767674702e-20, 6.0162305574997887e-20, 6.0525559129056712e-20, 6.0892619770114342e-20,
/* [452] */ 6.1263585958987563e-20, 6.1638560533838738e-20, 6.2017650987946062e-20, 6.240096977058771e-20,
/* [456] */ 6.2788634613437286e-20, 6.3180768885168317e-20, 6.3577501977308952e-20, 6.3978969724784013e-20,
/* [460] */ 6.4385314865037979e-20, 6.4796687540159733e-20, 6.5213245847042516e-20, 6.5635156441324361e-20,
/* [464] */ 6.60625952016853e-20, 6.6495747962050781e-20, 6.6934811320393724e-20, 6.7379993534175763e-20,
/* [468] */ 6.7831515514062906e-20, 6.8289611929446599e-20, 6.8754532441561504e-20, 6.9226543082700484e-20,
/* [472] */ 6.9705927803286983e-20, 7.0192990212507397e-20, 7.0688055542996486e-20, 7.1191472875921819e-20,
/* [476] */ 7.1703617670003266e-20, 7.2224894646888467e-20, 7.2755741096353193e-20, 7.3296630678623713e-20,
/* [480] */ 7.3848077818549056e-20, 7.4410642808486694e-20, 7.4984937765101967e-20, 7.5571633621866871e-20,
/* [484] */ 7.6171468386713451e-20, 7.6785256957023811e-20, 7.741390286755859e-20, 7.8058412459147469e-20,
/* [488] */ 7.8719912108823151e-20, 7.9399669373134973e-20, 8.0099119192138521e-20, 8.081989672282774e-20,
/* [492] */ 8.1563878981695832e-20, 8.2333238379901939e-20, 8.3130512601664359e-20, 8.3958697396906725e-20,
/* [496] */ 8.4821372242318269e-20, 8.5722874400271225e-20, 8.6668546442438178e-20, 8.7665099347792271e-20,
/* [500] */ 8.8721165356564412e-20, 8.9848179006810222e-20, 9.1061863799122794e-20, 9.2384933810531728e-20,
/* [504] */ 9.3852522168647537e-20, 9.5524799137180048e-20, 9.7524125577254293e-20, 1.0021490936397442e-19,
/* [508] */ 1.0842021724855044e-19,
};
/** Underlying source of randomness. */
protected final UniformRandomProvider rng;
/**
* @param rng Generator of uniformly distributed random numbers.
*/
ModifiedZigguratExponentialSampler512(UniformRandomProvider rng) {
this.rng = rng;
}
/** {@inheritDoc} */
@Override
public double sample() {
return createSample();
}
/**
* Creates the exponential sample with {@code mean = 1}.
*
* <p>Note: This has been extracted to a separate method so that the recursive call
* when sampling tries again targets this function. This allows sub-classes
* to override the sample method to generate a sample with a different mean using:
* <pre>
* @Override
* public double sample() {
* return super.sample() * mean;
* }
* </pre>
* Otherwise the sub-class {@code sample()} method will recursively call
* the overloaded sample() method when trying again which creates a bad sample due
* to compound multiplication of the mean.
*
* @return the sample
*/
final double createSample() {
final long x = nextLong();
// Float multiplication squashes these last 9 bits, so they can be used to sample i
final int i = ((int) x) & 0x1ff;
if (i < I_MAX) {
// Early exit.
return X[i] * (x & MAX_INT64);
}
final int j = selectRegion();
return j == 0 ? X_0 + createSample() : sampleOverhang(j);
}
/**
* Select the overhang region or the tail using alias sampling.
*
* @return the region
*/
protected int selectRegion() {
final long x = nextLong();
// j in [0, 512)
final int j = ((int) x) & 0x1ff;
// map to j in [0, N] with N the number of layers of the ziggurat
return x >= IPMF[j] ? MAP[j] : j;
}
/**
* Sample from overhang region {@code j}.
*
* @param j Index j (must be {@code > 0})
* @return the sample
*/
protected double sampleOverhang(int j) {
// Sample from the triangle:
// X[j],Y[j]
// |\-->u1
// | \ |
// | \ |
// | \| Overhang j (with hypotenuse not pdf(x))
// | \
// | |\
// | | \
// | u2 \
// +-------- X[j-1],Y[j-1]
// u2 = u1 + (u2 - u1) = u1 + uDistance
// If u2 < u1 then reflect in the hypotenuse by swapping u1 and u2.
long u1 = randomInt63();
long uDistance = randomInt63() - u1;
if (uDistance < 0) {
uDistance = -uDistance;
u1 -= uDistance;
}
final double x = sampleX(X, j, u1);
if (uDistance >= E_MAX) {
// Early Exit: x < y - epsilon
return x;
}
return sampleY(Y, j, u1 + uDistance) <= Math.exp(-x) ? x : sampleOverhang(j);
}
/**
* Generates a {@code long}.
*
* @return the long
*/
protected long nextLong() {
return rng.nextLong();
}
/**
* Return a positive long in {@code [0, 2^63)}.
*
* @return the long
*/
protected long randomInt63() {
return rng.nextLong() & MAX_INT64;
}
}
/**
* Compute the x value of the point in the overhang region from the uniform deviate.
* <pre>{@code
* X[j],Y[j]
* |\ |
* | \|
* | \
* | |\ Ziggurat overhang j (with hypotenuse not pdf(x))
* | | \
* | u2 \
* | \
* |-->u1 \
* +-------- X[j-1],Y[j-1]
*
* x = X[j] + u1 * (X[j-1] - X[j])
* }</pre>
*
* @param x Ziggurat data table X. Values assumed to be scaled by 2^-63.
* @param j Index j. Value assumed to be above zero.
* @param u1 Uniform deviate. Value assumed to be in {@code [0, 2^63)}.
* @return y
*/
static double sampleX(double[] x, int j, long u1) {
return x[j] * TWO_POW_63 + u1 * (x[j - 1] - x[j]);
}
/**
* Compute the y value of the point in the overhang region from the uniform deviate.
* <pre>{@code
* X[j],Y[j]
* |\ |
* | \|
* | \
* | |\ Ziggurat overhang j (with hypotenuse not pdf(x))
* | | \
* | u2 \
* | \
* |-->u1 \
* +-------- X[j-1],Y[j-1]
*
* y = Y[j-1] + (1-u2) * (Y[j] - Y[j-1])
* }</pre>
*
* @param y Ziggurat data table Y. Values assumed to be scaled by 2^-63.
* @param j Index j. Value assumed to be above zero.
* @param u2 Uniform deviate. Value assumed to be in {@code [0, 2^63)}.
* @return y
*/
static double sampleY(double[] y, int j, long u2) {
// Note: u2 is in [0, 2^63)
// Long.MIN_VALUE is used as an unsigned int with value 2^63:
// 1 - u2 = Long.MIN_VALUE - u2
//
// The subtraction from 1 can be avoided with:
// y = Y[j] + u2 * (Y[j-1] - Y[j])
// This is effectively sampleX(y, j, u2)
// Tests show the alternative is 1 ULP different with approximately 3% frequency.
// It has not been measured more than 1 ULP different.
return y[j - 1] * TWO_POW_63 + (Long.MIN_VALUE - u2) * (y[j] - y[j - 1]);
}
/**
* Throw an illegal state exception for the unknown parameter.
*
* @param parameter Parameter name
*/
private static void throwIllegalStateException(String parameter) {
throw new IllegalStateException("Unknown: " + parameter);
}
/**
* Baseline for the JMH timing overhead for production of an {@code double} value.
*
* @return the {@code double} value
*/
@Benchmark
public double baseline() {
return value;
}
/**
* Benchmark methods for obtaining an index from the lower bits of a long.
*
* <p>Note: This is disabled as there is no measurable difference between methods.
*
* @param sources Source of randomness.
* @return the sample value
*/
//@Benchmark
public int getIndex(IndexSources sources) {
return sources.getSampler().sample();
}
/**
* Benchmark methods for obtaining an index from the lower bits of a long and
* comparing them to a limit then returning the index as an {@code int}.
*
* <p>Note: This is disabled as there is no measurable difference between methods.
*
* @param sources Source of randomness.
* @return the sample value
*/
//@Benchmark
public int compareIndex(IndexCompareSources sources) {
return sources.getSampler().sample();
}
/**
* Benchmark methods for obtaining an unsigned long.
*
* <p>Note: This is disabled. Either there is no measurable difference between methods
* or the bit shift method is marginally faster depending on JDK and platform.
*
* @param sources Source of randomness.
* @return the sample value
*/
//@Benchmark
public long getUnsignedLong(LongSources sources) {
return sources.getSampler().sample();
}
/**
* Benchmark methods for obtaining an interpolated value from an unsigned long.
*
* <p>Note: This is disabled. The speed is typically: U1, 1minusU2, U_1minusU.
*
* @param sources Source of randomness.
* @return the sample value
*/
//@Benchmark
public double interpolate(InterpolationSources sources) {
return sources.getSampler().sample();
}
/**
* Benchmark methods for obtaining a sign value from a long.
*
* <p>Note: This is disabled. The branchless versions using a subtraction of
* 2 - 1 or 0 - 1 are faster.
*
* @param sources Source of randomness.
* @return the sample value
*/
//@Benchmark
public double signBit(SignBitSources sources) {
return sources.getSampler().sample();
}
/**
* Benchmark methods for obtaining 2 random longs in ascending order.
*
* <p>Note: This is disabled. The branchless versions using a ternary
* conditional assignment are faster. This may not manifest as a performance
* improvement when used in the ziggurat sampler as it is not on the
* hot path (i.e. sampling inside the ziggurat).
*
* @param sources Source of randomness.
* @return the sample value
*/
//@Benchmark
public long[] diff(DiffSources sources) {
return sources.getSampler().sample();
}
/**
* Benchmark methods for obtaining {@code exp(z)} when {@code -8 <= z <= 0}.
*
* <p>Note: This is disabled. On JDK 8 FastMath is faster. On JDK 11 Math.exp is
* a hotspot intrinsic and may be faster based on the platform architecture.
* Example results:
*
* <pre>
* JDK 8 JDK 11
* i7-6820HQ E5-1680 i7-6820HQ E5-1680 3960X
* noop 4.523 3.871 4.351 4.206 3.936
* Math.exp 61.350 48.519 22.552 19.195 12.568
* FastMath.exp 33.858 24.469 31.396 24.568 11.159
* </pre>
*
* <p>The ziggurat sampler avoids calls to Math.exp in the majority of cases
* when using McFarland's fast method for overhangs which exploit the known
* maximum difference between pdf(x) and the triangle hypotenuse. Example data
* of the frequency that Math.exp is called per sample from the base
* implementations (using n=2^31):
*
* <pre>
* Calls FastOverhangs SimpleOverhangs
* Exp exp(-x) 0.00271 0.0307
* Normal exp(-0.5*x*x) 0.00359 0.0197*
*
* * Increases to 0.0198 if the tail exponential sampler uses simple overhangs
* </pre>
*
* <p>Note that the maximum difference between pdf(x) and the triangle
* hypotenuse is smaller for the exponential distribution; thus the fast method
* can avoid using Math.exp more often. In the case of simple overhangs the
* normal distribution has more region covered by the ziggurat thus has a lower
* frequency of overhang sampling.
*
* <p>A significant speed-up of the exp function may improve run-time of the
* simple overhangs method. Any effect on the fast method is less likely to be
* noticed. This is observed in benchmark times which show an improvement of the
* simple overhangs method for the exponential relative to other methods on JDK
* 11 vs 8. However the simple overhangs is still slower as the exponential
* distribution is always concave and upper-right triangle samples are avoided
* by the fast overhang method.
*
* @param sources Source of randomness.
* @return the sample value
*/
//@Benchmark
public double exp(ExpSources sources) {
return sources.getSampler().sample();
}
/**
* Run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public double sample(SingleSources sources) {
return sources.getSampler().sample();
}
/**
* Run the sampler to generate a number of samples sequentially.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public double sequentialSample(SequentialSources sources) {
return sources.getSampler().sample();
}
}
| 2,786 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/distribution/DiscreteUniformSamplerGenerationPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.distribution;
import org.apache.commons.rng.RestorableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.distribution.DiscreteUniformSampler;
import org.apache.commons.rng.sampling.distribution.SharedStateDiscreteSampler;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import java.util.concurrent.TimeUnit;
/**
* Executes benchmark to compare the speed of generation of integer numbers in a positive range
* using the {@link DiscreteUniformSampler} or {@link UniformRandomProvider#nextInt(int)}.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = { "-server", "-Xms128M", "-Xmx128M" })
public class DiscreteUniformSamplerGenerationPerformance {
/** The number of samples. */
@Param({
"1",
"2",
"4",
"8",
"16",
"1000000",
})
private int samples;
/**
* The benchmark state (retrieve the various "RandomSource"s).
*/
@State(Scope.Benchmark)
public static class Sources {
/**
* RNG providers.
*
* <p>Use different speeds.</p>
*
* @see <a href="https://commons.apache.org/proper/commons-rng/userguide/rng.html">
* Commons RNG user guide</a>
*/
@Param({"SPLIT_MIX_64",
// Comment in for slower generators
//"MWC_256", "KISS", "WELL_1024_A",
//"WELL_44497_B"
})
private String randomSourceName;
/** RNG. */
private RestorableUniformRandomProvider generator;
/**
* @return the RNG.
*/
public UniformRandomProvider getGenerator() {
return generator;
}
/** Instantiates generator. */
@Setup
public void setup() {
final RandomSource randomSource = RandomSource.valueOf(randomSourceName);
generator = randomSource.create();
}
}
/**
* The upper range for the {@code int} generation.
*/
@State(Scope.Benchmark)
public static class IntRange {
/**
* The upper range for the {@code int} generation.
*
* <p>Note that the while loop uses a rejection algorithm. From the Javadoc for java.util.Random:</p>
*
* <pre>
* "The probability of a value being rejected depends on n. The
* worst case is n=2^30+1, for which the probability of a reject is 1/2,
* and the expected number of iterations before the loop terminates is 2."
* </pre>
*/
@Param({
"256", // Even: 1 << 8
"257", // Prime number
"1073741825", // Worst case: (1 << 30) + 1
})
private int upperBound;
/**
* Gets the upper bound.
*
* @return the upper bound
*/
public int getUpperBound() {
return upperBound;
}
}
// Benchmark methods.
// Avoid consuming the generated values inside the loop. Use a sum and
// consume at the end. This reduces the run-time as the BlackHole has
// a relatively high overhead compared with number generation.
// Subtracting the baseline from the other timings provides a measure
// of the extra work done by the algorithm to produce unbiased samples in a range.
/**
* @param bh the data sink
* @param source the source
*/
@Benchmark
public void nextIntBaseline(Blackhole bh, Sources source) {
int sum = 0;
for (int i = 0; i < samples; i++) {
sum += source.getGenerator().nextInt();
}
bh.consume(sum);
}
/**
* @param bh the data sink
* @param source the source
* @param range the range
*/
@Benchmark
public void nextIntRange(Blackhole bh, Sources source, IntRange range) {
final int n = range.getUpperBound();
int sum = 0;
for (int i = 0; i < samples; i++) {
sum += source.getGenerator().nextInt(n);
}
bh.consume(sum);
}
/**
* @param bh the data sink
* @param source the source
* @param range the range
*/
@Benchmark
public void nextDiscreteUniformSampler(Blackhole bh, Sources source, IntRange range) {
// Note: The sampler upper bound is inclusive.
final SharedStateDiscreteSampler sampler = DiscreteUniformSampler.of(
source.getGenerator(), 0, range.getUpperBound() - 1);
int sum = 0;
for (int i = 0; i < samples; i++) {
sum += sampler.sample();
}
bh.consume(sum);
}
}
| 2,787 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/distribution/LevySamplersPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.distribution;
import org.apache.commons.math3.distribution.LevyDistribution;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.distribution.ContinuousInverseCumulativeProbabilityFunction;
import org.apache.commons.rng.sampling.distribution.ContinuousSampler;
import org.apache.commons.rng.sampling.distribution.InverseTransformContinuousSampler;
import org.apache.commons.rng.sampling.distribution.LevySampler;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
/**
* Executes a benchmark to compare the speed of generation of Levy distributed random numbers
* using different methods.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = {"-server", "-Xms128M", "-Xmx128M"})
public class LevySamplersPerformance {
/**
* The value.
*
* <p>This must NOT be final!</p>
*/
private double value;
/**
* The samplers's to use for testing. Defines the RandomSource and the type of Levy sampler.
*/
@State(Scope.Benchmark)
public static class Sources {
/**
* RNG providers.
*
* <p>Use different speeds.</p>
*
* @see <a href="https://commons.apache.org/proper/commons-rng/userguide/rng.html">
* Commons RNG user guide</a>
*/
@Param({"SPLIT_MIX_64",
"MWC_256",
"JDK"})
private String randomSourceName;
/**
* The sampler type.
*/
@Param({"LevySampler", "InverseTransformDiscreteSampler"})
private String samplerType;
/** The sampler. */
private ContinuousSampler sampler;
/**
* @return the sampler.
*/
public ContinuousSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Setup
public void setup() {
final RandomSource randomSource = RandomSource.valueOf(randomSourceName);
final UniformRandomProvider rng = randomSource.create();
final double location = 0.0;
final double scale = 1.0;
if ("LevySampler".equals(samplerType)) {
sampler = LevySampler.of(rng, location, scale);
} else {
final ContinuousInverseCumulativeProbabilityFunction levyFunction =
new ContinuousInverseCumulativeProbabilityFunction() {
/** Use CM for the inverse CDF. null is for the unused RNG. */
private final LevyDistribution dist = new LevyDistribution(null, location, scale);
@Override
public double inverseCumulativeProbability(double p) {
return dist.inverseCumulativeProbability(p);
}
};
sampler = InverseTransformContinuousSampler.of(rng, levyFunction);
}
}
}
/**
* Baseline for the JMH timing overhead for production of an {@code double} value.
*
* @return the {@code double} value
*/
@Benchmark
public double baseline() {
return value;
}
/**
* Run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public double sample(Sources sources) {
return sources.getSampler().sample();
}
}
| 2,788 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/distribution/DiscreteSamplersPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.distribution;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.examples.jmh.RandomSources;
import org.apache.commons.rng.sampling.distribution.AliasMethodDiscreteSampler;
import org.apache.commons.rng.sampling.distribution.DiscreteSampler;
import org.apache.commons.rng.sampling.distribution.DiscreteUniformSampler;
import org.apache.commons.rng.sampling.distribution.GeometricSampler;
import org.apache.commons.rng.sampling.distribution.GuideTableDiscreteSampler;
import org.apache.commons.rng.sampling.distribution.LargeMeanPoissonSampler;
import org.apache.commons.rng.sampling.distribution.MarsagliaTsangWangDiscreteSampler;
import org.apache.commons.rng.sampling.distribution.RejectionInversionZipfSampler;
import org.apache.commons.rng.sampling.distribution.SmallMeanPoissonSampler;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
/**
* Executes benchmark to compare the speed of generation of random numbers
* from the various source providers for different types of {@link DiscreteSampler}.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = {"-server", "-Xms128M", "-Xmx128M"})
public class DiscreteSamplersPerformance {
/**
* The value.
*
* <p>This must NOT be final!</p>
*/
private int value;
/**
* The {@link DiscreteSampler} samplers to use for testing. Creates the sampler for each
* {@link org.apache.commons.rng.simple.RandomSource RandomSource} in the default
* {@link RandomSources}.
*/
@State(Scope.Benchmark)
public static class Sources extends RandomSources {
/** The probabilities for the discrete distribution. */
private static final double[] DISCRETE_PROBABILITIES;
static {
// The size of this distribution will effect the relative performance
// of the AliasMethodDiscreteSampler against the other samplers. The
// Alias sampler is optimised for power of 2 tables and will zero pad
// the distribution. Pick a midpoint value between a power of 2 size to
// baseline half of a possible speed advantage.
final int size = (32 + 64) / 2;
DISCRETE_PROBABILITIES = new double[size];
for (int i = 0; i < size; i++) {
DISCRETE_PROBABILITIES[i] = (i + 1.0) / size;
}
}
/**
* The sampler type.
*/
@Param({"DiscreteUniformSampler",
"RejectionInversionZipfSampler",
"SmallMeanPoissonSampler",
"LargeMeanPoissonSampler",
"GeometricSampler",
"MarsagliaTsangWangDiscreteSampler",
"MarsagliaTsangWangPoissonSampler",
"MarsagliaTsangWangBinomialSampler",
"GuideTableDiscreteSampler",
"AliasMethodDiscreteSampler"})
private String samplerType;
/** The sampler. */
private DiscreteSampler sampler;
/**
* @return the sampler.
*/
public DiscreteSampler getSampler() {
return sampler;
}
/** Instantiates sampler. */
@Override
@Setup
public void setup() {
super.setup();
final UniformRandomProvider rng = getGenerator();
if ("DiscreteUniformSampler".equals(samplerType)) {
sampler = DiscreteUniformSampler.of(rng, -98, 76);
} else if ("RejectionInversionZipfSampler".equals(samplerType)) {
sampler = RejectionInversionZipfSampler.of(rng, 43, 2.1);
} else if ("SmallMeanPoissonSampler".equals(samplerType)) {
sampler = SmallMeanPoissonSampler.of(rng, 8.9);
} else if ("LargeMeanPoissonSampler".equals(samplerType)) {
// Note: Use with a fractional part to the mean includes a small mean sample
sampler = LargeMeanPoissonSampler.of(rng, 41.7);
} else if ("GeometricSampler".equals(samplerType)) {
sampler = GeometricSampler.of(rng, 0.21);
} else if ("MarsagliaTsangWangDiscreteSampler".equals(samplerType)) {
sampler = MarsagliaTsangWangDiscreteSampler.Enumerated.of(rng, DISCRETE_PROBABILITIES);
} else if ("MarsagliaTsangWangPoissonSampler".equals(samplerType)) {
sampler = MarsagliaTsangWangDiscreteSampler.Poisson.of(rng, 8.9);
} else if ("MarsagliaTsangWangBinomialSampler".equals(samplerType)) {
sampler = MarsagliaTsangWangDiscreteSampler.Binomial.of(rng, 20, 0.33);
} else if ("GuideTableDiscreteSampler".equals(samplerType)) {
sampler = GuideTableDiscreteSampler.of(rng, DISCRETE_PROBABILITIES);
} else if ("AliasMethodDiscreteSampler".equals(samplerType)) {
sampler = AliasMethodDiscreteSampler.of(rng, DISCRETE_PROBABILITIES);
}
}
}
// Benchmarks methods below.
/**
* Baseline for the JMH timing overhead for production of an {@code int} value.
*
* @return the {@code int} value
*/
@Benchmark
public int baseline() {
return value;
}
/**
* Run the sampler.
*
* @param sources Source of randomness.
* @return the sample value
*/
@Benchmark
public int sample(Sources sources) {
return sources.getSampler().sample();
}
}
| 2,789 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/distribution/PoissonSamplerCachePerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.sampling.distribution;
import java.util.concurrent.TimeUnit;
import java.util.function.DoubleFunction;
import org.apache.commons.rng.RandomProviderState;
import org.apache.commons.rng.RestorableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.PermutationSampler;
import org.apache.commons.rng.sampling.distribution.DiscreteSampler;
import org.apache.commons.rng.sampling.distribution.PoissonSampler;
import org.apache.commons.rng.sampling.distribution.PoissonSamplerCache;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
/**
* Executes benchmark to compare the speed of generation of Poisson random numbers when using a
* cache.
*
* <p>The benchmark is designed for a worse case scenario of Poisson means that are uniformly spread
* over a range and non-integer. A single sample is required per mean, E.g.</p>
*
* <pre>
* int min = 40;
* int max = 1000;
* int range = max - min;
* UniformRandomProvider rng = ...;
*
* // Compare ...
* for (int i = 0; i < 1000; i++) {
* PoissonSampler.of(rng, min + rng.nextDouble() * range).sample();
* }
*
* // To ...
* PoissonSamplerCache cache = new PoissonSamplerCache(min, max);
* for (int i = 0; i < 1000; i++) {
* PoissonSamplerCache.createPoissonSampler(rng, min + rng.nextDouble() * range).sample();
* }
* </pre>
*
* <p>The alternative scenario where the means are integer is not considered as this could be easily
* handled by creating an array to hold the PoissonSamplers for each mean. This does not require any
* specialised caching of state and is simple enough to perform for single threaded applications:</p>
*
* <pre>
* public class SimpleUnsafePoissonSamplerCache {
* int min = 50;
* int max = 100;
* PoissonSampler[] samplers = new PoissonSampler[max - min + 1];
*
* public PoissonSampler createPoissonSampler(UniformRandomProvider rng, int mean) {
* if (mean < min || mean > max) {
* return PoissonSampler.of(rng, mean);
* }
* int index = mean - min;
* PoissonSampler sample = samplers[index];
* if (sampler == null) {
* sampler = PoissonSampler.of(rng, mean);
* samplers[index] = sampler;
* }
* return sampler;
* }
* }
* </pre>
*
* <p>Note that in this example the UniformRandomProvider is also cached and so this is only
* applicable to a single threaded application. Thread safety could be ensured using the
* {@link org.apache.commons.rng.sampling.SharedStateSampler SharedStateSampler} functionality
* of the cached sampler.</p>
*
* <p>Re-written to use the PoissonSamplerCache would provide a new PoissonSampler per call in a
* thread-safe manner:
*
* <pre>
* public class SimplePoissonSamplerCache {
* int min = 50;
* int max = 100;
* PoissonSamplerCache samplers = new PoissonSamplerCache(min, max);
*
* public PoissonSampler createPoissonSampler(UniformRandomProvider rng, int mean) {
* return samplers.createPoissonSampler(rng, mean);
* }
* }
* </pre>
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = { "-server", "-Xms128M", "-Xmx128M" })
public class PoissonSamplerCachePerformance {
/** Number of samples per run. */
private static final int NUM_SAMPLES = 100_000;
/**
* Number of range samples.
*
* <p>Note: The LargeMeanPoissonSampler will not use a SmallMeanPoissonSampler
* if the mean is an integer. This will occur if the [range sample] * range is
* an integer.
*
* <p>If the SmallMeanPoissonSampler is not used then the cache has more
* advantage over the uncached version as relatively more time is spent in
* initialising the algorithm.
*
* <p>To avoid this use a prime number above the maximum range
* (currently 4096). Any number (n/RANGE_SAMPLES) * range will not be integer
* with {@code n < RANGE_SAMPLES} and {@code range < RANGE_SAMPLES} (unless n==0).
*/
private static final int RANGE_SAMPLE_SIZE = 4099;
/** The size of the seed. */
private static final int SEED_SIZE = 128;
/**
* Seed used to ensure the tests are the same. This can be different per
* benchmark, but should be the same within the benchmark.
*/
private static final int[] SEED;
/**
* The range sample. Should contain doubles in the range 0 inclusive to 1 exclusive.
*
* <p>The range sample is used to create a mean using:
* rangeMin + sample * (rangeMax - rangeMin).
*
* <p>Ideally this should be large enough to fully sample the
* range when expressed as discrete integers, i.e. no sparseness, and random.
*/
private static final double[] RANGE_SAMPLE;
static {
// Build a random seed for all the tests
SEED = new int[SEED_SIZE];
final UniformRandomProvider rng = RandomSource.MWC_256.create();
for (int i = 0; i < SEED.length; i++) {
SEED[i] = rng.nextInt();
}
final int size = RANGE_SAMPLE_SIZE;
final int[] sample = PermutationSampler.natural(size);
PermutationSampler.shuffle(rng, sample);
RANGE_SAMPLE = new double[size];
for (int i = 0; i < size; i++) {
// Note: This will have one occurrence of zero in the range.
// This will create at least one LargeMeanPoissonSampler that will
// not use a SmallMeanPoissonSampler. The different performance of this
// will be lost among the other samples.
RANGE_SAMPLE[i] = (double) sample[i] / size;
}
}
/**
* The benchmark state (retrieve the various "RandomSource"s).
*/
@State(Scope.Benchmark)
public static class Sources {
/**
* RNG providers.
*
* <p>Use different speeds.</p>
*
* @see <a href="https://commons.apache.org/proper/commons-rng/userguide/rng.html">
* Commons RNG user guide</a>
*/
@Param({ "SPLIT_MIX_64",
// Comment in for slower generators
//"MWC_256", "KISS", "WELL_1024_A", "WELL_44497_B"
})
private String randomSourceName;
/** RNG. */
private RestorableUniformRandomProvider generator;
/**
* The state of the generator at the start of the test (for reproducible
* results).
*/
private RandomProviderState state;
/**
* @return the RNG.
*/
public UniformRandomProvider getGenerator() {
generator.restoreState(state);
return generator;
}
/** Instantiates generator. */
@Setup
public void setup() {
final RandomSource randomSource = RandomSource
.valueOf(randomSourceName);
// Use the same seed
generator = randomSource.create(SEED.clone());
state = generator.saveState();
}
}
/**
* The range of mean values for testing the cache.
*/
@State(Scope.Benchmark)
public static class MeanRange {
/**
* Test range.
*
* <p>The covers the best case scenario of caching everything (range=1) and upwards
* in powers of 4.
*/
@Param({ "1", "4", "16", "64", "256", "1024", "4096"})
private double range;
/**
* Gets the mean.
*
* @param i the index
* @return the mean
*/
public double getMean(int i) {
return getMin() + RANGE_SAMPLE[i % RANGE_SAMPLE.length] * range;
}
/**
* Gets the min of the range.
*
* @return the min
*/
public double getMin() {
return PoissonSamplerCache.getMinimumCachedMean();
}
/**
* Gets the max of the range.
*
* @return the max
*/
public double getMax() {
return getMin() + range;
}
}
/**
* Exercises a poisson sampler created for a single use with a range of means.
*
* @param factory The factory.
* @param range The range of means.
* @param bh Data sink.
*/
private static void runSample(DoubleFunction<DiscreteSampler> factory,
MeanRange range,
Blackhole bh) {
for (int i = 0; i < NUM_SAMPLES; i++) {
bh.consume(factory.apply(range.getMean(i)).sample());
}
}
// Benchmarks methods below.
/**
* @param sources Source of randomness.
* @param range The range.
* @param bh Data sink.
*/
@Benchmark
public void runPoissonSampler(Sources sources,
MeanRange range,
Blackhole bh) {
final UniformRandomProvider r = sources.getGenerator();
final DoubleFunction<DiscreteSampler> factory = mean -> PoissonSampler.of(r, mean);
runSample(factory, range, bh);
}
/**
* @param sources Source of randomness.
* @param range The range.
* @param bh Data sink.
*/
@Benchmark
public void runPoissonSamplerCacheWhenEmpty(Sources sources,
MeanRange range,
Blackhole bh) {
final UniformRandomProvider r = sources.getGenerator();
final PoissonSamplerCache cache = new PoissonSamplerCache(0, 0);
final DoubleFunction<DiscreteSampler> factory = mean -> cache.createSharedStateSampler(r, mean);
runSample(factory, range, bh);
}
/**
* @param sources Source of randomness.
* @param range The range.
* @param bh Data sink.
*/
@Benchmark
public void runPoissonSamplerCache(Sources sources,
MeanRange range,
Blackhole bh) {
final UniformRandomProvider r = sources.getGenerator();
final PoissonSamplerCache cache = new PoissonSamplerCache(
range.getMin(), range.getMax());
final DoubleFunction<DiscreteSampler> factory = mean -> cache.createSharedStateSampler(r, mean);
runSample(factory, range, bh);
}
}
| 2,790 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/sampling/distribution/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Benchmarks for the {@code org.apache.commons.rng.sampling.distribution} components.
*/
package org.apache.commons.rng.examples.jmh.sampling.distribution;
| 2,791 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/simple/SeedGenerationPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.simple;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.source64.SplitMix64;
import org.apache.commons.rng.simple.RandomSource;
import org.apache.commons.rng.simple.internal.SeedFactory;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Executes a benchmark to compare the speed of generating a single {@code int/long} value
* in a thread-safe way.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = {"-server", "-Xms512M", "-Xmx512M"})
public class SeedGenerationPerformance {
/**
* The increment of the seed per new instance.
* This is copied from ThreadLocalRandom.
*/
static final long SEED_INCREMENT = 0xbb67ae8584caa73bL;
/**
* The lock to own when using the generator. This lock is unfair and there is no
* particular access order for waiting threads.
*
* <p>This is used as an alternative to {@code synchronized} statements.</p>
*/
private static final ReentrantLock UNFAIR_LOCK = new ReentrantLock(false);
/**
* The lock to own when using the generator. This lock is fair and the longest waiting
* thread will be favoured.
*
* <p>This is used as an alternative to {@code synchronized} statements.</p>
*/
private static final ReentrantLock FAIR_LOCK = new ReentrantLock(true);
/**
* A representation of the golden ratio converted to a long:
* 2^64 * phi where phi = (sqrt(5) - 1) / 2.
*/
private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L;
/** The int value. Must NOT be final to prevent JVM optimisation! */
private int intValue;
/** The long value. Must NOT be final to prevent JVM optimisation! */
private long longValue;
/** The int value to use for 'randomness'. */
private volatile int volatileIntValue;
/** The long value to use for 'randomness'. */
private volatile long volatileLongValue;
/** The Atomic integer to use for 'randomness'. */
private final AtomicInteger atomicInt = new AtomicInteger();
/** The Atomic long to use for 'randomness'. */
private final AtomicLong atomicLong = new AtomicLong();
/** The state of the SplitMix generator. */
private final AtomicLong state = new AtomicLong();
/** The XoRoShiRo128Plus RNG. */
private final UniformRandomProvider xoRoShiRo128Plus = RandomSource.XO_RO_SHI_RO_128_PLUS.create();
/** The XorShift1024StarPhi RNG. */
private final UniformRandomProvider xorShift1024StarPhi = RandomSource.XOR_SHIFT_1024_S_PHI.create();
/** The Well44497b RNG. */
private final UniformRandomProvider well44497b = RandomSource.WELL_44497_B.create();
/** The JDK Random instance (the implementation is thread-safe). */
private final Random random = new Random();
/**
* Extend the {@link ThreadLocal} to allow creation of a local generator.
*/
private static final class ThreadLocalRNG extends ThreadLocal<UniformRandomProvider> {
/**
* The seed for constructors.
*/
private static final AtomicLong SEED = new AtomicLong(0);
/** Instance. */
private static final ThreadLocalRNG INSTANCE = new ThreadLocalRNG();
/** No public construction. */
private ThreadLocalRNG() {
// Do nothing. The seed could be initialized here.
}
@Override
protected UniformRandomProvider initialValue() {
return new SplitMix64(SEED.getAndAdd(SEED_INCREMENT));
}
/**
* Get the current thread's RNG.
*
* @return the uniform random provider
*/
public static UniformRandomProvider current() {
return INSTANCE.get();
}
}
/**
* Extend the {@link ThreadLocal} to allow creation of a local generator.
*/
private static final class ThreadLocalSplitMix extends ThreadLocal<SplitMix64> {
/**
* The seed for constructors.
*/
private static final AtomicLong SEED = new AtomicLong(0);
/** Instance. */
private static final ThreadLocalSplitMix INSTANCE = new ThreadLocalSplitMix();
/** No public construction. */
private ThreadLocalSplitMix() {
// Do nothing. The seed could be initialized here.
}
@Override
protected SplitMix64 initialValue() {
return new SplitMix64(SEED.getAndAdd(SEED_INCREMENT));
}
/**
* Get the current thread's RNG.
*
* @return the uniform random provider
*/
public static SplitMix64 current() {
return INSTANCE.get();
}
}
/**
* Extend the {@link ThreadLocal} to allow creation of a local sequence.
*/
private static final class ThreadLocalSequence extends ThreadLocal<long[]> {
/**
* The seed for constructors.
*/
private static final AtomicLong SEED = new AtomicLong(0);
/** Instance. */
private static final ThreadLocalSequence INSTANCE = new ThreadLocalSequence();
/** No public construction. */
private ThreadLocalSequence() {
// Do nothing. The seed could be initialized here.
}
@Override
protected long[] initialValue() {
return new long[] {SEED.getAndAdd(SEED_INCREMENT)};
}
/**
* Get the current thread's next sequence value.
*
* @return the next value
*/
public static long next() {
final long[] value = INSTANCE.get();
return value[0] += GOLDEN_GAMMA;
}
}
/**
* Get the next {@code int} from the RNG. This is synchronized on the generator.
*
* @param rng Random generator.
* @return the int
*/
private static int nextInt(UniformRandomProvider rng) {
synchronized (rng) {
return rng.nextInt();
}
}
/**
* Get the next {@code long} from the RNG. This is synchronized on the generator.
*
* @param rng Random generator.
* @return the long
*/
private static long nextLong(UniformRandomProvider rng) {
synchronized (rng) {
return rng.nextLong();
}
}
/**
* Get the next {@code int} from the RNG. The lock is used to guard access to the generator.
*
* @param lock Lock guarding access to the generator.
* @param rng Random generator.
* @return the int
*/
private static int nextInt(Lock lock, UniformRandomProvider rng) {
lock.lock();
try {
return rng.nextInt();
} finally {
lock.unlock();
}
}
/**
* Get the next {@code long} from the RNG. The lock is used to guard access to the generator.
*
* @param lock Lock guarding access to the generator.
* @param rng Random generator.
* @return the long
*/
private static long nextLong(Lock lock, UniformRandomProvider rng) {
lock.lock();
try {
return rng.nextLong();
} finally {
lock.unlock();
}
}
/**
* Perform the mixing step from the SplitMix algorithm. This is the Stafford variant
* 13 mix64 function.
*
* @param z the input value
* @return the output value
* @see <a
* href="http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html">Better
* Bit Mixing</a>
*/
private static long mixLong(long z) {
z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
return z ^ (z >>> 31);
}
/**
* Perform the 32-bit mixing step from the SplittableRandom algorithm. Note this is
* the 32 high bits of Stafford variant 4 mix64 function as int.
*
* @param z the input value
* @return the output value
* @see <a
* href="http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html">Better
* Bit Mixing</a>
*/
private static int mixInt(long z) {
z = (z ^ (z >>> 33)) * 0x62a9d9ed799705f5L;
return (int) (((z ^ (z >>> 28)) * 0xcb24d0a5c88c35b3L) >>> 32);
}
/**
* Baseline for a JMH method call with no return value.
*/
@Benchmark
public void baselineVoid() {
// Do nothing, this is a baseline
}
/**
* Baseline for a JMH method call returning an {@code int}.
*
* @return the value
*/
@Benchmark
public int baselineInt() {
return intValue;
}
/**
* Baseline for a JMH method call returning an {@code long}.
*
* @return the value
*/
@Benchmark
public long baselineLong() {
return longValue;
}
// The following methods use underscores to make parsing the results output easier.
// They are not documented as the names are self-documenting.
// CHECKSTYLE: stop MethodName
// CHECKSTYLE: stop JavadocMethod
// CHECKSTYLE: stop DesignForExtension
@Benchmark
public int XoRoShiRo128Plus_nextInt() {
return xoRoShiRo128Plus.nextInt();
}
@Benchmark
public int XorShift1024StarPhi_nextInt() {
return xorShift1024StarPhi.nextInt();
}
@Benchmark
public int Well44497b_nextInt() {
return well44497b.nextInt();
}
@Benchmark
public long XoRoShiRo128Plus_nextLong() {
return xoRoShiRo128Plus.nextLong();
}
@Benchmark
public long XorShift1024StarPhi_nextLong() {
return xorShift1024StarPhi.nextLong();
}
@Benchmark
public long Well44497b_nextLong() {
return well44497b.nextLong();
}
@Benchmark
public int Threads1_SeedFactory_createInt() {
return SeedFactory.createInt();
}
@Benchmark
public long Threads1_SeedFactory_createLong() {
return SeedFactory.createLong();
}
@Benchmark
public long Threads1_System_currentTimeMillis() {
// This may not be unique per call and is not random.
return System.currentTimeMillis();
}
@Benchmark
public long Threads1_System_nanoTime() {
// This is not random.
return System.nanoTime();
}
@Benchmark
public int Threads1_System_identityHashCode() {
return System.identityHashCode(new Object());
}
@Benchmark
public long Threads1_ThreadLocalRandom_nextLong() {
return ThreadLocalRandom.current().nextLong();
}
@Benchmark
public int Threads1_ThreadLocalRandom_nextInt() {
return ThreadLocalRandom.current().nextInt();
}
@Benchmark
public long Threads1_ThreadLocalRNG_nextLong() {
return ThreadLocalRNG.current().nextLong();
}
@Benchmark
public int Threads1_ThreadLocalRNG_nextInt() {
return ThreadLocalRNG.current().nextInt();
}
@Benchmark
public long Threads1_ThreadLocalSplitMix_nextLong() {
return ThreadLocalSplitMix.current().nextLong();
}
@Benchmark
public int Threads1_ThreadLocalSplitMix_nextInt() {
return ThreadLocalSplitMix.current().nextInt();
}
@Benchmark
public long Threads1_ThreadLocalSequenceMix_nextLong() {
return mixLong(ThreadLocalSequence.next());
}
@Benchmark
public int Threads1_ThreadLocalSequenceMix_nextInt() {
return mixInt(ThreadLocalSequence.next());
}
@Benchmark
public long Threads1_Random_nextLong() {
return random.nextLong();
}
@Benchmark
public int Threads1_Random_nextInt() {
return random.nextInt();
}
@Benchmark
public long Threads1_SyncSplitMix_nextLong() {
return mixLong(state.getAndAdd(GOLDEN_GAMMA));
}
@Benchmark
public int Threads1_SyncSplitMix_nextInt() {
return mixInt(state.getAndAdd(GOLDEN_GAMMA));
}
@Benchmark
public int Threads1_Sync_XoRoShiRo128Plus_nextInt() {
return nextInt(xoRoShiRo128Plus);
}
@Benchmark
public int Threads1_Sync_XorShift1024StarPhi_nextInt() {
return nextInt(xorShift1024StarPhi);
}
@Benchmark
public int Threads1_Sync_Well44497b_nextInt() {
return nextInt(well44497b);
}
@Benchmark
public long Threads1_Sync_XoRoShiRo128Plus_nextLong() {
return nextLong(xoRoShiRo128Plus);
}
@Benchmark
public long Threads1_Sync_XorShift1024StarPhi_nextLong() {
return nextLong(xorShift1024StarPhi);
}
@Benchmark
public long Threads1_Sync_Well44497b_nextLong() {
return nextLong(well44497b);
}
@Benchmark
public int Threads1_UnfairLock_XoRoShiRo128Plus_nextInt() {
return nextInt(UNFAIR_LOCK, xoRoShiRo128Plus);
}
@Benchmark
public int Threads1_UnfairLock_XorShift1024StarPhi_nextInt() {
return nextInt(UNFAIR_LOCK, xorShift1024StarPhi);
}
@Benchmark
public int Threads1_UnfairLock_Well44497b_nextInt() {
return nextInt(UNFAIR_LOCK, well44497b);
}
@Benchmark
public long Threads1_UnfairLock_XoRoShiRo128Plus_nextLong() {
return nextLong(UNFAIR_LOCK, xoRoShiRo128Plus);
}
@Benchmark
public long Threads1_UnfairLock_XorShift1024StarPhi_nextLong() {
return nextLong(UNFAIR_LOCK, xorShift1024StarPhi);
}
@Benchmark
public long Threads1_UnfairLock_Well44497b_nextLong() {
return nextLong(UNFAIR_LOCK, well44497b);
}
@Benchmark
public int Threads1_FairLock_XoRoShiRo128Plus_nextInt() {
return nextInt(FAIR_LOCK, xoRoShiRo128Plus);
}
@Benchmark
public int Threads1_FairLock_XorShift1024StarPhi_nextInt() {
return nextInt(FAIR_LOCK, xorShift1024StarPhi);
}
@Benchmark
public int Threads1_FairLock_Well44497b_nextInt() {
return nextInt(FAIR_LOCK, well44497b);
}
@Benchmark
public long Threads1_FairLock_XoRoShiRo128Plus_nextLong() {
return nextLong(FAIR_LOCK, xoRoShiRo128Plus);
}
@Benchmark
public long Threads1_FairLock_XorShift1024StarPhi_nextLong() {
return nextLong(FAIR_LOCK, xorShift1024StarPhi);
}
@Benchmark
public long Threads1_FairLock_Well44497b_nextLong() {
return nextLong(FAIR_LOCK, well44497b);
}
@Benchmark
public int Threads1_volatileInt_increment() {
return ++volatileIntValue;
}
@Benchmark
public long Threads1_volatileLong_increment() {
return ++volatileLongValue;
}
@Benchmark
public int Threads1_AtomicInt_getAndIncrement() {
return atomicInt.getAndIncrement();
}
@Benchmark
public long Threads1_AtomicLong_getAndIncrement() {
return atomicLong.getAndIncrement();
}
@Benchmark
@Threads(4)
public int Threads4_SeedFactory_createInt() {
return SeedFactory.createInt();
}
@Benchmark
@Threads(4)
public long Threads4_SeedFactory_createLong() {
return SeedFactory.createLong();
}
@Benchmark
@Threads(4)
public long Threads4_System_currentTimeMillis() {
// This may not be unique per call and is not random.
return System.currentTimeMillis();
}
@Benchmark
@Threads(4)
public long Threads4_System_nanoTime() {
// This is not random.
return System.nanoTime();
}
@Benchmark
@Threads(4)
public int Threads4_System_identityHashCode() {
return System.identityHashCode(new Object());
}
@Benchmark
@Threads(4)
public long Threads4_ThreadLocalRandom_nextLong() {
return ThreadLocalRandom.current().nextLong();
}
@Benchmark
@Threads(4)
public int Threads4_ThreadLocalRandom_nextInt() {
return ThreadLocalRandom.current().nextInt();
}
@Benchmark
@Threads(4)
public long Threads4_ThreadLocalRNG_nextLong() {
return ThreadLocalRNG.current().nextLong();
}
@Benchmark
@Threads(4)
public int Threads4_ThreadLocalRNG_nextInt() {
return ThreadLocalRNG.current().nextInt();
}
@Benchmark
@Threads(4)
public long Threads4_ThreadLocalSplitMix_nextLong() {
return ThreadLocalSplitMix.current().nextLong();
}
@Benchmark
@Threads(4)
public int Threads4_ThreadLocalSplitMix_nextInt() {
return ThreadLocalSplitMix.current().nextInt();
}
@Benchmark
@Threads(4)
public long Threads4_ThreadLocalSequenceMix_nextLong() {
return mixLong(ThreadLocalSequence.next());
}
@Benchmark
@Threads(4)
public int Threads4_ThreadLocalSequenceMix_nextInt() {
return mixInt(ThreadLocalSequence.next());
}
@Benchmark
@Threads(4)
public long Threads4_Random_nextLong() {
return random.nextLong();
}
@Benchmark
@Threads(4)
public int Threads4_Random_nextInt() {
return random.nextInt();
}
@Benchmark
@Threads(4)
public long Threads4_SyncSplitMix_nextLong() {
return mixLong(state.getAndAdd(GOLDEN_GAMMA));
}
@Benchmark
@Threads(4)
public int Threads4_SyncSplitMix_nextInt() {
return mixInt(state.getAndAdd(GOLDEN_GAMMA));
}
@Benchmark
@Threads(4)
public int Threads4_Sync_XoRoShiRo128Plus_nextInt() {
return nextInt(xoRoShiRo128Plus);
}
@Benchmark
@Threads(4)
public int Threads4_Sync_XorShift1024StarPhi_nextInt() {
return nextInt(xorShift1024StarPhi);
}
@Benchmark
@Threads(4)
public int Threads4_Sync_Well44497b_nextInt() {
return nextInt(well44497b);
}
@Benchmark
@Threads(4)
public long Threads4_Sync_XoRoShiRo128Plus_nextLong() {
return nextLong(xoRoShiRo128Plus);
}
@Benchmark
@Threads(4)
public long Threads4_Sync_XorShift1024StarPhi_nextLong() {
return nextLong(xorShift1024StarPhi);
}
@Benchmark
@Threads(4)
public long Threads4_Sync_Well44497b_nextLong() {
return nextLong(well44497b);
}
@Benchmark
@Threads(4)
public int Threads4_UnfairLock_XoRoShiRo128Plus_nextInt() {
return nextInt(UNFAIR_LOCK, xoRoShiRo128Plus);
}
@Benchmark
@Threads(4)
public int Threads4_UnfairLock_XorShift1024StarPhi_nextInt() {
return nextInt(UNFAIR_LOCK, xorShift1024StarPhi);
}
@Benchmark
@Threads(4)
public int Threads4_UnfairLock_Well44497b_nextInt() {
return nextInt(UNFAIR_LOCK, well44497b);
}
@Benchmark
@Threads(4)
public long Threads4_UnfairLock_XoRoShiRo128Plus_nextLong() {
return nextLong(UNFAIR_LOCK, xoRoShiRo128Plus);
}
@Benchmark
@Threads(4)
public long Threads4_UnfairLock_XorShift1024StarPhi_nextLong() {
return nextLong(UNFAIR_LOCK, xorShift1024StarPhi);
}
@Benchmark
@Threads(4)
public long Threads4_UnfairLock_Well44497b_nextLong() {
return nextLong(UNFAIR_LOCK, well44497b);
}
@Benchmark
@Threads(4)
public int Threads4_FairLock_XoRoShiRo128Plus_nextInt() {
return nextInt(FAIR_LOCK, xoRoShiRo128Plus);
}
@Benchmark
@Threads(4)
public int Threads4_FairLock_XorShift1024StarPhi_nextInt() {
return nextInt(FAIR_LOCK, xorShift1024StarPhi);
}
@Benchmark
@Threads(4)
public int Threads4_FairLock_Well44497b_nextInt() {
return nextInt(FAIR_LOCK, well44497b);
}
@Benchmark
@Threads(4)
public long Threads4_FairLock_XoRoShiRo128Plus_nextLong() {
return nextLong(FAIR_LOCK, xoRoShiRo128Plus);
}
@Benchmark
@Threads(4)
public long Threads4_FairLock_XorShift1024StarPhi_nextLong() {
return nextLong(FAIR_LOCK, xorShift1024StarPhi);
}
@Benchmark
@Threads(4)
public long Threads4_FairLock_Well44497b_nextLong() {
return nextLong(FAIR_LOCK, well44497b);
}
@Benchmark
@Threads(4)
public int Threads4_volatileInt_increment() {
return ++volatileIntValue;
}
@Benchmark
@Threads(4)
public long Threads4_volatileLong_increment() {
return ++volatileLongValue;
}
@Benchmark
@Threads(4)
public int Threads4_AtomicInt_getAndIncrement() {
return atomicInt.getAndIncrement();
}
@Benchmark
@Threads(4)
public long Threads4_AtomicLong_getAndIncrement() {
return atomicLong.getAndIncrement();
}
}
| 2,792 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/simple/ConstructionPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.simple;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.source32.ISAACRandom;
import org.apache.commons.rng.core.source32.JDKRandom;
import org.apache.commons.rng.core.source32.KISSRandom;
import org.apache.commons.rng.core.source32.MersenneTwister;
import org.apache.commons.rng.core.source32.MultiplyWithCarry256;
import org.apache.commons.rng.core.source32.Well1024a;
import org.apache.commons.rng.core.source32.Well19937a;
import org.apache.commons.rng.core.source32.Well19937c;
import org.apache.commons.rng.core.source32.Well44497a;
import org.apache.commons.rng.core.source32.Well44497b;
import org.apache.commons.rng.core.source32.Well512a;
import org.apache.commons.rng.core.source32.XoRoShiRo64Star;
import org.apache.commons.rng.core.source32.XoRoShiRo64StarStar;
import org.apache.commons.rng.core.source32.XoShiRo128Plus;
import org.apache.commons.rng.core.source32.XoShiRo128StarStar;
import org.apache.commons.rng.core.source64.MersenneTwister64;
import org.apache.commons.rng.core.source64.SplitMix64;
import org.apache.commons.rng.core.source64.TwoCmres;
import org.apache.commons.rng.core.source64.XoRoShiRo128Plus;
import org.apache.commons.rng.core.source64.XoRoShiRo128StarStar;
import org.apache.commons.rng.core.source64.XoShiRo256Plus;
import org.apache.commons.rng.core.source64.XoShiRo256StarStar;
import org.apache.commons.rng.core.source64.XoShiRo512Plus;
import org.apache.commons.rng.core.source64.XoShiRo512StarStar;
import org.apache.commons.rng.core.source64.XorShift1024Star;
import org.apache.commons.rng.core.source64.XorShift1024StarPhi;
import org.apache.commons.rng.core.util.NumberFactory;
import org.apache.commons.rng.examples.jmh.RandomSourceValues;
import org.apache.commons.rng.simple.RandomSource;
import org.apache.commons.rng.simple.internal.ProviderBuilder.RandomSourceInternal;
import org.apache.commons.rng.simple.internal.SeedFactory;
/**
* Executes a benchmark to compare the speed of construction of random number providers.
*
* <p>Note that random number providers are created and then used. Thus the construction time must
* be analysed together with the run time performance benchmark (see for example
* {@link org.apache.commons.rng.examples.jmh.core.NextLongGenerationPerformance
* NextIntGenerationPerformance} and
* {@link org.apache.commons.rng.examples.jmh.core.NextLongGenerationPerformance
* NextLongGenerationPerformance}).
*
* <pre>
* [Total time] = [Construction time] + [Run time]
* </pre>
*
* <p>Selection of a suitable random number provider based on construction speed should consider
* when the construction time is a large fraction of the run time. In the majority of cases the
* run time will be the largest component of the total time and the provider should be selected
* based on its other properties such as the period, statistical randomness and speed.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = { "-server", "-Xms512M", "-Xmx512M" })
public class ConstructionPerformance {
/** The number of different constructor seeds. */
private static final int SEEDS = 500;
/**
* The maximum seed array size. This is irrespective of data type just to ensure
* there is enough data in the random seeds. The value is for WELL_44497_A.
*/
private static final int MAX_SEED_SIZE = 1391;
/** The {@link Long} seeds. */
private static final Long[] LONG_SEEDS;
/** The {@link Integer} seeds. */
private static final Integer[] INTEGER_SEEDS;
/** The {@code long[]} seeds. */
private static final long[][] LONG_ARRAY_SEEDS;
/** The {@code int[]} seeds. */
private static final int[][] INT_ARRAY_SEEDS;
/** The {@code byte[]} seeds. */
private static final byte[][] BYTE_ARRAY_SEEDS;
/**
* The values. Must NOT be final to prevent JVM optimisation!
* This is used to test the speed of the BlackHole consuming an object.
*/
private Object[] values;
static {
LONG_SEEDS = new Long[SEEDS];
INTEGER_SEEDS = new Integer[SEEDS];
LONG_ARRAY_SEEDS = new long[SEEDS][];
INT_ARRAY_SEEDS = new int[SEEDS][];
BYTE_ARRAY_SEEDS = new byte[SEEDS][];
final UniformRandomProvider rng = RandomSource.XOR_SHIFT_1024_S_PHI.create();
for (int i = 0; i < SEEDS; i++) {
final long[] longArray = new long[MAX_SEED_SIZE];
final int[] intArray = new int[MAX_SEED_SIZE];
for (int j = 0; j < MAX_SEED_SIZE; j++) {
longArray[j] = rng.nextLong();
intArray[j] = (int) longArray[j];
}
LONG_SEEDS[i] = longArray[0];
INTEGER_SEEDS[i] = intArray[0];
LONG_ARRAY_SEEDS[i] = longArray;
INT_ARRAY_SEEDS[i] = intArray;
BYTE_ARRAY_SEEDS[i] = NumberFactory.makeByteArray(longArray);
}
}
/**
* Default constructor to initialize state.
*/
public ConstructionPerformance() {
values = new Object[SEEDS];
for (int i = 0; i < SEEDS; i++) {
values[i] = new Object();
}
}
/**
* The benchmark state (retrieve the various "RandomSource"s).
*/
@State(Scope.Benchmark)
public static class Sources extends RandomSourceValues {
/** The native seeds. */
private Object[] nativeSeeds;
/** The native seeds with arrays truncated to 1 element. */
private Object[] nativeSeeds1;
/** The {@code byte[]} seeds, truncated to the appropriate length for the native seed type. */
private byte[][] byteSeeds;
/** The implementing class for the random source. */
private Class<?> implementingClass;
/** The constructor. */
private Constructor<Object> constructor;
/**
* Gets the native seeds for the RandomSource.
*
* @return the native seeds
*/
public Object[] getNativeSeeds() {
return nativeSeeds;
}
/**
* Gets the native seeds for the RandomSource with arrays truncated to length 1.
*
* @return the native seeds
*/
public Object[] getNativeSeeds1() {
return nativeSeeds1;
}
/**
* Gets the native seeds for the RandomSource.
*
* @return the native seeds
*/
public byte[][] getByteSeeds() {
return byteSeeds;
}
/**
* Gets the implementing class.
*
* @return the implementing class
*/
public Class<?> getImplementingClass() {
return implementingClass;
}
/**
* Gets the constructor.
*
* @return the constructor
*/
public Constructor<Object> getConstructor() {
return constructor;
}
/**
* Create the random source and the test seeds.
*/
@Override
@SuppressWarnings("unchecked")
@Setup(Level.Trial)
public void setup() {
super.setup();
final RandomSource randomSource = getRandomSource();
nativeSeeds = findNativeSeeds(randomSource);
// Truncate array seeds to length 1
if (nativeSeeds[0].getClass().isArray()) {
nativeSeeds1 = new Object[SEEDS];
for (int i = 0; i < SEEDS; i++) {
nativeSeeds1[i] = copy(nativeSeeds[i], 1);
}
} else {
// N/A
nativeSeeds1 = nativeSeeds;
}
// Convert seeds to bytes
byteSeeds = new byte[SEEDS][];
final int byteSize = findNativeSeedLength(randomSource) *
findNativeSeedElementByteSize(randomSource);
for (int i = 0; i < SEEDS; i++) {
byteSeeds[i] = Arrays.copyOf(BYTE_ARRAY_SEEDS[i], byteSize);
}
// Cache the class type and constructor
implementingClass = getRandomSourceInternal(randomSource).getRng();
try {
constructor = (Constructor<Object>) implementingClass.getConstructor(nativeSeeds[0].getClass());
} catch (NoSuchMethodException ex) {
throw new IllegalStateException("Failed to find the constructor", ex);
}
}
/**
* Copy the specified length of the provided array object.
*
* @param object the object
* @param length the length
* @return the copy
*/
private static Object copy(Object object, int length) {
if (object instanceof int[]) {
return Arrays.copyOf((int[]) object, length);
}
if (object instanceof long[]) {
return Arrays.copyOf((long[]) object, length);
}
throw new AssertionError("Unknown seed array");
}
/**
* Find the native seeds for the RandomSource.
*
* @param randomSource the random source
* @return the native seeds
*/
private static Object[] findNativeSeeds(RandomSource randomSource) {
switch (randomSource) {
case TWO_CMRES:
case TWO_CMRES_SELECT:
return INTEGER_SEEDS;
case JDK:
case SPLIT_MIX_64:
return LONG_SEEDS;
case WELL_512_A:
case WELL_1024_A:
case WELL_19937_A:
case WELL_19937_C:
case WELL_44497_A:
case WELL_44497_B:
case MT:
case ISAAC:
case MWC_256:
case KISS:
case XO_RO_SHI_RO_64_S:
case XO_RO_SHI_RO_64_SS:
case XO_SHI_RO_128_PLUS:
case XO_SHI_RO_128_SS:
return INT_ARRAY_SEEDS;
case XOR_SHIFT_1024_S:
case XOR_SHIFT_1024_S_PHI:
case MT_64:
case XO_RO_SHI_RO_128_PLUS:
case XO_RO_SHI_RO_128_SS:
case XO_SHI_RO_256_PLUS:
case XO_SHI_RO_256_SS:
case XO_SHI_RO_512_PLUS:
case XO_SHI_RO_512_SS:
return LONG_ARRAY_SEEDS;
default:
throw new AssertionError("Unknown native seed");
}
}
/**
* Find the length of the native seed (number of elements).
*
* @param randomSource the random source
* @return the seed length
*/
private static int findNativeSeedLength(RandomSource randomSource) {
switch (randomSource) {
case JDK:
case SPLIT_MIX_64:
case TWO_CMRES:
case TWO_CMRES_SELECT:
return 1;
case WELL_512_A:
return 16;
case WELL_1024_A:
return 32;
case WELL_19937_A:
case WELL_19937_C:
return 624;
case WELL_44497_A:
case WELL_44497_B:
return 1391;
case MT:
return 624;
case ISAAC:
return 256;
case XOR_SHIFT_1024_S:
case XOR_SHIFT_1024_S_PHI:
return 16;
case MT_64:
return 312;
case MWC_256:
return 257;
case KISS:
return 4;
case XO_RO_SHI_RO_64_S:
case XO_RO_SHI_RO_64_SS:
return 2;
case XO_SHI_RO_128_PLUS:
case XO_SHI_RO_128_SS:
return 4;
case XO_RO_SHI_RO_128_PLUS:
case XO_RO_SHI_RO_128_SS:
return 2;
case XO_SHI_RO_256_PLUS:
case XO_SHI_RO_256_SS:
return 4;
case XO_SHI_RO_512_PLUS:
case XO_SHI_RO_512_SS:
return 8;
default:
throw new AssertionError("Unknown native seed size");
}
}
/**
* Find the byte size of a single element of the native seed.
*
* @param randomSource the random source
* @return the seed element byte size
*/
private static int findNativeSeedElementByteSize(RandomSource randomSource) {
switch (randomSource) {
case JDK:
case WELL_512_A:
case WELL_1024_A:
case WELL_19937_A:
case WELL_19937_C:
case WELL_44497_A:
case WELL_44497_B:
case MT:
case ISAAC:
case TWO_CMRES:
case TWO_CMRES_SELECT:
case MWC_256:
case KISS:
case XO_RO_SHI_RO_64_S:
case XO_RO_SHI_RO_64_SS:
case XO_SHI_RO_128_PLUS:
case XO_SHI_RO_128_SS:
return 4; // int
case SPLIT_MIX_64:
case XOR_SHIFT_1024_S:
case XOR_SHIFT_1024_S_PHI:
case MT_64:
case XO_RO_SHI_RO_128_PLUS:
case XO_RO_SHI_RO_128_SS:
case XO_SHI_RO_256_PLUS:
case XO_SHI_RO_256_SS:
case XO_SHI_RO_512_PLUS:
case XO_SHI_RO_512_SS:
return 8; // long
default:
throw new AssertionError("Unknown native seed element byte size");
}
}
/**
* Gets the random source internal.
*
* @param randomSource the random source
* @return the random source internal
*/
private static RandomSourceInternal getRandomSourceInternal(RandomSource randomSource) {
switch (randomSource) {
case JDK: return RandomSourceInternal.JDK;
case WELL_512_A: return RandomSourceInternal.WELL_512_A;
case WELL_1024_A: return RandomSourceInternal.WELL_1024_A;
case WELL_19937_A: return RandomSourceInternal.WELL_19937_A;
case WELL_19937_C: return RandomSourceInternal.WELL_19937_C;
case WELL_44497_A: return RandomSourceInternal.WELL_44497_A;
case WELL_44497_B: return RandomSourceInternal.WELL_44497_B;
case MT: return RandomSourceInternal.MT;
case ISAAC: return RandomSourceInternal.ISAAC;
case TWO_CMRES: return RandomSourceInternal.TWO_CMRES;
case TWO_CMRES_SELECT: return RandomSourceInternal.TWO_CMRES_SELECT;
case MWC_256: return RandomSourceInternal.MWC_256;
case KISS: return RandomSourceInternal.KISS;
case SPLIT_MIX_64: return RandomSourceInternal.SPLIT_MIX_64;
case XOR_SHIFT_1024_S: return RandomSourceInternal.XOR_SHIFT_1024_S;
case MT_64: return RandomSourceInternal.MT_64;
case XOR_SHIFT_1024_S_PHI: return RandomSourceInternal.XOR_SHIFT_1024_S_PHI;
case XO_RO_SHI_RO_64_S: return RandomSourceInternal.XO_RO_SHI_RO_64_S;
case XO_RO_SHI_RO_64_SS: return RandomSourceInternal.XO_RO_SHI_RO_64_SS;
case XO_SHI_RO_128_PLUS: return RandomSourceInternal.XO_SHI_RO_128_PLUS;
case XO_SHI_RO_128_SS: return RandomSourceInternal.XO_SHI_RO_128_SS;
case XO_RO_SHI_RO_128_PLUS: return RandomSourceInternal.XO_RO_SHI_RO_128_PLUS;
case XO_RO_SHI_RO_128_SS: return RandomSourceInternal.XO_RO_SHI_RO_128_SS;
case XO_SHI_RO_256_PLUS: return RandomSourceInternal.XO_SHI_RO_256_PLUS;
case XO_SHI_RO_256_SS: return RandomSourceInternal.XO_SHI_RO_256_SS;
case XO_SHI_RO_512_PLUS: return RandomSourceInternal.XO_SHI_RO_512_PLUS;
case XO_SHI_RO_512_SS: return RandomSourceInternal.XO_SHI_RO_512_SS;
default:
throw new AssertionError("Unknown random source internal");
}
}
}
/**
* The number of {@code int} values that are required to seed a generator.
*/
@State(Scope.Benchmark)
public static class IntSizes {
/** The number of values. */
@Param({"2",
"4",
"32",
"128", // Legacy limit on array size generation
"256",
"257",
"624",
"1391",
})
private int size;
/**
* Gets the number of {@code int} values required.
*
* @return the size
*/
public int getSize() {
return size;
}
}
/**
* The number of {@code long} values that are required to seed a generator.
*/
@State(Scope.Benchmark)
public static class LongSizes {
/** The number of values. */
@Param({"2",
"4",
"8",
"16",
"128", // Legacy limit on array size generation
"312",
})
private int size;
/**
* Gets the number of {@code long} values required.
*
* @return the size
*/
public int getSize() {
return size;
}
}
/**
* Baseline for JMH consuming a number of constructed objects.
* This shows the JMH timing overhead for all the construction benchmarks.
*
* @param bh Data sink.
*/
@Benchmark
public void baselineConsumeObject(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(values[i]);
}
}
/**
* Baseline for JMH consuming a number of new objects.
*
* @param bh Data sink.
*/
@Benchmark
public void newObject(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new Object());
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newJDKRandom(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new JDKRandom(LONG_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newWell512a(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new Well512a(INT_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newWell1024a(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new Well1024a(INT_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newWell19937a(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new Well19937a(INT_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newWell19937c(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new Well19937c(INT_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newWell44497a(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new Well44497a(INT_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newWell44497b(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new Well44497b(INT_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newMersenneTwister(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new MersenneTwister(INT_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newISAACRandom(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new ISAACRandom(INT_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newSplitMix64(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new SplitMix64(LONG_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newXorShift1024Star(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new XorShift1024Star(LONG_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newTwoCmres(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new TwoCmres(INTEGER_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newMersenneTwister64(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new MersenneTwister64(LONG_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newMultiplyWithCarry256(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new MultiplyWithCarry256(INT_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newKISSRandom(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new KISSRandom(INT_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newXorShift1024StarPhi(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new XorShift1024StarPhi(LONG_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newXoRoShiRo64Star(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new XoRoShiRo64Star(INT_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newXoRoShiRo64StarStar(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new XoRoShiRo64StarStar(INT_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newXoShiRo128Plus(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new XoShiRo128Plus(INT_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newXoShiRo128StarStar(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new XoShiRo128StarStar(INT_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newXoRoShiRo128Plus(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new XoRoShiRo128Plus(LONG_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newXoRoShiRo128StarStar(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new XoRoShiRo128StarStar(LONG_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newXoShiRo256Plus(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new XoShiRo256Plus(LONG_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newXoShiRo256StarStar(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new XoShiRo256StarStar(LONG_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newXoShiRo512Plus(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new XoShiRo512Plus(LONG_ARRAY_SEEDS[i]));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void newXoShiRo512StarStar(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(new XoShiRo512StarStar(LONG_ARRAY_SEEDS[i]));
}
}
/**
* Create a new instance using reflection with a cached constructor.
*
* @param sources Source of randomness.
* @param bh Data sink.
* @throws InvocationTargetException If reflection failed.
* @throws IllegalAccessException If reflection failed.
* @throws InstantiationException If reflection failed.
*/
@Benchmark
public void newInstance(Sources sources, Blackhole bh) throws InstantiationException,
IllegalAccessException, InvocationTargetException {
final Object[] nativeSeeds = sources.getNativeSeeds();
final Constructor<?> constructor = sources.getConstructor();
for (int i = 0; i < SEEDS; i++) {
bh.consume(constructor.newInstance(nativeSeeds[i]));
}
}
/**
* Create a new instance using reflection to lookup the constructor then invoke it.
*
* @param sources Source of randomness.
* @param bh Data sink.
* @throws InvocationTargetException If reflection failed.
* @throws IllegalAccessException If reflection failed.
* @throws InstantiationException If reflection failed.
* @throws SecurityException If reflection failed.
* @throws NoSuchMethodException If reflection failed.
* @throws IllegalArgumentException If reflection failed.
*/
@Benchmark
public void lookupNewInstance(Sources sources, Blackhole bh) throws InstantiationException,
IllegalAccessException, InvocationTargetException, NoSuchMethodException {
final Object[] nativeSeeds = sources.getNativeSeeds();
final Class<?> implementingClass = sources.getImplementingClass();
for (int i = 0; i < SEEDS; i++) {
bh.consume(implementingClass.getConstructor(nativeSeeds[i].getClass()).newInstance(nativeSeeds[i]));
}
}
/**
* @param sources Source of randomness.
* @param bh Data sink.
*/
@Benchmark
public void createNullSeed(Sources sources, Blackhole bh) {
final RandomSource randomSource = sources.getRandomSource();
final Object seed = null;
for (int i = 0; i < SEEDS; i++) {
bh.consume(randomSource.create(seed));
}
}
/**
* @param sources Source of randomness.
* @param bh Data sink.
*/
@Benchmark
public void createNativeSeed(Sources sources, Blackhole bh) {
final RandomSource randomSource = sources.getRandomSource();
final Object[] nativeSeeds = sources.getNativeSeeds();
for (int i = 0; i < SEEDS; i++) {
bh.consume(randomSource.create(nativeSeeds[i]));
}
}
/**
* Test the native seed with arrays truncated to length 1. This tests the speed
* of self-seeding.
*
* <p>This test is the same as {@link #createNativeSeed(Sources, Blackhole)} if
* the random source native seed is not an array.
*
* @param sources Source of randomness.
* @param bh Data sink.
*/
@Benchmark
public void createSelfSeed(Sources sources, Blackhole bh) {
final RandomSource randomSource = sources.getRandomSource();
final Object[] nativeSeeds1 = sources.getNativeSeeds1();
for (int i = 0; i < SEEDS; i++) {
bh.consume(randomSource.create(nativeSeeds1[i]));
}
}
/**
* @param sources Source of randomness.
* @param bh Data sink.
*/
@Benchmark
public void createLongSeed(Sources sources, Blackhole bh) {
final RandomSource randomSource = sources.getRandomSource();
for (int i = 0; i < SEEDS; i++) {
bh.consume(randomSource.create(LONG_SEEDS[i]));
}
}
/**
* @param sources Source of randomness.
* @param bh Data sink.
*/
@Benchmark
public void createByteArray(Sources sources, Blackhole bh) {
final RandomSource randomSource = sources.getRandomSource();
final byte[][] byteSeeds = sources.getByteSeeds();
for (int i = 0; i < SEEDS; i++) {
bh.consume(randomSource.create(byteSeeds[i]));
}
}
/**
* @param sizes Size of {@code int[]} seed.
* @param bh Data sink.
*/
@Benchmark
public void createIntArraySeed(IntSizes sizes, Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(SeedFactory.createIntArray(sizes.getSize()));
}
}
/**
* @param sizes Size of {@code long[]} seed.
* @param bh Data sink.
*/
@Benchmark
public void createLongArraySeed(LongSizes sizes, Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
bh.consume(SeedFactory.createLongArray(sizes.getSize()));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void createSingleIntegerSeed(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
// This has to be boxed to an object
bh.consume(Integer.valueOf(SeedFactory.createInt()));
}
}
/**
* @param bh Data sink.
*/
@Benchmark
public void createSingleLongSeed(Blackhole bh) {
for (int i = 0; i < SEEDS; i++) {
// This has to be boxed to an object
bh.consume(Long.valueOf(SeedFactory.createLong()));
}
}
}
| 2,793 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/simple/SeedArrayGenerationPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.simple;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Executes a benchmark to compare the speed of generating an array of {@code int/long} values
* in a thread-safe way.
*
* <p>Uses an upper limit of 128 for the size of an array seed.</p>
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = { "-server", "-Xms512M", "-Xmx512M" })
public class SeedArrayGenerationPerformance {
/**
* The lock to own when using the generator. This lock is unfair and there is no
* particular access order for waiting threads.
*
* <p>This is used as an alternative to {@code synchronized} statements.</p>
*/
private static final ReentrantLock UNFAIR_LOCK = new ReentrantLock(false);
/**
* The lock to own when using the generator. This lock is fair and the longest waiting
* thread will be favoured.
*
* <p>This is used as an alternative to {@code synchronized} statements.</p>
*/
private static final ReentrantLock FAIR_LOCK = new ReentrantLock(true);
/** The int[] value. Must NOT be final to prevent JVM optimisation! */
private int[] intValue;
/** The long[] value. Must NOT be final to prevent JVM optimisation! */
private long[] longValue;
/**
* The RandomSource to test.
*/
@State(Scope.Benchmark)
public static class SeedRandomSources {
/**
* RNG providers to test.
* For seed generation only long period generators should be considered.
*/
@Param({"WELL_44497_B",
"XOR_SHIFT_1024_S_PHI"})
private String randomSourceName;
/** RNG. */
private UniformRandomProvider generator;
/**
* Gets the generator.
*
* @return the RNG.
*/
public UniformRandomProvider getGenerator() {
return generator;
}
/**
* Look-up the {@link RandomSource} from the name and instantiates the generator.
*/
@Setup
public void setup() {
generator = RandomSource.valueOf(randomSourceName).create();
}
}
/**
* The number of values that are required to seed a generator.
*/
@State(Scope.Benchmark)
public static class SeedSizes {
/** The number of values. */
@Param({"2", "4", "8", "16", "32", "64", "128"})
private int size;
/**
* Gets the number of {@code int} values required.
*
* @return the size
*/
public int getSize() {
return size;
}
}
/**
* Define the number of seed values to create and the number to compute per synchronisation on
* the generator.
*/
@State(Scope.Benchmark)
public static class TestSizes {
/** The number of values. */
@Param({"2", "4", "8", "16", "32", "64", "128"})
private int size;
/** The block size is the number of values to compute per synchronisation on the generator. */
@Param({"2", "4", "8", "16", "32", "64", "128"})
private int blockSize;
/**
* Gets the number of {@code int} values required.
*
* @return the size
*/
public int getSize() {
return size;
}
/**
* @return the block size
*/
public int getBlockSize() {
return blockSize;
}
/**
* Verify the size parameters. This throws an exception if the block size exceeds the seed
* size as the test is redundant. JMH will catch the exception and run the next benchmark.
*/
@Setup
public void setup() {
if (getBlockSize() > getSize()) {
throw new AssertionError("Skipping benchmark: Block size is above seed size");
}
}
}
/**
* Get the next {@code int} from the RNG. This is synchronized on the generator.
*
* @param rng Random generator.
* @return the int
*/
private static int nextInt(UniformRandomProvider rng) {
synchronized (rng) {
return rng.nextInt();
}
}
/**
* Get the next {@code long} from the RNG. This is synchronized on the generator.
*
* @param rng Random generator.
* @return the long
*/
private static long nextLong(UniformRandomProvider rng) {
synchronized (rng) {
return rng.nextLong();
}
}
/**
* Fill the array between {@code start} inclusive and {@code end} exclusive from the RNG.
* This is synchronized on the generator.
*
* @param rng Random generator.
* @param array Array data.
* @param start Start (inclusive).
* @param end End (exclusive).
*/
private static void nextInt(UniformRandomProvider rng, int[] array, int start, int end) {
synchronized (rng) {
for (int i = start; i < end; i++) {
array[i] = rng.nextInt();
}
}
}
/**
* Fill the array between {@code start} inclusive and {@code end} exclusive from the
* RNG. This is synchronized on the generator.
*
* @param rng Random generator.
* @param array Array data.
* @param start Start (inclusive).
* @param end End (exclusive).
*/
private static void nextLong(UniformRandomProvider rng, long[] array, int start, int end) {
synchronized (rng) {
for (int i = start; i < end; i++) {
array[i] = rng.nextLong();
}
}
}
/**
* Get the next {@code int} from the RNG. The lock is used to guard access to the generator.
*
* @param lock Lock guarding access to the generator.
* @param rng Random generator.
* @return the int
*/
private static int nextInt(Lock lock, UniformRandomProvider rng) {
lock.lock();
try {
return rng.nextInt();
} finally {
lock.unlock();
}
}
/**
* Get the next {@code long} from the RNG. The lock is used to guard access to the generator.
*
* @param lock Lock guarding access to the generator.
* @param rng Random generator.
* @return the long
*/
private static long nextLong(Lock lock, UniformRandomProvider rng) {
lock.lock();
try {
return rng.nextLong();
} finally {
lock.unlock();
}
}
/**
* Fill the array between {@code start} inclusive and {@code end} exclusive from the RNG.
* The lock is used to guard access to the generator.
*
* @param lock Lock guarding access to the generator.
* @param rng Random generator.
* @param array Array data.
* @param start Start (inclusive).
* @param end End (exclusive).
*/
private static void nextInt(Lock lock, UniformRandomProvider rng, int[] array, int start, int end) {
lock.lock();
try {
for (int i = start; i < end; i++) {
array[i] = rng.nextInt();
}
} finally {
lock.unlock();
}
}
/**
* Fill the array between {@code start} inclusive and {@code end} exclusive from the RNG.
* The lock is used to guard access to the generator.
*
* @param lock Lock guarding access to the generator.
* @param rng Random generator.
* @param array Array data.
* @param start Start (inclusive).
* @param end End (exclusive).
*/
private static void nextLong(Lock lock, UniformRandomProvider rng, long[] array, int start, int end) {
lock.lock();
try {
for (int i = start; i < end; i++) {
array[i] = rng.nextLong();
}
} finally {
lock.unlock();
}
}
/**
* Baseline for a JMH method call with no return value.
*/
@Benchmark
public void baselineVoid() {
// Do nothing, this is a baseline
}
/**
* Baseline for a JMH method call returning an {@code int[]}.
*
* @return the value
*/
@Benchmark
public int[] baselineIntArray() {
return intValue;
}
/**
* Baseline for a JMH method call returning an {@code long[]}.
*
* @return the value
*/
@Benchmark
public long[] baselineLongArray() {
return longValue;
}
// The following methods use underscores to make parsing the results output easier.
// They are not documented as the names are self-documenting.
// CHECKSTYLE: stop MethodName
/**
* @param sources Source of randomness.
* @param sizes Size of the seed.
* @return the seed
*/
@Benchmark
public int[] createIntArraySeed(SeedRandomSources sources, SeedSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final int[] seed = new int[sizes.getSize()];
for (int i = 0; i < seed.length; i++) {
seed[i] = rng.nextInt();
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed.
* @return the seed
*/
@Benchmark
public long[] createLongArraySeed(SeedRandomSources sources, SeedSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final long[] seed = new long[sizes.getSize()];
for (int i = 0; i < seed.length; i++) {
seed[i] = rng.nextLong();
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed.
* @return the seed
*/
@Benchmark
public int[] Threads1_createIntArraySeed_Sync(SeedRandomSources sources, SeedSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final int[] seed = new int[sizes.getSize()];
for (int i = 0; i < seed.length; i++) {
seed[i] = nextInt(rng);
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed.
* @return the seed
*/
@Benchmark
public long[] Threads1_createLongArraySeed_Sync(SeedRandomSources sources, SeedSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final long[] seed = new long[sizes.getSize()];
for (int i = 0; i < seed.length; i++) {
seed[i] = nextLong(rng);
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed.
* @return the seed
*/
@Benchmark
public int[] Threads1_createIntArraySeed_UnfairLock(SeedRandomSources sources, SeedSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final int[] seed = new int[sizes.getSize()];
for (int i = 0; i < seed.length; i++) {
seed[i] = nextInt(UNFAIR_LOCK, rng);
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed.
* @return the seed
*/
@Benchmark
public long[] Threads1_createLongArraySeed_UnfairLock(SeedRandomSources sources, SeedSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final long[] seed = new long[sizes.getSize()];
for (int i = 0; i < seed.length; i++) {
seed[i] = nextLong(UNFAIR_LOCK, rng);
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed.
* @return the seed
*/
@Benchmark
public int[] Threads1_createIntArraySeed_FairLock(SeedRandomSources sources, SeedSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final int[] seed = new int[sizes.getSize()];
for (int i = 0; i < seed.length; i++) {
seed[i] = nextInt(FAIR_LOCK, rng);
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed.
* @return the seed
*/
@Benchmark
public long[] Threads1_createLongArraySeed_FairLock(SeedRandomSources sources, SeedSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final long[] seed = new long[sizes.getSize()];
for (int i = 0; i < seed.length; i++) {
seed[i] = nextLong(FAIR_LOCK, rng);
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed and compute blocks.
* @return the seed
*/
@Benchmark
public int[] Threads1_createIntArraySeedBlocks_Sync(SeedRandomSources sources, TestSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final int[] seed = new int[sizes.getSize()];
for (int i = 0; i < seed.length; i += sizes.getBlockSize()) {
nextInt(rng, seed, i, Math.min(i + sizes.getBlockSize(), seed.length));
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed and compute blocks.
* @return the seed
*/
@Benchmark
public long[] Threads1_createLongArraySeedBlocks_Sync(SeedRandomSources sources, TestSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final long[] seed = new long[sizes.getSize()];
for (int i = 0; i < seed.length; i += sizes.getBlockSize()) {
nextLong(rng, seed, i, Math.min(i + sizes.getBlockSize(), seed.length));
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed and compute blocks.
* @return the seed
*/
@Benchmark
public int[] Threads1_createIntArraySeedBlocks_UnfairLock(SeedRandomSources sources, TestSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final int[] seed = new int[sizes.getSize()];
for (int i = 0; i < seed.length; i += sizes.getBlockSize()) {
nextInt(UNFAIR_LOCK, rng, seed, i, Math.min(i + sizes.getBlockSize(), seed.length));
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed and compute blocks.
* @return the seed
*/
@Benchmark
public long[] Threads1_createLongArraySeedBlocks_UnfairLock(SeedRandomSources sources, TestSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final long[] seed = new long[sizes.getSize()];
for (int i = 0; i < seed.length; i += sizes.getBlockSize()) {
nextLong(UNFAIR_LOCK, rng, seed, i, Math.min(i + sizes.getBlockSize(), seed.length));
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed and compute blocks.
* @return the seed
*/
@Benchmark
public int[] Threads1_createIntArraySeedBlocks_FairLock(SeedRandomSources sources, TestSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final int[] seed = new int[sizes.getSize()];
for (int i = 0; i < seed.length; i += sizes.getBlockSize()) {
nextInt(FAIR_LOCK, rng, seed, i, Math.min(i + sizes.getBlockSize(), seed.length));
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed and compute blocks.
* @return the seed
*/
@Benchmark
public long[] Threads1_createLongArraySeedBlocks_FairLock(SeedRandomSources sources, TestSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final long[] seed = new long[sizes.getSize()];
for (int i = 0; i < seed.length; i += sizes.getBlockSize()) {
nextLong(FAIR_LOCK, rng, seed, i, Math.min(i + sizes.getBlockSize(), seed.length));
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed.
* @return the seed
*/
@Benchmark
@Threads(4)
public int[] Threads4_createIntArraySeed_Sync(SeedRandomSources sources, SeedSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final int[] seed = new int[sizes.getSize()];
for (int i = 0; i < seed.length; i++) {
seed[i] = nextInt(rng);
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed.
* @return the seed
*/
@Benchmark
@Threads(4)
public long[] Threads4_createLongArraySeed_Sync(SeedRandomSources sources, SeedSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final long[] seed = new long[sizes.getSize()];
for (int i = 0; i < seed.length; i++) {
seed[i] = nextLong(rng);
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed.
* @return the seed
*/
@Benchmark
@Threads(4)
public int[] Threads4_createIntArraySeed_UnfairLock(SeedRandomSources sources, SeedSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final int[] seed = new int[sizes.getSize()];
for (int i = 0; i < seed.length; i++) {
seed[i] = nextInt(UNFAIR_LOCK, rng);
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed.
* @return the seed
*/
@Benchmark
@Threads(4)
public long[] Threads4_createLongArraySeed_UnfairLock(SeedRandomSources sources, SeedSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final long[] seed = new long[sizes.getSize()];
for (int i = 0; i < seed.length; i++) {
seed[i] = nextLong(UNFAIR_LOCK, rng);
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed.
* @return the seed
*/
@Benchmark
@Threads(4)
public int[] Threads4_createIntArraySeed_FairLock(SeedRandomSources sources, SeedSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final int[] seed = new int[sizes.getSize()];
for (int i = 0; i < seed.length; i++) {
seed[i] = nextInt(FAIR_LOCK, rng);
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed.
* @return the seed
*/
@Benchmark
@Threads(4)
public long[] Threads4_createLongArraySeed_FairLock(SeedRandomSources sources, SeedSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final long[] seed = new long[sizes.getSize()];
for (int i = 0; i < seed.length; i++) {
seed[i] = nextLong(FAIR_LOCK, rng);
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed and compute blocks.
* @return the seed
*/
@Benchmark
@Threads(4)
public int[] Threads4_createIntArraySeedBlocks_Sync(SeedRandomSources sources, TestSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final int[] seed = new int[sizes.getSize()];
for (int i = 0; i < seed.length; i += sizes.getBlockSize()) {
nextInt(rng, seed, i, Math.min(i + sizes.getBlockSize(), seed.length));
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed and compute blocks.
* @return the seed
*/
@Benchmark
@Threads(4)
public long[] Threads4_createLongArraySeedBlocks_Sync(SeedRandomSources sources, TestSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final long[] seed = new long[sizes.getSize()];
for (int i = 0; i < seed.length; i += sizes.getBlockSize()) {
nextLong(rng, seed, i, Math.min(i + sizes.getBlockSize(), seed.length));
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed and compute blocks.
* @return the seed
*/
@Benchmark
@Threads(4)
public int[] Threads4_createIntArraySeedBlocks_UnfairLock(SeedRandomSources sources, TestSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final int[] seed = new int[sizes.getSize()];
for (int i = 0; i < seed.length; i += sizes.getBlockSize()) {
nextInt(UNFAIR_LOCK, rng, seed, i, Math.min(i + sizes.getBlockSize(), seed.length));
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed and compute blocks.
* @return the seed
*/
@Benchmark
@Threads(4)
public long[] Threads4_createLongArraySeedBlocks_UnfairLock(SeedRandomSources sources, TestSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final long[] seed = new long[sizes.getSize()];
for (int i = 0; i < seed.length; i += sizes.getBlockSize()) {
nextLong(UNFAIR_LOCK, rng, seed, i, Math.min(i + sizes.getBlockSize(), seed.length));
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed and compute blocks.
* @return the seed
*/
@Benchmark
@Threads(4)
public int[] Threads4_createIntArraySeedBlocks_FairLock(SeedRandomSources sources, TestSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final int[] seed = new int[sizes.getSize()];
for (int i = 0; i < seed.length; i += sizes.getBlockSize()) {
nextInt(FAIR_LOCK, rng, seed, i, Math.min(i + sizes.getBlockSize(), seed.length));
}
return seed;
}
/**
* @param sources Source of randomness.
* @param sizes Size of the seed and compute blocks.
* @return the seed
*/
@Benchmark
@Threads(4)
public long[] Threads4_createLongArraySeedBlocks_FairLock(SeedRandomSources sources, TestSizes sizes) {
final UniformRandomProvider rng = sources.getGenerator();
final long[] seed = new long[sizes.getSize()];
for (int i = 0; i < seed.length; i += sizes.getBlockSize()) {
nextLong(FAIR_LOCK, rng, seed, i, Math.min(i + sizes.getBlockSize(), seed.length));
}
return seed;
}
}
| 2,794 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/simple/ThreadLocalPerformance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.jmh.simple;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
import org.apache.commons.rng.simple.ThreadLocalRandomSource;
/**
* Executes benchmark to compare the speed of generation of low frequency
* random numbers on multiple-threads.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = {"-server", "-Xms128M", "-Xmx128M"})
public class ThreadLocalPerformance {
/**
* Number of random values to generate.
*/
@Param({"0", "1", "10", "100"})
private int numValues;
/**
* The benchmark state (to retrieve the various "RandomSource"s).
*/
@State(Scope.Benchmark)
public static class Sources {
/** The random source. */
protected RandomSource randomSource;
/**
* RNG providers.
*/
@Param({"SPLIT_MIX_64"})
private String randomSourceName;
/**
* @return the random source
*/
public RandomSource getRandomSource() {
return randomSource;
}
/** Instantiates the random source. */
@Setup
public void setup() {
randomSource = RandomSource.valueOf(randomSourceName);
}
}
/**
* The benchmark state (to retrieve the various "RandomSource"s thread locally).
*/
@State(Scope.Benchmark)
public static class LocalSources extends Sources {
/** The thread-local random provider. */
private ThreadLocal<UniformRandomProvider> rng;
/**
* @return the random number generator
*/
public UniformRandomProvider getRNG() {
return rng.get();
}
/** Instantiates the ThreadLocal holding the random source. */
@Override
@Setup
public void setup() {
super.setup();
rng = new ThreadLocal<UniformRandomProvider>() {
@Override
protected UniformRandomProvider initialValue() {
return randomSource.create();
}
};
}
}
/**
* @return the result
*/
@Benchmark
@Threads(4)
public long threadLocalRandom() {
final ThreadLocalRandom rng = ThreadLocalRandom.current();
long result = 0;
for (int i = 0; i < numValues; i++) {
result = result ^ rng.nextLong();
}
return result;
}
/**
* @return the result
*/
@Benchmark
@Threads(4)
public long threadLocalRandomWrapped() {
final ThreadLocalRandom rand = ThreadLocalRandom.current();
final UniformRandomProvider rng = rand::nextLong;
long result = 0;
for (int i = 0; i < numValues; i++) {
result = result ^ rng.nextLong();
}
return result;
}
/**
* @param sources Source of randomness.
* @return the result
*/
@Benchmark
@Threads(4)
public long randomSourceCreate(Sources sources) {
final UniformRandomProvider rng = sources.getRandomSource().create();
long result = 0;
for (int i = 0; i < numValues; i++) {
result = result ^ rng.nextLong();
}
return result;
}
/**
* @param sources Source of randomness.
* @return the result
*/
@Benchmark
@Threads(4)
public long threadLocalRandomSourceCurrent(Sources sources) {
final UniformRandomProvider rng = ThreadLocalRandomSource.current(sources.getRandomSource());
long result = 0;
for (int i = 0; i < numValues; i++) {
result = result ^ rng.nextLong();
}
return result;
}
/**
* @param localSources Local source of randomness.
* @return the result
*/
@Benchmark
@Threads(4)
public long threadLocalUniformRandomProvider(LocalSources localSources) {
final UniformRandomProvider rng = localSources.getRNG();
long result = 0;
for (int i = 0; i < numValues; i++) {
result = result ^ rng.nextLong();
}
return result;
}
}
| 2,795 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh | Create_ds/commons-rng/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/simple/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Benchmarks for the {@code org.apache.commons.rng.simple} components.
*/
package org.apache.commons.rng.examples.jmh.simple;
| 2,796 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples | Create_ds/commons-rng/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/ProbabilityDensityApproximationCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.sampling;
import java.io.PrintWriter;
import java.util.EnumSet;
import java.util.concurrent.Callable;
import java.io.IOException;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
import picocli.CommandLine.Command;
import picocli.CommandLine.Mixin;
import picocli.CommandLine.Option;
import org.apache.commons.rng.sampling.distribution.ZigguratNormalizedGaussianSampler;
import org.apache.commons.rng.sampling.distribution.ZigguratSampler;
import org.apache.commons.rng.sampling.distribution.MarsagliaNormalizedGaussianSampler;
import org.apache.commons.rng.sampling.distribution.StableSampler;
import org.apache.commons.rng.sampling.distribution.TSampler;
import org.apache.commons.rng.sampling.distribution.BoxMullerNormalizedGaussianSampler;
import org.apache.commons.rng.sampling.distribution.ChengBetaSampler;
import org.apache.commons.rng.sampling.distribution.AhrensDieterExponentialSampler;
import org.apache.commons.rng.sampling.distribution.AhrensDieterMarsagliaTsangGammaSampler;
import org.apache.commons.rng.sampling.distribution.InverseTransformParetoSampler;
import org.apache.commons.rng.sampling.distribution.LevySampler;
import org.apache.commons.rng.sampling.distribution.LogNormalSampler;
import org.apache.commons.rng.sampling.distribution.ContinuousUniformSampler;
import org.apache.commons.rng.sampling.distribution.GaussianSampler;
import org.apache.commons.rng.sampling.distribution.ContinuousSampler;
/**
* Approximation of the probability density by the histogram of the sampler output.
*/
@Command(name = "density",
description = {"Approximate the probability density of samplers."})
class ProbabilityDensityApproximationCommand implements Callable<Void> {
/** The standard options. */
@Mixin
private StandardOptions reusableOptions;
/** Number of (equal-width) bins in the histogram. */
@Option(names = {"-b", "--bins"},
description = "The number of bins in the histogram (default: ${DEFAULT-VALUE}).")
private int numBins = 25_000;
/** Number of samples to be generated. */
@Option(names = {"-n", "--samples"},
description = "The number of samples in the histogram (default: ${DEFAULT-VALUE}).")
private long numSamples = 1_000_000_000;
/** The samplers. */
@Option(names = {"-s", "--samplers"},
split = ",",
description = {"The samplers (comma-delimited for multiple options).",
"Valid values: ${COMPLETION-CANDIDATES}."})
private EnumSet<Sampler> samplers = EnumSet.noneOf(Sampler.class);
/** The samplers. */
@Option(names = {"-r", "--rng"},
description = {"The source of randomness (default: ${DEFAULT-VALUE})."})
private RandomSource randomSource = RandomSource.XOR_SHIFT_1024_S_PHI;
/** Flag to output all samplers. */
@Option(names = {"-a", "--all"},
description = "Output all samplers")
private boolean allSamplers;
/**
* The sampler. This enum uses lower case for clarity when matching the distribution name.
*/
enum Sampler {
/** The ziggurat gaussian sampler. */
ZigguratGaussianSampler,
/** The Marsaglia gaussian sampler. */
MarsagliaGaussianSampler,
/** The Box Muller gaussian sampler. */
BoxMullerGaussianSampler,
/** The modified ziggurat gaussian sampler. */
ModifiedZigguratGaussianSampler,
/** The Cheng beta sampler case 1. */
ChengBetaSamplerCase1,
/** The Cheng beta sampler case 2. */
ChengBetaSamplerCase2,
/** The Ahrens Dieter exponential sampler. */
AhrensDieterExponentialSampler,
/** The modified ziggurat exponential sampler. */
ModifiedZigguratExponentialSampler,
/** The Ahrens Dieter Marsaglia Tsang gamma sampler small gamma. */
AhrensDieterMarsagliaTsangGammaSamplerCase1,
/** The Ahrens Dieter Marsaglia Tsang gamma sampler large gamma. */
AhrensDieterMarsagliaTsangGammaSamplerCase2,
/** The inverse transform pareto sampler. */
InverseTransformParetoSampler,
/** The continuous uniform sampler. */
ContinuousUniformSampler,
/** The log normal ziggurat gaussian sampler. */
LogNormalZigguratGaussianSampler,
/** The log normal Marsaglia gaussian sampler. */
LogNormalMarsagliaGaussianSampler,
/** The log normal Box Muller gaussian sampler. */
LogNormalBoxMullerGaussianSampler,
/** The log normal modified ziggurat gaussian sampler. */
LogNormalModifiedZigguratGaussianSampler,
/** The Levy sampler. */
LevySampler,
/** The stable sampler. */
StableSampler,
/** The t sampler. */
TSampler,
}
/**
* @param sampler Sampler.
* @param min Right abscissa of the first bin: every sample smaller
* than that value will increment an additional bin (of infinite width)
* placed before the first "equal-width" bin.
* @param max abscissa of the last bin: every sample larger than or
* equal to that value will increment an additional bin (of infinite
* width) placed after the last "equal-width" bin.
* @param outputFile Filename (final name is "pdf.[filename].txt").
* @throws IOException Signals that an I/O exception has occurred.
*/
private void createDensity(ContinuousSampler sampler,
double min,
double max,
String outputFile)
throws IOException {
final double binSize = (max - min) / numBins;
final long[] histogram = new long[numBins];
long belowMin = 0;
long aboveMax = 0;
for (long n = 0; n < numSamples; n++) {
final double r = sampler.sample();
if (r < min) {
++belowMin;
continue;
}
if (r >= max) {
++aboveMax;
continue;
}
final int binIndex = (int) ((r - min) / binSize);
++histogram[binIndex];
}
final double binHalfSize = 0.5 * binSize;
final double norm = 1 / (binSize * numSamples);
try (PrintWriter out = new PrintWriter("pdf." + outputFile + ".txt", "UTF-8")) {
// CHECKSTYLE: stop MultipleStringLiteralsCheck
out.println("# Sampler: " + sampler);
out.println("# Number of bins: " + numBins);
out.println("# Min: " + min + " (fraction of samples below: " + (belowMin / (double) numSamples) + ")");
out.println("# Max: " + max + " (fraction of samples above: " + (aboveMax / (double) numSamples) + ")");
out.println("# Bin width: " + binSize);
out.println("# Histogram normalization factor: " + norm);
out.println("#");
out.println("# " + (min - binHalfSize) + " " + (belowMin * norm));
for (int i = 0; i < numBins; i++) {
out.println((min + (i + 1) * binSize - binHalfSize) + " " + (histogram[i] * norm));
}
out.println("# " + (max + binHalfSize) + " " + (aboveMax * norm));
// CHECKSTYLE: resume MultipleStringLiteralsCheck
}
}
/**
* Program entry point.
*
* @throws IOException if failure occurred while writing to files.
*/
@Override
public Void call() throws IOException {
if (allSamplers) {
samplers = EnumSet.allOf(Sampler.class);
} else if (samplers.isEmpty()) {
// CHECKSTYLE: stop regexp
System.err.println("ERROR: No samplers specified");
// CHECKSTYLE: resume regexp
System.exit(1);
}
final UniformRandomProvider rng = randomSource.create();
final double gaussMean = 1;
final double gaussSigma = 2;
final double gaussMin = -9;
final double gaussMax = 11;
if (samplers.contains(Sampler.ZigguratGaussianSampler)) {
createDensity(GaussianSampler.of(ZigguratNormalizedGaussianSampler.of(rng),
gaussMean, gaussSigma),
gaussMin, gaussMax, "gauss.ziggurat");
}
if (samplers.contains(Sampler.MarsagliaGaussianSampler)) {
createDensity(GaussianSampler.of(MarsagliaNormalizedGaussianSampler.of(rng),
gaussMean, gaussSigma),
gaussMin, gaussMax, "gauss.marsaglia");
}
if (samplers.contains(Sampler.BoxMullerGaussianSampler)) {
createDensity(GaussianSampler.of(BoxMullerNormalizedGaussianSampler.of(rng),
gaussMean, gaussSigma),
gaussMin, gaussMax, "gauss.boxmuller");
}
if (samplers.contains(Sampler.ModifiedZigguratGaussianSampler)) {
createDensity(GaussianSampler.of(ZigguratSampler.NormalizedGaussian.of(rng),
gaussMean, gaussSigma),
gaussMin, gaussMax, "gauss.modified.ziggurat");
}
final double betaMin = 0;
final double betaMax = 1;
if (samplers.contains(Sampler.ChengBetaSamplerCase1)) {
final double alphaBeta = 4.3;
final double betaBeta = 2.1;
createDensity(ChengBetaSampler.of(rng, alphaBeta, betaBeta),
betaMin, betaMax, "beta.case1");
}
if (samplers.contains(Sampler.ChengBetaSamplerCase2)) {
final double alphaBetaAlt = 0.5678;
final double betaBetaAlt = 0.1234;
createDensity(ChengBetaSampler.of(rng, alphaBetaAlt, betaBetaAlt),
betaMin, betaMax, "beta.case2");
}
final double meanExp = 3.45;
final double expMin = 0;
final double expMax = 60;
if (samplers.contains(Sampler.AhrensDieterExponentialSampler)) {
createDensity(AhrensDieterExponentialSampler.of(rng, meanExp),
expMin, expMax, "exp");
}
if (samplers.contains(Sampler.ModifiedZigguratExponentialSampler)) {
createDensity(ZigguratSampler.Exponential.of(rng, meanExp),
expMin, expMax, "exp.modified.ziggurat");
}
final double gammaMin = 0;
final double gammaMax1 = 40;
final double thetaGamma = 3.456;
if (samplers.contains(Sampler.AhrensDieterMarsagliaTsangGammaSamplerCase1)) {
final double alphaGammaSmallerThanOne = 0.1234;
createDensity(AhrensDieterMarsagliaTsangGammaSampler.of(rng, alphaGammaSmallerThanOne, thetaGamma),
gammaMin, gammaMax1, "gamma.case1");
}
if (samplers.contains(Sampler.AhrensDieterMarsagliaTsangGammaSamplerCase2)) {
final double alphaGammaLargerThanOne = 2.345;
final double gammaMax2 = 70;
createDensity(AhrensDieterMarsagliaTsangGammaSampler.of(rng, alphaGammaLargerThanOne, thetaGamma),
gammaMin, gammaMax2, "gamma.case2");
}
final double scalePareto = 23.45;
final double shapePareto = 0.789;
final double paretoMin = 23;
final double paretoMax = 400;
if (samplers.contains(Sampler.InverseTransformParetoSampler)) {
createDensity(InverseTransformParetoSampler.of(rng, scalePareto, shapePareto),
paretoMin, paretoMax, "pareto");
}
final double loUniform = -9.876;
final double hiUniform = 5.432;
if (samplers.contains(Sampler.ContinuousUniformSampler)) {
createDensity(ContinuousUniformSampler.of(rng, loUniform, hiUniform),
loUniform, hiUniform, "uniform");
}
final double scaleLogNormal = 2.345;
final double shapeLogNormal = 0.1234;
final double logNormalMin = 5;
final double logNormalMax = 25;
if (samplers.contains(Sampler.LogNormalZigguratGaussianSampler)) {
createDensity(LogNormalSampler.of(ZigguratNormalizedGaussianSampler.of(rng),
scaleLogNormal, shapeLogNormal),
logNormalMin, logNormalMax, "lognormal.ziggurat");
}
if (samplers.contains(Sampler.LogNormalMarsagliaGaussianSampler)) {
createDensity(LogNormalSampler.of(MarsagliaNormalizedGaussianSampler.of(rng),
scaleLogNormal, shapeLogNormal),
logNormalMin, logNormalMax, "lognormal.marsaglia");
}
if (samplers.contains(Sampler.LogNormalBoxMullerGaussianSampler)) {
createDensity(LogNormalSampler.of(BoxMullerNormalizedGaussianSampler.of(rng),
scaleLogNormal, shapeLogNormal),
logNormalMin, logNormalMax, "lognormal.boxmuller");
}
if (samplers.contains(Sampler.LogNormalModifiedZigguratGaussianSampler)) {
createDensity(LogNormalSampler.of(ZigguratSampler.NormalizedGaussian.of(rng),
scaleLogNormal, shapeLogNormal),
logNormalMin, logNormalMax, "lognormal.modified.ziggurat");
}
if (samplers.contains(Sampler.LevySampler)) {
final double levyLocation = 1.23;
final double levyscale = 0.75;
final double levyMin = levyLocation;
// Quantile 0 to 0.7 (avoid long tail to infinity)
final double levyMax = 6.2815;
createDensity(LevySampler.of(rng, levyLocation, levyscale),
levyMin, levyMax, "levy");
}
if (samplers.contains(Sampler.StableSampler)) {
final double stableAlpha = 1.23;
final double stableBeta = 0.75;
// Quantiles 0.05 to 0.9 (avoid long tail to infinity)
final double stableMin = -1.7862;
final double stableMax = 4.0364;
createDensity(StableSampler.of(rng, stableAlpha, stableBeta),
stableMin, stableMax, "stable");
}
if (samplers.contains(Sampler.TSampler)) {
final double tDegreesOfFreedom = 1.23;
// Quantiles 0.02 to 0.98 (avoid long tail to infinity)
final double tMin = -9.9264;
final double tMax = 9.9264;
createDensity(TSampler.of(rng, tDegreesOfFreedom),
tMin, tMax, "t");
}
return null;
}
}
| 2,797 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples | Create_ds/commons-rng/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/ManifestVersionProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.sampling;
import picocli.CommandLine.IVersionProvider;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
/**
* {@link IVersionProvider} implementation that returns version information from
* the package jar file's {@code /META-INF/MANIFEST.MF} file.
*
* @see <a
* href="https://github.com/remkop/picocli/blob/master/picocli-examples/src/main/java/picocli/examples/VersionProviderDemo2.java">PicoCLI
* version provider demo</a>
*/
class ManifestVersionProvider implements IVersionProvider {
/** {@inheritDoc} */
@Override
public String[] getVersion() throws Exception {
final Enumeration<URL> resources = Thread.currentThread().getContextClassLoader()
.getResources("META-INF/MANIFEST.MF");
while (resources.hasMoreElements()) {
final URL url = resources.nextElement();
try (InputStream stream = url.openStream()) {
final Manifest manifest = new Manifest(stream);
if (isApplicableManifest(manifest)) {
final Attributes attr = manifest.getMainAttributes();
return new String[] {get(attr, "Implementation-Title") + " version \"" +
get(attr, "Implementation-Version") + "\""};
}
} catch (final IOException ex) {
return new String[] {"Unable to read from " + url + ". " + ex};
}
}
return new String[0];
}
/**
* Checks if this is the applicable manifest for the package.
*
* @param manifest The manifest.
* @return true if is the applicable manifest
*/
private static boolean isApplicableManifest(Manifest manifest) {
final Attributes attributes = manifest.getMainAttributes();
return "org.apache.commons.rng.examples.sampling".equals(get(attributes, "Automatic-Module-Name"));
}
/**
* Gets the named object from the attributes using the key.
*
* @param attributes The attributes.
* @param key The key.
* @return the object
*/
private static Object get(Attributes attributes, String key) {
return attributes.get(new Attributes.Name(key));
}
}
| 2,798 |
0 | Create_ds/commons-rng/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples | Create_ds/commons-rng/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/ExamplesSamplingApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.examples.sampling;
import picocli.CommandLine;
/**
* Executes testing utilities for the samplers in the Commons RNG library.
*
* <p>Functionality includes:</p>
*
* <ul>
* <li>Creating a PDF approximation using sample data from a distribution
* <li>Sampling from a small range from a distribution to visually inspect sampling density
* </ul>
*/
public final class ExamplesSamplingApplication {
/** No public constructor. */
private ExamplesSamplingApplication() {}
/**
* Run the RNG examples stress command line application.
*
* @param args Application's arguments.
*/
public static void main(String[] args) {
// Build the command line manually so we can configure options.
final CommandLine cmd = new CommandLine(new ExamplesSamplingCommand())
.addSubcommand("density", new ProbabilityDensityApproximationCommand())
.addSubcommand("visual", new UniformSamplingVisualCheckCommand())
// Call last to apply to all sub-commands
.setCaseInsensitiveEnumValuesAllowed(true);
// Parse the command line and invokes the Callable program
cmd.execute(args);
}
}
| 2,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.