Beispiel #1
0
        public void Execute(object sender, DoWorkEventArgs e)
        {
            bw = (BackgroundWorker)sender;

            bw.ReportProgress(0, "Starting BDFConverter");
            CCIUtilities.Log.writeToLog("Starting BDFConverter on records in " + Path.Combine(directory, FileName));

            /***** Open BDF file *****/
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.Title = "Save as BDF file ...";
            dlg.AddExtension = true;
            dlg.DefaultExt = ".bdf"; // Default file extension
            dlg.Filter = "BDF Files (.bdf)|*.bdf"; // Filter files by extension
            dlg.FileName = FileName + "-converted";
            bool? result = dlg.ShowDialog();
            if (result == false)
            {
                e.Result = new int[] { 0, 0 };
                return;
            }
            newRecordLengthPts = oldRecordLengthPts / decimation;

            BDFWriter = new BDFEDFFileWriter(File.Open(dlg.FileName, FileMode.Create, FileAccess.ReadWrite),
                channels.Count + 1, /* Extra channel named Status will have group variable value in it */
                newRecordLengthSec, /* Record length in seconds */
                newRecordLengthPts, /* Record length in points */
                true); /* BDF format */

            log = new LogFile(dlg.FileName + ".log.xml", GVMapElements);
            bigBuff = new float[edfPlus.NumberOfChannels - 1, newRecordLengthPts];   //have to dimension to old channels rather than new
                                                                                //in case we need for reference calculations later
            /***** Create BDF header record *****/
            BDFWriter.LocalRecordingId = edfPlus.LocalRecordingId;
            BDFWriter.LocalSubjectId = edfPlus.LocalSubjectId;
            int chan;
            for (int i = 0; i < channels.Count; i++)
            {
                chan = channels[i];
                BDFWriter.channelLabel(i, edfPlus.channelLabel(chan));
                BDFWriter.transducer(i, edfPlus.transducer(chan));
                BDFWriter.dimension(i, edfPlus.dimension(chan));
                BDFWriter.pMax(i, edfPlus.pMax(chan));
                BDFWriter.pMin(i, edfPlus.pMin(chan));
                BDFWriter.dMax(i, edfPlus.dMax(chan));
                BDFWriter.dMin(i, edfPlus.dMin(chan));
                BDFWriter.prefilter(i, edfPlus.prefilter(chan));
            }
            chan = channels.Count;
            BDFWriter.channelLabel(chan, "Status"); //Make entries for Status channel
            BDFWriter.transducer(chan, "None");
            BDFWriter.dimension(chan, "");
            BDFWriter.pMax(chan, 32767);
            BDFWriter.pMin(chan, -32768);
            BDFWriter.dMax(chan, 32767);
            BDFWriter.dMin(chan, -32768);
            BDFWriter.prefilter(chan, "None");
            BDFWriter.writeHeader();

            log.registerHeader(this);

            BDFLoc stp = edfPlus.LocationFactory.New();
            BDFLoc lastEvent = edfPlus.LocationFactory.New();
            outLoc = BDFWriter.LocationFactory.New();
            lastStatus = 0;

            /***** MAIN LOOP *****/
            foreach (EventMark em in Events) //Loop through Event file
            {
                bw.ReportProgress(0, "Processing event " + em.Time.ToString("0.000")); //Report progress
                stp.FromSecs(em.Time + offset); //set stopping point, where Status transition should occur
                if (!runEDFtoMark(ref lastEvent, stp, lastStatus))
                    throw new Exception("Reached EOF before reaching event at " + em.Time.ToString("0.000") + "secs");
                if (GVMapElements.Contains(em.GV))
                    lastStatus = em.GV.Value;
                else if (deleteAsZero)
                    lastStatus = 0;

            }
            stp.EOF(); //copy out to end of file
            runEDFtoMark(ref lastEvent, stp, lastStatus);
            e.Result = new int[] { BDFWriter.NumberOfRecords, outLoc.Rec }; //both numbers should be the same
            BDFWriter.Close();
            log.Close();
        }
