public static void ImportHouseholdDefinition([NotNull] HouseholdDefinitionImporterOptions o, [NotNull] string connectionString)
        {
            var sim = new Simulator(connectionString);

            try {
                var sett = ModularHouseholdSerializer.ImportFromCSV(o.File, sim);
                SimIntegrityChecker.Run(sim);
                var bo = new BatchOptions
                {
                    OutputFileDefault = OutputFileDefault.ReasonableWithCharts,
                    EnergyIntensity   = EnergyIntensityType.EnergySavingPreferMeasured
                };
                var count = 1;
                foreach (var settlement in sett)
                {
                    bo.Suffix         = "CSV" + count++;
                    bo.SettlementName = settlement.Name;
                    BatchfileFromSettlement.MakeBatchfileFromSettlement(sim, bo);
                }
            }
            catch (Exception ex) {
                Logger.Exception(ex);
                if (!Config.CatchErrors)
                {
                    throw;
                }
            }
        }
Пример #2
0
        public void CheckSimIntegrityCheckerBenchmark()
        {
            CleanTestBase.RunAutomatically(false);
            const int runcount = 1;

            using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                Simulator sim = new Simulator(db.ConnectionString)
                {
                    MyGeneralConfig = { PerformCleanUpChecks = "True" }
                };
                sim.Should().NotBeNull();
                DateTime start = DateTime.Now;
                for (int i = 0; i < runcount; i++)
                {
                    SimIntegrityChecker.Run(sim);
                }

                DateTime end      = DateTime.Now;
                var      duration = end - start;
                Logger.Info("Duration was:" + duration.TotalMilliseconds / runcount + " milliseconds");
                db.Cleanup();
            }
            CleanTestBase.RunAutomatically(true);
        }
Пример #3
0
 public void RunTest()
 {
     using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         Simulator sim = new Simulator(db.ConnectionString);
         RealisticTraitEstimator.Run(sim);
         SimIntegrityChecker.Run(sim);
         db.Cleanup();
     }
 }
 public void GenerateSettlementPreviewTest()
 {
     using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         var sim      = new Simulator(db.ConnectionString);
         var template = sim.SettlementTemplates.It.First(x => x.Name.StartsWith("H0"));
         var ste      = new SettlementTemplateExecutor();
         ste.GenerateSettlementPreview(sim, template);
         ste.CreateSettlementFromPreview(sim, template);
         SimIntegrityChecker.Run(sim);
         db.Cleanup();
     }
 }
Пример #5
0
#pragma warning restore S125 // Sections of code should not be "commented out"
        public void RunTemplatePersonCreation()
        {
            using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                var sim = new Simulator(db.ConnectionString)
                {
                    MyGeneralConfig = { PerformCleanUpChecks = "False" }
                };
                SimIntegrityChecker.Run(sim);
                TemplatePersonCreator.CreateTemplatePersons(sim);
                db.Cleanup();
            }
        }
 public void RunTest()
 {
     using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         Simulator sim = new Simulator(db.ConnectionString);
         LivingPatternVariationCreator lpvc = new LivingPatternVariationCreator();
         //    lpvc.RunOfficeJobs(sim);
         //  lpvc.RunSleep(sim);
         lpvc.RunAlarm(sim);
         SimIntegrityChecker.Run(sim);
         db.Cleanup();
     }
 }
