Esempio n. 1
0
        public void OnlineDeviceActivationProcessorArrayTest()
        {
            var rnd = new Random(1);
            var nr  = new NormalRandom(0, 1, rnd);

            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) {
                wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                var calcParameters = CalcParametersFactory.MakeGoodDefaults().EnableShowSettlingPeriod();
                //calcParameters.Enable(CalcOption.ActionsLogfile);
                calcParameters.Enable(CalcOption.DeviceProfilesIndividualHouseholds);
                calcParameters.Enable(CalcOption.DetailedDatFiles);
                using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hh1", wd.InputDataLogger)) {
                    //SqlResultLoggingService srls = new SqlResultLoggingService(Path.Combine(wd.WorkingDirectory, "results.sqlite"));
                    var dsc = new DateStampCreator(calcParameters);

                    using (IOnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters)) {
                        var hhkey = new HouseholdKey("HH1");
                        fft.RegisterHousehold(Constants.GeneralHouseholdKey, "generalhousehold", HouseholdKeyType.General, "Description", null, null);
                        fft.RegisterHousehold(hhkey, "hh1", HouseholdKeyType.Household, "Description", null, null);
                        var odap         = new OnlineDeviceActivationProcessor(old, calcParameters, fft);
                        var deviceGuid   = "devguid".ToStrGuid();
                        var locationGuid = "locationGuid".ToStrGuid();
                        var loadtypeGuid = "ltguid".ToStrGuid();
                        var cdd          = new CalcDeviceDto("devicename", "devcatguid".ToStrGuid(), hhkey, OefcDeviceType.Device, "devcatname", "",
                                                             deviceGuid, locationGuid, "loc");

                        var key = new OefcKey(cdd, loadtypeGuid);
                        var clt = new CalcLoadType("lt1", "W", "kWh", 1, true, loadtypeGuid);
                        odap.RegisterDevice(clt.ConvertToDto(), cdd);
                        double[] stepValues = { 1.0, 0 };
                        var      valueList  = new List <double>(stepValues);
                        var      cp         = new CalcProfile("myCalcProfile", Guid.NewGuid().ToStrGuid(), valueList, ProfileType.Absolute, "synthetic");
                        var      ts1        = new TimeStep(1, 0, false);
                        var      cdl        = new CalcDeviceLoad("", 1, clt, 0, 0);
                        var      sv         = StepValues.MakeStepValues(cp, 10, RandomValueProfile.MakeStepValues(cp.StepValues.Count, nr, 0), cdl);
                        odap.AddNewStateMachine(ts1, clt.ConvertToDto(), "name1", "p1", key, cdd, sv);
                        double[] resultValues = { 0, 10.0, 0, 0, 0, 0, 0, 0, 0, 0 };

                        for (var i = 0; i < 10; i++)
                        {
                            var ts       = new TimeStep(i, 0, true);
                            var filerows = odap.ProcessOneTimestep(ts);
                            filerows.Count.Should().Be(1);
                            filerows[0].EnergyEntries.Count.Should().Be(1);
                            Logger.Info(filerows[0].EnergyEntries[0].ToString(CultureInfo.CurrentCulture));
                            resultValues[i].Should().Be(filerows[0].EnergyEntries[0]);
                            foreach (var fileRow in filerows)
                            {
                                fileRow.Save(odap.BinaryOutStreams[fileRow.LoadType]);
                            }
                        }
                    }
                }

                Logger.Info(wd.WorkingDirectory);
                wd.CleanUp();
            }
        }
        public void RunTransportDecoratorTest()
        {
            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                Config.IsInUnitTesting = true;
                var            rnd            = new Random(1);
                CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults();
                HouseholdKey   key            = new HouseholdKey("hh1");
                using (var calcRepo = SetupFullWorkingTransportationExample(wd, rnd, out _, out var srcloc, out var dstloc, out var dstSite, out var transportationHandler, out var abt, calcParameters, key))
                {
                    //make sure there is a travel route
                    const string personName  = "activator";
                    TimeStep     ts          = new TimeStep(0, 0, false);
                    var          travelroute = transportationHandler.GetTravelRouteFromSrcLoc(srcloc,
                                                                                              dstSite, ts, personName, calcRepo);
                    Assert.NotNull(travelroute);
                    // find if busy
                    var isbusy = abt.IsBusy(ts, srcloc, "", false);
                    isbusy.Should().BeFalse();
                    var affs = dstloc.Affordances.ToList();

                    Logger.Info("Activating affordance for time 0");
                    travelroute.GetDuration(ts, personName, new List <CalcTransportationDevice>());
                    affs[0].Activate(ts, "activator", srcloc, out var _);
                }
                //should throw exception the second time.
                Logger.Info("Activating affordance again for time 0");

                CalcAffordance.DoubleCheckBusyArray = false;
                wd.CleanUp();
            }
        }
Esempio n. 3
0
 public void RegisterDeviceActivationTest()
 {
     using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
     {
         wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
         wd.InputDataLogger.AddSaver(new DeviceActivationEntryLogger(wd.SqlResultLoggingService));
         wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
         CalcParameters cp = CalcParametersFactory.MakeGoodDefaults().EnableShowSettlingPeriod();
         using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hhname", wd.InputDataLogger))
         {
             var key = new HouseholdKey(" hh1");
             fft.HouseholdRegistry.RegisterHousehold(key, "hh key", HouseholdKeyType.Household, wd.InputDataLogger, "desc", null, null);
             fft.HouseholdRegistry.RegisterHousehold(Constants.GeneralHouseholdKey, "general", HouseholdKeyType.General, wd.InputDataLogger, "desc", null, null);
             DateStampCreator dsc = new DateStampCreator(cp);
             using OnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, cp);
             fft.HouseholdRegistry.RegisterHousehold(key, "hh key", HouseholdKeyType.Household, wd.InputDataLogger, "desc", null, null);
             CalcLoadTypeDto clt = new CalcLoadTypeDto("lt", "unitofpower", "unitofsum", 1, true, "guid".ToStrGuid());
             TimeStep        ts  = new TimeStep(1, 1, true);
             CalcDeviceDto   cdd = new CalcDeviceDto("devname", "".ToStrGuid(), key,
                                                     OefcDeviceType.Device, "devcatname", "", Guid.NewGuid().ToStrGuid(), "locguid".ToStrGuid(), "locname");
             DeviceActivationEntry aeue = new DeviceActivationEntry("affname", clt, 1, "activatorname", 1, ts, cdd);
             old.RegisterDeviceActivation(aeue);
             old.FinalSaveToDatabase();
         }
         wd.CleanUp();
     }
 }
        public void CalcAffordanceVariableTestSet()
        {
            var deviceCategoryGuid = Guid.NewGuid().ToStrGuid();
            //var r = new Random(0);
            //var nr = new NormalRandom(0, 0.1, r);
            const int stepcount = 150;

            Config.IsInUnitTesting = true;
            DateTime startdate = new DateTime(2018, 1, 1);
            DateTime enddate   = startdate.AddMinutes(stepcount);
            //_calcParameters.InitializeTimeSteps(startdate, enddate, new TimeSpan(0, 1, 0), 3, false);
            CalcParameters calcParameters =
                CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate);
            var timeStep = new TimeSpan(0, 1, 0);
            var cp       = new CalcProfile("profile", Guid.NewGuid().ToStrGuid(), timeStep, ProfileType.Absolute, "blub");

            cp.AddNewTimepoint(new TimeSpan(0), 100);
            cp.AddNewTimepoint(new TimeSpan(0, 10, 0), 0);
            cp.ConvertToTimesteps();
            var variables    = new List <CalcAffordanceVariableOp>();
            var variableReqs = new List <VariableRequirement>();
            var loc          = new CalcLocation("loc", Guid.NewGuid().ToStrGuid());
            CalcVariableRepository calcVariableRepository = new CalcVariableRepository();
            var          variableGuid = Guid.NewGuid().ToStrGuid();
            HouseholdKey key          = new HouseholdKey("hh1");
            CalcVariable cv           = new CalcVariable("varname", variableGuid, 0, loc.Name, loc.Guid, key);

            calcVariableRepository.RegisterVariable(cv);
            variables.Add(new CalcAffordanceVariableOp(cv.Name, 1, loc, VariableAction.SetTo,
                                                       VariableExecutionTime.Beginning, variableGuid));
            BitArray     isBusy = new BitArray(100, false);
            Random       rnd    = new Random();
            NormalRandom nr     = new NormalRandom(0, 1, rnd);

            using CalcRepo calcRepo = new CalcRepo(calcParameters: calcParameters, odap: new Mock <IOnlineDeviceActivationProcessor>().Object, normalRandom: nr, rnd: rnd);
            var aff = new CalcAffordance("bla", cp, loc, false, new List <CalcDesire>(), 0, 99,
                                         PermittedGender.All, false, 0.1, new ColorRGB(0, 0, 0), "bla", false, false, variables, variableReqs,
                                         ActionAfterInterruption.GoBackToOld, "bla", 100, false, "", Guid.NewGuid().ToStrGuid(),
                                         calcVariableRepository,
                                         new List <CalcAffordance.DeviceEnergyProfileTuple>(), isBusy, BodilyActivityLevel.Low, calcRepo);
            var lt       = new CalcLoadType("load", "unit1", "unit2", 1, true, Guid.NewGuid().ToStrGuid());
            var cdl      = new CalcDeviceLoad("cdl", 1, lt, 1, 0.1);
            var devloads = new List <CalcDeviceLoad> {
                cdl
            };
            CalcDeviceDto cdd = new CalcDeviceDto("device", deviceCategoryGuid, key,
                                                  OefcDeviceType.Device, "category", string.Empty,
                                                  Guid.NewGuid().ToStrGuid(), loc.Guid, loc.Name);
            var cd = new CalcDevice(devloads, loc,
                                    cdd, calcRepo);

            //loc.Variables.Add("Variable1", 0);
            aff.AddDeviceTuple(cd, cp, lt, 0, timeStep, 10, 1);
            TimeStep ts = new TimeStep(0, 0, false);

            aff.IsBusy(ts, loc, "name");
            //var variableOperator = new VariableOperator();
            aff.Activate(ts, "blub", loc, out var _);
            calcVariableRepository.GetValueByGuid(variableGuid).Should().Be(1);
        }
