Beispiel #1
0
        internal static void BuildFile(object sender, DoWorkEventArgs e)
        {
            Parameters parameters = (Parameters)e.Argument;

            DirectoryInfo di = new DirectoryInfo(parameters.directoryPath);
            try
            {
                if (!di.Exists) di.Create();
            }
            catch (Exception io)
            {
                throw new Exception("Directory creation failed: " + io.ToString());
            }

            parameters.fileName = di.FullName + Path.DirectorySeparatorChar + parameters.fileName;

            /* ***** Create new BDF/EDF file ***** */
            BDFEDFFileWriter file = new BDFEDFFileWriter(
                File.Open(parameters.fileName + (parameters.BDFFormat ? ".bdf" : ".edf"), FileMode.Create, FileAccess.ReadWrite),
                parameters.nChan + 1, // add one to include Status
                parameters.recordDuration,
                parameters.samplingRate,
                parameters.BDFFormat);

            file.LocalRecordingId = parameters.LocalRecordingId;
            file.LocalSubjectId = parameters.LocalSubjectId;
            for (int ichan = 0; ichan < parameters.nChan; ichan++)
            {
                file.channelLabel(ichan, parameters.ChannelLabelPrefix + " " + (ichan + 1).ToString("G"));
                file.transducer(ichan, parameters.TransducerString);
                file.dimension(ichan, parameters.PhysicalDimensionString);
                file.pMin(ichan, (int)Math.Ceiling(parameters.pMin));
                file.pMax(ichan, (int)Math.Ceiling(parameters.pMax));
                file.dMin(ichan, parameters.dMin);
                file.dMax(ichan, parameters.dMax);
                file.prefilter(ichan, parameters.PrefilterString);
            }
            file.channelLabel(parameters.nChan, "Status");
            file.transducer(parameters.nChan, "None");
            file.dimension(parameters.nChan, "None");
            file.pMin(parameters.nChan, -Math.Pow(2D, 23D));
            file.pMax(parameters.nChan, Math.Pow(2D, 23D) - 1);
            file.dMin(parameters.nChan, (int)file.pMin(parameters.nChan));
            file.dMax(parameters.nChan, (int)file.pMax(parameters.nChan));
            file.prefilter(parameters.nChan, "None");

            /* ***** Create Electrode position file ***** */
            double[] phi;
            double[] theta;
            setElectrodeLocations(parameters.nChan, out phi, out theta); // assign locations
            ElectrodeFileStream.ElectrodeOutputFileStream efs = new ElectrodeFileStream.ElectrodeOutputFileStream(
                File.Open(parameters.fileName + ".etr", FileMode.Create, FileAccess.Write),typeof(PhiThetaRecord));
            for (int i = 0; i < parameters.nChan; i++)
            {
                string sName = parameters.ChannelLabelPrefix + " " + (i + 1).ToString("0");
                PhiThetaRecord xy = new PhiThetaRecord(sName, phi[i], theta[i]);
                xy.write(efs, "");
            }
            efs.Close();

            /* ***** Create new HDR file ***** */
            new HeaderFileWriter(
                File.Open(parameters.fileName + ".hdr", FileMode.Create, FileAccess.Write),
                parameters.head);

            /* ***** Create new Event file and initialize ***** */
            EventFileWriter events = new EventFileWriter(
                File.Open(parameters.fileName + ".evt", FileMode.Create, FileAccess.Write));
            int lastN = 0; // last used index of Event
            int lastG = 0; // last used grayCode

            /* ***** Other preliminaries ***** */
            int nRec = (int)Math.Ceiling((double)parameters.totalFileLength / (double)parameters.recordDuration);
            int nPts = parameters.recordDuration * parameters.samplingRate;
            DateTime dt = DateTime.Now; // base time for events
            double T = 0D;
            deltaT = 1D / Convert.ToDouble(parameters.samplingRate);
            int[] statusChannel = new int[nPts];

            /* ***** Main loop ***** */
            for (int rec = 0; rec < nRec; rec++ ) //for each required record
            {
                for (int p = 0; p < nPts; p++) //for each point in a record
                {
                    foreach (Event evt in parameters.eventList) //loop through each Event definition
                    {
                        if (evt.IsNow(T)) // is next occurence of Event at this tick?
                        {
                            lastN = (lastN % ((1 << parameters.nBits) - 2)) + 1; // get next index value
                            OutputEvent oe = new OutputEvent(evt.EDEntry, dt.AddSeconds(T), lastN);
                            lastG = oe.GC; // get the corresponding grayCode value; calculated as OutputEvent created
                            int n = evt.GVs.Count;
                            oe.GVValue = new string[n]; // assign group variable values
                            for (int i = 0; i < n; i++)
                            {
                                oe.GVValue[i] = evt.oldGVValues[i].ToString("0");
                            }
                            events.writeRecord(oe); // write out new Event record
                        }
                    }

                    statusChannel[p] = lastG; //Status channel
                    double eventcontribution = calculateEventSignal(parameters);
                    for (int chan = 1; chan <= parameters.nChan; chan++)
                    {
                        file.putSample(chan - 1, p, parameters.window.Calculate(T, chan) + eventcontribution);
                    }
                    T += deltaT;
                }
                file.putStatus(statusChannel);
                file.write();
                if (Window1.bw.CancellationPending)
                {
                    file.Close();
                    events.Close();
                    e.Cancel = true;
                    return;
                }
                Window1.bw.ReportProgress(Convert.ToInt32(100D * (double)rec / (double)nRec));
            }
            events.Close();
            file.Close();
        }
 public override void write(ElectrodeOutputFileStream ofs, string nameSpace)
 {
     if (ofs.t != typeof(XYZRecord)) throw new Exception("Attempt to mix types in ElectrodeOutputFileStream.");
     XmlWriter xw = ofs.xw;
     xw.WriteStartElement("Electrode", nameSpace);
     xw.WriteAttributeString("Name", nameSpace, this.Name);
     xw.WriteElementString("X", nameSpace, this.X.ToString("G"));
     xw.WriteElementString("Y", nameSpace, this.Y.ToString("G"));
     xw.WriteElementString("Z", nameSpace, this.Z.ToString("G"));
     xw.WriteEndElement();
 }
 /// <summary>
 /// Write a Phi-Theta electode record; although stored internally in radians,
 /// record values are written in degrees for easier human readability
 /// </summary>
 /// <param name="ofs">Electrode output file stream</param>
 /// <param name="nameSpace"></param>
 public override void write(ElectrodeOutputFileStream ofs, string nameSpace)
 {
     if (ofs.t != typeof(PhiThetaRecord)) throw new Exception("Attempt to mix types in ElectrodeOutputFileStream.");
     XmlWriter xw = ofs.xw;
     xw.WriteStartElement("Electrode", nameSpace);
     xw.WriteAttributeString("Name", nameSpace, this.Name);
     xw.WriteElementString("Phi", nameSpace, (Phi * ToDeg).ToString("G"));
     xw.WriteElementString("Theta", nameSpace, (Theta * ToDeg).ToString("G"));
     xw.WriteEndElement();
 }
 public abstract void write(ElectrodeOutputFileStream ofs, string nameSpace);
        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);
            }
        }
 private void writeElectrodeFile()
 {
     if (efs != null)
     {
         foreach (XYZRecord xyz in electrodeLocations)
             xyz.write(efs, "");
         efs.Close();
         efs = null;
         output3.Text = "Wrote " + electrodeLocations.Count().ToString("0") + " electrode location records.";
     }
 }