Esempio n. 1
0
        static void Main()
        {
            App app = new App();
#if !DEBUG
            Console.WriteLine("NOT in DEBUG mode");
            try
            {
                app.Run(new MainWindow());
            }

            catch (Exception e)
            {
                ErrorWindow ew = new ErrorWindow();
                if (e.StackTrace != null)
                    ew.Message = "In " + e.TargetSite + ": " + e.Message +
                        ";\r\n" + e.StackTrace;
                else
                    ew.Message = "In EEGArtifactEditor: " + e.Message;
                ew.ShowDialog();
            }
#else
            Console.WriteLine("In DEBUG mode");
            app.Run(new MainWindow());
#endif
        }
Esempio n. 2
0
 private void Create_Click(object sender, RoutedEventArgs e)
 {
     Create.Visibility = Visibility.Collapsed;
     Progress.Text = "0%";
     Progress.Visibility = Visibility.Visible;
     QuitButton.Visibility = Visibility.Collapsed;
     CancelButton.Visibility = Visibility.Visible;
     Log.writeToLog("Beginning data consolidation to: " + SYSTATFileName.Text);
     try
     {
         systat = new SYSTAT.SYSTATFileStream(SYSTATFileName.Text,
             ((bool)SYS.IsChecked) ? SYSTAT.SYSTATFileStream.SFileType.SYS : SYSTAT.SYSTATFileStream.SFileType.SYD);
         bw.RunWorkerAsync(this);
     }
     catch (Exception err)
     {
         ErrorWindow ew = new ErrorWindow();
         ew.Message = "***** ERROR ***** MainWindow: " + err.Message;
         ew.ShowDialog();
         if (systat != null) systat.CloseStream();
     }
 }
Esempio n. 3
0
 private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     if (e.Cancelled)
     {
         if (systat != null) systat.CloseStream();
         Log.writeToLog("***** Cancelled *****");
     }
     else
         if (e.Error != null)
         {
             string s = "***** ERROR ***** " + e.Error.Message;
             ErrorWindow ew = new ErrorWindow();
             ew.Message = s;
             ew.ShowDialog();
             if (systat != null) systat.CloseStream();
             Log.writeToLog(s);
         }
     Progress.Visibility = Visibility.Collapsed;
     Create.Visibility = Visibility.Visible;
     CancelButton.Visibility = Visibility.Collapsed;
     QuitButton.Visibility = Visibility.Visible;
 }
