ningshuxia
2022-12-12 e78f5936fee9ab4fff600515bb20a41a28f329c4
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// <copyright file="Control.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-2018 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 System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using IStation.Numerics.Providers.SparseSolver;
using IStation.Numerics.Providers.FourierTransform;
using IStation.Numerics.Providers.LinearAlgebra;
 
namespace IStation.Numerics
{
    /// <summary>
    /// Sets parameters for the library.
    /// </summary>
    public static class Control
    {
        static int _maxDegreeOfParallelism;
        static int _parallelizeOrder;
        static int _parallelizeElements;
        static string _nativeProviderHintPath;
 
        static Control()
        {
            ConfigureAuto();
        }
 
        public static void ConfigureAuto()
        {
            // Random Numbers & Distributions
            CheckDistributionParameters = true;
 
            // Parallelization & Threading
            ThreadSafeRandomNumberGenerators = true;
            _maxDegreeOfParallelism = Environment.ProcessorCount;
            _parallelizeOrder = 64;
            _parallelizeElements = 300;
            TaskScheduler = TaskScheduler.Default;
        }
 
        public static void UseManaged()
        {
            LinearAlgebraControl.UseManaged();
            FourierTransformControl.UseManaged();
            SparseSolverControl.UseManaged();
        }
 
        public static void UseManagedReference()
        {
            LinearAlgebraControl.UseManagedReference();
            FourierTransformControl.UseManaged();
            SparseSolverControl.UseManaged();
        }
 
        /// <summary>
        /// Use a specific provider if configured, e.g. using
        /// environment variables, or fall back to the best providers.
        /// </summary>
        public static void UseDefaultProviders()
        {
            if (AppSwitches.DisableNativeProviders)
            {
                UseManaged();
                return;
            }
 
            LinearAlgebraControl.UseDefault();
            FourierTransformControl.UseDefault();
            SparseSolverControl.UseDefault();
        }
 
        /// <summary>
        /// Use the best provider available.
        /// </summary>
        public static void UseBestProviders()
        {
            if (AppSwitches.DisableNativeProviders || AppSwitches.DisableNativeProviderProbing)
            {
                UseManaged();
                return;
            }
 
            LinearAlgebraControl.UseBest();
            FourierTransformControl.UseBest();
            SparseSolverControl.UseBest();
        }
 
#if NATIVE
 
        /// <summary>
        /// Use the Intel MKL native provider for linear algebra.
        /// Throws if it is not available or failed to initialize, in which case the previous provider is still active.
        /// </summary>
        public static void UseNativeMKL()
        {
            LinearAlgebraControl.UseNativeMKL();
            FourierTransformControl.UseNativeMKL();
            SparseSolverControl.UseNativeMKL();
        }
 
        /// <summary>
        /// Use the Intel MKL native provider for linear algebra, with the specified configuration parameters.
        /// Throws if it is not available or failed to initialize, in which case the previous provider is still active.
        /// </summary>
        [CLSCompliant(false)]
        public static void UseNativeMKL(
            Providers.Common.Mkl.MklConsistency consistency = Providers.Common.Mkl.MklConsistency.Auto,
            Providers.Common.Mkl.MklPrecision precision = Providers.Common.Mkl.MklPrecision.Double,
            Providers.Common.Mkl.MklAccuracy accuracy = Providers.Common.Mkl.MklAccuracy.High)
        {
            LinearAlgebraControl.UseNativeMKL(consistency, precision, accuracy);
            FourierTransformControl.UseNativeMKL();
            SparseSolverControl.UseNativeMKL();
        }
 
        /// <summary>
        /// Try to use the Intel MKL native provider for linear algebra.
        /// </summary>
        /// <returns>
        /// True if the provider was found and initialized successfully.
        /// False if it failed and the previous provider is still active.
        /// </returns>
        public static bool TryUseNativeMKL()
        {
            bool linearAlgebra = LinearAlgebraControl.TryUseNativeMKL();
            bool fourierTransform = FourierTransformControl.TryUseNativeMKL();
            bool directSparseSolver = SparseSolverControl.TryUseNativeMKL();
            return linearAlgebra || fourierTransform || directSparseSolver;
        }
 
