ningshuxia
2022-11-22 4efe844d9bcc03435cbbeb1aedbda5bf6ebf5912
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// <copyright file="HybridMC.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 System.Linq;
using IStation.Numerics.Distributions;
using IStation.Numerics.Random;
 
namespace IStation.Numerics.Statistics.Mcmc
{
    /// <summary>
    /// A hybrid Monte Carlo sampler for multivariate distributions.
    /// </summary>
    public class HybridMC : HybridMCGeneric<double[]>
    {
        /// <summary>
        /// Number of parameters in the density function.
        /// </summary>
        private readonly int _length;
 
        /// <summary>
        /// Distribution to sample momentum from.
        /// </summary>
        private Normal _pDistribution;
 
        /// <summary>
        /// Standard deviations used in the sampling of different components of the
        /// momentum.
        /// </summary>
        private double[] _mpSdv;
 
        /// <summary>
        /// Gets or sets the standard deviations used in the sampling of different components of the
        /// momentum.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">When the length of pSdv is not the same as Length.</exception>
        public double[] MomentumStdDev
        {
            get => (double[])_mpSdv.Clone();
            set
            {
                CheckVariance(value);
                _mpSdv = (double[])value.Clone();
            }
        }
 
        /// <summary>
        /// Constructs a new Hybrid Monte Carlo sampler for a multivariate probability distribution.
        /// The components of the momentum will be sampled from a normal distribution with standard deviation
        /// 1 using the default <see cref="System.Random"/> random
        /// number generator. A three point estimation will be used for differentiation.
        /// This constructor will set the burn interval.
        /// </summary>
        /// <param name="x0">The initial sample.</param>
        /// <param name="pdfLnP">The log density of the distribution we want to sample from.</param>
        /// <param name="frogLeapSteps">Number frog leap simulation steps.</param>
        /// <param name="stepSize">Size of the frog leap simulation steps.</param>
        /// <param name="burnInterval">The number of iterations in between returning samples.</param>
        /// <exception cref="ArgumentOutOfRangeException">When the number of burnInterval iteration is negative.</exception>
        public HybridMC(double[] x0, DensityLn<double[]> pdfLnP, int frogLeapSteps, double stepSize, int burnInterval = 0)
            : this(x0, pdfLnP, frogLeapSteps, stepSize, burnInterval, new double[x0.Length], SystemRandomSource.Default, Grad)
        {
            for (int i = 0; i < _length; i++)
            {
                _mpSdv[i] = 1;
            }
        }
 
        /// <summary>
        /// Constructs a new Hybrid Monte Carlo sampler for a multivariate probability distribution.
        /// The components of the momentum will be sampled from a normal distribution with standard deviation
        /// specified by pSdv using the default <see cref="System.Random"/> random
        /// number generator. A three point estimation will be used for differentiation.
        /// This constructor will set the burn interval.
        /// </summary>
        /// <param name="x0">The initial sample.</param>
        /// <param name="pdfLnP">The log density of the distribution we want to sample from.</param>
        /// <param name="frogLeapSteps">Number frog leap simulation steps.</param>
        /// <param name="stepSize">Size of the frog leap simulation steps.</param>
        /// <param name="burnInterval">The number of iterations in between returning samples.</param>
        /// <param name="pSdv">The standard deviations of the normal distributions that are used to sample
        /// the components of the momentum.</param>
        /// <exception cref="ArgumentOutOfRangeException">When the number of burnInterval iteration is negative.</exception>
        public HybridMC(double[] x0, DensityLn<double[]> pdfLnP, int frogLeapSteps, double stepSize, int burnInterval, double[] pSdv)
            : this(x0, pdfLnP, frogLeapSteps, stepSize, burnInterval, pSdv, SystemRandomSource.Default)
        {
        }
 
        /// <summary>
        /// Constructs a new Hybrid Monte Carlo sampler for a multivariate probability distribution.
        /// The components of the momentum will be sampled from a normal distribution with standard deviation
        /// specified by pSdv using the a random number generator provided by the user.
        /// A three point estimation will be used for differentiation.
        /// This constructor will set the burn interval.
        /// </summary>
        /// <param name="x0">The initial sample.</param>
        /// <param name="pdfLnP">The log density of the distribution we want to sample from.</param>
        /// <param name="frogLeapSteps">Number frog leap simulation steps.</param>
        /// <param name="stepSize">Size of the frog leap simulation steps.</param>
        /// <param name="burnInterval">The number of iterations in between returning samples.</param>
        /// <param name="pSdv">The standard deviations of the normal distributions that are used to sample
        /// the components of the momentum.</param>
        /// <param name="randomSource">Random number generator used for sampling the momentum.</param>
        /// <exception cref="ArgumentOutOfRangeException">When the number of burnInterval iteration is negative.</exception>
        public HybridMC(double[] x0, DensityLn<double[]> pdfLnP, int frogLeapSteps, double stepSize, int burnInterval, double[] pSdv, System.Random randomSource)
            : this(x0, pdfLnP, frogLeapSteps, stepSize, burnInterval, pSdv, randomSource, Grad)
        {
        }
 
