Ejemplo n.º 1
0
        static void DoWrite(string fn, Dictionary <string, MatLab.DoubleList> data, Dictionary <string, List <MLCell> > dataCell, SortedDictionary <string, double> param,
                            List <MLArray> mlList, Hashtable seen)
        {
            log.Info("DoWrite start " + (GC.GetTotalMemory(false) / 1024.0 / 1024.0));

            foreach (var item in data)
            {
                double[][] temp    = item.Value.ToArray();
                MLArray    dbarray = new MLDouble(item.Key, temp);
                mlList.Add(dbarray);
                log.Info("DoWrite Double " + item.Key + " " + (GC.GetTotalMemory(false) / 1024.0 / 1024.0));
            }

            // datacell contains rows
            foreach (var item in dataCell)
            {
                // create msg table
                MLCell temp1 = new MLCell(item.Key + "1", new int[] { 1, item.Value.Count });
                int    a     = 0;
                // add rows to msg table
                foreach (var mlCell in item.Value)
                {
                    temp1[a] = item.Value[a];
                    a++;
                }
                // add table to masterlist
                mlList.Add(temp1);
                log.Info("DoWrite Cell " + item.Key + " " + (GC.GetTotalMemory(false) / 1024.0 / 1024.0));
            }

            log.Info("DoWrite mllist " + (GC.GetTotalMemory(false) / 1024.0 / 1024.0));

            MLCell cell = new MLCell("PARM", new int[] { param.Keys.Count, 2 });
            int    m    = 0;

            foreach (var item in param.Keys)
            {
                cell[m, 0] = new MLChar(null, item.ToString());
                cell[m, 1] = new MLDouble(null, new double[] { (double)param[item] }, 1);
                m++;
            }

            mlList.Add(cell);

            MLArray seenmsg = CreateCellArray("Seen", seen.Keys.Cast <string>().ToArray());

            mlList.Add(seenmsg);

            try
            {
                log.Info("write " + fn + ".mat");
                log.Info("DoWrite before" + (GC.GetTotalMemory(false) / 1024.0 / 1024.0));
                MatFileWriter mfw = new MatFileWriter(fn + ".mat", mlList, false);
                log.Info("DoWrite done" + (GC.GetTotalMemory(false) / 1024.0 / 1024.0));
            }
            catch (Exception err)
            {
                throw new Exception("There was an error when creating the MAT-file: \n" + err.ToString(), err);
            }
        }
Ejemplo n.º 2
0
        public void Write(List <float[]> dataArrays, List <string> dataNames)
        {
            if (dataArrays.Count < 1)
            {
                throw new ArgumentException("Data must contain at least one array");
            }

            if (dataArrays.Count != dataNames.Count)
            {
                throw new ArgumentException("Data arrays and names not equal.");
            }

            List <MLArray> mlList = new List <MLArray>();

            // convert float array to double array since that's what this API supports
            // pre-allocate a single array to be refilled.
            double[] doubleArray = new double[dataArrays[0].Length];

            for (int i = 0; i < dataArrays.Count; ++i)
            {
                for (int e = 0; e < dataArrays[i].Length; ++e)
                {
                    doubleArray[e] = (double)dataArrays[i][e];
                }

                mlList.Add(new MLDouble(dataNames[i], doubleArray, 1));
            }

            MatFileWriter mfw = new MatFileWriter(FilePath, mlList, compress: false);
        }
Ejemplo n.º 3
0
 public void Close()
 {
     using (Stream stream = new FileStream(_FileName, FileMode.Create))
     {
         var writer = new MatFileWriter(stream);
         writer.Write(_DataBuilder.NewFile(new[] { _DataBuilder.NewVariable("data", _DataStruct) }));
     }
 }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            List <MLArray> mlList = new List <MLArray>();

            mlList.Add(CreateTestStruct());

            try {
                MatFileWriter mfw = new MatFileWriter("C:\\Users\\cheics\\Documents\\cc.mat", mlList, true);
            } catch (Exception err) {
                Console.WriteLine("shit...");
            }
        }
