Exemple #1
0
        public void GetCalcManagerModularHouseholdTest()
        {
            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
                {
                    var            sim   = new Simulator(db.ConnectionString);
                    DeviceCategory light = null;
                    foreach (var deviceCategory in sim.DeviceCategories.MyItems)
                    {
                        deviceCategory.RefreshSubDevices();
                        if (deviceCategory.Name.Contains("Light"))
                        {
                            light = deviceCategory;
                        }
                    }
                    if (light != null)
                    {
                        Logger.Info("Light devices:" + light.SubDevices.Count);
                    }
                    sim.MyGeneralConfig.ApplyOptionDefault(OutputFileDefault.NoFiles);
                    sim.MyGeneralConfig.Enable(CalcOption.OverallSum);
                    sim.Should().NotBeNull();

                    var cmf = new CalcManagerFactory();
                    CalculationProfiler   calculationProfiler = new CalculationProfiler();
                    CalcStartParameterSet csps = new CalcStartParameterSet(sim.GeographicLocations[0],
                                                                           sim.TemperatureProfiles[0], sim.ModularHouseholds[0], EnergyIntensityType.Random, false,
                                                                           null, LoadTypePriority.Mandatory, null, null, null, sim.MyGeneralConfig.AllEnabledOptions(),
                                                                           new DateTime(2015, 1, 15), new DateTime(2015, 1, 18), new TimeSpan(0, 1, 0), ";", -1, new TimeSpan(0, 1, 0), false, false, false, 3, 3,
                                                                           calculationProfiler, wd.WorkingDirectory, false);

                    var cm = cmf.GetCalcManager(sim, csps, false);

                    cm.Run(ReportCancelFunc);
                    db.Cleanup();
                }
                wd.CleanUp();
            }
        }
        private void SetPageState(SplashScreenMessage splashScreenMessage)
        {
            switch (splashScreenMessage.Reason)
            {
            case Messages.Enums.SplashScreenMessageReason.CountrySelected:
                CountrySelection = selectedCountryPersist.Name;

                NavigationService.GoBack();

                DownloadCountryData();
                break;

            case Messages.Enums.SplashScreenMessageReason.FacebookLogin:
            case Messages.Enums.SplashScreenMessageReason.BumbleLogin:
            case Messages.Enums.SplashScreenMessageReason.TwitterLogin:
                base.user = UnitOfWork.UserRepository.GetUser();
                selectedCountryPersist = user.Country;

                DownloadCountryData();
                break;

            case Messages.Enums.SplashScreenMessageReason.ChangeCountry:
                AppCommandMessage.Send(Messages.Enums.AppCommandMessageReason.RemoveBackEntries);

                base.user         = UnitOfWork.UserRepository.GetUser();
                base.user.Country = null;
                UnitOfWork.UserRepository.Update(base.user);
                UnitOfWork.Save();
                resourcesLoaded = false;
                break;

            case Messages.Enums.SplashScreenMessageReason.ResetApp:
                AppCommandMessage.Send(Messages.Enums.AppCommandMessageReason.RemoveBackEntries);

                DatabaseSetup.Seed(UnitOfWork, true);

                resourcesLoaded = false;
                break;
            }
        }
        public void RunModularHouseholdTests()
        {
            using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
                {
                    JsonDatabaseExporter      hte  = new JsonDatabaseExporter(db.ConnectionString);
                    JsonDatabaseExportOptions hteo = new JsonDatabaseExportOptions();
                    string jsonPath = wd.Combine("hhexport.json");
                    hteo.Output         = jsonPath;
                    hteo.ProcessingType = TypesToProcess.ModularHouseholds;
                    hte.Export(hteo);
                    Simulator sim1    = new Simulator(db.ConnectionString);
                    int       hhcount = sim1.ModularHouseholds.It.Count;
                    foreach (ModularHousehold household in sim1.ModularHouseholds.It)
                    {
                        household.DeleteFromDB();
                    }

                    foreach (var house in sim1.Houses.It)
                    {
                        var households = house.Households.ToList();
                        foreach (var household in households)
                        {
                            house.DeleteHouseholdFromDB(household);
                        }
                    }
                    Logger.Info("################################################");
                    Logger.Info("Finished deleting");
                    Logger.Info("################################################");
                    JsonDatabaseImportOptions htio = new JsonDatabaseImportOptions {
                        Input = jsonPath, Type = TypesToProcess.ModularHouseholds
                    };
                    JsonDatabaseImporter hti = new JsonDatabaseImporter(db.ConnectionString);
                    hti.Import(htio);
                    Simulator sim2 = new Simulator(db.ConnectionString);
                    hhcount.Should().Be(sim2.ModularHouseholds.It.Count);
                }
            }
        }
