/*
  * 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"));
         }
     }
 }
Пример #2
0
        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 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);
 }
        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);
        }
Пример #5
0
        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 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 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);
        }
        public void StartHousehold([NotNull] Simulator sim, [NotNull] JsonCalcSpecification jcs, [NotNull] JsonReference calcObjectReference, [CanBeNull] Action <CalculationProfiler, string> makeAllCharts)
        {
            if (!CheckSimulator(jcs, sim))
            {
                throw new LPGPBadParameterException("Invalid simulation state");
            }

            var calcObject = GetCalcObject(sim, calcObjectReference);

            if (jcs.OutputDirectory == null)
            {
                jcs.OutputDirectory = AutomationUtili.CleanFileName(calcObject.Name) + " - " + calcObject;
            }
            _calculationProfiler.StartPart(Utili.GetCurrentMethodAndClass());
            if (calcObjectReference == null)
            {
                throw new LPGException("No calculation object was selected.");
            }
            var calculationStartTime = DateTime.Now;

            if (calcObject == null)
            {
                throw new LPGException("Could not find the Calc Object with the guid " + calcObjectReference.Guid);
            }

            var generalResultsDirectory = new DirectoryInfo(jcs.OutputDirectory ?? throw new LPGException("Output directory was null."));
            var finishedFile            = Path.Combine(generalResultsDirectory.FullName, Constants.FinishedFileFlag);

            if (Directory.Exists(generalResultsDirectory.FullName))
            {
                if (jcs.SkipExisting)
                {
                    if (File.Exists(finishedFile))
                    {
                        Logger.Error("Directory already exists and calculation is finished. Exiting.");
                        _calculationProfiler.StopPart(Utili.GetCurrentMethodAndClass());
                        return;
                    }
                }

                Logger.Warning("Directory already exists, but calculation is not finished or skip existing is not specified. Deleting folder.");
                var files = generalResultsDirectory.GetFiles();
                foreach (FileInfo file in files)
                {
                    if (file.Name.StartsWith("Log.", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }
                    if (file.Name.EndsWith(".db3", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }
                    file.Delete();
                }

                var directories = generalResultsDirectory.GetDirectories();
                foreach (DirectoryInfo info in directories)
                {
                    info.Delete(true);
                }

                Thread.Sleep(1000);
            }

            generalResultsDirectory.Create();
            Thread.Sleep(500);
            Logger.SetLogFilePath(Path.Combine(generalResultsDirectory.FullName, "Log.CommandlineCalculation.txt"));
            Logger.LogToFile = true;
            Logger.Get().FlushExistingMessages();
            Logger.Info("---------------------------");
            Logger.Info("Used calculation specification:");
            Logger.Info(JsonConvert.SerializeObject(jcs, Formatting.Indented), true);
            Logger.Info("---------------------------");
            Logger.Info("Directory: " + generalResultsDirectory.FullName);
            sim.MyGeneralConfig.StartDateUIString      = jcs.StartDate.ToString();
            sim.MyGeneralConfig.EndDateUIString        = jcs.EndDate.ToString();
            sim.MyGeneralConfig.InternalTimeResolution = "00:01:00";
            sim.MyGeneralConfig.DestinationPath        = generalResultsDirectory.FullName;
            sim.MyGeneralConfig.ApplyOptionDefault(jcs.DefaultForOutputFiles);
            if (jcs.CalcOptions != null)
            {
                foreach (var option in jcs.CalcOptions)
                {
                    //var option = option;

                    /*if (option == null) {
                     *  throw  new LPGException("Could not identify Calc Option " + option + ". Stopping.");
                     * }*/
                    Logger.Info("Enabling option " + option);
                    sim.MyGeneralConfig.Enable(option);
                }
            }

            if (jcs.DeleteDAT)
            {
                sim.MyGeneralConfig.DeleteDatFiles = "TRUE";
            }
            else
            {
                sim.MyGeneralConfig.DeleteDatFiles = "FALSE";
            }

            if (jcs.ExternalTimeResolution == null)
            {
                sim.MyGeneralConfig.ExternalTimeResolution = sim.MyGeneralConfig.InternalTimeResolution;
            }
            else
            {
                sim.MyGeneralConfig.ExternalTimeResolution = jcs.ExternalTimeResolution;
            }

            sim.MyGeneralConfig.RandomSeed = jcs.RandomSeed;
            var eit = jcs.EnergyIntensityType;

            if (eit == EnergyIntensityType.AsOriginal)
            {
                eit = calcObject.EnergyIntensityType;
            }

            var cs = new CalcStarter(sim);
            var temperatureProfile = sim.TemperatureProfiles.FindByJsonReference(jcs.TemperatureProfile);

            if (temperatureProfile == null)
            {
                throw new LPGException("Temperature Profile not found.");
            }

            if (jcs.GeographicLocation == null)
            {
                throw new LPGPBadParameterException("No geographic location was set in the calculation request");
            }
            var geographicLocation = sim.GeographicLocations.FindByJsonReference(jcs.GeographicLocation);

            if (geographicLocation == null)
            {
                throw new LPGException("Geographic location not found.");
            }


            DeviceSelection deviceSelection = null;

            if (jcs.DeviceSelection != null)
            {
                deviceSelection = sim.DeviceSelections.FindByJsonReference(jcs.DeviceSelection);
                if (deviceSelection == null)
                {
                    throw new LPGException("Unknown device selection \"" + jcs.DeviceSelection.Guid + "\"");
                }
            }



            if (jcs.EnableTransportation)
            {
            }

            if (jcs.LoadTypePriority == LoadTypePriority.Undefined)
            {
                if (calcObject.CalcObjectType == CalcObjectType.ModularHousehold)
                {
                    jcs.LoadTypePriority = LoadTypePriority.RecommendedForHouseholds;
                }
                else
                {
                    jcs.LoadTypePriority = LoadTypePriority.RecommendedForHouses;
                }
            }

            var options = sim.MyGeneralConfig.AllEnabledOptions();
            //options.Add(CalcOption.OverallDats);
            var calcStartParameterSet = new CalcStartParameterSet(ReportFinishFuncForHouseAndSettlement,
                                                                  ReportFinishFuncForHousehold,
                                                                  OpenTabFunc,
                                                                  null,
                                                                  geographicLocation,
                                                                  temperatureProfile,
                                                                  calcObject,
                                                                  eit,
                                                                  ReportCancelFunc,
                                                                  false,
                                                                  deviceSelection,
                                                                  jcs.LoadTypePriority,
                                                                  null,
                                                                  null,
                                                                  options,
                                                                  sim.MyGeneralConfig.StartDateDateTime,
                                                                  sim.MyGeneralConfig.EndDateDateTime,
                                                                  sim.MyGeneralConfig.InternalStepSize,
                                                                  sim.MyGeneralConfig.CSVCharacter,
                                                                  jcs.RandomSeed,
                                                                  sim.MyGeneralConfig.ExternalStepSize,
                                                                  sim.MyGeneralConfig.DeleteDatFilesBool,
                                                                  sim.MyGeneralConfig.WriteExcelColumnBool,
                                                                  sim.MyGeneralConfig.ShowSettlingPeriodBool,
                                                                  3,
                                                                  sim.MyGeneralConfig.RepetitionCount,
                                                                  _calculationProfiler,
                                                                  null,
                                                                  jcs.LoadtypesForPostprocessing,
                                                                  sim.MyGeneralConfig.DeviceProfileHeaderMode,
                                                                  jcs.IgnorePreviousActivitiesWhenNeeded, jcs.OutputDirectory, jcs.EnableTransportation);

            calcStartParameterSet.PreserveLogfileWhileClearingFolder = true;
            cs.Start(calcStartParameterSet);
            if (jcs.CalcOptions != null && jcs.CalcOptions.Contains(CalcOption.CalculationFlameChart))
            {
                string targetfile = Path.Combine(generalResultsDirectory.FullName, Constants.CalculationProfilerJson);
                using (StreamWriter sw = new StreamWriter(targetfile))
                {
                    _calculationProfiler.WriteJson(sw);
                }
            }
            _calculationProfiler.StopPart(Utili.GetCurrentMethodAndClass());
            if (makeAllCharts != null)
            {
                makeAllCharts(_calculationProfiler, calcStartParameterSet.ResultPath);
            }

            var duration = DateTime.Now - calculationStartTime;

            if (jcs.DeleteAllButPDF)
            {
                var allFileInfos = generalResultsDirectory.GetFiles("*.*", SearchOption.AllDirectories);
                foreach (var fi in allFileInfos)
                {
                    if (fi.Name.ToUpperInvariant().EndsWith(".PDF", StringComparison.Ordinal))
                    {
                        continue;
                    }

                    if (fi.Name.ToUpperInvariant().StartsWith("SUMPROFILES.", StringComparison.Ordinal))
                    {
                        continue;
                    }

                    if (fi.Name.ToUpperInvariant().StartsWith("HOUSEHOLDNAME.", StringComparison.Ordinal))
                    {
                        continue;
                    }

                    fi.Delete();
                }
            }

            if (jcs.DeleteSqlite)
            {
                var allFileInfos = generalResultsDirectory.GetFiles("*.sqlite", SearchOption.AllDirectories);
                GC.Collect();
                GC.WaitForPendingFinalizers();
                foreach (var fi in allFileInfos)
                {
                    try {
                        fi.Delete();
                    }
                    catch (Exception ex) {
                        Logger.Exception(ex);
                    }
                }
            }

            Logger.ImportantInfo("Calculation duration:" + duration);

            //cleanup empty directories
            var subdirs = generalResultsDirectory.GetDirectories();

            foreach (var subdir in subdirs)
            {
                var files      = subdir.GetFiles();
                var subsubdirs = subdir.GetDirectories();
                if (files.Length == 0 && subsubdirs.Length == 0)
                {
                    subdir.Delete();
                }
            }

            using (var sw = new StreamWriter(finishedFile)) {
                sw.WriteLine("Finished at " + DateTime.Now);
                sw.WriteLine("Duration in seconds:");
                sw.WriteLine(duration.TotalSeconds);
            }
        }