        /// <summary>
        /// Use the Nvidia CUDA native provider for linear algebra.
        /// Throws if it is not available or failed to initialize, in which case the previous provider is still active.
        /// </summary>
        public static void UseNativeCUDA()
        {
            LinearAlgebraControl.UseNativeCUDA();
        }
 
        /// <summary>
        /// Try to use the Nvidia CUDA native provider for linear algebra.
        /// </summary>
        /// <returns>
        /// True if the provider was found and initialized successfully.
        /// False if it failed and the previous provider is still active.
        /// </returns>
        public static bool TryUseNativeCUDA()
        {
            bool linearAlgebra = LinearAlgebraControl.TryUseNativeCUDA();
            return linearAlgebra;
        }
 
        /// <summary>
        /// Use the OpenBLAS native provider for linear algebra.
        /// Throws if it is not available or failed to initialize, in which case the previous provider is still active.
        /// </summary>
        public static void UseNativeOpenBLAS()
        {
            LinearAlgebraControl.UseNativeOpenBLAS();
        }
 
        /// <summary>
        /// Try to use the OpenBLAS native provider for linear algebra.
        /// </summary>
        /// <returns>
        /// True if the provider was found and initialized successfully.
        /// False if it failed and the previous provider is still active.
        /// </returns>
        public static bool TryUseNativeOpenBLAS()
        {
            bool linearAlgebra = LinearAlgebraControl.TryUseNativeOpenBLAS();
            return linearAlgebra;
        }
 
        /// <summary>
        /// Try to use any available native provider in an undefined order.
        /// </summary>
        /// <returns>
        /// True if one of the native providers was found and successfully initialized.
        /// False if it failed and the previous provider is still active.
        /// </returns>
        public static bool TryUseNative()
        {
            if (AppSwitches.DisableNativeProviders || AppSwitches.DisableNativeProviderProbing)
            {
                return false;
            }
 
            bool linearAlgebra = LinearAlgebraControl.TryUseNative();
            bool fourierTransform = FourierTransformControl.TryUseNative();
            bool directSparseSolver = SparseSolverControl.TryUseNative();
            return linearAlgebra || fourierTransform || directSparseSolver;
        }
#endif
 
        public static void FreeResources()
        {
            LinearAlgebraControl.FreeResources();
            FourierTransformControl.FreeResources();
            SparseSolverControl.FreeResources();
        }
 
        public static void UseSingleThread()
        {
            _maxDegreeOfParallelism = 1;
            ThreadSafeRandomNumberGenerators = false;
 
            LinearAlgebraControl.Provider.InitializeVerify();
            FourierTransformControl.Provider.InitializeVerify();
            SparseSolverControl.Provider.InitializeVerify();
        }
 
        public static void UseMultiThreading()
        {
            _maxDegreeOfParallelism = Environment.ProcessorCount;
            ThreadSafeRandomNumberGenerators = true;
 
            LinearAlgebraControl.Provider.InitializeVerify();
            FourierTransformControl.Provider.InitializeVerify();
            SparseSolverControl.Provider.InitializeVerify();
        }
 
        /// <summary>
        /// Gets or sets a value indicating whether the distribution classes check validate each parameter.
        /// For the multivariate distributions this could involve an expensive matrix factorization.
        /// The default setting of this property is <c>true</c>.
        /// </summary>
        public static bool CheckDistributionParameters { get; set; }
 
        /// <summary>
        /// Gets or sets a value indicating whether to use thread safe random number generators (RNG).
        /// Thread safe RNG about two and half time slower than non-thread safe RNG.
        /// </summary>
        /// <value>
        ///     <c>true</c> to use thread safe random number generators ; otherwise, <c>false</c>.
        /// </value>
        public static bool ThreadSafeRandomNumberGenerators { get; set; }
 
        /// <summary>
        /// Optional path to try to load native provider binaries from.
        /// </summary>
        public static string NativeProviderPath
        {
            get => _nativeProviderHintPath;
            set
            {
                _nativeProviderHintPath = value;
                LinearAlgebraControl.HintPath = value;
                FourierTransformControl.HintPath = value;
                SparseSolverControl.HintPath = value;
            }
        }
 