Exemple #4
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 LoadFromDatabaseTest()
 {
     using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         var affdev             = new ObservableCollection <AffordanceDevice>();
         var deviceCategories   = new ObservableCollection <DeviceCategory>();
         var realDevices        = new ObservableCollection <RealDevice>();
         var timeBasedProfiles  = new ObservableCollection <TimeBasedProfile>();
         var affordances        = new ObservableCollection <Affordance>();
         var dateBasedProfiles  = db.LoadDateBasedProfiles();
         var timeLimits         = db.LoadTimeLimits(dateBasedProfiles);
         var loadtypes          = db.LoadLoadTypes();
         var deviceActionGroups = db.LoadDeviceActionGroups();
         var deviceActions      = new ObservableCollection <DeviceAction>();
         db.ClearTable(AffordanceDevice.TableName);
         AffordanceDevice.LoadFromDatabase(affdev, db.ConnectionString, deviceCategories, realDevices,
                                           timeBasedProfiles, affordances, loadtypes, deviceActions, deviceActionGroups, false);
         affdev.Count.Should().Be(0);
         var rd = new RealDevice("blub", 1, "1", null, "name", true, false, db.ConnectionString, Guid.NewGuid().ToStrGuid());
         rd.SaveToDB();
         realDevices.Add(rd);
         var tp = new TimeBasedProfile("blub", null, db.ConnectionString, TimeProfileType.Relative,
                                       "fake", Guid.NewGuid().ToStrGuid());
         tp.SaveToDB();
         timeBasedProfiles.Add(tp);
         var aff = new Affordance("blub", tp, null, true, PermittedGender.All, 0, new ColorRGB(255, 0, 0),
                                  "bla", timeLimits[0], string.Empty, db.ConnectionString, false, false, 0, 99, false,
                                  ActionAfterInterruption.GoBackToOld, false, Guid.NewGuid().ToStrGuid(), BodilyActivityLevel.Low);
         aff.SaveToDB();
         affordances.Add(aff);
         var newaffdev = new AffordanceDevice(rd, tp, null, 0, aff.ID, realDevices, deviceCategories,
                                              "blub", loadtypes[0], db.ConnectionString, 1, Guid.NewGuid().ToStrGuid());
         newaffdev.SaveToDB();
         AffordanceDevice.LoadFromDatabase(affdev, db.ConnectionString, deviceCategories, realDevices,
                                           timeBasedProfiles, affordances, loadtypes, deviceActions, deviceActionGroups, false);
         affdev.Count.Should().Be(1);
         affdev[0].LoadType.Should().Be(loadtypes[0]);
         db.Cleanup();
     }
 }
        public void RunTestCurrentTimeLimits()
        {
            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                var path       = Path.Combine(wd.WorkingDirectory, "profilegeneratorcopy.db3");
                var sourcepath = DatabaseSetup.GetSourcepath(null);

                File.Copy(sourcepath, path);
                if (!File.Exists(path))
                {
                    throw new LPGException("Missing file!");
                }
                using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
                {
                    var mainSim = new Simulator(db.ConnectionString);
                    mainSim.TimeLimits.DeleteItem(mainSim.TimeLimits[0]);
                    mainSim.TimeLimits.DeleteItem(mainSim.TimeLimits[1]);
                    var dbm = new Database.DatabaseMerger.DatabaseMerger(mainSim);
                    dbm.RunFindItems(path, null);
                    Logger.Debug("importing:");
                    foreach (var dbBase in dbm.ItemsToImport)
                    {
                        Logger.Debug("importing:" + Environment.NewLine + dbBase.Entry.Name + " " + dbBase.Import);
                        dbBase.Import = true;
                    }
                    dbm.RunImport(null);
                    var allTimeLimits = new Dictionary <string, bool>();
                    foreach (var timeLimit in mainSim.TimeLimits.MyItems)
                    {
                        allTimeLimits.Add(timeLimit.CombineCompleteString(), true);
                    }
                    foreach (var timeLimit in dbm.OldSimulator.TimeLimits.MyItems)
                    {
                        allTimeLimits.ContainsKey(timeLimit.CombineCompleteString()).Should().BeTrue();
                    }
                    db.Cleanup();
                }
                wd.CleanUp();
            }
        }
        public void HouseGeneratorTestWithPersonSpecAndTransport()
        {
            //setup
            Logger.Get().StartCollectingAllMessages();
            using (WorkingDir workingDir = new WorkingDir(Utili.GetCurrentMethodAndClass())) {
                using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) {
                    Simulator  sim = new Simulator(db.ConnectionString);
                    WorkingDir wd  = workingDir;

                    //housedata
                    HouseData houseData = new HouseData(Guid.NewGuid().ToStrGuid(),
                                                        "HT01", 10000, 1000, "HouseGeneratorJobHouse");
                    var chargingStationSet = sim.ChargingStationSets
                                             .SafeFindByName("Charging At Home with 03.7 kW, output results to Car Electricity")
                                             .GetJsonReference();
                    Logger.Info("Using charging station " + chargingStationSet);
                    var transportationDeviceSet = sim.TransportationDeviceSets[0].GetJsonReference();
                    var travelRouteSet          = sim.TravelRouteSets[0].GetJsonReference();
                    var work          = new TransportationDistanceModifier("Work", "Car", 0);
                    var entertainment = new TransportationDistanceModifier("Entertainment", "Car", 12000);
                    List <TransportationDistanceModifier> tdm = new List <TransportationDistanceModifier>
                    {
                        work, entertainment
                    };
                    var householdData = new HouseholdData(Guid.NewGuid().ToString(),
                                                          "blub", chargingStationSet, transportationDeviceSet,
                                                          travelRouteSet, tdm, HouseholdDataSpecificationType.ByPersons);
                    houseData.Households.Add(householdData);
                    var persons = new List <PersonData> {
                        new PersonData(30, Gender.Male)
                    };
                    householdData.HouseholdDataPersonSpec = new HouseholdDataPersonSpecification(persons);
                    HouseCreationAndCalculationJob houseJob =
                        new HouseCreationAndCalculationJob("present", "2019", "trafokreis",
                                                           HouseDefinitionType.HouseData);
                    houseJob.House = houseData;
                    MakeAndCalculateHouseJob(houseJob, sim, wd, db);
                }
            }
        }
        public void LocationDeviceTest()
        {
            using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                db.ClearTable(LocationDevice.TableName);
                var profiles    = db.LoadTimeBasedProfiles();
                var realDevices = db.LoadRealDevices(out var deviceCategories, out var loadTypes,
                                                     profiles);
                var locdevs = new ObservableCollection <LocationDevice>();
                LocationDevice.LoadFromDatabase(locdevs, db.ConnectionString, realDevices, deviceCategories, loadTypes,
                                                false);
                (locdevs.Count).Should().Be(0);
                var locdev = new LocationDevice(null, realDevices[0], 1, db.ConnectionString,
                                                realDevices[0].Name, Guid.NewGuid().ToStrGuid());
                locdev.SaveToDB();
                LocationDevice.LoadFromDatabase(locdevs, db.ConnectionString, realDevices, deviceCategories, loadTypes,
                                                false);
                (locdevs.Count).Should().Be(1);

                db.Cleanup();
            }
        }