Esempio n. 4
0
        private void Create_Click(object sender, RoutedEventArgs e)
        {
            Create.Visibility = Visibility.Hidden;
            Log.writeToLog("Beginning data consolidation to: " + SYSTATFileName.Text);
            FMFileListItem fli;
            SYSTAT.SYSTATFileStream systat = null;
            try
            {
                systat = new SYSTAT.SYSTATFileStream(SYSTATFileName.Text,
                    ((bool)SYS.IsChecked) ? SYSTAT.SYSTATFileStream.SFileType.SYS : SYSTAT.SYSTATFileStream.SFileType.SYD);
                Log.writeToLog("Consolidating from files:");
                int fNum = 0;
                string s;
                foreach (FILMANFileRecord ffr in FILMANFileRecords)//First capture all the data variables to be created
                {
                    Log.writeToLog("     " + ffr.path);
                    systat.AddCommentLine(ffr.path); //FIRST comment line names file
                    for (int i = 0; i < 6; i++)
                        systat.AddCommentLine(ffr.stream.Description(i));
                    systat.AddCommentLine(new string('*', 72)); //LAST comment line to mark end
                    fli = ffr.FMFilePointSelector;
                    object[] GVcodes = new object[4] { fli.FileUID, ++fNum, 2, 0 }; //FfGg
                    // F is the FileUID
                    // G is the old GV number from FILMAN
                    // g is the renumbering of GVs
                    foreach (GroupVar gv in fli.GroupVars) //first the GVs
                    {
                        GVcodes[2] = (int)GVcodes[2] + 1;
                        if (gv.IsSel)
                        {
                            GVcodes[3] = (int)GVcodes[3] + 1;
                            s = FMFileListItem.GVNameParser.Encode(GVcodes, gv.namingConvention);
                            SYSTAT.SYSTATFileStream.Variable v;
                            v = new SYSTAT.SYSTATFileStream.Variable(s,
                                gv.Format == NSEnum.Number ? SYSTAT.SYSTATFileStream.SVarType.Number : SYSTAT.SYSTATFileStream.SVarType.String);
                            systat.AddVariable(v);
                        }
                    }
                    object[] Pcodes = new object[7] { fli.FileUID, fNum, 0, 0, 0, 0, "" }; //FfCcPpN
                    // F is the FileUID
                    // f is the index of file (1-based)
                    // C is the original channel number from FILMAN (1-based)
                    // c is the renumbering of channels (1-based)
                    // P is the original point number from FILMAN (1-based)
                    // p is the renumbering of points (1-based)
                    // N is the channel name
                    foreach (PointGroup pg in fli.PointGroups) //then the data points
                    {
                        foreach (int channel in pg.selectedChannels)
                        {
                            Pcodes[2] = channel + 1;
                            s = ffr.stream.ChannelNames(channel);
                            Pcodes[6] = s.Substring(0, Math.Min(s.Length, 11)).Trim().Replace(' ', '_');
                            Pcodes[3] = (int)Pcodes[3] + 1;
                            foreach (int point in pg.selectedPoints)
                            {
                                Pcodes[4] = point + 1;
                                Pcodes[5] = (int)Pcodes[5] + 1;
                                s = FMFileListItem.PointNameParser.Encode(Pcodes, pg.namingConvention);
                                SYSTAT.SYSTATFileStream.Variable v = new SYSTAT.SYSTATFileStream.Variable(s.Substring(0, Math.Min(12, s.Length)));
                                systat.AddVariable(v);
                            }
                        }
                    }
                }
                foreach (CSVFileRecord cfr in CSVFileRecords) //now get CSV variables
                {
                    Log.writeToLog("     " + cfr.path);
                    foreach (CSV.Variable v in cfr.stream.CSVVariables)
                    {
                        if (v.IsSel)
                        {
                            SYSTAT.SYSTATFileStream.Variable var;
                            var = new SYSTAT.SYSTATFileStream.Variable(v.Name, v.Type);
                            systat.AddVariable(var);
                        }
                    }
                } //end data variable capture; now we can write the SYSTAT header
                systat.WriteHeader();

                FILMANRecord FMRec;
                int numberOfRecords;
                if (FILMANFileRecords.Count > 0)
                    numberOfRecords = FILMANFileRecords[0].stream.NRecordSets;
                else
                    numberOfRecords = CSVFileRecords[0].stream.NumberOfRecords;
                Log.writeToLog("Creating " + numberOfRecords.ToString("0") + " records of " + TotalDataPoints().ToString("0") + " points");
                for (int recordNum = 0; recordNum < numberOfRecords; recordNum++)
                {
                    int pointNumber = 0;
                    foreach (FILMANFileRecord ffr in FILMANFileRecords)
                    {
                        fli = ffr.FMFilePointSelector;
                        FMRec = ffr.stream.read(recordNum, 0); //read first channel to get GV values
                        foreach (GroupVar gv in fli.GroupVars)
                        {
                            if (gv.IsSel)
                            {
                                int GVValue = FMRec.GV[gv.Index];
                                if (gv.GVE == null || gv.Format == NSEnum.Number || gv.Format == NSEnum.String)
                                    systat.SetVariableValue(pointNumber++, GVValue);
                                else //GVE != null & Format == NSEnum.MappingString
                                    systat.SetVariableValue(pointNumber++, gv.GVE.ConvertGVValueIntegerToString(GVValue));
                            }
                        }
                        foreach (PointGroup pg in fli.PointGroups)
                        {
                            foreach (int chan in pg.selectedChannels)
                            {
                                FMRec = ffr.stream.read(recordNum, chan);
                                foreach (int pt in pg.selectedPoints)
                                {
                                    systat.SetVariableValue(pointNumber++, FMRec[pt]);
                                }
                            }
                        }
                    }
                    foreach (CSVFileRecord cfr in CSVFileRecords) //now get CSV variables
                    {
                        cfr.stream.Read();
                        foreach (CSV.Variable v in cfr.stream.CSVVariables)
                            if (v.IsSel)
                                systat.SetVariableValue(pointNumber++, v.Value);
                    }
                    systat.WriteDataRecord();
                }

                systat.CloseStream();
                Log.writeToLog("Finished consolidation");
            }
            catch (Exception err)
            {
                ErrorWindow ew = new ErrorWindow();
                ew.Message = "***** ERROR ***** Source: " + err.Source + " Message: " + err.Message;
                ew.ShowDialog();
                if (systat != null) systat.CloseStream();
            }
            Create.Visibility = Visibility.Visible;
        }
