Exemple #1
0
        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)));
        }
Exemple #2
0
        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);
            }
        }
Exemple #3
0
        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);
            }
        }
        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);
            }
        }
Exemple #5
0
        //[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);
        }
Exemple #6
0
        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();
        }
Exemple #7
0
        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.
        }
Exemple #8
0
 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);
 }
Exemple #9
0
        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();
        }
Exemple #10
0
        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);
        }
Exemple #11
0
        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);
        }
Exemple #12
0
 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 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 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);
     }
 }
Exemple #15
0
        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);
        }
Exemple #16
0
        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)));
        }
Exemple #17
0
        // event RecordShipStateEvent;

        public Ship()
        {
            DeckEnable   = Configuration.IsDeckCompensationEnabled;
            omega_d_2i   = vb.Dense(new double[] { omega_dx_2i, omega_dy_2i, omega_dz_2i });
            DeckPosition = Position;
            if (DeckEnable)
            {
                ForwardFilterState        = MatlabReader.Read <double>("./ForwardFilter.mat", "forward_filter_state");
                CurrentDeckPredict        = MatlabReader.Read <double>("./ForwardFilter.mat", "current_deck_predict").Column(0);
                CurrentDeckControl        = MatlabReader.Read <double>("./ForwardFilter.mat", "current_deck_control").Column(0);
                CurrentDeckLateralControl = MatlabReader.Read <double>("./ForwardFilter.mat", "current_deck_control_lat").Column(0);
            }
        }
Exemple #18
0
        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);
        }
Exemple #19
0
        //[DeploymentItem(@"Data\test.mat", "Data")]
        public void MatlabWriterTest()
        {
            Dictionary <string, object> dict = MatlabReader.Read(Path.Combine(TestUtils.DataFolderPath, "test.mat"));
            string fileName = $"{System.IO.Path.GetTempPath()}MatlabWriterTest{Environment.CurrentManagedThreadId}.mat";

            using (MatlabWriter writer = new MatlabWriter(fileName))
            {
                foreach (var entry in dict)
                {
                    writer.Write(entry.Key, entry.Value);
                }
            }
            MatlabReaderTester(fileName);
        }
Exemple #20
0
 private void OpenMatFile()
 {
     //TODO: Change to button reaction or.. as a resource in debug
     using (var reader = new StreamReader(@"C:\Users\Lenovo\Desktop\ImageData.mat"))
     {
         _faceCoordinates = MatlabReader.Read <double>(reader.BaseStream, "SubDir_Data");
         List <double> list = new List <double>();
         for (int i = 0; i < 8; ++i)
         {
             list.Add(_faceCoordinates[i, 0]);
         }
     }
     ;
 }
Exemple #21
0
        static private void TestSparseGeneration(string Path)
        {
            var UniformMat = MatlabReader.Read <double> (Path, "Tri");
            var NodeCount  = MatlabReader.Read <double> (Path, "NodeCount");
            var Count      = NodeCount.ToArray();
            var Delaunay   = new int[UniformMat.RowCount, UniformMat.ColumnCount];

            for (int i = 0; i < Delaunay.GetLength(0); i++)
            {
                for (int j = 0; j < Delaunay.GetLength(1); j++)
                {
                    Delaunay [i, j] = (int)UniformMat [i, j] - 1;
                }
            }
            var myArray = new Sparse(Delaunay, (int)Count[0, 0]);
        }
Exemple #22
0
        //[DeploymentItem(@"Data\IRT2PL_10_250.mat", "Data")]
        public void MatlabReaderTest2()
        {
            Dictionary <string, object> dict = MatlabReader.Read(Path.Combine(TestUtils.DataFolderPath, "IRT2PL_10_250.mat"));

            Assert.Equal(5, dict.Count);
            Matrix m = (Matrix)dict["Y"];

            Assert.True(m.Rows == 250);
            Assert.True(m.Cols == 10);
            Assert.True(m[0, 1] == 0.0);
            Assert.True(m[1, 0] == 1.0);
            m = (Matrix)dict["difficulty"];
            Assert.True(m.Rows == 10);
            Assert.True(m.Cols == 1);
            Assert.True(MMath.AbsDiff(m[1], 0.7773) < 2e-4);
        }