Пример #11
0
        private void RunTimePerAffordance(
            [NotNull]
            Dictionary <string, Dictionary <string, Dictionary <string, int> > > affordanceTaggingSetByPersonByTagTimeUse,
            [NotNull] string householdName, [NotNull][ItemNotNull] List <CalcHouseholdPlanDto> householdPlans,
            [NotNull] IFileFactoryAndTracker fft,
            [NotNull] HouseholdKey householdKey,
            [NotNull] Dictionary <Tuple <HouseholdKey, int>, StreamWriter> fileNumberTracker)
        {
            var calcParameters = Repository.CalcParameters;
            var simduration    = calcParameters.OfficialEndTime -
                                 calcParameters.OfficialStartTime;
            var timefactor = 8760 / simduration.TotalHours;

            foreach (var calcHouseholdPlan in householdPlans)
            {
                if (householdName.StartsWith(calcHouseholdPlan.HouseholdName, StringComparison.Ordinal))
                {
                    var cleanedName = AutomationUtili.CleanFileName(calcHouseholdPlan.Name).Replace(".", "_");
                    var fileName    = "HouseholdPlan.Times." + cleanedName + "." + householdKey + ".csv";

                    var fileNumber = fileNumberTracker.Count;

                    var sw = fft.MakeFile <StreamWriter>(fileName,
                                                         "Comparison of the household plan and the reality", true,
                                                         ResultFileID.HouseholdPlanTime, householdKey, TargetDirectory.Reports,
                                                         calcParameters.InternalStepsize, CalcOption.HouseholdPlan, null, null,
                                                         calcHouseholdPlan.Name + "_" + fileNumber);

                    sw.WriteLine("##### Time per Affordance #####");

                    fileNumberTracker.Add(new Tuple <HouseholdKey, int>(householdKey, calcHouseholdPlan.ID), sw);
                    var timeByTagByPerson =
                        affordanceTaggingSetByPersonByTagTimeUse[calcHouseholdPlan.TaggingSetName];
                    foreach (var personTagList in timeByTagByPerson)
                    {
                        var personName = personTagList.Key;
                        sw.WriteLine("----- Time Use for " + personName + " -----");
                        var c = calcParameters.CSVCharacter;
                        sw.WriteLine("Tag" + c + "Time in Simulation [h]" + c + "Time in Simulation for 365d [h]" + c +
                                     "Planned time");
                        var timePerTag        = personTagList.Value;
                        var plannedTimePerTag =
                            calcHouseholdPlan.PersonTagTimeUsePlan[personName];
                        var plannedWithOthers = new Dictionary <string, TimeSpan>();
                        foreach (var keyValuePair in plannedTimePerTag)
                        {
                            plannedWithOthers.Add(keyValuePair.Key, keyValuePair.Value);
                        }

                        foreach (var keyValuePair in timePerTag)
                        {
                            if (!plannedWithOthers.ContainsKey(keyValuePair.Key))
                            {
                                plannedWithOthers.Add(keyValuePair.Key, new TimeSpan(0));
                            }
                        }

                        foreach (var keyValuePair in plannedWithOthers)
                        {
                            var    s = keyValuePair.Key + c;
                            double realValueHours = 0;
                            if (timePerTag.ContainsKey(keyValuePair.Key))
                            {
                                var minutes = timePerTag[keyValuePair.Key];
                                realValueHours = minutes / 60.0;
                            }

                            s += realValueHours + c;
                            s += realValueHours * timefactor + c;
                            s += keyValuePair.Value.TotalHours + c;
                            double percentage = -1;
                            if (Math.Abs(keyValuePair.Value.TotalHours) > Constants.Ebsilon)
                            {
                                percentage = realValueHours / keyValuePair.Value.TotalHours;
                            }

                            s += percentage;
                            if (Math.Abs(realValueHours) > Constants.Ebsilon ||
                                Math.Abs(keyValuePair.Value.TotalSeconds) > Constants.Ebsilon)
                            {
                                sw.WriteLine(s);
                            }
                        }
                    }

                    // found a plan
                }
            }
        }
        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);
        }
        private static void MakeGeneralBarChart([ItemNotNull][JetBrains.Annotations.NotNull] List <AffordanceEntry> entries, [JetBrains.Annotations.NotNull] string dstDir)
        {
            var householdNames = entries.Select(x => x.HouseholdName.Trim()).Distinct().ToList();
            // make absolute values
            var plotModel1 = MakePlotmodel(householdNames,
                                           ChartLocalizer.Get().GetTranslation("Electricity") + " in kWh");
            var affNames = entries.Select(x => x.AffordanceName).Distinct().ToList();

            affNames.Sort((x, y) => string.Compare(x, y, StringComparison.Ordinal));
            OxyPalette p;

            if (affNames.Count < 2)
            {
                p = OxyPalettes.Hue64;
            }
            else
            {
                p = OxyPalettes.HueDistinct(affNames.Count);
            }
            for (var i = 0; i < affNames.Count; i++)
            {
                var tag           = affNames[i];
                var columnSeries2 = new ColumnSeries
                {
                    IsStacked       = true,
                    StackGroup      = "1",
                    StrokeThickness = 1,
                    StrokeColor     = OxyColors.White,
                    Title           = ChartLocalizer.Get().GetTranslation(tag),
                    LabelPlacement  = LabelPlacement.Middle,
                    FillColor       = p.Colors[i]
                };
                foreach (var householdName in householdNames)
                {
                    var te =
                        entries.FirstOrDefault(x => x.AffordanceName == tag && x.HouseholdName == householdName);
                    if (te != null)
                    {
                        columnSeries2.Items.Add(new ColumnItem(te.Value));
                    }
                    else
                    {
                        columnSeries2.Items.Add(new ColumnItem(0));
                    }
                }
                plotModel1.Series.Add(columnSeries2);
            }

            var fileName = Path.Combine(dstDir, "MergedAffordanceEnergyUse.pdf");

            OxyPDFCreator.Run(plotModel1, fileName);
            var hhSums     = new Dictionary <string, double>();
            var households = entries.Select(x => x.HouseholdName).Distinct().ToList();

            foreach (var household in households)
            {
                var sum = entries.Where(x => x.HouseholdName == household).Select(x => x.Value).Sum();
                hhSums.Add(household, sum);
            }
            foreach (var affordanceName in affNames)
            {
                var plotModel2 = MakePlotmodel(householdNames, "Anteil am Gesamtverbrauch in Prozent");
                plotModel2.LegendFontSize = Fontsize;
                var columnSeries2 = new ColumnSeries
                {
                    IsStacked       = true,
                    StackGroup      = "1",
                    StrokeThickness = 1,
                    Title           = ChartLocalizer.Get().GetTranslation(affordanceName),
                    LabelPlacement  = LabelPlacement.Middle,
                    FillColor       = OxyColors.LightBlue
                };
                var averageValue =
                    entries.Where(x => x.AffordanceName == affordanceName)
                    .Select(x => x.Value / hhSums[x.HouseholdName] * 100)
                    .Average();
                var ls = new LineSeries
                {
                    Color = OxyColors.Red,
                    Title = "Durchschnitt"
                };
                for (var i = 0; i < householdNames.Count; i++)
                {
                    var householdName = householdNames[i];
                    ls.Points.Add(new DataPoint(i, averageValue));
                    var te =
                        entries.FirstOrDefault(
                            x => x.AffordanceName == affordanceName && x.HouseholdName == householdName);

                    if (te != null)
                    {
                        columnSeries2.Items.Add(new ColumnItem(te.Value / hhSums[householdName] * 100));
                    }
                    else
                    {
                        columnSeries2.Items.Add(new ColumnItem(0));
                    }
                }
                plotModel2.Series.Add(columnSeries2);
                plotModel2.Series.Add(ls);
                var cleanTag    = AutomationUtili.CleanFileName(affordanceName);
                var relfileName = Path.Combine(dstDir, "MergedAffordanceTaggingEnergyUse." + cleanTag + ".pdf");
                OxyPDFCreator.Run(plotModel2, relfileName);
            }
        }