Esempio n. 5
0
        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
        }
Esempio n. 6
0
        public MainWindow()
        {
            Log.writeToLog("Starting DatasetReviewer " + Assembly.GetExecutingAssembly().GetName().Version.ToString());

            do
            {
                bool r;
                do
                {
                    System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
                    dlg.Title = "Open Header file to be displayed...";
                    dlg.DefaultExt = ".hdr"; // Default file extension
                    dlg.Filter = "HDR Files (.hdr)|*.hdr"; // Filter files by extension
                    bool result = dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK;
                    if (!result) 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);
                    try
                    {
                        head = (new HeaderFileReader(dlg.OpenFile())).read();
                    }
                    catch (Exception e)
                    {
                        r = false; //loop around again
                        ErrorWindow ew = new ErrorWindow();
                        ew.Message = "Error reading Header file: " + e.Message;
                        continue;
                    }
                    ED = head.Events;

                    try
                    {
                        bdf = new BDFEDFFileStream.BDFEDFFileReader(
                            new FileStream(System.IO.Path.Combine(directory, head.BDFFile),
                                FileMode.Open, FileAccess.Read));
                    }
                    catch (Exception e)
                    {
                        r = false; //loop around again
                        ErrorWindow ew = new ErrorWindow();
                        ew.Message = "Error reading BDF file header: " + e.Message;
                        ew.ShowDialog();
                        continue;
                    }
                    BDFLength = (double)bdf.NumberOfRecords * bdf.RecordDurationDouble;

                    Window1 w = new Window1(this);
                    r = (bool)w.ShowDialog();

                } while (r == false);

                Log.writeToLog("     on dataset " + headerFileName);

                if (includeANAs)
                {
                    foreach (EventDictionaryEntry ede in ED.Values) // add ANA channels that are referenced by extrinsic Events
                    {
                        if (ede.IsCovered && ede.IsExtrinsic)
                        {
                            int chan = bdf.ChannelNumberFromLabel(ede.channelName);
                            if (!channelList.Contains(chan)) //don't enter duplicate
                                channelList.Add(chan);
                        }
                    }
                }
            } while (channelList.Count == 0);

            InitializeComponent();

            //initialize the individual channel graphs
            foreach (int i in channelList)
            {
                ChannelGraph pg = new ChannelGraph(this, i);
                GraphCanvas.Children.Add(pg);
            }

            Title = headerFileName; //set window title
            BDFFileInfo.Content = bdf.ToString();
            HDRFileInfo.Content = head.ToString();
            Event.EventFactory.Instance(head.Events); // set up the factory
            EventFileReader efr = null;
            try
            {
                    efr = new EventFileReader(
                        new FileStream(System.IO.Path.Combine(directory, head.EventFile),
                            FileMode.Open, FileAccess.Read)); // open Event file
                bool z = false;
                foreach (Event.InputEvent ie in efr)// read in all Events into dictionary
                {
                    if (ie.IsNaked)
                        events.Add(ie);
                    else if (events.Count(e => e.GC == ie.GC) == 0) //quietly skip duplicates
                    {
                        if (!z) //use first found covered Event to synchronize clocks
                            z = bdf.setZeroTime(ie);
                        events.Add(ie);
                    }
                }
                efr.Close(); //now events is Dictionary of Events in the dataset; lookup by GC
            }
            catch (Exception e)
            {
                ErrorWindow ew = new ErrorWindow();
                ew.Message = "Error reading Event file : " + e.Message + ". Exiting DatasetReviewer.";
                ew.ShowDialog();
                Log.writeToLog(Environment.NewLine +  e.StackTrace);
                Environment.Exit(0);
            }

            try
            {
                ElectrodeInputFileStream eif = new ElectrodeInputFileStream(
                    new FileStream(System.IO.Path.Combine(directory, head.ElectrodeFile),
                        FileMode.Open, FileAccess.Read)); //open Electrode file
                electrodes = eif.etrPositions; //read 'em in
            }
            catch (Exception e)
            {
                ErrorWindow ew = new ErrorWindow();
                ew.Message = "Error reading Electrode file : " + e.Message + ". Exitting DatasetReviewer.";
                ew.ShowDialog();
                Log.writeToLog(Environment.NewLine + e.StackTrace);
                Environment.Exit(0);
            }

            EventMarkers.Width = BDFLength;
            eventTB = new TextBlock(new Run("Events"));
            Canvas.SetBottom(eventTB, ScrollBarSize + 13D);

            //initialize gridline array
            for (int i = 0; i < 18; i++)
            {
                Line l = new Line();
                Grid.SetRow(l, 0);
                Grid.SetColumn(l, 0);
                Grid.SetColumnSpan(l, 2);
                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.MinValue);
                MainFrame.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 Event information popup
            eventPopupTB.Background = new LinearGradientBrush(c1, c2, 45D);
            eventPopupTB.Foreground = Brushes.Black;
            eventPopupTB.Padding = new Thickness(4D);
            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 = eventPopupTB;
            eventPopup.Placement = PlacementMode.MousePoint;
            eventPopup.AllowsTransparency = true;
            eventPopup.Child = b;

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

            //Initialize Event selector
            bool first = true;
            foreach (EventDictionaryEntry e in head.Events.Values)
            {
                MenuItem mi = (MenuItem)EventSelector.FindResource("EventMenuItem");
                mi.Header = e.Name;
                if (first)
                {
                    mi.IsChecked = true;
                    first = false;
                }
                EventSelector.Items.Add(mi);
            }

            noteFilePath = System.IO.Path.Combine(directory,System.IO.Path.ChangeExtension(head.BDFFile,".notes.txt"));
            //from here on the program is GUI-event driven
        }