Ejemplo n.º 5
0
        public void CreateMatlabFile()
        {
            double[][] data3x3 = new double[3][];
            data3x3[0] = new double[] { 100.0, 101.0, 102.0 }; // first row
            data3x3[1] = new double[] { 200.0, 201.0, 202.0 }; // second row
            data3x3[2] = new double[] { 300.0, 301.0, 302.0 }; // third row

            MLDouble       mlDoubleArray = new MLDouble("Matrix_3_by_3", data3x3);
            List <MLArray> mlList        = new List <MLArray> {
                mlDoubleArray
            };
            MatFileWriter mfw = new MatFileWriter("data.mat", mlList, false);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Im Matlab (MAT) Format speichern
        /// </summary>
        /// <param name="path">Pfad unter welchem die Datei angelegt wird</param>
        public void ToMatFile(string path)
        {
            var h = new MLDouble("H", GetPerformanceHeadValues(), 1);
            var q = new MLDouble("Q", GetPerformanceFlowValues(), 1);

            var mlList = new List <MLArray>
            {
                h,
                q
            };

            MatFileWriter mfw = new MatFileWriter(path, mlList, false);
        }
Ejemplo n.º 7
0
        public void RoundTrip(string matFileName)
        {
            var reader = new MatFileReader(matFileName);

            _tempFileName = Path.GetTempFileName();
            var writer = new MatFileWriter(_tempFileName, reader.Data, false);

            var roundTrip = new MatFileReader(_tempFileName);

            foreach (var(mla1, mla2) in reader.Data.Zip(roundTrip.Data, (mla1, mla2) => (mla1: mla1, mla2 :mla2)))
            {
                Compare(mla1, mla2);
            }
        }
        public void TestHuge()
        {
            var builder = new DataBuilder();
            var array   = builder.NewArray <double>(1000, 10000);

            array[0] = -13.5;
            array[1] = 17.0;
            var variable = builder.NewVariable("test", array);
            var matFile  = builder.NewFile(new[] { variable });

            using (var stream = new MemoryStream())
            {
                var writer = new MatFileWriter(stream);
                writer.Write(matFile);
            }
        }
Ejemplo n.º 9
0
        internal void saveAsMAT()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter           = "MAT files (*.mat)|*.mat|All files (*.*)|*.*";
            saveFileDialog.DefaultExt       = "mat";
            saveFileDialog.InitialDirectory = Properties.Settings.Default.saveImpedanceDirectory;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filename = saveFileDialog.FileName;
                string tmpinfo  = new FileInfo(filename).DirectoryName;
                Properties.Settings.Default.saveImpedanceDirectory = tmpinfo;
                List <MLArray> mlList    = new List <MLArray>();
                MLStructure    structure = new MLStructure("imp", new int[] { 1, 1 });
                structure["f", 0] = new MLDouble("", freqs, freqs.Length);

                //Only add non-null (sampled) channels
                int        numNonNull   = 0;
                List <int> goodChannels = new List <int>();
                for (int i = 0; i < impedance.Length; ++i)
                {
                    if (impedance[i] != null)
                    {
                        ++numNonNull;
                        goodChannels.Add(i);
                    }
                }
                double[][] nonNullImpedance = new double[numNonNull][];
                for (int i = 0; i < numNonNull; ++i)
                {
                    nonNullImpedance[i] = impedance[goodChannels[i]];
                }

                structure["z", 0] = new MLDouble("", nonNullImpedance);
                mlList.Add(structure);

                try
                {
                    MatFileWriter mfw = new MatFileWriter(filename, mlList, true);
                }
                catch (Exception err)
                {
                    MessageBox.Show("There was an error when creating the MAT-file: \n" + err.ToString(),
                                    "MAT-File Creation Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }
Ejemplo n.º 10
0
        public void WriteToMat(String writePath)
        {
            // Columns: data for each channel at given time
            // Rows: EEG amplitudes for given channel across all times

            if (EEGDataList.Count == 0)
            {
                return;
            }

            // "zeroed" time; in seconds
            double[][] times = new double[1][];
            times[0] = EEGDataList.Select(x => (double.Parse(x.SystemMillisecond) - RefTime) / 1000).ToArray();

            // Channel names
            // String[][] channels = new String[1][];
            // channels[0] = EEGDataList[0].Sensors.Select(x => x.Name).ToArray();

            // Generating list of data to be written
            double[][] matData = new double[EEGDataList[0].Sensors.Count()][];

            // for each sensor
            for (int i = 0; i < EEGDataList[0].Sensors.Count(); i++)
            {
                // write amplitude for all times into double array
                double[] amplitudes = new double[EEGDataList.Count()];
                for (int j = 0; j < EEGDataList.Count(); j++)
                {
                    Sensor sensor = EEGDataList[j].Sensors[i];

                    amplitudes[j] = sensor.Value;
                }
                matData[i] = amplitudes;
            }

            MLDouble mlAmplitudes = new MLDouble("amplitudes", matData);
            MLDouble mlTimes      = new MLDouble("times", times);
            // MLChar mlChannels = new MLChar("channels", channels);
            List <MLArray> mlList = new List <MLArray>();

            mlList.Add(mlAmplitudes);
            mlList.Add(mlTimes);
            MatFileWriter mfw = new MatFileWriter(writePath, mlList, false);

            Console.WriteLine("Written to file.");
        }
Ejemplo n.º 11
0
        static void DoWrite(string fn, Dictionary <string, DoubleList> data, SortedDictionary <string, double> param,
                            List <MLArray> mlList, Hashtable seen)
        {
            log.Info("DoWrite start " + (GC.GetTotalMemory(false) / 1024.0 / 1024.0));

            foreach (var item in data)
            {
                double[][] temp    = item.Value.ToArray();
                MLArray    dbarray = new MLDouble(item.Key, temp);
                mlList.Add(dbarray);
                log.Info("DoWrite " + item.Key + " " + (GC.GetTotalMemory(false) / 1024.0 / 1024.0));
            }

            log.Info("DoWrite mllist " + (GC.GetTotalMemory(false) / 1024.0 / 1024.0));

            MLCell cell = new MLCell("PARM", new int[] { param.Keys.Count, 2 });
            int    m    = 0;

            foreach (var item in param.Keys)
            {
                cell[m, 0] = new MLChar(null, item.ToString());
                cell[m, 1] = new MLDouble(null, new double[] { (double)param[item] }, 1);
                m++;
            }

            mlList.Add(cell);

            MLArray seenmsg = CreateCellArray("Seen", seen.Keys.Cast <string>().ToArray());

            mlList.Add(seenmsg);

            try
            {
                log.Info("write " + fn + ".mat");
                log.Info("DoWrite before" + (GC.GetTotalMemory(false) / 1024.0 / 1024.0));
                MatFileWriter mfw = new MatFileWriter(fn + ".mat", mlList, true);
                log.Info("DoWrite done" + (GC.GetTotalMemory(false) / 1024.0 / 1024.0));
            }
            catch (Exception err)
            {
                CustomMessageBox.Show("There was an error when creating the MAT-file: \n" + err.ToString(),
                                      "MAT-File Creation Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Im Matlab (MAT) Format speichern
        /// </summary>
        /// <param name="path">Pfad unter welchem die Datei angelegt wird</param>
        public void ToMatFile(string path)
        {
            var mlList = new List <MLArray>();

            if (IsVarioPump)
            {
                foreach (var rpm in GetDefaultRpms())
                {
                    mlList.Add(new MLDouble("H_" + rpm, GetPerformanceHeadValues(rpm), 1));
                    mlList.Add(new MLDouble("Q_" + rpm, GetPerformanceFlowValues(rpm), 1));
                }
            }
            else
            {
                mlList.Add(new MLDouble("H", GetPerformanceHeadValues(), 1));
                mlList.Add(new MLDouble("Q", GetPerformanceFlowValues(), 1));
            }

            MatFileWriter mfw = new MatFileWriter(path, mlList, false);
        }
        private void createMatFile()
        {
            List <MLArray> mlList = new List <MLArray>();

            mlList.Add(createStruct());

            try
            {
                MatFileWriter mfw = new MatFileWriter(folder + @"\" + exercise + criticalC1 + criticalC2 + criticalC3 + "-" + index + ".mat", mlList, true);
                //StringBuilder sb = new StringBuilder();
                //sb.Appe
                StreamWriter w = File.AppendText(folder + @"\" + exercise + ".txt");
                w.WriteLine(criticalC1 + " " + criticalC2 + " " + criticalC3);
                w.WriteLine(criticalC11 + " " + criticalC21 + " " + criticalC31);
                w.WriteLine(criticalC12 + " " + criticalC22 + " " + criticalC32);
                w.WriteLine(criticalC13 + " " + criticalC23 + " " + criticalC33);
                w.WriteLine(criticalC14 + " " + criticalC24 + " " + criticalC34);
                w.Flush();
            }
            catch (Exception err)
            {
                Console.WriteLine("shit...");
            }
        }
Ejemplo n.º 14
0
        public static void log(string fn)
        {
            string[] filelines;

            if (fn.ToLower().EndsWith(".bin"))
            {
                filelines = BinaryLog.ReadLog(fn).ToArray();
            }
            else
            {
                // read the file
                filelines = File.ReadAllLines(fn);
            }

            // store all the arrays
            List <MLArray> mlList = new List <MLArray>();
            // store data to putinto the arrays
            Dictionary <string, List <double[]> > data = new Dictionary <string, List <double[]> >();
            // store line item lengths
            Hashtable len = new Hashtable();
            // store whats we have seen in the log
            Hashtable seen = new Hashtable();
            // store the params seen
            SortedDictionary <string, double> param = new SortedDictionary <string, double>();

            // keep track of line no
            int a = 0;

            foreach (var line in filelines)
            {
                a++;
                Console.Write(a + "\r");

                string strLine = line.Replace(", ", ",");
                strLine = strLine.Replace(": ", ":");

                string[] items = strLine.Split(',', ':');

                // process the fmt messages
                if (line.StartsWith("FMT"))
                {
                    // +1 for line no
                    string[] names = new string[items.Length - 5 + 1];
                    names[0] = "LineNo";
                    Array.ConstrainedCopy(items, 5, names, 1, names.Length - 1);

                    MLArray format = CreateCellArray(items[3] + "_label", names);

                    if (items[3] == "PARM")
                    {
                    }
                    else
                    {
                        mlList.Add(format);
                    }

                    len[items[3]] = names.Length;
                } // process param messages
                else if (line.StartsWith("PARM"))
                {
                    try
                    {
                        param[items[1]] = double.Parse(items[2], CultureInfo.InvariantCulture);
                    }
                    catch { }
                }// everyting else is generic
                else
                {
                    // make sure the line is long enough
                    if (items.Length < 2)
                    {
                        continue;
                    }
                    // check we have a valid fmt message for this message type
                    if (!len.ContainsKey(items[0]))
                    {
                        continue;
                    }
                    // check the fmt length matchs what the log has
                    if (items.Length != (int)len[items[0]])
                    {
                        continue;
                    }

                    // make it as being seen
                    seen[items[0]] = 1;

                    double[] dbarray = new double[items.Length];

                    // set line no
                    dbarray[0] = a;

                    for (int n = 1; n < items.Length; n++)
                    {
                        try
                        {
                            dbarray[n] = double.Parse(items[n], CultureInfo.InvariantCulture);
                        }
                        catch { }
                    }

                    if (!data.ContainsKey(items[0]))
                    {
                        data[items[0]] = new List <double[]>();
                    }

                    data[items[0]].Add(dbarray);
                }
            }

            foreach (var item in data)
            {
                double[][] temp    = item.Value.ToArray();
                MLArray    dbarray = new MLDouble(item.Key, temp);
                mlList.Add(dbarray);
            }

            MLCell cell = new MLCell("PARM", new int[] { param.Keys.Count, 2 });
            int    m    = 0;

            foreach (var item in param.Keys)
            {
                cell[m, 0] = new MLChar(null, item.ToString());
                cell[m, 1] = new MLDouble(null, new double[] { (double)param[item] }, 1);
                m++;
            }

            mlList.Add(cell);

            MLArray seenmsg = CreateCellArray("Seen", seen.Keys.Cast <string>().ToArray());

            mlList.Add(seenmsg);

            try
            {
                MatFileWriter mfw = new MatFileWriter(fn + ".mat", mlList, true);
            }
            catch (Exception err)
            {
                MessageBox.Show("There was an error when creating the MAT-file: \n" + err.ToString(),
                                "MAT-File Creation Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            //if (args.Length < 1)
            //{
            //    throw new Exception("Result file name should be provided!");
            //}
            //string Resultfilename = args[0];
            int  evalCount;
            int  runId;
            bool success = int.TryParse(args[0], out evalCount);

            if (success)
            {
                //parsing runId
                bool success2 = int.TryParse(args[1], out runId);
                if (success2)
                {
                    var    thisPath       = System.IO.Directory.GetCurrentDirectory();
                    string Resultfilename = thisPath + "\\AutomaticXSCal\\Model\\run" + runId.ToString() + "\\SonghuaHDv2-" + evalCount.ToString() + ".mhydro - Result Files\\HD_Songhua.res1d";
                    // load a result file
                    IResultData resultData = new ResultData();
                    resultData.Connection = Connection.Create(Resultfilename);
                    Diagnostics resultDiagnostics = new Diagnostics("Diag");
                    resultData.Load(resultDiagnostics);
                    if (resultDiagnostics.ErrorCountRecursive > 0) //Report error messages if errors found in result file
                    {
                        throw new Exception("Result file could not be loaded.");
                    }

                    IRes1DReaches reaches = resultData.Reaches; //Load reaches data. A reach is a branch, or a part of a branch between two branch connections.
                    if (reaches.Count == 0)
                    {
                        throw new Exception("The selected file doesn't contain any branch to export data from. Please select another file.");                     //Report error message if no branch exists in file (e.g. for a catchment result file)
                    }
                    if (reaches[0].DataItems.Count == 0)
                    {
                        throw new Exception("The selected file doesn't contain any distributed item on branches and cannot be processed. Please select another file.");                                                                                                       //Report error if no result item exists in grid points (e.g. for a result file containing only structure results)
                    }
                    int          ExportItemIndex = 0;                                                                                                                                                                                                                         // DataItem = 0, for WaterLevel; DataItem = 1, for Discharge.
                    string       Outputfilename  = thisPath + "\\AutomaticXSCal\\Model\\run" + runId.ToString() + "\\ExportMain" + evalCount.ToString() + ".txt";
                    StreamWriter SW = File.CreateText(Outputfilename);                                                                                                                                                                                                        //Create the ouptut text file
                    SW.WriteLine(reaches[0].DataItems[ExportItemIndex].Quantity.Description.ToString() + " results (" + reaches[0].DataItems[ExportItemIndex].Quantity.EumQuantity.UnitDescription.ToString() + ") exported from " + Resultfilename + " on " + DateTime.Now); //Write input information (file name, item, unit) and date in the output text file
                    SW.WriteLine("Branch name" + "\t" + "Chainage" + "\t" + "X coordinate" + "\t" + "Y coordinate" + "\t" + "Min. value" + "\t" + "Max. value" + "\t" + "Mark 1 level" + "\t" + "Mark 2 level" + "\t" + "Mark 3 level");                                      //Write header to the output file


                    // Loop over all reaches
                    for (int j = 0; j < reaches.Count; j++)
                    {
                        IRes1DReach reach          = reaches[j];                       //Load reach number j
                        IDataItem   ResultDataItem = reach.DataItems[ExportItemIndex]; //Load data item number k (for example, number 0 for water level, in a standard HD result file)
                        int[]       indexList      = ResultDataItem.IndexList;         //Load the list of indexes for the current reach and the current data item. Each calculation point has its own index in the reach

                        //export water level
                        //StreamWriter SWWL = File.CreateText("WaterLevel.txt");
                        //using csmatio
                        string   matFpath = thisPath + "\\AutomaticXSCal\\Model\\run" + runId.ToString() + "\\WaterLevelTS" + evalCount.ToString() + ".mat";
                        int[]    dim_WL   = new int[] { 2922, ResultDataItem.NumberOfElements };// 2922 is the time series length at daily step
                        MLDouble mlWL     = new MLDouble("WLsim", dim_WL);

                        // Loop over all calculation points from the current reach
                        for (int i = 0; i < ResultDataItem.NumberOfElements; i++)
                        {
                            if (indexList != null)                                                  //Check if there is a calculation point
                            {
                                float[] TSDataForElement  = ResultDataItem.CreateTimeSeriesData(i); //Get the time series for calculation point i
                                double  MaxDataForElement = TSDataForElement.Max();                 //Get the maximum value from this time series
                                double  MinDataForElement = TSDataForElement.Min();                 //Get the minimum value from this time series
                                // too slow
                                //string wl_all = "";
                                //foreach (double wl in TSDataForElement)
                                //{
                                //    wl_all = wl_all + wl.ToString() + ",";
                                //}
                                //SWWL.WriteLine(wl_all.Substring(0,wl_all.Length - 1));
                                int ielement = 0;
                                foreach (double wl in TSDataForElement)
                                {
                                    mlWL.Set(wl, ielement, i);
                                    ielement++;
                                }

                                int             gridPointIndex = ResultDataItem.IndexList[i];      //Get the index of calculation point i
                                IRes1DGridPoint gridPoint      = reach.GridPoints[gridPointIndex]; //Load calculation point

                                if (gridPoint is IRes1DHGridPoint)                                 //Processing of h-points
                                {
                                    IRes1DHGridPoint   hGridPoint   = gridPoint as IRes1DHGridPoint;
                                    IRes1DCrossSection crossSection = hGridPoint.CrossSection;
                                    if (crossSection is IRes1DOpenCrossSection) //Check if calculation point has an open cross section, in which case extra information will be extracted
                                    {
                                        IRes1DOpenCrossSection openXs = crossSection as IRes1DOpenCrossSection;
                                        double M1 = openXs.Points[openXs.LeftLeveeBank].Z;                                                                                                                                                                                                                                   //Get Z elevation for marker 1
                                        double M2 = openXs.Points[openXs.LowestPoint].Z;                                                                                                                                                                                                                                     //Get Z elevation for marker 2
                                        double M3 = openXs.Points[openXs.RightLeveeBank].Z;                                                                                                                                                                                                                                  //Get Z elevation for marker 3
                                        SW.WriteLine(reach.Name + "\t" + hGridPoint.Chainage.ToString() + "\t" + hGridPoint.X.ToString() + "\t" + hGridPoint.Y.ToString() + "\t" + MinDataForElement.ToString() + "\t" + MaxDataForElement.ToString() + "\t" + M1.ToString() + "\t" + M2.ToString() + "\t" + M3.ToString()); //Write all information including marker levels to output file
                                    }
                                    else
                                    {
                                        SW.WriteLine(reach.Name + "\t" + hGridPoint.Chainage.ToString() + "\t" + hGridPoint.X.ToString() + "\t" + hGridPoint.Y.ToString() + "\t" + MinDataForElement.ToString() + "\t" + MaxDataForElement.ToString()); //For other calculation points (without cross sections), write information to output file
                                    }
                                }
                                else if (gridPoint is IRes1DQGridPoint) //Processing of regular Q-points
                                {
                                    IRes1DQGridPoint QGridPoint = gridPoint as IRes1DQGridPoint;
                                    SW.WriteLine(reach.Name + "\t" + QGridPoint.Chainage.ToString() + "\t" + QGridPoint.X.ToString() + "\t" + QGridPoint.Y.ToString() + "\t" + MinDataForElement.ToString() + "\t" + MaxDataForElement.ToString()); //Write information to output file
                                }
                                else if (gridPoint is IRes1DStructureGridPoint)                                                                                                                                                                     //Processing of structure Q-points
                                {
                                    IRes1DStructureGridPoint QGridPoint = gridPoint as IRes1DStructureGridPoint;
                                    SW.WriteLine(reach.Name + "\t" + QGridPoint.Chainage.ToString() + "\t" + QGridPoint.X.ToString() + "\t" + QGridPoint.Y.ToString() + "\t" + MinDataForElement.ToString() + "\t" + MaxDataForElement.ToString()); //Write information to output file
                                }
                                else
                                {
                                    SW.WriteLine("WARNING: a calculation point with a non-supported type could not be exported."); //Ensure that if a specific type of point is not supported by the current program, a message is returned and the program can proceed with the other points
                                }
                            }
                        }
                        //Save .mat files
                        List <MLArray> mlList = new List <MLArray>();
                        mlList.Add(mlWL);
                        MatFileWriter mfw = new MatFileWriter(matFpath, mlList, false);
                    }
                    SW.Close();           //Release the ouput file
                    resultData.Dispose(); //Release the result file
                }
            }
        }
Ejemplo n.º 16
0
        void btnCreate_Click(object sender, EventArgs e)
        {
            var mlList = new List <MLArray>();

            // Go through each of the options to add in the file
            if (chkCell.Checked)
            {
                mlList.Add(CreateCellArray());
            }
            if (chkStruct.Checked)
            {
                mlList.Add(CreateStructArray());
            }
            if (chkChar.Checked)
            {
                mlList.Add(CreateCharArray());
            }
            if (chkSparse.Checked)
            {
                mlList.Add(CreateSparseArray());
            }
            if (chkDouble.Checked)
            {
                mlList.Add(CreateDoubleArray());
            }
            if (chkSingle.Checked)
            {
                mlList.Add(CreateSingleArray());
            }
            if (chkInt8.Checked)
            {
                mlList.Add(CreateInt8Array());
            }
            if (chkUInt8.Checked)
            {
                mlList.Add(CreateUInt8Array());
            }
            if (chkInt16.Checked)
            {
                mlList.Add(CreateInt16Array());
            }
            if (chkUInt16.Checked)
            {
                mlList.Add(CreateUInt16Array());
            }
            if (chkInt32.Checked)
            {
                mlList.Add(CreateInt32Array());
            }
            if (chkUInt32.Checked)
            {
                mlList.Add(CreateUIn32Array());
            }
            if (chkInt64.Checked)
            {
                mlList.Add(CreateInt64Array());
            }
            if (chkUInt64.Checked)
            {
                mlList.Add(CreateUInt64Array());
            }
            if (chkImagMatrix.Checked)
            {
                mlList.Add(CreateImaginaryArray());
            }

            if (mlList.Count <= 0)
            {
                MessageBox.Show("You must select at least one MAT-file Creation Element in order to" +
                                " create a MAT-file.", "No MAT-file elements selected", MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);
                return;
            }

            // Get a filename name to write the file out to
            saveFileDialog.ShowDialog();
            var filename = saveFileDialog.FileName;

            txtOutput.Text += "Creating the MAT-file '" + filename + "'...";

            try
            {
                var mfw = new MatFileWriter(filename, mlList, chkCompress.Checked);
            }
            catch (Exception err)
            {
                MessageBox.Show("There was an error when creating the MAT-file: \n" + err,
                                "MAT-File Creation Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtOutput.Text += "Failed!\n";
                return;
            }

            txtOutput.Text += "Done!\nMAT-File created with the following data: \n";
            foreach (var mla in mlList)
            {
                txtOutput.Text += mla.ContentToString() + "\n";
            }
        }
Ejemplo n.º 17
0
        public static void tlog(string logfile)
        {
            List <MLArray> mlList  = new List <MLArray>();
            Hashtable      datappl = new Hashtable();

            using (MAVLinkInterface mine = new MAVLinkInterface())
            {
                try
                {
                    mine.logplaybackfile =
                        new BinaryReader(File.Open(logfile, FileMode.Open, FileAccess.Read, FileShare.Read));
                }
                catch
                {
                    CustomMessageBox.Show("Log Can not be opened. Are you still connected?");
                    return;
                }
                mine.logreadmode   = true;
                mine.speechenabled = false;

                while (mine.logplaybackfile.BaseStream.Position < mine.logplaybackfile.BaseStream.Length)
                {
                    MAVLink.MAVLinkMessage packet = mine.readPacket();
                    object data = packet.data;

                    if (data == null)
                    {
                        continue;
                    }

                    if (data is MAVLink.mavlink_heartbeat_t)
                    {
                        if (((MAVLink.mavlink_heartbeat_t)data).type == (byte)MAVLink.MAV_TYPE.GCS)
                        {
                            continue;
                        }
                    }

                    Type test = data.GetType();

                    DateTime time = mine.lastlogread;

                    double matlabtime = GetMatLabSerialDate(time);

                    try
                    {
                        foreach (var field in test.GetFields())
                        {
                            // field.Name has the field's name.

                            object fieldValue = field.GetValue(data); // Get value
                            if (field.FieldType.IsArray)
                            {
                            }
                            else
                            {
                                if (!datappl.ContainsKey(field.Name + "_" + field.DeclaringType.Name))
                                {
                                    datappl[field.Name + "_" + field.DeclaringType.Name] = new List <double[]>();
                                }

                                List <double[]> list =
                                    ((List <double[]>)datappl[field.Name + "_" + field.DeclaringType.Name]);

                                object value = fieldValue;

                                if (value.GetType() == typeof(Single))
                                {
                                    list.Add(new double[] { matlabtime, (double)(Single)field.GetValue(data) });
                                }
                                else if (value.GetType() == typeof(short))
                                {
                                    list.Add(new double[] { matlabtime, (double)(short)field.GetValue(data) });
                                }
                                else if (value.GetType() == typeof(ushort))
                                {
                                    list.Add(new double[] { matlabtime, (double)(ushort)field.GetValue(data) });
                                }
                                else if (value.GetType() == typeof(byte))
                                {
                                    list.Add(new double[] { matlabtime, (double)(byte)field.GetValue(data) });
                                }
                                else if (value.GetType() == typeof(sbyte))
                                {
                                    list.Add(new double[] { matlabtime, (double)(sbyte)field.GetValue(data) });
                                }
                                else if (value.GetType() == typeof(Int32))
                                {
                                    list.Add(new double[] { matlabtime, (double)(Int32)field.GetValue(data) });
                                }
                                else if (value.GetType() == typeof(UInt32))
                                {
                                    list.Add(new double[] { matlabtime, (double)(UInt32)field.GetValue(data) });
                                }
                                else if (value.GetType() == typeof(ulong))
                                {
                                    list.Add(new double[] { matlabtime, (double)(ulong)field.GetValue(data) });
                                }
                                else if (value.GetType() == typeof(long))
                                {
                                    list.Add(new double[] { matlabtime, (double)(long)field.GetValue(data) });
                                }
                                else if (value.GetType() == typeof(double))
                                {
                                    list.Add(new double[] { matlabtime, (double)(double)field.GetValue(data) });
                                }
                                else
                                {
                                    Console.WriteLine("Unknown data type");
                                }
                            }
                        }
                    }
                    catch
                    {
                    }
                }

                mine.logreadmode = false;
                mine.logplaybackfile.Close();
                mine.logplaybackfile = null;
            }

            foreach (string item in datappl.Keys)
            {
                double[][] temp    = ((List <double[]>)datappl[item]).ToArray();
                MLArray    dbarray = new MLDouble(item.Replace(" ", "_"), temp);
                mlList.Add(dbarray);
            }

            try
            {
                MatFileWriter mfw = new MatFileWriter(logfile + ".mat", mlList, true);
            }
            catch (Exception err)
            {
                MessageBox.Show("There was an error when creating the MAT-file: \n" + err.ToString(),
                                "MAT-File Creation Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
        }
Ejemplo n.º 18
0
        public static void ExportHotFrame(String rootFolder, String annotationName, HotFrame frame,
                                          MatlabExporterOptions options = MatlabExporterOptions.Overwrite, ILogger logger = null, CancellationToken cancelletionToken = default(CancellationToken))
        {
            // delete features

            /*List<Feature> newFeatureSet = new List<Feature>();
             * foreach (Feature feature in frame.Features)
             * {
             *  if (feature.DataStream != null) newFeatureSet.Add(feature);
             * }
             * frame.Features = newFeatureSet;*/


            String folderName  = rootFolder + "\\frame_" + annotationName;
            String matFilePath = folderName + "\\frame_" + annotationName + ".mat";

            Directory.CreateDirectory(folderName);

            logger?.WriteLineInfo("");
            logger?.WriteLineInfo("Convert frame to Matlab MAT format and export images!");
            logger?.WriteLineInfo("Export folder: " + folderName);
            logger?.WriteLineInfo("MAT file location: " + matFilePath);

            List <MLArray> mlList = new List <MLArray>();
            Dictionary <DataStream, List <VeloFeature> > velodyneData = new Dictionary <DataStream, List <VeloFeature> >();

            if ((options == MatlabExporterOptions.Append) && (File.Exists(matFilePath)))
            {
                MatFileReader matReader = new MatFileReader(matFilePath);
                mlList = matReader.Data;
            }

            int i = 0;

            foreach (Feature feature in frame.Features)
            {
                logger?.WriteLineInfo("Exporting: " + feature.DataStream.ShortName);

                MLStructure structFeatures = new MLStructure(feature.DataStream.ShortName, new int[] { 1, 1 });
                structFeatures["Name", 0]      = new MLChar(null, feature.DataStream.Name);
                structFeatures["ShortName", 0] = new MLChar(null, feature.DataStream.ShortName);

                if (cancelletionToken.IsCancellationRequested == true)
                {
                    logger?.WriteLineWarning("Export cancelled!");
                    return;
                }

                if (feature is GPSFeature)
                {
                    var gpsFeature = feature as GPSFeature;
                    structFeatures["Lat", 0]     = new MLDouble("", new double[] { gpsFeature.Position.Lat }, 1);
                    structFeatures["Lon", 0]     = new MLDouble("", new double[] { gpsFeature.Position.Lon }, 1);
                    structFeatures["Height", 0]  = new MLDouble("", new double[] { gpsFeature.Position.Height }, 1);
                    structFeatures["Quality", 0] = new MLDouble("", new double[] { gpsFeature.Position.Quality }, 1);

                    mlList.Add(structFeatures);
                }
                else if (feature is ImageFeature)
                {
                    ImageFeature imageFeature = feature as ImageFeature;
                    structFeatures["Timestamp", 0]  = new MLDouble("", new double[] { Utils.ConvertToUnixTimestamp(imageFeature.TimeStamp) }, 1);
                    structFeatures["TimestampC", 0] = ConvertDateTimeToMLDouble(imageFeature.TimeStamp);

                    double[][] points = new double[imageFeature.Points.Count][];
                    int        k      = 0;
                    foreach (ImagePoint pt in ((ImageFeature)feature).Points)
                    {
                        points[k]    = new double[3];
                        points[k][0] = pt.ID;
                        points[k][1] = pt.X;
                        points[k][2] = pt.Y;
                        k++;
                    }

                    if (k != 0)
                    {
                        MLDouble arrayPoints = new MLDouble("Points", points);
                        structFeatures["Points", 0] = arrayPoints;
                    }



                    // save images
                    if (imageFeature.Image != null)
                    {
                        using (Bitmap img = new Bitmap(imageFeature.Image))
                        {
                            img.Save(folderName + "\\frame_" + annotationName + "_" + feature.DataStream.ShortName + ".bmp");
                        }

                        // you can export the images here, but it's very slow and the code also needs to be tested!

                        /*using (Bitmap img = new Bitmap(imageFeature.Image))
                         * {
                         *
                         *  int[] dims = new int[] { img.Width, img.Height, 3 };
                         *  MLDouble arrImg = new MLDouble("Image", dims);
                         *  for (int i = 0; i < img.Width; i++)
                         *  {
                         *      for (int j = 0; j < img.Height; j++)
                         *      {
                         *          Color col = img.GetPixel(i, j);
                         *          arrImg.Set(col.R, i, j + img.Height * 0);
                         *          arrImg.Set(col.G, i, j + img.Height * 1);
                         *          arrImg.Set(col.B, i, j + img.Height * 2);
                         *      }
                         *  }
                         *
                         *  structFeatures["Image", 0] = arrImg;
                         * }*/
                    }

                    mlList.Add(structFeatures);
                }
                else if (feature is VeloFeature)
                {
                    VeloFeature veloFeature = feature as VeloFeature;
                    // if key does not exist create one
                    if (!velodyneData.ContainsKey(veloFeature.DataStream))
                    {
                        velodyneData.Add(veloFeature.DataStream, new List <VeloFeature>());
                    }

                    velodyneData[veloFeature.DataStream].Add(veloFeature);
                }

                i++;
                logger?.WriteProgress((double)i / (double)frame.Features.Count() * 100.0);
            }


            // ok, now finalize velodyne data
            foreach (KeyValuePair <DataStream, List <VeloFeature> > entry in velodyneData)
            {
                if (cancelletionToken.IsCancellationRequested == true)
                {
                    logger?.WriteLineWarning("Export cancelled!");
                    return;
                }

                MLStructure structFeatures = new MLStructure(entry.Key.ShortName, new int[] { 1, 1 });
                structFeatures["Name", 0]      = new MLChar(null, entry.Key.Name);
                structFeatures["ShortName", 0] = new MLChar(null, entry.Key.ShortName);
                structFeatures["TimeStamp", 0] = new MLDouble("", new double[] { Utils.ConvertToUnixTimestamp(frame.Timestamp) }, 1);

                // get number of points
                long n_points = 0;
                foreach (VeloFeature feature in entry.Value)
                {
                    n_points += feature.Points.Count();
                }

                if (n_points == 0)
                {
                    logger?.WriteLineWarning(entry.Key.ShortName + ": No features!");
                    continue;
                }

                // populate points
                double[][] points = new double[n_points][];
                int        k      = 0;
                foreach (VeloFeature feature in entry.Value)
                {
                    foreach (VelodynePoint pt in feature.Points)
                    {
                        points[k]    = new double[9];
                        points[k][0] = feature.ID;
                        points[k][1] = pt.X;
                        points[k][2] = pt.Y;
                        points[k][3] = pt.Z;
                        points[k][4] = Convert.ToDouble(pt.Intensity);
                        points[k][5] = pt.Distance;
                        points[k][6] = pt.Hz;
                        points[k][7] = pt.Vz;
                        points[k][8] = pt.InternalTime;
                        k++;
                    }
                }

                MLDouble arrayPoints = new MLDouble("Points", points);
                structFeatures["Points", 0] = arrayPoints;

                mlList.Add(structFeatures);
            }

            try
            {
                logger?.WriteLineInfo("Saving mat file...");
                MatFileWriter mfw = new MatFileWriter(matFilePath, mlList, true);
            }
            catch (Exception ex)
            {
                logger?.WriteLineError("Error occured: " + ex.ToString());
                return;
            }

            logger?.WriteProgress(100.0);
            logger?.WriteLineInfo("Done.");
        }
Ejemplo n.º 19
0
        public async static Task Export(String filename, Project project, ILogger logger = null, CancellationToken cancelletionToken = default(CancellationToken))
        {
            logger?.WriteLineInfo("");
            logger?.WriteLineInfo("Saving project into MAT file!");
            logger?.WriteLineInfo("MAT file location: " + filename);

            List <MLArray> mlList = new List <MLArray>();
            int            pi     = 0;

            foreach (DataStream dataStream in project.DataStreams)
            {
                pi++;
                cancelletionToken.ThrowIfCancellationRequested();

                logger?.WriteLineInfo("Exporting " + dataStream.ShortName + " datastream...");
                logger?.WriteProgress((double)pi / (double)project.DataStreams.Count() * 100.0);

                MLStructure structDataStream = new MLStructure(dataStream.ShortName, new int[] { 1, 1 });
                structDataStream["Name", 0]      = new MLChar(null, dataStream.Name);
                structDataStream["ShortName", 0] = new MLChar(null, dataStream.ShortName);

                if (dataStream.DataLines.Count > 0)
                {
                    // DataLines
                    MLCell arrayDataLines = new MLCell("DataLines", new int[] { dataStream.DataLines.Count, 1 });
                    int    k = 0;
                    foreach (DataLine dataLine in dataStream.DataLines)
                    {
                        MLStructure structDataLine = new MLStructure(dataStream.ShortName, new int[] { 1, 1 });
                        structDataLine["Timestamp", 0]  = new MLDouble("", new double[] { Utils.ConvertToUnixTimestamp(dataLine.TimeStamp) }, 1);
                        structDataLine["TimestampC", 0] = ConvertDateTimeToMLDouble(dataLine.TimeStamp);

                        if (dataLine is ImageDataLine)
                        {
                            structDataLine["ImageFileName", 0] = new MLChar(null, (dataLine as ImageDataLine).ImageFileName);
                        }

                        if (dataLine is VideoDataLine)
                        {
                            structDataLine["VideoFileName", 0] = new MLChar(null, (dataLine as VideoDataLine).VideoFileName);
                        }

                        arrayDataLines[k] = structDataLine;
                        k++;
                    }
                    structDataStream["DataLines", 0] = arrayDataLines;
                }


                if (dataStream is GPSDataStream)
                {
                    GPSDataStream gpsDataStream = dataStream as GPSDataStream;

                    // Event Marker
                    if (gpsDataStream.MarkerEvents.Count > 0)
                    {
                        MLCell arrayMarkerEvents = new MLCell("MarkerEvents", new int[] { gpsDataStream.MarkerEvents.Count, 1 });
                        int    k = 0;
                        foreach (EvenMarkerDataLine evnt in gpsDataStream.MarkerEvents)
                        {
                            MLStructure structEventMarkers = new MLStructure(dataStream.ShortName, new int[] { 1, 1 });
                            structEventMarkers["Timestamp", 0]  = new MLDouble("", new double[] { (double)evnt.TimeStamp.Ticks }, 1);
                            structEventMarkers["TimestampC", 0] = ConvertDateTimeToMLDouble(evnt.TimeStamp);
                            structEventMarkers["Port", 0]       = new MLChar(null, evnt.Port.ToString());
                            arrayMarkerEvents[k] = structEventMarkers;
                            k++;
                        }
                        structDataStream["MarkerEvents", 0] = arrayMarkerEvents;
                    }

                    // Positions
                    if (gpsDataStream.Positions.Count > 0)
                    {
                        double[][] points = new double[gpsDataStream.Positions.Count][];
                        int        k      = 0;
                        foreach (GPSPositionDataLine pt in gpsDataStream.Positions)
                        {
                            points[k]    = new double[5];
                            points[k][0] = Utils.ConvertToUnixTimestamp(pt.TimeStamp);
                            points[k][1] = pt.Lat;
                            points[k][2] = pt.Lon;
                            points[k][3] = pt.Height;
                            points[k][4] = pt.Quality;
                            k++;
                        }
                        MLDouble arrayPoints = new MLDouble("Points", points);
                        structDataStream["Points", 0] = arrayPoints;
                    }
                }

                mlList.Add(structDataStream);
            }

            try
            {
                MatFileWriter mfw = new MatFileWriter(filename, mlList, false);
            }
            catch (Exception ex)
            {
                logger?.WriteLineError("Error occured: " + ex.ToString());
                return;
            }

            logger?.WriteLineInfo("MAT file location: " + filename);
            logger?.WriteLineInfo("Done.");
        }
Ejemplo n.º 20
0
        public void createNetwork(bool matlabFile)
        {
            if (_nodesInputLayer <= 0 || _nodesOutputLayer <= 0)
            {
                throw new Exception("Invalid amount of input or output layer nodes");
            }

            //For creating txt
            FileStream   outFile       = null;
            StreamWriter fileWriterTxt = null;
            //For creating mat-file
            MatFileWriter  fileWriterMatlab = null;
            DataBuilder    dataBuilder      = null;
            IArrayOf <int> array            = null;

            //Total number of nodes
            int nodesTotal = _nodesInputLayer + _nodesOutputLayer;

            foreach (int nodes in _nodesHiddenLayers)
            {
                nodesTotal += nodes;
            }

            try{
                if (!matlabFile)
                {
                    outFile       = File.Create(Path.Combine(Directory.GetCurrentDirectory(), "network.nn"));
                    fileWriterTxt = new System.IO.StreamWriter(outFile);
                }
                else
                {
                    outFile          = new System.IO.FileStream("network.mat", System.IO.FileMode.Create);
                    fileWriterMatlab = new MatFileWriter(outFile);
                    dataBuilder      = new DataBuilder();
                    //Create the two dimensional array
                    array = dataBuilder.NewArray <int>(nodesTotal, nodesTotal);
                }

                int layerVertical   = 0;
                int layerHorizontal = 0;

                if (!matlabFile)
                {
                    fileWriterTxt.WriteLine("network = [");
                }

                for (int row = 0; row < nodesTotal; row++)
                {
                    layerVertical = currentLayer(row);

                    for (int column = 0; column < nodesTotal; column++)
                    {
                        layerHorizontal = currentLayer(column);

                        /*
                         * Sets node to one if when following condition is full filed
                         *
                         *    L0 | L1 | L2 | L3 |
                         * ----+----+----+----+----+
                         * L0 |    | X  |    |
                         * ----+----+----+----+----+
                         * L1 |    |    | X  |
                         * ----+----+----+----+----+
                         * L2 |    |    |    | X
                         * ----+----+----+----+----+
                         * L3 |    |    |    |
                         * ----+----+----+----+----+
                         */
                        if (layerVertical == (layerHorizontal - 1))
                        {
                            if (!matlabFile)
                            {
                                fileWriterTxt.Write(" 1");
                            }
                            else
                            {
                                array[row, column] = 1;
                            }
                        }
                        else
                        {
                            if (!matlabFile)
                            {
                                fileWriterTxt.Write(" 0");
                            }
                            else
                            {
                                array[row, column] = 0;
                            }
                        }
                    }
                    if (!matlabFile && row != nodesTotal)
                    {
                        fileWriterTxt.Write(";\n");
                    }
                }

                if (!matlabFile)
                {
                    fileWriterTxt.WriteLine("];");
                }
                else
                {
                    //Create the variable
                    IVariable network = dataBuilder.NewVariable("network", array);
                    //Create the matfile
                    IMatFile matFile = dataBuilder.NewFile(new[] { network });
                    //Write to the file
                    fileWriterMatlab.Write(matFile);
                }
            }catch (Exception ex) {
                Console.WriteLine(ex);
            } finally{
                if (!matlabFile)
                {
                    fileWriterTxt.Dispose();
                }
                outFile.Dispose();
            }
        }
Ejemplo n.º 21
0
        public static void tlog(string logfile)
        {
            List <MLArray> mlList  = new List <MLArray>();
            Hashtable      datappl = new Hashtable();

            using (Comms.CommsFile cf = new CommsFile(logfile))
                using (CommsStream cs = new CommsStream(cf, cf.BytesToRead))
                {
                    MAVLink.MavlinkParse parse = new MAVLink.MavlinkParse(true);

                    while (cs.Position < cs.Length)
                    {
                        MAVLink.MAVLinkMessage packet = parse.ReadPacket(cs);

                        if (packet == null)
                        {
                            continue;
                        }

                        object data = packet.data;

                        if (data == null)
                        {
                            continue;
                        }

                        if (data is MAVLink.mavlink_heartbeat_t)
                        {
                            if (((MAVLink.mavlink_heartbeat_t)data).type == (byte)MAVLink.MAV_TYPE.GCS)
                            {
                                continue;
                            }
                        }

                        Type test = data.GetType();

                        DateTime time = packet.rxtime;

                        double matlabtime = GetMatLabSerialDate(time);

                        try
                        {
                            foreach (var field in test.GetFields())
                            {
                                // field.Name has the field's name.

                                object fieldValue = field.GetValue(data); // Get value
                                if (field.FieldType.IsArray)
                                {
                                }
                                else
                                {
                                    if (!datappl.ContainsKey(field.Name + "_" + field.DeclaringType.Name))
                                    {
                                        datappl[field.Name + "_" + field.DeclaringType.Name] = new List <double[]>();
                                    }

                                    List <double[]> list =
                                        ((List <double[]>)datappl[field.Name + "_" + field.DeclaringType.Name]);

                                    object value = fieldValue;

                                    if (value.GetType() == typeof(Single))
                                    {
                                        list.Add(new double[] { matlabtime, (double)(Single)field.GetValue(data) });
                                    }
                                    else if (value.GetType() == typeof(short))
                                    {
                                        list.Add(new double[] { matlabtime, (double)(short)field.GetValue(data) });
                                    }
                                    else if (value.GetType() == typeof(ushort))
                                    {
                                        list.Add(new double[] { matlabtime, (double)(ushort)field.GetValue(data) });
                                    }
                                    else if (value.GetType() == typeof(byte))
                                    {
                                        list.Add(new double[] { matlabtime, (double)(byte)field.GetValue(data) });
                                    }
                                    else if (value.GetType() == typeof(sbyte))
                                    {
                                        list.Add(new double[] { matlabtime, (double)(sbyte)field.GetValue(data) });
                                    }
                                    else if (value.GetType() == typeof(Int32))
                                    {
                                        list.Add(new double[] { matlabtime, (double)(Int32)field.GetValue(data) });
                                    }
                                    else if (value.GetType() == typeof(UInt32))
                                    {
                                        list.Add(new double[] { matlabtime, (double)(UInt32)field.GetValue(data) });
                                    }
                                    else if (value.GetType() == typeof(ulong))
                                    {
                                        list.Add(new double[] { matlabtime, (double)(ulong)field.GetValue(data) });
                                    }
                                    else if (value.GetType() == typeof(long))
                                    {
                                        list.Add(new double[] { matlabtime, (double)(long)field.GetValue(data) });
                                    }
                                    else if (value.GetType() == typeof(double))
                                    {
                                        list.Add(new double[] { matlabtime, (double)(double)field.GetValue(data) });
                                    }
                                    else
                                    {
                                        Console.WriteLine("Unknown data type");
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                }

            foreach (string item in datappl.Keys)
            {
                double[][] temp    = ((List <double[]>)datappl[item]).ToArray();
                MLArray    dbarray = new MLDouble(item.Replace(" ", "_"), temp);
                mlList.Add(dbarray);
            }

            try
            {
                MatFileWriter mfw = new MatFileWriter(logfile + ".mat", mlList, false);
            }
            catch (Exception err)
            {
                throw new Exception("There was an error when creating the MAT-file: \n" + err.ToString(), err);
            }
        }
Ejemplo n.º 22
0
        public void Export(string filename)
        {
            double[][] p = new double[point.GetLength(0)][];
            for (int n = 0; n < point.GetLength(0); n++)
            {
                p[n] = new double[2];
                for (int m = 0; m < 2; m++)
                {
                    p[n][m] = point[n, m];
                }
            }

            int[][] e = new int[element.GetLength(0)][];
            for (int n = 0; n < element.GetLength(0); n++)
            {
                e[n] = new int[3];
                for (int m = 0; m < 3; m++)
                {
                    e[n][m] = element[n, m];
                }
            }


            int N = 0;

            foreach (var paramet in cutParam.Values)
            {
                if (paramet.Cut != null)
                {
                    N++;
                }
            }

            int k  = 0;
            int k0 = 0;

            double[][] c   = new double[N][];
            double[][] eps = new double[element.GetLength(0)][];
            foreach (var item in cutParam)
            {
                if (item.Value.Cut != null)
                {
                    c[k]    = new double[4];
                    c[k][0] = item.Key.extID;
                    c[k][1] = item.Value.T1;
                    c[k][2] = item.Value.T2;
                    c[k][3] = item.Value.T3;
                    k++;
                }

                eps[k0]    = new double[2];
                eps[k0][0] = item.Key.extID;
                eps[k0][1] = item.Value.Eps;

                k0++;
            }

            double[][] q = new double[point.GetLength(0)][];
            if (pref.WeightFunctionCalculate)
            {
                k = 0;
                foreach (var item in weightfunc)
                {
                    q[k] = new double[4];

                    q[k][0] = item.Key.extID;
                    q[k][1] = item.Value.q;
                    q[k][2] = item.Value.qx;
                    q[k][3] = item.Value.qy;

                    k++;
                }
            }

            MLDouble mlPoint   = new MLDouble(pref.VertexMatrixName, p);
            MLInt32  mlElement = new MLInt32(pref.ElementMatrixName, e);
            MLDouble mlCut     = new MLDouble(pref.CutTriangleMatrixName, c);

            List <MLArray> mlList = new List <MLArray>();

            mlList.Add(mlPoint);
            mlList.Add(mlElement);
            mlList.Add(mlCut);

            if (pref.CalcAreaRelation)
            {
                MLDouble mlEps = new MLDouble(pref.AreaRelationMatrixName, eps);
                mlList.Add(mlEps);
            }

            if (pref.WeightFunctionCalculate)
            {
                MLDouble mlq = new MLDouble(pref.WeightFunctionMatrixName, q);
                mlList.Add(mlq);
            }

            MatFileWriter mfr = new MatFileWriter(filename, mlList, false);
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            /* TODO
             * ratio 0-1 15 steps
             * 75 - 200 g/L 20 steps or so
             * wavelength:
             * 450-550
             * 550-590
             * 750-850
             */
            double ratioStart    = 0.7;
            double ratioEnd      = 1;
            double ratioIncrease = 0.1;

            double concentrationStart     = 75;
            double concentrationStop      = 200;
            double concentrationIncrement = 12.5;

            // TODO Add variable that stores the used parameters, or possibly create a dictionary with the parameters on one side and the data on the other side

            var         parameters  = ScatterParameters.GetExampleParameters();
            List <uint> wavelengths = new List <uint>();

            if (args.Length == 0 || args[0] == "-sweep-parameters-better")
            {
                //Set ratio and concentration variables
                //Then call regular sweep-parameters
                //ratioStart = 0.9;
                //concentrationStart = 150;
                if (args.Length == 0)
                {
                    args = new string[1];
                }
                args[0] = "-sweep-parameters";
            }
            if (args[0] == "-sweep-parameters")
            {
                for (uint i = 450; i < 550; i += 10)
                {
                    wavelengths.Add(i);
                }
                for (uint i = 550; i < 590; i += 10)
                {
                    wavelengths.Add(i);
                }

                for (uint i = 750; i < 890; i += 10)
                {
                    wavelengths.Add(i);
                }
            }
            else if (args[0] == "-manual")
            {
                Console.WriteLine("Enter the wavelength");
                wavelengths.Add(Convert.ToUInt32(Console.ReadLine()));
                parameters.Wavelength = wavelengths[0];
                Console.WriteLine("Enter the ratio");
                var ratioInput = Convert.ToDouble(Console.ReadLine());
                ratioStart    = ratioInput;
                ratioEnd      = ratioInput;
                ratioIncrease = 100;
                Console.WriteLine("Enter the concentration");
                var concentrationInput = Convert.ToDouble(Console.ReadLine());
                concentrationStart     = concentrationInput;
                concentrationStop      = concentrationInput;
                concentrationIncrement = 100;
            }
            else
            {
                wavelengths.Add(uint.Parse(args[0]));
            }

            double ratio = 0.0;

            const int numOfSamples = 3;

            DateTime start = DateTime.Now;

            Console.WriteLine("Started at {0:G}", start);

            var infoPath = $"output_data/{start:yyyy-MM-dd--HH-mm-ss}/info.txt";

            Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(infoPath)));
            using (StreamWriter writer = new StreamWriter(infoPath))
            {
                if (args.Length > 0)
                {
                    writer.WriteLine($"Run using parameters: {args[0]}");
                    writer.WriteLine($"Ratio start: {ratioStart}");
                    writer.WriteLine($"Ratio end: {ratioEnd}");
                    writer.WriteLine($"Ratio increment: {ratioIncrease}");

                    writer.WriteLine($"Concentration start: {concentrationStart}");
                    writer.WriteLine($"Concentration end: {concentrationStop}");
                    writer.WriteLine($"Concentration increment: {concentrationIncrement}");

                    writer.WriteLine($"Wavelengths:");
                    foreach (var wavelength in wavelengths)
                    {
                        writer.WriteLine(wavelength);
                    }
                }
                if (args[0] == "-manual")
                {
                    writer.WriteLine("Run using parameters: ");
                    writer.WriteLine($"Wavelength: {wavelengths[0]}");
                    writer.WriteLine($"Ratio: {ratioStart}");
                    writer.WriteLine($"Concentration: {concentrationStart}");
                }
            }

            for (int i = wavelengths.Count - 1; i >= 0; i--)
            {
                Console.WriteLine();
                uint wavelength = wavelengths[i];
                Console.WriteLine($"Wavelength: {wavelength}");
                Console.WriteLine($"Run {wavelengths.Count - i} of {wavelengths.Count}");
                //for (ratio = ratioStart; ratio <= ratioEnd; ratio += ratioIncrease)
                for (ratio = ratioEnd; ratio >= ratioStart; ratio -= ratioIncrease)
                {
                    for (double concentration = concentrationStop; concentration >= concentrationStart; concentration -= concentrationIncrement)
                    {
                        var builder         = new DataBuilder();
                        var detectedPhotons = builder.NewArray <double>(numOfSamples, 2);
                        parameters.ConcentrationBlood = concentration / 1000;
                        parameters.RatioOxygen        = ratio;
                        parameters.Wavelength         = wavelength;

                        for (int n = 0; n < numOfSamples; n++)
                        {
                            var data = Scatter.Scatterlight(parameters);
                            detectedPhotons[n, 0] = data.DetectedPhotons1;
                            detectedPhotons[n, 1] = data.DetectedPhotons2;
                            Console.Write(".");
                        }

                        var variable = builder.NewVariable("detectedPhotons1", detectedPhotons);
                        var matFile  = builder.NewFile(new[] { variable });

                        var path = $"output_data/{start:yyyy-MM-dd--HH-mm-ss}/{wavelength}/{ratio}/{concentration}.mat";
                        Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path)));
                        using (var fileStream = new FileStream(path, FileMode.Create))
                        {
                            var writer = new MatFileWriter(fileStream);
                            writer.Write(matFile);
                        }
                    }
                }
                DateTime tmpEnd       = DateTime.Now;
                TimeSpan tmpSpendTime = new TimeSpan(tmpEnd.Ticks - start.Ticks);

                using (StreamWriter writer = new StreamWriter($"output_data/{start:yyyy-MM-dd--HH-mm-ss}/{wavelength}/time.txt"))
                {
                    writer.WriteLine($"Time spend: {tmpSpendTime}");
                }
            }

            DateTime end       = DateTime.Now;
            TimeSpan spendTime = new TimeSpan(end.Ticks - start.Ticks);

            Console.WriteLine("Stopped at {0:G}", end);
            Console.WriteLine($"Time spend: {spendTime}");
            Console.WriteLine("Done");
            Console.WriteLine("Press any key to close...");
            Console.ReadKey();
        }