Esempio n. 5
0
        public void CalcPersonDesiresTest()
        {
            CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults();
            var            r = new Random(1);

            using (CalcRepo calcRepo = new CalcRepo(calcParameters: calcParameters, rnd: r))
            {
                var cpd = new CalcPersonDesires(calcRepo);
                var cd1 = new CalcDesire("blub0", 1, 0.5m, 0.1m, 1, 1, 1, -1, null, "", "");
                cpd.AddDesires(cd1);
                var cd2 = new CalcDesire("blub1", 2, 0.5m, 0.1m, 1, 1, 1, -1, null, "", "");
                cpd.AddDesires(cd2);
                Logger.Info("CalcPersonDesiresTest:" + cd1.Value + " ; " + cd2.Value);
                // satisfaction
                var satis1 = new CalcDesire("blub", 1, 0.5m, 12, 1, 1, 60, -1, null, "", "")
                {
                    Value = 1
                };
                var satisfactionValues = new List <CalcDesire>
                {
                    satis1
                };
                Logger.Info(cd1.Value + " ; " + cd2.Value);
                for (var i = 0; i < 20; i++)
                {
                    TimeStep ts = new TimeStep(i, 0, false);
                    cpd.ApplyDecay(ts);
                    cpd.ApplyAffordanceEffect(satisfactionValues, true, "blub");
                    Logger.Info(cd1.Value + " ; " + cd2.Value);
                }
            }
        }
        private static void SaveRun(bool forceRandom,
                                    [NotNull] Simulator sim,
                                    [NotNull] CalcStartParameterSet csps)
        {
            bool allgood = true;

#pragma warning disable 162
            bool success = RunOneCalcEntry(csps, sim, forceRandom);
            if (!success)
            {
                allgood = false;
            }
            //}

            if (!CalcStarter.ContinueRunning)
            {
                csps.ReportCancelFunc?.Invoke();
                return;
            }
#pragma warning restore 162
            if (allgood)
            {
                var cpf            = new CalcParametersFactory();
                var calcParameters = cpf.MakeCalculationParametersFromConfig(csps, forceRandom);
                var cpp            = new DatFileDeletor(calcParameters, csps.ResultPath, csps.CalcTarget.Name);
                cpp.ProcessResults();
                SaveCallFunction(csps.ReportFinishFuncForHousehold, csps);
            }
            else
            {
                throw new LPGException("No Results in CalcQueRunner! Please report this bug.");
            }
        }
        public void RunDoubleActivationTest()
        {
            var rnd = new Random(1);

            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults();
                HouseholdKey   key            = new HouseholdKey("hh1");
                using (var calcRepo = SetupFullWorkingTransportationExample(wd, rnd, out _, out var srcloc, out var dstloc, out var dstSite, out var transportationHandler, out var abt, calcParameters, key))
                {
                    //make sure there is a travel route
                    const string personname  = "activator";
                    TimeStep     ts          = new TimeStep(0, 0, false);
                    var          travelroute = transportationHandler.GetTravelRouteFromSrcLoc(srcloc, dstSite,
                                                                                              ts, personname, calcRepo);
                    Assert.NotNull(travelroute);
                    // find if busy
                    var isbusy = abt.IsBusy(ts, srcloc, personname, false);
                    isbusy.Should().BeFalse();
                    var affs = dstloc.Affordances.ToList();

                    Logger.Info("Activating affordance for time 0");
                    affs[0].Activate(ts, personname, srcloc, out _);
                }
                //should throw exception the second time.
                Logger.Info("Activating affordance again for time 0");
                //this should throw, since it is already busy
                //Assert.Throws<LPGException>(() =>affs[0].Activate(0, "activator", null, srcloc, new Dictionary<int, CalcProfile>(), out _));
                CalcAffordance.DoubleCheckBusyArray = false;
                wd.CleanUp();
            }
        }
Esempio n. 8
0
 public void TestLocationEntryBasics()
 {
     Config.IsInUnitTesting = true;
     using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
     {
         DateTime       startdate      = new DateTime(2018, 1, 1);
         DateTime       enddate        = startdate.AddMinutes(1000);
         CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate).SetSettlingDays(0).EnableShowSettlingPeriod();
         calcParameters.Options.Add(CalcOption.LocationsEntries);
         //FileFactoryAndTracker fft = new FileFactoryAndTracker(wd.WorkingDirectory,"blub",wd.InputDataLogger);
         //CalcLocation cl = new CalcLocation("blub", 1, Guid.NewGuid().ToStrGuid());
         //Mock<ILogFile> lf = new Mock<ILogFile>();
         //CalcPerson cp = MakeCalcPerson(cl,calcParameters,lf.Object);
         HouseholdKey  key = new HouseholdKey("hh1");
         TimeStep      ts  = new TimeStep(1, 0, false);
         LocationEntry le  = new LocationEntry(key, "personName", "personGuid".ToStrGuid(), ts, "locname",
                                               "locguid".ToStrGuid());
         DateStampCreator dsc = new DateStampCreator(calcParameters);
         using (OnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters))
         {
             wd.InputDataLogger.AddSaver(new LocationEntryLogger(wd.SqlResultLoggingService));
             old.AddLocationEntry(le);
             old.FinalSaveToDatabase();
         }
         var lel = new LocationEntryLogger(wd.SqlResultLoggingService);
         var e   = lel.Load(key);
         e.Count.Should().Be(1);
         wd.CleanUp();
     }
 }
        public void PickRandomAffordanceFromEquallyAttractiveOnesTest()
        {
            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) {
                CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults();
                calcParameters.AffordanceRepetitionCount = 0;
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
                using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "blub", wd.InputDataLogger)) {
                    fft.RegisterHousehold(Constants.GeneralHouseholdKey, "general", HouseholdKeyType.General, "desc", null, null);
                    //SqlResultLoggingService srls = new SqlResultLoggingService(wd.WorkingDirectory);
                    //DateStampCreator dsc = new DateStampCreator(calcParameters);
                    Random rnd = new Random();
                    //OnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters);
                    using (var lf = new LogFile(calcParameters, fft)) {
                        CalcProfile            cp  = new CalcProfile("cp1", Guid.NewGuid().ToStrGuid(), TimeSpan.FromMinutes(1), ProfileType.Absolute, "bla");
                        CalcVariableRepository crv = new CalcVariableRepository();
                        BitArray isBusy            = new BitArray(calcParameters.InternalTimesteps, false);
                        using CalcRepo calcRepo = new CalcRepo(lf: lf, calcParameters: calcParameters, rnd: rnd);
                        CalcAffordance aff1 = new CalcAffordance("aff1", cp, null, false, new List <CalcDesire>(), 10, 20, PermittedGender.All, true,
                                                                 1, LPGColors.AliceBlue, null, false, false, null, null, ActionAfterInterruption.GoBackToOld, "", 900, false, "",
                                                                 Guid.NewGuid().ToStrGuid(), crv, new List <CalcAffordance.DeviceEnergyProfileTuple>(), isBusy, BodilyActivityLevel.Low,
                                                                 calcRepo);
                        CalcAffordance aff2 = new CalcAffordance("aff2", cp, null, false, new List <CalcDesire>(), 10, 20, PermittedGender.All, true,
                                                                 1, LPGColors.AliceBlue, null, false, false, null, null, ActionAfterInterruption.GoBackToOld, "", 100, false, "",
                                                                 Guid.NewGuid().ToStrGuid(), crv, new List <CalcAffordance.DeviceEnergyProfileTuple>(), isBusy, BodilyActivityLevel.Low,
                                                                 calcRepo);

                        List <ICalcAffordanceBase> affs = new List <ICalcAffordanceBase> {
                            aff1,
                            aff2
                        };
                        int           aff1C        = 0;
                        int           aff2C        = 0;
                        BitArray      isSick       = new BitArray(calcParameters.InternalTimesteps);
                        BitArray      isOnVacation = new BitArray(calcParameters.InternalTimesteps);
                        CalcPersonDto calcPerson   = CalcPersonDto.MakeExamplePerson();
                        CalcPerson    cperson      = new CalcPerson(calcPerson, null, isSick, isOnVacation, calcRepo);
                        TimeStep      ts           = new TimeStep(1, 0, true);
                        for (int i = 0; i < 1000; i++)
                        {
                            ICalcAffordanceBase cab = cperson.PickRandomAffordanceFromEquallyAttractiveOnes(affs, ts, null, new HouseholdKey("bla"));
                            if (cab == aff1)
                            {
                                aff1C++;
                            }

                            if (cab == aff2)
                            {
                                aff2C++;
                            }
                        }

                        aff1C.Should().BeApproximatelyWithinPercent(900, 0.1);
                        Logger.Info("Number of selections for 90%:" + aff1C + ", 10%:" + aff2C);
                    }
                }
                wd.CleanUp();
            }
        }
        public void ProcessOneTimestepTestVariableFactor()
        {
            var calcParameters = CalcParametersFactory.MakeGoodDefaults();

            using var wd = new WorkingDir(Utili.GetCurrentMethodAndClass());
            wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
            using var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "name", wd.InputDataLogger);
            fft.RegisterGeneralHouse();
            using var old = new OnlineLoggingData(new DateStampCreator(calcParameters), wd.InputDataLogger, calcParameters);
            var odap    = new OnlineDeviceActivationProcessor(old, calcParameters, fft);
            var clt     = new CalcLoadType("clt1", "W", "kWh", 1, true, Guid.NewGuid().ToStrGuid());
            var devguid = Guid.NewGuid().ToStrGuid();
            var locguid = Guid.NewGuid().ToStrGuid();
            var cdd     = new CalcDeviceDto("dev1", "devcatguid".ToStrGuid(), new HouseholdKey("HH1"), OefcDeviceType.Device, "devcatname", "", devguid, locguid,
                                            "loc");
            var key = new OefcKey(cdd, clt.Guid);

            odap.RegisterDevice(clt.ConvertToDto(), cdd);
            double[]       timestepValues = { 0, 5, 10.0, 20, 30, 40, 0 };
            var            cp             = new CalcProfile("myCalcProfile", Guid.NewGuid().ToStrGuid(), timestepValues.ToList(), ProfileType.Absolute, "synthetic");
            var            ts1            = new TimeStep(1, 0, true);
            CalcDeviceLoad cdl            = new CalcDeviceLoad("", 1, clt, 0, 0);
            var            sv             = StepValues.MakeStepValues(cp, 1, RandomValueProfile.MakeStepValues(cp.StepValues.Count, NormalRandom, 0), cdl);

            odap.AddNewStateMachine(ts1, clt.ConvertToDto(), "name1", "p1", key, cdd, sv);
            double[] resultValues = { 0, 0, 5, 10.0, 20, 30, 40, 0 };
            //double[] resultValuesRow1 = {0, 0, 5, 10, 200, 3000, 4000, 0};
            var ctd  = new CalcTransformationDevice(odap, -1, 080, -1000, 1000, cdd, clt);
            var clt2 = new CalcLoadType("clt2", "W2", "kWh2", 1, true, Guid.NewGuid().ToStrGuid());

            ctd.AddOutputLoadType(clt2, 2, TransformationOutputFactorType.Interpolated);

            ctd.AddDatapoint(10, 1);
            ctd.AddDatapoint(20, 10);
            ctd.AddDatapoint(30, 100);
            for (var i = 0; i < resultValues.Length; i++)
            {
                var ts       = new TimeStep(i, calcParameters);
                var filerows = odap.ProcessOneTimestep(ts);
                filerows.Count.Should().Be(2);
                filerows[0].EnergyEntries.Count.Should().Be(1);
                var sb = new StringBuilder("row0 before:");
                sb.Append(filerows[0].EnergyEntries[0]);
                sb.Append(" row1 before:");
                sb.Append(filerows[1].EnergyEntries[0]);
                Assert.Equal(resultValues[i], filerows[0].EnergyEntries[0]);
                Assert.Equal(0, filerows[1].EnergyEntries[0]);
                ctd.ProcessOneTimestep(filerows, null);
                //(filerows[1].EnergyEntries[0]).Should().Be(resultValuesRow1[i]);
                sb.Append(" row0 after:");
                sb.Append(filerows[0].EnergyEntries[0]);
                sb.Append(" row1 after:");
                sb.Append(filerows[1].EnergyEntries[0]);
                Logger.Info(Utili.GetCurrentMethodAndClass() + " " + sb);
            }
        }
