Skip to content

Instantly share code, notes, and snippets.

@eliziario
Created June 23, 2017 04:32
Show Gist options
  • Save eliziario/7cc301f4a33e408f30073fab9864e7b5 to your computer and use it in GitHub Desktop.
Save eliziario/7cc301f4a33e408f30073fab9864e7b5 to your computer and use it in GitHub Desktop.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlDouble[][] MatrixKernel(SqlDouble[,] param)
{
Double[][] val = Array.ConvertAll(param.ToJaggedArray(),
el => Array.ConvertAll<SqlDouble, Double>(el, x => x.Value));
Matrix A = DenseMatrix.OfArray(CreateRectangularArray<Double>(val));
Vector<double>[] nullspace = A.Kernel();
return nullspace.Select(i => i.Select(j => new SqlDouble(j)).ToArray()).ToArray();
}
static T[,] CreateRectangularArray<T>(T[][] arrays)
{
int minorLength = arrays[0].Length;
T[,] ret = new T[arrays.Length, minorLength];
for (int i = 0; i < arrays.Length; i++)
{
var array = arrays[i];
if (array.Length != minorLength)
{
throw new ArgumentException
("All arrays must be the same length");
}
for (int j = 0; j < minorLength; j++)
{
ret[i, j] = array[j];
}
}
return ret;
}
}
internal static class ExtensionMethods
{
internal static T[][] ToJaggedArray<T>(this T[,] twoDimensionalArray)
{
int rowsFirstIndex = twoDimensionalArray.GetLowerBound(0);
int rowsLastIndex = twoDimensionalArray.GetUpperBound(0);
int numberOfRows = rowsLastIndex + 1;
int columnsFirstIndex = twoDimensionalArray.GetLowerBound(1);
int columnsLastIndex = twoDimensionalArray.GetUpperBound(1);
int numberOfColumns = columnsLastIndex + 1;
T[][] jaggedArray = new T[numberOfRows][];
for (int i = rowsFirstIndex; i <= rowsLastIndex; i++)
{
jaggedArray[i] = new T[numberOfColumns];
for (int j = columnsFirstIndex; j <= columnsLastIndex; j++)
{
jaggedArray[i][j] = twoDimensionalArray[i, j];
}
}
return jaggedArray;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment