Exemplo n.º 1
0
        private void Finish_Click(object sender, RoutedEventArgs e)
        {
            if (MarkerCanvas.markedRegions.Count != 0)
            {
                EventDictionaryEntry ede1;
                EventDictionaryEntry ede2;

                //Determine how many artifact files in existence to create unique name
                string[] files = Directory.GetFiles(directory, "*_artifact*.hdr", SearchOption.TopDirectoryOnly);
                int maxFileIndex = -1;
                for (int i = 0; i < files.Length; i++)
                {
                    Match m = Regex.Match(files[i], @"^.+_artifact(-\d+)*-(?<number>\d+)\.[hH][dD][rR]$");
                    if(m.Success) //has to match naming convention
                        maxFileIndex = Math.Max(maxFileIndex, Convert.ToInt32(m.Groups["number"].Value));
                }

                string newFileName;
                StringBuilder sb = new StringBuilder(header.Comment); //Add comment to HDR file documenting artifact marking
                if (sb.Length > 0) sb.Append(Environment.NewLine);
                sb.Append("Artifacts marked on " + DateTime.Today.ToShortDateString() + " by " + Environment.UserName);
                header.Comment = sb.ToString();
                if (updateFlag) //then, this dataset is based on another one; need to find out if this is an update of current dataset only, or if a new file is to be created
                {
                    if (!header.Events.TryGetValue("**ArtifactBegin", out ede1) || !header.Events.TryGetValue("**ArtifactEnd", out ede2) || !ede1.BDFBased || !ede2.BDFBased)
                        throw new Exception("Error in attempted update of previously marked dataset; may be update of old-form dataset");
                    Window3 w = new Window3();
                    w.Owner = this;
                    w.ShowDialog();
                    if (dialogReturn == 1) return;
                    if (dialogReturn == 2) //replace current files only
                        newFileName = System.IO.Path.GetFileNameWithoutExtension(header.EventFile); //Use old name; only update Comment
                    else //create new file set from old
                    {
                        newFileName = System.IO.Path.GetFileNameWithoutExtension(header.EventFile) + "-" + (maxFileIndex + 1).ToString("0");
                        header.EventFile = newFileName + ".evt";
                    }
                }
                else //this is based on a previously unmarked dataset; add new Event types to HDR
                {
                    //Modify header with new "naked" Events and file names
                    ede1 = new EventDictionaryEntry();
                    ede1.intrinsic = null;
                    ede1.BDFBased = true; //Use BDF-based clocking
                    ede1.Description = "Beginning of artifact region";
                    ede2 = new EventDictionaryEntry();
                    ede2.intrinsic = null;
                    ede2.BDFBased = true; //Use BDF-based clocking
                    ede2.Description = "End of artifact region";
                    header.Events.Add("**ArtifactBegin", ede1);
                    header.Events.Add("**ArtifactEnd", ede2);
                    newFileName = System.IO.Path.GetFileNameWithoutExtension(header.BDFFile) + @"_artifact-" +
                        (maxFileIndex + 1).ToString("0"); ; //create new filename
                    header.EventFile = newFileName + ".evt";
                    //and write new header out
                }

                header.Comment += (header.Comment == "" ? "" : Environment.NewLine) +
                    "Artefact Events marked on " + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss") +
                    " by " + Environment.UserName;
                FileStream fs = new FileStream(System.IO.Path.Combine(directory, newFileName + ".hdr"), FileMode.OpenOrCreate, FileAccess.Write);
                new HeaderFileWriter(fs, header); //write out new header

                foreach (MarkerRectangle mr in MarkerCanvas.markedRegions) //update Event file to include new artifact marks
                {
                    double eventTime = mr.leftEdge;
                    OutputEvent newOE = new OutputEvent(ede1, eventTime);
                    int index = events.FindIndex(ev => bdf.timeFromBeginningOfFileTo(ev) >= eventTime);
                    if (index < 0) //must be after last Event or no Events
                        events.Add(newOE);
                    else
                        events.Insert(index, newOE);
                    eventTime = mr.rightEdge;
                    newOE = new OutputEvent(ede2, eventTime);
                    index = events.FindIndex(ev => bdf.timeFromBeginningOfFileTo(ev) > eventTime);
                    if (index < 0)
                        events.Add(newOE);
                    else
                        events.Insert(index, newOE);
                }

                EventFileWriter efw = new EventFileWriter(
                    new FileStream(System.IO.Path.Combine(directory, header.EventFile), FileMode.OpenOrCreate, FileAccess.Write));
                foreach (OutputEvent ev in events)
                    efw.writeRecord(ev);
                efw.Close();
                Log.writeToLog("    Created/updated to dataset " + newFileName);
            }
            this.Close();
        }
Exemplo n.º 2
0
 //
 //Create a new Event for output
 //     need an indirect approach in order of permit the number of bits allocated
 //     to the Event.Index to be set at run time, but be unchangeable thereafter
 //
 public OutputEvent CreateOutputEvent(string name)
 {
     EventDictionaryEntry ede;
     if (!ed.TryGetValue(name, out ede)) //check to make sure there is an EventDictionaryEntry for this name
         throw new Exception("No entry in EventDictionary for \"" + name + "\"");
     OutputEvent e = new OutputEvent(ede);
     if (ede.IsCovered)
     {
         e.m_index = nextIndex();
         e.m_gc = grayCode((uint)e.Index);
     }
     //            markBDFstatus((uint)e.GC); //***** this is needed only if used for real-time application this BIOSEMI
     return e;
 }
Exemplo n.º 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();
        }