Esempio n. 11
0
        public void OnlineDeviceStateMachineTest()
        {
            var            startdate      = new DateTime(2018, 1, 1);
            var            enddate        = startdate.AddMinutes(200);
            CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults()
                                            .SetStartDate(startdate).SetEndDate(enddate).SetSettlingDays(0).EnableShowSettlingPeriod();
            var values = new double[10];

            for (var i = 0; i < values.Length; i++)
            {
                values[i] = i + 1;
                Logger.Info(values[i].ToString(CultureInfo.CurrentCulture));
            }

            var valueList     = new List <double>(values);
            var r             = new Random(1);
            var nr            = new NormalRandom(0, 1, r);
            var devGuid       = Guid.NewGuid().ToStrGuid();
            var locGuid       = Guid.NewGuid().ToStrGuid();
            var clt           = new CalcLoadType("lt", "kWh", "W", 1, true, Guid.NewGuid().ToStrGuid());
            var calcDeviceDto = new CalcDeviceDto("device", devGuid, new HouseholdKey("hh1"), OefcDeviceType.Device,
                                                  "mycategory", "", devGuid, locGuid, "locname");
            var            key  = new OefcKey(calcDeviceDto, locGuid);
            var            cp   = new CalcProfile("mycalcprofile", Guid.NewGuid().ToStrGuid(), valueList, ProfileType.Absolute, "bla");
            TimeStep       ts   = new TimeStep(5, 0, false);
            CalcDeviceLoad cdl  = new CalcDeviceLoad("", 1, clt, 0, 0);
            StepValues     sv   = StepValues.MakeStepValues(cp, 1, RandomValueProfile.MakeStepValues(cp.StepValues.Count, nr, 0), cdl);
            var            odsm = new OnlineDeviceStateMachine(ts, clt.ConvertToDto(), "device", key, "affordance",
                                                               calcParameters, sv, 0);

            calcParameters.SetDummyTimeSteps(0);
            odsm.CalculateOfficialEnergyUse().Should().Be(55); // all
            calcParameters.SetDummyTimeSteps(6);
            odsm.CalculateOfficialEnergyUse().Should().Be(54); // not the first
            //_calcParameters.InternalTimesteps = 20;
            calcParameters.SetDummyTimeSteps(15);
            odsm.CalculateOfficialEnergyUse().Should().Be(0);  // none
            calcParameters.SetDummyTimeSteps(14);
            odsm.CalculateOfficialEnergyUse().Should().Be(10); // only the last
            Logger.Info(odsm.CalculateOfficialEnergyUse().ToString(CultureInfo.CurrentCulture));
            startdate = new DateTime(2018, 1, 1);
            enddate   = startdate.AddMinutes(10);
            calcParameters.DisableShowSettlingPeriod();
            calcParameters.SetStartDate(startdate).SetEndDate(enddate)
            .SetDummyTimeSteps(5);
            odsm.CalculateOfficialEnergyUse().Should().Be(15); // only the first 5
            //_calcParameters.InternalTimesteps = 10; // only 5
            calcParameters.SetDummyTimeSteps(9);
            var val = odsm.CalculateOfficialEnergyUse();

            val.Should().Be(5); // only #5

            Logger.Info(odsm.CalculateOfficialEnergyUse().ToString(CultureInfo.CurrentCulture));
        }