Exemple #9
0
        public void LoadFromDatabaseTest()
        {
            using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                var tps = new ObservableCollection <TimeBasedProfile>();
                TimeBasedProfile.LoadFromDatabase(tps, db.ConnectionString, false);
                tps.Count.Should().BeGreaterThan(1);
                db.ClearTable(TimeBasedProfile.TableName);
                db.ClearTable(TimeDataPoint.TableName);
                tps.Clear();
                var tp = new TimeBasedProfile("hey", null, db.ConnectionString, TimeProfileType.Absolute,
                                              "fake", Guid.NewGuid().ToStrGuid());
                tp.SaveToDB();
                tp.AddNewTimepoint(new TimeSpan(1, 0, 0), 1);
                TimeBasedProfile.LoadFromDatabase(tps, db.ConnectionString, false);

                (tps.Count).Should().Be(1);
                (tps[0].TimeProfileType).Should().Be(TimeProfileType.Absolute);
                (tps[0].ObservableDatapoints.Count).Should().Be(1);
                db.Cleanup();
            }
        }
 public void DateBasedProfileSaveAndRestore()
 {
     using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         db.ClearTable(DateBasedProfile.TableName);
         db.ClearTable(DateProfileDataPoint.TableName);
         var profiles = new ObservableCollection <DateBasedProfile>();
         DateBasedProfile.LoadFromDatabase(profiles, db.ConnectionString, false);
         profiles.Count.Should().Be(0);
         var dbp = new DateBasedProfile("tempprofil1", "desc1", db.ConnectionString, Guid.NewGuid().ToStrGuid());
         dbp.SaveToDB();
         dbp.AddNewDatePoint(new DateTime(2014, 1, 1), 15);
         dbp.AddNewDatePoint(new DateTime(2014, 2, 1), 15);
         dbp.SaveToDB();
         DateBasedProfile.LoadFromDatabase(profiles, db.ConnectionString, false);
         profiles.Count.Should().Be(1);
         profiles[0].Datapoints.Count.Should().Be(2);
         profiles[0].DeleteDatePoint(profiles[0].Datapoints[0]);
         profiles[0].Datapoints.Count.Should().Be(1);
         db.Cleanup();
     }
 }