Пример #7
0
        public void TimeOffsetBugTest()
        {
            Config.AdjustTimesForSettlement = false;
            CleanTestBase.RunAutomatically(false);
            var start = DateTime.Now;

            using (var wd1 = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                var path = wd1.WorkingDirectory;
                Config.MakePDFCharts = false;
                if (Directory.Exists(path))
                {
                    Directory.Delete(path, true);
                }
                Directory.CreateDirectory(path);
                using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
                {
                    var sim       = new Simulator(db.ConnectionString);
                    var calcstart = DateTime.Now;
                    sim.MyGeneralConfig.StartDateUIString      = "1.1.2015";
                    sim.MyGeneralConfig.EndDateUIString        = "31.1.2015";
                    sim.MyGeneralConfig.InternalTimeResolution = "00:01:00";
                    sim.MyGeneralConfig.RandomSeed             = 5;
                    sim.MyGeneralConfig.ApplyOptionDefault(OutputFileDefault.Reasonable);
                    sim.MyGeneralConfig.ShowSettlingPeriod       = "false";
                    sim.MyGeneralConfig.CSVCharacter             = ";";
                    sim.MyGeneralConfig.SelectedLoadTypePriority = LoadTypePriority.RecommendedForHouseholds;
                    SimIntegrityChecker.Run(sim);

                    sim.Should().NotBeNull();

                    var cmf = new CalcManagerFactory();
                    //CalcDevice.UseRanges = true;
                    var geoloc = sim.GeographicLocations.FindFirstByName("Chemnitz", FindMode.Partial);
                    if (geoloc == null)
                    {
                        throw new LPGException("Geoloc was null");
                    }
                    var chh =
                        sim.ModularHouseholds.It.First(x => x.Name.StartsWith("CHR09", StringComparison.Ordinal));
                    CalculationProfiler calculationProfiler = new CalculationProfiler();

                    CalcStartParameterSet csps = new CalcStartParameterSet(geoloc,
                                                                           sim.TemperatureProfiles[0], chh, EnergyIntensityType.Random,
                                                                           false, null,
                                                                           sim.MyGeneralConfig.SelectedLoadTypePriority, null, null, null,
                                                                           sim.MyGeneralConfig.AllEnabledOptions(), new DateTime(2015, 1, 1), new DateTime(2015, 1, 31),
                                                                           new TimeSpan(0, 1, 0), ";", 5, new TimeSpan(0, 1, 0),
                                                                           false, false, false, 3, 3,
                                                                           calculationProfiler, wd1.WorkingDirectory, false);
                    var cm = cmf.GetCalcManager(sim, csps, false);
Пример #8
0
        public void DumpHouseholdContentsToTextTest()
        {
            using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) {
                using (var wd1 = new WorkingDir(Utili.GetCurrentMethodAndClass())) {
                    var sim = new Simulator(db.ConnectionString)
                    {
                        MyGeneralConfig =
                        {
                            StartDateUIString      = "01.01.2015",
                            EndDateUIString        = "02.01.2015",
                            InternalTimeResolution = "00:01:00",
                            ExternalTimeResolution = "00:15:00",
                            RandomSeed             = 5
                        }
                    };
                    sim.MyGeneralConfig.ApplyOptionDefault(OutputFileDefault.NoFiles);
                    sim.MyGeneralConfig.Enable(CalcOption.TotalsPerDevice);
                    sim.MyGeneralConfig.CSVCharacter = ";";
                    //ConfigSetter.SetGlobalTimeParameters(sim.MyGeneralConfig);
                    sim.Should().NotBeNull();
                    SimIntegrityChecker.Run(sim);
                    CalcManagerFactory.DoIntegrityRun = false;

                    var cmf = new CalcManagerFactory();
                    var calculationProfiler = new CalculationProfiler();
                    var csps = new CalcStartParameterSet(sim.GeographicLocations[0], sim.TemperatureProfiles[0], sim.ModularHouseholds[0],
                                                         EnergyIntensityType.Random, false, null, LoadTypePriority.RecommendedForHouses, null, null, null,
                                                         sim.MyGeneralConfig.AllEnabledOptions(), new DateTime(2015, 1, 1), new DateTime(2015, 1, 2), new TimeSpan(0, 1, 0), ";", 5,
                                                         new TimeSpan(0, 15, 0), false, false, false, 3, 3, calculationProfiler, wd1.WorkingDirectory, false);
                    var cm = cmf.GetCalcManager(sim, csps, false);
                    //,, wd1.WorkingDirectory, sim.ModularHouseholds[0], false,
                    //sim.TemperatureProfiles[0], sim.GeographicLocations[0], EnergyIntensityType.Random, version,
                    //LoadTypePriority.RecommendedForHouses, null,null
                    var dls = new DayLightStatus(new BitArray(100));
                    if (cm.CalcObject == null)
                    {
                        throw new LPGException("xxx");
                    }

                    cm.CalcObject.Init(dls, 1);
                    CalcManager.ExitCalcFunction = true;
                    cm.CalcObject.DumpHouseholdContentsToText();
                    cm.Dispose();

                    db.Cleanup();
                    wd1.CleanUp();
                }
            }
        }
Пример #9
0
 public void CheckSimIntegrityCheckerTest()
 {
     CleanTestBase.RunAutomatically(false);
     using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         Simulator sim = new Simulator(db.ConnectionString);
         sim.Should().NotBeNull();
         Vacation vac = sim.Vacations.CreateNewItem(sim.ConnectionString);
         vac.AddVacationTime(new DateTime(2017, 1, 1), new DateTime(2017, 2, 1), VacationType.GoAway);
         vac.AddVacationTime(new DateTime(2017, 2, 1), new DateTime(2017, 2, 15), VacationType.GoAway);
         SimIntegrityChecker.Run(sim);
         db.Cleanup();
     }
     CleanTestBase.RunAutomatically(true);
 }
 private void ReleaseCheck([NotNull] string filename)
 {
     using (var db = new DatabaseSetup("CheckForNewLeftovers", filename))
     {
         var sim = new Simulator(db.ConnectionString);
         CheckForNewItems(sim);
         CheckForDevicesWithoutCategory(sim);
         FindUnusedAffordance(sim);
         FindUnusedDevices(sim);
         //TODO: Add the trait check back
         //FindUnusedTraits(sim);
         sim.MyGeneralConfig.PerformCleanUpChecks = "false";
         SimIntegrityChecker.Run(sim);
         db.Cleanup();
     }
     CheckForCalculationOutcomeCompleteness();
 }
        public void RunHouseholdTemplateCreatorTest()
        {
            using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                var sim  = new Simulator(db.ConnectionString);
                var hhtc = new HouseholdTemplateCreator(sim);
                while (sim.HouseholdTemplates.It.Count > 0)
                {
                    sim.HouseholdTemplates.DeleteItem(sim.HouseholdTemplates.It[0]);
                }

                hhtc.Run(false, sim);

                SimIntegrityChecker.Run(sim);
                db.Cleanup();
            }
        }