Esempio n. 12
0
        public void SetTimeprofileTest()
        {
            DateTime       startdate      = new DateTime(2018, 1, 1);
            DateTime       enddate        = startdate.AddMinutes(10);
            CalcParameters calcParameters =
                CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate);

            CalcLoadType          clt  = MakeCalcLoadType();
            CalcLocation          cloc = new CalcLocation("blub", Guid.NewGuid().ToStrGuid());
            CalcDeviceLoad        cdl  = new CalcDeviceLoad("cdl1", 1, clt, 1, 0.1);
            List <CalcDeviceLoad> cdls = new List <CalcDeviceLoad>();

            using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                using (FileFactoryAndTracker fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hh1", wd.InputDataLogger))
                {
                    fft.RegisterHousehold(Constants.GeneralHouseholdKey, "General", HouseholdKeyType.General, "desc", null, null);
                    //SqlResultLoggingService srls = new SqlResultLoggingService(wd.WorkingDirectory);
                    DateStampCreator dsc = new DateStampCreator(calcParameters);

                    using (IOnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters))
                    {
                        cdls.Add(cdl);

                        OnlineDeviceActivationProcessor odap =
                            new OnlineDeviceActivationProcessor(old, calcParameters, fft);
                        var           deviceCategoryGuid = Guid.NewGuid().ToStrGuid();
                        CalcDeviceDto cdd = new CalcDeviceDto("bla", deviceCategoryGuid
                                                              , new HouseholdKey("HH-6"), OefcDeviceType.Device, "category",
                                                              string.Empty, Guid.NewGuid().ToStrGuid(), cloc.Guid, cloc.Name);
                        using CalcRepo calcRepo = new CalcRepo(odap: odap, calcParameters: calcParameters, normalRandom: NormalRandom);
                        CalcDevice cd = new CalcDevice(cdls, cloc,
                                                       cdd, calcRepo);
                        CalcProfile cp  = MakeCalcProfile5Min100();
                        TimeStep    ts1 = new TimeStep(1, calcParameters);
                        cd.SetAllLoadTypesToTimeprofile(cp, ts1, "test", "name1", 1);
                        TimeStep ts = new TimeStep(0, calcParameters);
                        cd.IsBusyDuringTimespan(ts, 1, 1, clt).Should().BeFalse();
                        cd.IsBusyDuringTimespan(ts.AddSteps(1), 1, 1, clt).Should().BeTrue();
                        cd.IsBusyDuringTimespan(ts.AddSteps(2), 1, 1, clt).Should().BeTrue();
                        cd.IsBusyDuringTimespan(ts.AddSteps(3), 1, 1, clt).Should().BeTrue();
                        cd.IsBusyDuringTimespan(ts.AddSteps(4), 1, 1, clt).Should().BeTrue();
                        cd.IsBusyDuringTimespan(ts.AddSteps(5), 1, 1, clt).Should().BeTrue();
                        cd.IsBusyDuringTimespan(ts.AddSteps(6), 0, 1, clt).Should().BeFalse();
                    }
                }

                wd.CleanUp();
            }
        }
        public void VariableLogfileTests1()
        {
            using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                wd.InputDataLogger.AddSaver(new VariableEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
                CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().EnableShowSettlingPeriod();
                using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "blub", wd.InputDataLogger))
                {
                    HouseholdKey key = new HouseholdKey("hh1");
                    fft.RegisterGeneralHouse();
                    fft.RegisterHousehold(key, "householdname", HouseholdKeyType.Household, "desc", null, null);
                    DateStampCreator dsc = new DateStampCreator(calcParameters);
                    using (IOnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters))
                    {
                        CalcVariableRepository cvr = new CalcVariableRepository();
                        //using (LogFile lf = new LogFile(calcParameters,fft, old,wd.SqlResultLoggingService, true))
                        CalcLocation cloc = new CalcLocation("loc1", Guid.NewGuid().ToStrGuid());
                        CalcVariable cv   = new CalcVariable("mycalcvar", Guid.NewGuid().ToStrGuid(),
                                                             0, cloc.Name, cloc.Guid, key);
                        cvr.RegisterVariable(cv);
                        TimeStep ts = new TimeStep(0, calcParameters);
                        old.AddVariableStatus(new CalcVariableEntry(cv.Name, cv.Guid, 1, cv.LocationName, cv.LocationGuid,
                                                                    cv.HouseholdKey, ts));
                        old.AddVariableStatus(new CalcVariableEntry(cv.Name, cv.Guid, 2, cv.LocationName, cv.LocationGuid,
                                                                    cv.HouseholdKey, ts));
                        old.AddVariableStatus(new CalcVariableEntry(cv.Name, cv.Guid, 3, cv.LocationName, cv.LocationGuid,
                                                                    cv.HouseholdKey, ts));
                        old.FinalSaveToDatabase();
                    }
                    VariableEntryLogger vel = new VariableEntryLogger(wd.SqlResultLoggingService);
                    var varEntries          = vel.Read(key);
                    foreach (CalcVariableEntry entry in varEntries)
                    {
                        Logger.Info(entry.Value.ToString(CultureInfo.InvariantCulture));
                    }
                    varEntries[0].Value.Should().Be(1);
                    varEntries[1].Value.Should().Be(2);
                    varEntries[2].Value.Should().Be(3);
                }

                /*old.
                 * cloc.Add();
                 * cloc[0].Variables.Add("trig1", 1.0);
                 * tlf.WriteLine(0, cloc);
                 * cloc[0].Variables["trig1"] = 2.0;
                 * tlf.WriteLine(1, cloc);
                 * lf.Close(null);*/
                wd.CleanUp();
            }
        }
        public void AddMoreDesiresTest()
        {
            Config.IsInUnitTesting = true;
            CalcParameters parameters = CalcParametersFactory.MakeGoodDefaults();
            HouseholdKey   key        = new HouseholdKey("hh5");
            var            persons    = new List <ModularHouseholdPerson>();
            var            p          = new Person("blub", 1, 1, 1, 1,
                                                   PermittedGender.Male, string.Empty, string.Empty, Guid.NewGuid().ToStrGuid());
            var tt  = new TraitTag("traittag", "", TraitLimitType.NoLimit, TraitPriority.All, Guid.NewGuid().ToStrGuid());
            var mhp = new ModularHouseholdPerson(null, -1, p.PrettyName, "", p, tt, Guid.NewGuid().ToStrGuid());

            persons.Add(mhp);
            var          hhVacations = new List <VacationTimeframe>();
            Random       r           = new Random(1);
            NormalRandom nr          = new NormalRandom(0, 1, r);
            //DeviceCategoryPicker picker = new DeviceCategoryPicker(r,null);
            //var parameters = new CalcFactoryParameters(picker);
            //CalcFactoryParameters.SetSkipChecking(true);
            //var cloc = new CalcLocation("cloc", 1, Guid.NewGuid().ToStrGuid());
            //var mock = new Mock<ILogFile>();
            CalcParameters       calcParameters = CalcParametersFactory.MakeGoodDefaults();
            VacationDtoFactory   vfac           = new VacationDtoFactory(calcParameters, r);
            CalcPersonDtoFactory cpf            = new CalcPersonDtoFactory(parameters, r, nr, vfac);
            var hhtDesires =
                new List <ModularHousehold.PersonTraitDesireEntry>();
            var d         = new Desire("desire", 1, 1, 1, string.Empty, 1, false, 1, "", Guid.NewGuid().ToStrGuid());
            var hhtDesire = new HHTDesire(1, 1, 1, d, HealthStatus.Healthy, 1, 1, string.Empty, "name", 1, 100,
                                          PermittedGender.All, Guid.NewGuid().ToStrGuid());
            var hht = new HouseholdTrait("blub", null, "", "", "", 1, 1, 1, 1, 1, TimeType.Day, 1, 1, TimeType.Day, 1,
                                         1, EstimateType.FromCalculations,
                                         "", Guid.NewGuid().ToStrGuid());

            hhtDesires.Add(
                new ModularHousehold.PersonTraitDesireEntry(
                    ModularHouseholdTrait.ModularHouseholdTraitAssignType.Age, null, hhtDesire, hht));
            //var sharedDesireValues = new Dictionary<Desire, SharedDesireValue>();
            var cpersons = cpf.MakePersonDtos(persons, key, hhVacations, hhtDesires, "hhname");

            cpersons.Count.Should().Be(1);
            var cp = cpersons[0];

            //CalcPersonFactory.AddTraitDesires(hhtDesires, cpersons, 1, "name", sharedDesireValues);
            cp.Desires.Count.Should().Be(1);
            cp.Desires.Count.Should().Be(1);
            p.PrettyName.Should().Be(cp.Name);
            p.Age.Should().Be(cp.Age);
            // id 1 for the dictionary
            Assert.Equal(d.PrettyName, cp.Desires[0].Name);
        }
        public void ProfileActivationEntryTest()
        {
            CalcParameters         calcParameters = CalcParametersFactory.MakeGoodDefaults();
            ProfileActivationEntry entry          = new ProfileActivationEntry("d1", "p1", "ps1", "lt", calcParameters);
            Dictionary <ProfileActivationEntry.ProfileActivationEntryKey, ProfileActivationEntry> entries =
                new Dictionary <ProfileActivationEntry.ProfileActivationEntryKey, ProfileActivationEntry>
            {
                { entry.GenerateKey(), entry }
            };

            entry.ActivationCount = 5;
            ProfileActivationEntry entry2 = new ProfileActivationEntry("d1", "p1", "ps1", "lt", calcParameters);
            bool result2 = entries.ContainsKey(entry2.GenerateKey());

            Assert.True(result2);
        }
Esempio n. 16
0
 public void GeographicLocationTypoTest()
 {
     using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
     {
         Simulator sim  = new Simulator(db.ConnectionString);
         var       pars = CalcParametersFactory.MakeGoodDefaults();
         foreach (GeographicLocation location in sim.GeographicLocations.It)
         {
             Logger.Info("Calculating " + location.PrettyName);
             SunriseTimes st = new SunriseTimes(location);
             st.MakeArray(pars.InternalTimesteps, pars.InternalStartTime, pars.InternalEndTime,
                          pars.InternalStepsize);
         }
         db.Cleanup();
     }
 }
