chickadee » srfi-27

SRFI 27

Source of Random Bits

TOC »

Documentation

A Chicken implementation of SRFI 27.

SRFI 27

Most procedures are per the SRFI 27 specification document. Only the extensions are documented here.

The most obvious extensions are support for multiple random number generators and multiple entropy sources.

Usage

(use srfi-27)

current-random-source

current-random-sourceprocedure
current-random-source RANDOM-SOURCEprocedure

Parameter for the default random-source.

The variable default-random-source is the initial (current-random-source).

The initial random-source is an instace of 'mrg32k3a, per SRFI 27.

registered-random-sources

registered-random-sourcesprocedure

Returns a list of the registered random-source names.

registered-random-source

registered-random-source NAMEprocedure

Returns the random-source creator for the specified NAME or #f if not registered.

random-source?

random-source? OBJprocedure
check-random-source LOC OBJ #!optional NAMprocedure
error-random-source LOC OBJ #!optional NAMprocedure

make-random-source

make-random-source #!optional SOURCE current-random-sourceprocedure

SOURCE is either a random-source or the symbol of a registered random-source, the name.

new-random-source

new-random-source RANDOM-SOURCEprocedure

Returns a new random-source from RANDOM-SOURCE.

Same as (make-random-source RANDOM-SOURCE).

random-source-name

random-source-name RANDOM-SOURCEprocedure

The symbolic name of the RANDOM-SOURCE.

random-source-documentation

random-source-documentation RANDOM-SOURCEprocedure

Some more information for the RANDOM-SOURCE.

random-source-log2-period

random-source-log2-period RANDOM-SOURCEprocedure

The period of the RANDOM-SOURCE as a power of 2. A fixnum.

random-source-maximum-range

random-source-maximum-range RANDOM-SOURCEprocedure

The largest integer the RANDOM-SOURCE can produce without resort to a bignum representation. An inexact-integer flonum, even for 64-bit CPUs.

random-source-entropy-source

random-source-entropy-source RANDOM-SOURCEprocedure

The current entropy-source for the RANDOM-SOURCE.

random-source-entropy-source-set!

random-source-entropy-source-set! RANDOM-SOURCE ENTROPY-SOURCEprocedure

Changes the current entropy-source for the RANDOM-SOURCE.

random-source-state-ref

random-source-state-ref RANDOM-SOURCEprocedure

Per the SRFI 27 specification the random-state is a valid external representation.

random-source-state-set!

random-source-state-set! RANDOM-SOURCE RANDOM-STATEprocedure

Only a RANDOM-STATE produced by a random-source-state-ref of the same random-source-name is acceptable.

random-source-randomize!

random-source-randomize! RANDOM-SOURCE #!optional ENTROPY-SOURCEprocedure

random-source-pseudo-randomize!

random-source-pseudo-randomize! RANDOM-SOURCE I Jprocedure

random-source-make-integers

random-source-make-integers RANDOM-SOURCEprocedure

The variable random-integer is a procedure: (random-source-make-integers default-random-source)

random-source-make-reals

random-source-make-reals RANDOM-SOURCE #!optional PRECISIONprocedure

The variable random-real is a procedure: (random-source-make-reals default-random-source)

PRECISION maybe #f, in which case the value is flonum-epsilon.

random-source-make-u8vectors

random-source-make-u8vectors RANDOM-SOURCEprocedure

Returns a procedure of one argument, the length of the generated vector, the returns a vector of random 8-bit unsigned values, a SRFI 4 u8vector.

The variable random-u8vector is a procedure: (random-source-make-u8vectors default-random-source)

random-source-make-f64vectors

random-source-make-f64vectors RANDOM-SOURCE #!optional PRECISIONprocedure

Returns a procedure of one argument, the length of the generated vector, the returns a vector of random 64-bit floatingpoint values, a SRFI 4 f64vector.

The variable random-f64vector is a procedure: (random-source-make-f64vectors default-random-source)

current-entropy-source

current-entropy-sourceprocedure
current-entropy-source ENTROPY-SOURCEprocedure

Parameter for the default entropy-source.

default-entropy-source is the initial (current-entropy-source).

The initial entropy-source is an instace of 'system-clock.

registered-entropy-sources

registered-entropy-sourcesprocedure

Returns a list of the registered entropy-source names.

registered-entropy-source