        /// <summary>
        /// Constructs a new Hybrid Monte Carlo sampler for a multivariate probability distribution.
        /// The components of the momentum will be sampled from a normal distribution with standard deviations
        /// given by pSdv. This constructor will set the burn interval, the method used for
        /// numerical differentiation and the random number generator.
        /// </summary>
        /// <param name="x0">The initial sample.</param>
        /// <param name="pdfLnP">The log density of the distribution we want to sample from.</param>
        /// <param name="frogLeapSteps">Number frog leap simulation steps.</param>
        /// <param name="stepSize">Size of the frog leap simulation steps.</param>
        /// <param name="burnInterval">The number of iterations in between returning samples.</param>
        /// <param name="pSdv">The standard deviations of the normal distributions that are used to sample
        /// the components of the momentum.</param>
        /// <param name="randomSource">Random number generator used for sampling the momentum.</param>
        /// <param name="diff">The method used for numerical differentiation.</param>
        /// <exception cref="ArgumentOutOfRangeException">When the number of burnInterval iteration is negative.</exception>
        /// <exception cref="ArgumentOutOfRangeException">When the length of pSdv is not the same as x0.</exception>
        public HybridMC(double[] x0, DensityLn<double[]> pdfLnP, int frogLeapSteps, double stepSize, int burnInterval, double[] pSdv, System.Random randomSource, DiffMethod diff)
            : base(x0, pdfLnP, frogLeapSteps, stepSize, burnInterval, randomSource, diff)
        {
            _length = x0.Length;
            MomentumStdDev = pSdv;
 
            Initialize(x0);
 
            Burn(BurnInterval);
        }
 
        /// <summary>
        /// Initialize parameters.
        /// </summary>
        /// <param name="x0">The current location of the sampler.</param>
        private void Initialize(double[] x0)
        {
            Current = (double[])x0.Clone();
            _pDistribution = new Normal(0.0, 1.0, RandomSource);
        }
 
        /// <summary>
        /// Checking that the location and the momentum are of the same dimension and that each component is positive.
        /// </summary>
        /// <param name="pSdv">The standard deviations used for sampling the momentum.</param>
        /// <exception cref="ArgumentOutOfRangeException">When the length of pSdv is not the same as Length or if any
        /// component is negative.</exception>
        /// <exception cref="ArgumentNullException">When pSdv is null.</exception>
        private void CheckVariance(double[] pSdv)
        {
            if (pSdv == null)
            {
                throw new ArgumentNullException(nameof(pSdv), "Standard deviation cannot be null.");
            }
            if (pSdv.Length != _length)
            {
                throw new ArgumentOutOfRangeException(nameof(pSdv), "Standard deviation of momentum must have same length as sample.");
            }
            if (pSdv.Any(sdv => sdv < 0))
            {
                throw new ArgumentOutOfRangeException(nameof(pSdv), "Standard deviation must be positive.");
            }
        }
 
        /// <summary>
        /// Use for copying objects in the Burn method.
        /// </summary>
        /// <param name="source">The source of copying.</param>
        /// <returns>A copy of the source object.</returns>
        protected override double[] Copy(double[] source)
        {
            var destination = new double[_length];
            Array.Copy(source, 0, destination, 0, _length);
            return destination;
        }
 
        /// <summary>
        /// Use for creating temporary objects in the Burn method.
        /// </summary>
        /// <returns>An object of type T.</returns>
        protected override double[] Create()
        {
            return new double[_length];
        }
 
        ///<inheritdoc/>
        protected override void DoAdd(ref double[] first, double factor, double[] second)
        {
            for (int i = 0; i < _length; i++)
            {
                first[i] += factor * second[i];
            }
        }
 
        /// <inheritdoc/>
        protected override void DoSubtract(ref double[] first, double factor, double[] second)
        {
            for (int i = 0; i < _length; i++)
            {
                first[i] -= factor * second[i];
            }
        }
 
        /// <inheritdoc/>
        protected override double DoProduct(double[] first, double[] second)
        {
            double prod = 0;
            for (int i = 0; i < _length; i++)
            {
                prod += first[i] * second[i];
            }
            return prod;
        }
 
        /// <summary>
        /// Samples the momentum from a normal distribution.
        /// </summary>
        /// <param name="p">The momentum to be randomized.</param>
        protected override void RandomizeMomentum(ref double[] p)
        {
            for (int j = 0; j < _length; j++)
            {
                p[j] = _mpSdv[j] * _pDistribution.Sample();
            }
        }
 
        /// <summary>
        /// The default method used for computing the gradient. Uses a simple three point estimation.
        /// </summary>
        /// <param name="function">Function which the gradient is to be evaluated.</param>
        /// <param name="x">The location where the gradient is to be evaluated.</param>
        /// <returns>The gradient of the function at the point x.</returns>
        static double[] Grad(DensityLn<double[]> function, double[] x)
        {
            int length = x.Length;
            var returnValue = new double[length];
            var increment = new double[length];
            var decrement = new double[length];
 
            Array.Copy(x, 0, increment, 0, length);
            Array.Copy(x, 0, decrement, 0, length);
 
            for (int i = 0; i < length; i++)
            {
                double y = x[i];
                double h = Math.Max(10e-4, (10e-7) * y);
                increment[i] += h;
                decrement[i] -= h;
                returnValue[i] = (function(increment) - function(decrement)) / (2 * h);
                increment[i] = y;
                decrement[i] = y;
            }
 
            return returnValue;
        }
    }
}