Пример #12
0
        public void CompleteAffordanceCreatorTest()
        {
            using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                Simulator        sim       = new Simulator(db.ConnectionString);
                VLoadType        lt        = sim.LoadTypes[0];
                DeviceCategory   dc        = sim.DeviceCategories[1];
                TimeBasedProfile tp        = sim.Timeprofiles[1];
                Location         loc       = sim.Locations[0];
                TraitTag         tag       = sim.TraitTags[0];
                TimeLimit        timeLimit = sim.TimeLimits[0];

                CompleteAffordanceAdd.CreateItems(sim, "aff", "Entertainment / desire", "device", "trait", lt, dc, tp, 1,
                                                  10, 1, 99, loc, tag, "traitclass", timeLimit, "affcategory", null, false, "newLocation");
                SimIntegrityChecker.Run(sim);
                db.Cleanup();
            }
        }
        public static void StartHouse(int house)
        {
            CleanTestBase.RunAutomatically(false);
            var start = DateTime.Now;

            using (var wd1 = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                var path = wd1.WorkingDirectory;
                Config.MakePDFCharts = false;
                using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
                {
                    var sim       = new Simulator(db.ConnectionString);
                    var calcstart = DateTime.Now;
                    sim.MyGeneralConfig.StartDateUIString      = "1.1.2015";
                    sim.MyGeneralConfig.EndDateUIString        = "31.1.2015";
                    sim.MyGeneralConfig.InternalTimeResolution = "00:01:00";
                    sim.MyGeneralConfig.RandomSeed             = 5;
                    sim.MyGeneralConfig.ApplyOptionDefault(OutputFileDefault.NoFiles);
                    sim.MyGeneralConfig.Enable(CalcOption.HouseSumProfilesFromDetailedDats);
                    sim.MyGeneralConfig.CSVCharacter             = ";";
                    sim.MyGeneralConfig.SelectedLoadTypePriority = LoadTypePriority.All;
                    SimIntegrityChecker.Run(sim);
                    //CalcParameters
                    //CalcParametersFactory.SetGlobalTimeParameters(sim.MyGeneralConfig);
                    //ConfigSetter.SetGlobalTimeParameters(sim.MyGeneralConfig);
                    sim.Should().NotBeNull();

                    var cmf = new CalcManagerFactory();
                    //CalcDevice.UseRanges = true;
                    var geoloc = sim.GeographicLocations.FindFirstByName("Chemnitz", FindMode.Partial);
                    if (geoloc == null)
                    {
                        throw new LPGException("Geoloc was null");
                    }
                    var house1 =
                        sim.Houses.It[house];
                    CalculationProfiler   calculationProfiler = new CalculationProfiler();
                    CalcStartParameterSet csps = new CalcStartParameterSet(geoloc,
                                                                           sim.TemperatureProfiles[0], house1, EnergyIntensityType.Random, false,
                                                                           null, LoadTypePriority.All, null, null, null, sim.MyGeneralConfig.AllEnabledOptions(),
                                                                           new DateTime(2015, 1, 1), new DateTime(2015, 1, 31), new TimeSpan(0, 1, 0), ";", 5, new TimeSpan(0, 1, 0), false, false, false, 3, 3,
                                                                           calculationProfiler, path, false);
                    var cm = cmf.GetCalcManager(sim, csps, false);
Пример #14
0
        public void TemplatePersonFullCalculationTest()
        {
            //TODO: fix this test
            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
                {
                    var sim = new Simulator(db.ConnectionString)
                    {
                        MyGeneralConfig = { PerformCleanUpChecks = "False" }
                    };
                    SimIntegrityChecker.Run(sim);
                    var newchh = TemplatePersonCreator.RunCalculationTests(sim);
                    foreach (var household in newchh)
                    {
                        var traits2Delete = new List <ModularHouseholdTrait>();
                        foreach (var modularHouseholdTrait in household.Traits)
                        {
                            if (modularHouseholdTrait.HouseholdTrait.MinimumPersonsInCHH > 1)
                            {
                                traits2Delete.Add(modularHouseholdTrait);
                            }
                        }
                        foreach (var modularHouseholdTrait in traits2Delete)
                        {
                            household.DeleteTraitFromDB(modularHouseholdTrait);
                        }
                    }

                    SimIntegrityChecker.Run(sim);
                    sim.MyGeneralConfig.StartDateUIString      = "1.1.2015";
                    sim.MyGeneralConfig.EndDateUIString        = "5.01.2015";
                    sim.MyGeneralConfig.InternalTimeResolution = "00:01:00";
                    sim.MyGeneralConfig.RandomSeed             = 5;
                    sim.MyGeneralConfig.ApplyOptionDefault(OutputFileDefault.Reasonable);
                    //ChartLocalizer.ShouldTranslate = false;
                    //ConfigSetter.SetGlobalTimeParameters(sim.MyGeneralConfig);
                    sim.Should().NotBeNull();
                    db.Cleanup();
                }
                wd.CleanUp();
            }
        }
Пример #15
0
        public void Run()
        {
            Logger.Info("Starting test");
            using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
                {
                    Directory.SetCurrentDirectory(wd.WorkingDirectory);

                    var sim = new Simulator(db.ConnectionString)
                    {
                        MyGeneralConfig = { PerformCleanUpChecks = "true" }
                    };
                    Logger.Info("First hh");
                    for (var i = 0; i < sim.ModularHouseholds.It.Count && i < 5; i++)
                    {
                        var mhh = sim.ModularHouseholds[i];
                        Logger.Info("exporting and importing " + mhh.Name);
                        var start = DateTime.Now;
                        if (mhh.CreationType != CreationType.ManuallyCreated)
                        {
                            continue;
                        }
                        var filename = Path.Combine(wd.WorkingDirectory, "testexport." + i + ".csv");
                        ModularHouseholdSerializer.ExportAsCSV(mhh, sim, filename);
                        ModularHouseholdSerializer.ImportFromCSV(filename, sim);
                        var import = DateTime.Now;
                        SimIntegrityChecker.Run(sim);
                        var durationTotal          = DateTime.Now - start;
                        var durationIntegrityCheck = DateTime.Now - import;
                        Logger.Info("Duration: total " + durationTotal.TotalSeconds + " seconds, integrity check: " +
                                    durationIntegrityCheck.TotalSeconds);
                    }
                    Logger.Info("finished");
                    Directory.SetCurrentDirectory(wd.PreviousCurrentDir);
                    db.Cleanup();
                    wd.CleanUp(1);
                }
            }
        }
        public void MakeRelease()
        {
            const string filename          = "profilegenerator-latest.db3";
            const bool   cleanDatabase     = true;
            const bool   makeZipAndSetup   = true;
            const bool   cleanCalcOutcomes = true;

            var releasename = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            releasename = releasename.Substring(0, 5);
            var          dst = @"v:\Dropbox\LPGReleases\releases" + releasename;
            const string src = @"C:\Work\LPGDev\ReleaseBuilder\bin\Debug\net48";

            //const string srcsim = @"v:\Dropbox\LPG\SimulationEngine\bin\x64\Debug";

            if (Directory.Exists(dst))
            {
                try
                {
                    Directory.Delete(dst, true);
                }
                catch (Exception ex)
                {
                    Logger.Info(ex.Message);
                }
            }
            Directory.CreateDirectory(dst);
            Thread.Sleep(100);
            CopyFiles(src, dst);
            Thread.Sleep(100);
            // CopyFiles(src, dst);
            ReleaseCheck(filename);
            //CopyFilesSimulationEngine(srcsim, dst);
            using (var db = new DatabaseSetup("Release", filename))
            {
                Logger.Info("Using database " + filename);
#pragma warning disable S2583 // Conditionally executed blocks should be reachable
                if (cleanDatabase)
                {
#pragma warning restore S2583 // Conditionally executed blocks should be reachable
                    //DeleteOldCalcOutcomes(db);
                    DissStuffDatabaseCleaner.Run(db.FileName);
                }
                if (cleanCalcOutcomes)
                {
                    CalculationOutcome.ClearTable(db.ConnectionString);
                }
                var sim = new Simulator(db.ConnectionString);
                sim.MyGeneralConfig.ApplyOptionDefault(OutputFileDefault.ReasonableWithChartsAndPDF);
                sim.MyGeneralConfig.PerformCleanUpChecks = "True";
                sim.MyGeneralConfig.ShowSettlingPeriod   = "False";
                sim.MyGeneralConfig.DestinationPath      = "C:\\Work\\";
                sim.MyGeneralConfig.ImagePath            = "C:\\Work\\";
                sim.MyGeneralConfig.RandomSeed           = -1;
                sim.MyGeneralConfig.StartDateString      = "01.01.2016";
                sim.MyGeneralConfig.EndDateString        = "31.12.2016";
                SimIntegrityChecker.Run(sim);
                sim.MyGeneralConfig.PerformCleanUpChecks = "False";
                sim.MyGeneralConfig.CSVCharacter         = ";";
                var forgottenUpdates = false;
                foreach (var trait in sim.HouseholdTraits.It)
                {
                    switch (trait.Name)
                    {
                    case "Cooking, average":
                    case "Cooking, maximum": continue;

                    default:

                        var count = trait.EstimatedTimeCount;
                        var tt    = trait.EstimatedTimeType;
                        trait.CalculateEstimatedTimes();
                        if (Math.Abs(trait.EstimatedTimeCount - count) > 0.0000001 || trait.EstimatedTimeType != tt)
                        {
                            forgottenUpdates = true;
                            Logger.Error("seems you forgot to update the estimate for " + trait.PrettyName +
                                         Environment.NewLine + "Prev count: " + count + " curr: " +
                                         trait.EstimatedTimeCount + Environment.NewLine + "prev tt: " + tt +
                                         " curr tt: " + trait.EstimatedTimeType);
                        }
                        break;
                    }
                }
                if (forgottenUpdates)
                {
                    throw new LPGException("Forgotten updates!\n" + Logger.Get().ReturnAllLoggedErrors());
                }

                // get rid of all templated items
#pragma warning disable S2583 // Conditions should not unconditionally evaluate to "true" or to "false"
                if (cleanDatabase)
                {
#pragma warning restore S2583 // Conditions should not unconditionally evaluate to "true" or to "false" {
                    var templatedItems = sim.FindAndDeleteAllTemplated();
                    if (templatedItems > 0)
                    {
                        throw new LPGException("Left templated items");
                    }
                }

                File.Copy(db.FileName, Path.Combine(dst, "profilegenerator.db3"));
            }
            Thread.Sleep(1000);

            //CopyFilesSimulationEngine(srcsim, dst);
            if (makeZipAndSetup)
            {
                MakeZipFile(releasename, dst);
                MakeSetup(dst, releasename);
            }
        }
        public void SettlementTemplatePreviewTest()
        {
            using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                var sim = new Simulator(db.ConnectionString);
                var st  = sim.SettlementTemplates.CreateNewItem(sim.ConnectionString);
                st.AddHouseSize(1, 2, 0.50);
                st.AddHouseSize(1, 2, 0.50);
                st.AddHouseType(sim.HouseTypes[0]);
                st.TemperatureProfile = sim.TemperatureProfiles[0];
                st.GeographicLocation = sim.GeographicLocations[0];
                st.DesiredHHCount     = 100;
                var limittrait = sim.HouseholdTraits.FindFirstByName("Showering with electric Air Heater");
                if (limittrait == null)
                {
                    throw new LPGException("Trait not found");
                }
                st.AddTraitLimit(limittrait, 1);
                st.AddHouseholdDistribution(1, 1, 0.95, EnergyIntensityType.EnergyIntensive);
                st.AddHouseholdDistribution(1, 2, 0.05, EnergyIntensityType.EnergySaving);
                st.AddHouseType(sim.HouseTypes[0]);
                foreach (var template in sim.HouseholdTemplates.It)
                {
                    st.AddHouseholdTemplate(template);
                }

                st.GenerateSettlementPreview(sim);
                var i           = 1;
                var traitCounts = new Dictionary <string, int>();
                foreach (var housePreviewEntry in st.HousePreviewEntries)
                {
                    Logger.Info("-------------------");
                    Logger.Info("HousePreviewEntry " + i++);
                    Logger.Info("Households:" + housePreviewEntry.Households.Count + " Housetype:" +
                                housePreviewEntry.HouseType?.Name + " First Housesize:" + housePreviewEntry.HouseSize);
                    var j = 1;
                    foreach (var calcObject in housePreviewEntry.Households)
                    {
                        Logger.Info("#" + j++ + " Persons: " + calcObject.CalculatePersonCount() + ", " +
                                    calcObject.Name + ", " + calcObject.EnergyIntensityType);
                        if (calcObject is ModularHousehold chh)
                        {
                            foreach (var trait in chh.Traits)
                            {
                                var name = trait.HouseholdTrait.Name;
                                if (!traitCounts.ContainsKey(name))
                                {
                                    traitCounts.Add(name, 1);
                                }
                                else
                                {
                                    traitCounts[name] += 1;
                                }
                            }
                        }
                    }
                }
                st.CreateSettlementFromPreview(sim);
                SimIntegrityChecker.Run(sim);
                db.Cleanup();
                foreach (var pair in traitCounts)
                {
                    Logger.Info(pair.Key + ": " + pair.Value);
                }
            }
        }
        public CalcManager GetCalcManager([NotNull] Simulator sim,
                                          [NotNull] CalcStartParameterSet csps, bool forceRandom)
        //, ICalcObject hh,
        //bool forceRandom, TemperatureProfile temperatureProfile,
        //GeographicLocation geographicLocation, EnergyIntensityType energyIntensity,
        //string fileVersion, LoadTypePriority loadTypePriority, [CanBeNull] DeviceSelection deviceSelection,
        //TransportationDeviceSet transportationDeviceSet, TravelRouteSet travelRouteSet,
        //)
        {
            csps.CalculationProfiler.StartPart(Utili.GetCurrentMethodAndClass() + " Initializing");
            if (sim == null)
            {
                throw new LPGException("Simulation was null");
            }

            if (csps.CalcOptions.Contains(CalcOption.LogAllMessages))
            {
                Logger.Get().StartCollectingAllMessages();
            }

            CalcManager cm = null;

            Logger.Info("Starting the calculation of " + csps.CalcTarget.Name);
            try
            {
                if (DoIntegrityRun)
                {
                    SimIntegrityChecker.Run(sim);
                }

                if (csps.CalcTarget.CalcObjectType == CalcObjectType.House &&
                    (csps.LoadTypePriority == LoadTypePriority.RecommendedForHouseholds ||
                     csps.LoadTypePriority == LoadTypePriority.Mandatory))
                {
                    throw new DataIntegrityException(
                              "You are trying to calculate a house with only the load types for a household. This would mess up the warm water calculations. Please fix the load type selection.");
                }

                var chh = csps.CalcTarget as ModularHousehold;

                var ds = GetDeviceSelection(csps, csps.CalcTarget, chh);

                var cpf            = new CalcParametersFactory();
                var calcParameters = cpf.MakeCalculationParametersFromConfig(csps, forceRandom);

                var sqlFileName = Path.Combine(csps.ResultPath, "Results.sqlite");
                var builder     = new ContainerBuilder();
                RegisterEverything(sim, csps.ResultPath, csps, csps.CalcTarget, builder,
                                   sqlFileName, calcParameters, ds);
                csps.CalculationProfiler.StopPart(Utili.GetCurrentMethodAndClass() + " Initializing");
                csps.CalculationProfiler.StartPart(Utili.GetCurrentMethodAndClass() + " Generating Model");
                var container = builder.Build();
                using (var scope = container.BeginLifetimeScope())
                {
                    var calcRepo = PrepareCalculation(sim, csps, scope,
                                                      out var dtoltdict, out var dls, out var variableRepository);
                    cm = new CalcManager(csps.ResultPath,
                                         //hh.Name,
                                         //householdPlans,
                                         //csps.LPGVersion,
                                         calcParameters.ActualRandomSeed, dls, variableRepository, calcRepo
                                         //scope.Resolve<SqlResultLoggingService>()
                                         );
                    //_calcParameters.Logfile = cm.Logfile;
                    //_calcParameters.NormalDistributedRandom = normalDistributedRandom;
                    //_calcParameters.RandomGenerator = randomGenerator;
                    //_calcParameters.Odap = cm.Odap;
                    //_calcParameters.EnergyIntensity = csps.EnergyIntensity;
                    // no vacation times needed for the light array
                    CalcObjectType         cot;
                    ICalcAbleObject        ch;
                    CalcVariableDtoFactory cvrdto            = scope.Resolve <CalcVariableDtoFactory>();
                    CalcDeviceTaggingSets  devicetaggingSets = scope.Resolve <CalcDeviceTaggingSets>();
                    if (csps.CalcTarget.GetType() == typeof(House))
                    {
                        ch = MakeCalcHouseObject(sim, csps, csps.CalcTarget, scope,
                                                 cvrdto, variableRepository, out cot, calcRepo);
                        CalcHouse chd = (CalcHouse)ch;
                        if (chd.EnergyStorages != null)
                        {
                            foreach (var calcEnergyStorage in chd.EnergyStorages)
                            {
                                foreach (var taggingSet in devicetaggingSets.AllCalcDeviceTaggingSets)
                                {
                                    taggingSet.AddTag(calcEnergyStorage.Name, "Energy Storage");
                                }
                            }
                        }
                    }
                    else if (csps.CalcTarget.GetType() == typeof(ModularHousehold))
                    {
                        ch = MakeCalcHouseholdObject(sim, csps, csps.CalcTarget, scope, cvrdto, variableRepository, out cot, calcRepo);
                    }
                    else
                    {
                        throw new LPGException("The type " + csps.CalcTarget.GetType() + " is missing!");
                    }

                    if (calcRepo.CalcParameters.Options.Contains(CalcOption.HouseholdContents))
                    {
                        calcRepo.InputDataLogger.Save(Constants.GeneralHouseholdKey,
                                                      devicetaggingSets.AllCalcDeviceTaggingSets);
                    }

                    CalcObjectInformation coi = new CalcObjectInformation(cot, ch.Name, csps.ResultPath);
                    if (calcRepo.CalcParameters.Options.Contains(CalcOption.HouseholdContents))
                    {
                        calcRepo.InputDataLogger.Save(Constants.GeneralHouseholdKey, coi);
                    }

                    //this logger doesnt save json, but strings!
                    calcRepo.InputDataLogger.Save(Constants.GeneralHouseholdKey, csps);
                    calcRepo.InputDataLogger.Save(Constants.GeneralHouseholdKey, dtoltdict.GetLoadTypeDtos());
                    cm.SetCalcObject(ch);
                    CalcManager.ExitCalcFunction = false;

                    //LogSeed(calcParameters.ActualRandomSeed, lf.FileFactoryAndTracker, calcParameters);
                    csps.CalculationProfiler.StopPart(Utili.GetCurrentMethodAndClass() + " Generating Model");
                    return(cm);
                }
            }
            catch
            {
                cm?.Dispose();
                throw;
            }
        }