Esempio n. 17
0
 public void TestLocationEntryBasicsWithFile()
 {
     Config.IsInUnitTesting = true;
     using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
     {
         wd.InputDataLogger.AddSaver(new LocationEntryLogger(wd.SqlResultLoggingService));
         DateTime       startdate      = new DateTime(2018, 1, 1);
         DateTime       enddate        = startdate.AddMinutes(1000);
         CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate).SetSettlingDays(0).EnableShowSettlingPeriod();
         calcParameters.Options.Add(CalcOption.LocationsEntries);
         //FileFactoryAndTracker fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hhname", wd.InputDataLogger);
         //LocationsLogFile llf = new LocationsLogFile(true, fft, calcParameters);
         //CalcLocation cl = new CalcLocation("blub", 1, Guid.NewGuid().ToStrGuid());
         //Mock<ILogFile> lf = new Mock<ILogFile>();
         //CalcPerson cp = MakeCalcPerson(cl,calcParameters,lf.Object);
         //LocationEntry le = new LocationEntry(cp, 1, cl,calcParameters);
         //llf.WriteEntry(le, new HouseholdKey("HH1"));
         //llf.WriteEntry(le, new HouseholdKey("HH2"));
         //llf.WriteEntry(le, new HouseholdKey("HH3"));
         //llf.Close();
         HouseholdKey  key1 = new HouseholdKey("hh1");
         TimeStep      ts   = new TimeStep(1, 0, false);
         LocationEntry le1  = new LocationEntry(key1, "personName", "personGuid".ToStrGuid(), ts, "locname",
                                                "locguid".ToStrGuid());
         HouseholdKey  key2 = new HouseholdKey("hh2");
         LocationEntry le2  = new LocationEntry(key2, "personName", "personGuid".ToStrGuid(), ts, "locname",
                                                "locguid".ToStrGuid());
         HouseholdKey  key3 = new HouseholdKey("hh3");
         LocationEntry le3  = new LocationEntry(key3, "personName", "personGuid".ToStrGuid(), ts, "locname",
                                                "locguid".ToStrGuid());
         DateStampCreator dsc = new DateStampCreator(calcParameters);
         using (OnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters))
         {
             old.AddLocationEntry(le1);
             old.AddLocationEntry(le2);
             old.AddLocationEntry(le3);
             old.FinalSaveToDatabase();
         }
         LocationEntryLogger lel = new LocationEntryLogger(wd.SqlResultLoggingService);
         var le = lel.Load(key1);
         Logger.Info("count: " + le.Count);
         string prev   = JsonConvert.SerializeObject(le1, Formatting.Indented);
         string loaded = JsonConvert.SerializeObject(le[0], Formatting.Indented);
         loaded.Should().Be(prev);
         wd.CleanUp();
     }
 }
        public void RunTest()
        {
            WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass());
            SqlResultLoggingService srls =
                new SqlResultLoggingService(Path.Combine(wd.WorkingDirectory));
            var calcParameters = CalcParametersFactory.MakeGoodDefaults();

            calcParameters.Enable(CalcOption.TemperatureFile);
            using (DatabaseSetup ds = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
            {
                Simulator             sim = new Simulator(ds.ConnectionString);
                TemperatureDataLogger tdl = new TemperatureDataLogger(srls, calcParameters);
                tdl.Run(Constants.GeneralHouseholdKey, sim.TemperatureProfiles[0]);
                ds.Cleanup();
            }
            wd.CleanUp();
        }
        public void FileFactoryAndTrackerTest()
        {
            Config.IsInUnitTesting = true;
            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
                CalcParameters  calcParameters = CalcParametersFactory.MakeGoodDefaults();
                var             clt            = new CalcLoadType("calcloadtype", "kwh", "kW", 0.001, true, Guid.NewGuid().ToStrGuid());
                BitArray        isSick         = new BitArray(calcParameters.InternalTimesteps);
                BitArray        isOnVacation   = new BitArray(calcParameters.InternalTimesteps);
                var             personDto      = CalcPersonDto.MakeExamplePerson();
                Random          r  = new Random();
                Mock <ILogFile> lf = new Mock <ILogFile>();
                using (CalcRepo calcRepo = new CalcRepo(rnd: r, lf: lf.Object, calcParameters: calcParameters))
                {
                    CalcLocation cloc = new CalcLocation("blub", Guid.NewGuid().ToStrGuid());
                    var          cp   = new CalcPerson(personDto,
                                                       cloc, isSick, isOnVacation, calcRepo);

                    /*"personname", 1, 1, null, 1, PermittedGender.Female, lf: null,
                     * householdKey: "hh1", startingLocation: null, traitTag: "traittag",
                     * householdName: "hhname0",calcParameters:calcParameters,isSick:isSick, guid:Guid.NewGuid().ToStrGuid());
                     */
                    var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "testhh", wd.InputDataLogger);
                    fft.RegisterHousehold(new HouseholdKey("hh1"), "test key", HouseholdKeyType.Household, "desc", null, null);
                    fft.RegisterHousehold(Constants.GeneralHouseholdKey, "general key", HouseholdKeyType.General, "desc", null, null);
                    fft.MakeFile <StreamWriter>("file1", "desc", true, ResultFileID.Actions,
                                                new HouseholdKey("hh1"), TargetDirectory.Charts, TimeSpan.FromMinutes(1),
                                                CalcOption.HouseholdContents,
                                                clt.ConvertToLoadTypeInformation(),
                                                cp.MakePersonInformation());
                    //fft.ResultFileList.WriteResultEntries(wd.WorkingDirectory);
                    ResultFileEntryLogger rfel = new ResultFileEntryLogger(wd.SqlResultLoggingService);
                    var rfes = rfel.Load();
                    rfes.Count.Should().BeGreaterThan(0);
                    //ResultFileList.ReadResultEntries(wd.WorkingDirectory);
                    fft.GetResultFileEntry(ResultFileID.Actions, clt.Name, new HouseholdKey("hh1"), cp.MakePersonInformation(), null);
                    fft.Dispose();
                }
                wd.CleanUp();
            }
        }
 public void BasicTest()
 {
     using (WorkingDir wd = new WorkingDir("BasicLogfileTest"))
     {
         CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().EnableShowSettlingPeriod();
         wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
         wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
         using (FileFactoryAndTracker fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hh1", wd.InputDataLogger))
         {
             fft.RegisterHousehold(Constants.GeneralHouseholdKey, "general", HouseholdKeyType.General, "desc", null, null);
             //SqlResultLoggingService srls = new SqlResultLoggingService(wd.WorkingDirectory);
             using (LogFile lf = new LogFile(calcParameters, fft))
             {
                 lf.Dispose();
             }
         }
         wd.CleanUp();
     }
 }
Esempio n. 21
0
        public void MakeCalcLocationsTest()
        {
            var locations = new List <Location>();
            var loc       = new Location("loc", 1, string.Empty, Guid.NewGuid().ToStrGuid());

            locations.Add(loc);
            Random r = new Random(1);
            DeviceCategoryPicker picker = new DeviceCategoryPicker(r, null);
            //var cp = new CalcFactoryParameters(picker);
            //var dict =new Dictionary<CalcLocation, List<IAssignableDevice>>();
            var deviceActions = new ObservableCollection <DeviceAction>();
            //var locdict = new Dictionary<Location, CalcLocation>();
            CalcParameters cp = CalcParametersFactory.MakeGoodDefaults();
            //var mock = new Mock<IOnlineDeviceActivationProcessor>();
            //var iodap = mock.Object;
            var locationDtoDict         = new CalcLoadTypeDtoDictionary(new Dictionary <VLoadType, CalcLoadTypeDto>());
            var ltDict                  = new CalcLoadTypeDictionary(new Dictionary <CalcLoadTypeDto, CalcLoadType>());
            CalcLocationDtoFactory cldt = new CalcLocationDtoFactory(cp, picker, locationDtoDict);
            Dictionary <CalcLocationDto, List <IAssignableDevice> > deviceLocationDict = new Dictionary <CalcLocationDto, List <IAssignableDevice> >();
            LocationDtoDict          calclocdict = new LocationDtoDict();
            List <DeviceCategoryDto> devcat      = new List <DeviceCategoryDto>();

            using CalcRepo calcRepo = new CalcRepo();
            //devcat.Add(new DeviceCategoryDto(dc.FullPath, Guid.NewGuid().ToStrGuid()));
            var locdtos = cldt.MakeCalcLocations(locations,
                                                 new HouseholdKey("hh1"),
                                                 EnergyIntensityType.EnergyIntensive,
                                                 deviceLocationDict,
                                                 deviceActions,
                                                 calclocdict,
                                                 devcat);

            locdtos.Count.Should().Be(1);
            locdtos[0].Name.Should().Be(loc.Name);
            CalcLocationFactory clf = new CalcLocationFactory(ltDict, calcRepo);
            //"HH1", EnergyIntensityType.EnergySaving, dict,deviceActions,
            DtoCalcLocationDict dcl = new DtoCalcLocationDict();
            var calclocs            = clf.MakeCalcLocations(locdtos, dcl, calcRepo);

            calclocs.Count.Should().Be(1);
            calclocs[0].Name.Should().Be(loc.Name);
            calclocs[0].Guid.Should().Be(locdtos[0].Guid);
        }
Esempio n. 22
0
 public void BasicTest()
 {
     using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
     {
         wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
         wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
         CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().EnableShowSettlingPeriod().SetSettlingDays(5);
         using (FileFactoryAndTracker fft = new FileFactoryAndTracker(wd.WorkingDirectory, "blub", wd.InputDataLogger))
         {
             fft.RegisterGeneralHouse();
             fft.RegisterHousehold(new HouseholdKey("HH1"), "test", HouseholdKeyType.Household, "desc",
                                   null, null);
             ThoughtsLogFile tlf = new ThoughtsLogFile(fft, calcParameters);
             Random          rnd = new Random();
             //NormalRandom nr = new NormalRandom(0, 0.1, rnd);
             // this array is pure nonsense and only to make it stop crashing the unit test
             //_calcParameters.InternalDateTimeForSteps = new List<DateTime>(4);
             //for (int i = 0; i < 4; i++)
             //{
             //  _calcParameters.InternalDateTimeForSteps.Add(DateTime.Now);
             //}
             CalcLocation    cloc         = new CalcLocation("cloc", Guid.NewGuid().ToStrGuid());
             BitArray        isSick       = new BitArray(calcParameters.InternalTimesteps);
             BitArray        isOnVacation = new BitArray(calcParameters.InternalTimesteps);
             CalcPersonDto   dto          = CalcPersonDto.MakeExamplePerson();
             Mock <ILogFile> lf           = new Mock <ILogFile>();
             NormalRandom    nr           = new NormalRandom(0, 0.1, rnd);
             using (CalcRepo calcRepo = new CalcRepo(rnd: rnd, lf: lf.Object, calcParameters: calcParameters, normalRandom: nr))
             {
                 CalcPerson cp = new CalcPerson(dto,
                                                cloc, isSick, isOnVacation, calcRepo);
                 //"personName", 0, 1, rnd, 1, PermittedGender.Male, null, "HH1" ,cloc,"traittag", "hhname0",calcParameters,isSick,Guid.NewGuid().ToStrGuid());
                 TimeStep     ts = new TimeStep(0, 0, false);
                 ThoughtEntry te = new ThoughtEntry(cp, ts, "blua");
                 calcParameters.SetSettlingDays(0);
                 tlf.WriteEntry(te, new HouseholdKey("HH1"));
             }
             tlf.Dispose();
         }
         wd.CleanUp();
     }
 }
Esempio n. 23
0
 public void RunTest()
 {
     using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
     {
         SqlResultLoggingService srls      = new SqlResultLoggingService(wd.WorkingDirectory);
         var calcParameters                = CalcParametersFactory.MakeGoodDefaults();
         CalcLoadTypeDtoDictionary   cltd  = new CalcLoadTypeDtoDictionary(new Dictionary <VLoadType, CalcLoadTypeDto>());
         CalcDeviceTaggingSetFactory cdtsf = new CalcDeviceTaggingSetFactory(calcParameters, cltd);
         using (DatabaseSetup ds = new DatabaseSetup(Utili.GetCurrentMethodAndClass()))
         {
             Simulator                          sim = new Simulator(ds.ConnectionString);
             CalcDeviceTaggingSets              devicetaggingset = cdtsf.GetDeviceTaggingSets(sim, 2);
             DeviceTaggingSetLogger             dtsl             = new DeviceTaggingSetLogger(srls);
             List <DeviceTaggingSetInformation> cdts             = new List <DeviceTaggingSetInformation>();
             cdts.AddRange(devicetaggingset.AllCalcDeviceTaggingSets);
             dtsl.Run(Constants.GeneralHouseholdKey, cdts);
             wd.CleanUp();
             ds.Cleanup();
         }
     }
 }
Esempio n. 24
0
        public void RunDaylightSavingsLoggerTests()
        {
            using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                SqlResultLoggingService sqrls = new SqlResultLoggingService(wd.WorkingDirectory);

                BitArray ba = new BitArray(365 * 24 * 60);
                for (int i = 0; i < ba.Length; i++)
                {
                    if (i % 3 == 0)
                    {
                        ba[i] = true;
                    }
                }
                DayLightStatus      dls            = new DayLightStatus(ba);
                CalcParameters      calcParameters = CalcParametersFactory.MakeGoodDefaults();
                DaylightTimesLogger dsl            = new DaylightTimesLogger(sqrls, calcParameters);
                dsl.Run(Constants.GeneralHouseholdKey, dls);
                wd.CleanUp();
            }
        }
