private void BtnCancelClick([CanBeNull] object sender, [CanBeNull] RoutedEventArgs e)
 {
     CalcStarter.CancelRun();
     MessageWindowHandler.Mw.ShowInfoMessage(
         "Stopping calculation... please wait a moment for the current step to finish.", "Please wait.");
     Logger.Info("Canceled the Calculation...");
 }
        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);
            }
        }
        public CalcDataRepository StartHousehold(int householdNumber, [JetBrains.Annotations.NotNull] string csvCharacter,

                                                 LoadTypePriority priority = LoadTypePriority.Mandatory, [CanBeNull] DateTime?enddate = null,
                                                 [CanBeNull] Action <GeneralConfig> configSetter = null,
                                                 EnergyIntensityType energyIntensity             = EnergyIntensityType.EnergyIntensive, bool useHouse = false)
#pragma warning restore RCS1141 // Add parameter to documentation comment.
        {
            Config.IsInUnitTesting = true;
            //string dstDirName;// = "Household" + householdNumber;
            //if (useHouse) {
            //  dstDirName = "House" + householdNumber;
            //}
            //if (directoryName != null) {

            _db = new DatabaseSetup("CalcStarterTests." + _directoryName);
            var sim = new Simulator(_db.ConnectionString)
            {
                MyGeneralConfig = { StartDateDateTime = new DateTime(2012, 1, 1), EndDateDateTime = new DateTime(2012, 1, 31) }
            };

            if (enddate != null)
            {
                sim.MyGeneralConfig.EndDateDateTime = enddate.Value;
            }
            sim.MyGeneralConfig.RandomSeed             = -1;
            sim.MyGeneralConfig.CSVCharacter           = csvCharacter;
            sim.MyGeneralConfig.ExternalTimeResolution = "00:15:00";
            sim.MyGeneralConfig.InternalTimeResolution = "00:01:00";
            sim.MyGeneralConfig.ApplyOptionDefault(OutputFileDefault.NoFiles);
            configSetter?.Invoke(sim.MyGeneralConfig);
            Logger.Info("Enabled options are:");
            foreach (var option in sim.MyGeneralConfig.AllEnabledOptions())
            {
                Logger.Info(option.ToString());
            }
            Logger.Info("External time resolution is: " + sim.MyGeneralConfig.ExternalTimeResolution);

            var cs = new CalcStarter(sim);

            Logger.Info("Number of modular households:" + sim.ModularHouseholds.MyItems.Count);
            if (sim.ModularHouseholds.MyItems.Count <= householdNumber)
            {
                return(null);
            }
            if (
                sim.ModularHouseholds[householdNumber].Description.ToLower(CultureInfo.CurrentCulture)
                .StartsWith("only for modular", StringComparison.Ordinal))
            {
                return(null);
            }
            string workingDir = Wd.WorkingDirectory;
            CalculationProfiler calculationProfiler = new CalculationProfiler();

            if (useHouse)
            {
                var house = sim.Houses.It[householdNumber];

                Logger.Info("CHH Device selection:" + house.Name);

                var cspsHouse = new CalcStartParameterSet(ReportFinishFuncForHouseAndSettlement,
                                                          ReportFinishFuncForHousehold, OpenTabFunc, null, sim.GeographicLocations[0],
                                                          sim.TemperatureProfiles[0], house, energyIntensity, ReportCancelFunc, false,
                                                          null, priority, null, null, sim.MyGeneralConfig.AllEnabledOptions(),
                                                          sim.MyGeneralConfig.StartDateDateTime, sim.MyGeneralConfig.EndDateDateTime, sim.MyGeneralConfig.InternalStepSize,
                                                          ";", -1, new TimeSpan(0, 15, 0), false, false, false, 3, 3, calculationProfiler, null, null,
                                                          DeviceProfileHeaderMode.Standard, false, workingDir, false);
                var duration = cspsHouse.OfficialSimulationEndTime - cspsHouse.OfficialSimulationStartTime;
                if (duration.TotalDays > 370)
                {
                    throw new LPGException("Trying to test with more than 1 year");
                }
                cs.Start(cspsHouse);
                return(null);
            }
            var chh = sim.ModularHouseholds[householdNumber];

            Logger.Info("Modular Household Device selection:" + chh.DeviceSelection?.Name);
            var csps = new CalcStartParameterSet(ReportFinishFuncForHouseAndSettlement,
                                                 ReportFinishFuncForHousehold, OpenTabFunc, null, sim.GeographicLocations[0],
                                                 sim.TemperatureProfiles[0], chh, energyIntensity, ReportCancelFunc, false,
                                                 null, priority, null, null, sim.MyGeneralConfig.AllEnabledOptions(),
                                                 sim.MyGeneralConfig.StartDateDateTime, sim.MyGeneralConfig.EndDateDateTime, sim.MyGeneralConfig.InternalStepSize,
                                                 ";", -1, new TimeSpan(0, 15, 0), false, false, false, 3, 3, calculationProfiler, null, null,
                                                 DeviceProfileHeaderMode.Standard, false, workingDir, false);
            var simduration = csps.OfficialSimulationEndTime - csps.OfficialSimulationStartTime;

            if (simduration.TotalDays > 370)
            {
                throw new LPGException("Trying to test with more than 1 year");
            }
            cs.Start(csps);
            CalcDataRepository cdr = new CalcDataRepository(Wd.SqlResultLoggingService);

            //sim.ModularHouseholds[householdNumber].Name
            return(cdr);
        }
 private void StopCalculationsClick([CanBeNull] object sender, [CanBeNull] RoutedEventArgs e)
 {
     CalcStarter.CancelRun();
     Presenter.InCalculation = false;
 }