Пример #14
0
        public static void MakeBatchfileFromSettlement([NotNull] Simulator sim, [NotNull] BatchOptions bo)
        {
            Settlement settlement;

            if (bo.SettlementIndex != null)
            {
                settlement = sim.Settlements[bo.SettlementIndex.Value];
            }
            else if (!string.IsNullOrWhiteSpace(bo.SettlementName))
            {
                settlement = sim.Settlements.FindFirstByName(bo.SettlementName);
                if (settlement == null)
                {
                    throw new LPGException("Could not find the settlement!");
                }
            }
            else
            {
                throw new LPGException(
                          "Neither settlement index or settlement name was set. Please set at least one of the two.");
            }
            Logger.Info("Selected " + settlement.Name);
            var cleanSettlementName = AutomationUtili.CleanFileName(settlement.Name);

            cleanSettlementName = cleanSettlementName.Replace(" ", string.Empty);
            if (cleanSettlementName.Length > 20)
            {
                cleanSettlementName = cleanSettlementName.Substring(0, 20);
            }
            var filename = "Start-" + cleanSettlementName + "." + bo.Suffix + ".cmd";

            using (var sw = new StreamWriter(filename)) {
                var          options      = GetAllOptions(sim, settlement, bo);
                const string start        = "Simulationengine.exe Calculate ";
                var          idx          = 1;
                var          totalentries = settlement.HouseholdCount;
                var          formatstring = "D1";
                if (totalentries > 9)
                {
                    formatstring = "D2";
                }
                if (totalentries > 99)
                {
                    formatstring = "D3";
                }
                if (totalentries > 999)
                {
                    formatstring = "D4";
                }
                foreach (var settlementHH in settlement.Households)
                {
                    for (var i = 0; i < settlementHH.Count; i++)
                    {
                        var outputDir = idx.ToString(formatstring, CultureInfo.CurrentCulture) + "_" +
                                        GetCalcObjectName(settlementHH.Name);
                        var calcobject = string.Empty;
                        if (settlementHH.CalcObjectType == CalcObjectType.ModularHousehold)
                        {
                            var hhindex = sim.ModularHouseholds.It.IndexOf((ModularHousehold)settlementHH.CalcObject);
                            calcobject = "-CalcObjectType ModularHousehold  -CalcObjectNumber " + hhindex +
                                         " -OutputDirectory " + outputDir;
                        }
                        if (settlementHH.CalcObjectType == CalcObjectType.House)
                        {
                            var hhindex = sim.Houses.It.IndexOf((House)settlementHH.CalcObject);
                            calcobject = "-CalcObjectType House  -CalcObjectNumber " + hhindex + " -OutputDirectory " +
                                         outputDir + " -LoadtypePriority RecommendedForHouses ";
                        }
                        var cmdline = start + " " + calcobject + " " + options;
                        while (cmdline.Contains("  "))
                        {
                            cmdline = cmdline.Replace("  ", " ");
                        }
                        sw.WriteLine(cmdline);
                        idx++;
                    }
                }
                sw.Close();
            }

            var settlementIndex = sim.Settlements.It.IndexOf(settlement);

            MakeSettlementJson(settlement, sim, bo, new DirectoryInfo(".").FullName);

            Logger.Info("Finished writing to " + filename);
            var parfilename = "Start-" + cleanSettlementName + "." + bo.Suffix + "Parallel.cmd";

            using (var sw = new StreamWriter(parfilename)) {
                if (string.IsNullOrWhiteSpace(bo.ParallelCores))
                {
                    bo.ParallelCores = Environment.ProcessorCount.ToString(CultureInfo.InvariantCulture);
                }
                sw.WriteLine("Simulationengine.exe LaunchParallel -NumberOfCores " + bo.ParallelCores + " -Batchfile " + filename +
                             " -ArchiveDirectory f:\\" + cleanSettlementName + "_archive");
                sw.WriteLine("Simulationengine.exe ProcessSettlement -Directory . -SettlementIndex " + settlementIndex +
                             " -CheckSettlement ");
                sw.WriteLine("Simulationengine.exe ProcessSettlement -Directory . -AverageSumForDirectory ");
                sw.WriteLine("Simulationengine.exe ProcessSettlement -Directory . -CondenseActionEntries ");
                sw.WriteLine("Simulationengine.exe ProcessSettlement -Directory . -CondenseDeviceSums ");

                //this one is not very useful and takes forever
                sw.WriteLine("# Simulationengine.exe ProcessSettlement -Directory . -MergeActionEntries ");
                //this one is not very useful and takes forever
                sw.WriteLine("# Simulationengine.exe ProcessSettlement -Directory . -MergeAffordanceEnergyUse ");
                sw.WriteLine("# Simulationengine.exe ProcessSettlement -Directory . -MergeAffordanceTagging ");

                sw.WriteLine("# Simulationengine.exe ProcessSettlement -Directory . -MergeDeviceSumProfiles ");
                sw.WriteLine("Simulationengine.exe ProcessSettlement -Directory . -MergeDeviceSums ");
                sw.WriteLine("Simulationengine.exe ProcessSettlement -Directory . -MergeDeviceTagging ");
                sw.WriteLine("Simulationengine.exe ProcessSettlement -Directory . -MergeMulitpleWeekdayProfiles ");
                sw.WriteLine("Simulationengine.exe ProcessSettlement -Directory . -CalcCollectResults ");
            }
        }
        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);
            }
        }
