예제 #1
0
    // Use this for initialization
    void Start()
    {
        string path = "C:/Users/...myfolder.../data.csv";

        // get ecg at 250Hz sample rate. Record data for 5sec untill thresholds (97th-percentiles for voltage and voltage change) are determined.
        // Then keep checking if both thresholds are reached within 0.02sec, but don't allow two r peaks within 0.196sec. Write down everything to path.
        ecg1 = new ECG(250, 5, 0.97f, 0.97f, 0.02f, 0.196f, path);
    }
예제 #2
0
        /// <summary>
        /// Used to generate ECG signal model from PhysioNet signal files. Method searches for .HEA, .DAT and .ATR files
        /// with the name given as method call parameter.
        /// </summary>
        /// <param name="signalFileName">Full path to the HEA file (e.g. C:\100.HEA)</param>
        /// <returns>Generated ECG model.</returns>
        static public ECG loadECGFromSignalFile(String signalFileName, int channelToLoad = 1)
        {
            String route = signalFileName.Substring(0, signalFileName.Length - 4);

            if (!File.Exists(route + ".dat") && !File.Exists(route + ".txt"))
            {
                List <RequiredFilesMissingException.RequiredFiles> requiredFiles = new List <RequiredFilesMissingException.RequiredFiles>
                {
                    RequiredFilesMissingException.RequiredFiles.DAT,
                    RequiredFilesMissingException.RequiredFiles.TXT
                };

                throw new RequiredFilesMissingException(requiredFiles);
            }

            ECG ecg = null;

            if (File.Exists(route + ".dat"))
            {
                ecg = loadECGFromSignalBinaryFile(signalFileName, channelToLoad);
            }
            else
            {
                ecg = loadECGFromSignalTextFile(signalFileName, channelToLoad);
            }

            List <ECGAnnotation> standardAnnotations = null;
            List <ECGAnnotation> customAnnotations   = null;

            if (File.Exists(route + ".atr"))
            {
                standardAnnotations = loadStandardAnnotations(route + ".atr", channelToLoad);
            }

            if (File.Exists(route + ".cust"))
            {
                customAnnotations = loadCustomAnnotations(route + ".cust", channelToLoad);
            }

            if (standardAnnotations != null)
            {
                if (customAnnotations != null)
                {
                    standardAnnotations = standardAnnotations.Concat(customAnnotations).ToList();
                }

                ecg.Annotations = standardAnnotations;
            }
            else
            {
                if (customAnnotations != null)
                {
                    ecg.Annotations = customAnnotations;
                }
            }

            return(ecg);
        }
예제 #3
0
        public void Delete(int id)
        {
            ECG ECG = _db.ECGs.Find(id);

            if (ECG != null)
            {
                _db.ECGs.Remove(ECG);
            }
        }
예제 #4
0
 public void StopRecording()
 {
     EIT?.CompleteAdding();
     ECG?.CompleteAdding();
     SystemEvents?.StopRecording();
     RPosition?.StopRecording();
     Tags?.StopRecording();
     RecordingInProgress = false;
 }
예제 #5
0
        /// <summary>
        /// Used to save ECG signal model to PhysioNet signal files. Method generates .HEA, .DAT and .ATR files
        /// with the name given as method call parameter.
        /// </summary>
        /// <param name="signalFileName">Path + signal name (e.g. C:\100)</param>
        static public void saveECGToSignalFiles(ECG signal, String signalFileName)
        {
            // save HEA ATR DAT & CUST

            // save standard annotations
            saveStandardAnnotations(signal, signalFileName.Substring(0, signalFileName.Length - 4));

            //save custom annotations
            saveCustomAnnotations(signal, signalFileName.Substring(0, signalFileName.Length - 4));
        }