Exemple #11
0
 public void TravelRouteSetTestImportExport()
 {
     using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         Simulator sim            = new Simulator(db.ConnectionString);
         var       travelrouteset = sim.TravelRouteSets[0];
         //var copy =
         TravelRouteSet.ImportFromItem(travelrouteset, sim);
         //var jsonOriginal = JsonConvert.SerializeObject(travelrouteset, Formatting.Indented,
         //    new JsonSerializerSettings()
         //    {
         //        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
         //    });
         //var jsonCopy = JsonConvert.SerializeObject(copy, Formatting.Indented,
         //    new JsonSerializerSettings()
         //    {
         //        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
         //    });
         db.Cleanup();
     }
     //(jsonCopy).Should().Be(jsonOriginal);
 }
 public void CalculationOutcomeTest()
 {
     Config.ShowDeleteMessages = false;
     Logger.Threshold          = Severity.Error;
     using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         db.ClearTable(CalculationOutcome.TableName);
         db.ClearTable(LoadtypeOutcome.TableName);
         var ca = new CalculationOutcome("1", "2", "3", "4", "5", "6", "7", "8", TimeSpan.FromHours(1),
                                         DateTime.Today, DateTime.Today,
                                         db.ConnectionString, 0, 0, null, Guid.NewGuid().ToStrGuid());
         ca.SaveToDB();
         ca.AddLoadType("bla", 10);
         ca.AddAffordanceTimeUse("bla", "blub", 1, 1);
         var cas = new ObservableCollection <CalculationOutcome>();
         CalculationOutcome.LoadFromDatabase(cas, db.ConnectionString, false);
         (cas.Count).Should().Be(1);
         (cas[0].Entries.Count).Should().Be(1);
         (cas[0].AffordanceTimeUses.Count).Should().Be(1);
         db.Cleanup();
     }
 }
        private static void MakeAndCalculateHouseJob([JetBrains.Annotations.NotNull] HouseCreationAndCalculationJob houseJob,
                                                     [JetBrains.Annotations.NotNull] Simulator sim, [JetBrains.Annotations.NotNull] WorkingDir wd,
                                                     [JetBrains.Annotations.NotNull] DatabaseSetup db)
        {
//calcSpec
            houseJob.CalcSpec = new JsonCalcSpecification {
                DefaultForOutputFiles = OutputFileDefault.Reasonable,
                StartDate             = new DateTime(2017, 1, 1),
                EndDate            = new DateTime(2017, 1, 3),
                GeographicLocation = sim.GeographicLocations.FindFirstByName("Berlin", FindMode.Partial)
                                     ?.GetJsonReference() ??
                                     throw new LPGException("No Berlin in the DB"),
                                           TemperatureProfile = sim.TemperatureProfiles[0].GetJsonReference(),
                                           OutputDirectory    = wd.Combine("Results")
            };
            var dstDir = wd.Combine("profilegenerator.db3");

            File.Copy(db.FileName, dstDir, true);
            houseJob.PathToDatabase = dstDir;

            StartHouseJob(houseJob, wd, "xxx");
        }
 public void GetCalcProfileTest()
 {
     using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         var tp = new TimeBasedProfile("blub", null, db.ConnectionString, TimeProfileType.Relative,
                                       "fake", Guid.NewGuid().ToStrGuid());
         tp.SaveToDB();
         tp.AddNewTimepoint(new TimeSpan(0, 0, 0), 100, false);
         tp.AddNewTimepoint(new TimeSpan(0, 2, 0), 0, false);
         tp.AddNewTimepoint(new TimeSpan(0, 4, 0), 100, false);
         tp.AddNewTimepoint(new TimeSpan(0, 6, 0), 0, false);
         var ctp = CalcDeviceFactory.GetCalcProfile(tp, new TimeSpan(0, 0, 30));
         ctp.TimeSpanDataPoints.Count.Should().Be(4);
         ctp.StepValues.Count.Should().Be(12);
         var v = ctp.StepValues;
         v[0].Should().Be(1);
         v[1].Should().Be(1);
         v[2].Should().Be(1);
         v[3].Should().Be(1);
         db.Cleanup();
     }
 }
        public void ModularHouseholdTest()
        {
            using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                db.ClearTable(ModularHousehold.TableName);
                db.ClearTable(ModularHouseholdTrait.TableName);
                db.ClearTable(ModularHouseholdPerson.TableName);
                var persons         = new ObservableCollection <Person>();
                var result          = new ObservableCollection <ModularHousehold>();
                var householdTraits = new ObservableCollection <HouseholdTrait>();
                var hht             = new HouseholdTrait("blub", null, "blub", db.ConnectionString, "none", 1, 100, 10, 1, 1,
                                                         TimeType.Day, 1, 1, TimeType.Day, 1, 0, EstimateType.Theoretical, "", Guid.NewGuid().ToStrGuid());
                hht.SaveToDB();
                householdTraits.Add(hht);
                var deviceSelections = new ObservableCollection <DeviceSelection>();
                var ds = new DeviceSelection("ds", null, "bla", db.ConnectionString, Guid.NewGuid().ToStrGuid());
                ds.SaveToDB();
                deviceSelections.Add(ds);
                var vacations = db.LoadVacations();
                var hhTags    = db.LoadHouseholdTags();
                var traitTags = db.LoadTraitTags();

                ModularHousehold.LoadFromDatabase(result, db.ConnectionString, householdTraits, deviceSelections, false,
                                                  persons, vacations, hhTags, traitTags);
                (result.Count).Should().Be(0);
                var chh = new ModularHousehold("blub", null, "blub", db.ConnectionString, ds, "src", null, null,
                                               EnergyIntensityType.Random, CreationType.ManuallyCreated, Guid.NewGuid().ToStrGuid());
                chh.SaveToDB();
                chh.AddTrait(hht, ModularHouseholdTrait.ModularHouseholdTraitAssignType.Age, null);
                chh.SaveToDB();
                result.Clear();
                ModularHousehold.LoadFromDatabase(result, db.ConnectionString, householdTraits, deviceSelections, false,
                                                  persons, vacations, hhTags, traitTags);
                (result.Count).Should().Be(1);
                (result[0].Traits.Count).Should().Be(1);
                db.Cleanup();
            }
        }
        public void TransportationDeviceSetTest()
        {
            using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                db.ClearTable(TransportationDeviceSet.TableName);
                db.ClearTable(TransportationDevice.TableName);
                db.ClearTable(TransportationDeviceCategory.TableName);
                TransportationDeviceSet tds =
                    new TransportationDeviceSet("transportationdeviceset", null, db.ConnectionString, "desc",
                                                System.Guid.NewGuid().ToStrGuid());
                tds.SaveToDB();

                TransportationDeviceCategory tdc = new TransportationDeviceCategory("transportationdevicecategory",
                                                                                    null, db.ConnectionString, "desc", true, System.Guid.NewGuid().ToStrGuid());
                tdc.SaveToDB();
                VLoadType vlt = (VLoadType)VLoadType.CreateNewItem(null, db.ConnectionString);
                vlt.SaveToDB();
                TransportationDevice tdev = new TransportationDevice("mydevice", null, db.ConnectionString, "", 1, SpeedUnit.Kmh,
                                                                     tdc, 1000, 10, 100, 100, vlt,
                                                                     System.Guid.NewGuid().ToStrGuid());
                tdev.SaveToDB();
                ObservableCollection <TransportationDevice> transportationDevices = new ObservableCollection <TransportationDevice>
                {
                    tdev
                };
                tds.AddDevice(tdev);

                /*ObservableCollection<TransportationDeviceCategory> categories = new ObservableCollection<TransportationDeviceCategory>
                 * {
                 *  tdc
                 * };*/
                ObservableCollection <TransportationDeviceSet> result = new ObservableCollection <TransportationDeviceSet>();
                TransportationDeviceSet.LoadFromDatabase(result, db.ConnectionString, false, transportationDevices);
                db.Cleanup();
                (result.Count).Should().Be(1);
                (result[0].TransportationDeviceSetEntries.Count).Should().Be(1);
            }
        }
 public void AffordanceVariableTests2()
 {
     using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         db.ClearTable(Affordance.TableName);
         db.ClearTable(AffordanceStandby.TableName);
         db.ClearTable(AffordanceDevice.TableName);
         db.ClearTable(AffordanceDesire.TableName);
         db.ClearTable(AffordanceSubAffordance.TableName);
         db.ClearTable(AffordanceTaggingEntry.TableName);
         db.ClearTable(HHTAffordance.TableName);
         db.ClearTable(AffVariableOperation.TableName);
         var v = new Variable("var1", "desc", "unit", db.ConnectionString, Guid.NewGuid().ToStrGuid());
         v.SaveToDB();
         Config.IsInUnitTesting = true;
         var col = new ColorRGB(255, 0, 0);
         var aff = new Affordance("bla", null, null, true, PermittedGender.Female, 0.1m, col,
                                  "affordanceCategory", null, "desc", db.ConnectionString, true, true, 0, 99, false,
                                  ActionAfterInterruption.GoBackToOld, false, Guid.NewGuid().ToStrGuid(), BodilyActivityLevel.Low);
         aff.SaveToDB();
         aff.ExecutedVariables.Count.Should().Be(0);
         aff.AddVariableOperation(0, VariableLocationMode.CurrentLocation, null, VariableAction.SetTo, v,
                                  string.Empty,
                                  VariableExecutionTime.Beginning);
         aff.SaveToDB();
         aff.ExecutedVariables.Count.Should().Be(1);
         var sim2             = new Simulator(db.ConnectionString);
         var affordanceLoaded = sim2.Affordances.It[0];
         affordanceLoaded.ExecutedVariables.Count.Should().Be(1);
         affordanceLoaded.ExecutedVariables[0].Name.Should().Be("var1");
         affordanceLoaded.DeleteVariableOperation(affordanceLoaded.ExecutedVariables[0]);
         affordanceLoaded.ExecutedVariables.Count.Should().Be(0);
         var sim3 = new Simulator(db.ConnectionString);
         var affordanceLoaded2 = sim3.Affordances.It[0];
         affordanceLoaded2.ExecutedVariables.Count.Should().Be(0);
         db.Cleanup();
     }
 }
        public void LoadFromDatabaseTest()
        {
            using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                GeneralConfig.LoadFromDatabase(db.ConnectionString, false);
                db.ClearTable(GeneralConfig.TableName);
                db.ClearTable(SingleOption.TableName);
                var gc = GeneralConfig.LoadFromDatabase(db.ConnectionString, false);

                // options test
                // first make sure none are enabled after clearing the table
                var count = gc.Options.Count(x => x.Value.SettingValue);
                (count).Should().Be(0);
                // enable one and check
                gc.Enable(CalcOption.OverallDats);
                var count2 = gc.Options.Count(x => x.Value.SettingValue);
                (count2).Should().Be(1);
                var gc2    = GeneralConfig.LoadFromDatabase(db.ConnectionString, false);
                var count3 = gc2.Options.Count(x => x.Value.SettingValue);
                Logger.Info(count3.ToString(CultureInfo.InvariantCulture));
                db.Cleanup();
            }
        }
        public void CSVImportTest()
        {
            using (var db1 = new DatabaseSetup(Utili.GetCurrentMethodAndClass() + "_export"))
            {
                //export
                using (var wd = SetupDB3(Utili.GetCurrentMethodAndClass()))
                {
                    var sim = new Simulator(db1.ConnectionString);
                    ModularHouseholdSerializer.ExportAsCSV(sim.ModularHouseholds[0], sim,
                                                           Path.Combine(wd.WorkingDirectory, "testexportfile.csv"));
                    //import

                    var arguments = new List <string>
                    {
                        "--ImportHouseholdDefinition",
                        "testexportfile.csv"
                    };
                    MainSimEngine.Run(arguments.ToArray(), "simulationengine.exe");
                    db1.Cleanup();
                    wd.CleanUp(1);
                }
            }
        }