Exemple #23
0
        //[DeploymentItem(@"Data\test.mat", "Data")]
        public void MatlabWriterTest()
        {
            Dictionary <string, object> dict = MatlabReader.Read(Path.Combine(
#if NETCORE
                                                                     Path.GetDirectoryName(typeof(PsychTests).Assembly.Location), // work dir is not the one with Microsoft.ML.Probabilistic.Tests.dll on netcore and neither is .Location on netfull
#endif
                                                                     "Data", "test.mat"));
            string fileName = $"{System.IO.Path.GetTempPath()}MatlabWriterTest{Environment.CurrentManagedThreadId}.mat";

            using (MatlabWriter writer = new MatlabWriter(fileName))
            {
                foreach (var entry in dict)
                {
                    writer.Write(entry.Key, entry.Value);
                }
            }
            MatlabReaderTester(fileName);
        }
        public void MatlabMatrixRoundtrip()
        {
            var denseDouble = Matrix <double> .Build.Random(20, 20);

            var denseComplex = Matrix <Complex> .Build.Random(10, 10);

            var diagonalDouble = Matrix <double> .Build.DiagonalOfDiagonalArray(new[] { 1.0, 2.0, 3.0 });

            var sparseDouble = Matrix <double> .Build.Sparse(20, 20, (i, j) => i % (j + 1) == 2?i + 10 *j : 0);

            var denseDoubleP    = MatlabWriter.Pack(denseDouble, "denseDouble");
            var denseComplexP   = MatlabWriter.Pack(denseComplex, "denseComplex");
            var diagonalDoubleP = MatlabWriter.Pack(diagonalDouble, "diagonalDouble");
            var sparseDoubleP   = MatlabWriter.Pack(sparseDouble, "sparseDouble");

            Assert.That(MatlabReader.Unpack <double>(denseDoubleP).Equals(denseDouble));
            Assert.That(MatlabReader.Unpack <Complex>(denseComplexP).Equals(denseComplex));
            Assert.That(MatlabReader.Unpack <double>(diagonalDoubleP).Equals(diagonalDouble));
            Assert.That(MatlabReader.Unpack <double>(sparseDoubleP).Equals(sparseDouble));

            Assert.That(MatlabReader.Unpack <double>(denseDoubleP).Storage, Is.TypeOf <DenseColumnMajorMatrixStorage <double> >());
            Assert.That(MatlabReader.Unpack <Complex>(denseComplexP).Storage, Is.TypeOf <DenseColumnMajorMatrixStorage <Complex> >());
            Assert.That(MatlabReader.Unpack <double>(diagonalDoubleP).Storage, Is.TypeOf <SparseCompressedRowMatrixStorage <double> >());
            Assert.That(MatlabReader.Unpack <double>(sparseDoubleP).Storage, Is.TypeOf <SparseCompressedRowMatrixStorage <double> >());

            if (File.Exists("testrt.mat"))
            {
                File.Delete("testrt.mat");
            }

            MatlabWriter.Store("testrt.mat", new[] { denseDoubleP, denseComplexP, diagonalDoubleP, sparseDoubleP });

            Assert.That(MatlabReader.Read <double>("testrt.mat", "denseDouble").Equals(denseDouble));
            Assert.That(MatlabReader.Read <Complex>("testrt.mat", "denseComplex").Equals(denseComplex));
            Assert.That(MatlabReader.Read <double>("testrt.mat", "diagonalDouble").Equals(diagonalDouble));
            Assert.That(MatlabReader.Read <double>("testrt.mat", "sparseDouble").Equals(sparseDouble));

            Assert.That(MatlabReader.Read <double>("testrt.mat", "denseDouble").Storage, Is.TypeOf <DenseColumnMajorMatrixStorage <double> >());
            Assert.That(MatlabReader.Read <Complex>("testrt.mat", "denseComplex").Storage, Is.TypeOf <DenseColumnMajorMatrixStorage <Complex> >());
            Assert.That(MatlabReader.Read <double>("testrt.mat", "diagonalDouble").Storage, Is.TypeOf <SparseCompressedRowMatrixStorage <double> >());
            Assert.That(MatlabReader.Read <double>("testrt.mat", "sparseDouble").Storage, Is.TypeOf <SparseCompressedRowMatrixStorage <double> >());

            File.Delete("testrt.mat");
        }
