Exemple #1
0
 public BDFPoint(BDFEDFFileReader bdf)
 {
     _rec = 0;
     _pt = 0;
     _recSize = bdf.NSamp;
     _sec = bdf.RecordDurationDouble;
     _st = _sec / (double)_recSize;
 }
Exemple #2
0
 static void Main(string[] args)
 {
     string fileName = @"C:\\Users\Jim\Desktop\Real datasets\S00xx-AP-20141107-1226\S0082-AP-20141107-1226.bdf";
     BDFEDFFileReader bdf = new BDFEDFFileReader(new FileStream(fileName, FileMode.Open, FileAccess.Read));
     Console.WriteLine("Opened BDF file " + fileName);
     string s;
     while (true)
     {
         Console.Write("Record number> ");
         if ((s = Console.ReadLine()) == "") break;
         BDFEDFRecord rec = bdf.read(Convert.ToInt32(s));
         Console.WriteLine("Rec # = " + rec.RecordNumber.ToString("0"));
         int[] status = bdf.getStatus();
         Console.Write(HexDump(status, 12, 2));
     }
 }
        public Window2()
        {
            Log.writeToLog("Starting FileConverter " + Utilities.getVersionNumber());

            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.Title = "Open Header file for conversion...";
            dlg.DefaultExt = ".hdr"; // Default file extension
            dlg.Filter = "HDR Files (.hdr)|*.hdr"; // Filter files by extension
            Nullable<bool> result = dlg.ShowDialog();
            if (result == null || result == false) { this.Close(); Environment.Exit(0); }

            directory = System.IO.Path.GetDirectoryName(dlg.FileName);

            head = (new HeaderFileReader(dlg.OpenFile())).read();
            ED = head.Events;

            bdf = new BDFEDFFileReader(
                new FileStream(System.IO.Path.Combine(directory, head.BDFFile),
                    FileMode.Open, FileAccess.Read));
            oldSR = bdf.NSamp / bdf.RecordDurationDouble;
            oldNP = bdf.NSamp;
            oldNS = bdf.RecordDurationDouble;

            InitializeComponent();

            this.MinHeight = SystemInformation.WorkingArea.Height - 240;
            this.Title = "Convert " + System.IO.Path.GetFileNameWithoutExtension(dlg.FileName);
            this.TitleLine.Text = head.Title + " - " + head.Date + " " + head.Time + " S=" + head.Subject.ToString("0000");

            _EDEList = ED.Values.ToList<EventDictionaryEntry>();
            listView1.SelectedItem = 0;
            listView1.Focus();
            listView1.ItemsSource = EDEList;

            System.Windows.Data.Binding GVBinding = new System.Windows.Data.Binding();
            GVBinding.Source = this;
            GVBinding.NotifyOnSourceUpdated = true;
            GVBinding.Path = new PropertyPath("GVList");
            GVBinding.Mode = BindingMode.OneWay;
            listView2.SetBinding(System.Windows.Controls.ListView.ItemsSourceProperty, GVBinding);
            GVList = EDEList[0].GroupVars;
        }