Пример #16
0
        private void MakeBarCharts([JetBrains.Annotations.NotNull] ResultFileEntry rfe, [JetBrains.Annotations.NotNull] string plotName, [JetBrains.Annotations.NotNull] DirectoryInfo basisPath,
                                   [JetBrains.Annotations.NotNull] Dictionary <string, List <TagEntry> > consumption)
        {
            Profiler.StartPart(Utili.GetCurrentMethodAndClass());
            foreach (var pair in consumption)
            {
                var hasReferenceValue = pair.Value.Any(x => x.ReferenceValues.Count > 0);
                if (!hasReferenceValue)
                {
                    continue;
                }
                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;
                var labelFontSize = 12;
                if (Config.MakePDFCharts)
                {
                    plotModel1.DefaultFontSize = Parameters.PDFFontSize;
                    plotModel1.LegendFontSize  = Parameters.PDFFontSize;
                    labelFontSize = 16;
                }
                plotModel1.LegendSymbolMargin = 20;
                if (Parameters.ShowTitle)
                {
                    plotModel1.Title = plotName;
                }

                var categoryAxis1 = new CategoryAxis
                {
                    MinorStep = 1,
                    Minimum   = -0.5
                };
                categoryAxis1.Labels.Add(ChartLocalizer.Get().GetTranslation("Simulated"));
                var firstEntry     = pair.Value[0];
                var referenceCount = firstEntry.ReferenceHeaders.Count;
                for (var i = 0; i < referenceCount; i++)
                {
                    categoryAxis1.Labels.Add(ChartLocalizer.Get().GetTranslation(firstEntry.ReferenceHeaders[i]));
                }
                categoryAxis1.GapWidth       = 1;
                categoryAxis1.MaximumPadding = 0.02;
                categoryAxis1.Position       = AxisPosition.Left;
                plotModel1.Axes.Add(categoryAxis1);

                var sum1 = pair.Value.Select(x => x.Value).Sum();
                var sums = new List <double>();
                foreach (var entry in pair.Value)
                {
                    for (var i = 0; i < entry.ReferenceValues.Count; i++)
                    {
                        if (sums.Count < i + 1)
                        {
                            sums.Add(0);
                        }
                        sums[i] += entry.ReferenceValues[i];
                    }
                }
                var    sum2        = sums.Max();
                var    totalSum    = Math.Max(sum1, sum2);
                string s2          = rfe.LoadTypeInformation?.Name ?? "";
                var    linearAxis1 = new LinearAxis
                {
                    AbsoluteMinimum = 0,
                    MaximumPadding  = 0.02,
                    MinimumPadding  = 0,
                    MajorStep       = totalSum / 5,
                    MinorTickSize   = 0,
                    Position        = AxisPosition.Bottom,
                    Title           = ChartLocalizer.Get().GetTranslation(s2) + " in " + rfe.LoadTypeInformation?.UnitOfSum +
                                      string.Empty
                };
                plotModel1.Axes.Add(linearAxis1);
                OxyPalette p;
                if (pair.Value.Count > 1)
                {
                    p = OxyPalettes.HueDistinct(pair.Value.Count);
                }
                else
                {
                    p = OxyPalettes.Hue64;
                }
                var colSums = new Dictionary <int, double>
                {
                    { 0, 0 },
                    { 1, 0 }
                };
                var count = 0;
                foreach (var tagentry in pair.Value)
                {
                    var columnSeries2 = new BarSeries
                    {
                        FillColor = p.Colors[count]
                    };
                    count++;
                    columnSeries2.IsStacked       = true;
                    columnSeries2.StackGroup      = "1";
                    columnSeries2.StrokeThickness = 1;
                    columnSeries2.StrokeColor     = OxyColor.FromArgb(255, 255, 255, 255);
                    columnSeries2.StrokeThickness = 0.1;
                    columnSeries2.Title           = ChartLocalizer.Get().GetTranslation(tagentry.TagName);
                    columnSeries2.LabelPlacement  = LabelPlacement.Middle;
                    var coli = new BarItem(tagentry.Value);
                    columnSeries2.Items.Add(coli);
                    foreach (var referenceValue in tagentry.ReferenceValues)
                    {
                        var coli2 = new BarItem(referenceValue);
                        columnSeries2.Items.Add(coli2);
                    }
                    var col = 0;
                    if (tagentry.Value / sum1 > 0.2)
                    {
                        var d         = tagentry.Value;
                        var valuetext = d.ToString("N0", CultureInfo.CurrentCulture) + " " + rfe.LoadTypeInformation?.UnitOfSum + " (" +
                                        (d / sum1 * 100).ToString("N1", CultureInfo.CurrentCulture) + " %)";
                        SetRectangelAnnotation(col, colSums, plotModel1, valuetext, d, 0.25, 0.35, labelFontSize);
                        var shortendName = ChartLocalizer.Get().GetTranslation(tagentry.TagName).Trim();
                        if (shortendName.Length > 20)
                        {
                            shortendName = shortendName.Substring(0, 17) + "...";
                        }
                        SetRectangelAnnotation(col, colSums, plotModel1, shortendName, d, 0.35, 0.45, labelFontSize);
                    }
                    col++;
                    double refValue = 0;
                    if (tagentry.ReferenceValues.Count > 0)
                    {
                        refValue = tagentry.ReferenceValues[0];
                    }
                    if (refValue / sum2 > 0.15)
                    {
                        var valueText = refValue.ToString("N0", CultureInfo.CurrentCulture) + " " + rfe.LoadTypeInformation?.UnitOfSum +
                                        " (" + (refValue / sum2 * 100).ToString("N1", CultureInfo.CurrentCulture) +
                                        " %)";
                        SetRectangelAnnotation(col, colSums, plotModel1, valueText, refValue, 0.25, 0.35,
                                               labelFontSize);
                        var labelText = ChartLocalizer.Get().GetTranslation(tagentry.TagName);
                        SetRectangelAnnotation(col, colSums, plotModel1, labelText, refValue, 0.35, 0.45,
                                               labelFontSize);
                    }
                    colSums[0] += tagentry.Value;
                    if (tagentry.ReferenceValues.Count > 0)
                    {
                        colSums[1] += tagentry.ReferenceValues[0];
                    }
                    plotModel1.Series.Add(columnSeries2);
                }
                var fi           = new FileInfo(rfe.FullFileName);
                var modifiedName = fi.Name.Substring(0, fi.Name.Length - 3) + AutomationUtili.CleanFileName(pair.Key) +
                                   ".bars";
                if (fi.DirectoryName == null)
                {
                    throw new LPGException("File was not assigned to a directory");
                }

                var cleanedfullname = Path.Combine(fi.DirectoryName, modifiedName);
                Save(plotModel1, plotName, cleanedfullname, basisPath, CalcOption.HouseholdContents);
            }
            Profiler.StopPart(Utili.GetCurrentMethodAndClass());
        }