Esempio n. 25
0
        public void TestBasics()
        {
            // needs major redesign of calcperson class
            using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {// StreamFactory sf = new StreamFactory();
                DateTime       startdate      = new DateTime(2018, 1, 1);
                DateTime       enddate        = startdate.AddMinutes(100);
                CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate).EnableShowSettlingPeriod().SetSettlingDays(0);
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
                using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "test1", wd.InputDataLogger))
                {
                    fft.RegisterHousehold(Constants.GeneralHouseholdKey, "general", HouseholdKeyType.General, "desc", null, null);
                    //SqlResultLoggingService srls = new SqlResultLoggingService(wd.WorkingDirectory);
                    CalculationProfiler profiler = new CalculationProfiler();
                    CalcRepo            calcRepo = CalcRepo.Make(calcParameters, wd.InputDataLogger, wd.WorkingDirectory, "name", profiler);
                    DesiresLogFile      dlf      = new DesiresLogFile(fft, calcParameters);
                    CalcDesire          cd1      = new CalcDesire("desire1", 1, 0.5m, 12, 1, 1, 60, -1, null, "", "");

                    //NormalRandom nr = new NormalRandom(0, 0.1, r);
                    CalcLocation  cloc         = new CalcLocation("cloc", Guid.NewGuid().ToStrGuid());
                    BitArray      isSick       = new BitArray(calcParameters.InternalTimesteps);
                    BitArray      isOnVacation = new BitArray(calcParameters.InternalTimesteps);
                    CalcPersonDto calcPerson   = CalcPersonDto.MakeExamplePerson();
                    CalcPerson    cp           = new CalcPerson(calcPerson, cloc,
                                                                isSick, isOnVacation, calcRepo);
                    //"bla", 1, 5, r, 48, PermittedGender.Male, lf, "HH1", cloc, "traittag", "hhname0",calcParameters,isSick,Guid.NewGuid().ToStrGuid());
                    cp.PersonDesires.AddDesires(cd1);
                    dlf.RegisterDesires(cp.PersonDesires.Desires.Values);
                    TimeStep    ts = new TimeStep(0, 0, true);
                    DesireEntry de = new DesireEntry(cp, ts, cp.PersonDesires, dlf, calcParameters);
                    fft.RegisterHousehold(new HouseholdKey("hh1"), "bla", HouseholdKeyType.Household, "desc", null, null);
                    dlf.WriteEntry(de, new HouseholdKey("hh1"));
                    dlf.Dispose();
                }
                wd.CleanUp();
            }
        }