        /// <summary>
        /// Gets or sets a value indicating how many parallel worker threads shall be used
        /// when parallelization is applicable.
        /// </summary>
        /// <remarks>Default to the number of processor cores, must be between 1 and 1024 (inclusive).</remarks>
        public static int MaxDegreeOfParallelism
        {
            get => _maxDegreeOfParallelism;
            set
            {
                _maxDegreeOfParallelism = Math.Max(1, Math.Min(1024, value));
 
                // Reinitialize providers:
                LinearAlgebraControl.Provider.InitializeVerify();
                FourierTransformControl.Provider.InitializeVerify();
                SparseSolverControl.Provider.InitializeVerify();
            }
        }
 
        /// <summary>
        /// Gets or sets the TaskScheduler used to schedule the worker tasks.
        /// </summary>
        public static TaskScheduler TaskScheduler { get; set; }
 
        /// <summary>
        /// Gets or sets the order of the matrix when linear algebra provider
        /// must calculate multiply in parallel threads.
        /// </summary>
        /// <value>The order. Default 64, must be at least 3.</value>
        internal static int ParallelizeOrder
        {
            get => _parallelizeOrder;
            set => _parallelizeOrder = Math.Max(3, value);
        }
 
        /// <summary>
        /// Gets or sets the number of elements a vector or matrix
        /// must contain before we multiply threads.
        /// </summary>
        /// <value>Number of elements. Default 300, must be at least 3.</value>
        internal static int ParallelizeElements
        {
            get => _parallelizeElements;
            set => _parallelizeElements = Math.Max(3, value);
        }
 
        public static string Describe()
        {
#if NET40
            var versionAttribute = typeof(Control).Assembly
                .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false)
                .OfType<AssemblyInformationalVersionAttribute>()
                .FirstOrDefault();
#else
            var versionAttribute = typeof(Control).GetTypeInfo().Assembly.GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute;
#endif
 
            var sb = new StringBuilder();
            sb.AppendLine("Math.NET Numerics Configuration:");
            sb.AppendLine($"Version {versionAttribute?.InformationalVersion}");
#if NETSTANDARD1_3
            sb.AppendLine("Built for .Net Standard 1.3");
#elif NETSTANDARD2_0
            sb.AppendLine("Built for .Net Standard 2.0");
#elif NET40
            sb.AppendLine("Built for .Net Framework 4.0");
#elif NET461
            sb.AppendLine("Built for .Net Framework 4.6.1");
#endif
#if !NATIVE
            sb.AppendLine("No Native Provider Support");
#endif
            sb.AppendLine($"Linear Algebra Provider: {LinearAlgebraControl.Provider}");
            sb.AppendLine($"Fourier Transform Provider: {FourierTransformControl.Provider}");
            sb.AppendLine($"Sparse Solver Provider: {SparseSolverControl.Provider}");
            sb.AppendLine($"Max Degree of Parallelism: {MaxDegreeOfParallelism}");
            sb.AppendLine($"Parallelize Elements: {ParallelizeElements}");
            sb.AppendLine($"Parallelize Order: {ParallelizeOrder}");
            sb.AppendLine($"Check Distribution Parameters: {CheckDistributionParameters}");
            sb.AppendLine($"Thread-Safe RNGs: {ThreadSafeRandomNumberGenerators}");
#if NETSTANDARD1_3 || NETSTANDARD2_0
            // This would also work in .Net 4.0, but we don't want the dependency just for that.
            sb.AppendLine($"Operating System: {RuntimeInformation.OSDescription}");
            sb.AppendLine($"Operating System Architecture: {RuntimeInformation.OSArchitecture}");
            sb.AppendLine($"Framework: {RuntimeInformation.FrameworkDescription}");
            sb.AppendLine($"Process Architecture: {RuntimeInformation.ProcessArchitecture}");
#else
            sb.AppendLine($"Operating System: {Environment.OSVersion}");
            sb.AppendLine($"Framework: {Environment.Version}");
#endif
            return sb.ToString();
        }
    }
}