public ETan(string filename) { z = MatlabReader.Read <double>(filename, "etan_z").Column(0); rms = MatlabReader.Read <Complex>(filename, "etan_rms").Column(0); this.filename = filename; name = System.IO.Path.GetFileName(filename); }
public void CalculateGraphTest() { var testData = MatlabReader.ReadAll <double>("data.mat")["Data"]; var testResult = MatlabReader.ReadAll <double>("testResult.mat")["SecPathKJ"]; Algorithm algorithm = new Algorithm(); Vector <double> result = Vector <double> .Build.Dense(512, 0); //for (int i = 0; i < testData.RowCount; i = i + 512) //{ for (int j = 0; j < 1; j++) { //var chanData = testData.Column(j, i, 512); //var outData = testData.Column(16, i, 512); var chanData = testData.Column(j); var outData = testData.Column(16); result = algorithm.Nlms(outData, chanData, 512, 0.1); } //} for (int i = 0; i < testResult.RowCount; i++) { if (Math.Abs(testResult[i, 0] - result[i]) > 1e-10) { Assert.Fail(); } } }
public static void Main(string[] args) { const string dataset = "nips12raw_str602"; string filename = Path.Combine(DataPath, dataset + ".mat"); var dataList = MatlabReader.List(filename); var counts = MatlabReader.Read <double>(filename, "counts"); var wc = MatlabReader.Read <double>(filename, "wc"); // var lda = new LDA(wc.RowCount, 20); const int batches = 100; var lda = new LDAShared(batches, wc.RowCount, 20); var wordsInDoc = counts.EnumerateColumns() .Select(row => row.EnumerateIndexed().ToDictionary(ia => ia.Item1, ia => (int)ia.Item2)) .ToArray(); Dirichlet[] postTheta; Dirichlet[] postPhi; lda.Infer(wordsInDoc, 1.0, 1.0, out postTheta, out postPhi); var ldaPredict = new LDAPredictionModel(wc.RowCount, 20); var predictions = ldaPredict.Predict(postTheta, postPhi); foreach (var prediction in predictions) { Console.WriteLine(prediction); } }
public static void TestReadingMat() { // test reading a .mat file // string path = "/nfs/nhome/live/wittawat/SHARE/gatsby/research/code/saved/test_mat.mat"; string path = "../../Saved/test_mat1.mat"; Dictionary <string, Object> dict = MatlabReader.Read(path); // a struct is read as a Dictionary<string, Object> Console.WriteLine("s: {0}", dict["s"]); Dictionary <string, Object> s = (Dictionary <string, Object>)dict["s"]; Object aobj = s["a"]; Console.WriteLine("s.a: {0}", aobj); Console.WriteLine("s.st: {0}", s["st"]); // cell array (1d) is read as Object[,] (2d) Object[,] cobj = (Object[, ])s["c"]; Console.WriteLine("s.c: {0}", cobj[0, 1]); // a numerical array is read as MicrosoftResearch.Infer.Maths.Matrix Object lobj = s["l"]; Console.WriteLine("s.l: {0}", lobj.GetType()); // mat file cannot contain Matlab objects. Otherwise, an exception // is thrown. }
public ActionResult Index() { var t = _dbContext.BasicInformations.First(); var CalCount = MatlabReader.Read <double>(t.PathToData, "Vk_record").Column(0); return(Ok(CalCount.ToList().Where((c, i) => i % 50 == 0))); }
public void SolidPoint3D() { var projcoord = MatlabReader.Read <double>("..\\..\\..\\MGroup.IGA.Tests\\InputFiles\\SolidPointProjectiveCP.mat", "projcoord"); var projectiveCPCoordinates = new double[735, 4]; var counter = 0; for (int i = 0; i < numberOfCPKsi3D + 1; i++) { for (int j = 0; j < numberOfCPHeta3D + 1; j++) { for (int k = 0; k < numberofCPZeta3D + 1; k++) { var index = k * (numberOfCPHeta3D + 1) * (numberOfCPKsi3D + 1) + j * (numberOfCPKsi3D + 1) + i; projectiveCPCoordinates[counter, 0] = projcoord.At(index, 0); projectiveCPCoordinates[counter, 1] = projcoord.At(index, 1); projectiveCPCoordinates[counter, 2] = projcoord.At(index, 2); projectiveCPCoordinates[counter, 3] = projcoord.At(index, 3); } } } var point = ParaviewNurbs3D.SolidPoint3D(numberOfCPKsi3D, degreeKsi3D, knotValueVectorKsi3D, numberOfCPHeta3D, degreeHeta3D, knotValueVectorHeta3D, numberofCPZeta3D, degreeZeta3D, knotValueVectorZeta3D, projectiveCPCoordinates, coordinateKsi3D, coordinateHeta3D, coordinateZeta3D); var expectedPoint = new double[] { 0.75, 0, 0, 1 }; for (int i = 0; i < point.Length; i++) { Utilities.AreValuesEqual(expectedPoint[i], point[i], 1e-14); } }
private void BrowseRefButton_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); if (Directory.Exists(@"C: \Users\ConraN01\Documents\")) { ofd.InitialDirectory = @"C:\Users\ConraN01\Documents\Spyder_WS\MRI_RF_TF_Tool_Project\Test Files for Python Utility\Neuro Orion MRI RF Heating TF Files"; } ofd.Filter = "Matlab MAT (*.mat)|*.mat|All Files (*.*)|*.*"; if (ofd.ShowDialog() != DialogResult.OK) { return; } try { Bkgz = MatlabReader.Read <double>(ofd.FileName, "z").Column(0); BkgSr = MatlabReader.Read <Complex>(ofd.FileName, "Sr").Column(0); BkgFilename = ofd.FileName; BackgroundTFFilenameLabel.Text = System.IO.Path.GetFileNameWithoutExtension(ofd.FileName); } catch (Exception ex) { Bkgz = null; BkgSr = null; BackgroundTFFilenameLabel.Text = "..."; BkgFilename = null; Replot(); MessageBox.Show(this, ex.ToString(), "TF Reading Error"); return; } Replot(); }
private void BrowseTransferFunctionButton_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.InitialDirectory = @"C:\Users\ConraN01\Documents\Spyder_WS\MRI_RF_TF_Tool_Project\Test Files for Python Utility\Neuro Orion MRI RF Heating TF Files"; ofd.Filter = "Matlab MAT (*.mat)|*.mat|All Files (*.*)|*.*"; ofd.Title = "Select TF files..."; if (ofd.ShowDialog() != DialogResult.OK) { return; } if (ofd.FileNames.Length == 0) { MessageBox.Show(this, "No files selected", "TF Reading Error"); return; } try { var f = ofd.FileName; var shortfname = System.IO.Path.GetFileName(f); var mz = MatlabReader.Read <double>(f, "z"); var msr = MatlabReader.Read <Complex>(f, "Sr"); // Take either first row or column.... if (mz.ColumnCount == 1 && mz.RowCount > 1) { TFz = mz.Column(0); } else if (mz.RowCount == 1 && mz.ColumnCount > 1) { TFz = mz.Row(0); } else { throw new FormatException("Input matrix must be 1xN or Nx1, with N>=2"); } if (msr.ColumnCount == 1 && msr.RowCount > 1) { TFSr = msr.Column(0); } else if (mz.RowCount == 1 && msr.ColumnCount > 1) { TFSr = msr.Row(0); } else { throw new FormatException("Input matrix must be 1xN or Nx1, with N>=2"); } if (TFz.Count != TFSr.Count) { throw new FormatException("Input matrices must be of equal dimensions"); } TransferFunctionFilenameLabel.Text = shortfname; TFFileFullPath = ofd.FileName; ViewTFButton.Enabled = true; } catch (Exception ex) { MessageBox.Show(this, "TF File could not be opened!\n\n" + ex.Message, "Error loading TF file", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void CompareTFButton_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); List <Vector <double> > ZList = new List <Vector <double> >(); List <Vector <Complex> > SrList = new List <Vector <Complex> >(); ofd.InitialDirectory = @"C:\Users\ConraN01\Documents\Spyder_WS\MRI_RF_TF_Tool_Project\Test Files for Python Utility\Neuro Orion MRI RF Heating TF Files"; ofd.Multiselect = true; ofd.Filter = "Matlab MAT (*.mat)|*.mat|All Files (*.*)|*.*"; if (ofd.ShowDialog() != DialogResult.OK) { return; } if (ofd.FileNames.Length == 0) { MessageBox.Show(this, "No files selected", "TF Reading Error"); } try { foreach (string f in ofd.FileNames) { ZList.Add(MatlabReader.Read <double>(f, "z").Column(0)); SrList.Add(MatlabReader.Read <Complex>(f, "Sr").Column(0)); } } catch (Exception ex) { MessageBox.Show(this, ex.ToString(), "TF Reading Error"); return; } TFComparisonForm tfcf = new TFComparisonForm(ofd.FileNames, ZList, SrList); tfcf.Show(); }
//[ValidateAntiForgeryToken] public ActionResult Create([FromBody] ddd collection) { Console.WriteLine(collection); var dateTimes = collection.selectedOptiont.Select(s => { if (DateTime.TryParse(s, out DateTime dt)) { return(dt); } else { // 这种时间应该是不会有对应的记录的 return(DateTime.MinValue); } }); var t = _dbContext.BasicInformations .Where(s => dateTimes.Any(t => s.DateTime == t)); List <IEnumerable <double> > data = new(t.Count()); foreach (var item in t) { // https://stackoverflow.com/questions/267033/getting-odd-even-part-of-a-sequence-with-linq data.Add(MatlabReader.Read <double>(item.PathToData, collection.dataItem).Column(0) .ToList().Where((c, i) => i % 50 == 0)); } //t.Select(s => ); //var CalCount = MatlabReader.Read<double>(t.First().PathToData, "Vk_record").Column(0); var dates = _dbContext.BasicInformations.Take(3).Select(s => s.DateTime); return(Ok(new { collection, data, dates })); //return Ok(collection); }
public void CanReadFirstMatrix() { var matrix = MatlabReader.Read <double>("./data/Matlab/A.mat"); Assert.AreEqual(100, matrix.RowCount); Assert.AreEqual(100, matrix.ColumnCount); Assert.AreEqual(typeof(LinearAlgebra.Double.DenseMatrix), matrix.GetType()); AssertHelpers.AlmostEqual(100.108979553704, matrix.FrobeniusNorm(), 5); }
public void CanReadFloatNamedSparseMatrix() { var matrix = MatlabReader.Read <float>("./data/Matlab/sparse-small.mat", "S"); Assert.AreEqual(100, matrix.RowCount); Assert.AreEqual(100, matrix.ColumnCount); Assert.AreEqual(typeof(LinearAlgebra.Single.SparseMatrix), matrix.GetType()); AssertHelpers.AlmostEqual(17.6385090630805f, matrix.FrobeniusNorm(), 6); }
public void CanReadNamedMatrices() { var matrices = MatlabReader.ReadAll <double>("./data/Matlab/collection.mat", "Ad", "Au64"); Assert.AreEqual(2, matrices.Count); foreach (var matrix in matrices) { Assert.AreEqual(typeof(LinearAlgebra.Double.DenseMatrix), matrix.Value.GetType()); } }
public void CanReadFloatAllMatrices() { var matrices = MatlabReader.ReadAll <float>("./data/Matlab/collection.mat"); Assert.AreEqual(30, matrices.Count); foreach (var matrix in matrices) { Assert.AreEqual(typeof(LinearAlgebra.Single.DenseMatrix), matrix.Value.GetType()); } }
/// <summary> /// Lee una matriz con una matriz de entrada de filas como numero de muestras y columnas como cararateristicas /// </summary> /// <param name="path">Ruta al archivo .mat</param> /// <param name="InputKey"> nombre de la matriz de caracteristicas en matlab</param> /// <param name="TargetKey">nombre de la matriz (n x 1) de targets en Matlab</param> /// <returns>entrega una lista con los registros de eentradas y objetivo</returns> public static List <NetEvaluation.InputAndTarget> ReadDataMatlabMatrix(string path, string InputKey, string TargetKey) { Dictionary <string, Matrix <float> > ms = MatlabReader.ReadAll <float>(path); List <NetEvaluation.InputAndTarget> list = new List <NetEvaluation.InputAndTarget>(); for (int i = 0; i < ms.Values.First().RowCount; i++) { list.Add(new NetEvaluation.InputAndTarget(ms[InputKey].Row(i).ToArray(), ms[TargetKey].At(i, 0))); } return(list); }
public void CanReadFloatNamedSparseMatrix() { using (var stream = TestData.Data.ReadStream("Matlab.sparse-small.mat")) { var matrix = MatlabReader.Read <float>(stream, "S"); Assert.AreEqual(100, matrix.RowCount); Assert.AreEqual(100, matrix.ColumnCount); Assert.AreEqual(typeof(LinearAlgebra.Single.SparseMatrix), matrix.GetType()); AssertHelpers.AlmostEqual(17.6385090630805f, matrix.FrobeniusNorm(), 6); } }
public Disturbance() { IsWindEnabled = Configuration.IsWindEnabled; if (IsWindEnabled) { CalCount = MatlabReader.Read <double>("./WindModel.mat", "cal_count").Column(0); WindModelState = MatlabReader.Read <double>("./WindModel.mat", "wind_model_state"); Wind = MatlabReader.Read <double>("./WindModel.mat", "wind").Column(0); WindLateral = MatlabReader.Read <double>("./WindModel.mat", "wind_lat").Column(0); } }
public void CanReadFirstMatrix() { using (var stream = TestData.Data.ReadStream("Matlab.A.mat")) { var matrix = MatlabReader.Read <double>(stream); Assert.AreEqual(100, matrix.RowCount); Assert.AreEqual(100, matrix.ColumnCount); Assert.AreEqual(typeof(LinearAlgebra.Double.DenseMatrix), matrix.GetType()); AssertHelpers.AlmostEqual(100.108979553704, matrix.FrobeniusNorm(), 5); } }
internal void ProbabilisticIndexMap() { //TODO: change the path for cross platform using double[,] dataIn = MatlabReader.ReadMatrix(new double[10, 6400 * 3], @"c:\temp\pim\chand.txt", ' '); Vector[,] pixData = new Vector[10, 6400]; for (int i = 0; i < pixData.GetLength(0); i++) { int ct = 0; for (int j = 0; j < pixData.GetLength(1); j++) { pixData[i, j] = Vector.FromArray(dataIn[i, ct++], dataIn[i, ct++], dataIn[i, ct++]); } } Range images = new Range(pixData.GetLength(0)); Range pixels = new Range(pixData.GetLength(1)); VariableArray2D <Vector> pixelData = Variable.Constant(pixData, images, pixels); // For each image we have a palette of L multivariate Gaussians Range L = new Range(2); VariableArray2D <Vector> means = Variable.Array <Vector>(images, L).Named("means"); means[images, L] = Variable.VectorGaussianFromMeanAndPrecision( Vector.FromArray(0.5, 0.5, 0.5), PositiveDefiniteMatrix.Identity(3)).ForEach(images, L); VariableArray2D <PositiveDefiniteMatrix> precs = Variable.Array <PositiveDefiniteMatrix>(images, L).Named("precs"); precs[images, L] = Variable.WishartFromShapeAndScale(1.0, PositiveDefiniteMatrix.Identity(3)).ForEach(images, L); // Across all pixels we have a VariableArray <Vector> pi = Variable.Array <Vector>(pixels); pi[pixels] = Variable.Dirichlet(L, new double[] { 1.1, 1.0 }).ForEach(pixels); // For each pixel of each image we have a discrete indicator VariableArray2D <int> ind = Variable.Array <int>(images, pixels).Named("ind"); ind[images, pixels] = Variable.Discrete(pi[pixels]).ForEach(images); using (Variable.ForEach(pixels)) { using (Variable.ForEach(images)) { using (Variable.Switch(ind[images, pixels])) { pixelData[images, pixels] = Variable.VectorGaussianFromMeanAndPrecision(means[images, ind[images, pixels]], precs[images, ind[images, pixels]]); } } } InferenceEngine ie = new InferenceEngine(new VariationalMessagePassing()); ie.ShowProgress = true; ie.NumberOfIterations = 5; Console.WriteLine("Dist over L: " + ie.Infer(pi)); }
public void CanReadNamedMatrix() { var matrices = MatlabReader.ReadAll <double>("./data/Matlab/collection.mat", "Ad"); Assert.AreEqual(1, matrices.Count); var ad = matrices["Ad"]; Assert.AreEqual(100, ad.RowCount); Assert.AreEqual(100, ad.ColumnCount); AssertHelpers.AlmostEqual(100.431635988639, ad.FrobeniusNorm(), 5); Assert.AreEqual(typeof(LinearAlgebra.Double.DenseMatrix), ad.GetType()); }
public void CanWriteComplexMatrices() { var mat1 = Matrix <Complex> .Build.Dense(5, 3); for (var i = 0; i < mat1.ColumnCount; i++) { mat1[i, i] = new Complex(i + .1, i + .1); } var mat2 = Matrix <Complex> .Build.Dense(4, 5); for (var i = 0; i < mat2.RowCount; i++) { mat2[i, i] = new Complex(i + .1, i + .1); } var mat3 = Matrix <Complex> .Build.Sparse(5, 4); mat3[0, 0] = new Complex(1.1, 1.1); mat3[0, 2] = new Complex(2.2, 2.2); mat3[4, 3] = new Complex(3.3, 3.3); var mat4 = Matrix <Complex> .Build.Sparse(3, 5); mat4[0, 0] = new Complex(1.1, 1.1); mat4[0, 2] = new Complex(2.2, 2.2); mat4[2, 4] = new Complex(3.3, 3.3); Matrix <Complex>[] write = { mat1, mat2, mat3, mat4 }; string[] names = { "mat1", "dense_matrix_2", "s1", "sparse2" }; if (File.Exists("testz.mat")) { File.Delete("testz.mat"); } MatlabWriter.Write("testz.mat", write, names); var read = MatlabReader.ReadAll <Complex>("testz.mat", names); Assert.AreEqual(write.Length, read.Count); for (var i = 0; i < write.Length; i++) { var w = write[i]; var r = read[names[i]]; Assert.AreEqual(w.RowCount, r.RowCount); Assert.AreEqual(w.ColumnCount, r.ColumnCount); Assert.IsTrue(w.Equals(r)); } File.Delete("testz.mat"); }
public void CanReadFloatAllMatrices() { using (var stream = TestData.Data.ReadStream("Matlab.collection.mat")) { var matrices = MatlabReader.ReadAll <float>(stream); Assert.AreEqual(30, matrices.Count); foreach (var matrix in matrices) { Assert.AreEqual(typeof(LinearAlgebra.Single.DenseMatrix), matrix.Value.GetType()); } } }
public void CanWriteDoubleMatrices() { Matrix <double> mat1 = Matrix <double> .Build.Dense(5, 5); for (var i = 0; i < mat1.ColumnCount; i++) { mat1[i, i] = i + .1; } Matrix <double> mat2 = Matrix <double> .Build.Dense(4, 5); for (var i = 0; i < mat2.RowCount; i++) { mat2[i, i] = i + .1; } Matrix <double> mat3 = Matrix <double> .Build.Sparse(5, 4); mat3[0, 0] = 1.1; mat3[0, 2] = 2.2; mat3[4, 3] = 3.3; Matrix <double> mat4 = Matrix <double> .Build.Sparse(3, 5); mat4[0, 0] = 1.1; mat4[0, 2] = 2.2; mat4[2, 4] = 3.3; Matrix <double>[] write = { mat1, mat2, mat3, mat4 }; string[] names = { "mat1", "dense_matrix_2", "s1", "sparse2" }; if (File.Exists("testd.mat")) { File.Delete("testd.mat"); } MatlabWriter.Write("testd.mat", write, names); var read = MatlabReader.ReadAll <double>("testd.mat", names); Assert.AreEqual(write.Length, read.Count); for (var i = 0; i < write.Length; i++) { var w = write[i]; var r = read[names[i]]; Assert.AreEqual(w.RowCount, r.RowCount); Assert.AreEqual(w.ColumnCount, r.ColumnCount); Assert.IsTrue(w.Equals(r)); } File.Delete("testd.mat"); }
static void Main(string[] args) { if (!System.Console.IsOutputRedirected) { System.Console.Clear(); } CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); System.Console.WriteLine("Principal Component Analysis ex.7_pca"); System.Console.WriteLine("=====================================\n"); var M = Matrix <double> .Build; var V = Vector <double> .Build; //// ================== Part 1: Load Example Dataset =================== // We start this exercise by using a small dataset that is easily to // visualize // // read all matrices of a file by name into a dictionary Dictionary <string, Matrix <double> > mr = MatlabReader.ReadAll <double>("data\\ex7data1.mat"); // loads dataset System.Console.WriteLine("Loading dataset....\n"); Matrix <double> X = mr["X"]; System.Console.WriteLine(X); //// =============== Part 2: Principal Component Analysis =============== // You should now implement PCA, a dimension reduction technique. You // should complete the code in pca.m // System.Console.WriteLine("\nRunning PCA on example dataset.\n\n"); // Before running PCA, it is important to first normalize X System.Console.WriteLine("Features normalization..."); (Matrix <double> X_norm, Matrix <double> mu, Matrix <double> sigma)norm_res; norm_res = FeatureNormalize(X); System.Console.WriteLine(norm_res.X_norm); // Run PCA (Matrix <double> U, Vector <double> S)pca_res; pca_res = pca(norm_res.X_norm); System.Console.WriteLine("Top eigenvector: \n"); System.Console.WriteLine(" U(:,1) = {0:f6} {1:f6} \n", pca_res.U[0, 0], pca_res.U[1, 0]); System.Console.WriteLine("\n(you should expect to see -0.707107 -0.707107)\n"); Pause(); }
public static void TestLoadingMatData() { string path = Config.PathToSavedFile("data/banknote_norm.mat"); Dictionary <string, object> dict = MatlabReader.Read(path); Matrix x = (Matrix)dict["X"]; Console.WriteLine(x); Console.WriteLine(); Matrix y = (Matrix)dict["Y"]; Console.WriteLine(y); }
public void CanReadNamedMatrices() { using (var stream = TestData.Data.ReadStream("Matlab.collection.mat")) { var matrices = MatlabReader.ReadAll <double>(stream, "Ad", "Au64"); Assert.AreEqual(2, matrices.Count); foreach (var matrix in matrices) { Assert.AreEqual(typeof(LinearAlgebra.Double.DenseMatrix), matrix.Value.GetType()); } } }
internal void LogisticIrtTest() { Variable <int> numStudents = Variable.New <int>().Named("numStudents"); Range student = new Range(numStudents); VariableArray <double> ability = Variable.Array <double>(student).Named("ability"); ability[student] = Variable.GaussianFromMeanAndPrecision(0, 1e-6).ForEach(student); Variable <int> numQuestions = Variable.New <int>().Named("numQuestions"); Range question = new Range(numQuestions); VariableArray <double> difficulty = Variable.Array <double>(question).Named("difficulty"); difficulty[question] = Variable.GaussianFromMeanAndPrecision(0, 1e-6).ForEach(question); VariableArray <double> discrimination = Variable.Array <double>(question).Named("discrimination"); discrimination[question] = Variable.Exp(Variable.GaussianFromMeanAndPrecision(0, 1).ForEach(question)); VariableArray2D <bool> response = Variable.Array <bool>(student, question).Named("response"); response[student, question] = Variable.BernoulliFromLogOdds(((ability[student] - difficulty[question]).Named("minus") * discrimination[question]).Named("product")); bool[,] data; double[] discriminationTrue = new double[0]; bool useDummyData = false; if (useDummyData) { data = new bool[4, 2]; for (int i = 0; i < data.GetLength(0); i++) { for (int j = 0; j < data.GetLength(1); j++) { data[i, j] = (i > j); } } } else { // simulated data // also try IRT2PL_10_250.mat //TODO: change path for cross platform using Dictionary <string, object> dict = MatlabReader.Read(@"..\..\..\Tests\Data\IRT2PL_10_1000.mat"); Matrix m = (Matrix)dict["Y"]; data = ConvertToBool(m.ToArray()); m = (Matrix)dict["discrimination"]; discriminationTrue = Util.ArrayInit(data.GetLength(1), i => m[i]); } numStudents.ObservedValue = data.GetLength(0); numQuestions.ObservedValue = data.GetLength(1); response.ObservedValue = data; InferenceEngine engine = new InferenceEngine(); engine.Algorithm = new VariationalMessagePassing(); Console.WriteLine(StringUtil.JoinColumns(engine.Infer(discrimination), " should be ", StringUtil.ToString(discriminationTrue))); }
internal void ProbabilisticIndexMapNoGate() { //TODO: change path for cross platform using double[,] pixData = MatlabReader.ReadMatrix(new double[10, 6400], @"c:\temp\pim\chand2.txt", ' '); Range images = new Range(pixData.GetLength(0)); Range pixels = new Range(pixData.GetLength(1)); VariableArray2D <double> pixelData = Variable.Constant(pixData, images, pixels); //pixelData.QuoteInMSL = false; // For each image we have a palette of L multivariate Gaussians VariableArray <double> means = Variable.Array <double>(images).Named("means"); means[images] = Variable.GaussianFromMeanAndPrecision(0.5, 1).ForEach(images); VariableArray <double> precs = Variable.Array <double>(images).Named("precs"); precs[images] = Variable.GammaFromShapeAndScale(1.0, 1.0).ForEach(images); // Across all pixels we have a VariableArray <Vector> pi = Variable.Array <Vector>(pixels).Named("pi"); Dirichlet[] dinit = new Dirichlet[pixels.SizeAsInt]; for (int i = 0; i < dinit.Length; i++) { double d = Rand.Double(); dinit[i] = new Dirichlet(1.0 + d / 10, 1.0 - d / 10); } pi[pixels] = Variable.Dirichlet(new double[] { 1.0 }).ForEach(pixels); // For each pixel of each image we have a discrete indicator VariableArray2D <int> ind = Variable.Array <int>(images, pixels).Named("ind"); ind[images, pixels] = Variable.Discrete(pi[pixels]).ForEach(images); using (Variable.ForEach(pixels)) { using (Variable.ForEach(images)) { pixelData[images, pixels] = Variable.GaussianFromMeanAndPrecision(means[images], //10); precs[images]); Variable.ConstrainEqualRandom(ind[images, pixels], Discrete.Uniform(1)); } } InferenceEngine ie = new InferenceEngine(new VariationalMessagePassing()); ie.ModelName = "PIM_NoGate"; ie.NumberOfIterations = 8; ie.ShowTimings = true; DistributionArray <Dirichlet> piDist = ie.Infer <DistributionArray <Dirichlet> >(pi); //Console.WriteLine("Dist over pi: " + ie.Infer(pi)); //TODO: change path for cross platform using WriteMatrix(piDist.ToArray(), @"C:\temp\pim\results.txt"); }
public void MatlabWriteNumericNameTest() { string fileName = $"{System.IO.Path.GetTempPath()}MatlabWriteNumericNameTest{Environment.CurrentManagedThreadId}.mat"; using (MatlabWriter writer = new MatlabWriter(fileName)) { writer.Write("24", new int[0]); } Dictionary <string, object> vars = MatlabReader.Read(fileName); int[] ints = (int[])vars["24"]; Assert.Empty(ints); }
public void CanReadFloatNamedMatrix() { using (var stream = TestData.Data.ReadStream("Matlab.collection.mat")) { var matrices = MatlabReader.ReadAll <float>(stream, "Ad"); Assert.AreEqual(1, matrices.Count); var ad = matrices["Ad"]; Assert.AreEqual(100, ad.RowCount); Assert.AreEqual(100, ad.ColumnCount); AssertHelpers.AlmostEqual(100.431635988639f, ad.FrobeniusNorm(), 6); Assert.AreEqual(typeof(LinearAlgebra.Single.DenseMatrix), ad.GetType()); } }