예제 #6
0
        /// <summary>
        /// Performs QRS-complex detection on ECG signal provided as call argument.
        /// </summary>
        /// <param name="signal">ECG signal object</param>
        /// <returns>List of ECG points determined to be R spikes and Decimal value for measured heart-rate</returns>
        public static List <ECGPoint> QRS_Detect(ECG signal)
        {
            // extract voltages from ecg signal points
            double[] voltages = signal.Points.Select(point => point.Value).ToArray();
            // perform QRS detection
            List <int> spikeIndices = SoAndChan(voltages);
            // map indices of R spikes into corresponding ecg signal points
            List <ECGPoint> spikes = spikeIndices.Select(index => signal.Points[index]).ToList();

            return(spikes);
        }
예제 #7
0
 public Task StartLogging(AcquisitionProtocolParameters acquisitionProtocol)
 {
     EIT = new EIT(RecordNumber++, EITDefaultChunkSize, acquisitionProtocol.AsJson(), fileId, groupEIT, Logger);
     //var acquisitionInformation = new AcquisitionInformation(acquisitionProtocol, fileId, groupEIT, Logger);
     //acquisitionInformation.FlushDataAndCloseObject();
     ECG = new ECG(fileId, groupRoot, ECGDefaultChunkSize, (int)acquisitionProtocol.ScanDescription.EcgParams.SampleRate, Logger);
     SystemEvents.StartLogging();
     RPosition.StartLogging();
     Tags.StartLogging();
     return(Task.CompletedTask);
 }
예제 #8
0
        private void Open_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog()
            {
                DefaultExt = ".HEA",
                Filter     = "HEA Files (*.HEA)|*.HEA"
            };

            // Display OpenFileDialog by calling ShowDialog method
            Nullable <bool> result = dlg.ShowDialog();


            // Get the selected file name
            if (result == true)
            {
                // Open file name
                string filename = dlg.FileName;
                try
                {
                    List <String> channelNames = IOManager.loadCanals(filename);

                    ChannelSelector channelSelector = new ChannelSelector(channelNames);
                    channelSelector.ShowDialog();

                    int selectedChannelIndex = channelSelector.SelectedChannel;
                    if (selectedChannelIndex == -1)
                    {
                        MessageBox.Show("No channel selected. Aborting signal load.");
                        return;
                    }

                    signal            = IOManager.loadECGFromSignalFile(filename, selectedChannelIndex + 1);
                    ecgView.ECGSignal = signal;
                }
                catch (RequiredFilesMissingException ex)
                {
                    String msg = "Signal files missing: ";
                    foreach (RequiredFilesMissingException.RequiredFiles rf in ex.MissingFiles)
                    {
                        msg += rf + " ";
                    }
                    MessageBox.Show(msg);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unexpected error occurred: " + ex.Message);
                }
            }
            // else just ignore it
        }
예제 #9
0
        public static double Determine_HeartRate(ECG signal, double lowerTimeIndex, double upperTimeIndex)
        {
            List <ECGPoint> spikesWithinBounds = signal.Spikes.Where(ecgpoint =>
            {
                return(ecgpoint.TimeIndex >= lowerTimeIndex && ecgpoint.TimeIndex <= upperTimeIndex);
            }).ToList();

            // get the seconds between first and the last spike
            double sumTimesBetweenSpikes = spikesWithinBounds[spikesWithinBounds.Count - 1].TimeIndex - spikesWithinBounds[0].TimeIndex;
            // determine the HR
            double heartRate = 60 * spikesWithinBounds.Count / sumTimesBetweenSpikes;

            return(Math.Round(heartRate, 2));
        }
예제 #10
0
        private void MenuItem_FileOpen_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();

            fd.Filter      = "Signal Files (*.EDF, *.TXT, *.CSV) | *.TXT; *.EDF; *.CSV";
            fd.Title       = "Open RAW data file.";
            fd.Multiselect = false;

            if (fd.ShowDialog() == true)
            {
                var signalSamples = ReadSignalFile(fd.FileName);
                ECG.SetSignalData(signalSamples);
            }
        }