Exemple #20
0
        public void RunLocationStatisticsMakerTest()
        {
            using WorkingDir wd    = new WorkingDir(Utili.GetCurrentMethodAndClass());
            using DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass());
            Simulator sim = new Simulator(db.ConnectionString)
            {
                MyGeneralConfig = { StartDateUIString = "15.1.2015", EndDateUIString = "18.1.2015", InternalTimeResolution = "00:01:00" }
            };

            sim.MyGeneralConfig.ApplyOptionDefault(OutputFileDefault.NoFiles);
            sim.MyGeneralConfig.Enable(CalcOption.LocationsFile);
            //ConfigSetter.SetGlobalTimeParameters(sim.MyGeneralConfig);
            sim.Should().NotBeNull();
            sim.MyGeneralConfig.RandomSeed = 10;
            CalcManagerFactory    cmf = new CalcManagerFactory();
            CalculationProfiler   calculationProfiler = new CalculationProfiler();
            CalcStartParameterSet csps = new CalcStartParameterSet(sim.GeographicLocations[0],
                                                                   sim.TemperatureProfiles[0], sim.ModularHouseholds[0],
                                                                   EnergyIntensityType.Random, false, null,
                                                                   LoadTypePriority.All, null, null, null, sim.MyGeneralConfig.AllEnabledOptions(),
                                                                   new DateTime(2015, 1, 15), new DateTime(2015, 1, 18), new TimeSpan(0, 1, 0), ";", 10, new TimeSpan(0, 1, 0), false, false, false, 3, 3,
                                                                   calculationProfiler, wd.WorkingDirectory, false);
            CalcManager cm = cmf.GetCalcManager(sim, csps, false);
 public void LoadFromDatabaseTest()
 {
     using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         ObservableCollection <TraitTag> traitTags = db.LoadTraitTags();
         var timeprofiles = db.LoadTimeBasedProfiles();
         var realDevices  = db.LoadRealDevices(out var deviceCategories, out var loadtypes, timeprofiles);
         var locations    = db.LoadLocations(realDevices, deviceCategories, loadtypes);
         db.LoadTransportation(locations, out var transportationDeviceSets,
                               out var travelRouteSets, out var _,
                               out var _, loadtypes,
                               out var chargingStationSets);
         db.LoadHouseholdsAndHouses(out var modularHouseholds,
                                    out var houses, out var timeLimits, traitTags, chargingStationSets,
                                    travelRouteSets, transportationDeviceSets);
         var settlements        = new ObservableCollection <Settlement>();
         var geoloc             = db.LoadGeographicLocations(out _, timeLimits);
         var temperaturProfiles = db.LoadTemperatureProfiles();
         Settlement.LoadFromDatabase(settlements, db.ConnectionString, temperaturProfiles, geoloc,
                                     modularHouseholds, houses, false);
         db.Cleanup();
     }
 }
        public void RunVacationGetProbabilityRangesTest()
        {
            using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                var sim  = new Simulator(db.ConnectionString);
                var dbp  = sim.DateBasedProfiles.CreateNewItem(sim.ConnectionString);
                var year = DateTime.Now.Year;
                dbp.AddNewDatePoint(new DateTime(year, 1, 1), 0.3);
                dbp.AddNewDatePoint(new DateTime(year, 3, 1), 0.7);
                dbp.AddNewDatePoint(new DateTime(year, 3, 2), 0.6);
                dbp.AddNewDatePoint(new DateTime(year, 8, 1), 0);

                var probabilityarr = dbp.GetValueArray(new DateTime(year, 1, 1), new DateTime(year + 1, 1, 1),
                                                       new TimeSpan(1, 0, 0, 0));
                var result = HouseholdTemplateExecutor.VacationGetProbabilityRanges(probabilityarr, year);
                foreach (var range in result)
                {
                    Logger.Info("Range: " + range.Start + " - " + range.End + " : " + range.Probability);
                }
                (result.Count).Should().Be(dbp.Datapoints.Count - 1);
                db.Cleanup();
            }
        }