Пример #19
0
        public void MakeRelease()
        {
            const string filename          = "profilegenerator-latest.db3";
            const bool   cleanDatabase     = true;
            const bool   makeZipAndSetup   = true;
            const bool   cleanCalcOutcomes = true;

            Logger.Info("### Starting Release");
            var releasename = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            releasename = releasename.Substring(0, 5);
            Logger.Info("Release name: " + releasename);
            //return;
            var dstWin     = @"v:\Dropbox\LPGReleases\releases" + releasename + "\\net48";
            var dstLinux   = @"v:\Dropbox\LPGReleases\releases" + releasename + "\\linux";
            var dstWinCore = @"v:\Dropbox\LPGReleases\releases" + releasename + "\\netCore";

            //const string srcsim = @"v:\Dropbox\LPG\SimulationEngine\bin\x64\Debug";

            PrepareDirectory(dstWin);
            PrepareDirectory(dstLinux);
            PrepareDirectory(dstWinCore);
            const string srclpg = @"C:\Work\LPGDev\WpfApplication1\bin\Debug\net48";

            Logger.Info("### Copying win lpg files");
            var          filesForSetup = WinLpgCopier.CopyLpgFiles(srclpg, dstWin);
            const string srcsim        = @"C:\Work\LPGDev\SimulationEngine\bin\Debug\net48";

            SimEngineCopier.CopySimEngineFiles(srcsim, dstWin);
            const string srcsim2 = @"C:\Work\LPGDev\SimEngine2\bin\Release\netcoreapp3.1\win10-x64";

            SimEngine2Copier.CopySimEngine2Files(srcsim2, dstWinCore);
            const string srcsimLinux = @"C:\Work\LPGDev\SimEngine2\bin\Release\netcoreapp3.1\linux-x64";

            LinuxFileCopier.CopySimEngineLinuxFiles(srcsimLinux, dstLinux);
            Logger.Info("### Finished copying lpg files");
            // CopyFiles(src, dst);
            Logger.Info("### Performing release checks");
            ReleaseCheck(filename);
            //CopyFilesSimulationEngine(srcsim, dst);
            using (var db = new DatabaseSetup("Release", filename))
            {
                Logger.Info("Using database " + filename);
#pragma warning disable S2583 // Conditionally executed blocks should be reachable
                if (cleanDatabase)
                {
#pragma warning restore S2583 // Conditionally executed blocks should be reachable
                    //DeleteOldCalcOutcomes(db);
                    Logger.Info("### cleaning database");
                    DissStuffDatabaseCleaner.Run(db.FileName);
                }
                if (cleanCalcOutcomes)
                {
                    Logger.Info("### cleaning calc outcomes");
                    CalculationOutcome.ClearTable(db.ConnectionString);
                }
                Logger.Info("### integrity check");
                var sim = new Simulator(db.ConnectionString);
                sim.MyGeneralConfig.ApplyOptionDefault(OutputFileDefault.ReasonableWithChartsAndPDF);
                sim.MyGeneralConfig.PerformCleanUpChecks = "True";
                sim.MyGeneralConfig.ShowSettlingPeriod   = "False";
                sim.MyGeneralConfig.DestinationPath      = "C:\\Work\\";
                sim.MyGeneralConfig.ImagePath            = "C:\\Work\\";
                sim.MyGeneralConfig.RandomSeed           = -1;
                sim.MyGeneralConfig.StartDateString      = "01.01.2016";
                sim.MyGeneralConfig.EndDateString        = "31.12.2016";
                SimIntegrityChecker.Run(sim);
                sim.MyGeneralConfig.PerformCleanUpChecks = "False";
                sim.MyGeneralConfig.CSVCharacter         = ";";
                var forgottenUpdates = false;
                Logger.Info("### updating estimates");
                foreach (var trait in sim.HouseholdTraits.It)
                {
                    switch (trait.Name)
                    {
                    case "Cooking, average":
                    case "Cooking, maximum": continue;

                    default:

                        var count = trait.EstimatedTimeCount;
                        var tt    = trait.EstimatedTimeType;
                        trait.CalculateEstimatedTimes();
                        if (Math.Abs(trait.EstimatedTimeCount - count) > 0.0000001 || trait.EstimatedTimeType != tt)
                        {
                            forgottenUpdates = true;
                            Logger.Error("seems you forgot to update the estimate for " + trait.PrettyName +
                                         Environment.NewLine + "Prev count: " + count + " curr: " +
                                         trait.EstimatedTimeCount + Environment.NewLine + "prev tt: " + tt +
                                         " curr tt: " + trait.EstimatedTimeType);
                        }
                        break;
                    }
                }
                if (forgottenUpdates)
                {
                    throw new LPGException("Forgotten updates!\n" + Logger.Get().ReturnAllLoggedErrors());
                }

                // get rid of all templated items
#pragma warning disable S2583 // Conditions should not unconditionally evaluate to "true" or to "false"
                if (cleanDatabase)
                {
                    Logger.Info("### deleting all templated items");
#pragma warning restore S2583 // Conditions should not unconditionally evaluate to "true" or to "false" {
                    var templatedItems = sim.FindAndDeleteAllTemplated();
                    if (templatedItems > 0)
                    {
                        throw new LPGException("Left templated items");
                    }
                }

                File.Copy(db.FileName, Path.Combine(dstWin, "profilegenerator.db3"));
                File.Copy(db.FileName, Path.Combine(dstWinCore, "profilegenerator.db3"));
                File.Copy(db.FileName, Path.Combine(dstLinux, "profilegenerator.db3"));
            }
            Thread.Sleep(1000);
            Logger.Info("### Finished copying all files");
            //CopyFilesSimulationEngine(srcsim, dst);
            if (makeZipAndSetup)
            {
                List <FileInfo> fileForUpload = new List <FileInfo>();
                fileForUpload.Add(MakeZipFile(releasename, dstWin));
                fileForUpload.Add(MakeZipFile(releasename + "_core", dstWinCore));
                fileForUpload.Add(MakeZipFile(releasename + "_linux", dstLinux));
                fileForUpload.Add(MakeSetup(dstWin, releasename, filesForSetup));
                var dstUpload = @"v:\Dropbox\LPGReleases\releases" + releasename + "\\upload";
                PrepareDirectory(dstUpload);
                foreach (FileInfo fi in fileForUpload)
                {
                    string dstName = Path.Combine(dstUpload, fi.Name);
                    fi.CopyTo(dstName, true);
                }
            }
        }