private static IEventFileWriter<IUserCommand> ConstructEventFileWriter() { var serializer = ConstructSerializer(); var hashChecksumTranscodingStreamFactory = ConstructTranscodingStreamFactories(); var streamEventWriter = new StreamEventWriter<IUserCommand>( serializer, hashChecksumTranscodingStreamFactory); var eventFileWriter = new EventFileWriter<IUserCommand>(streamEventWriter); return eventFileWriter; }
public FileWriter(string logdir, Graph graph, int max_queue = 10, int flush_secs = 120, string filename_suffix = null, Session session = null) { if (session == null) { event_writer = new EventFileWriter(logdir, max_queue, flush_secs, filename_suffix); } }
public void CreateMultipleFiles() { string path = AppDomain.CurrentDomain.BaseDirectory; var message = new EventMessage(EventLevel.Info, "Wello world info".PadRight(1024, '0')); string filename1 = Path.Combine(path, "CreateMultipleFiles-" + message.TimeStamp.ToString("yyyy-MM-dd")) + " (1).txt"; string filename2 = Path.Combine(path, "CreateMultipleFiles-" + message.TimeStamp.ToString("yyyy-MM-dd")) + " (2).txt"; string filename3 = Path.Combine(path, "CreateMultipleFiles-" + message.TimeStamp.ToString("yyyy-MM-dd")) + " (3).txt"; bool exist1 = File.Exists(filename1); bool exist2 = File.Exists(filename2); bool exist3 = File.Exists(filename3); if (exist1) { File.Delete(filename1); } if (exist2) { File.Delete(filename2); } if (exist3) { File.Delete(filename3); } var writer = new EventFileWriter(path, "CreateMultipleFiles-", 1); for (int i = 0; i < 2; i++) { writer.Write(message); } exist1 = File.Exists(filename1); exist2 = File.Exists(filename2); exist3 = File.Exists(filename3); if (exist1) { File.Delete(filename1); } if (exist2) { File.Delete(filename2); } if (exist3) { File.Delete(filename3); } Assert.True(exist1); Assert.True(exist2); Assert.False(exist3); }
public void WriteMessage() { var message = new EventMessage(EventLevel.Info, "Wello world info"); string path = AppDomain.CurrentDomain.BaseDirectory; var writer = new EventFileWriter(path, "WriteMessage-", 1); writer.Write(message); string filename = Path.Combine(path, "WriteMessage-" + message.TimeStamp.ToString("yyyy-MM-dd")) + " (1).txt"; Assert.True(File.Exists(filename)); File.Delete(filename); }
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(); }
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(); }
//Process the PK events found: returns true if files succesfully written private bool ProcessEvents() { //GV 1 if (!head.GroupVars.ContainsKey("Source channel")) { GVEntry gve = new GVEntry(); gve.GVValueDictionary = new Dictionary<string, int>(); gve.Description = "Source channel for this Event"; foreach (ChannelItem ci in ChannelEntries.Items) { //create GV Value entry for each channel name channelOptions co = channels[ci.Channel.SelectedIndex]; int i; gve.GVValueDictionary.TryGetValue(co.name, out i); if (i == 0) gve.GVValueDictionary.Add(co.name, co.channel + 1); //Use "external" (1-based) channel numbering } head.GroupVars.Add("Source channel", gve); //Channel name: add to GV list in HDR newGVList[0] = gve; } else newGVList[0] = head.GroupVars["Source channel"]; //GV 2 newGVList[1] = head.AddOrGetGroupVar("Found fit", "Found satisfactory fit to PK signal", new string[] { "Found", "Not found" }); //GV 3 newGVList[2] = head.AddOrGetGroupVar("Magnitude", "Estimate of the magnitude of PK signal in scale of channel"); //GV 4 newGVList[3] = head.AddOrGetGroupVar("Direction", "Direction of PK signal", new string[] { "Positive", "Negative" }); //GV 5 newGVList[4] = head.AddOrGetGroupVar("Alpha TC", "Estimate of the time constant (in millisecs) for the rising edge of the PK signal"); //GV 6 newGVList[5] = head.AddOrGetGroupVar("Chi square", "Chi square estimate of goodness of fit to the PK signal"); //GV 7 newGVList[6] = head.AddOrGetGroupVar("Serial number", "Serial number for this channel/filter combination"); //GV 8 newGVList[7] = head.AddOrGetGroupVar("Trend degree", "Degree of trend removal of original PK signal plus 2"); //GV 9 newGVList[8] = head.AddOrGetGroupVar("Filter length", "Length of filter in points"); //GV 10 newGVList[9] = head.AddOrGetGroupVar("Threshold", "Capturing threshold in microV/sec"); //GV 11 newGVList[10] = head.AddOrGetGroupVar("Minimum length", "Minimum length of above-threshold filter signal in points"); //Create Event Dictionary entry for each new PK event/ChannelItem foreach (ChannelItem ci in ChannelEntries.Items) { EventDictionaryEntry ede = head.AddNewEvent(ci.ImpliedEventName, "PK detector events from PKDetectorAnalyzer based on channel " + ci.Channel.Text, newGVList); ede.BDFBased = true; //naked Event with clock BDF-based } head.Comment += (head.Comment == "" ? "" : Environment.NewLine) + "PK source Events added on " + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss") + " by " + Environment.UserName; //Now read old Event file events = new List<Event.OutputEvent>(); Event.EventFactory.Instance(head.Events); // set up Event factory, based on EventDictionary in HDR EventFileReader efr = new EventFileReader( new FileStream(System.IO.Path.Combine(directory, head.EventFile), FileMode.Open, FileAccess.Read)); // open Event file bool zeroSet = false; foreach (Event.InputEvent ie in efr) // read in all Events into dictionary { events.Add(new Event.OutputEvent(ie)); //make list of all current Events if (!zeroSet && ie.IsCovered) //set zeroTime based on first encounter covered Event { bdf.setZeroTime(ie); zeroSet = true; } } efr.Close(); //write out new HDR file FileStream fs = null; bool OK = false; while (!OK) { try { head.EventFile = newFileName + ".evt"; //now we can change Event file name and write out new HDR fs = new FileStream(System.IO.Path.Combine(directory, newFileName + ".hdr"), FileMode.CreateNew, FileAccess.Write); OK = true; } catch (IOException) //force only a new { Replace_dataset rd = new Replace_dataset(newFileName, this.FNExtension.Text); rd.WindowStartupLocation = WindowStartupLocation.CenterOwner; rd.Owner = this; rd.ShowDialog(); if (rd.Result > 0) { if (rd.Result == 3) //Exit { Status.Text = "Cancelled writing new dataset"; return false; } if (rd.Result == 1) //Yes { OK = true; fs = new FileStream(System.IO.Path.Combine(directory, newFileName + ".hdr"), FileMode.Create, FileAccess.Write); } else //N0: new extension, try again { this.FNExtension.Text = rd.NewExtension.Text; //this will also change newFileName } } } } new HeaderFileWriter(fs, head); foreach (eventTime et in eventTimeList) { double ST = bdf.SampleTime(et.channelNumber); //create a naked Event at this time Event.OutputEvent newEvent = new Event.OutputEvent(head.Events[et.channelItem.ImpliedEventName], (double)(et.t0 + et.startTime) * ST); //assign GV values to new event newEvent.GVValue = new string[11]; newEvent.GVValue[0] = bdf.channelLabel(et.channelNumber); newEvent.GVValue[1] = et.foundFit ? "Found" : "Not found"; newEvent.GVValue[2] = ((int)Math.Abs(et.A)).ToString("0"); newEvent.GVValue[3] = et.sign > 0 ? "Positive" : "Negative"; newEvent.GVValue[4] = ((int)(1000D / et.a)).ToString("0"); if (et.chiSquare < 2E9) newEvent.GVValue[5] = ((int)et.chiSquare).ToString("0"); else newEvent.GVValue[5] = "0"; newEvent.GVValue[6] = et.serialNumber.ToString("0"); newEvent.GVValue[7] = (et.trendDegree + 2).ToString("0"); newEvent.GVValue[8] = et.filterLength.ToString("0"); newEvent.GVValue[9] = ((int)(et.threshold / ST)).ToString("0"); newEvent.GVValue[10] = et.minimumLength.ToString("0"); events.Add(newEvent); } events = events.OrderBy(ev => bdf.timeFromBeginningOfFileTo(ev)).ToList(); //sort Events into time order fs = new FileStream(System.IO.Path.Combine(directory,head.EventFile), FileMode.Create, FileAccess.Write); EventFileWriter efw = new EventFileWriter(fs); foreach (Event.OutputEvent ev in events) efw.writeRecord(ev); efw.Close(); lf.Close(); //close out log file //and copy out to file logStream.WriteTo(new FileStream(System.IO.Path.Combine(directory, newFileName + ".pkda.log.xml"), FileMode.Create, FileAccess.Write)); return true; }