Esempio n. 26
0
        public void MatchAutonomousDevicesWithNormalDevicesTest()
        {
            // make different devices at different locations
            // only a single one should be matched.
            var startdate      = new DateTime(2018, 1, 1);
            var enddate        = startdate.AddMinutes(100);
            var calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate);

            //_calcParameters.InitializeTimeSteps(startdate, enddate, new TimeSpan(0, 1, 0), 3, false);

            Config.IsInUnitTesting = true;
            var cloc1    = new CalcLocation("loc1", Guid.NewGuid().ToStrGuid());
            var cloc2    = new CalcLocation("loc1", Guid.NewGuid().ToStrGuid());
            var cdevload = new List <CalcDeviceLoad>();
            var clt      = new CalcLoadType("calcloadtype", "power", "sum", 1, true, Guid.NewGuid().ToStrGuid());

            cdevload.Add(new CalcDeviceLoad("load", 100, clt, 0, 0));
            var devCategoryGuid = Guid.NewGuid().ToStrGuid();
            IMock <IOnlineDeviceActivationProcessor> iodap = new Mock <IOnlineDeviceActivationProcessor>();

            using (var calcRepo = new CalcRepo(iodap.Object, calcParameters: calcParameters)) {
                var cdd1 = new CalcDeviceDto("cdevice1", devCategoryGuid, new HouseholdKey("HH1"), OefcDeviceType.Device, "category", "",
                                             Guid.NewGuid().ToStrGuid(), cloc1.Guid, cloc1.Name);

                var cdLoc1 = new CalcDevice(new List <CalcDeviceLoad>(), cloc1, cdd1, calcRepo);
                var cdd2   = new CalcDeviceDto("cdevice1", devCategoryGuid, new HouseholdKey("HH1"), OefcDeviceType.Device, "category", "",
                                               Guid.NewGuid().ToStrGuid(), cloc1.Guid, cloc1.Name);
                var cdLoc1B = new CalcDevice(new List <CalcDeviceLoad>(), cloc1, cdd2, calcRepo);
                var cdd3    = new CalcDeviceDto("cdevice1", devCategoryGuid, new HouseholdKey("HH1"), OefcDeviceType.Device, "category", "",
                                                Guid.NewGuid().ToStrGuid(), cloc2.Guid, cloc2.Name);
                var cdLoc2 = new CalcDevice(new List <CalcDeviceLoad>(), cloc2, cdd3, calcRepo);
                var cp     = new CalcProfile("cp1", Guid.NewGuid().ToStrGuid(), TimeSpan.FromMilliseconds(1), ProfileType.Absolute, "blub");
                //CalcVariableRepository crv = new CalcVariableRepository();
                //VariableRequirement vr = new VariableRequirement("");
                var requirements = new List <VariableRequirement>();
                var cdd4         = new CalcDeviceDto("cdevice1", devCategoryGuid, new HouseholdKey("HH1"), OefcDeviceType.Device, "category", "",
                                                     Guid.NewGuid().ToStrGuid(), cloc1.Guid, cloc1.Name);
                var cadLoc1  = new CalcAutoDev(cp, clt, cdevload, 0, 1, cloc1, requirements, cdd4, calcRepo);
                var autodevs = new List <CalcAutoDev> {
                    cadLoc1
                };
                var normalDevices = new List <CalcDevice> {
                    cdLoc1,
                    cdLoc1B,
                    cdLoc2
                };
                CalcHousehold.MatchAutonomousDevicesWithNormalDevices(autodevs, normalDevices);
                //var totalmatchcount = 0;
                foreach (var device in normalDevices)
                {
                    Logger.Info(device.Name);
                    foreach (var matchingAutoDev in device.MatchingAutoDevs)
                    {
                        //      totalmatchcount++;
                        Logger.Info("\t" + matchingAutoDev.Name);
                    }
                }

                cdLoc1.MatchingAutoDevs.Count.Should().Be(1);
            }

            //(totalmatchcount).Should().Be(1);
        }
        public CalcHouseholdDto MakeSingleFactory([NotNull] WorkingDir wd, [NotNull] DatabaseSetup db)
        {
            var builder = new ContainerBuilder();

            wd.InputDataLogger.AddSaver(new CalcPersonDtoLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new CalcAffordanceDtoLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new CalcVariableDtoLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new BridgeDayEntryLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new HouseholdDtoLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new CalcSiteDtoLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new CalcTransportationDeviceDtoLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new CalcTravelRouteDtoLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new TransportationStatusLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new TransportationEventLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));

            var sim = new Simulator(db.ConnectionString);

            var mhh       = sim.ModularHouseholds[0];
            var r         = new Random(1);
            var ltdtoDict = CalcLoadTypeDtoFactory.MakeLoadTypes(sim.LoadTypes.It, new TimeSpan(0, 1, 0),
                                                                 LoadTypePriority.RecommendedForHouseholds);
            var ltdict     = CalcLoadTypeFactory.MakeLoadTypes(ltdtoDict);
            var parameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(2018, 1, 1)
                             .SetEndDate(new DateTime(2018, 1, 1, 2, 0, 0)).SetSettlingDays(0).EnableShowSettlingPeriod();

            builder.Register(x => parameters).As <CalcParameters>().SingleInstance();
            builder.Register(x => new DateStampCreator(parameters)).As <DateStampCreator>().SingleInstance();
            builder.Register(c => ltdict).As <CalcLoadTypeDictionary>().SingleInstance();
            builder.Register(c => ltdtoDict).As <CalcLoadTypeDtoDictionary>().SingleInstance();
            builder.Register(c => new NormalRandom(0, 1, r)).As <NormalRandom>().SingleInstance();
            builder.Register(c => new FileFactoryAndTracker(wd.WorkingDirectory, mhh.Name, wd.InputDataLogger))
            .As <FileFactoryAndTracker>()
            .SingleInstance();
            builder.Register(c => new SqlResultLoggingService(wd.WorkingDirectory)).As <SqlResultLoggingService>()
            .SingleInstance();
            builder.Register(c => wd.InputDataLogger).As <IInputDataLogger>().SingleInstance();

            builder.Register(c => new OnlineLoggingData(c.Resolve <DateStampCreator>(), c.Resolve <IInputDataLogger>(),
                                                        c.Resolve <CalcParameters>()))
            .As <OnlineLoggingData>().As <IOnlineLoggingData>().SingleInstance();

            builder.Register(c => new LogFile(parameters,
                                              c.Resolve <FileFactoryAndTracker>())).As <ILogFile>().SingleInstance();
            builder.RegisterType <OnlineDeviceActivationProcessor>().As <IOnlineDeviceActivationProcessor>()
            .SingleInstance();
            builder.RegisterType <CalcModularHouseholdFactory>().As <CalcModularHouseholdFactory>().SingleInstance();
            builder.Register(x => new DeviceCategoryPicker(r, null)).As <IDeviceCategoryPicker>().SingleInstance();

            builder.Register(x => r).As <Random>().SingleInstance();
            builder.RegisterType <CalcDeviceFactory>().As <CalcDeviceFactory>().SingleInstance();
            builder.RegisterType <CalcDeviceDtoFactory>().As <CalcDeviceDtoFactory>().SingleInstance();
            builder.RegisterType <CalcLocationFactory>().As <CalcLocationFactory>().SingleInstance();
            builder.RegisterType <CalcLocationDtoFactory>().As <CalcLocationDtoFactory>().SingleInstance();
            builder.RegisterType <CalcPersonFactory>().As <CalcPersonFactory>().SingleInstance();
            builder.RegisterType <CalcPersonDtoFactory>().As <CalcPersonDtoFactory>().SingleInstance();
            builder.RegisterType <CalcAffordanceFactory>().As <CalcAffordanceFactory>().SingleInstance();
            builder.RegisterType <CalcAffordanceDtoFactory>().As <CalcAffordanceDtoFactory>().SingleInstance();
            builder.RegisterType <CalcTransportationFactory>().As <CalcTransportationFactory>().SingleInstance();
            builder.RegisterType <CalcModularHouseholdDtoFactory>().As <CalcModularHouseholdDtoFactory>()
            .SingleInstance();
            builder.RegisterType <CalcVariableDtoFactory>().As <CalcVariableDtoFactory>().SingleInstance();
            builder.RegisterType <CalcTransportationDtoFactory>().As <CalcTransportationDtoFactory>().SingleInstance();
            builder.RegisterType <VacationDtoFactory>().As <VacationDtoFactory>().SingleInstance();
            builder.RegisterType <AvailabilityDtoRepository>().As <AvailabilityDtoRepository>().SingleInstance();
            builder.RegisterType <CalcVariableRepository>().As <CalcVariableRepository>().SingleInstance();
            builder.RegisterType <CalcRepo>().As <CalcRepo>().SingleInstance();
            var container = builder.Build();

            using (var scope = container.BeginLifetimeScope()) {
                var hhdtofac = scope.Resolve <CalcModularHouseholdDtoFactory>();

                var tds = sim.TransportationDeviceSets[0];
                tds.SaveToDB();
                var trs = sim.TravelRouteSets[0];
                trs.SaveToDB();
                var css = sim.ChargingStationSets[0];
                css.SaveToDB();
                var fft = scope.Resolve <FileFactoryAndTracker>();
                fft.RegisterGeneralHouse();
                var dtohh = hhdtofac.MakeCalcModularHouseholdDto(sim,
                                                                 mhh,
                                                                 sim.TemperatureProfiles[0],
                                                                 new HouseholdKey("hh1"),
                                                                 sim.GeographicLocations[0],
                                                                 out _,
                                                                 tds,
                                                                 trs,
                                                                 EnergyIntensityType.Random,
                                                                 css);
                fft.Dispose();
                db.Cleanup();
                wd.CleanUp();
                return(dtohh);
            }
        }
        public void RunMakeCalcTest()
        {
            //TODO: fix the container registering
            var builder = new ContainerBuilder();

            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) {
                var path        = wd.WorkingDirectory;
                var inputlogger = wd.InputDataLogger;
                wd.InputDataLogger.AddSaver(new CalcPersonDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcAffordanceDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcVariableDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new BridgeDayEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new HouseholdDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcSiteDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcTransportationDeviceDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcTravelRouteDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new TransportationStatusLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new TransportationEventLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));

                using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) {
                    var sim = new Simulator(db.ConnectionString);

                    var mhh       = sim.ModularHouseholds[0];
                    var r         = new Random(1);
                    var dcp       = new DeviceCategoryPicker(r, null);
                    var ltdtoDict = CalcLoadTypeDtoFactory.MakeLoadTypes(sim.LoadTypes.It, new TimeSpan(0, 1, 0),
                                                                         LoadTypePriority.RecommendedForHouseholds);
                    var ltdict = CalcLoadTypeFactory.MakeLoadTypes(ltdtoDict);
                    //var picker = new DeviceCategoryPicker(r,null);
                    var nr         = new NormalRandom(0, 0.1, r);
                    var parameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(2018, 1, 1)
                                     .SetEndDate(new DateTime(2018, 1, 1, 2, 0, 0)).SetSettlingDays(0).EnableShowSettlingPeriod();
                    builder.Register(x => parameters).As <CalcParameters>().SingleInstance();
                    builder.Register(x => new DateStampCreator(parameters)).As <DateStampCreator>().SingleInstance();
                    builder.Register(c => ltdict).As <CalcLoadTypeDictionary>().SingleInstance();
                    builder.Register(c => ltdtoDict).As <CalcLoadTypeDtoDictionary>().SingleInstance();
                    builder.Register(c => new NormalRandom(0, 1, r)).As <NormalRandom>().SingleInstance();
                    builder.Register(c => new FileFactoryAndTracker(path, mhh.Name, inputlogger))
                    .As <FileFactoryAndTracker>().SingleInstance();
                    builder.Register(c => new SqlResultLoggingService(path)).As <SqlResultLoggingService>()
                    .SingleInstance();
                    builder.Register(c => inputlogger).As <IInputDataLogger>().As <InputDataLogger>().SingleInstance();

                    builder.Register(c => new OnlineLoggingData(c.Resolve <DateStampCreator>(),
                                                                c.Resolve <IInputDataLogger>(), c.Resolve <CalcParameters>())).As <OnlineLoggingData>().As <IOnlineLoggingData>()
                    .SingleInstance();

                    builder.Register(c => new LogFile(parameters, c.Resolve <FileFactoryAndTracker>())).As <ILogFile>()
                    .SingleInstance();
                    builder.RegisterType <OnlineDeviceActivationProcessor>().As <IOnlineDeviceActivationProcessor>()
                    .SingleInstance();
                    builder.RegisterType <CalcModularHouseholdFactory>().As <CalcModularHouseholdFactory>()
                    .SingleInstance();
                    builder.Register(x => new DeviceCategoryPicker(r, null)).As <IDeviceCategoryPicker>()
                    .SingleInstance();

                    builder.Register(x => r).As <Random>().SingleInstance();
                    builder.RegisterType <CalcDeviceFactory>().As <CalcDeviceFactory>().SingleInstance();
                    builder.RegisterType <CalcDeviceDtoFactory>().As <CalcDeviceDtoFactory>().SingleInstance();
                    builder.RegisterType <CalcLocationFactory>().As <CalcLocationFactory>().SingleInstance();
                    builder.RegisterType <CalcLocationDtoFactory>().As <CalcLocationDtoFactory>().SingleInstance();
                    builder.RegisterType <CalcPersonFactory>().As <CalcPersonFactory>().SingleInstance();
                    builder.RegisterType <CalcPersonDtoFactory>().As <CalcPersonDtoFactory>().SingleInstance();
                    builder.RegisterType <CalcAffordanceFactory>().As <CalcAffordanceFactory>().SingleInstance();
                    builder.RegisterType <CalcAffordanceDtoFactory>().As <CalcAffordanceDtoFactory>().SingleInstance();
                    builder.RegisterType <CalcTransportationFactory>().As <CalcTransportationFactory>().SingleInstance();
                    builder.RegisterType <CalcModularHouseholdDtoFactory>().As <CalcModularHouseholdDtoFactory>()
                    .SingleInstance();
                    builder.RegisterType <CalcVariableDtoFactory>().As <CalcVariableDtoFactory>().SingleInstance();
                    builder.RegisterType <CalcTransportationDtoFactory>().As <CalcTransportationDtoFactory>()
                    .SingleInstance();
                    builder.RegisterType <VacationDtoFactory>().As <VacationDtoFactory>().SingleInstance();
                    builder.RegisterType <AvailabilityDtoRepository>().As <AvailabilityDtoRepository>().SingleInstance();
                    builder.RegisterType <CalcVariableRepository>().As <CalcVariableRepository>().SingleInstance();
                    builder.RegisterType <CalcRepo>().As <CalcRepo>().SingleInstance();
                    var container = builder.Build();
                    using (var scope = container.BeginLifetimeScope()) {
                        var hhdtofac = scope.Resolve <CalcModularHouseholdDtoFactory>();

                        var tds = sim.TransportationDeviceSets[0];
                        tds.SaveToDB();
                        var trs = sim.TravelRouteSets[0];
                        trs.SaveToDB();
                        var css = sim.ChargingStationSets[0];
                        css.SaveToDB();

                        /*Site home = sim.Sites.CreateNewItem(sim.ConnectionString);
                         * home.Name = "home";
                         * home.SaveToDB();
                         * Site outside = sim.Sites.CreateNewItem(sim.ConnectionString);
                         * outside.Name = "outside";
                         * outside.SaveToDB();
                         * home.AddLocation(sim.Locations.SafeFindByName("Living room", FindMode.IgnoreCase));
                         * home.AddLocation(sim.Locations.SafeFindByName("Kitchen", FindMode.IgnoreCase));
                         * home.AddLocation(sim.Locations.SafeFindByName("Bath", FindMode.IgnoreCase));
                         * home.AddLocation(sim.Locations.SafeFindByName("Bedroom", FindMode.IgnoreCase));
                         * home.AddLocation(sim.Locations.SafeFindByName("Children's room", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("Dance Studio", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("Supermarket", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("Garden", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("Museum", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("School", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("Food Market", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("Sidewalk", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("Office Workplace 1", FindMode.IgnoreCase));
                         * TravelRoute tr = new TravelRoute(null, db.ConnectionString, "tr1", "desc", home, outside);
                         * tr.SaveToDB();
                         * trs.AddRoute(tr);*/
                        var fft = scope.Resolve <FileFactoryAndTracker>();
                        fft.RegisterGeneralHouse();
                        var ctf = scope.Resolve <CalcTransportationFactory>();
                        //LogFile lf = new LogFile(wd.WorkingDirectory, "hh1", true);
                        //lf.RegisterKey("hh1", "hh1-prettyname");
                        var dtohh = hhdtofac.MakeCalcModularHouseholdDto(sim, mhh,
                                                                         sim.TemperatureProfiles[0], new HouseholdKey("hh1"), sim.GeographicLocations[0],
                                                                         out var dtolocs, tds, trs,
                                                                         EnergyIntensityType.Random, css);
                        var cvdto = scope.Resolve <CalcVariableDtoFactory>();
                        var cvr   = scope.Resolve <CalcVariableRepository>();
                        foreach (var v in cvdto.VariableDtos.Values)
                        {
                            cvr.RegisterVariable(new CalcVariable(v.Name, v.Guid, v.Value,
                                                                  v.LocationName, v.LocationGuid, v.HouseholdKey));
                        }

                        var cmhf = scope.Resolve <CalcModularHouseholdFactory>();
                        //CalcTransportationDtoFactory dtoFactory = new CalcTransportationDtoFactory(ltdtoDict);
                        //dtoFactory.MakeTransportationDtos(sim, sim.ModularHouseholds[0], tds, trs, out var sites,out var transportationDevices, out var routes, dtohh.LocationDtos, dtohh.HouseholdKey);
                        var calcRepo = scope.Resolve <CalcRepo>();
                        var chh      = cmhf.MakeCalcModularHousehold(dtohh, out var dtoCalcLocationDict, null, null,
                                                                     calcRepo);
                        //ctf.MakeTransportation(dtohh,dtoCalcLocationDict,chh);
                        if (chh.TransportationHandler == null)
                        {
                            throw new LPGException("no transportation handler");
                        }

                        var          src        = chh.TransportationHandler.CalcSites[0].Locations[0];
                        var          dst        = chh.TransportationHandler.CalcSites[1].Locations[0];
                        const string personname = "personname";
                        var          ts         = new TimeStep(1, parameters);
                        dst.Affordances[0].IsBusy(ts, src, personname, false);
                        dst.Affordances[0].Activate(ts, personname, src, out var personTimeProfile);
                        fft.Dispose();
                    }

                    db.Cleanup();
                }

                wd.CleanUp();
            }
        }