Пример #17
0
        private static void MakeBarCharts([JetBrains.Annotations.NotNull] string setName, [ItemNotNull][JetBrains.Annotations.NotNull] List <TagEntry> entries, [JetBrains.Annotations.NotNull] string dstDirectory)
        {
            var householdNames = entries.Select(x => x.HouseholdName.Trim()).Distinct().ToList();
            // make absolute values
            var plotModel1 = MakePlotmodel(householdNames,
                                           ChartLocalizer.Get().GetTranslation("Electricity") + " in kWh");
            var        tagNames = entries.Select(x => x.TagName).Distinct().ToList();
            OxyPalette p;

            if (tagNames.Count < 2)
            {
                p = OxyPalettes.Hue64;
            }
            else
            {
                p = OxyPalettes.HueDistinct(tagNames.Count);
            }
            for (var i = 0; i < tagNames.Count; i++)
            {
                var tag = tagNames[i];

                var columnSeries2 = new ColumnSeries
                {
                    IsStacked       = true,
                    StackGroup      = "1",
                    StrokeThickness = 1,
                    StrokeColor     = OxyColors.White,
                    Title           = ChartLocalizer.Get().GetTranslation(tag),
                    LabelPlacement  = LabelPlacement.Middle,
                    FillColor       = p.Colors[i]
                };
                foreach (var householdName in householdNames)
                {
                    var te = entries.FirstOrDefault(x => x.TagName == tag && x.HouseholdName == householdName);
                    if (te != null)
                    {
                        columnSeries2.Items.Add(new ColumnItem(te.Value));
                    }
                    else
                    {
                        columnSeries2.Items.Add(new ColumnItem(0));
                    }
                }
                plotModel1.Series.Add(columnSeries2);
            }
            var fileName = "MergedDeviceTagging." + setName + ".pdf";

            OxyPDFCreator.Run(plotModel1, fileName);
            var hhSums = new Dictionary <string, double>();

            foreach (var householdName in householdNames)
            {
                var sum = entries.Where(x => x.HouseholdName == householdName).Select(x => x.Value).Sum();
                hhSums.Add(householdName, sum);
            }
            foreach (var tagName in tagNames)
            {
                var plotModel2    = MakePlotmodel(householdNames, "Anteil am Gesamtverbrauch in Prozent");
                var columnSeries2 = new ColumnSeries
                {
                    IsStacked       = true,
                    StackGroup      = "1",
                    StrokeThickness = 1,
                    StrokeColor     = OxyColors.White,
                    Title           = ChartLocalizer.Get().GetTranslation(tagName),
                    LabelPlacement  = LabelPlacement.Middle,
                    FillColor       = OxyColors.LightBlue
                };
                foreach (var householdName in householdNames)
                {
                    var te =
                        entries.FirstOrDefault(x => x.TagName == tagName && x.HouseholdName == householdName);

                    if (te != null)
                    {
                        columnSeries2.Items.Add(new ColumnItem(te.Value / hhSums[householdName] * 100));
                    }
                    else
                    {
                        columnSeries2.Items.Add(new ColumnItem(0));
                    }
                }
                plotModel2.Series.Add(columnSeries2);
                var cleanTag    = AutomationUtili.CleanFileName(tagName);
                var relfileName = Path.Combine(dstDirectory,
                                               "MergedDeviceTagging." + setName + "." + cleanTag + ".pdf");
                OxyPDFCreator.Run(plotModel2, relfileName);
            }
        }
        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);
            }
        }
        public T MakeFile <T>([NotNull] string fileName, [NotNull] string description,
                              bool displayResultFileEntry, ResultFileID rfid1,
                              [NotNull] HouseholdKey householdKey,
                              TargetDirectory targetDirectory, TimeSpan timeResolution,
                              CalcOption enablingOption,
                              [CanBeNull] LoadTypeInformation lti    = null,
                              [CanBeNull] PersonInformation pi       = null,
                              [CanBeNull] string additionalFileIndex = null)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new LPGException("Filename was empty");
            }
            if (!HouseholdRegistry.IsHouseholdRegistered(householdKey))
            {
                throw new LPGException("Forgotten Household Key: " + householdKey);
            }
            if (fileName.Contains(".."))
            {
                throw new LPGException("Filename with two dots. This looks bad. Please fix: " + fileName);
            }
            if (fileName.Contains("  "))
            {
                throw new LPGException("Filename with two spaces. This looks bad. Please fix: " + fileName);
            }
            var    rfid          = rfid1;
            var    cleanFileName = AutomationUtili.CleanFileName(fileName);
            string targetDir     = GetFullPathForTargetdirectry(targetDirectory);

            if (!Directory.Exists(targetDir))
            {
                Directory.CreateDirectory(targetDir);
            }
            var fileInfo = new FileInfo(Path.Combine(targetDir, cleanFileName));

            if (fileInfo.FullName.Length > 250)
            {
                throw new LPGException("The result filename " + fileInfo.FullName + " was longer than 250 characters which is a problem for Windows. Maybe chose a shorter directory name or nest less deep and try again?");
            }
            if (fileInfo.Exists)
            {
                throw new LPGException("The file " + fileInfo.Name + " already exists. Can't create it again!");
            }
            bool tryagain;

            if (!_allValidIds.Contains((int)rfid))
            {
                throw new LPGException("Invalid result file ID");
            }
            do
            {
                try {
                    if (typeof(T) == typeof(StreamWriter))
                    {
                        var stream = _getStream.GetWriterStream(fileInfo.FullName);
#pragma warning disable S2930 // "IDisposables" should be disposed
                        var sw = new StreamWriter(stream);
#pragma warning restore S2930 // "IDisposables" should be disposed
                        var ret = (T)(object)sw;
                        var rfe = new ResultFileEntry(description, fileInfo, displayResultFileEntry, sw,
                                                      null, stream, rfid, _calcObjectName, householdKey.Key,
                                                      lti, pi, additionalFileIndex, timeResolution, enablingOption);
                        ResultFileList.ResultFiles.Add(rfe.HashKey, rfe);
                        _inputDataLogger.Save(rfe);
                        return(ret);
                    }
                    if (typeof(T) == typeof(BinaryWriter))
                    {
                        var stream = _getStream.GetWriterStream(fileInfo.FullName);
#pragma warning disable S2930 // "IDisposables" should be disposed
                        var bw = new BinaryWriter(stream);
#pragma warning restore S2930 // "IDisposables" should be disposed
                        var ret = (T)(object)bw;
                        var rfe = new ResultFileEntry(description, fileInfo, displayResultFileEntry, null, bw,
                                                      stream, rfid, _calcObjectName, householdKey.Key, lti, pi,
                                                      additionalFileIndex, timeResolution, enablingOption);
                        ResultFileList.ResultFiles.Add(rfe.HashKey, rfe);
                        _inputDataLogger.Save(rfe);
                        return(ret);
                    }
                    if (typeof(T) == typeof(Stream))
                    {
                        var stream = _getStream.GetWriterStream(fileInfo.FullName);
                        var ret    = (T)(object)stream;
                        var rfe    = new ResultFileEntry(description, fileInfo, displayResultFileEntry, null, null,
                                                         stream, rfid, _calcObjectName, householdKey.Key, lti, pi,
                                                         additionalFileIndex, timeResolution, enablingOption);
                        ResultFileList.ResultFiles.Add(rfe.HashKey, rfe);
                        _inputDataLogger.Save(rfe);
                        return(ret);
                    }
                    if (typeof(T) == typeof(FileStream))
                    {
                        var stream = _getStream.GetWriterStream(fileInfo.FullName);
                        var ret    = (T)(object)stream;
                        var rfe    = new ResultFileEntry(description, fileInfo, displayResultFileEntry, null, null,
                                                         stream, rfid, _calcObjectName, householdKey.Key, lti, pi,
                                                         additionalFileIndex, timeResolution, enablingOption);
                        ResultFileList.ResultFiles.Add(rfe.HashKey, rfe);
                        _inputDataLogger.Save(rfe);
                        return(ret);
                    }

                    throw new LPGException("Unknown stream type in Makefile<T>");
                }
                catch (IOException ioe) {
                    if (!Config.IsInUnitTesting)
                    {
                        var errormessage = "The file " + fileInfo.FullName +
                                           " could not be opened. The exact error message was:" + Environment.NewLine + ioe.Message +
                                           Environment.NewLine + Environment.NewLine;
                        errormessage += " Maybe you forgot to close Excel? Press YES to try again!";
                        var dr = MessageWindowHandler.Mw.ShowYesNoMessage(errormessage, "Error opening file!");
                        if (dr == LPGMsgBoxResult.Yes)
                        {
                            tryagain = true;
                        }
                        else
                        {
                            tryagain = false;
                        }
                    }
                    else
                    {
                        tryagain = false;
                    }
                }
            } while (tryagain);
            throw new DataIntegrityException("Couldn't open file \"" + fileInfo.FullName + "\". Aborting.");
        }