registered-entropy-source NAMEprocedure

Returns the entropy-source creator for the specified NAME or #f if not registered.

entropy-source?

entropy-source? OBJprocedure
check-entropy-source LOC OBJ #!optional NAMprocedure
error-entropy-source LOC OBJ #!optional NAMprocedure

make-entropy-source

make-entropy-source #!optional SOURCE current-entropy-sourceprocedure

SOURCE is either a entropy-source or the symbol of a registered entropy-source, the name.

new-entropy-source

new-entropy-source ENTROPY-SOURCEprocedure

Returns a new entropy-source from ENTROPY-SOURCE.

Same as (make-random-entropy ENTROPY-SOURCE).

entropy-source-name

entropy-source-name ENTROPY-SOURCEprocedure

The symbolic name of the ENTROPY-SOURCE.

entropy-source-documentation

entropy-source-documentation ENTROPY-SOURCEprocedure

Some more information for the ENTROPY-SOURCE.

entropy-source-u8

entropy-source-u8 ENTROPY-SOURCEprocedure

Returns a non-negative fixnum from the ENTROPY-SOURCE.

entropy-source-f64

entropy-source-f64 ENTROPY-SOURCEprocedure

Returns a flonum from the ENTROPY-SOURCE.

entropy-source-u8vector

entropy-source-u8vector ENTROPY-SOURCE LENGTH #!optional U8VECTORprocedure

Returns a u8vector with the 0 thru LENGTH-1 elements filled with non-negative fixnums from the ENTROPY-SOURCE. If U8VECTOR is supplied then this is used otherwise a new vector is returned.

entropy-source-f64vector

entropy-source-f64vector ENTROPY-SOURCE LENGTH #!optional F64VECTORprocedure

Returns a f64vector with the 0 thru LENGTH-1 elements filled with flonums from the ENTROPY-SOURCE. If F64VECTOR is supplied then this is used otherwise a new vector is returned.

entropy-source-integer

entropy-source-integer ENTROPY-SOURCprocedure

Returns an integer from the ENTROPY-SOURCE.

Random Sources