예제 #11
0
        static private void saveCustomAnnotations(ECG signal, String signalFileName)
        {
            FileStream           fileStream   = new FileStream(signalFileName + ".cust", FileMode.Create);
            StreamWriter         streamWriter = new StreamWriter(fileStream);
            List <ECGAnnotation> annotations  = signal.Annotations;

            foreach (var annotation in annotations)
            {
                if (annotation.Type == ANNOTATION_TYPE.ANSWER || annotation.Type == ANNOTATION_TYPE.SOLUTION)
                {
                    streamWriter.WriteLine("{0} {1} {2} {3}", annotation.Type, signal.Channel, annotation.TimeIndex, annotation.Text);
                }
            }
            streamWriter.Close();
        }
예제 #12
0
        private async Task CloseHandles()
        {
            ProcedureInformation.FlushDataAndCloseObject();
            SystemInformation.FlushDataAndCloseObject();
            CalibrationGroup.FlushDataAndCloseObject();
            //wait for writing all data before resetting
            if (EIT != null)
            {
                await EIT.WaitForDataWritten();

                EIT.Dispose();
            }

            if (ECG != null)
            {
                await ECG.WaitForDataWritten();

                ECG.Dispose();
            }
            if (SystemEvents != null)
            {
                await SystemEvents.WaitForDataWritten();

                SystemEvents.Dispose();
            }

            if (RPosition != null)
            {
                await RPosition.WaitForDataWritten();

                RPosition.Dispose();
            }
            if (Tags != null)
            {
                await Tags.WaitForDataWritten();

                Tags.Dispose();
            }
            if (UserEventsGroup != null)
            {
                await UserEventsGroup.WaitForDataWritten();

                UserEventsGroup.Dispose();
            }
            await Task.CompletedTask;
        }
예제 #13
0
        static private ECG loadECGFromSignalTextFile(String signalFileName, int channelToLoad = 1)
        {
            String          signal       = signalFileName.Substring(0, signalFileName.Length - 4);
            FileStream      file         = new FileStream(signal + ".txt", FileMode.Open);
            StreamReader    streamReader = new StreamReader(file);
            List <ECGPoint> ecgPoints    = new List <ECGPoint>();
            string          line         = "";

            line = streamReader.ReadLine();
            int count = 0;

            while (!(line.Contains("0.000")))
            {
                if (line == null)
                {
                    break;
                }
                try
                {
                    line = streamReader.ReadLine();
                }
                catch (Exception)
                {
                    Console.WriteLine(ecgPoints.ToString());
                }
            }

            do
            {
                ECGPoint ecgPoint = new ECGPoint();
                ecgPoint.Value     = (double.Parse(line.Split('\t')[channelToLoad]));
                ecgPoint.TimeIndex = count / Convert.ToDouble(Frequency);
                ecgPoints.Add(ecgPoint);
            } while ((line = streamReader.ReadLine()) != null);
            file.Close();
            streamReader.Close();
            ECG ecg = new ECG();

            ecg.Name         = signalFileName;
            ecg.Points       = ecgPoints;
            ecg.SamplingRate = Frequency;
            ecg.Channel      = channelToLoad;
            return(ecg);
        }
예제 #14
0
        private void StaticAfterInitializeComponent()
        {
            String[]      values = File.ReadAllText(@"C:\Projects\moar.csv").Replace("\r\n", ";").Split(';');
            List <double> points = new List <double>();

            for (int i = 1; i < values.Length; i += 3)
            {
                points.Add(Double.Parse(values[i], CultureInfo.InvariantCulture));
            }

            signal = new ECG();
            signal.SamplingRate = 360;
            signal.Name         = "100";
            for (int i = 0; i < points.Count; i++)
            {
                signal.Points.Add(new ECGPoint()
                {
                    TimeIndex = (double)(i + 1) / 360, Value = points[i]
                });
            }
            ecgView.ECGSignal = signal;
        }
예제 #15
0
 public void AppendEcgCycleDescriptionSample(ECGCycleDescription e) => ECG.AppendEcgCycleDescriptionSample(e);
