private void loadDSL() { OpenFileDialog fo = new OpenFileDialog(); fo.Filter = "MATLAB file (*.mat)|*.mat"; if (fo.ShowDialog() == DialogResult.OK) { matfile = fo.FileName; try { MatFileReader r = new MatFileReader(fo.FileName); Dictionary <string, MLArray> content = r.Content; if (content["DSL"] is MLStructure) { MLStructure matStr = (MLStructure)content["DSL"]; for (int i = 0; i < matStr.N; i++) { //MLDouble attack = (MLDouble)matStr["attack\0",i]; MLDouble attack = (MLDouble)matStr["@", i]; //MLDouble attack = (MLDouble)matStr["", 0]; } } } catch (Exception ex) { MessageBox.Show("Error reading .MAT file" + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("You did not select a file! Using current parameter values", "No selection", MessageBoxButtons.OK, MessageBoxIcon.Information); Filename = ""; } toolStripStatusLabel1.Text = "Loaded DSL prescription " + Filename; }
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); } }
private static MLDouble ConvertDateTimeToMLDouble(DateTime TimeStamp) { MLDouble tsArray = new MLDouble(null, new double[] { TimeStamp.Year, TimeStamp.Month, TimeStamp.Day, TimeStamp.Hour, TimeStamp.Minute, (double)TimeStamp.Second + (double)TimeStamp.Millisecond / 1000.0 }, 1); return(tsArray); }
private static MLCell CreateCellArrayCustom(string name, string[] items) { var cell = new MLCell(name, new int[] { items.Length, 1 }); int i = 0; foreach (var item in items) { double ans = 0; if (double.TryParse(items[i], out ans)) { cell[i] = new MLDouble(null, new double[] { ans }, 1); i++; continue; } if (items[i].TrimStart().StartsWith("[") && items[i].TrimEnd().EndsWith("]")) { cell[i] = CreateCellArrayCustom("", items[i].Split(new[] { ' ', '[', ']' }, StringSplitOptions.RemoveEmptyEntries)); i++; continue; } cell[i] = new MLChar(null, (string)items[i].Trim()); i++; } return(cell); }
private static nirs.core.Probe loadSDprobe(string file) { MatFileReader mfr = new MatFileReader(file); double[][] lambda2; MLStructure SD = (mfr.Content["SD"] as MLStructure); MLDouble MLlambda = null; if (SD.Keys.Contains("Lambda")) { MLlambda = (SD["Lambda"] as MLDouble); } else if (SD.Keys.Contains("lambda")) { MLlambda = (SD["lambda"] as MLDouble); } lambda2 = MLlambda.GetArray(); int[] lambda = new int[lambda2[0].Length]; for (int i = 0; i < lambda2[0].Length; i++) { lambda[i] = (int)lambda2[0][i]; } return(loadSDprobe(file, lambda)); }
private double[][] LoadDict(string dictionaryPath) { // Read in dictionary. MatFileReader mfr = new MatFileReader(dictionaryPath); MLDouble ml = mfr.Content["dic"] as MLDouble; this.dict_dimension = ml.Dimensions; return(ml.GetArray()); }
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); }
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); }
/// <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); }
//public void CreateCSVFile(DataTable dt, string strFilePath) //{ // #region Export Grid to CSV // // Create the CSV file to which grid data will be exported. // StreamWriter sw = new StreamWriter(strFilePath, false); // // First we will write the headers. // //DataTable dt = m_dsProducts.Tables[0]; // int iColCount = dt.Columns.Count; // for (int i = 0; i < iColCount; i++) // { // sw.Write(dt.Columns[i]); // if (i < iColCount - 1) // { // sw.Write(","); // } // } // sw.Write(sw.NewLine); // // Now write all the rows. // foreach (DataRow dr in dt.Rows) // { // for (int i = 0; i < iColCount; i++) // { // if (!Convert.IsDBNull(dr[i])) // { // sw.Write(dr[i].ToString()); // } // if (i < iColCount - 1) // { // sw.Write(","); // } // } // sw.Write(sw.NewLine); // } // sw.Close(); // #endregion //} private MLArray createStruct() { MLStructure outStruct = new MLStructure("kinectData", new int[] { 1, 1 }); //string[] headers = {"HipCenterX", "HipCenterY", "HipCenterZ", "SpineX", "SpineY", "SpineZ", "ShoulderCenterX", // "ShoulderCenterY", "ShoulderCenterZ", "HeadX", "HeadY", "HeadZ", "ShoulderLeftX", // "ShoulderLeftY", "ShoulderLeftZ", "ElbowLeftX", "ElbowLeftY", "ElbowLeftZ", "WristLeftX", // "WristLeftY", "WristLeftZ", "HandLeftX", "HandLeftY", "HandLeftZ", "ShoulderRightX", // "ShoulderRightY", "ShoulderRightZ", "ElbowRightX", "ElbowRightY", "ElbowRightZ", // "WristRightX", "WristRightY", "WristRightZ", "HandRightX", "HandRightY", "HandRightZ", // "HipLeftX", "HipLeftY", "HipLeftZ", "KneeLeftX", "KneeLeftY", "KneeLeftZ", "AnkleLeftX", // "AnkleLeftY", "AnkleLeftZ", "FootLeftX", "FootLeftY", "FootLeftZ", "HipRightX", "HipRightY", // "HipRightZ", "KneeRightX", "KneeRightY", "KneeRightZ", "AnkleRightX", "AnkleRightY", // "AnkleRightZ", "FootRightX", "FootRightY", "FootRightZ"}; double criticalC1D = Convert.ToDouble(criticalC1); double criticalC2D = Convert.ToDouble(criticalC2); double criticalC3D = Convert.ToDouble(criticalC3); double criticalC11D = Convert.ToDouble(criticalC11); double criticalC21D = Convert.ToDouble(criticalC21); double criticalC31D = Convert.ToDouble(criticalC31); double criticalC12D = Convert.ToDouble(criticalC12); double criticalC22D = Convert.ToDouble(criticalC22); double criticalC32D = Convert.ToDouble(criticalC32); double criticalC13D = Convert.ToDouble(criticalC13); double criticalC23D = Convert.ToDouble(criticalC23); double criticalC33D = Convert.ToDouble(criticalC33); double criticalC14D = Convert.ToDouble(criticalC14); double criticalC24D = Convert.ToDouble(criticalC24); double criticalC34D = Convert.ToDouble(criticalC34); double[] ccArray = { criticalC1D, criticalC2D, criticalC3D, criticalC11D, criticalC21D, criticalC31D, criticalC12D, criticalC22D, criticalC32D, criticalC13D, criticalC23D, criticalC33D, criticalC14D, criticalC24D, criticalC34D }; Double[] skelDataA = (Double[])skelData.ToArray(typeof(double)); Double[] gpVectorA = (Double[])gpVector.ToArray(typeof(double)); Double[] kinectTiltA = (Double[])kinectTilt.ToArray(typeof(double)); outStruct["skelData", 0] = new MLDouble("", skelDataA, 60); outStruct["dateHeader", 0] = new MLChar("", timeStamp); outStruct["criticalComps", 0] = new MLDouble("", ccArray, 3); outStruct["exercise", 0] = new MLChar("", exercise); MLStructure groundStruct = new MLStructure("", new int[] { 1, 1 }); groundStruct["height", 0] = new MLDouble("", new double[] { 0.68 }, 1); // metres? groundStruct["gpVector", 0] = new MLDouble("", gpVectorA, 4); //metres? groundStruct["kinectTilt", 0] = new MLDouble("", kinectTiltA, 1); //degrees outStruct["groundPlaneData", 0] = groundStruct; return(outStruct); }
public void TrainModel(string featureFilePath) { MatFileReader mfr = new MatFileReader(featureFilePath); MLSingle ml = mfr.Content["rgbdfea"] as MLSingle; int[] dimension = ml.Dimensions; double[][] mlArray = MatrixUtil.Transpose(ml.GetArray()); MLDouble label = mfr.Content["rgbdclabel"] as MLDouble; double[] labels = label.GetArray()[0]; this.TrainModel(labels, mlArray); }
static MLStructure getStructure(IEnumerable<UAVObject> data, Type type) { int rowCount = data.Count(); MLStructure structure = new MLStructure(type.Name, new int[] { 1, 1 }); var timestamp = data.Select(k => k.timestamp).ToArray(); structure["timestamp"] = new MLUInt32("", timestamp, rowCount); foreach (var prop in type.GetFields().Where(j => j.FieldType.BaseType == typeof(UAVObjectField))) { string name = prop.Name; double[] fieldata = data.Select( k=> Convert.ToDouble(((UAVObjectField)prop.GetValue(k)).getValue(0))).ToArray(); structure[name] = new MLDouble("", fieldata, rowCount); } return structure; }
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); } } }
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."); }
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; } }
private static MLArray CreateTestStruct() { MLStructure outStruct = new MLStructure("kinectData", new int[] { 1, 1 }); double[] myRealNums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; // new MLInt64("IA", myRealNums, myImagNums, length); // IA: matlab Name (blank for struct) // realNumbers => Double array of the real parts // imagNumbers => Double array of the img parts // length => dimension of the matrix outStruct["skelData", 0] = new MLDouble("", myRealNums, 2); outStruct["dateHeader", 0] = new MLChar("", "January 29th... etc..."); MLStructure groundStruct = new MLStructure("", new int[] { 1, 1 }); groundStruct["height", 0] = new MLDouble("", new double[] { 0.68 }, 1); // metres? groundStruct["gpVector", 0] = new MLDouble("", new double[] {1.4, 1, 1, 1}, 4); //metres? groundStruct["kinectTilt", 0] = new MLInt16("", new Int16[]{ -15 }, 1); //degrees outStruct["groundPlaneData", 0] = groundStruct; return outStruct; }
private static MLCell CreateCellArrayCustom(string name, string[] items) { var cell = new MLCell(name, new int[] { items.Length, 1 }); int i = 0; foreach (var item in items) { double ans = 0; if (double.TryParse(items[i], out ans)) { cell[i] = new MLDouble(null, new double[] { ans }, 1); i++; continue; } cell[i] = new MLChar(null, (string)items[i].Trim()); i++; } return(cell); }
private static MLArray CreateTestStruct() { MLStructure outStruct = new MLStructure("kinectData", new int[] { 1, 1 }); double[] myRealNums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; // new MLInt64("IA", myRealNums, myImagNums, length); // IA: matlab Name (blank for struct) // realNumbers => Double array of the real parts // imagNumbers => Double array of the img parts // length => dimension of the matrix outStruct["skelData", 0] = new MLDouble("", myRealNums, 2); outStruct["dateHeader", 0] = new MLChar("", "January 29th... etc..."); MLStructure groundStruct = new MLStructure("", new int[] { 1, 1 }); groundStruct["height", 0] = new MLDouble("", new double[] { 0.68 }, 1); // metres? groundStruct["gpVector", 0] = new MLDouble("", new double[] { 1.4, 1, 1, 1 }, 4); //metres? groundStruct["kinectTilt", 0] = new MLInt16("", new Int16[] { -15 }, 1); //degrees outStruct["groundPlaneData", 0] = groundStruct; return(outStruct); }
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); } }
private static MLCell CreateCellArrayCustom(string name, string[] items) { var cell = new MLCell(name, new int[] { items.Length, 1 }); int i = 0; foreach (var item in items) { double ans = 0; if (double.TryParse(items[i], out ans)) { cell[i] = new MLDouble(null, new double[] { ans }, 1); i++; continue; } cell[i] = new MLChar(null, (string)items[i].Trim()); i++; } return cell; }
public static void log(string fn) { // read the file string[] 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")) { param[items[1]] = double.Parse(items[2]); }// 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]); } 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; } }
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."); }
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; } }
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."); }
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; } }
{ // methods devoted to file I/O public static core.Data readDOTnirs(string filename) { core.Data data = new core.Data(); MatFileReader mfr = new MatFileReader(filename); MLDouble mlD = (mfr.Content["d"] as MLDouble); if (mlD != null) { double[][] d = mlD.GetArray(); double[] dd = d[0]; data.data = new List <double> [dd.Length]; for (int i = 0; i < dd.Length; i++) { data.data[i] = new List <double>(); } for (int i = 0; i < d.Length; i++) { double[] dd3 = d[i]; for (int j = 0; j < dd3.Length; j++) { data.data[j].Add(dd3[j]); } } } MLDouble mlT = (mfr.Content["t"] as MLDouble); if (mlT != null) { double[][] t = mlT.GetArray(); data.time = new List <double>(); for (int i = 0; i < t.Length; i++) { data.time.Add(t[i][0]); } } data.numsamples = data.time.Count; double[][] lambda; MLStructure SD = (mfr.Content["SD"] as MLStructure); MLDouble MLlambda = null; if (SD.Keys.Contains("Lambda")) { MLlambda = (SD["Lambda"] as MLDouble); } else if (SD.Keys.Contains("lambda")) { MLlambda = (SD["lambda"] as MLDouble); } MLDouble MLsrcpos = null; if (SD.Keys.Contains("SrcPos")) { MLsrcpos = (SD["SrcPos"] as MLDouble); } else if (SD.Keys.Contains("srcpos")) { MLsrcpos = (SD["srcpos"] as MLDouble); } MLDouble MLdetpos = null; if (SD.Keys.Contains("DetPos")) { MLdetpos = (SD["DetPos"] as MLDouble); } else if (SD.Keys.Contains("detpos")) { MLdetpos = (SD["detpos"] as MLDouble); } if (MLdetpos != null) { double[][] detpos = MLdetpos.GetArray(); data.probe.DetPos = new double[detpos.Length, 3]; data.probe.DetectorLabels = new string[detpos.Length]; for (int i = 0; i < detpos.Length; i++) { data.probe.DetPos[i, 0] = (float)detpos[i][0]; data.probe.DetPos[i, 1] = (float)detpos[i][1]; data.probe.DetPos[i, 2] = (float)detpos[i][2]; data.probe.DetectorLabels[i] = String.Format("Detector-{0}", +1); } data.probe.numDet = detpos.Length; } if (MLsrcpos != null) { double[][] srcpos = MLsrcpos.GetArray(); data.probe.SrcPos = new double[srcpos.Length, 3]; data.probe.SourceLabels = new string[srcpos.Length]; for (int i = 0; i < srcpos.Length; i++) { data.probe.SrcPos[i, 0] = (float)srcpos[i][0]; data.probe.SrcPos[i, 1] = (float)srcpos[i][1]; data.probe.SrcPos[i, 2] = (float)srcpos[i][2]; data.probe.SourceLabels[i] = String.Format("Source-{0}", i + 1); } data.probe.numSrc = srcpos.Length; } if (MLlambda != null) { lambda = MLlambda.GetArray(); MLDouble mlMeasList = (mfr.Content["ml"] as MLDouble); if (mlMeasList != null) { double[][] ml = mlMeasList.GetArray(); data.probe.ChannelMap = new ChannelMap[ml.Length]; for (int i = 0; i < ml.Length; i++) { data.probe.ChannelMap[i] = new ChannelMap(); data.probe.ChannelMap[i].sourceindex = (int)ml[i][0] - 1; data.probe.ChannelMap[i].detectorindex = (int)ml[i][1] - 1; data.probe.ChannelMap[i].channelname = String.Format("Src{0}-Det{1}", data.probe.ChannelMap[i].sourceindex + 1, data.probe.ChannelMap[i].detectorindex + 1); data.probe.ChannelMap[i].wavelength = lambda[0][(int)ml[i][3] - 1]; data.probe.ChannelMap[i].datasubtype = String.Format("{0}nm", data.probe.ChannelMap[i].wavelength); } } } data.probe.numChannels = data.probe.ChannelMap.Length; data.probe.measlistAct = new bool[data.probe.numChannels]; for (int i = 0; i < data.probe.numChannels; i++) { data.probe.measlistAct[i] = false; } data.probe.measlistAct[0] = true; // TODO add stimulus information // TODO add 3D probe information // TODO add demographics info // TODO add auxillary information // TODO exceptipon catches for case-sensitive variable names data.description = filename; return(data); }
private double[,] MLDoubleParser(MLDouble Variable) { var dims = Variable.Dimensions; var CS_Variable = new double[dims[0], dims[1]]; if (dims.Length > 2) { throw new Exception("Variable being Parsed must be one or two dimensional"); } int idx = 0; for (int j = 0; j < dims[1]; j++) { for (int i = 0; i < dims[0]; i++) { CS_Variable[i, j] = Variable.Get(idx); idx++; } } return CS_Variable; }
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; } }
/// <summary> /// Reads <c>miMATRIX</c> from the input stream. /// </summary> /// <remarks> /// If reading was not finished (which is normal for filtered results) /// returns <c>null</c>. /// </remarks> /// <param name="buf">The <c>BinaryReader</c> input stream.</param> /// <param name="isRoot">When <c>true</c> informs that if this is a top level /// matrix.</param> /// <returns><c>MLArray</c> or <c>null</c> if matrix does not match <c>filter</c></returns> private MLArray ReadMatrix( Stream buf, bool isRoot ) { // result MLArray mlArray = null; ISMatTag tag; // read flags int[] flags = ReadFlags( buf ); int attributes = (flags.Length != 0 ) ? flags[0] : 0; int nzmax = ( flags.Length != 0 ) ? flags[1] : 0; int type = attributes & 0xff; // read Array dimension int[] dims = ReadDimension( buf ); // read Array name string name = ReadName( buf ); // If this array is filtered out return immediately if( isRoot && !_filter.Matches(name) ) { return null; } // read data switch (type) { case MLArray.mxSTRUCT_CLASS: MLStructure mlStruct = new MLStructure(name, dims, type, attributes); BinaryReader br = new BinaryReader(buf); // field name length - this subelement always uses the compressed data element format tag = new ISMatTag(br.BaseStream); int maxlen = br.ReadInt32(); // Read fields data as Int8 tag = new ISMatTag(br.BaseStream); // calculate number of fields int numOfFields = tag.Size / maxlen; // padding after field names int padding = (tag.Size % 8) != 0 ? 8 - tag.Size % 8 : 0; string[] fieldNames = new string[numOfFields]; for (int i = 0; i < numOfFields; i++) { byte[] names = new byte[maxlen]; br.Read(names, 0, names.Length); fieldNames[i] = ZeroEndByteArrayToString(names); } br.ReadBytes(padding); // read fields for (int index = 0; index < mlStruct.M * mlStruct.N; index++) { for (int i = 0; i < numOfFields; i++) { // read matrix recursively tag = new ISMatTag(br.BaseStream); if (tag.Size > 0) { MLArray fieldValue = ReadMatrix(br.BaseStream, false); mlStruct[fieldNames[i], index] = fieldValue; } else { mlStruct[fieldNames[i], index] = new MLEmptyArray(); } } } mlArray = mlStruct; //br.Close(); break; case MLArray.mxCELL_CLASS: MLCell cell = new MLCell(name, dims, type, attributes); for (int i = 0; i < cell.M * cell.N; i++) { tag = new ISMatTag(buf); if (tag.Size > 0) { MLArray cellmatrix = ReadMatrix(buf, false); cell[i] = cellmatrix; } else { cell[i] = new MLEmptyArray(); } } mlArray = cell; break; case MLArray.mxDOUBLE_CLASS: mlArray = new MLDouble(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<double>)mlArray).RealByteBuffer, (ByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<double>)mlArray).ImaginaryByteBuffer, (ByteStorageSupport)mlArray); } break; case MLArray.mxUINT8_CLASS: mlArray = new MLUInt8(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<byte>)mlArray).RealByteBuffer, (ByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<byte>)mlArray).ImaginaryByteBuffer, (ByteStorageSupport)mlArray); } break; case MLArray.mxINT8_CLASS: mlArray = new MLInt8(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<byte>)mlArray).RealByteBuffer, (ByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<byte>)mlArray).ImaginaryByteBuffer, (ByteStorageSupport)mlArray); } break; case MLArray.mxUINT64_CLASS: mlArray = new MLUInt64(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<byte>)mlArray).RealByteBuffer, (ByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<byte>)mlArray).ImaginaryByteBuffer, (ByteStorageSupport)mlArray); } break; case MLArray.mxINT64_CLASS: mlArray = new MLInt64(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<byte>)mlArray).RealByteBuffer, (ByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<byte>)mlArray).ImaginaryByteBuffer, (ByteStorageSupport)mlArray); } break; case MLArray.mxCHAR_CLASS: MLChar mlchar = new MLChar(name, dims, type, attributes); //read real tag = new ISMatTag(buf); char[] ac = tag.ReadToCharArray(); for (int i = 0; i < ac.Length; i++) { mlchar.SetChar(ac[i], i); } mlArray = mlchar; break; case MLArray.mxSPARSE_CLASS: MLSparse sparse = new MLSparse(name, dims, attributes, nzmax); // read ir (row indices) tag = new ISMatTag(buf); int[] ir = tag.ReadToIntArray(); // read jc (column indices) tag = new ISMatTag(buf); int[] jc = tag.ReadToIntArray(); // read pr (real part) tag = new ISMatTag(buf); double[] ad1 = tag.ReadToDoubleArray(); int n = 0; for (int i = 0; i < ir.Length; i++) { if (i < sparse.N) { n = jc[i]; } sparse.SetReal(ad1[i], ir[i], n); } //read pi (imaginary part) if (sparse.IsComplex) { tag = new ISMatTag(buf); double[] ad2 = tag.ReadToDoubleArray(); int n1 = 0; for (int i = 0; i < ir.Length; i++) { if (i < sparse.N) { n1 = jc[i]; } sparse.SetImaginary(ad2[i], ir[i], n1); } } mlArray = sparse; break; default: throw new MatlabIOException("Incorrect Matlab array class: " + MLArray.TypeToString(type)); } return mlArray; }
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); }
public static void writeDOTnirs(core.Data data, string filename, int startIdx = 0, int endIdx = Int32.MaxValue) { // Store the data into the *.nirs matlab format try { int numsamples = data.numsamples; int numch = data.probe.numChannels; int naux = data.auxillaries.Length; numsamples = Math.Min(endIdx - startIdx, numsamples - startIdx); // save the structure as mat file using MatFileWriter List <MLArray> mlList = new List <MLArray>(); double[][] d = new double[numsamples][]; double[][] t = new double[numsamples][]; double[][] aux = new double[numsamples][]; for (int j = startIdx; j < startIdx + numsamples; j++) { double[] dloc = new double[numch]; for (int i = 0; i < numch; i++) { dloc[i] = data.data[i][j]; } try { if (naux > 0) { double[] aloc = new double[naux]; for (int ii = 0; ii < naux; ii++) { aloc[ii] = data.auxillaries[ii].data[j]; } aux[j - startIdx] = aloc; } else { double[] aa = new double[1]; aa[0] = 0; aux[j - startIdx] = aa; } } catch { // Console.WriteLine("error writing aux"); double[] aa = new double[1]; aa[0] = 0; aux[j - startIdx] = aa; } double[] tt = new double[1]; double[] ss = new double[1]; ss[0] = 0; tt[0] = data.time[j]; t[j - startIdx] = tt; d[j - startIdx] = dloc; } MLDouble mldata = new MLDouble("d", d); mlList.Add(mldata); MLDouble mlaux = new MLDouble("aux", aux); mlList.Add(mlaux); MLDouble mltime = new MLDouble("t", t); mlList.Add(mltime); double[][] s = new double[numsamples][]; for (int j = startIdx; j < startIdx + numsamples; j++) { double[] dloc = new double[data.stimulus.Count]; double thistime = data.time[j]; for (int i = 0; i < data.stimulus.Count; i++) { dloc[i] = 0; for (int k = 0; k < data.stimulus[i].onsets.Count; k++) { double onset = data.stimulus[i].onsets[k]; double dur = data.stimulus[i].duration[k]; if (thistime >= onset & thistime <= onset + dur) { dloc[i] = data.stimulus[i].amplitude[k]; } } } s[j - startIdx] = dloc; } MLDouble mls = new MLDouble("s", s); mlList.Add(mls); MLCell condNames = new MLCell("CondNames", new int[] { 1, data.stimulus.Count }); for (int i = 0; i < data.stimulus.Count; i++) { condNames[0, i] = new MLChar(null, data.stimulus[i].name); } mlList.Add(condNames); // Probe MLStructure mlSD = new MLStructure("SD", new int[] { 1, 1 }); List <string> datasubtype = new List <string>(); for (int i = 0; i < data.probe.numChannels; i++) { if (!datasubtype.Contains(data.probe.ChannelMap[i].datasubtype)) { datasubtype.Add(data.probe.ChannelMap[i].datasubtype); } } double[] lambda = new double[datasubtype.Count]; for (int i = 0; i < data.probe.numChannels; i++) { lambda[datasubtype.IndexOf(data.probe.ChannelMap[i].datasubtype)] = data.probe.ChannelMap[i].wavelength; } double[][] srcpos = new double[data.probe.numSrc][]; for (int j = 0; j < data.probe.numSrc; j++) { double[] slo = new double[3]; for (int i = 0; i < 2; i++) { slo[i] = data.probe.SrcPos[j, i]; } slo[2] = 0; srcpos[j] = slo; } double[][] detpos = new double[data.probe.numDet][]; for (int j = 0; j < data.probe.numDet; j++) { double[] dlo = new double[3]; for (int i = 0; i < 2; i++) { dlo[i] = data.probe.DetPos[j, i]; } dlo[2] = 0; detpos[j] = dlo; } mlSD["NumDet", 0] = new MLDouble("", new double[] { data.probe.numDet }, 1); mlSD["NumSrc", 0] = new MLDouble("", new double[] { data.probe.numSrc }, 1); mlSD["Lambda", 0] = new MLDouble("", lambda, 1); mlSD["SrcPos", 0] = new MLDouble("", srcpos); mlSD["DetPos", 0] = new MLDouble("", detpos); if (data.probe.isregistered) { double[][] srcpos3d = new double[data.probe.numSrc][]; for (int j = 0; j < data.probe.numSrc; j++) { double[] slo = new double[3]; for (int i = 0; i < 3; i++) { slo[i] = data.probe.SrcPos3D[j, i]; } srcpos3d[j] = slo; } double[][] detpos3d = new double[data.probe.numDet][]; for (int j = 0; j < data.probe.numDet; j++) { double[] dlo = new double[3]; for (int i = 0; i < 3; i++) { dlo[i] = data.probe.DetPos3D[j, i]; } detpos3d[j] = dlo; } mlSD["SrcPos3D", 0] = new MLDouble("", srcpos3d); mlSD["DetPos3D", 0] = new MLDouble("", detpos3d); } // fixes for HOMER2 mlSD["SpatialUnit"] = new MLChar("", "mm"); // Add demographics as a struct MLStructure demo = new MLStructure("demographics", new int[] { 1, 1 }); for (int i = 0; i < data.demographics.Keys.Count; i++) { object val = data.demographics.get(data.demographics.Keys[i]); string valstr = string.Format("{0}", val); demo[data.demographics.Keys[i], 0] = new MLChar("", valstr); } mlList.Add(demo); double[][] ml = new double[data.probe.numChannels][]; for (int i = 0; i < data.probe.numChannels; i++) { double[] m = new double[4]; m[0] = data.probe.ChannelMap[i].sourceindex + 1; m[1] = data.probe.ChannelMap[i].detectorindex + 1; m[2] = 0; m[3] = 1 + datasubtype.IndexOf(data.probe.ChannelMap[i].datasubtype); ml[i] = m; } MLDouble mlml = new MLDouble("ml", ml); mlList.Add(mlml); mlSD["MeasList", 0] = new MLDouble("", ml); mlList.Add(mlSD); MLStructure mlStim = new MLStructure("StimDesign", new int[] { data.stimulus.Count, 1 }); for (int i = 0; i < data.stimulus.Count; i++) { mlStim["name", i] = new MLChar("", data.stimulus[i].name); double[] onset = new double[data.stimulus[i].onsets.Count]; for (int ii = 0; ii < data.stimulus[i].onsets.Count; ii++) { onset[ii] = data.stimulus[i].onsets[ii]; } double[] dur = new double[data.stimulus[i].duration.Count]; for (int ii = 0; ii < data.stimulus[i].duration.Count; ii++) { dur[ii] = data.stimulus[i].duration[ii]; } double[] amp = new double[data.stimulus[i].amplitude.Count]; for (int ii = 0; ii < data.stimulus[i].amplitude.Count; ii++) { amp[ii] = data.stimulus[i].amplitude[ii]; } mlStim["onset", i] = new MLDouble("", onset, 1); mlStim["dur", i] = new MLDouble("", dur, 1); mlStim["amp", i] = new MLDouble("", amp, 1); } if (data.stimulus.Count > 0) { mlList.Add(mlStim); } new MatFileWriter(filename, mlList, false); } catch { Console.WriteLine("Unable to save .nirs file"); } return; }
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); } } }
public static void SaveMatFile() { // create a MATLAB char and double variable and add it to the structure //MLChar scoreName = ; //MLDouble scoreValue = new MLDouble("", new double[] { 12345 }, 1); int maxIter = 0; foreach(ActionData ad in ActionData.actionList) { if(ad.iterationNum > maxIter) { maxIter = ad.iterationNum; } } string dateLbl = ""; dateLbl += System.DateTime.Now.Year.ToString(); dateLbl += System.DateTime.Now.Month.ToString(); dateLbl += System.DateTime.Now.Day.ToString(); dateLbl += System.DateTime.Now.ToFileTimeUtc().ToString(); int chunkSize = 50; int effChunkSize = 50; int chunk = 0; int actionIndex = 0; List<string> fieldList = new List<string> (); fieldList.Add ("obstacle"); fieldList.Add ("goal"); fieldList.Add ("item"); fieldList.Add ("robot"); fieldList.Add ("selectedItem"); while((chunk)*chunkSize < ActionData.actionList.Count) { int i = 0; int ii = 0; actionIndex = chunk*chunkSize; if(chunkSize + actionIndex >= ActionData.actionList.Count) effChunkSize = ActionData.actionList.Count-actionIndex; else effChunkSize = chunkSize; MLStructure structure = new MLStructure("simDat", new int[] { effChunkSize, 1 }); List<MLArray> mlList = new List<MLArray>(); MLDouble arr; while(actionIndex < ActionData.actionList.Count) { ActionData ad = actionList[actionIndex] as ActionData; structure["speed", i] = new MLDouble("", new double[] {maxIter}, 1); structure["beforePos", i] = new MLDouble("", new double[] {ad.beforePos.x,ad.beforePos.y,ad.beforePos.z }, 1); structure["beforeOrient", i] = new MLDouble("", new double[] {ad.beforeOrient.eulerAngles.x,ad.beforeOrient.eulerAngles.y,ad.beforeOrient.eulerAngles.z}, 1); //Debug.Log(dateLbl+"_"+chunk+"["+i+"]" +"("+ad.beforeOrient.x+","+ad.beforeOrient.y+","+ad.beforeOrient.z+")"); structure["afterPos", i] = new MLDouble("", new double[] {ad.afterPos.x,ad.afterPos.y,ad.afterPos.z}, 1); structure["afterOrient", i] = new MLDouble("", new double[] {ad.afterOrient.eulerAngles.x,ad.afterOrient.eulerAngles.y,ad.afterOrient.eulerAngles.z}, 1); structure["robotType", i] = new MLChar("", ad.robotType); structure["itemType", i] = new MLChar("", ad.itemType); ii=0; foreach(string fieldName in fieldList) { int id = ad.positionNames.IndexOf(fieldName); Vector3 vecValue; if(id >= 0) vecValue = ad.positionVecs[id]; else vecValue = new Vector3(100,100,100); // We pass an invalid value structure[fieldName, i] = new MLDouble("", new double[] {vecValue.x,vecValue.y,vecValue.z}, 1); ii++; } i++; actionIndex++; } mlList.Add(structure); MatFileWriter mfw = new MatFileWriter("playDat"+dateLbl+"_"+chunk+".mat", mlList, false); mfw.GetType(); Debug.Log ("Saved (" + chunk + ")playDat" + dateLbl + ".mat"); chunk ++; ActionData.actionList = new List<ActionData>(); } }
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; } }
{ // methods devoted to file I/O /// <subjid>.wl1 - wavelength #1 data /// <subjid>.wl2 - wavelength #2 data /// <subjid>_config.txt - config file /// <subjid>.evt - stimulus events(data taken from config file) /// <subjid>_probeInfo.mat - probe file /// <subjid>.tpl -topology file(data taken from config file) /// public static core.Data readNIRx(string filename) { core.Data data = new core.Data(); filename = filename.Substring(0, filename.IndexOf(".wl1", StringComparison.Ordinal)); // Read the header file List <string> hdrFields = new List <string>(); List <string> hdrValues = new List <string>(); string line; System.IO.StreamReader file = new System.IO.StreamReader(filename + ".hdr"); while ((line = file.ReadLine()) != null) { if (line.Contains("=")) { int found = line.IndexOf("=", StringComparison.Ordinal); hdrFields.Add(line.Substring(0, found)); string value = line.Substring(found + 1); if (value.Contains("#")) { value = ""; while ((line = file.ReadLine()) != null) { if (line.Contains("#")) { break; } value = value + "\r" + line; } } if (value.Contains("\"")) { value = value.Substring(1, value.Length - 2); } hdrValues.Add(value); } } file.Close(); string targetDirectory = Path.GetDirectoryName(filename + ".hdr"); string[] fileEntries = Directory.GetFiles(targetDirectory); string probeFile = Path.Combine(targetDirectory, "Standard_probeInfo.mat"); foreach (string i in fileEntries) { if (i.Contains("probeInfo.mat")) { probeFile = Path.Combine(targetDirectory, i); break; } } // Now, read the Probe_info.mat file MatFileReader mfr = new MatFileReader(probeFile); MLStructure probeInfo = (mfr.Content["probeInfo"] as MLStructure); MLStructure probes = (probeInfo["probes"] as MLStructure); MLDouble coords_s2 = (probes["coords_s2"] as MLDouble); MLDouble coords_d2 = (probes["coords_d2"] as MLDouble); MLDouble coords_c2 = (probes["coords_c2"] as MLDouble); double[][] srcpos = coords_s2.GetArray(); double[][] detpos = coords_d2.GetArray(); double[][] landpos = coords_c2.GetArray(); // TODO read all the 3D stuff too MLDouble coords_s3 = (probes["coords_s3"] as MLDouble); MLDouble coords_d3 = (probes["coords_d3"] as MLDouble); MLDouble coords_c3 = (probes["coords_c3"] as MLDouble); double[][] srcpos3D = coords_s3.GetArray(); double[][] detpos3D = coords_d3.GetArray(); double[][] landpos3D = coords_c3.GetArray(); data.probe.numSrc = srcpos.Length; data.probe.numDet = detpos.Length; data.probe.DetPos = new double[detpos.Length, 3]; data.probe.DetectorLabels = new string[detpos.Length]; for (int i = 0; i < detpos.Length; i++) { data.probe.DetPos[i, 0] = (float)detpos[i][0]; data.probe.DetPos[i, 1] = (float)detpos[i][1]; data.probe.DetPos[i, 2] = 0; data.probe.DetectorLabels[i] = string.Format("Detector-{0}", i + 1); } data.probe.SrcPos = new double[srcpos.Length, 3]; data.probe.SourceLabels = new string[srcpos.Length]; for (int i = 0; i < srcpos.Length; i++) { data.probe.SrcPos[i, 0] = (float)srcpos[i][0]; data.probe.SrcPos[i, 1] = (float)srcpos[i][1]; data.probe.SrcPos[i, 2] = 0; data.probe.SourceLabels[i] = string.Format("Source-{0}", i + 1); } data.probe.LandmarkPos = new double[landpos.Length, 3]; data.probe.LandmarkLabels = new string[landpos.Length]; for (int i = 0; i < landpos.Length; i++) { data.probe.LandmarkPos[i, 0] = (float)landpos[i][0]; data.probe.LandmarkPos[i, 1] = (float)landpos[i][1]; data.probe.LandmarkPos[i, 2] = 0; data.probe.LandmarkLabels[i] = string.Format("Landmark(temp)-{0}", i + 1); } data.probe.DetPos3D = new double[detpos3D.Length, 3]; for (int i = 0; i < detpos3D.Length; i++) { data.probe.DetPos3D[i, 0] = (double)detpos3D[i][0]; data.probe.DetPos3D[i, 1] = (double)detpos3D[i][1]; data.probe.DetPos3D[i, 2] = (double)detpos3D[i][1]; } data.probe.SrcPos3D = new double[srcpos3D.Length, 3]; for (int i = 0; i < srcpos3D.Length; i++) { data.probe.SrcPos3D[i, 0] = (double)srcpos3D[i][0]; data.probe.SrcPos3D[i, 1] = (double)srcpos3D[i][1]; data.probe.SrcPos3D[i, 2] = (double)srcpos3D[i][2]; } data.probe.LandmarkPos3D = new double[landpos.Length, 3]; for (int i = 0; i < landpos.Length; i++) { data.probe.LandmarkPos3D[i, 0] = (float)landpos3D[i][0]; data.probe.LandmarkPos3D[i, 1] = (float)landpos3D[i][1]; data.probe.LandmarkPos3D[i, 2] = (float)landpos3D[i][2]; } data.probe.isregistered = true; int LambdaIdx = hdrFields.IndexOf("Wavelengths"); string[] lam = hdrValues[LambdaIdx].Split('\t'); double[] lambda = new double[lam.Length]; for (int i = 0; i < lam.Length; i++) { lambda[i] = Convert.ToDouble(lam[i]); } int SDmaskIdx = hdrFields.IndexOf("S-D-Mask"); string[] mask = hdrValues[SDmaskIdx].Split('\r'); bool[,] SDMask = new bool[data.probe.numSrc, data.probe.numDet]; for (int i = 1; i < data.probe.numSrc + 1; i++) { string[] mask2 = mask[i].Split('\t'); for (int j = 0; j < data.probe.numDet; j++) { SDMask[i - 1, j] = false; if (mask2[j].Contains("1")) { SDMask[i - 1, j] = true; } } } int cnt = 0; for (int i = 0; i < SDMask.GetLength(0); i++) { for (int j = 0; j < SDMask.GetLength(1); j++) { if (SDMask[i, j]) { cnt++; } } } data.probe.ChannelMap = new ChannelMap[cnt * lambda.Length]; cnt = 0; List <int> ChanIdx = new List <int>(); int cnt2 = 0; for (int w = 0; w < lambda.Length; w++) { for (int i = 0; i < SDMask.GetLength(0); i++) { for (int j = 0; j < SDMask.GetLength(1); j++) { if (SDMask[i, j]) { data.probe.ChannelMap[cnt] = new ChannelMap(); data.probe.ChannelMap[cnt].sourceindex = i; data.probe.ChannelMap[cnt].detectorindex = j; data.probe.ChannelMap[cnt].channelname = String.Format("Src{0}-Det{1}", data.probe.ChannelMap[cnt].sourceindex + 1, data.probe.ChannelMap[cnt].detectorindex + 1); data.probe.ChannelMap[cnt].wavelength = lambda[w]; data.probe.ChannelMap[cnt].datasubtype = String.Format("{0}nm", data.probe.ChannelMap[cnt].wavelength); cnt++; if (w == 0) { ChanIdx.Add(cnt2); } } cnt2++; } } } data.probe.numChannels = data.probe.ChannelMap.Length; data.probe.measlistAct = new bool[data.probe.numChannels]; for (int i = 0; i < data.probe.numChannels; i++) { data.probe.measlistAct[i] = false; } data.probe.measlistAct[0] = true; // read the actual data System.IO.StreamReader file2 = new System.IO.StreamReader(filename + ".wl1"); string lines = file2.ReadToEnd(); string[] tpts = lines.Split('\r'); data.data = new List <double> [data.probe.numChannels]; for (int i = 0; i < data.data.Length; i++) { data.data[i] = new List <double>(); } for (int i = 0; i < tpts.Length - 1; i++) { if (tpts[i].Contains("\n")) { tpts[i] = tpts[i].Substring(1, tpts[i].Length - 1); } string[] pts = tpts[i].Split(' '); for (int j = 0; j < ChanIdx.Count; j++) { data.data[j].Add(Convert.ToDouble(pts[ChanIdx[j]])); } } file2 = new System.IO.StreamReader(filename + ".wl2"); lines = file2.ReadToEnd(); tpts = lines.Split('\r'); for (int i = 0; i < tpts.Length - 1; i++) { if (tpts[i].Contains("\n")) { tpts[i] = tpts[i].Substring(1, tpts[i].Length - 1); } string[] pts = tpts[i].Split(' '); for (int j = 0; j < ChanIdx.Count; j++) { data.data[j + data.probe.numChannels / 2].Add(Convert.ToDouble(pts[ChanIdx[j]])); } } // finally, the time vector int fsIdx = hdrFields.IndexOf("SamplingRate"); double fs = Convert.ToDouble(hdrValues[fsIdx]); data.numsamples = data.data.GetLength(1); data.time = new List <double>(); for (int i = 0; i < data.numsamples; i++) { data.time.Add(i / fs); } // TODO add stimulus information int EventIdx = hdrFields.IndexOf("Events"); string[] eventline = hdrValues[EventIdx].Split('\r'); double[,] events = new double[eventline.Length - 1, 3]; for (int i = 1; i < eventline.Length; i++) { string[] eventline2 = eventline[i].Split('\t'); for (int j = 0; j < 2; j++) { events[i - 1, j] = Convert.ToDouble(eventline2[j]); } } List <double> uniqEvents = new List <double>(); int[] uniqEventCount = new int[events.GetLength(0)]; for (int i = 0; i < events.GetLength(0); i++) { uniqEventCount[i] = 0; if (!uniqEvents.Contains(events[i, 1])) { uniqEvents.Add(events[i, 1]); } int ii = uniqEvents.IndexOf(events[i, 1]); uniqEventCount[ii]++; } data.stimulus = new List <Stimulus>(); for (int i = 0; i < uniqEvents.Count; i++) { Stimulus stimulus = new Stimulus(); stimulus.name = String.Format("Event-{0}", uniqEvents[i]); stimulus.onsets = new List <double>(); stimulus.duration = new List <double>(); stimulus.amplitude = new List <double>(); int n = 0; for (int j = 0; j < events.GetLength(0); j++) { if (Math.Abs(events[j, 1] - uniqEvents[i]) < 0.0001) { stimulus.onsets.Add(events[j, 0]); stimulus.duration.Add(1); stimulus.amplitude.Add(1); n++; } } data.stimulus.Add(stimulus); } //add demographics info List <string> Fields = new List <string>() { "Subject", "notes", "FileName", "Date", "Device", "Source", "Mod", "APD", "NIRStar", "Mod Amp" }; for (int i = 0; i < Fields.Count; i++) { int idx = hdrFields.IndexOf(Fields[i]); if (idx > -1) { data.demographics.set(Fields[i], hdrValues[idx]); } } data.description = targetDirectory; return(data); }
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 } } }
//public void CreateCSVFile(DataTable dt, string strFilePath) //{ // #region Export Grid to CSV // // Create the CSV file to which grid data will be exported. // StreamWriter sw = new StreamWriter(strFilePath, false); // // First we will write the headers. // //DataTable dt = m_dsProducts.Tables[0]; // int iColCount = dt.Columns.Count; // for (int i = 0; i < iColCount; i++) // { // sw.Write(dt.Columns[i]); // if (i < iColCount - 1) // { // sw.Write(","); // } // } // sw.Write(sw.NewLine); // // Now write all the rows. // foreach (DataRow dr in dt.Rows) // { // for (int i = 0; i < iColCount; i++) // { // if (!Convert.IsDBNull(dr[i])) // { // sw.Write(dr[i].ToString()); // } // if (i < iColCount - 1) // { // sw.Write(","); // } // } // sw.Write(sw.NewLine); // } // sw.Close(); // #endregion //} private MLArray createStruct() { MLStructure outStruct = new MLStructure("kinectData", new int[] { 1, 1 }); //string[] headers = {"HipCenterX", "HipCenterY", "HipCenterZ", "SpineX", "SpineY", "SpineZ", "ShoulderCenterX", // "ShoulderCenterY", "ShoulderCenterZ", "HeadX", "HeadY", "HeadZ", "ShoulderLeftX", // "ShoulderLeftY", "ShoulderLeftZ", "ElbowLeftX", "ElbowLeftY", "ElbowLeftZ", "WristLeftX", // "WristLeftY", "WristLeftZ", "HandLeftX", "HandLeftY", "HandLeftZ", "ShoulderRightX", // "ShoulderRightY", "ShoulderRightZ", "ElbowRightX", "ElbowRightY", "ElbowRightZ", // "WristRightX", "WristRightY", "WristRightZ", "HandRightX", "HandRightY", "HandRightZ", // "HipLeftX", "HipLeftY", "HipLeftZ", "KneeLeftX", "KneeLeftY", "KneeLeftZ", "AnkleLeftX", // "AnkleLeftY", "AnkleLeftZ", "FootLeftX", "FootLeftY", "FootLeftZ", "HipRightX", "HipRightY", // "HipRightZ", "KneeRightX", "KneeRightY", "KneeRightZ", "AnkleRightX", "AnkleRightY", // "AnkleRightZ", "FootRightX", "FootRightY", "FootRightZ"}; double criticalC1D = Convert.ToDouble(criticalC1); double criticalC2D = Convert.ToDouble(criticalC2); double criticalC3D = Convert.ToDouble(criticalC3); double criticalC11D = Convert.ToDouble(criticalC11); double criticalC21D = Convert.ToDouble(criticalC21); double criticalC31D = Convert.ToDouble(criticalC31); double criticalC12D = Convert.ToDouble(criticalC12); double criticalC22D = Convert.ToDouble(criticalC22); double criticalC32D = Convert.ToDouble(criticalC32); double criticalC13D = Convert.ToDouble(criticalC13); double criticalC23D = Convert.ToDouble(criticalC23); double criticalC33D = Convert.ToDouble(criticalC33); double criticalC14D = Convert.ToDouble(criticalC14); double criticalC24D = Convert.ToDouble(criticalC24); double criticalC34D = Convert.ToDouble(criticalC34); double[] ccArray = { criticalC1D, criticalC2D, criticalC3D, criticalC11D, criticalC21D, criticalC31D, criticalC12D, criticalC22D, criticalC32D, criticalC13D, criticalC23D, criticalC33D, criticalC14D, criticalC24D, criticalC34D}; Double[] skelDataA = (Double[])skelData.ToArray(typeof(double)); Double[] gpVectorA = (Double[])gpVector.ToArray(typeof(double)); Double[] kinectTiltA = (Double[])kinectTilt.ToArray(typeof(double)); outStruct["skelData", 0] = new MLDouble("", skelDataA, 60); outStruct["dateHeader", 0] = new MLChar("", timeStamp); outStruct["criticalComps", 0] = new MLDouble("", ccArray, 3); outStruct["exercise", 0] = new MLChar("", exercise); MLStructure groundStruct = new MLStructure("", new int[] { 1, 1 }); groundStruct["height", 0] = new MLDouble("", new double[] { 0.68 }, 1); // metres? groundStruct["gpVector", 0] = new MLDouble("", gpVectorA, 4); //metres? groundStruct["kinectTilt", 0] = new MLDouble("", kinectTiltA, 1); //degrees outStruct["groundPlaneData", 0] = groundStruct; return outStruct; }
/// <summary> /// Reads <c>miMATRIX</c> from the input stream. /// </summary> /// <remarks> /// If reading was not finished (which is normal for filtered results) /// returns <c>null</c>. /// </remarks> /// <param name="buf">The <c>BinaryReader</c> input stream.</param> /// <param name="isRoot">When <c>true</c> informs that if this is a top level /// matrix.</param> /// <returns><c>MLArray</c> or <c>null</c> if matrix does not match <c>filter</c></returns> private MLArray ReadMatrix(Stream buf, bool isRoot) { // result MLArray mlArray = null; ISMatTag tag; // read flags int[] flags = ReadFlags(buf); int attributes = (flags.Length != 0) ? flags[0] : 0; int nzmax = (flags.Length != 0) ? flags[1] : 0; int type = attributes & 0xff; // read Array dimension int[] dims = ReadDimension(buf); // read Array name string name = ReadName(buf); // If this array is filtered out return immediately if (isRoot && !_filter.Matches(name)) { return(null); } // read data switch (type) { case MLArray.mxSTRUCT_CLASS: MLStructure mlStruct = new MLStructure(name, dims, type, attributes); BinaryReader br = new BinaryReader(buf); // field name length - this subelement always uses the compressed data element format tag = new ISMatTag(br.BaseStream); int maxlen = br.ReadInt32(); // Read fields data as Int8 tag = new ISMatTag(br.BaseStream); // calculate number of fields int numOfFields = tag.Size / maxlen; // padding after field names int padding = (tag.Size % 8) != 0 ? 8 - tag.Size % 8 : 0; string[] fieldNames = new string[numOfFields]; for (int i = 0; i < numOfFields; i++) { byte[] names = new byte[maxlen]; br.Read(names, 0, names.Length); fieldNames[i] = ZeroEndByteArrayToString(names); } br.ReadBytes(padding); // read fields for (int index = 0; index < mlStruct.M * mlStruct.N; index++) { for (int i = 0; i < numOfFields; i++) { // read matrix recursively tag = new ISMatTag(br.BaseStream); if (tag.Size > 0) { MLArray fieldValue = ReadMatrix(br.BaseStream, false); mlStruct[fieldNames[i], index] = fieldValue; } else { mlStruct[fieldNames[i], index] = new MLEmptyArray(); } } } mlArray = mlStruct; //br.Close(); break; case MLArray.mxCELL_CLASS: MLCell cell = new MLCell(name, dims, type, attributes); for (int i = 0; i < cell.M * cell.N; i++) { tag = new ISMatTag(buf); if (tag.Size > 0) { MLArray cellmatrix = ReadMatrix(buf, false); cell[i] = cellmatrix; } else { cell[i] = new MLEmptyArray(); } } mlArray = cell; break; case MLArray.mxDOUBLE_CLASS: mlArray = new MLDouble(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <double>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <double>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxSINGLE_CLASS: mlArray = new MLSingle(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <float>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <float>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxUINT8_CLASS: mlArray = new MLUInt8(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <byte>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <byte>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxINT8_CLASS: mlArray = new MLInt8(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <sbyte>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <sbyte>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxUINT16_CLASS: mlArray = new MLUInt16(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <ushort>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <ushort>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxINT16_CLASS: mlArray = new MLInt16(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <short>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <short>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxUINT32_CLASS: mlArray = new MLUInt32(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <uint>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <uint>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxINT32_CLASS: mlArray = new MLInt32(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <int>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <int>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxUINT64_CLASS: mlArray = new MLUInt64(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <ulong>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <ulong>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxINT64_CLASS: mlArray = new MLInt64(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <long>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray <long>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxCHAR_CLASS: MLChar mlchar = new MLChar(name, dims, type, attributes); //read real tag = new ISMatTag(buf); char[] ac = tag.ReadToCharArray(); for (int i = 0; i < ac.Length; i++) { mlchar.SetChar(ac[i], i); } mlArray = mlchar; break; case MLArray.mxSPARSE_CLASS: MLSparse sparse = new MLSparse(name, dims, attributes, nzmax); // read ir (row indices) tag = new ISMatTag(buf); int[] ir = tag.ReadToIntArray(); // read jc (column indices) tag = new ISMatTag(buf); int[] jc = tag.ReadToIntArray(); // read pr (real part) tag = new ISMatTag(buf); double[] ad1 = tag.ReadToDoubleArray(); int n = 0; for (int i = 0; i < ir.Length; i++) { if (i < sparse.N) { n = jc[i]; } sparse.SetReal(ad1[i], ir[i], n); } //read pi (imaginary part) if (sparse.IsComplex) { tag = new ISMatTag(buf); double[] ad2 = tag.ReadToDoubleArray(); int n1 = 0; for (int i = 0; i < ir.Length; i++) { if (i < sparse.N) { n1 = jc[i]; } sparse.SetImaginary(ad2[i], ir[i], n1); } } mlArray = sparse; break; default: throw new MatlabIOException("Incorrect Matlab array class: " + MLArray.TypeToString(type)); } return(mlArray); }
private static nirs.core.Probe loadSDprobe(string file, int[] lambda) { nirs.core.Probe probe = new core.Probe(); MatFileReader mfr = new MatFileReader(file); MLStructure SD = (mfr.Content["SD"] as MLStructure); MLDouble MLsrcpos = null; if (SD.Keys.Contains("SrcPos")) { MLsrcpos = (SD["SrcPos"] as MLDouble); } else if (SD.Keys.Contains("srcpos")) { MLsrcpos = (SD["srcpos"] as MLDouble); } MLDouble MLdetpos = null; if (SD.Keys.Contains("DetPos")) { MLdetpos = (SD["DetPos"] as MLDouble); } else if (SD.Keys.Contains("detpos")) { MLdetpos = (SD["detpos"] as MLDouble); } if (MLdetpos != null) { double[][] detpos = MLdetpos.GetArray(); probe.DetPos = new double[detpos.Length, 3]; probe.DetectorLabels = new string[detpos.Length]; for (int i = 0; i < detpos.Length; i++) { probe.DetPos[i, 0] = (float)detpos[i][0]; probe.DetPos[i, 1] = (float)detpos[i][1]; probe.DetPos[i, 2] = (float)detpos[i][2]; probe.DetectorLabels[i] = String.Format("Detector-{0}", +1); } probe.numDet = detpos.Length; } if (MLsrcpos != null) { double[][] srcpos = MLsrcpos.GetArray(); probe.SrcPos = new double[srcpos.Length, 3]; probe.SourceLabels = new string[srcpos.Length]; for (int i = 0; i < srcpos.Length; i++) { probe.SrcPos[i, 0] = (float)srcpos[i][0]; probe.SrcPos[i, 1] = (float)srcpos[i][1]; probe.SrcPos[i, 2] = (float)srcpos[i][2]; probe.SourceLabels[i] = String.Format("Source-{0}", i + 1); } probe.numSrc = srcpos.Length; } MLDouble mlMeasList = null; if (mfr.Content.ContainsKey("ml")) { mlMeasList = (mfr.Content["ml"] as MLDouble); } else { mlMeasList = (SD["MeasList"] as MLDouble); } if (mlMeasList != null) { double[][] ml = mlMeasList.GetArray(); probe.ChannelMap = new ChannelMap[ml.Length]; for (int i = 0; i < ml.Length; i++) { probe.ChannelMap[i] = new ChannelMap(); probe.ChannelMap[i].sourceindex = (int)ml[i][0] - 1; probe.ChannelMap[i].detectorindex = (int)ml[i][1] - 1; probe.ChannelMap[i].channelname = String.Format("Src{0}-Det{1}", probe.ChannelMap[i].sourceindex + 1, probe.ChannelMap[i].detectorindex + 1); probe.ChannelMap[i].wavelength = lambda[(int)ml[i][3] - 1]; probe.ChannelMap[i].datasubtype = String.Format("{0}nm", probe.ChannelMap[i].wavelength); } } probe.numChannels = probe.ChannelMap.Length; probe.measlistAct = new bool[probe.numChannels]; for (int i = 0; i < probe.numChannels; i++) { probe.measlistAct[i] = false; } probe.measlistAct[0] = true; probe.numWavelengths = lambda.Length; return(probe); }