Exemple #23
0
 public void VLoadTypeTest()
 {
     using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         db.ClearTable(VLoadType.TableName);
         var loadts = new ObservableCollection <VLoadType>();
         VLoadType.LoadFromDatabase(loadts, db.ConnectionString, false);
         (loadts.Count).Should().Be(0);
         var loadType = new VLoadType("loadtype1", "blub", "bla", "blu", 1000, 1, new TimeSpan(1, 0, 0), 1,
                                      db.ConnectionString, LoadTypePriority.Mandatory, true, Guid.NewGuid().ToStrGuid());
         loadType.SaveToDB();
         VLoadType.LoadFromDatabase(loadts, db.ConnectionString, false);
         (loadts.Count).Should().Be(1);
         var lt = loadts[0];
         lt.Name.Should().Be("loadtype1");
         (lt.Description).Should().Be("blub");
         lt.DeleteFromDB();
         loadts.Clear();
         VLoadType.LoadFromDatabase(loadts, db.ConnectionString, false);
         (loadts.Count).Should().Be(0);
         db.Cleanup();
     }
 }
Exemple #24
0
 public void AffordanceTaggingSetTestNone()
 {
     using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         var sim = new Simulator(db.ConnectionString);
         foreach (var affordanceTaggingSet in sim.AffordanceTaggingSets.MyItems)
         {
             foreach (var affordanceTaggingEntry in affordanceTaggingSet.Entries)
             {
                 if (affordanceTaggingEntry.Tag == null)
                 {
                     throw new LPGException("Tag was null");
                 }
                 if (affordanceTaggingEntry.Tag.Name == "none")
                 {
                     throw new LPGException("None-Tag found in " + affordanceTaggingSet.Name + " for affordance " +
                                            affordanceTaggingEntry.Affordance?.Name);
                 }
             }
         }
         db.Cleanup();
     }
 }
        private async Task SetRunPrerequisites()
        {
            List <Company> documentsToStore = new List <Company>
            {
                new Company {
                    Id = "companies/1", Name = "Name1", Phone = "Phone1"
                },
                new Company {
                    Id = "companies/2", Name = "Name2", Phone = "Phone2"
                },
                new Company {
                    Id = "companies/3", Name = "Name3", Phone = "Phone3"
                },
                new Company {
                    Id = "companies/4", Name = "Name4", Phone = "Phone4"
                },
                new Company {
                    Id = "companies/5", Name = "Name5", Phone = "Phone5"
                }
            };

            await DatabaseSetup.EnsureUserCollectionExists(UserId, documentsToStore);
        }