Esempio n. 29
0
        public void MakeCalcLocationsTestWithDeviceCategory()
        {
            using WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass());
            var            builder        = new ContainerBuilder();
            var            r              = new Random(1);
            CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(2018, 1, 1)
                                            .SetEndDate(new DateTime(2018, 1, 1, 2, 0, 0)).SetSettlingDays(0).EnableShowSettlingPeriod();
            //CalcFactoryParameters.SetSkipChecking(true);
            //var nr = new NormalRandom(0, 1, r);
            var locations = new List <Location>();
            var loc       = new Location("loc", 1, string.Empty, Guid.NewGuid().ToStrGuid());

            locations.Add(loc);
            var devices = new ObservableCollection <RealDevice>();

            var dc  = new DeviceCategory("dc", -1, string.Empty, false, devices, Guid.NewGuid().ToStrGuid(), 1, true);
            var rd  = new RealDevice("rd", 1, string.Empty, dc, string.Empty, false, false, string.Empty, Guid.NewGuid().ToStrGuid(), 1);
            var rd2 = new RealDevice("rd2", 1, string.Empty, dc, string.Empty, false, false, string.Empty, Guid.NewGuid().ToStrGuid(), 1);

            dc.SubDevices.Add(rd);
            loc.AddDevice(dc, false);
            loc.AddDevice(rd2, false);
            var deviceLocationDict = new Dictionary <CalcLocationDto, List <IAssignableDevice> >();

            List <DeviceCategoryDto> devcat = new List <DeviceCategoryDto> {
                new DeviceCategoryDto(dc.FullPath, Guid.NewGuid().ToStrGuid())
            };

            devices.Add(rd);
            devices.Add(rd2);
            //var dict =new Dictionary<CalcLocation, List<IAssignableDevice>>();
            var allDeviceActions = new ObservableCollection <DeviceAction>();

            //var locdict = new Dictionary<Location, CalcLocation>();
            builder.Register(x => new CalcLoadTypeDtoDictionary(new Dictionary <VLoadType, CalcLoadTypeDto>())).As <CalcLoadTypeDtoDictionary>()
            .SingleInstance();
            builder.Register(x => new CalcLoadTypeDictionary(new Dictionary <CalcLoadTypeDto, CalcLoadType>())).As <CalcLoadTypeDictionary>()
            .SingleInstance();
            builder.Register(x => new DeviceCategoryPicker(r, null)).As <IDeviceCategoryPicker>().SingleInstance();
            builder.Register(x => calcParameters).As <CalcParameters>().SingleInstance();
            //builder.RegisterType<CalcLocationFactory>().As<CalcLocationFactory>().SingleInstance();
            Mock <IOnlineDeviceActivationProcessor> odapmock = new Mock <IOnlineDeviceActivationProcessor>();

            builder.Register(x => odapmock.Object).As <IOnlineDeviceActivationProcessor>().SingleInstance();
            builder.Register(x => r).As <Random>().SingleInstance();
            var idl = wd.InputDataLogger;

            builder.Register(x => idl).As <IInputDataLogger>().SingleInstance();
            string path = wd.WorkingDirectory;

            builder.Register(x => new FileFactoryAndTracker(path, "HH1", idl)).As <FileFactoryAndTracker>()
            .SingleInstance();
            builder.Register(x => new SqlResultLoggingService(path)).As <SqlResultLoggingService>().SingleInstance();
            builder.Register(x => new DateStampCreator(x.Resolve <CalcParameters>())).As <DateStampCreator>().SingleInstance();
            builder.Register(x => new DateStampCreator(x.Resolve <CalcParameters>())).As <DateStampCreator>().SingleInstance();
            builder.Register(x => new OnlineLoggingData(x.Resolve <DateStampCreator>(), x.Resolve <IInputDataLogger>(), x.Resolve <CalcParameters>()))
            .As <OnlineLoggingData>().SingleInstance();
            builder.Register(x => new LogFile(calcParameters,
                                              x.Resolve <FileFactoryAndTracker>())).As <ILogFile>().SingleInstance();
            builder.RegisterType <CalcDeviceFactory>().As <CalcDeviceFactory>().SingleInstance();
            builder.RegisterType <CalcLocationFactory>().As <CalcLocationFactory>().SingleInstance();
            builder.RegisterType <CalcPersonFactory>().As <CalcPersonFactory>().SingleInstance();
            builder.RegisterType <CalcModularHouseholdFactory>().As <CalcModularHouseholdFactory>().SingleInstance();
            builder.RegisterType <CalcLocationDtoFactory>().As <CalcLocationDtoFactory>();
            builder.RegisterType <InputDataLogger>().As <InputDataLogger>().SingleInstance();
            builder.RegisterType <CalcRepo>().As <CalcRepo>().SingleInstance();
            var container = builder.Build();

            using (var scope = container.BeginLifetimeScope()) {
                var             cldt        = scope.Resolve <CalcLocationDtoFactory>();
                var             calcRepo    = scope.Resolve <CalcRepo>();
                LocationDtoDict calclocdict = new LocationDtoDict();
                var             locdtos     = cldt.MakeCalcLocations(locations,
                                                                     new HouseholdKey("HH1"),
                                                                     EnergyIntensityType.EnergySaving,
                                                                     deviceLocationDict,
                                                                     allDeviceActions,
                                                                     calclocdict,
                                                                     devcat);

                CalcLocationFactory clf = scope.Resolve <CalcLocationFactory>();
                DtoCalcLocationDict dtl = new DtoCalcLocationDict();
                var clocations          = clf.MakeCalcLocations(locdtos, dtl, calcRepo);

                clocations.Count.Should().Be(1);
                clocations[0].LightDevices.Count.Should().Be(2);
                foreach (var device in clocations[0].LightDevices)
                {
                    Logger.Info(device.Name);
                }
            }

            wd.CleanUp();
        }
Esempio n. 30
0
        public void MakeCalcLocationsTestWithDevice()
        {
            var            builder        = new ContainerBuilder();
            var            r              = new Random(1);
            CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(2018, 1, 1)
                                            .SetEndDate(new DateTime(2018, 1, 1, 2, 0, 0)).SetSettlingDays(0).EnableShowSettlingPeriod();
            var picker = new DeviceCategoryPicker(r, null);

            builder.Register(x => picker).As <DeviceCategoryPicker>().SingleInstance();
            //var nr = new NormalRandom(0, 1, r);
            var locations = new List <Location>();
            var loc       = new Location("loc", 1, string.Empty, Guid.NewGuid().ToStrGuid());

            locations.Add(loc);
            var devices = new ObservableCollection <RealDevice>();
            var dc      = new DeviceCategory("dc", -1, string.Empty, false, devices, Guid.NewGuid().ToStrGuid(), 1, true);
            List <DeviceCategoryDto> devcat = new List <DeviceCategoryDto> {
                new DeviceCategoryDto(dc.FullPath, Guid.NewGuid().ToStrGuid())
            };
            var rd = new RealDevice("rd", 1, string.Empty, dc, string.Empty, false, false, string.Empty, Guid.NewGuid().ToStrGuid(), 1);

            loc.AddDevice(rd, false);
            var deviceLocationDict = new Dictionary <CalcLocationDto, List <IAssignableDevice> >();
            var allDeviceActions   = new ObservableCollection <DeviceAction>();

            //CalcLoadTypeDictionary cltd = CalcLoadTypeFactory.MakeLoadTypes(new ObservableCollection<VLoadType>(),calcParameters.InternalStepsize, calcParameters.LoadTypePriority);
            builder.Register(x => new DateStampCreator(x.Resolve <CalcParameters>())).As <DateStampCreator>().SingleInstance();
            builder.Register(x => new CalcLoadTypeDtoDictionary(new Dictionary <VLoadType, CalcLoadTypeDto>())).As <CalcLoadTypeDtoDictionary>()
            .SingleInstance();
            builder.Register(x => new CalcLoadTypeDictionary(new Dictionary <CalcLoadTypeDto, CalcLoadType>())).As <CalcLoadTypeDictionary>()
            .SingleInstance();
            builder.Register(x => new DeviceCategoryPicker(r, null)).As <IDeviceCategoryPicker>().SingleInstance();
            builder.Register(_ => calcParameters).As <CalcParameters>().SingleInstance();
            //builder.RegisterType<CalcLocationFactory>().As<CalcLocationFactory>().SingleInstance();
            Mock <IOnlineDeviceActivationProcessor> odapmock = new Mock <IOnlineDeviceActivationProcessor>();

            builder.Register(x => odapmock.Object).As <IOnlineDeviceActivationProcessor>().SingleInstance();
            builder.Register(x => r).As <Random>().SingleInstance();
            builder.RegisterType <CalcDeviceFactory>().As <CalcDeviceFactory>().SingleInstance();
            builder.RegisterType <CalcLocationFactory>().As <CalcLocationFactory>().SingleInstance();
            builder.RegisterType <CalcLocationDtoFactory>().As <CalcLocationDtoFactory>();
            builder.RegisterType <CalcRepo>().As <CalcRepo>().SingleInstance();
            var container = builder.Build();

            using var scope = container.BeginLifetimeScope();
            var             calcRepo    = scope.Resolve <CalcRepo>();
            var             cldt        = scope.Resolve <CalcLocationDtoFactory>();
            LocationDtoDict calclocdict = new LocationDtoDict();
            var             locdtos     = cldt.MakeCalcLocations(locations,
                                                                 new HouseholdKey("HH1"),
                                                                 EnergyIntensityType.EnergyIntensive,
                                                                 deviceLocationDict,
                                                                 allDeviceActions,
                                                                 calclocdict,
                                                                 devcat);

            //CalcDeviceFactory cdf = scope.Resolve<CalcDeviceFactory>();
            CalcLocationFactory clf = scope.Resolve <CalcLocationFactory>();
            DtoCalcLocationDict dtl = new DtoCalcLocationDict();
            var clocations          = clf.MakeCalcLocations(locdtos, dtl, calcRepo);

            clocations.Count.Should().Be(1);
            clocations[0].LightDevices.Count.Should().Be(2);
        }