Browse Source

Isolate native provider implementations out of Numerics

pull/769/head
Christoph Ruegg 5 years ago
parent
commit
796923641c
  1. 24
      MathNet.Numerics.sln
  2. 3
      MathNet.Numerics.sln.DotSettings
  3. 8
      build.fsx
  4. 1
      src/Benchmark/Benchmark.csproj
  5. 10
      src/Benchmark/LinearAlgebra/DenseMatrixProduct.cs
  6. 5
      src/Benchmark/LinearAlgebra/DenseVector.cs
  7. 4
      src/Benchmark/Transforms/FFT.cs
  8. 3
      src/Numerics.Tests/Numerics.Tests.CUDA.csproj
  9. 3
      src/Numerics.Tests/Numerics.Tests.MKL.csproj
  10. 3
      src/Numerics.Tests/Numerics.Tests.OpenBLAS.csproj
  11. 24
      src/Numerics.Tests/Providers/SparseSolver/double/SparseSolverProviderTests.cs
  12. 3
      src/Numerics.Tests/StatisticsTests/StatisticsTests.cs
  13. 20
      src/Numerics.Tests/UseLinearAlgebraProvider.cs
  14. 12
      src/Numerics/AppSwitches.cs
  15. 23
      src/Numerics/Control.cs
  16. 81
      src/Numerics/Providers/FourierTransform/FourierTransformControl.cs
  17. 36
      src/Numerics/Providers/IProviderCreator.cs
  18. 1092
      src/Numerics/Providers/LinearAlgebra/Acml/AcmlLinearAlgebraProvider.Complex.cs
  19. 1095
      src/Numerics/Providers/LinearAlgebra/Acml/AcmlLinearAlgebraProvider.Complex32.cs
  20. 1096
      src/Numerics/Providers/LinearAlgebra/Acml/AcmlLinearAlgebraProvider.Double.cs
  21. 1095
      src/Numerics/Providers/LinearAlgebra/Acml/AcmlLinearAlgebraProvider.Single.cs
  22. 263
      src/Numerics/Providers/LinearAlgebra/Acml/SafeNativeMethods.cs
  23. 143
      src/Numerics/Providers/LinearAlgebra/LinearAlgebraControl.cs
  24. 2
      src/Numerics/Providers/LinearAlgebra/Managed/ManagedLinearAlgebraProvider.Complex.cs
  25. 2
      src/Numerics/Providers/LinearAlgebra/Managed/ManagedLinearAlgebraProvider.Complex32.cs
  26. 2
      src/Numerics/Providers/LinearAlgebra/Managed/ManagedLinearAlgebraProvider.Double.cs
  27. 2
      src/Numerics/Providers/LinearAlgebra/Managed/ManagedLinearAlgebraProvider.Single.cs
  28. 2
      src/Numerics/Providers/LinearAlgebra/Managed/ManagedLinearAlgebraProvider.cs
  29. 88
      src/Numerics/Providers/ProviderProbe.cs
  30. 2
      src/Numerics/Providers/SparseSolver/Managed/ManagedSparseSolverProvider.cs
  31. 95
      src/Numerics/Providers/SparseSolver/SparseSolverControl.cs
  32. 80
      src/Providers.CUDA/ArrayExtensions.cs
  33. 44
      src/Providers.CUDA/Compatibility.cs
  34. 60
      src/Providers.CUDA/CudaControl.cs
  35. 6
      src/Providers.CUDA/CudaProvider.cs
  36. 6
      src/Providers.CUDA/CudaProviderCapabilities.cs
  37. 93
      src/Providers.CUDA/LinearAlgebra/CudaLinearAlgebraControl.cs
  38. 8
      src/Providers.CUDA/LinearAlgebra/CudaLinearAlgebraProvider.Complex.cs
  39. 8
      src/Providers.CUDA/LinearAlgebra/CudaLinearAlgebraProvider.Complex32.cs
  40. 8
      src/Providers.CUDA/LinearAlgebra/CudaLinearAlgebraProvider.Double.cs
  41. 8
      src/Providers.CUDA/LinearAlgebra/CudaLinearAlgebraProvider.Single.cs
  42. 10
      src/Providers.CUDA/LinearAlgebra/CudaLinearAlgebraProvider.cs
  43. 6
      src/Providers.CUDA/NativeProviderLoader.cs
  44. 34
      src/Providers.CUDA/Providers.CUDA.csproj
  45. 6
      src/Providers.CUDA/SafeNativeMethods.cs
  46. 1
      src/Providers.CUDA/paket.references
  47. 80
      src/Providers.MKL/ArrayExtensions.cs
  48. 44
      src/Providers.MKL/Compatibility.cs
  49. 93
      src/Providers.MKL/FourierTransform/MklFourierTransformControl.cs
  50. 8
      src/Providers.MKL/FourierTransform/MklFourierTransformProvider.cs
  51. 102
      src/Providers.MKL/LinearAlgebra/MklLinearAlgebraControl.cs
  52. 8
      src/Providers.MKL/LinearAlgebra/MklLinearAlgebraProvider.Complex.cs
  53. 8
      src/Providers.MKL/LinearAlgebra/MklLinearAlgebraProvider.Complex32.cs
  54. 8
      src/Providers.MKL/LinearAlgebra/MklLinearAlgebraProvider.Double.cs
  55. 8
      src/Providers.MKL/LinearAlgebra/MklLinearAlgebraProvider.Single.cs
  56. 10
      src/Providers.MKL/LinearAlgebra/MklLinearAlgebraProvider.cs
  57. 80
      src/Providers.MKL/MklControl.cs
  58. 7
      src/Providers.MKL/MklProvider.cs
  59. 6
      src/Providers.MKL/MklProviderCapabilities.cs
  60. 6
      src/Providers.MKL/MklProviderPrecision.cs
  61. 252
      src/Providers.MKL/NativeProviderLoader.cs
  62. 34
      src/Providers.MKL/Providers.MKL.csproj
  63. 6
      src/Providers.MKL/SafeNativeMethods.cs
  64. 93
      src/Providers.MKL/SparseSolver/MklSparseSolverControl.cs
  65. 10
      src/Providers.MKL/SparseSolver/MklSparseSolverProvider.Complex.cs
  66. 10
      src/Providers.MKL/SparseSolver/MklSparseSolverProvider.Complex32.cs
  67. 10
      src/Providers.MKL/SparseSolver/MklSparseSolverProvider.Double.cs
  68. 9
      src/Providers.MKL/SparseSolver/MklSparseSolverProvider.Single.cs
  69. 13
      src/Providers.MKL/SparseSolver/MklSparseSolverProvider.cs
  70. 1
      src/Providers.MKL/paket.references
  71. 80
      src/Providers.OpenBLAS/ArrayExtensions.cs
  72. 44
      src/Providers.OpenBLAS/Compatibility.cs
  73. 93
      src/Providers.OpenBLAS/LinearAlgebra/OpenBlasLinearAlgebraControl.cs
  74. 8
      src/Providers.OpenBLAS/LinearAlgebra/OpenBlasLinearAlgebraProvider.Complex.cs
  75. 8
      src/Providers.OpenBLAS/LinearAlgebra/OpenBlasLinearAlgebraProvider.Complex32.cs
  76. 8
      src/Providers.OpenBLAS/LinearAlgebra/OpenBlasLinearAlgebraProvider.Double.cs
  77. 8
      src/Providers.OpenBLAS/LinearAlgebra/OpenBlasLinearAlgebraProvider.Single.cs
  78. 10
      src/Providers.OpenBLAS/LinearAlgebra/OpenBlasLinearAlgebraProvider.cs
  79. 252
      src/Providers.OpenBLAS/NativeProviderLoader.cs
  80. 60
      src/Providers.OpenBLAS/OpenBlasControl.cs
  81. 6
      src/Providers.OpenBLAS/OpenBlasProvider.cs
  82. 6
      src/Providers.OpenBLAS/OpenBlasProviderCapabilities.cs
  83. 34
      src/Providers.OpenBLAS/Providers.OpenBLAS.csproj
  84. 8
      src/Providers.OpenBLAS/SafeNativeMethods.cs
  85. 1
      src/Providers.OpenBLAS/paket.references

24
MathNet.Numerics.sln

@ -70,6 +70,12 @@ ProjectSection(SolutionItems) = preProject
README.md = README.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Providers.MKL", "src\Providers.MKL\Providers.MKL.csproj", "{0B5FAFAA-4286-4D92-B5AB-CBA75ADDA0BB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Providers.CUDA", "src\Providers.CUDA\Providers.CUDA.csproj", "{3C0D4A87-CC89-43B6-B028-4122099D692F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Providers.OpenBLAS", "src\Providers.OpenBLAS\Providers.OpenBLAS.csproj", "{FBE18DF3-EEC3-4812-9FB4-B9EA6EAEC029}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -113,6 +119,24 @@ Global
{82444930-9FD7-41B6-B476-CCE41A0C0A0B}.Release|Any CPU.Build.0 = Release|Any CPU
{82444930-9FD7-41B6-B476-CCE41A0C0A0B}.Release-Signed|Any CPU.ActiveCfg = Release|Any CPU
{82444930-9FD7-41B6-B476-CCE41A0C0A0B}.Release-Signed|Any CPU.Build.0 = Release|Any CPU
{0B5FAFAA-4286-4D92-B5AB-CBA75ADDA0BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0B5FAFAA-4286-4D92-B5AB-CBA75ADDA0BB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0B5FAFAA-4286-4D92-B5AB-CBA75ADDA0BB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0B5FAFAA-4286-4D92-B5AB-CBA75ADDA0BB}.Release|Any CPU.Build.0 = Release|Any CPU
{0B5FAFAA-4286-4D92-B5AB-CBA75ADDA0BB}.Release-Signed|Any CPU.ActiveCfg = Debug|Any CPU
{0B5FAFAA-4286-4D92-B5AB-CBA75ADDA0BB}.Release-Signed|Any CPU.Build.0 = Debug|Any CPU
{3C0D4A87-CC89-43B6-B028-4122099D692F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3C0D4A87-CC89-43B6-B028-4122099D692F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3C0D4A87-CC89-43B6-B028-4122099D692F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3C0D4A87-CC89-43B6-B028-4122099D692F}.Release|Any CPU.Build.0 = Release|Any CPU
{3C0D4A87-CC89-43B6-B028-4122099D692F}.Release-Signed|Any CPU.ActiveCfg = Debug|Any CPU
{3C0D4A87-CC89-43B6-B028-4122099D692F}.Release-Signed|Any CPU.Build.0 = Debug|Any CPU
{FBE18DF3-EEC3-4812-9FB4-B9EA6EAEC029}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FBE18DF3-EEC3-4812-9FB4-B9EA6EAEC029}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FBE18DF3-EEC3-4812-9FB4-B9EA6EAEC029}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FBE18DF3-EEC3-4812-9FB4-B9EA6EAEC029}.Release|Any CPU.Build.0 = Release|Any CPU
{FBE18DF3-EEC3-4812-9FB4-B9EA6EAEC029}.Release-Signed|Any CPU.ActiveCfg = Debug|Any CPU
{FBE18DF3-EEC3-4812-9FB4-B9EA6EAEC029}.Release-Signed|Any CPU.Build.0 = Debug|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

3
MathNet.Numerics.sln.DotSettings

@ -59,17 +59,20 @@ OTHER DEALINGS IN THE SOFTWARE.
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=FFT/@EntryIndexedValue">FFT</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=ILU/@EntryIndexedValue">ILU</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=ILUTP/@EntryIndexedValue">ILUTP</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=LA/@EntryIndexedValue">LA</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=LU/@EntryIndexedValue">LU</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=MAE/@EntryIndexedValue">MAE</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=MC/@EntryIndexedValue">MC</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=MCMC/@EntryIndexedValue">MCMC</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=MILU/@EntryIndexedValue">MILU</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=MKL/@EntryIndexedValue">MKL</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=MSE/@EntryIndexedValue">MSE</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=PDF/@EntryIndexedValue">PDF</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=QR/@EntryIndexedValue">QR</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SAD/@EntryIndexedValue">SAD</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SAS/@EntryIndexedValue">SAS</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SPSS/@EntryIndexedValue">SPSS</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SS/@EntryIndexedValue">SS</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SSD/@EntryIndexedValue">SSD</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SVD/@EntryIndexedValue">SVD</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=TFQMR/@EntryIndexedValue">TFQMR</s:String>

8
build.fsx

@ -51,10 +51,16 @@ let numericsNuGetPackage = nugetPackage "MathNet.Numerics" numericsRelease
let numericsFSharpNuGetPackage = nugetPackage "MathNet.Numerics.FSharp" numericsRelease
let numericsStrongNameNuGetPackage = nugetPackage "MathNet.Numerics.Signed" numericsRelease
let numericsFSharpStrongNameNuGetPackage = nugetPackage "MathNet.Numerics.FSharp.Signed" numericsRelease
let numericsProvidersMklNuGetPackage = nugetPackage "MathNet.Numerics.Providers.MKL" numericsRelease
let numericsProvidersOpenBlasNuGetPackage = nugetPackage "MathNet.Numerics.Providers.OpenBLAS" numericsRelease
let numericsProvidersCudaNuGetPackage = nugetPackage "MathNet.Numerics.Providers.CUDA" numericsRelease
let numericsProject = project "MathNet.Numerics" "src/Numerics/Numerics.csproj" [numericsNuGetPackage; numericsStrongNameNuGetPackage]
let numericsFsharpProject = project "MathNet.Numerics.FSharp" "src/FSharp/FSharp.fsproj" [numericsFSharpNuGetPackage; numericsFSharpStrongNameNuGetPackage]
let numericsSolution = solution "Numerics" "MathNet.Numerics.sln" [numericsProject; numericsFsharpProject] [numericsZipPackage; numericsStrongNameZipPackage]
let numericsProvidersMklProject = project "MathNet.Numerics.Providers.MKL" "src/Providers.MKL/Providers.MKL.csproj" [numericsProvidersMklNuGetPackage]
let numericsProvidersOpenBlasProject = project "MathNet.Numerics.Providers.OpenBLAS" "src/Providers.OpenBLAS/Providers.OpenBLAS.csproj" [numericsProvidersOpenBlasNuGetPackage]
let numericsProvidersCudaProject = project "MathNet.Numerics.Providers.CUDA" "src/Providers.CUDA/Providers.CUDA.csproj" [numericsProvidersCudaNuGetPackage]
let numericsSolution = solution "Numerics" "MathNet.Numerics.sln" [numericsProject; numericsFsharpProject; numericsProvidersMklProject; numericsProvidersOpenBlasProject; numericsProvidersCudaProject] [numericsZipPackage; numericsStrongNameZipPackage]
// DATA EXTENSION PACKAGES

1
src/Benchmark/Benchmark.csproj

