public IndividualHouseholdJsonSumProfileProcessor([NotNull] CalcDataRepository repository, [NotNull] IFileFactoryAndTracker fft, [NotNull] ICalculationProfiler calculationProfiler) : base( repository, AutomationUtili.GetOptionList(CalcOption.JsonHouseholdSumFiles), calculationProfiler, "Individual Household Json Sum Profiles") =>
private MessageFromServerToClient MakeRequest([NotNull] RequestSocket socket, [NotNull] MessageFromClientToServer message) { byte[] messageBytes = LZ4MessagePackSerializer.Serialize(message); byte[] answer; Stopwatch sw = Stopwatch.StartNew(); TimeSpan ts = new TimeSpan(0, 1, 0); lock (_socketLock) { var success = socket.TrySendFrame(ts, messageBytes); if (!success) { throw new DistSimException("could not send to server"); } success = socket.TryReceiveFrameBytes(ts, out answer); if (!success) { throw new DistSimException("could not receive from server"); } } var answermessage = LZ4MessagePackSerializer.Deserialize <MessageFromServerToClient>(answer); sw.Stop(); var prettySizeSent = AutomationUtili.MakePrettySize(messageBytes.Length); var prettysizeAnswer = AutomationUtili.MakePrettySize(answer.Length); _logger.Info("Sent " + prettySizeSent + " and received an answer with a length of " + prettysizeAnswer + ", elapsed: " + sw.Elapsed, _threadId); return(answermessage); }
public DurationCurveMaker([NotNull] CalcDataRepository repository, [NotNull] ICalculationProfiler calculationProfiler, [NotNull] IFileFactoryAndTracker fft) : base(repository, AutomationUtili.GetOptionList(CalcOption.DurationCurve), calculationProfiler, "Duration Curves") { _fft = fft; }
/* * private static void CopyAll([NotNull] DirectoryInfo source, [NotNull] DirectoryInfo target) * { * Directory.CreateDirectory(target.FullName); * * // Copy each file into the new directory. * foreach (var fi in source.GetFiles()) * { * Logger.Info(string.Format(CultureInfo.CurrentCulture, @"Copying {0}\{1}", target.FullName, fi.Name)); * fi.CopyTo(Path.Combine(target.FullName, fi.Name), true); * } * * // Copy each subdirectory using recursion. * foreach (var diSourceSubDir in source.GetDirectories()) * { * var nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name); * CopyAll(diSourceSubDir, nextTargetSubDir); * } * }*/ public void RunDirectHouseholds() { using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) { using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { Simulator sim = new Simulator(db.ConnectionString); string dir = wd.Combine("DirectHouseJobs"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } foreach (var mhh in sim.ModularHouseholds.It) { HouseCreationAndCalculationJob hj = new HouseCreationAndCalculationJob("Households", "2019", "TK", HouseDefinitionType.HouseData); hj.House = new HouseData(Guid.NewGuid().ToStrGuid(), "HT01", 10000, 10000, "House for " + mhh.Name); hj.House.Households.Add(new HouseholdData(Guid.NewGuid().ToString(), mhh.Name, null, null, null, null, HouseholdDataSpecificationType.ByHouseholdName)); hj.House.Households[0].HouseholdNameSpec = new HouseholdNameSpecification(mhh.GetJsonReference()); SetCalcSpec(hj, sim); string fn = Path.Combine(dir, AutomationUtili.CleanFileName(mhh.Name) + ".json"); File.WriteAllText(fn, JsonConvert.SerializeObject(hj, Formatting.Indented)); } //CopyAll(new DirectoryInfo(dir), new DirectoryInfo(@"X:\HouseJobs\Blockstrom\DirectHouseholds")); } } }
public static List <MsgFile> ReadMsgFiles(bool addFullFiles, [NotNull][ItemNotNull] List <FileInfo> filteredFiles, [NotNull] DirectoryInfo baseDir, [NotNull] DistLogger logger, [NotNull] ThreadId threadId) { var lpgFiles = new List <MsgFile>(); long totalSize = 0; foreach (var fi in filteredFiles) { var relativeDirectory = ""; if (fi.DirectoryName?.Length > baseDir.FullName.Length) { relativeDirectory = fi.DirectoryName.Substring(baseDir.FullName.Length).Trim().Trim('\\'); } MsgFile jf = new MsgFile(fi, relativeDirectory); if (addFullFiles) { jf.FileContent = File.ReadAllBytes(fi.FullName); } totalSize += fi.Length; lpgFiles.Add(jf); } string prettySize = AutomationUtili.MakePrettySize(totalSize); logger.Info("Collected files with " + prettySize, threadId); return(lpgFiles); }
public TransportationDeviceJson([JetBrains.Annotations.NotNull] ICalculationProfiler calculationProfiler, [JetBrains.Annotations.NotNull] CalcDataRepository repository, [JetBrains.Annotations.NotNull] IFileFactoryAndTracker fft ) : base(repository, AutomationUtili.GetOptionList(CalcOption.TansportationDeviceJsons), calculationProfiler, "Transportation Device Statistics as Json", 10) { _fft = fft; }
public TimeOfUseMaker( [NotNull] CalcDataRepository repository, [NotNull] ICalculationProfiler profiler, [NotNull] IFileFactoryAndTracker fft) : base(repository, AutomationUtili.GetOptionList(CalcOption.TimeOfUsePlot), profiler, "Time of Use Averages") { _fft = fft; }
public HouseSumProfilesFromDetailedDatsProcessor([NotNull] IFileFactoryAndTracker fft, [NotNull] CalcDataRepository repository, [NotNull] ICalculationProfiler profiler) : base(repository, AutomationUtili.GetOptionList(CalcOption.HouseSumProfilesFromDetailedDats), profiler, "Individual Sum Profiles") { _fft = fft; }
public WeekdayLoadProfileMaker( [NotNull] IFileFactoryAndTracker fft, [NotNull] CalcDataRepository repository, [NotNull] ICalculationProfiler profiler ) : base(repository, AutomationUtili.GetOptionList(CalcOption.WeekdayProfiles), profiler, "Weekday Profiles") { _fft = fft; }
public MakeActivationsPerHour([NotNull] CalcDataRepository repository, [NotNull] ICalculationProfiler profiler, [NotNull] IFileFactoryAndTracker fft) : base(repository, AutomationUtili.GetOptionList(CalcOption.ActivationsPerHour), profiler, "Activiations per Hour", 0) { _fft = fft; }
public ImportFileCreatorPolysun([NotNull] CalcDataRepository repository, [NotNull] ICalculationProfiler profiler, [NotNull] IFileFactoryAndTracker fft) : base(repository, AutomationUtili.GetOptionList(CalcOption.PolysunImportFiles), profiler, "Polysun Import Files") { _fft = fft; }
public MakeHouseholdPlanResult( [NotNull] CalcDataRepository repository, [NotNull] ICalculationProfiler profiler, [NotNull] IFileFactoryAndTracker fft) : base(repository, AutomationUtili.GetOptionList(CalcOption.HouseholdPlan), profiler, "Household Plans", 0) { _fft = fft; }
//[JetBrains.Annotations.NotNull]private readonly Dictionary<HouseholdKey, StreamWriter> _files; public MakeTotalsPerLoadtype( [NotNull] CalcDataRepository repository, [NotNull] ICalculationProfiler profiler, [NotNull] IInputDataLogger inputDataLogger) : base(repository, AutomationUtili.GetOptionList(CalcOption.TotalsPerLoadtype), profiler, "Totals per LoadType") { _inputDataLogger = inputDataLogger; // _files = new Dictionary<HouseholdKey, StreamWriter>(); }
public BodilyActivityLevelsStatistics([NotNull] ICalculationProfiler calculationProfiler, [NotNull] CalcDataRepository repository, IFileFactoryAndTracker fft) : base(repository, AutomationUtili.GetOptionList(CalcOption.BodilyActivityStatistics), calculationProfiler, "Make Bodily Activity Level Counts", 10) { _repository = repository; _fft = fft; _calculationProfiler = calculationProfiler; }
public MakeTotalsPerDevice([NotNull] CalcDataRepository repository, [NotNull] ICalculationProfiler profiler, [NotNull] IFileFactoryAndTracker fft, IInputDataLogger inputDataLogger) : base(repository, AutomationUtili.GetOptionList(CalcOption.TotalsPerDevice), profiler, "Totals per Device") { _inputDataLogger = inputDataLogger; _fft = fft; }
private static string GetCalcObjectName([NotNull] string name) { var cleanname = AutomationUtili.CleanFileName(name); cleanname = cleanname.Replace(" ", string.Empty).Replace("+", string.Empty).Replace(",", "_"); if (cleanname.Length > 20) { cleanname = cleanname.Substring(0, 20); } return(cleanname); }
public void BeginTransaction() { lock (Dblock) { if (_databasesInTransaction.ContainsKey(_database.ConnectionString)) { throw new FlaException("double entry for " + _database.ConnectionString); } _databasesInTransaction.Add(_database.ConnectionString, AutomationUtili.GetCallingMethodAndClass()); _database.BeginTransaction(); _isInTransaction[DBFilename] = true; _transactionSetters[DBFilename] = AutomationUtili.GetCallingMethodAndClass(); } }
public AffordanceStatisticsWriter([JetBrains.Annotations.NotNull] CalcDataRepository repository, [JetBrains.Annotations.NotNull] ICalculationProfiler profiler, [JetBrains.Annotations.NotNull] IInputDataLogger logger) : base(repository, AutomationUtili.GetOptionList(CalcOption.AffordanceEnergyUse), profiler, "Affordance Energy Use") { _logger = logger; /* EnergyUseByHouseholdAffordanceAndLoadtype = * new Dictionary<HouseholdKey, Dictionary<CalcLoadTypeDto, Dictionary<string, double>>>(); * _energyUseListByHouseholdAffordanceAndLoadtype = * new Dictionary<HouseholdKey, Dictionary<CalcLoadTypeDto, Dictionary<string, List<double>>>>(); * _energyUseListByHouseholdAffordancePersonAndLoadtype = * new Dictionary<HouseholdKey, * Dictionary<CalcLoadTypeDto, Dictionary<string, Dictionary<string, double>>>>(); */ }
public CalcLoadType([NotNull] string pName, [NotNull] string unitOfPower, [NotNull] string unitOfSum, double conversionFactor, bool showInCharts, StrGuid guid) : base(pName, guid) { UnitOfPower = unitOfPower; UnitOfSum = unitOfSum; ConversionFactor = conversionFactor; ShowInCharts = showInCharts; _fileName = AutomationUtili.CleanFileName(pName); while (_fileName.Contains(" ")) { _fileName = _fileName.Replace(" ", " "); } _lti = new LoadTypeInformation(Name, UnitOfSum, UnitOfPower, ConversionFactor, ShowInCharts, _fileName, Guid); _dto = new CalcLoadTypeDto(pName, unitOfPower, unitOfSum, conversionFactor, ShowInCharts, guid); }
private void MakePieCharts([JetBrains.Annotations.NotNull] string fileName, [JetBrains.Annotations.NotNull] string plotName, [JetBrains.Annotations.NotNull] DirectoryInfo basisPath, [JetBrains.Annotations.NotNull] Dictionary <string, List <TagEntry> > consumption) { foreach (var pair in consumption) { var plotModel1 = new PlotModel(); pair.Value.Sort((x, y) => x.Value.CompareTo(y.Value)); plotModel1.LegendBorderThickness = 0; plotModel1.LegendOrientation = LegendOrientation.Horizontal; plotModel1.LegendPlacement = LegendPlacement.Outside; plotModel1.LegendPosition = LegendPosition.BottomCenter; if (Parameters.ShowTitle) { plotModel1.Title = plotName; } var pieSeries1 = new PieSeries { InsideLabelColor = OxyColors.White, InsideLabelPosition = 0.8, StrokeThickness = 2, AreInsideLabelsAngled = true }; foreach (var tuple in pair.Value) { var name = tuple.TagName.Trim(); if (name.Length > 30) { name = name.Substring(0, 20) + "..."; } var slice = new PieSlice(name, tuple.Value); pieSeries1.Slices.Add(slice); } plotModel1.Series.Add(pieSeries1); var fi = new FileInfo(fileName); var modifiedName = fi.Name.Substring(0, fi.Name.Length - 3) + AutomationUtili.CleanFileName(pair.Key); if (fi.DirectoryName == null) { throw new LPGException("Directory name was null"); } var cleanedfullname = Path.Combine(fi.DirectoryName, modifiedName); Save(plotModel1, plotName, cleanedfullname, basisPath, CalcOption.HouseholdContents); } }
public void MakeDocument([JetBrains.Annotations.NotNull] string pdfDstPath, [JetBrains.Annotations.NotNull] string calcObjectName, bool startpdf, bool requireAll, [JetBrains.Annotations.NotNull] string csvCharacter, [JetBrains.Annotations.NotNull] FileFactoryAndTracker fft) { // Create a MigraDoc document _calculationProfiler.StartPart(Utili.GetCurrentMethodAndClass() + " - PDF Layout"); var document = CreateDocument(pdfDstPath, requireAll, csvCharacter); _calculationProfiler.StopPart(Utili.GetCurrentMethodAndClass() + " - PDF Layout"); _calculationProfiler.StartPart(Utili.GetCurrentMethodAndClass() + " - PDF Render"); #pragma warning disable 618 var renderer = new PdfDocumentRenderer(true, PdfFontEmbedding.Always) #pragma warning restore 618 { Document = document }; Logger.ImportantInfo("Rendering the PDF. This will take a really long time without any progress report..."); renderer.RenderDocument(); _calculationProfiler.StopPart(Utili.GetCurrentMethodAndClass() + " - PDF Render"); _calculationProfiler.StartPart(Utili.GetCurrentMethodAndClass() + " - PDF Cleanup"); // Save the document... if (!Directory.Exists(pdfDstPath)) { Directory.CreateDirectory(pdfDstPath); } var filename = "Overview." + AutomationUtili.CleanFileName(calcObjectName) + ".pdf"; var dstFullName = Path.Combine(pdfDstPath, filename); if (File.Exists(dstFullName)) { File.Delete(dstFullName); } Logger.ImportantInfo("----"); Logger.ImportantInfo(dstFullName); Logger.ImportantInfo("----"); Logger.ImportantInfo("Saving the PDF..."); renderer.PdfDocument.Save(dstFullName); GC.WaitForPendingFinalizers(); GC.Collect(); // ...and start a viewer. if (startpdf) { Process.Start(dstFullName); } fft.RegisterFile(filename, "Overview of all results", true, ResultFileID.PDF, Constants.GeneralHouseholdKey, TargetDirectory.Root, CalcOption.MakePDF); _calculationProfiler.StopPart(Utili.GetCurrentMethodAndClass() + " - PDF Cleanup"); //return new ResultFileEntry("Overview", filename, dstFullName, true); }
public Thread MakeThreadAndStart([NotNull] ThreadStart start, [NotNull] string name, bool isStaThread = false) { var t = new Thread(start); t.Name = AutomationUtili.GetCallingMethodAndClass() + " - " + name; if (isStaThread) { t.SetApartmentState(ApartmentState.STA); } lock (ThreadList) { ThreadList.Add(t); } t.Start(); return(t); }
public void Save([JetBrains.Annotations.NotNull] PlotModel plotModel1, [JetBrains.Annotations.NotNull] string plotName, [JetBrains.Annotations.NotNull] string csvFullFileName, [JetBrains.Annotations.NotNull] DirectoryInfo basisPath, CalcOption enablingOption, [CanBeNull] string newDstFileName = null, bool makePng = true) { if (plotName.Contains("\\") || plotName.Trim().Length == 0 || plotName.Contains(".")) { throw new LPGException("Plotname is messed up. Please report!"); } var fiCsv = new FileInfo(csvFullFileName.Replace("/", " ")); var destinationFileName = fiCsv.Name; if (newDstFileName != null) { destinationFileName = newDstFileName; } destinationFileName = destinationFileName.Replace(".csv", string.Empty); destinationFileName += ".png"; destinationFileName = AutomationUtili.CleanFileName(destinationFileName); if (fiCsv.DirectoryName == null) { throw new LPGException("Directory name was null. This is a bug. Please report."); } var fi = new FileInfo(Path.Combine(basisPath.FullName, "Charts", destinationFileName)); if (makePng) { if (fi.Exists) { throw new LPGException("File already exists?!? " + fi.FullName); } FFT.RegisterFile(fi.Name, "Plot for " + plotName, true, ResultFileID.Chart, Constants.GeneralHouseholdKey, TargetDirectory.Charts, enablingOption, fi.Name); PngExporter.Export(plotModel1, fi.FullName, _parameters.Width, _parameters.Height, OxyColor.FromArgb(255, 255, 255, 255), _parameters.Dpi); } if (Config.MakePDFCharts) { var pdfChartName = fi.FullName.Substring(0, fi.FullName.Length - 4); pdfChartName += ".pdf"; FFT.RegisterFile(pdfChartName, "PDF Plot for " + plotName, true, ResultFileID.Chart, Constants.GeneralHouseholdKey, TargetDirectory.Charts, enablingOption, pdfChartName); OxyPDFCreator.Run(plotModel1, pdfChartName); } }
public void RunHouseholdTemplate() { using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) { using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { Simulator sim = new Simulator(db.ConnectionString); string dir = wd.Combine("DirectHouseJobs"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } Random rnd = new Random(); List <string> houseTypes = sim.HouseTypes.It.Select(x => x.Name.Substring(0, x.Name.IndexOf(" ", StringComparison.Ordinal))).ToList(); foreach (var mhh in sim.HouseholdTemplates.It) { for (int i = 0; i < 100; i++) { HouseCreationAndCalculationJob hj = new HouseCreationAndCalculationJob("TemplatedRandomHouseType", "2019", "TK", HouseDefinitionType.HouseData); string ht = houseTypes[rnd.Next(houseTypes.Count)]; Logger.Info(ht); hj.House = new HouseData(Guid.NewGuid().ToStrGuid(), ht, 10000, 10000, "House for " + mhh.Name + " " + i); hj.House.Households.Add(new HouseholdData(Guid.NewGuid().ToString(), mhh.Name, null, null, null, null, HouseholdDataSpecificationType.ByTemplateName)); hj.House.Households[0].HouseholdTemplateSpec = new HouseholdTemplateSpecification(mhh.Name); SetCalcSpec(hj, sim); if (hj.CalcSpec?.CalcOptions == null) { throw new LPGException("calcoption not set"); } hj.CalcSpec.CalcOptions.Add(CalcOption.EnergyCarpetPlot); hj.CalcSpec.CalcOptions.Add(CalcOption.HouseSumProfilesFromDetailedDats); string fn = Path.Combine(dir, AutomationUtili.CleanFileName(mhh.Name) + "." + i + ".json"); File.WriteAllText(fn, JsonConvert.SerializeObject(hj, Formatting.Indented)); } } //CopyAll(new DirectoryInfo(dir), new DirectoryInfo(@"X:\HouseJobs\Blockstrom\TemplatedHouses")); } } }
private void WriteTexBlock([NotNull] StreamWriter sw, [NotNull] string pngFileName, [NotNull] string blockName, [NotNull] string typeDesc, [NotNull] string basisDir) { sw.WriteLine(); sw.WriteLine(@"<!--\FloatBarrier-->"); var cleanBlockName = typeDesc + "_" + blockName; cleanBlockName = AutomationUtili.CleanFileName(cleanBlockName).Replace(" ", string.Empty); sw.WriteLine("#### " + blockName + " [" + cleanBlockName + "]"); sw.WriteLine(); sw.WriteLine("<!--"); sw.WriteLine(@"\begin{figure}[!ht]"); sw.WriteLine(@"\centering"); var relativefilename = "Manual/" + pngFileName.Substring(basisDir.Length).Replace("\\", "/"); sw.WriteLine(@"\includegraphics[keepaspectratio,width=\textwidth,height=10cm]{" + relativefilename + "}"); if (blockName.ToLower(CultureInfo.CurrentCulture) == "overview") { sw.WriteLine(@"\caption{" + blockName + " of the element '" + typeDesc + "'}"); } else { sw.WriteLine(@"\caption{Section '" + blockName + "' of the element '" + typeDesc + "'}"); } var cleanBlockname = AutomationUtili.CleanFileName(blockName).Replace(" ", string.Empty); var cleanTypeDesc = AutomationUtili.CleanFileName(typeDesc).Replace(" ", string.Empty); sw.WriteLine(@"\label{" + cleanTypeDesc + "_" + cleanBlockname + "}"); sw.WriteLine(@"\end{figure}"); sw.WriteLine("-->"); sw.WriteLine(); foreach (var label in _labels) { sw.WriteLine("- **" + label + "** <!--\\newline--> "); sw.WriteLine(); } }
private static void MakeBarCharts([ItemNotNull][JetBrains.Annotations.NotNull] List <AffTagEntry> entries, [JetBrains.Annotations.NotNull] string dstDirectory) { var personNames = entries.Select(x => x.PersonName.Trim()).Distinct().ToList(); // make absolute values var plotModel1 = MakePlotmodel(personNames, "Simulationszeit in Prozent"); var tagNames = entries.Select(x => x.AffTagName).Distinct().ToList(); OxyPalette p; if (tagNames.Count < 2) { p = OxyPalettes.Hue64; } else { p = OxyPalettes.HueDistinct(tagNames.Count); } var personSums = new Dictionary <string, double>(); foreach (var personName in personNames) { var sum = entries.Where(x => x.PersonName == personName).Select(x => x.Value).Sum(); personSums.Add(personName, sum); } for (var i = 0; i < tagNames.Count; i++) { var tag = tagNames[i]; var columnSeries2 = new ColumnSeries { IsStacked = true, StackGroup = "1", XAxisKey = "N", StrokeThickness = 1, Title = ChartLocalizer.Get().GetTranslation(tag), LabelPlacement = LabelPlacement.Middle, StrokeColor = OxyColors.White, FillColor = p.Colors[i] }; foreach (var personName in personNames) { var te = entries.FirstOrDefault(x => x.AffTagName == tag && x.PersonName == personName); if (te != null) { columnSeries2.Items.Add(new ColumnItem(te.Value / personSums[te.PersonName] * 100)); } else { columnSeries2.Items.Add(new ColumnItem(0)); } } plotModel1.Series.Add(columnSeries2); } const string fileName = "MergedAffordanceTaggingSet.WoBleibtDieZeit.Absolute.pdf"; OxyPDFCreator.Run(plotModel1, fileName); foreach (var tagName in tagNames) { var plotModel2 = MakePlotmodel(personNames, "Anteil an der Gesamtzeit in Prozent"); var columnSeries2 = new ColumnSeries { IsStacked = true, StackGroup = "1", StrokeThickness = 1, StrokeColor = OxyColors.White, XAxisKey = "N", Title = ChartLocalizer.Get().GetTranslation(tagName), LabelPlacement = LabelPlacement.Middle, FillColor = OxyColors.LightBlue }; var averageValue = entries.Where(x => x.AffTagName == tagName) .Select(x => x.Value / personSums[x.PersonName] * 100) .Average(); var ls = new LineSeries { Color = OxyColors.Red, Title = "Durchschnitt" }; for (var i = 0; i < personNames.Count; i++) { var personName = personNames[i]; ls.Points.Add(new DataPoint(i, averageValue)); var te = entries.FirstOrDefault(x => x.AffTagName == tagName && x.PersonName == personName); if (te != null) { columnSeries2.Items.Add(new ColumnItem(te.Value / personSums[personName] * 100)); } else { columnSeries2.Items.Add(new ColumnItem(0)); } } plotModel2.Series.Add(columnSeries2); plotModel2.Series.Add(ls); var cleanTag = AutomationUtili.CleanFileName(tagName); var relfileName = Path.Combine(dstDirectory, "MergedAffordanceTaggingSet.WoBleibtDieZeit." + cleanTag + ".pdf"); OxyPDFCreator.Run(plotModel2, relfileName); } }
protected override FileProcessingResult MakeOnePlot(ResultFileEntry rfe) { Profiler.StartPart(Utili.GetCurrentMethodAndClass()); string plotName = "Execution Count for " + rfe.HouseholdNumberString; var consumption = new Dictionary <string, List <Tuple <string, double> > >(); var lastname = string.Empty; if (rfe.FullFileName == null) { throw new LPGException("filename was null"); } using (var sr = new StreamReader(rfe.FullFileName)) { while (!sr.EndOfStream) { var s = sr.ReadLine(); if (s == null) { throw new LPGException("Readline failed."); } var cols = s.Split(Parameters.CSVCharacterArr, StringSplitOptions.None); if (s == "-----") { var name = sr.ReadLine(); if (name == null) { throw new LPGException("Readline failed."); } consumption.Add(name, new List <Tuple <string, double> >()); lastname = name; sr.ReadLine(); // header } else { var d = Convert.ToDouble(cols[1], CultureInfo.CurrentCulture); consumption[lastname].Add(new Tuple <string, double>(cols[0], d)); } } } foreach (var pair in consumption) { var mylist = pair.Value; mylist.Sort(Comparison); } foreach (var pair in consumption) { var plotModel1 = new PlotModel { // general LegendBorderThickness = 0, LegendOrientation = LegendOrientation.Horizontal, LegendPlacement = LegendPlacement.Outside, LegendPosition = LegendPosition.BottomCenter }; var personName = pair.Key; if (Parameters.ShowTitle) { plotModel1.Title = plotName + " " + personName; } plotModel1.IsLegendVisible = false; // axes var cate = new CategoryAxis { AbsoluteMinimum = 0, MinimumPadding = 0, GapWidth = 0, MinorStep = 1, Title = " ", Angle = 90, AxisTitleDistance = 150, ClipTitle = false }; plotModel1.Axes.Add(cate); var linearAxis2 = new LinearAxis { AbsoluteMinimum = 0, MaximumPadding = 0.06, MinimumPadding = 0, Title = "Times of execution" }; plotModel1.Axes.Add(linearAxis2); // data OxyPalette p; if (pair.Value.Count > 1) { p = OxyPalettes.HueDistinct(pair.Value.Count); } else { p = OxyPalettes.Hue64; } var columnSeries2 = new ColumnSeries { StrokeThickness = 0, Title = "Actions" }; for (var i = 0; i < pair.Value.Count; i++) { var label = pair.Value[i].Item1; if (label.Length > 40) { label = label.Substring(0, 40); } cate.Labels.Add(label); var ci = new ColumnItem(pair.Value[i].Item2) { Color = p.Colors[i] }; columnSeries2.Items.Add(ci); } plotModel1.Series.Add(columnSeries2); var fi = new FileInfo(rfe.FullFileName); var pn = fi.Name.Substring(0, fi.Name.Length - 3); var cleanedName = AutomationUtili.CleanFileName(pair.Key); if (fi.DirectoryName == null) { throw new LPGException("Directory Name was null"); } var correctfilename = Path.Combine(fi.DirectoryName, pn + cleanedName + ".png"); Save(plotModel1, plotName, correctfilename, Parameters.BaseDirectory, CalcOption.ActivationsPerHour); } Profiler.StopPart(Utili.GetCurrentMethodAndClass()); return(FileProcessingResult.ShouldCreateFiles); }
public LocationStatisticsMaker([JetBrains.Annotations.NotNull] IFileFactoryAndTracker fft, [JetBrains.Annotations.NotNull] CalcDataRepository repository, [JetBrains.Annotations.NotNull] ICalculationProfiler profiler) : base(repository, AutomationUtili.GetOptionList(CalcOption.LocationsFile), profiler, "Location Statistics", 0) { _fft = fft; MakeStreamWriterFunc = GetWriter; }
public void SnapshotExpanders([CanBeNull] TabItem ti) { try { _labels.Clear(); Logger.Get().SafeExecuteWithWait(() => { var view = (UserControl)ti.Content; dynamic presenter = view.DataContext; if (TestWithReflection(presenter, "Item")) { DBBase item = presenter.Item; _typeDescRaw = item.TypeDescription; } else { _typeDescRaw = ti.Header.ToString(); } var typeDescClean = AutomationUtili.CleanFileName(_typeDescRaw).Replace(" ", string.Empty); _basisDir = _sim.MyGeneralConfig.DestinationPath; _dstDir = Path.Combine(_basisDir, _itemCount.ToString("00", CultureInfo.CurrentCulture) + "-" + typeDescClean); if (!Directory.Exists(_dstDir)) { Directory.CreateDirectory(_dstDir); } var di = new DirectoryInfo(_dstDir); if (di.Parent == null) { throw new LPGException("Di parent was null"); } _texName = Path.Combine(di.Parent.FullName, _itemCount.ToString("00", CultureInfo.CurrentCulture) + ".Screenshots." + typeDescClean + ".tex"); dynamic dynView = view; Grid maingrid = dynView.Content; ScrollViewer sv = null; foreach (var child in maingrid.Children) { sv = child as ScrollViewer; if (sv != null) { break; } } if (sv == null) { throw new LPGException("No scrollviewer"); } _stackPanel = (StackPanel)sv.Content; }); var count = 1; if (_texName == null) { throw new LPGException("Texname was null"); } if (_basisDir == null) { throw new LPGException("_basisDir was null"); } if (_stackPanel == null) { throw new LPGException("_stackPanel was null"); } using (var sw = new StreamWriter(_texName)) { if (_dstDir == null) { throw new LPGException("_dstDir was null"); } var overviewName = Path.Combine(_dstDir, "0-overview.png"); Logger.Get().SafeExecuteWithWait(() => { WriteTexBlock(sw, overviewName, "Overview", _typeDescRaw, _basisDir); _elements = new List <UIElement>(); if (_stackPanel == null) { throw new LPGException("Stackpanel was null"); } foreach (var child in _stackPanel.Children) { _elements.Add((UIElement)child); } }); // split everything if (_elements == null) { throw new LPGException("_elements was null"); } foreach (var uiElement in _elements) { var exp = (Expander)uiElement; Logger.Get().SafeExecuteWithWait(() => exp.IsExpanded = true); Thread.Sleep(100); var count1 = count; Logger.Get().SafeExecuteWithWait(() => { var border = (Border)exp.Header; var textblock = (TextBlock)border.Child; _labels.Clear(); FixElements(exp.Content); exp.UpdateLayout(); var blockName = textblock.Text; var cleanblockName = AutomationUtili.CleanFileName(blockName).Replace(" ", string.Empty); if (_dstDir == null) { throw new LPGException("_dstDir was null"); } var blockFileName = Path.Combine(_dstDir, count1 + "-" + cleanblockName + ".png"); if (_basisDir == null) { throw new InvalidOperationException(); } WriteTexBlock(sw, blockFileName, blockName, _typeDescRaw, _basisDir); SnapshotPng(exp, blockFileName); }); count++; } if (_stackPanel == null) { throw new LPGException("_stackpanel was null"); } Logger.Get().SafeExecuteWithWait(() => SnapshotPng(_stackPanel, overviewName)); Logger.Info("Successfully screenshotted " + _typeDescRaw + " to " + _dstDir); } } catch (Exception ex) { Logger.Exception(ex); } }
private string MakeResultFileDirectory([NotNull] MessageFromClientToServer req) { if (_settings.ServerSettings.ResultArchiveDirectory == null) { throw new DistSimException("Result archive dir is null"); } string resultFileArchiveDirectory = _settings.ServerSettings.ResultArchiveDirectory; bool allok = true; if (!string.IsNullOrWhiteSpace(req.Scenario)) { resultFileArchiveDirectory = Path.Combine(resultFileArchiveDirectory, AutomationUtili.CleanFileName(req.Scenario)); } else { allok = false; } if (!string.IsNullOrWhiteSpace(req.Year)) { resultFileArchiveDirectory = Path.Combine(resultFileArchiveDirectory, AutomationUtili.CleanFileName(req.Year)); } else { allok = false; } if (!string.IsNullOrWhiteSpace(req.Trafokreis)) { resultFileArchiveDirectory = Path.Combine(resultFileArchiveDirectory, AutomationUtili.CleanFileName(req.Trafokreis)); } else { allok = false; } if (!string.IsNullOrWhiteSpace(req.HouseName)) { resultFileArchiveDirectory = Path.Combine(resultFileArchiveDirectory, AutomationUtili.CleanFileName(req.HouseName)); } else { allok = false; } if (!allok) { var dt = DateTime.Now; string datetimestr = dt.Year + "." + dt.Month + "." + dt.Day + "-" + dt.Hour + "." + dt.Minute + "." + dt.Second; resultFileArchiveDirectory = Path.Combine(resultFileArchiveDirectory, "Broken", datetimestr); Logger.Error("scenario information was broken, using the following directory instead: " + resultFileArchiveDirectory, _threadId); } Logger.Info("Saving results to: " + resultFileArchiveDirectory, _threadId); if (resultFileArchiveDirectory == _settings.ServerSettings.ResultArchiveDirectory) { throw new DistSimException("Somehow the resultdirectory was the main archive directory. this is wrong."); } Logger.Info("Make result archive directory " + resultFileArchiveDirectory, _threadId); return(resultFileArchiveDirectory); }