Exemple #25
0
        private void MatlabReaderTester(string fileName)
        {
            Dictionary <string, object> dict = MatlabReader.Read(fileName);

            Assert.Equal(12, dict.Count);
            Matrix aScalar = (Matrix)dict["aScalar"];

            Assert.Equal(1, aScalar.Rows);
            Assert.Equal(1, aScalar.Cols);
            Assert.Equal(5.0, aScalar[0, 0]);
            Assert.Equal("string", (string)dict["aString"]);
            MatlabReader.ComplexMatrix aComplexScalar = (MatlabReader.ComplexMatrix)dict["aComplexScalar"];
            Assert.Equal(5.0, aComplexScalar.Real[0, 0]);
            Assert.Equal(3.0, aComplexScalar.Imaginary[0, 0]);
            MatlabReader.ComplexMatrix aComplexVector = (MatlabReader.ComplexMatrix)dict["aComplexVector"];
            Assert.Equal(1.0, aComplexVector.Real[0, 0]);
            Assert.Equal(2.0, aComplexVector.Imaginary[0, 0]);
            Assert.Equal(3.0, aComplexVector.Real[0, 1]);
            Assert.Equal(4.0, aComplexVector.Imaginary[0, 1]);
            var aStruct = (Dictionary <string, object>)dict["aStruct"];

            Assert.Equal(2, aStruct.Count);
            Assert.Equal(1.0, ((Matrix)aStruct["field1"])[0]);
            Assert.Equal("two", (string)aStruct["field2"]);
            object[,] aCell = (object[, ])dict["aCell"];
            Assert.Equal(1.0, ((Matrix)aCell[0, 0])[0]);
            int[] intArray = (int[])dict["intArray"];
            Assert.Equal(1, intArray[0]);
            int[] uintArray = (int[])dict["uintArray"];
            Assert.Equal(1, uintArray[0]);
            bool[] aLogical = (bool[])dict["aLogical"];
            Assert.True(aLogical[0]);
            Assert.True(aLogical[1]);
            Assert.False(aLogical[2]);
            object[,,] aCell3D = (object[, , ])dict["aCell3D"];
            Assert.Null(aCell3D[0, 0, 0]);
            Assert.Equal(7.0, ((Matrix)aCell3D[0, 0, 1])[0, 0]);
            Assert.Equal(6.0, ((Matrix)aCell3D[0, 1, 0])[0, 0]);
            double[,,,] array4D = (double[, , , ])dict["array4D"];
            Assert.Equal(4.0, array4D[0, 0, 1, 0]);
            Assert.Equal(5.0, array4D[0, 0, 0, 1]);
            long[] aLong = (long[])dict["aLong"];
            Assert.Equal(1234567890123456789L, aLong[0]);
        }