Exemple #26
0
 public void SiteWithLocationTest()
 {
     using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         db.ClearTable(Site.TableName);
         db.ClearTable(SiteLocation.TableName);
         Location loc = new Location("loc1", null, db.ConnectionString, Guid.NewGuid().ToStrGuid());
         loc.SaveToDB();
         Site site = new Site("site1", null, db.ConnectionString, "desc", Guid.NewGuid().ToStrGuid());
         site.SaveToDB();
         site.AddLocation(loc);
         //loading
         ObservableCollection <Site>     slocs = new ObservableCollection <Site>();
         ObservableCollection <Location> locs  = new ObservableCollection <Location>
         {
             loc
         };
         Site.LoadFromDatabase(slocs, db.ConnectionString,
                               false, locs);
         db.Cleanup();
         (slocs.Count).Should().Be(1);
     }
 }
        public void AffordanceStandbyTests2()
        {
            using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                db.ClearTable(Affordance.TableName);
                db.ClearTable(AffordanceStandby.TableName);
                db.ClearTable(AffordanceDevice.TableName);
                db.ClearTable(AffordanceDesire.TableName);
                db.ClearTable(AffordanceSubAffordance.TableName);
                db.ClearTable(AffordanceTaggingEntry.TableName);
                db.ClearTable(HHTAffordance.TableName);
                db.ClearTable(AffVariableRequirement.TableName);

                Config.IsInUnitTesting = true;
                var col = new ColorRGB(255, 0, 0);
                var aff = new Affordance("bla", null, null, true, PermittedGender.Female, 0.1m, col,
                                         "AffordanceCategory", null, "desc", db.ConnectionString, true, true, 0, 99, false,
                                         ActionAfterInterruption.GoBackToOld, false, Guid.NewGuid().ToStrGuid(), BodilyActivityLevel.Low);
                aff.SaveToDB();
                aff.AffordanceStandbys.Count.Should().Be(0);
                var rd2 = new RealDevice("rd2", 1, string.Empty, null, string.Empty, false, false, db.ConnectionString, Guid.NewGuid().ToStrGuid());
                rd2.SaveToDB();
                aff.AddStandby(rd2);
                aff.SaveToDB();
                aff.AffordanceStandbys.Count.Should().Be(1);
                var sim2             = new Simulator(db.ConnectionString);
                var loadedAffordance = sim2.Affordances.It[0];
                loadedAffordance.AffordanceStandbys.Count.Should().Be(1);
                loadedAffordance.AffordanceStandbys[0].Device?.Name.Should().Be("rd2");
                loadedAffordance.DeleteStandby(loadedAffordance.AffordanceStandbys[0]);
                loadedAffordance.AffordanceStandbys.Count.Should().Be(0);
                var sim3 = new Simulator(db.ConnectionString);
                var affordanceLoaded2 = sim3.Affordances.It[0];
                affordanceLoaded2.AffordanceStandbys.Count.Should().Be(0);
                db.Cleanup();
            }
        }
        public void CalculateMaximumInternalTimeResolutionTestForRealDevice()
        {
            using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                Config.IsInUnitTesting = true;
                var col     = new ColorRGB(255, 0, 0);
                var devices = new ObservableCollection <RealDevice>();
                var rd2     = new RealDevice("rd2", 1, string.Empty, null, string.Empty, false, false, db.ConnectionString, Guid.NewGuid().ToStrGuid());
                rd2.SaveToDB();
                devices.Add(rd2);

                var deviceCategories = new ObservableCollection <DeviceCategory>();
                //var deviceActions = new ObservableCollection<DeviceAction>();
                var aff = new Affordance("bla", null, null, false, PermittedGender.All, 1, col, string.Empty, null,
                                         string.Empty,
                                         db.ConnectionString, true, true, 0, 100, false, ActionAfterInterruption.GoBackToOld, false, Guid.NewGuid().ToStrGuid(),
                                         BodilyActivityLevel.Low);
                aff.SaveToDB();

                var tp = new TimeBasedProfile("tp", null, db.ConnectionString, TimeProfileType.Relative, "fake", Guid.NewGuid().ToStrGuid());
                tp.SaveToDB();
                tp.AddNewTimepoint(new TimeSpan(0, 0, 0), 1, false);
                tp.AddNewTimepoint(new TimeSpan(0, 1, 0), 1, false);
                tp.AddNewTimepoint(new TimeSpan(0, 10, 0), 1, false);

                var lt = new VLoadType("lt", string.Empty, "bla", "blub", 1, 1, new TimeSpan(0, 1, 0), 1,
                                       db.ConnectionString,
                                       LoadTypePriority.Mandatory, true, Guid.NewGuid().ToStrGuid());
                lt.SaveToDB();
                aff.AddDeviceProfile(rd2, tp, 0, devices, deviceCategories, lt, 1);

                var ts = aff.CalculateMaximumInternalTimeResolution();
                (ts.TotalSeconds).Should().Be(60);
                Logger.Info(ts.ToString());
                db.Cleanup();
            }
        }
        public void ModularHouseholdOldImportTest()
        {
            using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                using (var db1 = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
                {
                    var sim1A = new Simulator(db1.ConnectionString);
                    //make the first
                    var tt      = sim1A.ModularHouseholds[0];
                    var jsonHH1 = tt.GetJson();
                    //make a new one, import the first one and compare
                    sim1A.ModularHouseholds.DeleteItem(tt);
                    // ReSharper disable once RedundantAssignment
                    sim1A = null;

                    var sim1B = new Simulator(db1.ConnectionString);
                    using (var db2 = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
                    {
                        //var sim2 = new Simulator(db1.ConnectionString);
                        DatabaseMerger.DatabaseMerger dbm = new DatabaseMerger.DatabaseMerger(sim1B);
                        dbm.RunFindItems(db2.FileName, null);
                        dbm.RunImport(null);
                    }
                    // ReSharper disable once RedundantAssignment
                    sim1B = null;

                    var sim1C   = new Simulator(db1.ConnectionString);
                    var tt2     = sim1C.ModularHouseholds[0];
                    var jsonHH2 = tt2.GetJson();
                    jsonHH2.Should().BeEquivalentTo(jsonHH1, o => o
                                                    .Excluding(x => x.SelectedMemberPath.EndsWith("Guid") ||
                                                               x.SelectedMemberPath.EndsWith("ID")));
                    db1.Cleanup();
                }
                wd.CleanUp(0, false);
            }
        }
        public void RunChargingStationSetTests()
        {
            using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                db.ClearTable(ChargingStationSet.TableName);
                Location loc = new Location("loc1", null, db.ConnectionString, Guid.NewGuid().ToStrGuid());
                loc.SaveToDB();
                ChargingStationSet sl = new ChargingStationSet("blub", null, db.ConnectionString, "desc", Guid.NewGuid().ToStrGuid());
                sl.SaveToDB();
                TransportationDeviceCategory tdc = new TransportationDeviceCategory("tdc", null, db.ConnectionString, "desc", false, Guid.NewGuid().ToStrGuid());
                tdc.SaveToDB();
                VLoadType vlt = (VLoadType)VLoadType.CreateNewItem(s => false, db.ConnectionString);
                vlt.SaveToDB();
                Site site = (Site)Site.CreateNewItem(_ => false, db.ConnectionString);
                site.SaveToDB();
                sl.AddChargingStation(tdc, vlt, 10, site, vlt);

                ObservableCollection <VLoadType> lts = new ObservableCollection <VLoadType>
                {
                    vlt
                };
                ObservableCollection <TransportationDeviceCategory> cats = new ObservableCollection <TransportationDeviceCategory>
                {
                    tdc
                };
                ObservableCollection <ChargingStationSet> css = new ObservableCollection <ChargingStationSet>();
                ObservableCollection <Site> sites             = new ObservableCollection <Site>
                {
                    site
                };
                ChargingStationSet.LoadFromDatabase(css,
                                                    db.ConnectionString, false, lts, cats, sites);
                db.Cleanup();
                (css.Count).Should().Be(1);
                (css[0].ChargingStations.Count).Should().Be(1);
            }
        }