A random source module must be loaded before it can be used. This maybe obvious but a call of (make-random-source 'moa) will fail unless the extension "moa" is loaded.

See make-random-source for use of the NAME.

Pierre L'Ecuyer's Multiple Recursive Generator 32k3a random number generator

Usage
(use mrg32k3a)
make-random-source-mrg32k3a
make-random-source-mrg32k3aprocedure

Registered NAME is 'mrg32k3a

George Marsaglia's Multiply With Carry random number generator

Usage
(use mwc)
make-random-source-mwc
make-random-source-mwcprocedure

Registered NAME is 'mwc

George Marsaglia's Mother Of All random number generator

Usage
(use moa)
make-random-source-moa
make-random-source-moaprocedure

Registered NAME is 'moa

Composite Random Source

Usage

(use composite-random-source)

composite-random-source

(composite-random-source [RANDOM-SOURCE ...] [#:comb-int INTEGER-COMBINE] [#:comb-real REAL-COMBINE]) => random-sourceprocedure

Returns a new random-source that combines the behaviors of the supplied RANDOM-SOURCE ....

INTEGER-COMBINE default is (lambda (ints bnd) (modulo (apply + ints) bnd)).

REAL-COMBINE default is (lambda (reals prec) (apply * reals)).

Does not register the constructed random-source.

Experimental at best.

Entropy Sources

An entropy source module must be loaded before it can be used.

System Clock

Usage
(use entropy-clock)
make-entropy-source-system-clock
make-entropy-source-system-clockprocedure

Registered NAME is 'system-clock

Windows Crypt Device

Usage
(use entropy-windows)
make-entropy-source-crypt
make-entropy-source-crypt #!optional BUFFER-LENGTHprocedure

Registered NAME is 'crypt

Unix Random Device

Usage
(use entropy-unix)
make-entropy-source-urandom-device
make-entropy-source-urandom-deviceprocedure

Registered NAME is 'random-device

make-entropy-source-random-device
make-entropy-source-random-deviceprocedure

Registered NAME is 'urandom-device

Procedure Entropy Source

U8PROC is a procedure of no arguments returning a fixnum in the range 0 .. 255.

F64PROC is a procedure of no arguments returning a finite flonum.

Usage

(use entropy-procedure)

make-entropy-source/procedures

(make-entropy-source/procedures U8PROC F64PROC [#:name (gensym 'procedures-)] [#:docu "Entropy from procedures"]) => entropy-sourceprocedure

Returns an unregistered entropy-source built from the supplied U8PROC and F64PROC procedures.

make-entropy-source/f64procedure

(make-entropy-source/f64procedure F64PROC [#:name (gensym 'procedures-)] [#:docu "Entropy from procedures"]) => entropy-sourceprocedure

Returns an unregistered entropy-source built from the supplied F64PROC procedure.

Port Entropy Source

Usage

(use entropy-port)

entropy-port-lifetime

entropy-port-lifetime #!optional SECONDSparameter

The number of SECONDS an entropy port is kept open without any activity.

SECONDS is a positive real or a boolean: #t, to reset the default seconds, or #f, to determine the lifetime by GC finalizstion.

make-entropy-source/port

(make-entropy-source/port PORT [#:name (gensym 'port-)] [#:docu "Entropy from an open port"]) => entropy-sourceprocedure

Returns an unregistered entropy-source built from the supplied PORT, which is treated as a binary stream.

The PORT is kept open and must be closed by the caller, if at all.

make-entropy-source/port-open

(make-entropy-source/port-open OPENER [#:name (gensym 'port-)] [#:docu "Entropy from port"]) => entropy-sourceprocedure

Returns an unregistered entropy-source built from the supplied OPENER.

OPENER is a (procedure () port), returning an opened port.

The returned port has an (entropy-port-lifetime) so the port may be closed and OPENER called more than once.

make-entropy-source/port-open-timed

(make-entropy-source/port-open-timed OPENER SECONDS [#:name (gensym 'timed-port-)] [#:docu "Entropy from timed open port"]) => entropy-sourceprocedure

Returns an unregistered entropy-source built from the supplied OPENER & SECONDS.

SECONDS is interpreted as with entropy-port-lifetime.

OPENER is interpreted as with make-entropy-source/port-open.

make-entropy-source/file

(make-entropy-source/file NAMSTR [#:name (gensym 'file-)] [#:docu (string-append "Entropy from file \"" namstr "\"")]) => entropy-sourceprocedure

Returns an unregistered entropy-source using the file named by the pathname NAMSTR.

The opened port for the file NAMSTR is interpreted as with make-entropy-source/port-open.

Simple Distributions

Provides exact-real and inexact-real generators.

All return 2 values: the generator itself and a procedure returning the argument values used to parameterize the generator. The second return value can be safely ignored, as it is below.

Usage

(use srfi-27-uniform-random)

make-uniform-random-integers

(make-uniform-random-integers [#:high #f] [#:low 0] [#:precision 1] [#:source (current-random-source)]) => (procedure () integer)procedure

low, high and precision are integers.

source is a random-source.

high, if not supplied, is the (random-source-maximum-range source).

The generator returns integers in the range low .. high with an index of precision. Unlike a (random-integer) result negative integers are possible.

The range of the generator is checked for logical soundness.

make-uniform-random-reals

(make-uniform-random-reals [#:precision #f] [#:source (current-random-source)]) => (procedure () real)procedure

The generator is as (random-source-make-reals source precision).

Vector Distributions

The procedures named as per make-random-... return a procedure of one argument N, the length of vector to be created.

The procedures named random-...! side-effect the supplied vector.

The nomenclature vector% is used to indicate a disjoint type union of vector, f32vector, f64vector. If the user is really keen to access the API for this type it is available in the, undocumented, "srfi-27-vector-support" module.

Usage

(use srfi-27-vector)

make-random-permutations

random-permutation!

(make-random-permutations [#:randoms (make-uniform-random-integers)]) => (procedure (integer) vector)procedure
(random-permutation! VECTOR [#:randoms (make-uniform-random-integers)]) => vectorprocedure

Performs the "Knuth shuffle" (or "Fisher-Yates shuffle").

Fills VECTOR with a random permutation of the finite set {0 ... N-1}, where N = (vector-length VECTOR).

make-random-vector

random-vector!

(make-random-vector [#:randoms (make-uniform-random-reals)]) => (procedure (integer) vector)procedure
(random-vector! VECTOR% [#:randoms (make-uniform-random-reals)]) => vector%procedure

Fills VECTOR with inexact real random numbers from the random distribution generator randoms.

make-random-hollow-sphere

random-hollow-sphere!

(make-random-hollow-sphere [#:mu 0.0] [#:sigma 1.0] [#:randoms (make-uniform-random-reals)]) => (procedure (integer) vector)procedure
(random-hollow-sphere! VECTOR% [#:mu 0.0] [#:sigma 1.0] [#:randoms (make-uniform-random-reals)]) => vector%procedure

Fills VECTOR% with inexact real random numbers the sum of whose squares is equal to 1.0. Thinking of VECTOR% as coordinates in space of dimension N = (vector%-length VECTOR%), the coordinates are uniformly distributed over the surface of the unit n-sphere.

make-random-solid-sphere

random-solid-sphere!

(make-random-solid-sphere [#:mu 0.0] [#:sigma 1.0] [#:randoms (make-uniform-random-reals)]) => (procedure (integer) vector)procedure
(random-solid-sphere! VECTOR% [#:mu 0.0] [#:sigma 1.0] [#:randoms (make-uniform-random-reals)]) => vector%procedure

Fills VECTOR% with inexact real random numbers the sum of whose squares is less than 1.0. Thinking of VECTOR% as coordinates in space of dimension N = (vector%-length VECTOR%), the coordinates are uniformly distributed within the unit n-sphere.

Other Distributions

Provides generators for some common distributions ranging over some subset of the inexact-reals. The domain of the generators depends, of course, on the specific distribution.

All return 2 values: the generator itself and a procedure returning the argument values used to parameterize the generator. The second return value can be safely ignored, as it is below.

Usage

(use srfi-27-distributions)

make-random-normals

(make-random-normals [#:mu 0.0] [#:sigma 1.0] [#:randoms (make-uniform-random-reals)]) => (procedure () real)procedure

make-random-exponentials

(make-random-exponentials [#:mu 1.0] [#:randoms (make-uniform-random-reals)]) => (procedure () real)procedure

make-random-triangles

(make-random-triangles [#:s 0.0] [#:m 0.5] [#:l 1.0] [#:randoms (make-uniform-random-reals)]) => (procedure () real)procedure

make-random-poissons

(make-random-poissons [#:mu 1.0] [#:randoms (make-uniform-random-reals)]) => (procedure () integer)procedure

make-random-bernoullis

(make-random-bernoullis [#:p 0.5] [#:randoms (make-uniform-random-reals)]) => (procedure () boolean)procedure

make-random-binomials

(make-random-binomials [#:t 1] [#:p 0.5] [#:randoms (make-uniform-random-reals)]) => (procedure () integer)procedure

make-random-geometrics

(make-random-geometrics [#:p 0.5] [#:randoms (make-uniform-random-reals)])) => (procedure () integer)procedure

make-random-lognormals

(make-random-lognormals [#:mu 1.0] [#:sigma 1.0] [#:randoms (make-uniform-random-reals)]) => (procedure () real)procedure

make-random-cauchys

(make-random-cauchys [#:median 0.0] [#:sigma 1.0] [#:randoms (make-uniform-random-reals)]) => (procedure () real)procedure

make-random-gammas

(make-random-gammas [#:alpha 1.0] [#:theta 1.0] [#:randoms (make-uniform-random-reals)]) => (procedure () real)procedure

make-random-erlangs

(make-random-erlangs [#:alpha 1] [#:theta 1.0] [#:randoms (make-uniform-random-reals)]) => (procedure () real)procedure

make-random-paretos

(make-random-paretos [#:alpha 1.0] [#:xmin 1.0] [#:randoms (make-uniform-random-reals)]) => (procedure () real)procedure

make-random-levys

(make-random-levys [#:gamma 1.0] [#:delta 0.0] [#:randoms (make-uniform-random-reals)]) => (procedure () real)procedure

make-random-weibulls

(make-random-weibulls [#:shape 1.0] [#:scale 1.0] [#:randoms (make-uniform-random-reals)]) => (procedure () real)procedure

Examples

(use srfi-27 srfi-27-uniform-random srfi-27-vector mwc entropy-unix entropy-port)

(define (make-random-k-vector #!optional (k 1024))
  (let ((rs1 (make-random-source 'mwc))) ; or (make-random-source-mwc)
    (parameterize ((entropy-port-lifetime 30)) ; don't keep open port around too much
      (random-source-entropy-source-set! rs1 (make-entropy-source-random-device)) )
    (make-random-vector #:randoms (make-uniform-random-integers #:high k #:low (- k) #:precision 2 #:source rs1))))
(use data-structures entropy-procedure)

(define (make-entropy-constant n)
  (make-entropy-source/f64procedure
    (constantly (exact->inexact n))
    #:name (string->uninterned-symbol (conc "entropy-constant-" n))
    #:docu (conc "Entropy constant " n)) )
(use srfi-1 srfi-13 coops)

;; Named (has a name) "concept"

(define-generic (name obj))
(define-class <named> () (
  (namsym #:reader name) ) )

;; Moves forward thru a set of values "concept"

(define-generic (step-function obj))
(define-class <stepper> () (
  (nxtval #:reader step-function) ) )
(define-generic (next-value obj))
(define-method (next-value (obj <stepper>)) ((step-function obj)))

;; Parameterized extension "concept"

(define-generic (parameters obj))
(define-generic (basis obj))
(define-class <parameterized> () (
  (parms #:reader parameters)
  (src #:reader basis) ) )

;; Parameterized generative set of random values "concept"

(define-class <random-distribution> (<named> <parameterized> <stepper>) (
  temp ) )

;; Create an instance of <random-distribution> where the arguments are
;; the same as the documented procedural distribution API.
;;
;; SRFI 27 API: ({some distribution constructor} arg...)
;;      OO API: (make-random-distribution {some distribution constructor} arg...)

(define-syntax make-random-distribution
  (syntax-rules ()
    ((_ ?ctor ?arg0 ...)
      (make <random-distribution> 'temp (?ctor ?arg0 ...)) ) ) )

(define-method (initialize-instance (obj <random-distribution>))
  ; The 'ctor' should be a globally defined procedure compiled
  ; with procedure-information. So if following nomenclature then the last
  ; procedure name element will be the kind of distribution.
  (let* ((temp (slot-value obj 'temp))
         (ctor (car temp))
         (procinfo (procedure-information ctor))
         (name (and procinfo (pair? procinfo) (symbol->string (car procinfo))))
         (name (and name
                    (and-let* ((kndpos (string-index-right name #\-)))
                      (substring/shared name (fx+ kndpos 1)) ) ) )
         (dstr-vals (receive (apply ctor (cdr temp))))
         (parms (and (fx<= 2 (length dstr-vals)) (receive ((second dstr-vals))))) )
    (set! (slot-value obj 'temp) #f) ;"free" the "any" slot
    (set! (slot-value obj 'namsym) (string->symbol name))
    (set! (slot-value obj 'nxtval) (first dstr-vals))
    (set! (slot-value obj 'parms) (and parms (drop-right parms 1)))
    (set! (slot-value obj 'src) (and parms (last parms))) ) )

; Use it

(use srfi-27-distributions)

(make-random-distribution make-random-exponentials #:mu 0.5)
;=> <random-distribution> with
; name          'exponentials
; step-function <procedure>
; parameters    '(0,5)
; basis         <procedure>

Notes

Bugs and Limitations

Requirements

miscmacros numbers check-errors synch vector-lib thread-utils timed-resource

Author

Kon Lovett

Version history

3.1.8
Fix for ticket #630.
3.1.7
Fix for unsigned integer from entropic f64.
3.1.6
Fix for composite-random-source missing argument.
3.1.5
Fix for mrg32k3a bad state values.
3.1.4
Fix for mrg32k3a-pack-state bad index.
3.1.3
Fix for 64-bit fixnums and random integers.
3.1.2
Fix for "entropy-windows" make-entropy-source-crypt.
3.1.1
Moved thread stuff to own extensions.
3.1.0
Changed all random-source-name to lowercase symbols. Changed random-state tags to same as random-source-name. Added new-(random|entropy)-source, @(random|entropy)-source-constructor & (random|entropy)-source-name. Exported registered-(random|entropy)-sources & registered-(random|entropy)-source.
3.0.1
Bug fix for bad external state symbol. Use of 64-bit arithmetic instead of double in C code.
3.0.0
Initial release for Chicken 4

License

Copyright (C) 2010 Kon Lovett. All rights reserved.

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

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

THE SOFTWARE IS PROVIDED ASIS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Does not supercede any restrictions found in the source code.

Contents »