HaltonSequenceGenerator.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.math4.legacy.random;

  18. import java.util.function.Supplier;

  19. import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
  20. import org.apache.commons.math4.legacy.exception.NotPositiveException;
  21. import org.apache.commons.math4.legacy.exception.NullArgumentException;
  22. import org.apache.commons.math4.legacy.exception.OutOfRangeException;

  23. /**
  24.  * Implementation of a Halton sequence.
  25.  * <p>
  26.  * A Halton sequence is a low-discrepancy sequence generating points in the interval [0, 1] according to
  27.  * <pre>
  28.  *   H(n) = d_0 / b + d_1 / b^2 .... d_j / b^j+1
  29.  *
  30.  *   with
  31.  *
  32.  *   n = d_j * b^j-1 + ... d_1 * b + d_0 * b^0
  33.  * </pre>
  34.  * For higher dimensions, subsequent prime numbers are used as base, e.g. { 2, 3, 5 } for a Halton sequence in R^3.
  35.  * <p>
  36.  * Halton sequences are known to suffer from linear correlation for larger prime numbers, thus the individual digits
  37.  * are usually scrambled. This implementation already comes with support for up to 40 dimensions with optimal weight
  38.  * numbers from <a href="http://etd.lib.fsu.edu/theses/available/etd-07062004-140409/unrestricted/dissertation1.pdf">
  39.  * H. Chi: Scrambled quasirandom sequences and their applications</a>.
  40.  * <p>
  41.  * The generator supports two modes:
  42.  * <ul>
  43.  *   <li>sequential generation of points: {@link #get()}</li>
  44.  *   <li>random access to the i-th point in the sequence: {@link #skipTo(int)}</li>
  45.  * </ul>
  46.  *
  47.  * @see <a href="http://en.wikipedia.org/wiki/Halton_sequence">Halton sequence (Wikipedia)</a>
  48.  * @see <a href="https://lirias.kuleuven.be/bitstream/123456789/131168/1/mcm2005_bartv.pdf">
  49.  * On the Halton sequence and its scramblings</a>
  50.  * @since 3.3
  51.  */
  52. public class HaltonSequenceGenerator implements Supplier<double[]> {

  53.     /** The first 40 primes. */
  54.     private static final int[] PRIMES = new int[] {
  55.         2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
  56.         71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139,
  57.         149, 151, 157, 163, 167, 173
  58.     };

  59.     /** The optimal weights used for scrambling of the first 40 dimension. */
  60.     private static final int[] WEIGHTS = new int[] {
  61.         1, 2, 3, 3, 8, 11, 12, 14, 7, 18, 12, 13, 17, 18, 29, 14, 18, 43, 41,
  62.         44, 40, 30, 47, 65, 71, 28, 40, 60, 79, 89, 56, 50, 52, 61, 108, 56,
  63.         66, 63, 60, 66
  64.     };

  65.     /** Space dimension. */
  66.     private final int dimension;

  67.     /** The current index in the sequence. */
  68.     private int count;

  69.     /** The base numbers for each component. */
  70.     private final int[] base;

  71.     /** The scrambling weights for each component. */
  72.     private final int[] weight;

  73.     /**
  74.      * Construct a new Halton sequence generator for the given space dimension.
  75.      *
  76.      * @param dimension the space dimension
  77.      * @throws OutOfRangeException if the space dimension is outside the allowed range of [1, 40]
  78.      */
  79.     public HaltonSequenceGenerator(final int dimension) {
  80.         this(dimension, PRIMES, WEIGHTS);
  81.     }

  82.     /**
  83.      * Construct a new Halton sequence generator with the given base numbers and weights for each dimension.
  84.      * The length of the bases array defines the space dimension and is required to be &gt; 0.
  85.      *
  86.      * @param dimension the space dimension
  87.      * @param bases the base number for each dimension, entries should be (pairwise) prime, may not be null
  88.      * @param weights the weights used during scrambling, may be null in which case no scrambling will be performed
  89.      * @throws NullArgumentException if base is null
  90.      * @throws OutOfRangeException if the space dimension is outside the range [1, len], where
  91.      *   len refers to the length of the bases array
  92.      * @throws DimensionMismatchException if weights is non-null and the length of the input arrays differ
  93.      */
  94.     public HaltonSequenceGenerator(final int dimension, final int[] bases, final int[] weights) {
  95.         NullArgumentException.check(bases);

  96.         if (dimension < 1 || dimension > bases.length) {
  97.             throw new OutOfRangeException(dimension, 1, PRIMES.length);
  98.         }

  99.         if (weights != null && weights.length != bases.length) {
  100.             throw new DimensionMismatchException(weights.length, bases.length);
  101.         }

  102.         this.dimension = dimension;
  103.         this.base = bases.clone();
  104.         this.weight = weights == null ? null : weights.clone();
  105.         count = 0;
  106.     }

  107.     /** {@inheritDoc} */
  108.     @Override
  109.     public double[] get() {
  110.         final double[] v = new double[dimension];
  111.         for (int i = 0; i < dimension; i++) {
  112.             int index = count;
  113.             double f = 1.0 / base[i];

  114.             int j = 0;
  115.             while (index > 0) {
  116.                 final int digit = scramble(i, j, base[i], index % base[i]);
  117.                 v[i] += f * digit;
  118.                 index /= base[i]; // floor( index / base )
  119.                 f /= base[i];
  120.             }
  121.         }
  122.         count++;
  123.         return v;
  124.     }

  125.     /**
  126.      * Performs scrambling of digit {@code d_j} according to the formula:
  127.      * <pre>
  128.      *   ( weight_i * d_j ) mod base
  129.      * </pre>
  130.      * Implementations can override this method to do a different scrambling.
  131.      *
  132.      * @param i the dimension index
  133.      * @param j the digit index
  134.      * @param b the base for this dimension
  135.      * @param digit the j-th digit
  136.      * @return the scrambled digit
  137.      */
  138.     protected int scramble(final int i, final int j, final int b, final int digit) {
  139.         return weight != null ? (weight[i] * digit) % b : digit;
  140.     }

  141.     /**
  142.      * Skip to the i-th point in the Halton sequence.
  143.      * <p>
  144.      * This operation can be performed in O(1).
  145.      *
  146.      * @param index the index in the sequence to skip to
  147.      * @return the i-th point in the Halton sequence
  148.      * @throws NotPositiveException if {@code index < 0}.
  149.      */
  150.     public double[] skipTo(final int index) {
  151.         if (index < 0) {
  152.             throw new NotPositiveException(index);
  153.         }

  154.         count = index;
  155.         return get();
  156.     }

  157.     /**
  158.      * Returns the index i of the next point in the Halton sequence that will be returned
  159.      * by calling {@link #get()}.
  160.      *
  161.      * @return the index of the next point
  162.      */
  163.     public int getNextIndex() {
  164.         return count;
  165.     }
  166. }