Esempio n. 5
0
        public void RunCalcStarter()
        {
            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) {
                using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) {
                    var sim = new Simulator(db.ConnectionString);
                    sim.MyGeneralConfig.StartDateString = "01.01.2013";
                    Config.IsInUnitTesting            = true;
                    Config.ExtraUnitTestChecking      = true;
                    sim.MyGeneralConfig.EndDateString = "02.01.2013";
                    sim.MyGeneralConfig.ApplyOptionDefault(OutputFileDefault.Reasonable);
                    sim.MyGeneralConfig.Enable(CalcOption.TotalsPerLoadtype);
                    sim.MyGeneralConfig.Enable(CalcOption.TotalsPerDevice);
                    sim.MyGeneralConfig.InternalTimeResolution = "00:01:00";
                    var cp   = new CalculationProfiler();
                    var csps = new CalcStartParameterSet(ReportFinishFuncForHouseAndSettlement, ReportFinishFuncForHousehold, OpenTabFunc, null,
                                                         sim.GeographicLocations[0], sim.TemperatureProfiles[0], sim.ModularHouseholds[0], EnergyIntensityType.EnergySaving,
                                                         ReportCancelFunc, false, null, LoadTypePriority.Mandatory, null, null, sim.MyGeneralConfig.AllEnabledOptions(),
                                                         new DateTime(2018, 1, 1), new DateTime(2018, 1, 2), new TimeSpan(0, 1, 0), ";", 5, new TimeSpan(0, 1, 0), false, false, false,
                                                         3, 3, cp, null, null, DeviceProfileHeaderMode.Standard, false, wd.WorkingDirectory, false);
                    var cs = new CalcStarter(sim);
                    cs.Start(csps);

                    /*var dstpath = Path.Combine(wd.WorkingDirectory,
                     *  DirectoryNames.CalculateTargetdirectory(TargetDirectory.Reports), "TotalsPerLoadtype.csv");
                     * using (var sr = new StreamReader(dstpath)) {
                     *  sr.ReadLine();
                     *  while (!sr.EndOfStream) {
                     *      var line = sr.ReadLine();
                     *      if (line == null) {
                     *          throw new LPGException("Result was null");
                     *      }
                     *
                     *      var arr = line.Split(';');
                     *      Logger.Info(line);
                     *      var devicesumFileName = Path.Combine(wd.WorkingDirectory,
                     *          DirectoryNames.CalculateTargetdirectory(TargetDirectory.Reports),
                     *          "DeviceSums." + arr[0] + ".csv");
                     *      using (var devsum = new StreamReader(devicesumFileName)) {
                     *          while (!devsum.EndOfStream) {
                     *              var s = devsum.ReadLine();
                     *              if (s == null) {
                     *                  throw new LPGException("Result was null");
                     *              }
                     *
                     *              if (s.StartsWith("Sums;", StringComparison.Ordinal)) {
                     *                  var sumarr = s.Split(';');
                     *                  Logger.Info("Line from totalsPerLoadType");
                     *                  Logger.Info(line);
                     *                  Logger.Info("Line from " + devicesumFileName);
                     *                  Logger.Info(s);
                     *                  var arr1 = sumarr[1];
                     *                  if (arr1.Length > 6) {
                     *                      arr1 = arr1.Substring(0, 6);
                     *                  }
                     *
                     *                  var arr2 = arr[3];
                     *                  if (arr2.Length > 6) {
                     *                      arr2 = arr2.Substring(0, 6);
                     *                  }
                     *
                     *                  (arr2).Should().Be(arr1);
                     *              }
                     *          }
                     *      }
                     *  }
                     * }*/

                    wd.CleanUp();
                    db.Cleanup();
                }
            }
        }