Exemple #26
0
        //[DeploymentItem(@"Data\IRT2PL_10_250.mat", "Data")]
        public void MatlabReaderTest2()
        {
            Dictionary <string, object> dict = MatlabReader.Read(Path.Combine(
#if NETCORE
                                                                     Path.GetDirectoryName(typeof(PsychTests).Assembly.Location), // work dir is not the one with Microsoft.ML.Probabilistic.Tests.dll on netcore and neither is .Location on netfull
#endif
                                                                     "Data", "IRT2PL_10_250.mat"));

            Assert.Equal(5, dict.Count);
            Matrix m = (Matrix)dict["Y"];

            Assert.True(m.Rows == 250);
            Assert.True(m.Cols == 10);
            Assert.True(m[0, 1] == 0.0);
            Assert.True(m[1, 0] == 1.0);
            m = (Matrix)dict["difficulty"];
            Assert.True(m.Rows == 10);
            Assert.True(m.Cols == 1);
            Assert.True(MMath.AbsDiff(m[1], 0.7773) < 2e-4);
        }
Exemple #27
0
        public void MatlabWriteStringDictionaryTest()
        {
            Dictionary <string, string> dictString = new Dictionary <string, string>();

            dictString["a"] = "a";
            dictString["b"] = "b";
            string fileName = $"{System.IO.Path.GetTempPath()}MatlabWriteStringDictionaryTest{Environment.CurrentManagedThreadId}.mat";

            using (MatlabWriter writer = new MatlabWriter(fileName))
            {
                writer.Write("dictString", dictString);
            }
            Dictionary <string, object> vars = MatlabReader.Read(fileName);
            Dictionary <string, object> dict = (Dictionary <string, object>)vars["dictString"];

            foreach (var entry in dictString)
            {
                Assert.Equal(dictString[entry.Key], dict[entry.Key]);
            }
        }
Exemple #28
0
        public void MatlabWriteStringListTest()
        {
            List <string> strings = new List <string>();

            strings.Add("a");
            strings.Add("b");
            string fileName = $"{System.IO.Path.GetTempPath()}MatlabWriteStringListTest{Environment.CurrentManagedThreadId}.mat";

            using (MatlabWriter writer = new MatlabWriter(fileName))
            {
                writer.Write("strings", strings);
            }
            Dictionary <string, object> vars = MatlabReader.Read(fileName);

            string[] array = (string[])vars["strings"];
            for (int i = 0; i < array.Length; i++)
            {
                Assert.Equal(strings[i], array[i]);
            }
        }
Exemple #29
0
        private void button1_Click(object sender, EventArgs e)
        {
            int             i = 0;
            double          x, h, a, wu;
            Matrix <double> data = MatlabReader.Read <double>("data.mat");
            Matrix <double> time = MatlabReader.Read <double>("time.mat");
            Matrix <double> kp   = MatlabReader.Read <double>("kp.mat");

            while (data[i, 0] == 0)
            {
                i += 1;
            }
            txtdelay.Text = time[i, 0].ToString();//计算延时

            txtkp.Text   = kp[10, 0].ToString();
            x            = Convert.ToDouble(txtkp.Text);
            h            = Convert.ToDouble(txth.Text);
            a            = Convert.ToDouble(txta.Text);
            wu           = Convert.ToDouble(txtwu.Text);
            txttime.Text = (System.Math.Sqrt((x * 4 * h / 3.1415 / a) * (x * 4 * h / 3.1415 / a) - 1) / wu).ToString();//计算时间常数
        }
Exemple #30
0
        public void LoadDataFromMat(string filePath, out Vector[] X, out bool[] Y)
        {
            // Expect X (dxn) and Y (1xn) in the mat file
            Dictionary <string, object> dict = MatlabReader.Read(filePath);
            Matrix xmat = (Matrix)dict["X"];

            X = MatrixUtils.SplitColumns(xmat);
            int n = X.Length;
            // Y is actually a 1xn vector
            Matrix ymat = (Matrix)dict["Y"];

            double[,] yarr = ymat.ToArray();
            if (yarr.GetLength(1) != n)
            {
                throw new ArgumentException("length of X and Y do not match.");
            }
            Y = new bool[n];
            for (int i = 0; i < n; i++)
            {
                // expect 0, 1
                Y[i] = yarr[0, i] > 0.5;
            }
        }