Esempio n. 7
0
        private void PerformOpenPFile()
        {
            string s;
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Open parameter file ...";
            dlg.DefaultExt = ".par"; // Default file extension
            dlg.Filter = "PAR Files (.par)|*.par"; // Filter files by extension
            dlg.InitialDirectory = Properties.Settings.Default.LastParFile;

            bool result = dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK;
            if (!result) return;

            Properties.Settings.Default.LastParFile = System.IO.Path.GetDirectoryName(dlg.FileName);

            XmlReaderSettings xrs = new XmlReaderSettings();
            xrs.CloseInput = true;
            xrs.IgnoreWhitespace = true;
            XmlReader xml = XmlReader.Create(dlg.OpenFile(), xrs);
            try
            {
                if(!xml.ReadToFollowing("ASCtoFMParameters")) throw new XmlException("No ASCtoFMParameters element found");
                s = xml["ClockSync"];
                if (s == "First covered Event")
                    SyncToFirst.IsChecked = true;
                else
                    if (s == "None")
                        NoSyncToStatus.IsChecked = true;
                    else
                        SyncToMiddle.IsChecked = true;
                xml.ReadStartElement("ASCtoFMParameters");

                xml.ReadStartElement("EpisodeDescriptions");
                while (EpisodeEntries.Items.Count > 0) EpisodeEntries.Items.RemoveAt(0); //remove old entries
                while (xml.Name == "EpisodeDescription")
                {
                    EpisodeDescriptionEntry ede = new EpisodeDescriptionEntry(head, this);
                    if (ede.ReadNewSettings(xml))
                        EpisodeEntries.Items.Add(ede);
                }
                xml.ReadEndElement(/* EpisodeDescriptions */);

                listView2.SelectedItem = null;
                xml.ReadStartElement("GroupVariables");
                while (xml.Name == "GV")
                {
                    s = xml.ReadElementContentAsString();
                    for (int i = 0; i < listView2.Items.Count; i++)
                    {
                        if (((GVEntry)listView2.Items[i]).Name == s)
                        {
                            listView2.SelectedItems.Add(listView2.Items[i]);
                            break;
                        }
                    } //silently skip GVs not in current dataset
                }
                xml.ReadEndElement(/* GroupVariables */);

                SelChan.Text = xml.ReadElementString("Channels");

                s = xml["Remove"];
                if (s != null) //may not exist if using Radin reference
                    if (s == "Offsets") removeOffsets.IsChecked = true;
                    else
                        if (s == "Trends") removeTrends.IsChecked = true;
                        else
                            noneOffsets.IsChecked = true;
                xml.ReadStartElement("Samples");
                Decimation.Text = xml.ReadElementString("Decimation");
                RecLength.Text = xml.ReadElementString("RecordLength");
                if (xml.Name == "RadinReference")
                {
                    Radin.IsChecked = true;
                    xml.ReadStartElement();
                    RadinLow.Text = xml.ReadElementString("From");
                    RadinHigh.Text = xml.ReadElementString("To");
                    xml.ReadEndElement(/* RadinReference */);
                }
                else
                    Radin.IsChecked = false;
                xml.ReadEndElement(/* Samples */);

                s = xml["Type"]; //Type must be present
                if (s == "SelectedChannels") radioButton2.IsChecked = true;
                else
                    if (s == "Expression") radioButton4.IsChecked = true;
                    else
                        radioButton3.IsChecked = true;
                string v = xml.ReadElementString("Reference");
                if (s != "None")
                    if (s == "Expression") RefChanExpression.Text = v;
                    else RefChan.Text = v; //SelectedChannels case

                xml.ReadEndElement(/* ASCtoFMParameters */);
            }
            catch (XmlException e)
            {
                ErrorWindow er = new ErrorWindow();
                er.Message = "Error in parameter file at line number " + e.LineNumber.ToString("0") + ". Unable to continue.";
                er.ShowDialog();
            }
            xml.Close();
            RemoveSpec.IsEnabled = EpisodeEntries.Items.Count > 1;
        }
