ningshuxia
2022-12-01 ad494f13d2ddf31f142cf7fb908b3a6e90395a1a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
// <copyright file="MCMCSampler.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2010 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
 
using System;
using IStation.Numerics.Random;
 
namespace IStation.Numerics.Statistics.Mcmc
{
    /// <summary>
    /// A method which samples datapoints from a proposal distribution. The implementation of this sampler
    /// is stateless: no variables are saved between two calls to Sample. This proposal is different from
    /// <seealso cref="LocalProposalSampler{T}"/> in that it doesn't take any parameters; it samples random
    /// variables from the whole domain.
    /// </summary>
    /// <typeparam name="T">The type of the datapoints.</typeparam>
    /// <returns>A sample from the proposal distribution.</returns>
    public delegate T GlobalProposalSampler<out T>();
 
    /// <summary>
    /// A method which samples datapoints from a proposal distribution given an initial sample. The implementation
    /// of this sampler is stateless: no variables are saved between two calls to Sample. This proposal is different from
    /// <seealso cref="GlobalProposalSampler{T}"/> in that it samples locally around an initial point. In other words, it
    /// makes a small local move rather than producing a global sample from the proposal.
    /// </summary>
    /// <typeparam name="T">The type of the datapoints.</typeparam>
    /// <param name="init">The initial sample.</param>
    /// <returns>A sample from the proposal distribution.</returns>
    public delegate T LocalProposalSampler<T>(T init);
 
    /// <summary>
    /// A function which evaluates a density.
    /// </summary>
    /// <typeparam name="T">The type of data the distribution is over.</typeparam>
    /// <param name="sample">The sample we want to evaluate the density for.</param>
    public delegate double Density<in T>(T sample);
 
    /// <summary>
    /// A function which evaluates a log density.
    /// </summary>
    /// <typeparam name="T">The type of data the distribution is over.</typeparam>
    /// <param name="sample">The sample we want to evaluate the log density for.</param>
    public delegate double DensityLn<in T>(T sample);
 
    /// <summary>
    /// A function which evaluates the log of a transition kernel probability.
    /// </summary>
    /// <typeparam name="T">The type for the space over which this transition kernel is defined.</typeparam>
    /// <param name="to">The new state in the transition.</param>
    /// <param name="from">The previous state in the transition.</param>
    /// <returns>The log probability of the transition.</returns>
    public delegate double TransitionKernelLn<in T>(T to, T from);
 
    /// <summary>
    /// The interface which every sampler must implement.
    /// </summary>
    /// <typeparam name="T">The type of samples this sampler produces.</typeparam>
    public abstract class McmcSampler<T>
    {
        /// <summary>
        /// The random number generator for this class.
        /// </summary>
        private System.Random _randomNumberGenerator;
 
        /// <summary>
        /// Keeps track of the number of accepted samples.
        /// </summary>
        protected int Accepts;
 
        /// <summary>
        /// Keeps track of the number of calls to the proposal sampler.
        /// </summary>
        protected int Samples;
 
        /// <summary>
        /// Initializes a new instance of the <see cref="McmcSampler{T}"/> class.
        /// </summary>
        /// <remarks>Thread safe instances are two and half times slower than non-thread
        /// safe classes.</remarks>
        protected McmcSampler()
        {
            Accepts = 0;
            Samples = 0;
            RandomSource = SystemRandomSource.Default;
        }
 
        /// <summary>
        /// Gets or sets the random number generator.
        /// </summary>
        /// <exception cref="ArgumentNullException">When the random number generator is null.</exception>
        public System.Random RandomSource
        {
            get => _randomNumberGenerator;
            set => _randomNumberGenerator = value ?? SystemRandomSource.Default;
        }
 
        /// <summary>
        /// Returns one sample.
        /// </summary>
        public abstract T Sample();
 
        /// <summary>
        /// Returns a number of samples.
        /// </summary>
        /// <param name="n">The number of samples we want.</param>
        /// <returns>An array of samples.</returns>
        public virtual T[] Sample(int n)
        {
            var ret = new T[n];
            for (int i = 0; i < n; i++)
            {
                ret[i] = Sample();
            }
            return ret;
        }
 
        /// <summary>
        /// Gets the acceptance rate of the sampler.
        /// </summary>
        public double AcceptanceRate => Accepts / (double)Samples;
    }
}