Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2886_SymRegGrammarEnumeration/HeuristicLab.Algorithms.DataAnalysis.SymRegGrammarEnumeration/Analysis/SentenceLogger.cs @ 16017

Last change on this file since 16017 was 15982, checked in by bburlacu, 7 years ago

#2886: Add storable constructors for analyzers

File size: 5.1 KB
Line 
1using System;
2using System.Diagnostics;
3using System.IO;
4using System.IO.Compression;
5using HeuristicLab.Common;
6using HeuristicLab.Core;
7using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
8
9namespace HeuristicLab.Algorithms.DataAnalysis.SymRegGrammarEnumeration {
10  [Item("SentenceLogger", "")]
11  [StorableClass]
12  public class SentenceLogger : Item, IGrammarEnumerationAnalyzer {
13    private readonly string workingDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
14    private readonly string columnDelimiter = ";";
15    private readonly string header = "hash;length;infix";
16
17    private string distinctSentencesFileName;
18    private string allSentencesFileName;
19    private string shortestDistinctSentencesFileName;
20
21    private TextWriterTraceListener distinctSentencesFileTrace;
22    private TextWriterTraceListener allSentencesFileTrace;
23
24    public SentenceLogger() { }
25
26    [StorableConstructor]
27    protected SentenceLogger(bool deserializing) : base(deserializing) { }
28
29    protected SentenceLogger(SentenceLogger original, Cloner cloner) : base(original, cloner) { }
30
31    public override IDeepCloneable Clone(Cloner cloner) {
32      return new SentenceLogger(this, cloner);
33    }
34
35    public void Register(GrammarEnumerationAlgorithm algorithm) {
36      algorithm.Stopped += GrammarEnumerationAlgorithmOnStopped;
37      algorithm.ExceptionOccurred += GrammarEnumerationAlgorithmOnStopped;
38
39      algorithm.SentenceGenerated += SentenceGenerated;
40      algorithm.DistinctSentenceGenerated += DistinctSentenceGenerated;
41    }
42
43    public void Deregister(GrammarEnumerationAlgorithm algorithm) {
44      algorithm.Stopped -= GrammarEnumerationAlgorithmOnStopped;
45      algorithm.ExceptionOccurred -= GrammarEnumerationAlgorithmOnStopped;
46
47      algorithm.SentenceGenerated -= SentenceGenerated;
48      algorithm.DistinctSentenceGenerated -= DistinctSentenceGenerated;
49    }
50
51    private void GrammarEnumerationAlgorithmOnStopped(object sender, EventArgs eventArgs) {
52      distinctSentencesFileTrace.Close();
53      allSentencesFileTrace.Close();
54
55      // Remove duplicates afterwards using bash commands from the git bash
56      // string bashExecutable = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Programs\Git\git-bash.exe";
57      //
58      // string commandCreate = $"echo \"{header}\" > {shortestDistinctSentencesFileName.Replace("\\", "/")}";
59      // string commandFill = $"sort -s {distinctSentencesFileName.Replace("\\", "/")} | uniq -w 10 >> {shortestDistinctSentencesFileName.Replace("\\", "/")}";
60      //
61      // ProcessStartInfo startInfo = new ProcessStartInfo {
62      //   WindowStyle = ProcessWindowStyle.Hidden,
63      //   UseShellExecute = false,
64      //   CreateNoWindow = true,
65      //   FileName = bashExecutable,
66      //   RedirectStandardError = true,
67      //   RedirectStandardOutput = true,
68      //   Arguments = $"-c '{commandCreate};{commandFill}'"
69      // };
70      // Process.Start(startInfo);
71    }
72
73    private void Init(object sender) {
74      string datePostfix = $"_{DateTime.Now:yyyy-MM-dd_HH-mm}_TreeSize-{((GrammarEnumerationAlgorithm)sender).MaxComplexity}.csv.gz";
75      distinctSentencesFileName = workingDir + @"\distinctSentences" + datePostfix;
76      allSentencesFileName = workingDir + @"\allSentences" + datePostfix;
77      shortestDistinctSentencesFileName = workingDir + @"\shortestDistinctSentences" + datePostfix;
78
79      distinctSentencesFileTrace = new TextWriterTraceListener(new GZipStream(new FileStream(distinctSentencesFileName, FileMode.Create), CompressionMode.Compress));
80      allSentencesFileTrace = new TextWriterTraceListener(new GZipStream(new FileStream(allSentencesFileName, FileMode.Create), CompressionMode.Compress));
81      ((StreamWriter)distinctSentencesFileTrace.Writer).AutoFlush = true;
82      ((StreamWriter)allSentencesFileTrace.Writer).AutoFlush = true;
83
84      allSentencesFileTrace.WriteLine(header);
85    }
86
87    private void DistinctSentenceGenerated(object sender, PhraseAddedEventArgs phraseAddedEventArgs) {
88      if (distinctSentencesFileName == null) Init(sender);
89      distinctSentencesFileTrace.WriteLine(ToCsvLine(
90        ((uint)phraseAddedEventArgs.NewHash).ToString("D10"),
91        phraseAddedEventArgs.NewPhrase.Count().ToString("D3"),
92        //phraseAddedEventArgs.NewPhrase.ToString(),
93        ((GrammarEnumerationAlgorithm)sender).Grammar.ToInfixString(phraseAddedEventArgs.NewPhrase)));
94    }
95
96
97    private void SentenceGenerated(object sender, PhraseAddedEventArgs phraseAddedEventArgs) {
98      if (allSentencesFileTrace == null) Init(sender);
99      allSentencesFileTrace.WriteLine(ToCsvLine(
100        ((uint)phraseAddedEventArgs.NewHash).ToString("D10"),
101        phraseAddedEventArgs.NewPhrase.Count().ToString("D3"),
102        //phraseAddedEventArgs.NewPhrase.ToString(),
103        ((GrammarEnumerationAlgorithm)sender).Grammar.ToInfixString(phraseAddedEventArgs.NewPhrase)));
104    }
105
106    private string ToCsvLine(params string[] cols) {
107      return string.Join(columnDelimiter, cols);
108    }
109  }
110}
Note: See TracBrowser for help on using the repository browser.