Exemple #4
0
 /// <summary>
 /// Links all input Events to a particular dataset in order to make the timing of InputEvents relative
 /// to the BDF file
 /// </summary>
 /// <param name="Head">HDR file reader for the dataset</param>
 /// <param name="BDF">BDF file reader for the dataset</param>
 public static void LinkEventsToDataset(Header.Header Head, BDFEDFFileReader BDF)
 {
     head = Head;
     bdf = BDF;
 }
        public MainWindow()
        {
            bool r;
            do //first get HDR file and open BDF file
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Title = "Open Header of dataset to be edited...";
                dlg.DefaultExt = ".hdr"; // Default file extension
                dlg.Filter = "HDR Files (.hdr)|*.hdr"; // Filter files by extension
                Nullable<bool> result = dlg.ShowDialog();
                if (result == null || result == false) Environment.Exit(0); 

                directory = System.IO.Path.GetDirectoryName(dlg.FileName); //will use to find other files in dataset
                headerFileName = System.IO.Path.GetFileNameWithoutExtension(dlg.FileName);

                header = (new HeaderFileReader(dlg.OpenFile())).read();
                updateFlag = header.Events.ContainsKey("**ArtifactBegin"); //indicates that we are editing a dataset that has already been edited for artifacts

                bdf = new BDFEDFFileReader(new FileStream(System.IO.Path.Combine(directory, header.BDFFile),
                        FileMode.Open, FileAccess.Read));

                //make list of candidate EEG channels, so that channel selection window can use it
                BDFLength = (double)bdf.NumberOfRecords * bdf.RecordDuration;
                string trans = bdf.transducer(0); //here we assumne that channel 0 is an EEG channel
                for (int i = 0; i < bdf.NumberOfChannels - 1; i++) //exclude Status channel
                    if (bdf.transducer(i) == trans) EEGChannels.Add(i);

                Window1 w = new Window1(this); //open channel selection and file approval window
                r = (bool)w.ShowDialog();

            } while (r == false);

            InitializeComponent();

            Log.writeToLog("Starting EEGArtifactEditor " + Assembly.GetExecutingAssembly().GetName().Version.ToString() +
                " on dataset " + headerFileName);
            ViewerGrid.Width = BDFLength;

            try
            {
                //process Events in current dataset; we have to do this now in case this is an update situation, but don't have to when we finish
                Event.EventFactory.Instance(header.Events); // set up the factory, based on this Event dictionary
                //and read them in
                EventFileReader efr = new EventFileReader(
                    new FileStream(System.IO.Path.Combine(directory, header.EventFile),
                        FileMode.Open, FileAccess.Read)); // open Event file

                foreach (InputEvent ie in efr)// read in all Events into list
                    events.Add(new OutputEvent(ie));
                efr.Close(); //now events is list of Events in the dataset

                //now set zeroTime for this BDF file, after finding an appropriate (non-"naked") Event
                bool ok = false;
                foreach (OutputEvent ev in events)
                    if (header.Events[ev.Name].IsCovered)
                    {
                        bdf.setZeroTime(ev);
                        ok = true;
                        break;
                    }
                if (!ok)
                {
                    ErrorWindow ew = new ErrorWindow();
                    ew.Message = "Unable to find a covered Event in this dataset on which to synchronize clocks. Exiting.";
                    ew.ShowDialog();
                    Log.writeToLog("Unable to synchronize clocks.");
                    this.Close();
                }

                if (updateFlag) //re-editing this dataset for artifacts
                {
                    Event.EventFactory.Instance(header.Events); // set up the factory, based on this Event dictionary
                    //and read them in
                    OutputEvent ev;
                    int i = 0;
                    double left;
                    while (i < events.Count)
                    {
                        ev = events[i];
                        if (ev.Name == "**ArtifactBegin")
                        {
                            left = bdf.timeFromBeginningOfFileTo(ev);
                            events.Remove(ev);
                            while (i < events.Count)
                            {
                                ev = events[i];
                                if (ev.Name == "**ArtifactEnd")
                                {
                                    MarkerCanvas.createMarkRegion(left, bdf.timeFromBeginningOfFileTo(ev));
                                    events.Remove(ev);
                                    break;
                                }
                                if (ev.Name == "**ArtifactBegin")
                                    throw (new Exception("Unmatched artifact Event in Event file " +
                                        System.IO.Path.Combine(directory, header.EventFile)));
                                i++;
                            }
                        }
                        else
                            i++;
                    }
                }

                //initialize the individual channel canvases

                foreach (int chan in selectedEEGChannels)
                {
                    ChannelCanvas cc = new ChannelCanvas(this, chan);
                    currentChannelList.Add(cc);
                    ViewerCanvas.Children.Add(cc);
                    ViewerCanvas.Children.Add(cc.offScaleRegions);
                }


                Title = headerFileName; //set window title
                BDFFileInfo.Content = bdf.ToString();
                HDRFileInfo.Content = header.ToString();

                ElectrodeInputFileStream eif = new ElectrodeInputFileStream(
                    new FileStream(System.IO.Path.Combine(directory, header.ElectrodeFile),
                        FileMode.Open, FileAccess.Read)); //open Electrode file
                electrodes = eif.etrPositions;

                //initialize vertical gridline array; never more than 18
                for (int i = 0; i < 18; i++)
                {
                    Line l = new Line();
                    Grid.SetRow(l, 0);
                    Grid.SetColumn(l, 0);
                    l.Y1 = 0D;
                    l.HorizontalAlignment = HorizontalAlignment.Left;
                    l.VerticalAlignment = VerticalAlignment.Stretch;
                    l.IsHitTestVisible = false;
                    l.Stroke = Brushes.LightBlue;
                    l.Visibility = Visibility.Hidden;
                    Panel.SetZIndex(l, int.MaxValue);
                    VerticalGrid.Children.Add(l);
                    gridlines[i] = l;
                }

                //Initialize timer
                timer.AutoReset = true;
                timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);

                //Initialize channel information popup
                Color c1 = Color.FromArgb(0xFF, 0xF8, 0xF8, 0xF8);
                Color c2 = Color.FromArgb(0xFF, 0xC8, 0xC8, 0xC8);
                popupTB.Background = new LinearGradientBrush(c1, c2, 45D);
                popupTB.Foreground = Brushes.Black;
                popupTB.Padding = new Thickness(4D);
                Border b = new Border();
                b.BorderThickness = new Thickness(1);
                b.CornerRadius = new CornerRadius(4);
                b.BorderBrush = Brushes.Tomato;
                b.Margin = new Thickness(0, 0, 24, 24); //allows drop shadow to show up
                b.Effect = new DropShadowEffect();
                b.Child = popupTB;
                channelPopup.Placement = PlacementMode.MousePoint;
                channelPopup.AllowsTransparency = true;
                channelPopup.Child = b;

                //Initialize FOV slider
                FOV.Maximum = Math.Log10(BDFLength);
                FOV.Value = 1D;
                FOVMax.Text = BDFLength.ToString("0");

                //Note file always uses the "main" orginal dataset name, which should be the BDFFile name; this keeps notes from all levels of
                //processing in the same place
                noteFilePath = System.IO.Path.Combine(directory, System.IO.Path.GetFileNameWithoutExtension(header.BDFFile) + ".notes.txt");
            }
            catch (Exception ex)
            {
                ErrorWindow ew = new ErrorWindow();
                ew.Message = "Error in EEGArtifactEditor initialization" + ex.Message;
                ew.ShowDialog();
                this.Close(); //exit
            }

            //from here on the program is GUI-event driven
        }
        public Window2()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Open Header file ...";
            dlg.DefaultExt = ".hdr"; // Default file extension
            dlg.Filter = "HDR Files (.hdr)|*.hdr"; // Filter files by extension
            dlg.InitialDirectory = Properties.Settings.Default.LastDataset;
            bool result = dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK;
            if (!result) Environment.Exit(0);

            headerFileName = System.IO.Path.GetFileNameWithoutExtension(dlg.FileName);
            directory = System.IO.Path.GetDirectoryName(dlg.FileName);
            Properties.Settings.Default.LastDataset = directory;

            CCIUtilities.Log.writeToLog("Starting ASCtoFMConverter " + CCIUtilities.Utilities.getVersionNumber());

            head = (new HeaderFileReader(dlg.OpenFile())).read();
            ED = head.Events;

            bdf = new BDFEDFFileReader(
                new FileStream(System.IO.Path.Combine(directory, head.BDFFile),
                    FileMode.Open, FileAccess.Read));
            samplingRate = (int)((double)bdf.NSamp / bdf.RecordDurationDouble);

            OpenPCommand.InputGestures.Add(
                new KeyGesture(Key.O, ModifierKeys.Control | ModifierKeys.Shift, "Ctrl+Shift+O"));
            SavePCommand.InputGestures.Add(
                new KeyGesture(Key.S, ModifierKeys.Control, "Crtl+S"));
            ProcessCommand.InputGestures.Add(
                new KeyGesture(Key.P, ModifierKeys.Control, "Crtl+P"));
            ExitCommand.InputGestures.Add(new KeyGesture(Key.Q, ModifierKeys.Control, "Crtl+Q"));

            InitializeComponent();

            //***** Set up menu commands and short cuts

            CommandBinding cbOpenP = new CommandBinding(OpenPCommand, cbOpen_Execute, cbOpen_CanExecute);
            this.CommandBindings.Add(cbOpenP);

            CommandBinding cbSaveP = new CommandBinding(SavePCommand, cbSave_Execute, validParams_CanExecute);
            this.CommandBindings.Add(cbSaveP);

            CommandBinding cbProcess = new CommandBinding(ProcessCommand, ConvertFM_Click, validParams_CanExecute);
            this.CommandBindings.Add(cbProcess);

            CommandBinding cbExit = new CommandBinding(ExitCommand, Done_Click, cbExit_CanExecute);
            this.CommandBindings.Add(cbExit);

            this.MinHeight = SystemInformation.WorkingArea.Height - 240;
            this.EpisodeEntries.Items.Add(new EpisodeDescriptionEntry(head, this)); //include initial episode description

            this.Title = "Convert " + headerFileName;
            this.TitleLine.Text = head.Title + " - " + head.Date + " " + head.Time + " S=" + head.Subject.ToString("0000");

            if (head.GroupVars != null)
            {
                System.Windows.Data.Binding GVBinding = new System.Windows.Data.Binding();
                GVBinding.Source = this;
                GVBinding.NotifyOnSourceUpdated = true;
                GVBinding.Path = new PropertyPath("GVList");
                GVBinding.Mode = BindingMode.OneWay;
                listView2.SetBinding(System.Windows.Controls.ListView.ItemsSourceProperty, GVBinding);
                GVList = head.GroupVars.Values.ToList<GVEntry>();
            }
            else
                GVList = new List<GVEntry>(0);

            this.Activate();
        }