@ -16,6 +16,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Numerics\Numerics.csproj" />
<ProjectReference Include="..\Providers.MKL\Providers.MKL.csproj" />
</ItemGroup>
<Import Project="..\..\.paket\Paket.Restore.targets" />
</Project>

10
src/Benchmark/LinearAlgebra/DenseMatrixProduct.cs

@ -5,7 +5,7 @@ using BenchmarkDotNet.Environments;
using BenchmarkDotNet.Jobs;
using MathNet.Numerics;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.Providers.Common.Mkl;
using MathNet.Numerics.Providers.MKL;
namespace Benchmark.LinearAlgebra
{
@ -77,16 +77,16 @@ namespace Benchmark.LinearAlgebra
Control.UseManaged();
break;
case ProviderId.NativeMKLAutoHigh:
Control.UseNativeMKL(MklConsistency.Auto, MklPrecision.Double, MklAccuracy.High);
MklControl.UseNativeMKL(MklConsistency.Auto, MklPrecision.Double, MklAccuracy.High);
break;
case ProviderId.NativeMKLAutoLow:
Control.UseNativeMKL(MklConsistency.Auto, MklPrecision.Double, MklAccuracy.Low);
MklControl.UseNativeMKL(MklConsistency.Auto, MklPrecision.Double, MklAccuracy.Low);
break;
case ProviderId.NativeMKLAvx2High:
Control.UseNativeMKL(MklConsistency.AVX2, MklPrecision.Double, MklAccuracy.High);
MklControl.UseNativeMKL(MklConsistency.AVX2, MklPrecision.Double, MklAccuracy.High);
break;
case ProviderId.NativeMKLAvx2Low:
Control.UseNativeMKL(MklConsistency.AVX2, MklPrecision.Double, MklAccuracy.Low);
MklControl.UseNativeMKL(MklConsistency.AVX2, MklPrecision.Double, MklAccuracy.Low);
break;
}
}

5
src/Benchmark/LinearAlgebra/DenseVector.cs

@ -3,9 +3,8 @@ using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Environments;
using BenchmarkDotNet.Jobs;
using MathNet.Numerics;
using MathNet.Numerics.Providers.Common.Mkl;
using MathNet.Numerics.Providers.LinearAlgebra;
using MathNet.Numerics.Providers.MKL;
using Complex = System.Numerics.Complex;
namespace Benchmark.LinearAlgebra
@ -57,7 +56,7 @@ namespace Benchmark.LinearAlgebra
Control.UseManagedReference();
break;
case ProviderId.NativeMKL:
Control.UseNativeMKL(MklConsistency.Auto, MklPrecision.Double, MklAccuracy.High);
MklControl.UseNativeMKL(MklConsistency.Auto, MklPrecision.Double, MklAccuracy.High);
break;
}

4
src/Benchmark/Transforms/FFT.cs

@ -4,7 +4,7 @@ using BenchmarkDotNet.Environments;
using BenchmarkDotNet.Jobs;
using MathNet.Numerics;
using MathNet.Numerics.IntegralTransforms;
using MathNet.Numerics.Providers.Common.Mkl;
using MathNet.Numerics.Providers.MKL;
using Complex = System.Numerics.Complex;
namespace Benchmark.Transforms
@ -47,7 +47,7 @@ namespace Benchmark.Transforms
Control.UseManaged();
break;
case ProviderId.NativeMKL:
Control.UseNativeMKL(MklConsistency.Auto, MklPrecision.Double, MklAccuracy.High);
MklControl.UseNativeMKL(MklConsistency.Auto, MklPrecision.Double, MklAccuracy.High);
break;
}

3
src/Numerics.Tests/Numerics.Tests.CUDA.csproj

@ -3,7 +3,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<GenerateProgramFile>false</GenerateProgramFile>
<TargetFrameworks>net461;netcoreapp3.1</TargetFrameworks>
<TargetFrameworks>net5.0;net48</TargetFrameworks>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<AssemblyName>MathNet.Numerics.Tests.CUDA</AssemblyName>
<RootNamespace>MathNet.Numerics.Tests</RootNamespace>
@ -23,6 +23,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Numerics\Numerics.csproj" />
<ProjectReference Include="..\Providers.CUDA\Providers.CUDA.csproj" />
<ProjectReference Include="..\TestData\TestData.csproj" />
</ItemGroup>
<ItemGroup>

3
src/Numerics.Tests/Numerics.Tests.MKL.csproj

@ -3,7 +3,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<GenerateProgramFile>false</GenerateProgramFile>
<TargetFrameworks>net461;netcoreapp3.1</TargetFrameworks>
<TargetFrameworks>net5.0;net48</TargetFrameworks>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<AssemblyName>MathNet.Numerics.Tests.MKL</AssemblyName>
<RootNamespace>MathNet.Numerics.Tests</RootNamespace>
@ -23,6 +23,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Numerics\Numerics.csproj" />
<ProjectReference Include="..\Providers.MKL\Providers.MKL.csproj" />
<ProjectReference Include="..\TestData\TestData.csproj" />
</ItemGroup>
<ItemGroup>

3
src/Numerics.Tests/Numerics.Tests.OpenBLAS.csproj

@ -3,7 +3,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<GenerateProgramFile>false</GenerateProgramFile>
<TargetFrameworks>net461;netcoreapp3.1</TargetFrameworks>
<TargetFrameworks>net5.0;net48</TargetFrameworks>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<AssemblyName>MathNet.Numerics.Tests.OpenBLAS</AssemblyName>
<RootNamespace>MathNet.Numerics.Tests</RootNamespace>
@ -23,6 +23,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Numerics\Numerics.csproj" />
<ProjectReference Include="..\Providers.OpenBLAS\Providers.OpenBLAS.csproj" />
<ProjectReference Include="..\TestData\TestData.csproj" />
</ItemGroup>
<ItemGroup>

24
src/Numerics.Tests/Providers/SparseSolver/double/SparseSolverProviderTests.cs

@ -9,7 +9,6 @@ using System.Collections.Generic;
namespace MathNet.Numerics.UnitTests.Providers.SparseSolver.Double
{
#if NATIVE
#if MKL
/// <summary>
@ -20,7 +19,7 @@ namespace MathNet.Numerics.UnitTests.Providers.SparseSolver.Double
{
readonly double[] _b4 = { 1.0, 2.0, 3.0, 4.0};
readonly double[] _b5 = { 1.0, 2.0, 3.0, 4.0, 5.0 };
/// <summary>
/// Test matrix to use.
/// </summary>
@ -245,11 +244,11 @@ namespace MathNet.Numerics.UnitTests.Providers.SparseSolver.Double
// for Node1, u = -1 gives -a + b = x1
// for Node2, u = +1 gives a + b = x2
//
// So,
// So,
// x = (x2 - x1)/2*u + (x2 + x1)/2
// u = 2*(x - x1)/(x2 - x1) - 1
//
// This gives
// This gives
// dx = l/2*du where l = x2 - x1 = x21 is length of the line
//
// Interpolation function, Ni(u) = ai + bi*u for i = 1, 2
@ -257,11 +256,11 @@ namespace MathNet.Numerics.UnitTests.Providers.SparseSolver.Double
// N1(+1) = a1 + b1 = 0 -> a1 = 1/2, b1 = -1/2
// N2(-1) = a2 - b2 = 0
// N2(+1) = a2 + b2 = 1 -> a2 = 1/2, b2 = 1/2
// so,
// so,
// N1 = (1 - u) / 2
// N2 = (1 + u) / 2
//
// Using the chain rule of differentiation,
// Using the chain rule of differentiation,
// ∂Ni(x)/∂u = ∂Ni/∂x ∂x/∂u
//
// Here,
@ -273,7 +272,7 @@ namespace MathNet.Numerics.UnitTests.Providers.SparseSolver.Double
// ∂N1/∂x = 2/l ∂N1/∂u = - 1/l
// ∂N2/∂x = 2/l ∂N2/∂u = 1/l
//-----------------------------------------------------------------------------
// By using V(u) = Σ Vi*Ni(u) and ω = Ni for i = 1, 2
// By using V(u) = Σ Vi*Ni(u) and ω = Ni for i = 1, 2
// the weak form of the master equation is given as
//
// ∫ ω [d/dx(α dV/dx) + γ] dx = 0
@ -328,7 +327,7 @@ namespace MathNet.Numerics.UnitTests.Providers.SparseSolver.Double
{
// V(u) can be described with interpolation functions
// V(u) = V1*N1(u) + V2*N2(u)
// where
// where
// N1 = (1 - u) / 2
// N2 = (1 + u) / 2
// The transformation from x to u,
@ -345,7 +344,7 @@ namespace MathNet.Numerics.UnitTests.Providers.SparseSolver.Double
var Vx = V1 * (1 - u) * 0.5 + V2 * (1 + u) * 0.5;
// Electric field,
// Electric field,
// E = -∇V
// where
// ∇V = [ (∂/∂x) ∑ViNi ]
@ -385,7 +384,7 @@ namespace MathNet.Numerics.UnitTests.Providers.SparseSolver.Double
public Node[] Nodes;
public Element[] Elements;
public Matrix<double> Kmatrix;
public Matrix<double> Kmatrix;
public Vector<double> Rhs;
public Domain(int elementCount = 4, double length = 0.08, double relativePermittivity = 1, double chargeDensity = 1E-8)
@ -395,7 +394,7 @@ namespace MathNet.Numerics.UnitTests.Providers.SparseSolver.Double
Permittivity = Constants.ElectricPermittivity * relativePermittivity;
ChargeDensity = chargeDensity;
// Create nodes and elements
// Create nodes and elements
Nodes = new Node[elementCount + 1];
Elements = new Element[elementCount];
@ -466,7 +465,7 @@ namespace MathNet.Numerics.UnitTests.Providers.SparseSolver.Double
// Imposition of Dirichlet boundary conditions
//
// If xn is given, i.e. x2 = b0, then the linear equations,
// If xn is given, i.e. x2 = b0, then the linear equations,
// [ K11 K12 K13 K14 ][ x1 ] = [ b1 ]
// [ K21 K22 K23 K24 ][ x2 ] [ b2 ]
// [ K31 K32 K33 K34 ][ x3 ] [ b3 ]
@ -579,7 +578,6 @@ namespace MathNet.Numerics.UnitTests.Providers.SparseSolver.Double
}
#endif
#endif
}

3
src/Numerics.Tests/StatisticsTests/StatisticsTests.cs

@ -1004,9 +1004,6 @@ namespace MathNet.Numerics.UnitTests.StatisticsTests
Assert.That(new RunningStatistics(new[] { 2d, 3d }).PopulationVariance, Is.Not.NaN);
}
/// <summary>
/// URL http://mathnetnumerics.codeplex.com/workitem/5667
/// </summary>
[Test]
public void Median_CodeplexIssue5667()
{

20
src/Numerics.Tests/UseLinearAlgebraProvider.cs

@ -28,10 +28,17 @@
// </copyright>
using System;
using MathNet.Numerics.Providers.Common.Mkl;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
#if MKL
using MathNet.Numerics.Providers.MKL;
#elif CUDA
using MathNet.Numerics.Providers.CUDA;
#elif OPENBLAS
using MathNet.Numerics.Providers.OpenBLAS;
#endif
namespace MathNet.Numerics.UnitTests
{
[AttributeUsage(AttributeTargets.Assembly)]
@ -39,19 +46,14 @@ namespace MathNet.Numerics.UnitTests
{
public void BeforeTest(ITest testDetails)
{
#if NATIVE
string outDir = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), @"../../../../../out/");
#if MKL
Control.NativeProviderPath = System.IO.Path.Combine(outDir, @"MKL/Windows/");
Control.UseNativeMKL(MklConsistency.AVX, MklPrecision.Double, MklAccuracy.High);
MklControl.UseNativeMKL(MklConsistency.AVX, MklPrecision.Double, MklAccuracy.High);
#elif CUDA
Control.UseNativeCUDA();
CudaControl.UseNativeCUDA();
#elif OPENBLAS
Control.UseNativeOpenBLAS();
#else
Control.UseManaged();
#endif
OpenBlasControl.UseNativeOpenBLAS();
#else
Control.UseManaged();
#endif

12
src/Numerics/AppSwitches.cs

@ -1,8 +1,7 @@
// <copyright file="AppSwitches.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
// https://github.com/mathnet/mathnet-numerics
// https://mathnetnumerics.codeplex.com
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2020 Math.NET
//
@ -44,7 +43,6 @@ namespace MathNet.Numerics
const string AppSwitchDisableNativeProviderProbing = "Switch.MathNet.Numerics.Providers.DisableNativeProviderProbing";
const string AppSwitchDisableNativeProviders = "Switch.MathNet.Numerics.Providers.DisableNativeProviders";
const string AppSwitchDisableMklNativeProvider = "Switch.MathNet.Numerics.Providers.DisableMklNativeProvider";
const string AppSwitchDisableAcmlNativeProvider = "Switch.MathNet.Numerics.Providers.DisableAcmlNativeProvider";
const string AppSwitchDisableCudaNativeProvider = "Switch.MathNet.Numerics.Providers.DisableCudaNativeProvider";
const string AppSwitchDisableOpenBlasNativeProvider = "Switch.MathNet.Numerics.Providers.DisableOpenBlasNativeProvider";
@ -88,12 +86,6 @@ namespace MathNet.Numerics
set => SetSwitch(AppSwitchDisableMklNativeProvider, value);
}
public static bool DisableAcmlNativeProvider
{
get => IsEnabled(AppSwitchDisableAcmlNativeProvider);
set => SetSwitch(AppSwitchDisableAcmlNativeProvider, value);
}
public static bool DisableCudaNativeProvider
{
get => IsEnabled(AppSwitchDisableCudaNativeProvider);

23
src/Numerics/Control.cs

@ -3,7 +3,7 @@
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2018 Math.NET
// Copyright (c) 2009-2021 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
@ -114,8 +114,6 @@ namespace MathNet.Numerics
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.
@ -127,20 +125,6 @@ namespace MathNet.Numerics
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.
@ -220,7 +204,6 @@ namespace MathNet.Numerics
bool directSparseSolver = SparseSolverControl.TryUseNative();
return linearAlgebra || fourierTransform || directSparseSolver;
}
#endif
public static void FreeResources()
{
@ -351,9 +334,7 @@ namespace MathNet.Numerics
#elif NET40
sb.AppendLine("Built for .Net Framework 4.0");
#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}");

81
src/Numerics/Providers/FourierTransform/FourierTransformControl.cs

@ -3,7 +3,7 @@
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2020 Math.NET
// Copyright (c) 2009-2021 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
@ -34,11 +34,20 @@ namespace MathNet.Numerics.Providers.FourierTransform
public static class FourierTransformControl
{
const string EnvVarFFTProvider = "MathNetNumericsFFTProvider";
const string EnvVarFFTProviderPath = "MathNetNumericsFFTProviderPath";
static IFourierTransformProvider _fourierTransformProvider;
static readonly object StaticLock = new object();
const string MklTypeName = "MathNet.Numerics.Providers.MKL.FourierTransform.MklFourierTransformControl, MathNet.Numerics.Providers.MKL";
static readonly ProviderProbe<IFourierTransformProvider> MklProbe = new ProviderProbe<IFourierTransformProvider>(MklTypeName, AppSwitches.DisableMklNativeProvider);
/// <summary>
/// Optional path to try to load native provider binaries from.
/// If not set, Numerics will fall back to the environment variable
/// `MathNetNumericsFFTProviderPath` or the default probing paths.
/// </summary>
public static string HintPath { get; set; }
/// <summary>
/// Gets or sets the Fourier transform provider. Consider to use UseNativeMKL or UseManaged instead.
/// </summary>
@ -69,38 +78,12 @@ namespace MathNet.Numerics.Providers.FourierTransform
}
}
/// <summary>
/// Optional path to try to load native provider binaries from.
/// If not set, Numerics will fall back to the environment variable
/// `MathNetNumericsFFTProviderPath` or the default probing paths.
/// </summary>
public static string HintPath { get; set; }
public static IFourierTransformProvider CreateManaged()
{
return new Managed.ManagedFourierTransformProvider();
}
public static void UseManaged()
{
Provider = CreateManaged();
}
#if NATIVE
public static IFourierTransformProvider CreateNativeMKL()
{
return new Mkl.MklFourierTransformProvider(GetCombinedHintPath());
}
public static IFourierTransformProvider CreateManaged() => new Managed.ManagedFourierTransformProvider();
public static void UseManaged() => Provider = CreateManaged();
public static void UseNativeMKL()
{
Provider = CreateNativeMKL();
}
public static void UseNativeMKL() => Provider = MklProbe.Create();
public static bool TryUseNativeMKL() => TryUse(MklProbe.TryCreate());
public static bool TryUseNativeMKL()
{
return TryUse(CreateNativeMKL());
}
/// <summary>
/// Try to use a native provider, if available.
@ -114,13 +97,12 @@ namespace MathNet.Numerics.Providers.FourierTransform
return TryUseNativeMKL();
}
#endif
static bool TryUse(IFourierTransformProvider provider)
public static bool TryUse(IFourierTransformProvider provider)
{
try
{
if (!provider.IsAvailable())
if (provider == null || !provider.IsAvailable())
{
return false;
}
@ -146,14 +128,10 @@ namespace MathNet.Numerics.Providers.FourierTransform
return;
}
#if NATIVE
if (!TryUseNative())
{
UseManaged();
}
#else
UseManaged();
#endif
}
/// <summary>
@ -169,7 +147,6 @@ namespace MathNet.Numerics.Providers.FourierTransform
return;
}
#if NATIVE
var value = Environment.GetEnvironmentVariable(EnvVarFFTProvider);
switch (value != null ? value.ToUpperInvariant() : string.Empty)
{
@ -182,30 +159,8 @@ namespace MathNet.Numerics.Providers.FourierTransform
UseBest();
break;
}
#else
UseBest();
#endif
}
public static void FreeResources()
{
Provider.FreeResources();
}
static string GetCombinedHintPath()
{
if (!String.IsNullOrEmpty(HintPath))
{
return HintPath;
}
var value = Environment.GetEnvironmentVariable(EnvVarFFTProviderPath);
if (!String.IsNullOrEmpty(value))
{
return value;
}
return null;
}
public static void FreeResources() => Provider.FreeResources();
}
}