예제 #16
0
        public ActionResult Create(Record record, HttpPostedFileBase txtfile)
        {
            if (ModelState.IsValid)
            {
                string filename = ""; string path = ""; string Data = "";
                if (txtfile != null && txtfile.ContentLength > 0)
                {
                    filename = System.Guid.NewGuid() + "_" + txtfile.FileName;
                    path     = Server.MapPath("~/Signals/" + filename);
                    txtfile.SaveAs(path);
                    //   record.Data = filename;
                    Data        = System.IO.File.ReadAllText(path);
                    record.Data = Data;
                }
                #region Filter File
                string path1 = Server.MapPath("~/Matlab");
                System.IO.File.WriteAllText(path1 + "\\" + filename, Data);
                MLApp.MLApp matlab = new MLApp.MLApp();
                matlab.Execute("cd('" + path1 + "')");
                matlab.Execute("a=load('" + filename + "')");
                matlab.Execute("c=baselinefilter(a," + 370 + ")");
                var    o        = (double[, ])matlab.GetVariable("c", "base");
                string filedata = "";

                for (int i = 0; i < o.GetLength(0); i++)
                {
                    for (int j = 0; j < o.GetLength(1); j++)
                    {
                        filedata += o[i, j] + " ";
                    }
                    filedata.Trim(' ');

                    filedata += "\n";
                }
                #endregion //DONE!

                #region Pass File to Feature Extractor
                ECG    ecgFeatureExtractor = new ECG();
                string InputVector         = ecgFeatureExtractor.ExtractFeatures(filedata, filename, 370); // fs = 370
                string filename2           = "feat.txt";
                System.IO.File.WriteAllText(path1 + "\\" + filename2, InputVector);
                #endregion


                #region simulate network
                matlab.Execute("b = load ('" + filename2 + "')");
                matlab.Execute("n = load('matlab.mat')");
                matlab.Execute("s = sim(n.net ,b)");
                var obj = (double[, ])matlab.GetVariable("s", "base");
                #endregion

                /* #region Make Logical Decision
                 * int MaxIndex = -1;
                 * int numpulses = obj.GetLength(1);
                 * int numpvc = 0; int numlbbb = 0; int numrbbb = 0; int numnormal = 0;
                 * var vector = new List<double>();
                 * for (int j = 0; j < numpulses; j++)
                 * {
                 *  // for (int i = 0; i < obj.GetLength(0); i++)
                 *   for (int i = 0; i < 4; i++)
                 *   {
                 *       vector.Add(obj[i, j]);
                 *   }
                 *   MaxIndex = vector.IndexOf(vector.Max());
                 *   switch (MaxIndex)
                 *   {
                 *       case 0: //pvc
                 *           numpvc++;
                 *           break;
                 *       case 1: //lbbb
                 *           numlbbb++;
                 *           break;
                 *       case 2: //rbbb
                 *           numrbbb++;
                 *           break;
                 *       case 3: //normal
                 *           numnormal++;
                 *           break;
                 *       default:
                 *           break;
                 *   }
                 * }
                 * string result = "Pvc = " + ((double)(numpvc * 100) / numpulses )+ "%" + "Lbbb = "
                 + ((double)(numlbbb * 100) / numpulses )+ "% " + "Rbbb = "
                 + ((double)(numrbbb * 100) / numpulses )+ "% " + "Normal = "
                 + ((double)(numnormal * 100) / numpulses )+ "%";
                 +
                 + //string result = "Pvc = " + numpvc + "lbbb = " + numlbbb + "rbbb =" + numrbbb + "normal = " + numnormal;
                 #endregion
                 */
                #region other result
                int non = 0;
                int nol = 0;
                int nor = 0;
                int nop = 0;
                for (int i = 0; i < obj.GetLength(1); i++)
                {
                    double maxx = -1;
                    for (int j = 0; j < 4; j++)
                    {
                        if (obj[0, i] >= maxx)
                        {
                            maxx = obj[0, i];
                        }
                        if (obj[1, i] >= maxx)
                        {
                            maxx = obj[1, i];
                        }
                        if (obj[2, i] >= maxx)
                        {
                            maxx = obj[2, i];
                        }
                        if (obj[3, i] >= maxx)
                        {
                            maxx = obj[3, i];
                        }
                        if (obj[0, i] == maxx)
                        {
                            nop++;
                        }
                        if (obj[1, i] == maxx)
                        {
                            nol++;
                        }
                        if (obj[2, i] == maxx)
                        {
                            nor++;
                        }
                        if (obj[3, i] == maxx)
                        {
                            non++;
                        }
                    }
                }
                string resultt = "Pvc = " + nop + "lbbb = " + nol + "rbbb =" + nor + "normal = " + non;

                /*   string resultt = "Pvc = " + (double)((nop * 100) / obj.GetLength(0)) + "%" + "Lbbb = "
                 + (double)((nol * 100) / obj.GetLength(0)) + "% " + "Rbbb = "
                 + (double)((nor * 100) / obj.GetLength(0))+ "% " + "Normal = "
                 + (double)((non * 100) / obj.GetLength(0)) + "%";*/
                #endregion
                record.Result = resultt;
                //int PatientID = WebSecurity.GetUserId(User.Identity.Name);
                //Patient patient = db.Patients.Find(record.PatientID);
                int pid = 0;
                foreach (Patient pa in db.Patients)
                {
                    if (pa.Name == User.Identity.Name)
                    {
                        pid = pa.PatientID;
                    }
                }

                record.PatientID = pid;
                db.Records.Add(record);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.PatientID = new SelectList(db.Patients, "PatientID", "Name", record.PatientID);
            return(View(record));
        }
예제 #17
0
        public string Upload(int Id, string filename, string Data, int fs)
        {
            //TODO: Pass the file to the Feature Extractor

            #region Filter File
            string path = Server.MapPath("~/Models/MatlabFilters");
            System.IO.File.WriteAllText(path + "\\" + filename, Data);
            MLApp.MLApp matlab = new MLApp.MLApp();
            matlab.Execute("cd('" + path + "')");
            matlab.Execute("a=load('" + filename + "')");
            matlab.Execute("c=baselinefilter(a," + fs + ")");
            var    o        = (double[, ])matlab.GetVariable("c", "base");
            string filedata = "";

            for (int i = 0; i < o.GetLength(0); i++)
            {
                for (int j = 0; j <= o.GetLength(1); j++)
                {
                    filedata += o[i, j] + " ";
                }
                filedata.Trim(' ');

                filedata += "\n";
            }
            #endregion

            #region Pass File to Feature Extractor
            ECG ecgFeatureExtractor = new ECG();
            InputVector = ecgFeatureExtractor.ExtractFeatures(filedata, filename, fs); // fs = 370
            string filename2 = "feat.txt";
            File.WriteAllText(path + "\\" + filename2, InputVector);
            #endregion

            //File.WriteAllText(path + "\\" + filename,InputVector);

            #region Create New Record
            CardiologistV2.DAL.DatabaseContext db = new CardiologistV2.DAL.DatabaseContext();
            var p = db.Patients.Find(Id);
            var r = new CardiologistV2.Models.Record();
            r.PatientID = Id;
            r.Recdate   = DateTime.Now;
            r.Data      = filedata;

            //r.Featuress.Add(new Features() {
            //Value=InputVector,
            //})
            ;// = InputVector;
            #endregion

            //Calling Matlab...
            #region simulate network
            matlab.Execute("b = load('" + filename2 + "')");
            matlab.Execute("n = load('matlab.mat')");
            matlab.Execute("s = sim(n.net ,b)");
            var obj = (double[, ])matlab.GetVariable("s", "base");
            #endregion

            #region Make Logical Decision
            int MaxIndex = -1;
            int numpulses = obj.GetLength(1);
            int numpvc = 0; int numlbbb = 0; int numrbbb = 0; int numnormal = 0;
            var vector = new List <double>();
            for (int j = 0; j < numpulses; j++)
            {
                for (int i = 0; i < obj.GetLength(0); i++)
                {
                    vector.Add(obj[i, j]);
                }
                MaxIndex = vector.IndexOf(vector.Max());
                switch (MaxIndex)
                {
                case 0:     //pvc
                    numpvc++;
                    break;

                case 1:     //lbbb
                    numlbbb++;
                    break;

                case 2:     //rbbb
                    numrbbb++;
                    break;

                case 3:     //normal
                    numnormal++;
                    break;

                default:
                    break;
                }
            }

            string result = "Pvc = " + ((double)numpvc * 100.00) / numpulses + "%" + "Lbbb = "
                            + ((double)numlbbb * 100.00) / numpulses + "% " + "Rbbb = "
                            + ((double)numrbbb * 100.00) / numpulses + "% " + "Normal = "
                            + ((double)numnormal * 100.00) / numpulses + "%";
            #endregion

            #region Save in Database
            r.Result = result;
            p.Records.Add(r);
            db.SaveChanges();
            #endregion
            //TODO: Say everything's Alright
            return("200|" + result);
        }
예제 #18
0
 public void AppendEcgSample(ECGFrame e)
 {
     ECG.Enqueue(e);
 }
예제 #19
0
 /// <summary>
 /// Clears the current view and all associated data.
 /// </summary>
 public void clear()
 {
     _ecgSignal = null;
     refresh();
 }
예제 #20
0
    public bool processECG(float y0, ECG ecg)
    {
        bool rpeak = false; // first assume there is no heartbeat

        ecg.currentTimestamp = Time.time;
        //ecg.timestamp.Add(ecg.currentTimestamp);

        ecg.currentVolt = y0;
        //ecg.voltage.Add(ecg.currentVoltage);

        ecg.currentDiff = Mathf.Abs(ecg.currentVolt - ecg.lastVoltage);
        //ecg.voltage_diff.Add(ecg.currentDiff);

        if (ecg.counter < ecg.timepointsTillThreshold)
        {
            ecg.firstMeasurementsVolt[ecg.counter] = ecg.currentVolt; // in beginning, also write to additional array that can be sorted
            ecg.firstMeasurementsDiff[ecg.counter] = ecg.currentDiff;
        }

        // Determine threshold at given point in time
        if (ecg.counter == ecg.timepointsTillThreshold)
        {
            Array.Sort(ecg.firstMeasurementsVolt);
            ecg.thresholdVolt = ecg.firstMeasurementsVolt[Mathf.FloorToInt(ecg.firstMeasurementsVolt.Length * ecg.thresholdVoltPercentile)];

            Array.Sort(ecg.firstMeasurementsDiff);
            ecg.thresholdDiff = ecg.firstMeasurementsDiff[Mathf.FloorToInt(ecg.firstMeasurementsDiff.Length * ecg.thresholdDiffPercentile)];

            Debug.Log("voltage threshold was set to " + ecg.thresholdVolt + ", voltage change threshold was set to " + +ecg.thresholdDiff);
        }

        // then start finding R-peaks
        if (ecg.counter > ecg.timepointsTillThreshold)
        {
            if (ecg.currentVolt > ecg.thresholdVolt)
            {
                ecg.VoltageThresholdReached = ecg.timeDelay;                                       // if threshold is reached, wave a flag and see if other threshold is reached within timeDelay too
            }
            if (ecg.currentDiff > ecg.thresholdDiff)
            {
                ecg.VoltageDiffThresholdReached = ecg.timeDelay;
            }
        }

        if (ecg.VoltageThresholdReached > 0 & ecg.VoltageDiffThresholdReached > 0 & ecg.counterSinceLastPeak > ecg.blockTime) // only if both thresholds have been reached will we call this an r peak
        {
            rpeak = true;

            /*
             * float bpm = 60 * ecg.samplingrate / ecg.counterSinceLastPeak;
             * for (int i = 0; i < ecg.counterSinceLastPeak; i++)
             * {
             *  ecg.heartrate_realtime.Add(bpm);
             * }
             */
            ecg.counterSinceLastPeak = -1; // start counting again
        }

        ecg.line = ecg.counter.ToString() + ";" + ecg.currentVolt.ToString() + ";" + ecg.currentDiff.ToString() + ";" + ecg.currentTimestamp.ToString() + ";" + ecg.VoltageThresholdReached.ToString() + ";" + ecg.VoltageDiffThresholdReached.ToString() + ";" + rpeak.ToString(); // + ";" + ecg.heartrate_realtime.ToString();
        ecg.sw.WriteLine(ecg.line);


        if (ecg.VoltageThresholdReached > 0)
        {
            ecg.VoltageThresholdReached--;
        }
        if (ecg.VoltageDiffThresholdReached > 0)
        {
            ecg.VoltageDiffThresholdReached--;
        }
        ecg.counter++;
        ecg.counterSinceLastPeak++;
        ecg.lastVoltage = ecg.currentVolt;
        //ecg.r_peak_realtime.Add(rpeak);
        return(rpeak);
    }
예제 #21
0
 public void Create(ECG ECG)
 {
     _db.ECGs.Add(ECG);
 }
예제 #22
0
        static private void saveStandardAnnotations(ECG ecg, String atrFileName)
        {
            int sampleTime = 0;
            int num        = 0;
            int chan       = 0;

            FileStream   fs                 = new FileStream(atrFileName + ".atr", FileMode.Create);
            BinaryWriter writer             = new BinaryWriter(fs);
            byte         buf                = Convert.ToByte(0x0);
            byte         nul                = Convert.ToByte(0x0);
            int          previousSampleTime = 0;

            ecg.Annotations = ecg.Annotations.OrderBy(an => an.TimeIndex).ToList();

            for (int i = 0; i < ecg.Annotations.Count; i++)
            {
                ECGAnnotation annotation = ecg.Annotations.ElementAt(i);
                if (annotation.Type == ANNOTATION_TYPE.PHYSIONET_STANDARD)
                {
                    sampleTime         = Convert.ToInt32(annotation.TimeIndex * Frequency) - previousSampleTime;
                    previousSampleTime = Convert.ToInt32(annotation.TimeIndex * Frequency);

                    buf = Convert.ToByte(sampleTime & 0xFF);
                    writer.Write(buf);
                    buf = Convert.ToByte(Convert.ToByte((annotation.Code << 2) & 0xFF) | (Convert.ToByte((sampleTime >> 8) & 0xFF) & 0x3));
                    writer.Write(buf);

                    if (annotation.Aux != null && annotation.Aux.Length > 0)
                    {
                        buf = Convert.ToByte((annotation.Aux.Length + 1) & 0xFF);
                        writer.Write(buf);
                        buf = Convert.ToByte(Convert.ToByte((63 << 2) & 0xFF) | (Convert.ToByte(((annotation.Aux.Length + 1) >> 8) & 0xFF) & 0x3));
                        writer.Write(buf);

                        // write down AUX
                        for (int j = 0; j < annotation.Aux.Length; j++)
                        {
                            writer.Write(Convert.ToByte(annotation.Aux[j] & 0xFF));
                        }

                        writer.Write(nul); // string termination...

                        if (annotation.Aux.Length + 1 % 2 != 0)
                        {
                            writer.Write(nul);
                        }
                    }

                    if (annotation.SubTyp != 0)
                    {
                        // write down SUB
                        buf = Convert.ToByte(annotation.SubTyp & 0xFF);
                        writer.Write(buf);
                        buf = Convert.ToByte(Convert.ToByte((61 << 2) & 0xFF) | (Convert.ToByte((annotation.SubTyp >> 8) & 0xFF) & 0x3));
                        writer.Write(buf);
                    }

                    if ((ecg.Channel - 1) != chan)
                    {
                        chan = (ecg.Channel - 1);
                        // write down new CHAN

                        buf = Convert.ToByte(chan & 0xFF);
                        writer.Write(buf);
                        buf = Convert.ToByte(Convert.ToByte((62 << 2) & 0xFF) | (Convert.ToByte((chan >> 8) & 0xFF) & 0x3));
                        writer.Write(buf);
                    }

                    if (annotation.Num != num)
                    {
                        num = annotation.Num;
                        // write down new NUM

                        buf = Convert.ToByte(annotation.Num & 0xFF);
                        writer.Write(buf);
                        buf = Convert.ToByte(Convert.ToByte((60 << 2) & 0xFF) | (Convert.ToByte((annotation.Num >> 8) & 0xFF) & 0x3));
                        writer.Write(buf);
                    }
                }
            }

            // write EOF
            writer.Write(nul);
            writer.Write(nul);
            writer.Close();
        }
예제 #23
0
        static private ECG loadECGFromSignalBinaryFile(String signalFileName, int channelToLoad = 1)
        {
            String          signal = signalFileName.Substring(0, signalFileName.Length - 4);
            FileStream      file = new FileStream(signal + ".dat", FileMode.Open);
            BinaryReader    binReader = new BinaryReader(file);
            List <ECGPoint> ecgPoints = new List <ECGPoint>();
            int             count = 0;
            short           flag = 0;
            long            low = 0, high = 0;

            byte[] buf = { 0, 0, 0 };

            for (int i = 0; i < file.Length / 3; i++)
            {
                for (short j = 1; j <= 2; j++)
                {
                    count++;
                    switch (flag)
                    {
                    case 0:
                        try
                        {
                            buf = binReader.ReadBytes(3);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.ToString());
                        }
                        low  = buf[1] & 0x0F;
                        high = buf[1] & 0xF0;
                        if (channelToLoad == j)
                        {
                            if (low > 7)
                            {
                                ECGPoint ecgPoint = new ECGPoint();
                                ecgPoint.TimeIndex = count / Convert.ToDouble(Frequency);
                                ecgPoint.Value     = Convert.ToDouble(buf[0] + (low << 8) - 4096);
                                ecgPoints.Add(ecgPoint);
                            }
                            else
                            {
                                ECGPoint ecgPoint = new ECGPoint();
                                ecgPoint.TimeIndex = count / Convert.ToDouble(Frequency);
                                ecgPoint.Value     = Convert.ToDouble((buf[0] + (low << 8) - 1024) * 0.005);
                                ecgPoints.Add(ecgPoint);
                            }
                        }
                        flag = 1;
                        break;

                    case 1:
                        if (channelToLoad == j)
                        {
                            if (high > 127)
                            {
                                ECGPoint ecgPoint = new ECGPoint();
                                ecgPoint.TimeIndex = count / Convert.ToDouble(Frequency);
                                ecgPoint.Value     = Convert.ToDouble(buf[2] + (high << 4) - 4096);
                                ecgPoints.Add(ecgPoint);
                            }
                            else
                            {
                                ECGPoint ecgPoint = new ECGPoint();
                                ecgPoint.TimeIndex = count / Convert.ToDouble(Frequency);
                                ecgPoint.Value     = Convert.ToDouble((buf[2] + (high << 4) - 1024) * 0.005);
                                ecgPoints.Add(ecgPoint);
                            }
                        }
                        flag = 0;
                        break;
                    }
                }
            }
            file.Close();
            binReader.Close();
            ECG ecg = new ECG();

            ecg.Name         = signalFileName;
            ecg.Points       = ecgPoints;
            ecg.SamplingRate = Frequency;
            ecg.Channel      = channelToLoad;
            return(ecg);
            // look for HEA ATR DAT & CUST on path etc.
        }
예제 #24
0
 private void MenuItem_GenerateSignal_Click(object sender, RoutedEventArgs e)
 {
     float[] signalSamples = SignalGenerator.GenerateSignal();
     ECG.SetSignalData(signalSamples);
 }
예제 #25
0
 public void Update(ECG ECG)
 {
     _db.Entry(ECG).State = EntityState.Modified;
 }