Beispiel #2
0
        public void Execute(object sender, DoWorkEventArgs e)
        {
            bw = (BackgroundWorker)sender;

            bw.ReportProgress(0, "Starting BDFConverter");
            CCIUtilities.Log.writeToLog("Starting BDFConverter on records in " + directory);

            /***** Read electrode file *****/
            ElectrodeInputFileStream etrFile = new ElectrodeInputFileStream(
                new FileStream(Path.Combine(directory, eventHeader.ElectrodeFile), FileMode.Open, FileAccess.Read));

            /***** Open BDF file *****/
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.Title = "Save as BDF file ...";
            dlg.AddExtension = true;
            dlg.DefaultExt = ".bdf"; // Default file extension
            dlg.Filter = "BDF Files (.bdf)|*.bdf"; // Filter files by extension
            dlg.FileName = Path.GetFileNameWithoutExtension(eventHeader.BDFFile);
            bool? result = dlg.ShowDialog();
            if (result == false)
            {
                e.Result = new int[] { 0, 0 };
                return;
            }
            samplingRate = BDF.NSamp / BDF.RecordDuration; //Old sampling rate; exact as number of samples and duration are always an exact multiple
            oldOffsetInPts = Convert.ToInt32(offset * samplingRate);
            int newSamplingRate = (int)((double)samplingRate / (double)decimation + 0.5); //Make best estimate possible with integers
            newOffsetInPts = Convert.ToInt32(offset * newSamplingRate);
            newRecordLength = length * newSamplingRate; //new record length must be exact multiple of the sampling rate in BDF
            newStatus = new int[newRecordLength];
            status = new int[BDF.NSamp];
            GV0 = GV[0];

            BDFWriter = new BDFEDFFileWriter(File.Open(dlg.FileName, FileMode.Create, FileAccess.ReadWrite),
                channels.Count + 1, /* Extra channel will have group variable value in it */
                length, /* Record length in seconds, must be integer */
                newSamplingRate,
                true);

            log = new LogFile(dlg.FileName + ".log.xml");
            bigBuff = new float[BDF.NumberOfChannels - 1, newRecordLength];   //have to dimension to old channels rather than new
                                                                                //in case we need for reference calculations later
            /***** Create BDF header record *****/
            BDFWriter.LocalRecordingId = BDF.LocalRecordingId;
            BDFWriter.LocalSubjectId = BDF.LocalSubjectId;
            int chan;
            for (int i = 0; i < channels.Count; i++)
            {
                chan = channels[i];
                BDFWriter.channelLabel(i, BDF.channelLabel(chan));
                BDFWriter.transducer(i, BDF.transducer(chan));
                BDFWriter.dimension(i, BDF.dimension(chan));
                BDFWriter.pMax(i, BDF.pMax(chan));
                BDFWriter.pMin(i, BDF.pMin(chan));
                BDFWriter.dMax(i, BDF.dMax(chan));
                BDFWriter.dMin(i, BDF.dMin(chan));
                BDFWriter.prefilter(i, BDF.prefilter(chan));
            }
            chan = channels.Count;
            BDFWriter.channelLabel(chan, GV0.Name); //Make entries for old Status channel
            BDFWriter.transducer(chan, "None");
            BDFWriter.dimension(chan, "");
            BDFWriter.pMax(chan, 262143);
            BDFWriter.pMin(chan, -262144);
            BDFWriter.dMax(chan, 262143);
            BDFWriter.dMin(chan, -262144);
            BDFWriter.prefilter(chan, "None");

            log.registerHeader(this);

            /***** Open Event file for reading *****/
            EventFactory.Instance(eventHeader.Events); // set up the factory
            EventFileReader EventFR = new EventFileReader(
                new FileStream(Path.Combine(directory, eventHeader.EventFile), FileMode.Open, FileAccess.Read));

            BDFLoc stp = BDF.LocationFactory.New();
            BDFLoc lastEvent = BDF.LocationFactory.New();
            if (!EDE.intrinsic) //set threshold
                if (risingEdge) threshold = EDE.channelMin + (EDE.channelMax - EDE.channelMin) * threshold;
                else threshold = EDE.channelMax - (EDE.channelMax - EDE.channelMin) * threshold;

            nominalT = BDF.LocationFactory.New(); //nominal Event time based on Event.Time
            actualT = BDF.LocationFactory.New(); //actual Event time in Status channel
            //Note: these should be the same if the two clocks run the same rate (DAQ and computer)
            /***** MAIN LOOP *****/
            foreach (InputEvent ie in EventFR) //Loop through Event file
            {
                bw.ReportProgress(0, "Processing event " + ie.Index.ToString("0")); //Report progress

                if (ie.Name == EDE.Name) // Event match found in Event file
                {
                    if(findEvent(ref stp, ie))
                        if (allSamps) //this is a continuous copy, not Event generated episodic conversion
                        {
                            runBDFtoEvent(lastEvent, ref stp, ie);
                            lastEvent = BDF.LocationFactory.New();
                        }
                        else createBDFRecord(stp, ie); //Create BDF recordset around this point; i.e. Event generated episodic conversion
                }
            }
            if (allSamps) //copy out to end of file
            {
                stp.Rec = BDF.NumberOfRecords;
                stp.Pt = 0;
                runBDFtoEvent(lastEvent, ref stp, null);
            }
            e.Result = new int[] { BDFWriter.NumberOfRecords, BDFWriter.NumberOfRecords };
            BDFWriter.Close();
            EventFR.Close();
            log.Close();
        }
Beispiel #3
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();
        }