36
src/Numerics/Providers/IProviderCreator.cs

@ -0,0 +1,36 @@
// <copyright file="IProviderCreator.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
// https://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2021 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>
namespace MathNet.Numerics.Providers
{
public interface IProviderCreator<T> where T : class
{
T CreateProvider();
}
}

1092
src/Numerics/Providers/LinearAlgebra/Acml/AcmlLinearAlgebraProvider.Complex.cs

File diff suppressed because it is too large

1095
src/Numerics/Providers/LinearAlgebra/Acml/AcmlLinearAlgebraProvider.Complex32.cs

File diff suppressed because it is too large

1096
src/Numerics/Providers/LinearAlgebra/Acml/AcmlLinearAlgebraProvider.Double.cs

File diff suppressed because it is too large

1095
src/Numerics/Providers/LinearAlgebra/Acml/AcmlLinearAlgebraProvider.Single.cs

File diff suppressed because it is too large

263
src/Numerics/Providers/LinearAlgebra/Acml/SafeNativeMethods.cs

@ -1,263 +0,0 @@
// <copyright file="SafeNativeMethods.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
//
// 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>
#if NATIVEACML
using System.Runtime.InteropServices;
using System.Security;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.LinearAlgebra.Acml
{
/// <summary>
/// P/Invoke methods to the native math libraries.
/// </summary>
[SuppressUnmanagedCodeSecurity]
[SecurityCritical]
internal static class SafeNativeMethods
{
/// <summary>
/// Name of the native DLL.
/// </summary>
const string DllName = "MathNET.Numerics.ACML.dll";
#region BLAS
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern void s_axpy(int n, float alpha, float[] x, [In, Out] float[] y);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern void d_axpy(int n, double alpha, double[] x, [In, Out] double[] y);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern void c_axpy(int n, Complex32 alpha, Complex32[] x, [In, Out] Complex32[] y);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern void z_axpy(int n, Complex alpha, Complex[] x, [In, Out] Complex[] y);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern void s_scale(int n, float alpha, [Out] float[] x);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern void d_scale(int n, double alpha, [Out] double[] x);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern void c_scale(int n, Complex32 alpha, [In, Out] Complex32[] x);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern void z_scale(int n, Complex alpha, [In, Out] Complex[] x);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern float s_dot_product(int n, float[] x, float[] y);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern double d_dot_product(int n, double[] x, double[] y);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern Complex32 c_dot_product(int n, Complex32[] x, Complex32[] y);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern Complex z_dot_product(int n, Complex[] x, Complex[] y);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern void s_matrix_multiply(Transpose transA, Transpose transB, int m, int n, int k, float alpha, float[] x, float[] y, float beta, [In, Out] float[] c);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern void d_matrix_multiply(Transpose transA, Transpose transB, int m, int n, int k, double alpha, double[] x, double[] y, double beta, [In, Out] double[] c);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern void c_matrix_multiply(Transpose transA, Transpose transB, int m, int n, int k, Complex32 alpha, Complex32[] x, Complex32[] y, Complex32 beta, [In, Out] Complex32[] c);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern void z_matrix_multiply(Transpose transA, Transpose transB, int m, int n, int k, Complex alpha, Complex[] x, Complex[] y, Complex beta, [In, Out] Complex[] c);
#endregion BLAS
#region LAPACK
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern float s_matrix_norm(byte norm, int rows, int columns, [In] float[] a, [In, Out] float[] work);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern float d_matrix_norm(byte norm, int rows, int columns, [In] double[] a, [In, Out] double[] work);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern float c_matrix_norm(byte norm, int rows, int columns, [In] Complex32[] a, [In, Out] float[] work);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern double z_matrix_norm(byte norm, int rows, int columns, [In] Complex[] a, [In, Out] double[] work);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int s_cholesky_factor(int n, [In, Out] float[] a);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int d_cholesky_factor(int n, [In, Out] double[] a);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int c_cholesky_factor(int n, [In, Out] Complex32[] a);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int z_cholesky_factor(int n, [In, Out] Complex[] a);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int s_lu_factor(int n, [In, Out] float[] a, [In, Out] int[] ipiv);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int d_lu_factor(int n, [In, Out] double[] a, [In, Out] int[] ipiv);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int c_lu_factor(int n, [In, Out] Complex32[] a, [In, Out] int[] ipiv);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int z_lu_factor(int n, [In, Out] Complex[] a, [In, Out] int[] ipiv);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int s_lu_inverse(int n, [In, Out] float[] a, [In, Out] float[] work, int lwork);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int d_lu_inverse(int n, [In, Out] double[] a, [In, Out] double[] work, int lwork);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int c_lu_inverse(int n, [In, Out] Complex32[] a, [In, Out] Complex32[] work, int lwork);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int z_lu_inverse(int n, [In, Out] Complex[] a, [In, Out] Complex[] work, int lwork);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int s_lu_inverse_factored(int n, [In, Out] float[] a, [In, Out] int[] ipiv, [In, Out] float[] work, int lwork);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int d_lu_inverse_factored(int n, [In, Out] double[] a, [In, Out] int[] ipiv, [In, Out] double[] work, int lwork);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int c_lu_inverse_factored(int n, [In, Out] Complex32[] a, [In, Out] int[] ipiv, [In, Out] Complex32[] work, int lwork);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int z_lu_inverse_factored(int n, [In, Out] Complex[] a, [In, Out] int[] ipiv, [In, Out] Complex[] work, int lwork);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int s_lu_solve_factored(int n, int nrhs, float[] a, [In, Out] int[] ipiv, [In, Out] float[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int d_lu_solve_factored(int n, int nrhs, double[] a, [In, Out] int[] ipiv, [In, Out] double[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int c_lu_solve_factored(int n, int nrhs, Complex32[] a, [In, Out] int[] ipiv, [In, Out] Complex32[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int z_lu_solve_factored(int n, int nrhs, Complex[] a, [In, Out] int[] ipiv, [In, Out] Complex[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int s_lu_solve(int n, int nrhs, float[] a, [In, Out] float[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int d_lu_solve(int n, int nrhs, double[] a, [In, Out] double[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int c_lu_solve(int n, int nrhs, Complex32[] a, [In, Out] Complex32[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int z_lu_solve(int n, int nrhs, Complex[] a, [In, Out] Complex[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int s_cholesky_solve(int n, int nrhs, float[] a, [In, Out] float[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int d_cholesky_solve(int n, int nrhs, double[] a, [In, Out] double[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int c_cholesky_solve(int n, int nrhs, Complex32[] a, [In, Out] Complex32[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int z_cholesky_solve(int n, int nrhs, Complex[] a, [In, Out] Complex[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int s_cholesky_solve_factored(int n, int nrhs, float[] a, [In, Out] float[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int d_cholesky_solve_factored(int n, int nrhs, double[] a, [In, Out] double[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int c_cholesky_solve_factored(int n, int nrhs, Complex32[] a, [In, Out] Complex32[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int z_cholesky_solve_factored(int n, int nrhs, Complex[] a, [In, Out] Complex[] b);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int s_qr_factor(int m, int n, [In, Out] float[] r, [In, Out] float[] tau, [In, Out] float[] q, [In, Out] float[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int d_qr_factor(int m, int n, [In, Out] double[] r, [In, Out] double[] tau, [In, Out] double[] q, [In, Out] double[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int c_qr_factor(int m, int n, [In, Out] Complex32[] r, [In, Out] Complex32[] tau, [In, Out] Complex32[] q, [In, Out] Complex32[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int z_qr_factor(int m, int n, [In, Out] Complex[] r, [In, Out] Complex[] tau, [In, Out] Complex[] q, [In, Out] Complex[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int s_qr_solve(int m, int n, int bn, float[] r, float[] b, [In, Out] float[] x, [In, Out] float[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int d_qr_solve(int m, int n, int bn, double[] r, double[] b, [In, Out] double[] x, [In, Out] double[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int c_qr_solve(int m, int n, int bn, Complex32[] r, Complex32[] b, [In, Out] Complex32[] x, [In, Out] Complex32[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int z_qr_solve(int m, int n, int bn, Complex[] r, Complex[] b, [In, Out] Complex[] x, [In, Out] Complex[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int s_qr_solve_factored(int m, int n, int bn, float[] r, float[] b, float[] tau, [In, Out] float[] x, [In, Out] float[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int d_qr_solve_factored(int m, int n, int bn, double[] r, double[] b, double[] tau, [In, Out] double[] x, [In, Out] double[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int c_qr_solve_factored(int m, int n, int bn, Complex32[] r, Complex32[] b, Complex32[] tau, [In, Out] Complex32[] x, [In, Out] Complex32[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int z_qr_solve_factored(int m, int n, int bn, Complex[] r, Complex[] b, Complex[] tau, [In, Out] Complex[] x, [In, Out] Complex[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int s_svd_factor(bool computeVectors, int m, int n, [In, Out] float[] a, [In, Out] float[] s, [In, Out] float[] u, [In, Out] float[] v, [In, Out] float[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int d_svd_factor(bool computeVectors, int m, int n, [In, Out] double[] a, [In, Out] double[] s, [In, Out] double[] u, [In, Out] double[] v, [In, Out] double[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int c_svd_factor(bool computeVectors, int m, int n, [In, Out] Complex32[] a, [In, Out] Complex32[] s, [In, Out] Complex32[] u, [In, Out] Complex32[] v, [In, Out] Complex32[] work, int len);
[DllImport(DllName, ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
internal static extern int z_svd_factor(bool computeVectors, int m, int n, [In, Out] Complex[] a, [In, Out] Complex[] s, [In, Out] Complex[] u, [In, Out] Complex[] v, [In, Out] Complex[] work, int len);
#endregion LAPACK
}
}
#endif

143
src/Numerics/Providers/LinearAlgebra/LinearAlgebraControl.cs

@ -3,7 +3,7 @@
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2020 Math.NET
// Copyright (c) 2009-2021 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
@ -34,11 +34,26 @@ namespace MathNet.Numerics.Providers.LinearAlgebra
public static class LinearAlgebraControl
{
const string EnvVarLAProvider = "MathNetNumericsLAProvider";
const string EnvVarLAProviderPath = "MathNetNumericsLAProviderPath";
static ILinearAlgebraProvider _linearAlgebraProvider;
static readonly object StaticLock = new object();
const string MklTypeName = "MathNet.Numerics.Providers.MKL.LinearAlgebra.MklLinearAlgebraControl, MathNet.Numerics.Providers.MKL";
static readonly ProviderProbe<ILinearAlgebraProvider> MklProbe = new ProviderProbe<ILinearAlgebraProvider>(MklTypeName, AppSwitches.DisableMklNativeProvider);
const string OpenBlasTypeName = "MathNet.Numerics.Providers.OpenBLAS.LinearAlgebra.OpenBlasLinearAlgebraControl, MathNet.Numerics.Providers.OpenBLAS";
static readonly ProviderProbe<ILinearAlgebraProvider> OpenBlasProbe = new ProviderProbe<ILinearAlgebraProvider>(OpenBlasTypeName, AppSwitches.DisableOpenBlasNativeProvider);
const string CudaTypeName = "MathNet.Numerics.Providers.CUDA.LinearAlgebra.CudaLinearAlgebraControl, MathNet.Numerics.Providers.CUDA";
static readonly ProviderProbe<ILinearAlgebraProvider> CudaProbe = new ProviderProbe<ILinearAlgebraProvider>(CudaTypeName, AppSwitches.DisableCudaNativeProvider);
/// <summary>
/// Optional path to try to load native provider binaries from.
/// If not set, Numerics will fall back to the environment variable
/// `MathNetNumericsLAProviderPath` or the default probing paths.
/// </summary>
public static string HintPath { get; set; }
/// <summary>
/// Gets or sets the linear algebra provider.
/// Consider to use UseNativeMKL or UseManaged instead.
@ -70,90 +85,20 @@ namespace MathNet.Numerics.Providers.LinearAlgebra
}
}
/// <summary>
/// Optional path to try to load native provider binaries from.
/// If not set, Numerics will fall back to the environment variable
/// `MathNetNumericsLAProviderPath` or the default probing paths.
/// </summary>
public static string HintPath { get; set; }
public static ILinearAlgebraProvider CreateManaged()
{
return new Managed.ManagedLinearAlgebraProvider();
}
public static void UseManaged()
{
Provider = CreateManaged();
}
internal static ILinearAlgebraProvider CreateManagedReference()
{
return new ManagedReference.ManagedReferenceLinearAlgebraProvider();
}
internal static void UseManagedReference()
{
Provider = CreateManagedReference();
}
#if NATIVE
[CLSCompliant(false)]
public static ILinearAlgebraProvider CreateNativeMKL(
Common.Mkl.MklConsistency consistency = Common.Mkl.MklConsistency.Auto,
Common.Mkl.MklPrecision precision = Common.Mkl.MklPrecision.Double,
Common.Mkl.MklAccuracy accuracy = Common.Mkl.MklAccuracy.High)
{
return new Mkl.MklLinearAlgebraProvider(GetCombinedHintPath(), consistency, precision, accuracy);
}
[CLSCompliant(false)]
public static void UseNativeMKL(
Common.Mkl.MklConsistency consistency = Common.Mkl.MklConsistency.Auto,
Common.Mkl.MklPrecision precision = Common.Mkl.MklPrecision.Double,
Common.Mkl.MklAccuracy accuracy = Common.Mkl.MklAccuracy.High)
{
Provider = CreateNativeMKL(consistency, precision, accuracy);
}
[CLSCompliant(false)]
public static bool TryUseNativeMKL(
Common.Mkl.MklConsistency consistency = Common.Mkl.MklConsistency.Auto,
Common.Mkl.MklPrecision precision = Common.Mkl.MklPrecision.Double,
Common.Mkl.MklAccuracy accuracy = Common.Mkl.MklAccuracy.High)
{
return TryUse(CreateNativeMKL(consistency, precision, accuracy));
}
public static ILinearAlgebraProvider CreateManaged() => new Managed.ManagedLinearAlgebraProvider();
public static void UseManaged() => Provider = CreateManaged();
public static ILinearAlgebraProvider CreateNativeCUDA()
{
return new Cuda.CudaLinearAlgebraProvider(GetCombinedHintPath());
}
internal static ILinearAlgebraProvider CreateManagedReference() => new ManagedReference.ManagedReferenceLinearAlgebraProvider();
internal static void UseManagedReference() => Provider = CreateManagedReference();
public static void UseNativeCUDA()
{
Provider = CreateNativeCUDA();
}
public static void UseNativeMKL() => Provider = MklProbe.Create();
public static bool TryUseNativeMKL() => TryUse(MklProbe.TryCreate());
public static bool TryUseNativeCUDA()
{
return TryUse(CreateNativeCUDA());
}
public static void UseNativeCUDA() => Provider = CudaProbe.Create();
public static bool TryUseNativeCUDA() => TryUse(CudaProbe.TryCreate());
public static ILinearAlgebraProvider CreateNativeOpenBLAS()
{
return new OpenBlas.OpenBlasLinearAlgebraProvider(GetCombinedHintPath());
}
public static void UseNativeOpenBLAS()
{
Provider = CreateNativeOpenBLAS();
}
public static bool TryUseNativeOpenBLAS()
{
return TryUse(CreateNativeOpenBLAS());
}
public static void UseNativeOpenBLAS() => Provider = OpenBlasProbe.Create();
public static bool TryUseNativeOpenBLAS() => TryUse(OpenBlasProbe.TryCreate());
/// <summary>
/// Try to use a native provider, if available.
@ -167,13 +112,12 @@ namespace MathNet.Numerics.Providers.LinearAlgebra
return TryUseNativeMKL() || TryUseNativeOpenBLAS() || TryUseNativeCUDA();
}
#endif
static bool TryUse(ILinearAlgebraProvider provider)
public static bool TryUse(ILinearAlgebraProvider provider)
{
try
{
if (!provider.IsAvailable())
if (provider == null || !provider.IsAvailable())
{
return false;
}
@ -199,14 +143,10 @@ namespace MathNet.Numerics.Providers.LinearAlgebra
return;
}
#if NATIVE
if (!TryUseNative())
{
UseManaged();
}
#else
UseManaged();
#endif
}
/// <summary>
@ -222,7 +162,6 @@ namespace MathNet.Numerics.Providers.LinearAlgebra
return;
}
#if NATIVE
var value = Environment.GetEnvironmentVariable(EnvVarLAProvider);
switch (value != null ? value.ToUpperInvariant() : string.Empty)
{
@ -242,30 +181,8 @@ namespace MathNet.Numerics.Providers.LinearAlgebra
UseBest();
break;
}
#else
UseBest();
#endif
}
public static void FreeResources()
{
Provider.FreeResources();
}
static string GetCombinedHintPath()
{
if (!String.IsNullOrEmpty(HintPath))
{
return HintPath;
}
var value = Environment.GetEnvironmentVariable(EnvVarLAProviderPath);
if (!String.IsNullOrEmpty(value))
{
return value;
}
return null;
}
public static void FreeResources() => Provider.FreeResources();
}
}

2
src/Numerics/Providers/LinearAlgebra/Managed/ManagedLinearAlgebraProvider.Complex.cs

@ -38,7 +38,7 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Managed
/// <summary>
/// The managed linear algebra provider.
/// </summary>
internal partial class ManagedLinearAlgebraProvider
public partial class ManagedLinearAlgebraProvider
{
/// <summary>
/// Adds a scaled vector to another: <c>result = y + alpha*x</c>.

2
src/Numerics/Providers/LinearAlgebra/Managed/ManagedLinearAlgebraProvider.Complex32.cs

@ -38,7 +38,7 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Managed
/// <summary>
/// The managed linear algebra provider.
/// </summary>
internal partial class ManagedLinearAlgebraProvider
public partial class ManagedLinearAlgebraProvider
{
/// <summary>
/// Adds a scaled vector to another: <c>result = y + alpha*x</c>.

2
src/Numerics/Providers/LinearAlgebra/Managed/ManagedLinearAlgebraProvider.Double.cs

@ -38,7 +38,7 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Managed
/// <summary>
/// The managed linear algebra provider.
/// </summary>
internal partial class ManagedLinearAlgebraProvider
public partial class ManagedLinearAlgebraProvider
{
/// <summary>
/// Adds a scaled vector to another: <c>result = y + alpha*x</c>.

2
src/Numerics/Providers/LinearAlgebra/Managed/ManagedLinearAlgebraProvider.Single.cs

@ -38,7 +38,7 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Managed
/// <summary>
/// The managed linear algebra provider.
/// </summary>
internal partial class ManagedLinearAlgebraProvider
public partial class ManagedLinearAlgebraProvider
{
/// <summary>
/// Adds a scaled vector to another: <c>result = y + alpha*x</c>.

2
src/Numerics/Providers/LinearAlgebra/Managed/ManagedLinearAlgebraProvider.cs

@ -34,7 +34,7 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Managed
/// <summary>
/// The managed linear algebra provider.
/// </summary>
internal partial class ManagedLinearAlgebraProvider : ILinearAlgebraProvider
public partial class ManagedLinearAlgebraProvider : ILinearAlgebraProvider
{
/// <summary>
/// Try to find out whether the provider is available, at least in principle.

88
src/Numerics/Providers/ProviderProbe.cs

@ -0,0 +1,88 @@
// <copyright file="ProviderProbe.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
// https://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2021 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.Threading;
namespace MathNet.Numerics.Providers
{
public class ProviderProbe<T> where T : class
{
readonly bool _disabled;
readonly Lazy<IProviderCreator<T>> _creator;
public ProviderProbe(string typeName, bool disabled = false)
{
_disabled = disabled;
_creator = new Lazy<IProviderCreator<T>>(() =>
{
var type = Type.GetType(typeName);
return Activator.CreateInstance(type) as IProviderCreator<T>;
}, LazyThreadSafetyMode.ExecutionAndPublication);
}
public T Create()
{
if (_disabled)
{
throw new NotSupportedException("Specific Native Provider disabled by an application switch");
}
if (AppSwitches.DisableNativeProviders)
{
throw new NotSupportedException("Native Providers are disabled by an application switch");
}
if (AppSwitches.DisableNativeProviderProbing)
{
throw new NotSupportedException("Native Provider Probing is disabled by an application switch");
}
return _creator.Value.CreateProvider();
}
public T TryCreate()
{
if (_disabled || AppSwitches.DisableNativeProviderProbing || AppSwitches.DisableNativeProviders)
{
return null;
}
try
{
return _creator.Value.CreateProvider();
}
catch
{
// intentionally swallow exceptions here - use the explicit variants if you're interested in why
return null;
}
}
}
}

2
src/Numerics/Providers/SparseSolver/Managed/ManagedSparseSolverProvider.cs

@ -6,7 +6,7 @@ namespace MathNet.Numerics.Providers.SparseSolver.Managed
/// <summary>
/// The managed sparse solver provider
/// </summary>
internal partial class ManagedSparseSolverProvider : ISparseSolverProvider
public partial class ManagedSparseSolverProvider : ISparseSolverProvider
{
/// <summary>
/// Try to find out whether the provider is available, at least in principle.

95
src/Numerics/Providers/SparseSolver/SparseSolverControl.cs

@ -3,7 +3,7 @@
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2020 Math.NET
// Copyright (c) 2009-2021 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
@ -34,11 +34,20 @@ namespace MathNet.Numerics.Providers.SparseSolver
public static class SparseSolverControl
{
const string EnvVarSSProvider = "MathNetNumericsSSProvider";
const string EnvVarSSProviderPath = "MathNetNumericsSSProviderPath";
static ISparseSolverProvider _sparseSolverProvider;
static readonly object StaticLock = new object();
const string MklTypeName = "MathNet.Numerics.Providers.MKL.SparseSolver.MklSparseSolverControl, MathNet.Numerics.Providers.MKL";
static readonly ProviderProbe<ISparseSolverProvider> MklProbe = new ProviderProbe<ISparseSolverProvider>(MklTypeName, AppSwitches.DisableMklNativeProvider);
/// <summary>
/// Optional path to try to load native provider binaries from.
/// If not set, Numerics will fall back to the environment variable
/// `MathNetNumericsSSProviderPath` or the default probing paths.
/// </summary>
public static string HintPath { get; set; }
/// <summary>
/// Gets or sets the sparse solver provider. Consider to use UseNativeMKL or UseManaged instead.
/// </summary>
@ -69,38 +78,11 @@ namespace MathNet.Numerics.Providers.SparseSolver
}
}
/// <summary>
/// Optional path to try to load native provider binaries from.
/// If not set, Numerics will fall back to the environment variable
/// `MathNetNumericsSSProviderPath` or the default probing paths.
/// </summary>
public static string HintPath { get; set; }
public static ISparseSolverProvider CreateManaged()
{
return new Managed.ManagedSparseSolverProvider();
}
public static void UseManaged()
{
Provider = CreateManaged();
}
#if NATIVE
public static ISparseSolverProvider CreateNativeMKL()
{
return new Mkl.MklSparseSolverProvider(GetCombinedHintPath());
}
public static void UseNativeMKL()
{
Provider = CreateNativeMKL();
}
public static ISparseSolverProvider CreateManaged() => new Managed.ManagedSparseSolverProvider();
public static void UseManaged() => Provider = CreateManaged();
public static bool TryUseNativeMKL()
{
return TryUse(CreateNativeMKL());
}
public static void UseNativeMKL() => Provider = MklProbe.Create();
public static bool TryUseNativeMKL() => TryUse(MklProbe.TryCreate());
/// <summary>
/// Try to use a native provider, if available.
@ -114,13 +96,12 @@ namespace MathNet.Numerics.Providers.SparseSolver
return TryUseNativeMKL();
}
#endif
static bool TryUse(ISparseSolverProvider provider)
public static bool TryUse(ISparseSolverProvider provider)
{
try
{
if (!provider.IsAvailable())
if (provider == null || !provider.IsAvailable())
{
return false;
}
@ -135,6 +116,19 @@ namespace MathNet.Numerics.Providers.SparseSolver
}
}
public static bool TryUse(Lazy<IProviderCreator<ISparseSolverProvider>> providerCreator)
{
try
{
return TryUse(providerCreator.Value?.CreateProvider());
}
catch
{
// intentionally swallow exceptions here - use the explicit variants if you're interested in why
return false;
}
}
/// <summary>
/// Use the best provider available.
/// </summary>
@ -146,14 +140,10 @@ namespace MathNet.Numerics.Providers.SparseSolver
return;
}
#if NATIVE
if (!TryUseNative())
{
UseManaged();
}
#else
UseManaged();
#endif
}
/// <summary>
@ -169,7 +159,6 @@ namespace MathNet.Numerics.Providers.SparseSolver
return;
}
#if NATIVE
var value = Environment.GetEnvironmentVariable(EnvVarSSProvider);
switch (value != null ? value.ToUpperInvariant() : string.Empty)
{
@ -182,30 +171,8 @@ namespace MathNet.Numerics.Providers.SparseSolver
UseBest();
break;
}
#else
UseBest();
#endif
}
public static void FreeResources()
{
Provider.FreeResources();
}
static string GetCombinedHintPath()
{
if (!String.IsNullOrEmpty(HintPath))
{
return HintPath;
}
var value = Environment.GetEnvironmentVariable(EnvVarSSProviderPath);
if (!String.IsNullOrEmpty(value))
{
return value;
}
return null;
}
public static void FreeResources() => Provider.FreeResources();
}
}

80
src/Providers.CUDA/ArrayExtensions.cs

@ -0,0 +1,80 @@
// <copyright file="ArrayExtensions.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
// https://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2021 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 Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.CUDA
{
/// <summary>
/// Useful extension methods for Arrays.
/// </summary>
internal static class ArrayExtensions
{
/// <summary>
/// Copies the values from on array to another.
/// </summary>
/// <param name="source">The source array.</param>
/// <param name="dest">The destination array.</param>
public static void Copy(this double[] source, double[] dest)
{
Buffer.BlockCopy(source, 0, dest, 0, source.Length * Constants.SizeOfDouble);
}
/// <summary>
/// Copies the values from on array to another.
/// </summary>
/// <param name="source">The source array.</param>
/// <param name="dest">The destination array.</param>
public static void Copy(this float[] source, float[] dest)
{
Buffer.BlockCopy(source, 0, dest, 0, source.Length * Constants.SizeOfFloat);
}
/// <summary>
/// Copies the values from on array to another.
/// </summary>
/// <param name="source">The source array.</param>
/// <param name="dest">The destination array.</param>
public static void Copy(this Complex[] source, Complex[] dest)
{
Array.Copy(source, 0, dest, 0, source.Length);
}
/// <summary>
/// Copies the values from on array to another.
/// </summary>
/// <param name="source">The source array.</param>
/// <param name="dest">The destination array.</param>
public static void Copy(this Complex32[] source, Complex32[] dest)
{
Array.Copy(source, 0, dest, 0, source.Length);
}
}
}

44
src/Providers.CUDA/Compatibility.cs

@ -0,0 +1,44 @@
using System.Globalization;
#if NET40
namespace System.Runtime.CompilerServices
{
internal class FormattableStringFactory
{
public static FormattableString Create(string format, params object[] args)
{
return new FormattableString(format, args);
}
}
}
namespace System
{
internal class FormattableString
{
private readonly string format;
private readonly object[] args;
public FormattableString(string format, object[] args)
{
this.format = format;
this.args = args;
}
public static string Invariant(FormattableString messageFormat)
{
return messageFormat.ToString(CultureInfo.InvariantCulture);
}
public string ToString(IFormatProvider formatProvider)
{
return string.Format(formatProvider, format, args);
}
public override string ToString()
{
return string.Format(format, args);
}
}
}
#endif

60
src/Providers.CUDA/CudaControl.cs

@ -0,0 +1,60 @@
// <copyright file="CudaControl.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
// https://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2021 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 MathNet.Numerics.Providers.CUDA.LinearAlgebra;
namespace MathNet.Numerics.Providers.CUDA
{
public static class CudaControl
{
internal const string EnvVarCUDAProviderPath = "MathNetNumericsCUDAProviderPath";
/// <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 UseNativeCUDA()
{
CudaLinearAlgebraControl.UseNativeCUDA();
}
/// <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 TryUseNativeCUDA()
{
bool linearAlgebra = CudaLinearAlgebraControl.TryUseNativeCUDA();
return linearAlgebra;
}
}
}

6
src/Numerics/Providers/Common/Cuda/CudaProvider.cs → src/Providers.CUDA/CudaProvider.cs

@ -27,12 +27,10 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Collections.Generic;
namespace MathNet.Numerics.Providers.Common.Cuda
namespace MathNet.Numerics.Providers.CUDA
{
public static class CudaProvider
{
@ -149,5 +147,3 @@ namespace MathNet.Numerics.Providers.Common.Cuda
}
}
}
#endif

6
src/Numerics/Providers/Common/Cuda/CudaProviderCapabilities.cs → src/Providers.CUDA/CudaProviderCapabilities.cs

@ -27,9 +27,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
namespace MathNet.Numerics.Providers.Common.Cuda
namespace MathNet.Numerics.Providers.CUDA
{
internal enum ProviderPlatform : int
{
@ -49,5 +47,3 @@ namespace MathNet.Numerics.Providers.Common.Cuda
LinearAlgebraMinor = 129,
}
}
#endif

93
src/Providers.CUDA/LinearAlgebra/CudaLinearAlgebraControl.cs

@ -0,0 +1,93 @@
// <copyright file="CudaLinearAlgebraControl.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
// https://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2021 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 MathNet.Numerics.Providers.LinearAlgebra;
namespace MathNet.Numerics.Providers.CUDA.LinearAlgebra
{
public class CudaLinearAlgebraControl : IProviderCreator<ILinearAlgebraProvider>
{
const string EnvVarLAProviderPath = "MathNetNumericsLAProviderPath";
/// <summary>
/// Optional path to try to load native provider binaries from.
/// If not set, Numerics will fall back to the environment variable
/// `MathNetNumericsMKLProviderPath` or the default probing paths.
/// </summary>
public static string HintPath { get; set; }
public static ILinearAlgebraProvider CreateNativeCUDA()
{
return new CudaLinearAlgebraProvider(GetCombinedHintPath());
}
public static void UseNativeCUDA()
{
LinearAlgebraControl.Provider = CreateNativeCUDA();
}
public static bool TryUseNativeCUDA()
{
return LinearAlgebraControl.TryUse(CreateNativeCUDA());
}
static string GetCombinedHintPath()
{
if (!String.IsNullOrEmpty(HintPath))
{
return HintPath;
}
if (!String.IsNullOrEmpty(LinearAlgebraControl.HintPath))
{
return LinearAlgebraControl.HintPath;
}
var value = Environment.GetEnvironmentVariable(CudaControl.EnvVarCUDAProviderPath);
if (!String.IsNullOrEmpty(value))
{
return value;
}
value = Environment.GetEnvironmentVariable(EnvVarLAProviderPath);
if (!String.IsNullOrEmpty(value))
{
return value;
}
return null;
}
public ILinearAlgebraProvider CreateProvider()
{
return CreateNativeCUDA();
}
}
}

8
src/Numerics/Providers/LinearAlgebra/Cuda/CudaLinearAlgebraProvider.Complex.cs → src/Providers.CUDA/LinearAlgebra/CudaLinearAlgebraProvider.Complex.cs

@ -27,14 +27,12 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Security;
using MathNet.Numerics.Providers.Common.Cuda;
using MathNet.Numerics.Providers.LinearAlgebra;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.LinearAlgebra.Cuda
namespace MathNet.Numerics.Providers.CUDA.LinearAlgebra
{
/// <summary>
/// NVidia's CUDA Toolkit linear algebra provider.
@ -572,5 +570,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Cuda
}
}
}
#endif

8
src/Numerics/Providers/LinearAlgebra/Cuda/CudaLinearAlgebraProvider.Complex32.cs → src/Providers.CUDA/LinearAlgebra/CudaLinearAlgebraProvider.Complex32.cs

@ -27,13 +27,11 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Security;
using MathNet.Numerics.Providers.Common.Cuda;
using MathNet.Numerics.Providers.LinearAlgebra;
namespace MathNet.Numerics.Providers.LinearAlgebra.Cuda
namespace MathNet.Numerics.Providers.CUDA.LinearAlgebra
{
/// <summary>
/// NVidia's CUDA Toolkit linear algebra provider.
@ -571,5 +569,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Cuda
}
}
}
#endif

8
src/Numerics/Providers/LinearAlgebra/Cuda/CudaLinearAlgebraProvider.Double.cs → src/Providers.CUDA/LinearAlgebra/CudaLinearAlgebraProvider.Double.cs

@ -27,13 +27,11 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Security;
using MathNet.Numerics.Providers.Common.Cuda;
using MathNet.Numerics.Providers.LinearAlgebra;
namespace MathNet.Numerics.Providers.LinearAlgebra.Cuda
namespace MathNet.Numerics.Providers.CUDA.LinearAlgebra
{
/// <summary>
/// NVidia's CUDA Toolkit linear algebra provider.
@ -571,5 +569,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Cuda
}
}
}
#endif

8
src/Numerics/Providers/LinearAlgebra/Cuda/CudaLinearAlgebraProvider.Single.cs → src/Providers.CUDA/LinearAlgebra/CudaLinearAlgebraProvider.Single.cs

@ -27,13 +27,11 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Security;
using MathNet.Numerics.Providers.Common.Cuda;
using MathNet.Numerics.Providers.LinearAlgebra;
namespace MathNet.Numerics.Providers.LinearAlgebra.Cuda
namespace MathNet.Numerics.Providers.CUDA.LinearAlgebra
{
/// <summary>
/// NVidia's CUDA Toolkit linear algebra provider.
@ -571,5 +569,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Cuda
}
}
}
#endif

10
src/Numerics/Providers/LinearAlgebra/Cuda/CudaLinearAlgebraProvider.cs → src/Providers.CUDA/LinearAlgebra/CudaLinearAlgebraProvider.cs

@ -27,17 +27,15 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using MathNet.Numerics.Providers.Common.Cuda;
using MathNet.Numerics.Providers.LinearAlgebra.Managed;
namespace MathNet.Numerics.Providers.LinearAlgebra.Cuda
namespace MathNet.Numerics.Providers.CUDA.LinearAlgebra
{
/// <summary>
/// NVidia's CUDA Toolkit linear algebra provider.
/// </summary>
internal partial class CudaLinearAlgebraProvider : Managed.ManagedLinearAlgebraProvider, IDisposable
internal partial class CudaLinearAlgebraProvider : ManagedLinearAlgebraProvider, IDisposable
{
const int MinimumCompatibleRevision = 1;
@ -190,5 +188,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Cuda
}
}
}
#endif

6
src/Numerics/Providers/Common/NativeProviderLoader.cs → src/Providers.CUDA/NativeProviderLoader.cs

@ -27,8 +27,6 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Collections.Generic;
using System.IO;
@ -37,7 +35,7 @@ using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
namespace MathNet.Numerics.Providers.Common
namespace MathNet.Numerics.Providers.CUDA
{
/// <summary>
/// Helper class to load native libraries depending on the architecture of the OS and process.
@ -252,5 +250,3 @@ namespace MathNet.Numerics.Providers.Common
}
}
}
#endif

34
src/Providers.CUDA/Providers.CUDA.csproj

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net5.0;net461;net40;netstandard2.0</TargetFrameworks>
<AssemblyName>MathNet.Numerics.Providers.CUDA</AssemblyName>
<RootNamespace>MathNet.Numerics.Providers.CUDA</RootNamespace>
<IsPackable>true</IsPackable>
<PackageId>MathNet.Numerics.Providers.CUDA$(PackageIdSuffix)</PackageId>
<VersionPrefix>4.15.0</VersionPrefix>
<VersionSuffix></VersionSuffix>
<Title>Math.NET Numerics CUDA Provider$(TitleSuffix)</Title>
<Description>Math.NET Numerics is the numerical foundation of the Math.NET project, aiming to provide methods and algorithms for numerical computations in science, engineering and every day use. Supports .Net 5.0 or higher, .NET Standard 2.0 and .NET Framework 4.0 or higher, on Windows, Linux and Mac.$(DescriptionSuffix)</Description>
<PackageReleaseNotes>Precision: Round (with integer part rounding) ~Jon Larborn
Precision: RoundToMultiple, RoundToPower
F#: BigRational.FromDecimal ~Brian Berns</PackageReleaseNotes>
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
<GeneratePackageOnBuild>false</GeneratePackageOnBuild>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<EnableDefaultCompileItems>true</EnableDefaultCompileItems>
<NoWarn>1701;1702;1705;1591;1573</NoWarn>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net40'">
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.Serialization" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Numerics\Numerics.csproj" />
</ItemGroup>
<Import Project="..\..\.paket\Paket.Restore.targets" />
</Project>

6
src/Numerics/Providers/Common/Cuda/SafeNativeMethods.cs → src/Providers.CUDA/SafeNativeMethods.cs

@ -26,15 +26,13 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Runtime.InteropServices;
using System.Security;
using MathNet.Numerics.Providers.LinearAlgebra;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.Common.Cuda
namespace MathNet.Numerics.Providers.CUDA
{
/// <summary>
/// P/Invoke methods to the native math libraries.
@ -375,5 +373,3 @@ namespace MathNet.Numerics.Providers.Common.Cuda
// ReSharper restore InconsistentNaming
}
}
#endif

1
src/Providers.CUDA/paket.references

@ -0,0 +1 @@
Microsoft.NETFramework.ReferenceAssemblies

80
src/Providers.MKL/ArrayExtensions.cs

@ -0,0 +1,80 @@
// <copyright file="ArrayExtensions.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
// https://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2021 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 Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.MKL
{
/// <summary>
/// Useful extension methods for Arrays.
/// </summary>
internal static class ArrayExtensions
{
/// <summary>
/// Copies the values from on array to another.
/// </summary>
/// <param name="source">The source array.</param>
/// <param name="dest">The destination array.</param>
public static void Copy(this double[] source, double[] dest)
{
Buffer.BlockCopy(source, 0, dest, 0, source.Length * Constants.SizeOfDouble);
}
/// <summary>
/// Copies the values from on array to another.
/// </summary>
/// <param name="source">The source array.</param>
/// <param name="dest">The destination array.</param>
public static void Copy(this float[] source, float[] dest)
{
Buffer.BlockCopy(source, 0, dest, 0, source.Length * Constants.SizeOfFloat);
}
/// <summary>
/// Copies the values from on array to another.
/// </summary>
/// <param name="source">The source array.</param>
/// <param name="dest">The destination array.</param>
public static void Copy(this Complex[] source, Complex[] dest)
{
Array.Copy(source, 0, dest, 0, source.Length);
}
/// <summary>
/// Copies the values from on array to another.
/// </summary>
/// <param name="source">The source array.</param>
/// <param name="dest">The destination array.</param>
public static void Copy(this Complex32[] source, Complex32[] dest)
{
Array.Copy(source, 0, dest, 0, source.Length);
}
}
}

44
src/Providers.MKL/Compatibility.cs

@ -0,0 +1,44 @@
using System.Globalization;
#if NET40
namespace System.Runtime.CompilerServices
{
internal class FormattableStringFactory
{
public static FormattableString Create(string format, params object[] args)
{
return new FormattableString(format, args);
}
}
}
namespace System
{
internal class FormattableString
{
private readonly string format;
private readonly object[] args;
public FormattableString(string format, object[] args)
{
this.format = format;
this.args = args;
}
public static string Invariant(FormattableString messageFormat)
{
return messageFormat.ToString(CultureInfo.InvariantCulture);
}
public string ToString(IFormatProvider formatProvider)
{
return string.Format(formatProvider, format, args);
}
public override string ToString()
{
return string.Format(format, args);
}
}
}
#endif

93
src/Providers.MKL/FourierTransform/MklFourierTransformControl.cs

@ -0,0 +1,93 @@
// <copyright file="MklFourierTransformControl.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
// https://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2021 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 MathNet.Numerics.Providers.FourierTransform;
namespace MathNet.Numerics.Providers.MKL.FourierTransform
{
public class MklFourierTransformControl : IProviderCreator<IFourierTransformProvider>
{
const string EnvVarFFTProviderPath = "MathNetNumericsFFTProviderPath";
/// <summary>
/// Optional path to try to load native provider binaries from.
/// If not set, Numerics will fall back to the environment variable
/// `MathNetNumericsMKLProviderPath` or the default probing paths.
/// </summary>
public static string HintPath { get; set; }
public static IFourierTransformProvider CreateNativeMKL()
{
return new MklFourierTransformProvider(GetCombinedHintPath());
}
public static void UseNativeMKL()
{
FourierTransformControl.Provider = CreateNativeMKL();
}
public static bool TryUseNativeMKL()
{
return FourierTransformControl.TryUse(CreateNativeMKL());
}
static string GetCombinedHintPath()
{
if (!String.IsNullOrEmpty(HintPath))
{
return HintPath;
}
if (!String.IsNullOrEmpty(FourierTransformControl.HintPath))
{
return FourierTransformControl.HintPath;
}
var value = Environment.GetEnvironmentVariable(MklControl.EnvVarMKLProviderPath);
if (!String.IsNullOrEmpty(value))
{
return value;
}
value = Environment.GetEnvironmentVariable(EnvVarFFTProviderPath);
if (!String.IsNullOrEmpty(value))
{
return value;
}
return null;
}
public IFourierTransformProvider CreateProvider()
{
return CreateNativeMKL();
}
}
}

8
src/Numerics/Providers/FourierTransform/Mkl/MklFourierTransformProvider.cs → src/Providers.MKL/FourierTransform/MklFourierTransformProvider.cs

@ -26,14 +26,12 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Threading;
using MathNet.Numerics.Providers.Common.Mkl;
using MathNet.Numerics.Providers.FourierTransform;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.FourierTransform.Mkl
namespace MathNet.Numerics.Providers.MKL.FourierTransform
{
internal class MklFourierTransformProvider : IFourierTransformProvider, IDisposable
{
@ -367,5 +365,3 @@ namespace MathNet.Numerics.Providers.FourierTransform.Mkl
}
}
}
#endif

102
src/Providers.MKL/LinearAlgebra/MklLinearAlgebraControl.cs

@ -0,0 +1,102 @@
// <copyright file="MklLinearAlgebraControl.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
// https://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2021 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 MathNet.Numerics.Providers.LinearAlgebra;
namespace MathNet.Numerics.Providers.MKL.LinearAlgebra
{
public class MklLinearAlgebraControl : IProviderCreator<ILinearAlgebraProvider>
{
const string EnvVarLAProviderPath = "MathNetNumericsLAProviderPath";
/// <summary>
/// Optional path to try to load native provider binaries from.
/// If not set, Numerics will fall back to the environment variable
/// `MathNetNumericsMKLProviderPath` or the default probing paths.
/// </summary>
public static string HintPath { get; set; }
public static ILinearAlgebraProvider CreateNativeMKL(
MklConsistency consistency = MklConsistency.Auto,
MklPrecision precision = MklPrecision.Double,
MklAccuracy accuracy = MklAccuracy.High)
{
return new MklLinearAlgebraProvider(GetCombinedHintPath(), consistency, precision, accuracy);
}
public static void UseNativeMKL(
MklConsistency consistency = MklConsistency.Auto,
MklPrecision precision = MklPrecision.Double,
MklAccuracy accuracy = MklAccuracy.High)
{
LinearAlgebraControl.Provider = CreateNativeMKL(consistency, precision, accuracy);
}
public static bool TryUseNativeMKL(
MklConsistency consistency = MklConsistency.Auto,
MklPrecision precision = MklPrecision.Double,
MklAccuracy accuracy = MklAccuracy.High)
{
return LinearAlgebraControl.TryUse(CreateNativeMKL(consistency, precision, accuracy));
}
static string GetCombinedHintPath()
{
if (!String.IsNullOrEmpty(HintPath))
{
return HintPath;
}
if (!String.IsNullOrEmpty(LinearAlgebraControl.HintPath))
{
return LinearAlgebraControl.HintPath;
}
var value = Environment.GetEnvironmentVariable(MklControl.EnvVarMKLProviderPath);
if (!String.IsNullOrEmpty(value))
{
return value;
}
value = Environment.GetEnvironmentVariable(EnvVarLAProviderPath);
if (!String.IsNullOrEmpty(value))
{
return value;
}
return null;
}
public ILinearAlgebraProvider CreateProvider()
{
return CreateNativeMKL();
}
}
}

8
src/Numerics/Providers/LinearAlgebra/Mkl/MklLinearAlgebraProvider.Complex.cs → src/Providers.MKL/LinearAlgebra/MklLinearAlgebraProvider.Complex.cs

@ -27,15 +27,13 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Security;
using MathNet.Numerics.LinearAlgebra.Factorization;
using MathNet.Numerics.Providers.Common.Mkl;
using MathNet.Numerics.Providers.LinearAlgebra;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.LinearAlgebra.Mkl
namespace MathNet.Numerics.Providers.MKL.LinearAlgebra
{
/// <summary>
/// Intel's Math Kernel Library (MKL) linear algebra provider.
@ -1200,5 +1198,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Mkl
}
}
}
#endif

8
src/Numerics/Providers/LinearAlgebra/Mkl/MklLinearAlgebraProvider.Complex32.cs → src/Providers.MKL/LinearAlgebra/MklLinearAlgebraProvider.Complex32.cs

@ -27,15 +27,13 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Security;
using MathNet.Numerics.LinearAlgebra.Factorization;
using MathNet.Numerics.Providers.Common.Mkl;
using MathNet.Numerics.Providers.LinearAlgebra;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.LinearAlgebra.Mkl
namespace MathNet.Numerics.Providers.MKL.LinearAlgebra
{
/// <summary>
/// Intel's Math Kernel Library (MKL) linear algebra provider.
@ -1195,5 +1193,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Mkl
}
}
}
#endif

8
src/Numerics/Providers/LinearAlgebra/Mkl/MklLinearAlgebraProvider.Double.cs → src/Providers.MKL/LinearAlgebra/MklLinearAlgebraProvider.Double.cs

@ -27,15 +27,13 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Security;
using MathNet.Numerics.LinearAlgebra.Factorization;
using MathNet.Numerics.Providers.Common.Mkl;
using MathNet.Numerics.Providers.LinearAlgebra;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.LinearAlgebra.Mkl
namespace MathNet.Numerics.Providers.MKL.LinearAlgebra
{
/// <summary>
/// Intel's Math Kernel Library (MKL) linear algebra provider.
@ -1200,5 +1198,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Mkl
}
}
}
#endif

8
src/Numerics/Providers/LinearAlgebra/Mkl/MklLinearAlgebraProvider.Single.cs → src/Providers.MKL/LinearAlgebra/MklLinearAlgebraProvider.Single.cs

@ -27,15 +27,13 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Security;
using MathNet.Numerics.LinearAlgebra.Factorization;
using MathNet.Numerics.Providers.Common.Mkl;
using MathNet.Numerics.Providers.LinearAlgebra;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.LinearAlgebra.Mkl
namespace MathNet.Numerics.Providers.MKL.LinearAlgebra
{
/// <summary>
/// Intel's Math Kernel Library (MKL) linear algebra provider.
@ -1195,5 +1193,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Mkl
}
}
}
#endif

10
src/Numerics/Providers/LinearAlgebra/Mkl/MklLinearAlgebraProvider.cs → src/Providers.MKL/LinearAlgebra/MklLinearAlgebraProvider.cs

@ -27,12 +27,10 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using MathNet.Numerics.Providers.Common.Mkl;
using MathNet.Numerics.Providers.LinearAlgebra.Managed;
namespace MathNet.Numerics.Providers.LinearAlgebra.Mkl
namespace MathNet.Numerics.Providers.MKL.LinearAlgebra
{
/// <summary>
/// Error codes return from the MKL provider.
@ -48,7 +46,7 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Mkl
/// <summary>
/// Intel's Math Kernel Library (MKL) linear algebra provider.
/// </summary>
internal partial class MklLinearAlgebraProvider : Managed.ManagedLinearAlgebraProvider, IDisposable
internal partial class MklLinearAlgebraProvider : ManagedLinearAlgebraProvider, IDisposable
{
const int MinimumCompatibleRevision = 4;
@ -130,5 +128,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.Mkl
}
}
}
#endif

80
src/Providers.MKL/MklControl.cs

@ -0,0 +1,80 @@
// <copyright file="MklControl.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
// https://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2021 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 MathNet.Numerics.Providers.MKL.FourierTransform;
using MathNet.Numerics.Providers.MKL.LinearAlgebra;
using MathNet.Numerics.Providers.MKL.SparseSolver;
namespace MathNet.Numerics.Providers.MKL
{
public static class MklControl
{
internal const string EnvVarMKLProviderPath = "MathNetNumericsMKLProviderPath";
/// <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()
{
MklLinearAlgebraControl.UseNativeMKL();
MklFourierTransformControl.UseNativeMKL();
MklSparseSolverControl.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>
public static void UseNativeMKL(
MklConsistency consistency = MklConsistency.Auto,
MklPrecision precision = MklPrecision.Double,
MklAccuracy accuracy = MklAccuracy.High)
{
MklLinearAlgebraControl.UseNativeMKL(consistency, precision, accuracy);
MklFourierTransformControl.UseNativeMKL();
MklSparseSolverControl.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 = MklLinearAlgebraControl.TryUseNativeMKL();
bool fourierTransform = MklFourierTransformControl.TryUseNativeMKL();
bool directSparseSolver = MklSparseSolverControl.TryUseNativeMKL();
return linearAlgebra || fourierTransform || directSparseSolver;
}
}
}

7
src/Numerics/Providers/Common/Mkl/MklProvider.cs → src/Providers.MKL/MklProvider.cs

@ -27,12 +27,10 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Collections.Generic;
namespace MathNet.Numerics.Providers.Common.Mkl
namespace MathNet.Numerics.Providers.MKL
{
public static class MklProvider
{
@ -83,7 +81,6 @@ namespace MathNet.Numerics.Providers.Common.Mkl
}
/// <returns>Revision</returns>
[CLSCompliant(false)]
public static int Load(
string hintPath = null,
MklConsistency consistency = MklConsistency.Auto,
@ -346,5 +343,3 @@ namespace MathNet.Numerics.Providers.Common.Mkl
}
}
}
#endif

6
src/Numerics/Providers/Common/Mkl/MklProviderCapabilities.cs → src/Providers.MKL/MklProviderCapabilities.cs

@ -27,9 +27,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
namespace MathNet.Numerics.Providers.Common.Mkl
namespace MathNet.Numerics.Providers.MKL
{
internal enum ProviderPlatform : int
{
@ -61,5 +59,3 @@ namespace MathNet.Numerics.Providers.Common.Mkl
SparseSolverMinor = 513,
}
}
#endif

6
src/Numerics/Providers/Common/Mkl/MklProviderPrecision.cs → src/Providers.MKL/MklProviderPrecision.cs

@ -27,9 +27,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
namespace MathNet.Numerics.Providers.Common.Mkl
namespace MathNet.Numerics.Providers.MKL
{
/// <summary>
/// Consistency vs. performance trade-off between runs on different machines.
@ -50,14 +48,12 @@ namespace MathNet.Numerics.Providers.Common.Mkl
AVX2 = 10
}
[CLSCompliant(false)]
public enum MklAccuracy : uint
{
Low = 0x1,
High = 0x2
}
[CLSCompliant(false)]
public enum MklPrecision : uint
{
Single = 0x10,

252
src/Providers.MKL/NativeProviderLoader.cs

@ -0,0 +1,252 @@
// <copyright file="NativeProviderLoader.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-2016 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.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
namespace MathNet.Numerics.Providers.MKL
{
/// <summary>
/// Helper class to load native libraries depending on the architecture of the OS and process.
/// </summary>
internal static class NativeProviderLoader
{
static readonly object StaticLock = new Object();
const string X86 = "x86";
const string X64 = "x64";
const string IA64 = "ia64";
const string ARM = "arm";
const string ARM64 = "arm64";
/// <summary>
/// Dictionary of handles to previously loaded libraries,
/// </summary>
static readonly Lazy<Dictionary<string, IntPtr>> NativeHandles = new Lazy<Dictionary<string, IntPtr>>(LazyThreadSafetyMode.PublicationOnly);
/// <summary>
/// Gets a string indicating the architecture and bitness of the current process.
/// </summary>
static readonly Lazy<string> ArchitectureKey = new Lazy<string>(EvaluateArchitectureKey, LazyThreadSafetyMode.PublicationOnly);
/// <summary>
/// If the last native library failed to load then gets the corresponding exception
/// which occurred or null if the library was successfully loaded.
/// </summary>
internal static Exception LastException { get; private set; }
static bool IsUnix
{
get
{
var p = Environment.OSVersion.Platform;
return p == PlatformID.Unix || p == PlatformID.MacOSX;
}
}
static string EvaluateArchitectureKey()
{
//return (IntPtr.Size == 8) ? X64 : X86;
if (IsUnix)
{
// Only support x86 and amd64 on Unix as there isn't a reliable way to detect the architecture
return Environment.Is64BitProcess ? X64 : X86;
}
var architecture = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
if (string.Equals(architecture, "x86", StringComparison.OrdinalIgnoreCase))
{
return X86;
}
if (string.Equals(architecture, "amd64", StringComparison.OrdinalIgnoreCase)
|| string.Equals(architecture, "x64", StringComparison.OrdinalIgnoreCase))
{
return Environment.Is64BitProcess ? X64 : X86;
}
if (string.Equals(architecture, "ia64", StringComparison.OrdinalIgnoreCase))
{
return IA64;
}
if (string.Equals(architecture, "arm", StringComparison.OrdinalIgnoreCase))
{
return Environment.Is64BitProcess ? ARM64 : ARM;
}
// Fallback if unknown
return architecture;
}
/// <summary>
/// Load the native library with the given filename.
/// </summary>
/// <param name="fileName">The file name of the library to load.</param>
/// <param name="hintPath">Hint path where to look for the native binaries. Can be null.</param>
/// <returns>True if the library was successfully loaded or if it has already been loaded.</returns>
internal static bool TryLoad(string fileName, string hintPath)
{
if (string.IsNullOrEmpty(fileName))
{
throw new ArgumentNullException(nameof(fileName));
}
// If we have hint path provided by the user, look there first
if (TryLoadFromDirectory(fileName, hintPath))
{
return true;
}
// If we have an overall hint path provided by the user, look there next
if (Control.NativeProviderPath != hintPath && TryLoadFromDirectory(fileName, Control.NativeProviderPath))
{
return true;
}
// Look under the current AppDomain's base directory
if (TryLoadFromDirectory(fileName, AppDomain.CurrentDomain.BaseDirectory))
{
return true;
}
// Look at this assembly's directory
if (TryLoadFromDirectory(fileName, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)))
{
return true;
}
return false;
}
/// <summary>
/// Try to load a native library by providing its name and a directory.
/// Tries to load an implementation suitable for the current CPU architecture
/// and process mode if there is a matching subfolder.
/// </summary>
/// <returns>True if the library was successfully loaded or if it has already been loaded.</returns>
static bool TryLoadFromDirectory(string fileName, string directory)
{
if (!Directory.Exists(directory))
{
return false;
}
directory = Path.GetFullPath(directory);
// If we have a know architecture, try the matching subdirectory first
var architecture = ArchitectureKey.Value;
if (!string.IsNullOrEmpty(architecture) && TryLoadFile(new FileInfo(Path.Combine(Path.Combine(directory, architecture), fileName))))
{
return true;
}
// Otherwise try to load directly from the provided directory
return TryLoadFile(new FileInfo(Path.Combine(directory, fileName)));
}
/// <summary>
/// Try to load a native library by providing the full path including the file name of the library.
/// </summary>
/// <returns>True if the library was successfully loaded or if it has already been loaded.</returns>
static bool TryLoadFile(FileInfo file)
{
lock (StaticLock)
{
IntPtr libraryHandle;
if (NativeHandles.Value.TryGetValue(file.Name, out libraryHandle))
{
return true;
}
if (!file.Exists)
{
// If the library isn't found within an architecture specific folder then return false
// to allow normal P/Invoke searching behavior when the library is called
return false;
}
// If successful this will return a handle to the library
libraryHandle = IsUnix ? UnixLoader.LoadLibrary(file.FullName) : WindowsLoader.LoadLibrary(file.FullName);
if (libraryHandle == IntPtr.Zero)
{
int lastError = Marshal.GetLastWin32Error();
var exception = new System.ComponentModel.Win32Exception(lastError);
LastException = exception;
}
else
{
LastException = null;
NativeHandles.Value[file.Name] = libraryHandle;
}
return libraryHandle != IntPtr.Zero;
}
}
[SuppressUnmanagedCodeSecurity]
[SecurityCritical]
static class WindowsLoader
{
public static IntPtr LoadLibrary(string fileName)
{
return LoadLibraryEx(fileName, IntPtr.Zero, LOAD_WITH_ALTERED_SEARCH_PATH);
}
// Search for dependencies in the library's directory rather than the calling process's directory
const uint LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008;
[DllImport("kernel32", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true)]
static extern IntPtr LoadLibraryEx(string fileName, IntPtr reservedNull, uint flags);
}
[SuppressUnmanagedCodeSecurity]
[SecurityCritical]
static class UnixLoader
{
public static IntPtr LoadLibrary(string fileName)
{
return dlopen(fileName, RTLD_NOW);
}
const int RTLD_NOW = 2;
[DllImport("libdl.so", SetLastError = true)]
static extern IntPtr dlopen(String fileName, int flags);
}
}
}

34
src/Providers.MKL/Providers.MKL.csproj

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net5.0;net461;net40;netstandard2.0</TargetFrameworks>
<AssemblyName>MathNet.Numerics.Providers.MKL</AssemblyName>
<RootNamespace>MathNet.Numerics.Providers.MKL</RootNamespace>
<IsPackable>true</IsPackable>
<PackageId>MathNet.Numerics.Providers.MKL$(PackageIdSuffix)</PackageId>
<VersionPrefix>4.15.0</VersionPrefix>
<VersionSuffix></VersionSuffix>
<Title>Math.NET Numerics MKL Provider$(TitleSuffix)</Title>
<Description>Math.NET Numerics is the numerical foundation of the Math.NET project, aiming to provide methods and algorithms for numerical computations in science, engineering and every day use. Supports .Net 5.0 or higher, .NET Standard 2.0 and .NET Framework 4.0 or higher, on Windows, Linux and Mac.$(DescriptionSuffix)</Description>
<PackageReleaseNotes>Precision: Round (with integer part rounding) ~Jon Larborn
Precision: RoundToMultiple, RoundToPower
F#: BigRational.FromDecimal ~Brian Berns</PackageReleaseNotes>
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
<GeneratePackageOnBuild>false</GeneratePackageOnBuild>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<EnableDefaultCompileItems>true</EnableDefaultCompileItems>
<NoWarn>1701;1702;1705;1591;1573</NoWarn>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net40'">
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.Serialization" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Numerics\Numerics.csproj" />
</ItemGroup>
<Import Project="..\..\.paket\Paket.Restore.targets" />
</Project>

6
src/Numerics/Providers/Common/Mkl/SafeNativeMethods.cs → src/Providers.MKL/SafeNativeMethods.cs

@ -26,15 +26,13 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Runtime.InteropServices;
using System.Security;
using MathNet.Numerics.Providers.LinearAlgebra;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.Common.Mkl
namespace MathNet.Numerics.Providers.MKL
{
/// <summary>
/// P/Invoke methods to the native math libraries.
@ -457,5 +455,3 @@ namespace MathNet.Numerics.Providers.Common.Mkl
// ReSharper restore InconsistentNaming
}
}
#endif

93
src/Providers.MKL/SparseSolver/MklSparseSolverControl.cs

@ -0,0 +1,93 @@
// <copyright file="MklSparseSolverControl.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
// https://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2021 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 MathNet.Numerics.Providers.SparseSolver;
namespace MathNet.Numerics.Providers.MKL.SparseSolver
{
public class MklSparseSolverControl : IProviderCreator<ISparseSolverProvider>
{
const string EnvVarSSProviderPath = "MathNetNumericsSSProviderPath";
/// <summary>
/// Optional path to try to load native provider binaries from.
/// If not set, Numerics will fall back to the environment variable
/// `MathNetNumericsMKLProviderPath` or the default probing paths.
/// </summary>
public static string HintPath { get; set; }
public static ISparseSolverProvider CreateNativeMKL()
{
return new MklSparseSolverProvider(GetCombinedHintPath());
}
public static void UseNativeMKL()
{
SparseSolverControl.Provider = CreateNativeMKL();
}
public static bool TryUseNativeMKL()
{
return SparseSolverControl.TryUse(CreateNativeMKL());
}
static string GetCombinedHintPath()
{
if (!String.IsNullOrEmpty(HintPath))
{
return HintPath;
}
if (!String.IsNullOrEmpty(SparseSolverControl.HintPath))
{
return SparseSolverControl.HintPath;
}
var value = Environment.GetEnvironmentVariable(MklControl.EnvVarMKLProviderPath);
if (!String.IsNullOrEmpty(value))
{
return value;
}
value = Environment.GetEnvironmentVariable(EnvVarSSProviderPath);
if (!String.IsNullOrEmpty(value))
{
return value;
}
return null;
}
public ISparseSolverProvider CreateProvider()
{
return CreateNativeMKL();
}
}
}

10
src/Numerics/Providers/SparseSolver/Mkl/MklSparseSolverProvider.Complex.cs → src/Providers.MKL/SparseSolver/MklSparseSolverProvider.Complex.cs

@ -1,11 +1,9 @@
#if NATIVE
using MathNet.Numerics.Providers.Common.Mkl;
using System;
using System;
using System.Security;
using MathNet.Numerics.Providers.SparseSolver;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.SparseSolver.Mkl
namespace MathNet.Numerics.Providers.MKL.SparseSolver
{
/// <summary>
/// Intel's Math Kernel Library (MKL) direct sparse solver provider.
@ -80,5 +78,3 @@ namespace MathNet.Numerics.Providers.SparseSolver.Mkl
}
}
}
#endif

10
src/Numerics/Providers/SparseSolver/Mkl/MklSparseSolverProvider.Complex32.cs → src/Providers.MKL/SparseSolver/MklSparseSolverProvider.Complex32.cs

@ -1,10 +1,8 @@
#if NATIVE
using MathNet.Numerics.Providers.Common.Mkl;
using System;
using System;
using System.Security;
using MathNet.Numerics.Providers.SparseSolver;
namespace MathNet.Numerics.Providers.SparseSolver.Mkl
namespace MathNet.Numerics.Providers.MKL.SparseSolver
{
/// <summary>
/// Intel's Math Kernel Library (MKL) direct sparse solver provider.
@ -79,5 +77,3 @@ namespace MathNet.Numerics.Providers.SparseSolver.Mkl
}
}
}
#endif

10
src/Numerics/Providers/SparseSolver/Mkl/MklSparseSolverProvider.Double.cs → src/Providers.MKL/SparseSolver/MklSparseSolverProvider.Double.cs

@ -1,10 +1,8 @@
#if NATIVE
using MathNet.Numerics.Providers.Common.Mkl;
using System;
using System;
using System.Security;
using MathNet.Numerics.Providers.SparseSolver;
namespace MathNet.Numerics.Providers.SparseSolver.Mkl
namespace MathNet.Numerics.Providers.MKL.SparseSolver
{
/// <summary>
/// Intel's Math Kernel Library (MKL) direct sparse solver provider.
@ -79,5 +77,3 @@ namespace MathNet.Numerics.Providers.SparseSolver.Mkl
}
}
}
#endif

9
src/Numerics/Providers/SparseSolver/Mkl/MklSparseSolverProvider.Single.cs → src/Providers.MKL/SparseSolver/MklSparseSolverProvider.Single.cs

@ -1,10 +1,8 @@
#if NATIVE
using MathNet.Numerics.Providers.Common.Mkl;
using System;
using System;
using System.Security;
using MathNet.Numerics.Providers.SparseSolver;
namespace MathNet.Numerics.Providers.SparseSolver.Mkl
namespace MathNet.Numerics.Providers.MKL.SparseSolver
{
/// <summary>
/// Intel's Math Kernel Library (MKL) direct sparse solver provider.
@ -79,4 +77,3 @@ namespace MathNet.Numerics.Providers.SparseSolver.Mkl
}
}
}
#endif

13
src/Numerics/Providers/SparseSolver/Mkl/MklSparseSolverProvider.cs → src/Providers.MKL/SparseSolver/MklSparseSolverProvider.cs

@ -1,14 +1,12 @@
#if NATIVE
using System;
using MathNet.Numerics.Providers.SparseSolver.Managed;
using MathNet.Numerics.Providers.Common.Mkl;
using System;
namespace MathNet.Numerics.Providers.SparseSolver.Mkl
namespace MathNet.Numerics.Providers.MKL.SparseSolver
{
/// <summary>
/// Intel's Math Kernel Library (MKL) sparse solver provider.
/// </summary>
internal partial class MklSparseSolverProvider : Managed.ManagedSparseSolverProvider, IDisposable
internal partial class MklSparseSolverProvider : ManagedSparseSolverProvider, IDisposable
{
const int MinimumCompatibleRevision = 14;
@ -72,6 +70,3 @@ namespace MathNet.Numerics.Providers.SparseSolver.Mkl
}
}
}
#endif

1
src/Providers.MKL/paket.references

@ -0,0 +1 @@
Microsoft.NETFramework.ReferenceAssemblies

80
src/Providers.OpenBLAS/ArrayExtensions.cs

@ -0,0 +1,80 @@
// <copyright file="ArrayExtensions.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
// https://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2021 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 Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.OpenBLAS
{
/// <summary>
/// Useful extension methods for Arrays.
/// </summary>
internal static class ArrayExtensions
{
/// <summary>
/// Copies the values from on array to another.
/// </summary>
/// <param name="source">The source array.</param>
/// <param name="dest">The destination array.</param>
public static void Copy(this double[] source, double[] dest)
{
Buffer.BlockCopy(source, 0, dest, 0, source.Length * Constants.SizeOfDouble);
}
/// <summary>
/// Copies the values from on array to another.
/// </summary>
/// <param name="source">The source array.</param>
/// <param name="dest">The destination array.</param>
public static void Copy(this float[] source, float[] dest)
{
Buffer.BlockCopy(source, 0, dest, 0, source.Length * Constants.SizeOfFloat);
}
/// <summary>
/// Copies the values from on array to another.
/// </summary>
/// <param name="source">The source array.</param>
/// <param name="dest">The destination array.</param>
public static void Copy(this Complex[] source, Complex[] dest)
{
Array.Copy(source, 0, dest, 0, source.Length);
}
/// <summary>
/// Copies the values from on array to another.
/// </summary>
/// <param name="source">The source array.</param>
/// <param name="dest">The destination array.</param>
public static void Copy(this Complex32[] source, Complex32[] dest)
{
Array.Copy(source, 0, dest, 0, source.Length);
}
}
}

44
src/Providers.OpenBLAS/Compatibility.cs

@ -0,0 +1,44 @@
using System.Globalization;
#if NET40
namespace System.Runtime.CompilerServices
{
internal class FormattableStringFactory
{
public static FormattableString Create(string format, params object[] args)
{
return new FormattableString(format, args);
}
}
}
namespace System
{
internal class FormattableString
{
private readonly string format;
private readonly object[] args;
public FormattableString(string format, object[] args)
{
this.format = format;
this.args = args;
}
public static string Invariant(FormattableString messageFormat)
{
return messageFormat.ToString(CultureInfo.InvariantCulture);
}
public string ToString(IFormatProvider formatProvider)
{
return string.Format(formatProvider, format, args);
}
public override string ToString()
{
return string.Format(format, args);
}
}
}
#endif

93
src/Providers.OpenBLAS/LinearAlgebra/OpenBlasLinearAlgebraControl.cs

@ -0,0 +1,93 @@
// <copyright file="OpenBlasLinearAlgebraControl.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
// https://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2021 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 MathNet.Numerics.Providers.LinearAlgebra;
namespace MathNet.Numerics.Providers.OpenBLAS.LinearAlgebra
{
public class OpenBlasLinearAlgebraControl : IProviderCreator<ILinearAlgebraProvider>
{
const string EnvVarLAProviderPath = "MathNetNumericsLAProviderPath";
/// <summary>
/// Optional path to try to load native provider binaries from.
/// If not set, Numerics will fall back to the environment variable
/// `MathNetNumericsMKLProviderPath` or the default probing paths.
/// </summary>
public static string HintPath { get; set; }
public static ILinearAlgebraProvider CreateNativeOpenBLAS()
{
return new OpenBlasLinearAlgebraProvider(GetCombinedHintPath());
}
public static void UseNativeOpenBLAS()
{
LinearAlgebraControl.Provider = CreateNativeOpenBLAS();
}
public static bool TryUseNativeOpenBLAS()
{
return LinearAlgebraControl.TryUse(CreateNativeOpenBLAS());
}
static string GetCombinedHintPath()
{
if (!String.IsNullOrEmpty(HintPath))
{
return HintPath;
}
if (!String.IsNullOrEmpty(LinearAlgebraControl.HintPath))
{
return LinearAlgebraControl.HintPath;
}
var value = Environment.GetEnvironmentVariable(OpenBlasControl.EnvVarOpenBLASProviderPath);
if (!String.IsNullOrEmpty(value))
{
return value;
}
value = Environment.GetEnvironmentVariable(EnvVarLAProviderPath);
if (!String.IsNullOrEmpty(value))
{
return value;
}
return null;
}
public ILinearAlgebraProvider CreateProvider()
{
return CreateNativeOpenBLAS();
}
}
}

8
src/Numerics/Providers/LinearAlgebra/OpenBlas/OpenBlasLinearAlgebraProvider.Complex.cs → src/Providers.OpenBLAS/LinearAlgebra/OpenBlasLinearAlgebraProvider.Complex.cs

@ -27,15 +27,13 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Security;
using MathNet.Numerics.LinearAlgebra.Factorization;
using MathNet.Numerics.Providers.Common.OpenBlas;
using MathNet.Numerics.Providers.LinearAlgebra;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.LinearAlgebra.OpenBlas
namespace MathNet.Numerics.Providers.OpenBLAS.LinearAlgebra
{
/// <summary>
/// OpenBLAS linear algebra provider.
@ -1020,5 +1018,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.OpenBlas
}
}
}
#endif

8
src/Numerics/Providers/LinearAlgebra/OpenBlas/OpenBlasLinearAlgebraProvider.Complex32.cs → src/Providers.OpenBLAS/LinearAlgebra/OpenBlasLinearAlgebraProvider.Complex32.cs

@ -27,15 +27,13 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Security;
using MathNet.Numerics.LinearAlgebra.Factorization;
using MathNet.Numerics.Providers.Common.OpenBlas;
using MathNet.Numerics.Providers.LinearAlgebra;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.LinearAlgebra.OpenBlas
namespace MathNet.Numerics.Providers.OpenBLAS.LinearAlgebra
{
/// <summary>
/// OpenBLAS linear algebra provider.
@ -1015,5 +1013,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.OpenBlas
}
}
}
#endif

8
src/Numerics/Providers/LinearAlgebra/OpenBlas/OpenBlasLinearAlgebraProvider.Double.cs → src/Providers.OpenBLAS/LinearAlgebra/OpenBlasLinearAlgebraProvider.Double.cs

@ -27,15 +27,13 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Security;
using MathNet.Numerics.LinearAlgebra.Factorization;
using MathNet.Numerics.Providers.Common.OpenBlas;
using MathNet.Numerics.Providers.LinearAlgebra;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.LinearAlgebra.OpenBlas
namespace MathNet.Numerics.Providers.OpenBLAS.LinearAlgebra
{
/// <summary>
/// OpenBLAS linear algebra provider.
@ -1020,5 +1018,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.OpenBlas
}
}
}
#endif

8
src/Numerics/Providers/LinearAlgebra/OpenBlas/OpenBlasLinearAlgebraProvider.Single.cs → src/Providers.OpenBLAS/LinearAlgebra/OpenBlasLinearAlgebraProvider.Single.cs

@ -27,15 +27,13 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Security;
using MathNet.Numerics.LinearAlgebra.Factorization;
using MathNet.Numerics.Providers.Common.OpenBlas;
using MathNet.Numerics.Providers.LinearAlgebra;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.LinearAlgebra.OpenBlas
namespace MathNet.Numerics.Providers.OpenBLAS.LinearAlgebra
{
/// <summary>
/// OpenBLAS linear algebra provider.
@ -1015,5 +1013,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.OpenBlas
}
}
}
#endif

10
src/Numerics/Providers/LinearAlgebra/OpenBlas/OpenBlasLinearAlgebraProvider.cs → src/Providers.OpenBLAS/LinearAlgebra/OpenBlasLinearAlgebraProvider.cs

@ -27,12 +27,10 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using MathNet.Numerics.Providers.Common.OpenBlas;
using MathNet.Numerics.Providers.LinearAlgebra.Managed;
namespace MathNet.Numerics.Providers.LinearAlgebra.OpenBlas
namespace MathNet.Numerics.Providers.OpenBLAS.LinearAlgebra
{
/// <summary>
/// Error codes return from the native OpenBLAS provider.
@ -55,7 +53,7 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.OpenBlas
/// <summary>
/// OpenBLAS linear algebra provider.
/// </summary>
internal partial class OpenBlasLinearAlgebraProvider : Managed.ManagedLinearAlgebraProvider, IDisposable
internal partial class OpenBlasLinearAlgebraProvider : ManagedLinearAlgebraProvider, IDisposable
{
const int MinimumCompatibleRevision = 1;
@ -117,5 +115,3 @@ namespace MathNet.Numerics.Providers.LinearAlgebra.OpenBlas
}
}
}
#endif

252
src/Providers.OpenBLAS/NativeProviderLoader.cs

@ -0,0 +1,252 @@
// <copyright file="NativeProviderLoader.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-2016 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.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
namespace MathNet.Numerics.Providers.OpenBLAS
{
/// <summary>
/// Helper class to load native libraries depending on the architecture of the OS and process.
/// </summary>
internal static class NativeProviderLoader
{
static readonly object StaticLock = new Object();
const string X86 = "x86";
const string X64 = "x64";
const string IA64 = "ia64";
const string ARM = "arm";
const string ARM64 = "arm64";
/// <summary>
/// Dictionary of handles to previously loaded libraries,
/// </summary>
static readonly Lazy<Dictionary<string, IntPtr>> NativeHandles = new Lazy<Dictionary<string, IntPtr>>(LazyThreadSafetyMode.PublicationOnly);
/// <summary>
/// Gets a string indicating the architecture and bitness of the current process.
/// </summary>
static readonly Lazy<string> ArchitectureKey = new Lazy<string>(EvaluateArchitectureKey, LazyThreadSafetyMode.PublicationOnly);
/// <summary>
/// If the last native library failed to load then gets the corresponding exception
/// which occurred or null if the library was successfully loaded.
/// </summary>
internal static Exception LastException { get; private set; }
static bool IsUnix
{
get
{
var p = Environment.OSVersion.Platform;
return p == PlatformID.Unix || p == PlatformID.MacOSX;
}
}
static string EvaluateArchitectureKey()
{
//return (IntPtr.Size == 8) ? X64 : X86;
if (IsUnix)
{
// Only support x86 and amd64 on Unix as there isn't a reliable way to detect the architecture
return Environment.Is64BitProcess ? X64 : X86;
}
var architecture = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
if (string.Equals(architecture, "x86", StringComparison.OrdinalIgnoreCase))
{
return X86;
}
if (string.Equals(architecture, "amd64", StringComparison.OrdinalIgnoreCase)
|| string.Equals(architecture, "x64", StringComparison.OrdinalIgnoreCase))
{
return Environment.Is64BitProcess ? X64 : X86;
}
if (string.Equals(architecture, "ia64", StringComparison.OrdinalIgnoreCase))
{
return IA64;
}
if (string.Equals(architecture, "arm", StringComparison.OrdinalIgnoreCase))
{
return Environment.Is64BitProcess ? ARM64 : ARM;
}
// Fallback if unknown
return architecture;
}
/// <summary>
/// Load the native library with the given filename.
/// </summary>
/// <param name="fileName">The file name of the library to load.</param>
/// <param name="hintPath">Hint path where to look for the native binaries. Can be null.</param>
/// <returns>True if the library was successfully loaded or if it has already been loaded.</returns>
internal static bool TryLoad(string fileName, string hintPath)
{
if (string.IsNullOrEmpty(fileName))
{
throw new ArgumentNullException(nameof(fileName));
}
// If we have hint path provided by the user, look there first
if (TryLoadFromDirectory(fileName, hintPath))
{
return true;
}
// If we have an overall hint path provided by the user, look there next
if (Control.NativeProviderPath != hintPath && TryLoadFromDirectory(fileName, Control.NativeProviderPath))
{
return true;
}
// Look under the current AppDomain's base directory
if (TryLoadFromDirectory(fileName, AppDomain.CurrentDomain.BaseDirectory))
{
return true;
}
// Look at this assembly's directory
if (TryLoadFromDirectory(fileName, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)))
{
return true;
}
return false;
}
/// <summary>
/// Try to load a native library by providing its name and a directory.
/// Tries to load an implementation suitable for the current CPU architecture
/// and process mode if there is a matching subfolder.
/// </summary>
/// <returns>True if the library was successfully loaded or if it has already been loaded.</returns>
static bool TryLoadFromDirectory(string fileName, string directory)
{
if (!Directory.Exists(directory))
{
return false;
}
directory = Path.GetFullPath(directory);
// If we have a know architecture, try the matching subdirectory first
var architecture = ArchitectureKey.Value;
if (!string.IsNullOrEmpty(architecture) && TryLoadFile(new FileInfo(Path.Combine(Path.Combine(directory, architecture), fileName))))
{
return true;
}
// Otherwise try to load directly from the provided directory
return TryLoadFile(new FileInfo(Path.Combine(directory, fileName)));
}
/// <summary>
/// Try to load a native library by providing the full path including the file name of the library.
/// </summary>
/// <returns>True if the library was successfully loaded or if it has already been loaded.</returns>
static bool TryLoadFile(FileInfo file)
{
lock (StaticLock)
{
IntPtr libraryHandle;
if (NativeHandles.Value.TryGetValue(file.Name, out libraryHandle))
{
return true;
}
if (!file.Exists)
{
// If the library isn't found within an architecture specific folder then return false
// to allow normal P/Invoke searching behavior when the library is called
return false;
}
// If successful this will return a handle to the library
libraryHandle = IsUnix ? UnixLoader.LoadLibrary(file.FullName) : WindowsLoader.LoadLibrary(file.FullName);
if (libraryHandle == IntPtr.Zero)
{
int lastError = Marshal.GetLastWin32Error();
var exception = new System.ComponentModel.Win32Exception(lastError);
LastException = exception;
}
else
{
LastException = null;
NativeHandles.Value[file.Name] = libraryHandle;
}
return libraryHandle != IntPtr.Zero;
}
}
[SuppressUnmanagedCodeSecurity]
[SecurityCritical]
static class WindowsLoader
{
public static IntPtr LoadLibrary(string fileName)
{
return LoadLibraryEx(fileName, IntPtr.Zero, LOAD_WITH_ALTERED_SEARCH_PATH);
}
// Search for dependencies in the library's directory rather than the calling process's directory
const uint LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008;
[DllImport("kernel32", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true)]
static extern IntPtr LoadLibraryEx(string fileName, IntPtr reservedNull, uint flags);
}
[SuppressUnmanagedCodeSecurity]
[SecurityCritical]
static class UnixLoader
{
public static IntPtr LoadLibrary(string fileName)
{
return dlopen(fileName, RTLD_NOW);
}
const int RTLD_NOW = 2;
[DllImport("libdl.so", SetLastError = true)]
static extern IntPtr dlopen(String fileName, int flags);
}
}
}

60
src/Providers.OpenBLAS/OpenBlasControl.cs

@ -0,0 +1,60 @@
// <copyright file="OpenBlasControl.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// https://numerics.mathdotnet.com
// https://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2021 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 MathNet.Numerics.Providers.OpenBLAS.LinearAlgebra;
namespace MathNet.Numerics.Providers.OpenBLAS
{
public static class OpenBlasControl
{
internal const string EnvVarOpenBLASProviderPath = "MathNetNumericsOpenBLASProviderPath";
/// <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()
{
OpenBlasLinearAlgebraControl.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 = OpenBlasLinearAlgebraControl.TryUseNativeOpenBLAS();
return linearAlgebra;
}
}
}

6
src/Numerics/Providers/Common/OpenBlas/OpenBlasProvider.cs → src/Providers.OpenBLAS/OpenBlasProvider.cs

@ -27,12 +27,10 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System;
using System.Collections.Generic;
namespace MathNet.Numerics.Providers.Common.OpenBlas
namespace MathNet.Numerics.Providers.OpenBLAS
{
public static class OpenBlasProvider
{
@ -172,5 +170,3 @@ namespace MathNet.Numerics.Providers.Common.OpenBlas
}
}
}
#endif

6
src/Numerics/Providers/Common/OpenBlas/OpenBlasProviderCapabilities.cs → src/Providers.OpenBLAS/OpenBlasProviderCapabilities.cs

@ -27,9 +27,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
namespace MathNet.Numerics.Providers.Common.OpenBlas
namespace MathNet.Numerics.Providers.OpenBLAS
{
internal enum ProviderPlatform : int
{
@ -51,5 +49,3 @@ namespace MathNet.Numerics.Providers.Common.OpenBlas
LinearAlgebraMinor = 129
}
}
#endif

34
src/Providers.OpenBLAS/Providers.OpenBLAS.csproj

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net5.0;net461;net40;netstandard2.0</TargetFrameworks>
<AssemblyName>MathNet.Numerics.Providers.OpenBLAS</AssemblyName>
<RootNamespace>MathNet.Numerics.Providers.OpenBLAS</RootNamespace>
<IsPackable>true</IsPackable>
<PackageId>MathNet.Numerics.Providers.OpenBLAS$(PackageIdSuffix)</PackageId>
<VersionPrefix>4.15.0</VersionPrefix>
<VersionSuffix></VersionSuffix>
<Title>Math.NET Numerics OpenBLAS Provider$(TitleSuffix)</Title>
<Description>Math.NET Numerics is the numerical foundation of the Math.NET project, aiming to provide methods and algorithms for numerical computations in science, engineering and every day use. Supports .Net 5.0 or higher, .NET Standard 2.0 and .NET Framework 4.0 or higher, on Windows, Linux and Mac.$(DescriptionSuffix)</Description>
<PackageReleaseNotes>Precision: Round (with integer part rounding) ~Jon Larborn
Precision: RoundToMultiple, RoundToPower
F#: BigRational.FromDecimal ~Brian Berns</PackageReleaseNotes>
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
<GeneratePackageOnBuild>false</GeneratePackageOnBuild>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<EnableDefaultCompileItems>true</EnableDefaultCompileItems>
<NoWarn>1701;1702;1705;1591;1573</NoWarn>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net40'">
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.Serialization" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Numerics\Numerics.csproj" />
</ItemGroup>
<Import Project="..\..\.paket\Paket.Restore.targets" />
</Project>

8
src/Numerics/Providers/Common/OpenBlas/SafeNativeMethods.cs → src/Providers.OpenBLAS/SafeNativeMethods.cs

@ -26,15 +26,13 @@
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
#if NATIVE
using System.Runtime.InteropServices;
using System.Security;
using MathNet.Numerics.Providers.LinearAlgebra;
using MathNet.Numerics.Providers.LinearAlgebra.OpenBlas;
using MathNet.Numerics.Providers.OpenBLAS.LinearAlgebra;
using Complex = System.Numerics.Complex;
namespace MathNet.Numerics.Providers.Common.OpenBlas
namespace MathNet.Numerics.Providers.OpenBLAS
{
/// <summary>
/// P/Invoke methods to the native math libraries.
@ -301,5 +299,3 @@ namespace MathNet.Numerics.Providers.Common.OpenBlas
#endregion LAPACK
}
}
#endif

1
src/Providers.OpenBLAS/paket.references

@ -0,0 +1 @@
Microsoft.NETFramework.ReferenceAssemblies
Loading…
Cancel
Save