Exemple #7
0
        static void Main(string[] args)
        {
            List<eventTime> eventList = new List<eventTime>();
            Console.Write("Degree of fit desired: ");
            int degree = Convert.ToInt32(Console.ReadLine());

            BDFEDFFileReader bdf = new BDFEDFFileReader(new FileStream(@"C:\\Users\Jim\Desktop\PK detector data\S9998-AP-20150210-1205_PKcubes.bdf", FileMode.Open, FileAccess.Read));
            Console.WriteLine("Opened BDF file");
            double[] d = bdf.readAllChannelData(5);
            int N = d.Length;
            double n = (double)N;

            Console.WriteLine(d[0].ToString() + " " + d[1].ToString() + " " + d[100].ToString());

            removeTrend(d, degree);
            Console.WriteLine(d[0].ToString() + " " + d[1].ToString() + " " + d[100].ToString());

            double[] V = new double[filterN];
            double c1 = 12D / (double)(filterN * (filterN - 1) * (filterN + 1));
            double offset = ((double)filterN - 1D) / 2D;
            for (int i = 0; i < filterN; i++) V[i] = c1 * ((double)i - offset);
            List<double> filtered = new List<double>(64);
            byte[] marker = new byte[N];
            bool inEvent = false;
            int eventLength = 0;
            double sign = 1D;
            for (int i = 0; i < N; i++)
            {
                double s = 0;
                for (int j = 0; j < filterN; j++)
                {
                    int index = i + j - filterN / 2;
                    if (index < 0) //handle start-up
                        s += V[j] * d[0]; //repeat first value to its left
                    else if (index >= N) //handle end
                        s += V[j] * d[N - 1]; //repeat last value to its right
                    else //usual case
                        s += V[j] * d[index];
                }
                if (Math.Abs(s) > threshold) //above threshold?
                {
                    if (!inEvent) //found beginning of new event
                    {
                        sign = s > 0D ? 1D : -1D;
                        eventLength = 0;
                        inEvent = true;
                    }
                    filtered.Add(s - sign * threshold);
                    eventLength++;
                }
                else //below threshold
                    if (inEvent) //are we just exiting an event?
                    {
                        if (eventLength > minimumLength) //event counts only if longer than minimum length
                        {
                            eventTime e = new eventTime();
                            e.time = i - eventLength;
                            e.length = eventLength;
                            e.sign = sign;
                            e.filteredSignal = filtered;
                            filtered = new List<double>(64); //need new filtered array
                            eventList.Add(e);
                        }
                        else
                            filtered.Clear();
                        inEvent = false;
                    }
            }
            int dataLength;
            double t;
            eventTime et0;
            eventTime et1;
            double t0 = (double)filterN / (2D * SR);
            for (int i = 0; i < eventList.Count - 1; i++)
            {
                et0 = eventList[i];
                et1 = eventList[i + 1];
                dataLength = Math.Min(et1.time - et0.time, 16000);
                double max = double.MinValue;
                for (int p = et0.time; p < et0.time + et0.length; p++) max = Math.Max(max, Math.Abs(d[p]));
                et0.A = et0.sign * max; //correct sign of displacement; could be max sign*Abs(displacement)
                et0.C = d[et0.time]; //estimate of initial offset
                et0.B = et0.C; //current actual "baseline"
                et0.a = 4D; //typical alpha
                et0.b = 0.04; //typical beta
                t = t0; //half filterN / SR
                if (et0.foundFit = fitSignal(d, et0.time, dataLength, ref et0.A, ref et0.B, ref et0.C, ref et0.a, ref et0.b, ref t))
                    et0.time += (int)(t * SR);
                Console.WriteLine();
                Console.WriteLine(et0.time.ToString("0") + " (" + LM.Result.ToString() + ", " + LM.Iterations.ToString("0") +
                    ", " + LM.ChiSquare.ToString("0.0") + ", " + LM.normalizedStandardErrorOfFit.ToString("0.00") + "): ");
                Console.WriteLine(et0.A.ToString("0.0") + " " + et0.B.ToString("0.0") + " " + et0.C.ToString("0.0") +
                    " " + et0.a.ToString("0.000") + " " + et0.b.ToString("0.00000") + " " + t.ToString("0.000") + " ");
                NVector Sp = LM.parameterStandardError;
                Console.WriteLine(Sp[0].ToString("0.00") + " " + Sp[1].ToString("0.00") + " " + Sp[2].ToString("0.00") +
                    " " + Sp[3].ToString("0.0000") + " " + Sp[4].ToString("0.000000") + " " + Sp[5].ToString("0.0000") + " ");
            }
            et0 = eventList[eventList.Count - 1];
            dataLength = Math.Min(N - et0.time, 16000);
            et0.A = et0.sign * 5000D; //correct sign of displacement; could be max sign*Abs(displacement)
            et0.C = d[et0.time]; //estimate of initial offset
            et0.B = et0.C;
            et0.a = 4D;
            et0.b = 0.05;
            t = 0.25;
            if (et0.foundFit = fitSignal(d, et0.time, dataLength, ref et0.A, ref et0.B, ref et0.C, ref et0.a, ref et0.b, ref t))
                et0.time += (int)(t * SR);
            Console.WriteLine(et0.time.ToString("0") + " (" + LM.Result.ToString() + ", " + LM.Iterations.ToString("0") +
                ", " + LM.ChiSquare.ToString("0.0") + "): " + et0.A.ToString("0.0") + " " + et0.B.ToString("0.0") + " " + et0.C.ToString("0.0") +
                " " + et0.a.ToString("0.000") + " " + et0.b.ToString("0.00000") + " " + t.ToString("0.000") + " ");

            Console.WriteLine("Total events found = " + eventList.Count.ToString("0"));
            ConsoleKeyInfo cki = Console.ReadKey();
        }
        public MainWindow()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Open Header file ...";
            dlg.DefaultExt = ".hdr"; // Default file extension
            dlg.Filter = "HDR Files (.hdr)|*.hdr"; // Filter files by extension
            dlg.InitialDirectory = Properties.Settings.Default.LastDataset;
            DialogResult result = dlg.ShowDialog();
            if (result != System.Windows.Forms.DialogResult.OK) Environment.Exit(0);

            directory = System.IO.Path.GetDirectoryName(dlg.FileName);
            Properties.Settings.Default.LastDataset = directory;
            headerFileName = System.IO.Path.GetFileNameWithoutExtension(dlg.FileName);

            CCIUtilities.Log.writeToLog("Starting PKDetectorAnalyzer " + CCIUtilities.Utilities.getVersionNumber() +
                " on " + headerFileName);

            head = (new HeaderFileReader(dlg.OpenFile())).read();

            bdf = new BDFEDFFileReader(
                new FileStream(System.IO.Path.Combine(directory, head.BDFFile),
                    FileMode.Open, FileAccess.Read));
            for (int i = 0; i < bdf.NumberOfChannels; i++) //first see if this file has standard transducer labels
                if (bdf.transducer(i) == "Analog Input Box")
                    channels.Add(new channelOptions(i, bdf.channelLabel(i))); //if it does, use them as channel choices
            if (channels.Count == 0) //if it does not, then show all channels
                for (int i = 0; i < bdf.NumberOfChannels; i++)
                    channels.Add(new channelOptions(i, bdf.channelLabel(i)));
            AnalogChannelCount = channels.Count;

            OpenPCommand.InputGestures.Add(
                new KeyGesture(Key.O, ModifierKeys.Control | ModifierKeys.Shift, "Ctrl+Shift+O"));
            SavePCommand.InputGestures.Add(
                new KeyGesture(Key.S, ModifierKeys.Control, "Crtl+S"));
            ProcessCommand.InputGestures.Add(
                new KeyGesture(Key.P, ModifierKeys.Control, "Crtl+P"));
            ExitCommand.InputGestures.Add(new KeyGesture(Key.Q, ModifierKeys.Control, "Crtl+Q"));

            InitializeComponent();

            //***** Set up menu commands and short cuts

            CommandBinding cbOpenP = new CommandBinding(OpenPCommand, cbOpen_Execute, cbOpen_CanExecute);
            this.CommandBindings.Add(cbOpenP);

            CommandBinding cbSaveP = new CommandBinding(SavePCommand, cbSave_Execute, validParams_CanExecute);
            this.CommandBindings.Add(cbSaveP);

            CommandBinding cbProcess = new CommandBinding(ProcessCommand, ProcessChannels_Click, validParams_CanExecute);
            this.CommandBindings.Add(cbProcess);

            CommandBinding cbExit = new CommandBinding(ExitCommand, Quit_Click, cbExit_CanExecute);
            this.CommandBindings.Add(cbExit);

            //***** Set up defaults and other housekeeping

            Title = headerFileName;
            TitleLine.Text = directory + System.IO.Path.DirectorySeparatorChar + headerFileName;
            FNExtension.Text = "PKDetection";
            DataContext = this;

            ChannelItem ci = new ChannelItem(this);
            ChannelEntries.Items.Add(ci);
            ci.Channel.SelectedIndex = 0;
            Process.IsEnabled = true; //have to reenable here -- like checkError(); values are guarenteed valid however

            this.Activate();
        }