Esempio n. 8
0
        public MainWindow()
        {
            bool standAlone = Environment.GetCommandLineArgs().Length < 3;
            Window1 w;
            string templateFileName;
            string ETRFileName;
            bool useMonitor;
            if (standAlone)
            {
                w = new Window1();
                try
                {
                    foreach (string s in Directory.EnumerateFiles(networkFolder + System.IO.Path.DirectorySeparatorChar + templatesFolder))
                    {
                        string f = System.IO.Path.GetFileNameWithoutExtension(s);
                        w.Templates.Items.Add(f);
                    }
                }
                catch (Exception e)
                {
                    CCIUtilities.ErrorWindow ew = new CCIUtilities.ErrorWindow();
                    ew.Message = "Unable to access Templates folder; message = " + e.Message;
                    ew.ShowDialog();
                    Environment.Exit(0);
                }
                w.Templates.SelectedIndex = 0;
                w.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                if (!(bool)w.ShowDialog()) Environment.Exit(0);
                mode = w._mode;
                if (mode == 0) samples = w._sampCount1;
                else if (mode == 1) samples = w._sampCount2;
                else if (mode == 3) threshold = w._SDThresh;
                voice = (bool)w.Voice.IsChecked;
                hemisphere = w.Hemisphere.SelectedIndex;
                templateFileName = (string)w.Templates.SelectedValue;
                ETRFileName = System.IO.Path.GetFileNameWithoutExtension(w._etrFileName);
                useMonitor = (bool)w.Monitor.IsChecked;
            }
            else
            {
                mode = 0; //always single click
                samples = 1; //single sample only
                voice = true;
                hemisphere = 0; //X+
                templateFileName = Environment.GetCommandLineArgs()[1];
                ETRFileName = networkFolder + System.IO.Path.DirectorySeparatorChar + Environment.GetCommandLineArgs()[2];
                useMonitor = true;
            }

            //Read in electrode array template
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreWhitespace = true;
            settings.IgnoreComments = true;
            settings.IgnoreProcessingInstructions = true;
            settings.CloseInput = true;
            XmlReader templateReader = XmlReader.Create(networkFolder + System.IO.Path.DirectorySeparatorChar +
                templatesFolder + System.IO.Path.DirectorySeparatorChar + templateFileName + ".xml", settings); //templates are always on network drive
            templateReader.MoveToContent();
            templateReader.MoveToAttribute("N");
            numberOfElectrodes = templateReader.ReadContentAsInt(); //number of items
            templateList = new List<electrodeTemplateListElement>(numberOfElectrodes);
            templateReader.ReadStartElement("ElectrodeNames");
            for (int i = 0; i < numberOfElectrodes; i++)
            {
                templateReader.ReadStartElement("Electrode");
                electrodeTemplateListElement ele = new electrodeTemplateListElement();
                ele.Name = templateReader.ReadElementContentAsString("Print","");
                if (templateReader.Name == "Speak")
                {
                    ele.speakType = templateReader["Type"];
                    if (ele.speakType == "String")
                        ele.speakString = templateReader.ReadElementContentAsString("Speak", ""); //read string to speak
                    else
                    {
                        templateReader.ReadStartElement("Speak");
                        while (templateReader.Name != "Speak")
                            ele.speakString += templateReader.ReadOuterXml(); //read SSML string to speak
                        templateReader.ReadEndElement(/*Speak*/);
                    }
                }
                else
                {
                    ele.speakType = "None";
                    ele.speakString = null;
                }
                templateList.Add(ele);
                templateReader.ReadEndElement(/*Electrode*/);
            }
            templateReader.ReadEndElement(/*ElectrodeNames*/);
            templateReader.Close();

            //Open electrode position file
            efs = new ElectrodeOutputFileStream(
                new FileStream(ETRFileName + "." + numberOfElectrodes.ToString("000") + ".etr", FileMode.Create, FileAccess.Write),
                typeof(XYZRecord));
            electrodeLocations = new List<XYZRecord>(numberOfElectrodes); //set up temporary location list, so changes can be made

            projection = new Projection(eyeDistance);

            InitializeComponent();

            this.MinWidth = (double)SystemInformation.WorkingArea.Width * 96D / screenDPI;
            this.MinHeight = (double)SystemInformation.WorkingArea.Height * 96D / screenDPI;

            //Initialize Polhemus into standard state
            try
            {
                PolhemusStream ps = new PolhemusStream();
                p = new PolhemusController(ps);
                p.InitializeSystem();
                p.SetEchoMode(PolhemusController.EchoMode.On); //Echo on
                p.OutputFormat(PolhemusController.Format.Binary); //Binary output
                int v = hemisphere % 2 == 1 ? -1 : 1; //set correct hemisphere of operation
                if (hemisphere < 2)
                    p.HemisphereOfOperation(null, v, 0, 0);
                else if (hemisphere < 4)
                    p.HemisphereOfOperation(null, 0, v, 0);
                else
                    p.HemisphereOfOperation(null, 0, 0, v);
                p.SetUnits(PolhemusController.Units.Metric); //Metric measurements
                Type[] df1 = { typeof(CartesianCoordinates) }; //set up cartesian coordinate output only for stylus
                p.OutputDataList(1, df1);
                Type[] df2 = { typeof(CartesianCoordinates), typeof(DirectionCosineMatrix) }; //coordinates and direction cosines for reference sensor
                p.OutputDataList(2, df2);
                StylusAcquisition.Monitor c = null;
                if (useMonitor)
                    c = Monitor;
                w = null; //free resources, if any
                if (mode == 0)
                {
                    StylusAcquisition.SingleShot sm = SinglePoint;
                    sa = new StylusAcquisition(p, sm, c);
                }
                else
                {
                    StylusAcquisition.Continuous sm = ContinuousPoints;
                    sa = new StylusAcquisition(p, sm, c);
                }
                AcquisitionFinished += new PointAcquisitionFinishedEventHandler(AcquisitionLoop);
                electrodeNumber = -3; //Fiducial points are first
                if(!standAlone)
                {
                    Window2 w2 = new Window2();
                    w2.ElecTemplate.Text = Environment.GetCommandLineArgs()[1];
                    w2.Output.Text = Environment.GetCommandLineArgs()[2];
                    if (!(bool)w2.ShowDialog()) Environment.Exit(0);
                }
                AcquisitionLoop(sa, null); //Prime the pump!
            }
            catch (Exception e)
            {
                ErrorWindow ew = new ErrorWindow();
                ew.Message = "Error in Polhemus initialization: " + e.Message;
                ew.ShowDialog();
                Environment.Exit(1);
            }
        }