Пример #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 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);
        }
Пример #3
0
        public void AddOutputLoadType([NotNull] CalcLoadType loadType, double factor, TransformationOutputFactorType factorType)
        {
            var olt = new OutputLoadType(loadType, factor, factorType);

            _devProcessorKeys.Add(loadType, _odap.RegisterDevice(loadType.ConvertToDto(), _deviceDto));
            _outputLoadTypes.Add(olt);
        }
        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);
            }
        }
Пример #5
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));
        }
Пример #6
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();
            }
        }
        private static void CheckForBusyness([NotNull] CalcLocation loc,
                                             [NotNull] CalcAffordance aff,
                                             [NotNull] CalcDevice cd, [NotNull] CalcLoadType lt)
        {
            Logger.Info("------------");
            TimeStep ts1 = new TimeStep(0, 0, true);

            Logger.Info("aff.isbusy 0: " + aff.IsBusy(ts1, loc, "person", false));
            var prevstate = false;

            for (var i = 0; i < 100; i++)
            {
                TimeStep ts2 = new TimeStep(i, 0, true);
                if (aff.IsBusy(ts2, loc, "person", false) != prevstate)
                {
                    prevstate = aff.IsBusy(ts2, loc, "name", false);
                    Logger.Info("aff.isbusy:" + i + ": " + prevstate);
                }
            }

            Logger.Info("aff.isbusy 100: " + aff.IsBusyArray[100]);

            prevstate = false;
            Logger.Info("aff.isbusyarray 0:   " + aff.IsBusyArray[0]);
            for (var i = 0; i < 100; i++)
            {
                if (aff.IsBusyArray[i] != prevstate)
                {
                    prevstate = aff.IsBusyArray[i];
                    Logger.Info("aff.isbusyarray: " + i + ": " + prevstate);
                }
            }

            Logger.Info("aff.isbusyarray 100: " + aff.IsBusyArray[100]);

            prevstate = false;
            TimeStep ts3 = new TimeStep(0, 0, false);

            Logger.Info("cd.isbusyarray 0:   " + cd.GetIsBusyForTesting(ts3, lt));
            for (var i = 0; i < 100; i++)
            {
                TimeStep ts4 = new TimeStep(i, 0, false);
                if (cd.GetIsBusyForTesting(ts4, lt) != prevstate)
                {
                    prevstate = cd.GetIsBusyForTesting(ts4, lt);
                    Logger.Info("cd.isbusyarray: " + i + ": " + prevstate);
                }
            }
            TimeStep ts5 = new TimeStep(100, 0, false);

            Logger.Info("cd.isbusyarray 100: " + cd.GetIsBusyForTesting(ts5, lt));
        }
        public static CalcLoadTypeDictionary MakeLoadTypes(
            [NotNull] CalcLoadTypeDtoDictionary dtoDict)
        {
            var ltDict = new Dictionary <CalcLoadTypeDto, CalcLoadType>();

            foreach (var dto in dtoDict.Ltdtodict.Values)
            {
                var calcLoadType = new CalcLoadType(dto.Name, dto.UnitOfPower, dto.UnitOfSum,
                                                    dto.ConversionFactor, dto.ShowInCharts, dto.Guid);
                ltDict.Add(dto, calcLoadType);
            }
            return(new CalcLoadTypeDictionary(ltDict));
        }
        private List <CalcAutoDev> MakeCalcAutoDevsFromHouse([NotNull] CalcHouseDto house,
                                                             [NotNull][ItemNotNull] List <CalcLocation> houseLocations)
        {
            var autodevs = new List <CalcAutoDev>(house.AutoDevs.Count);

            // zur kategorien zuordnung
            foreach (var hhautodev in house.AutoDevs)
            {
                CalcProfile           calcProfile = CalcDeviceFactory.MakeCalcProfile(hhautodev.CalcProfile, _calcRepo.CalcParameters);
                CalcLoadType          clt         = _ltDict.GetLoadtypeByGuid(hhautodev.LoadtypeGuid);
                List <CalcDeviceLoad> loads       = new List <CalcDeviceLoad>();
                foreach (CalcDeviceLoadDto loadDto in hhautodev.Loads)
                {
                    CalcDeviceLoad load = new CalcDeviceLoad(loadDto.Name,
                                                             loadDto.MaxPower,
                                                             _ltDict.GetLoadtypeByGuid(loadDto.LoadTypeGuid),
                                                             loadDto.AverageYearlyConsumption,
                                                             loadDto.PowerStandardDeviation);
                    loads.Add(load);
                }

                List <VariableRequirement> requirements = new List <VariableRequirement>();
                foreach (var reqDto in hhautodev.Requirements)
                {
                    VariableRequirement rq = new VariableRequirement(reqDto.Name,
                                                                     reqDto.Value,
                                                                     reqDto.CalcLocationName,
                                                                     reqDto.LocationGuid,
                                                                     reqDto.VariableCondition,
                                                                     _variableRepository,
                                                                     reqDto.VariableGuid);
                    requirements.Add(rq);
                }

                CalcLocation houseLocation = houseLocations.Single(x => x.Guid == hhautodev.CalcLocationGuid);
                var          cautodev      = new CalcAutoDev(
                    calcProfile,
                    clt,
                    loads,
                    hhautodev.TimeStandardDeviation,
                    hhautodev.Multiplier,
                    houseLocation,
                    requirements, hhautodev, _calcRepo);
                var busyarr = _availabilityDtoRepository.GetByGuid(hhautodev.BusyArr.Guid);
                cautodev.ApplyBitArry(busyarr, _ltDict.GetLoadtypeByGuid(hhautodev.LoadtypeGuid));
                autodevs.Add(cautodev);
            }

            return(autodevs);
        }
Пример #10
0
        public void AddChargingStation([NotNull] CalcLoadType gridchargingLoadType,
                                       [NotNull] CalcTransportationDeviceCategory cat,
                                       double chargingDeviceMaxChargingPower,
                                       [NotNull] CalcLoadType carChargingLoadType,
                                       CalcRepo calcRepo)
        {
            string name = Name + " - Charging station " + (ChargingDevices.Count + 1);

            CalcChargingStation station = new CalcChargingStation(cat,
                                                                  gridchargingLoadType, chargingDeviceMaxChargingPower, name,
                                                                  System.Guid.NewGuid().ToStrGuid(), _householdKey, carChargingLoadType, calcRepo);

            ChargingDevices.Add(station);
        }
        public void DumpHouseholdContentsToText()
        {
            if (_households == null)
            {
                throw new LPGException("households should not be null.");
            }

            if (_calcRepo.CalcParameters.IsSet(CalcOption.HouseholdContents))
            {
                using (var swHouse =
                           _calcRepo.FileFactoryAndTracker.MakeFile <StreamWriter>("HouseSpec." + Constants.HouseKey.Key + ".txt",
                                                                                   "Detailed house description", true, ResultFileID.PersonFile, Constants.HouseKey, TargetDirectory.Root,
                                                                                   _calcRepo.CalcParameters.InternalStepsize, CalcOption.HouseholdContents)) {
                    swHouse.WriteLine("Space Heating");
                    if (_calcSpaceHeating != null)
                    {
                        swHouse.WriteLine(_calcSpaceHeating.Name);
                        var summedDegreeDays = _calcSpaceHeating.CalcDegreeDays.Values.Select(x => x.HeatingAmount).Sum();
                        swHouse.WriteLine("Degree day sum: " + summedDegreeDays);
                        swHouse.WriteLine("Load types");
                        CalcLoadType lt = null;
                        foreach (var load in _calcSpaceHeating.Loads)
                        {
                            lt = load.LoadType;
                            swHouse.WriteLine("\t" + load.LoadType.Name + " Avg:" + load.AverageYearlyConsumption + " - StdDev:" + load.PowerStandardDeviation + " Val:" + load.Value);
                        }

                        int count = 0;
                        if (lt == null)
                        {
                            throw new LPGException("Loadtype was null in the space heating calculation");
                        }
                        for (int i = 0; i < _calcSpaceHeating.IsBusyForLoadType[lt].Length; i++)
                        {
                            count += _calcSpaceHeating.IsBusyForLoadType[lt][i] ? 1 : 0;
                        }

                        swHouse.WriteLine("Busy timesteps: " + count);
                        foreach (var val in _calcSpaceHeating.CalcDegreeDays.Values)
                        {
                            swHouse.WriteLine(val.HeatingAmount);
                        }
                    }
                }
            }
            foreach (var calcHousehold in _households)
            {
                calcHousehold.DumpHouseholdContentsToText();
            }
        }
Пример #12
0
 public CalcTransformationDevice([NotNull] IOnlineDeviceActivationProcessor odap, double minValue,
                                 double maxValue, double minimumOutputPower, double maximumInputPower, [NotNull] CalcDeviceDto deviceDto,
                                 [NotNull] CalcLoadType inputLoadType)
     : base(deviceDto.Name, deviceDto.Guid)
 {
     _odap            = odap;
     _minValue        = minValue;
     _maxValue        = maxValue;
     _outputLoadTypes = new List <OutputLoadType>();
     _conditions      = new List <CalcTransformationCondition>();
     _minPower        = minimumOutputPower;
     _maxPower        = maximumInputPower;
     _inputLoadType   = inputLoadType;
     _deviceDto       = deviceDto;
 }
Пример #13
0
 public CalcGenerator([NotNull] IOnlineDeviceActivationProcessor odap,
                      [NotNull] CalcLoadType loadType,
                      [NotNull] List <double> values,
                      [NotNull] CalcParameters calcParameters, [NotNull] CalcDeviceDto calcDeviceDto) : base(calcDeviceDto.Name, calcDeviceDto.Guid)
 {
     //_devProcessorKey = new OefcKey(householdKey, OefcDeviceType.Generator, guid, "-1", loadType.Guid, "Generator");
     _odap            = odap;
     _loadType        = loadType;
     _values          = values;
     _devProcessorKey = _odap.RegisterDevice(_loadType.ConvertToDto(), calcDeviceDto);
     if (values.Count != calcParameters.InternalTimesteps)
     {
         throw new LPGException("Not enough values in the generator to fill the entire period!");
     }
 }
Пример #14
0
        private void MakeTransportationDevice([NotNull] CalcHousehold chh,
                                              [NotNull][ItemNotNull]
                                              List <CalcTransportationDeviceDto> transportationDevices)
        {
            foreach (var transportationDevice in transportationDevices)
            {
                var loads = new List <CalcDeviceLoad>();
                foreach (var load in transportationDevice.Loads)
                {
                    CalcLoadType clt = _loadTypeDict.GetLoadtypeByGuid(load.LoadTypeGuid);
                    loads.Add(new CalcDeviceLoad(load.Name, load.MaxPower, clt, 0, 0));
                }

                double distanceToEnergyFactor = transportationDevice.EnergyToDistanceFactor;

                CalcLoadType chargingLoadType = null;
                if (transportationDevice.ChargingCalcLoadTypeGuid.HasValue)
                {
                    chargingLoadType = _loadTypeDict.GetLoadtypeByGuid(transportationDevice.ChargingCalcLoadTypeGuid.Value);
                }
                if (chh.TransportationHandler == null)
                {
                    throw new LPGException("no transportation handler");
                }

                CalcDeviceDto cdd = new CalcDeviceDto(transportationDevice.Name,
                                                      transportationDevice.Category.Guid,
                                                      chh.HouseholdKey,
                                                      OefcDeviceType.Transportation, transportationDevice.Category.Name,
                                                      string.Empty, transportationDevice.Guid, StrGuid.Empty, string.Empty);
                var category = chh.TransportationHandler.GetCategory(transportationDevice.Category);
                CalcTransportationDevice cd = new CalcTransportationDevice(
                    category,
                    transportationDevice.AverageSpeedInMPerS, loads,
                    transportationDevice.FullRangeInMeters,
                    distanceToEnergyFactor, transportationDevice.MaxChargingPower, chargingLoadType,
                    chh.TransportationHandler.CalcSites,
                    cdd, _calcRepo);
                if (category.IsLimitedToSingleLocation)
                {
                    chh.TransportationHandler.AddVehicleDepotDevice(cd);
                }
                else
                {
                    chh.TransportationHandler.LocationUnlimitedDevices.Add(cd);
                }
            }
        }
 public CalcChargingStation([NotNull] CalcTransportationDeviceCategory deviceCategory, [NotNull] CalcLoadType gridChargingLoadType,
                            double maxChargingPower,
                            [NotNull] string chargingStationName, StrGuid chargingStationGuid,
                            [NotNull] HouseholdKey householdKey,
                            [NotNull] CalcLoadType carChargingLoadType, CalcRepo calcRepo)
 {
     _householdKey        = householdKey;
     _calcRepo            = calcRepo;
     CarChargingLoadType  = carChargingLoadType;
     DeviceCategory       = deviceCategory;
     GridChargingLoadType = gridChargingLoadType;
     MaxChargingPower     = maxChargingPower;
     ChargingStationName  = chargingStationName;
     ChargingStationGuid  = chargingStationGuid;
     IsAvailable          = true;
 }
Пример #16
0
        private List <CalcAffordance.DeviceEnergyProfileTuple> MakeDeviceEnergyProfileTuples([ItemNotNull][NotNull] List <CalcDevice> devices,
                                                                                             [NotNull] CalcAffordanceDto affordancedto)
        {
            List <CalcAffordance.DeviceEnergyProfileTuple> deviceEnergyProfiles =
                new List <CalcAffordance.DeviceEnergyProfileTuple>();

            foreach (DeviceEnergyProfileTupleDto dto in affordancedto.Energyprofiles)
            {
                StrGuid      devguid = dto.CalcDeviceGuid;
                CalcDevice   device  = devices.Single(x => x.Guid == devguid);
                CalcProfile  cp      = CalcDeviceFactory.MakeCalcProfile(dto.TimeProfile, _calcRepo.CalcParameters);
                CalcLoadType clt     = _loadTypeDictionary.GetLoadtypeByGuid(dto.CalcLoadTypeGuid);
                CalcAffordance.DeviceEnergyProfileTuple dep = new CalcAffordance.DeviceEnergyProfileTuple(device,
                                                                                                          cp, clt, dto.TimeOffset, _calcRepo.CalcParameters.InternalStepsize, dto.Multiplier, dto.Probability);
                deviceEnergyProfiles.Add(dep);
            }

            return(deviceEnergyProfiles);
        }
        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();
            }
        }
Пример #18
0
        private void SetTimeprofile([NotNull] CalcProfile calcProfile, [NotNull] TimeStep startidx,
                                    [NotNull] CalcLoadType loadType,
                                    [NotNull] string affordanceName, [NotNull] string activatingPersonName, StrGuid locationGuid)
        {
            CalcDeviceLoad cdl = null;

            foreach (var calcDeviceLoad in _loads)
            {
                if (calcDeviceLoad.LoadType == loadType)
                {
                    cdl = calcDeviceLoad;
                }
            }

            if (cdl == null)
            {
                throw new LPGException("It was tried to activate the loadtype " + loadType.Name +
                                       " even though that one is not set for the device " + Name);
            }

            /*   var factor = cdl.Value * multiplier;
             * if (calcProfile.ProfileType == ProfileType.Absolute)
             * {
             *     factor = 1 * multiplier;
             * }*/
            if (_calcRepo.Odap == null && !Config.IsInUnitTesting)
            {
                throw new LPGException("ODAP was null. Please report");
            }

            //   var totalDuration = calcProfile.GetNewLengthAfterCompressExpand(timefactor);
            //OefcKey key = new OefcKey(_calcDeviceDto.HouseholdKey, OefcDeviceType.Transportation, Guid, "-1", cdl.LoadType.Guid, "Transportation");
            var key = _keysByLocGuidAndLoadtype[locationGuid][cdl.LoadType];
            var rvp = RandomValueProfile.MakeStepValues(calcProfile.StepValues.Count, _calcRepo.NormalRandom, 0);
            var sv  = StepValues.MakeStepValues(calcProfile, 1, rvp, cdl);

            _calcRepo.Odap.AddNewStateMachine(startidx, cdl.LoadType.ConvertToDto(), affordanceName, activatingPersonName,
                                              key, _calcDeviceDto, sv);
            //SetBusy(startidx, totalDuration, loadType, activateDespiteBeingBusy);
            // return totalDuration + startidx;
        }
        public void CalcTransportationDeviceDriveTest()
        {
            using var wd  = new WorkingDir(Utili.GetCurrentMethodAndClass());
            using var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "blub", wd.InputDataLogger);
            wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
            //_calcParameters.CSVCharacter = ";";_calcParameters.InitializeTimeSteps(new DateTime(2018,1,1),new DateTime(2018,1,31),new TimeSpan(0,1,0),3,true  );
            var calcParameters = CalcParametersFactory.MakeGoodDefaults();

            var category = new CalcTransportationDeviceCategory("category", true, Guid.NewGuid().ToStrGuid());
            var lt2      = new CalcLoadType("driving load", "km/h", "km", 10000, false, Guid.NewGuid().ToStrGuid());
            var rnd      = new Random(1);
            var nr       = new NormalRandom(0, 0.1, rnd);
            //SqlResultLoggingService srls = new SqlResultLoggingService(wd.WorkingDirectory);
            var dsc = new DateStampCreator(calcParameters);

            using var old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters);
            using var lf  = new LogFile(calcParameters, fft, true);
            var key = new HouseholdKey("hh1");

            fft.RegisterHousehold(key, "Household", HouseholdKeyType.Household, "Description", null, null);
            fft.RegisterGeneralHouse();
            var chargingCalcLoadType = new CalcLoadType("charging load", "W", "kWh", 0.50, false, Guid.NewGuid().ToStrGuid());
            var odap = new OnlineDeviceActivationProcessor(old, calcParameters, fft);

            using var calcRepo = new CalcRepo(rnd: rnd, normalRandom: nr, lf: lf, calcParameters: calcParameters, odap: odap,
                                              onlineLoggingData: old);
            var srcSite = new CalcSite("srcsite", Guid.NewGuid().ToStrGuid(), key);
            var dstSite = new CalcSite("dstSite", Guid.NewGuid().ToStrGuid(), key);
            var station = new CalcChargingStation(category, chargingCalcLoadType, 500, "stationname", "stationguid".ToStrGuid(),
                                                  key, chargingCalcLoadType, calcRepo);

            dstSite.ChargingDevices.Add(station);
            var calcSites = new List <CalcSite> {
                srcSite,
                dstSite
            };
            var cdd = new CalcDeviceDto("transport device", category.Guid, key, OefcDeviceType.Transportation, category.Name,
                                        string.Empty, Guid.NewGuid().ToStrGuid(), StrGuid.Empty, string.Empty);
            var loads = new List <CalcDeviceLoad> {
                new CalcDeviceLoad("load1", 10, lt2, 10000, 0)
            };
            var ctd = new CalcTransportationDevice(category, 10, loads, 10000, 1, 1000, chargingCalcLoadType, calcSites, cdd,
                                                   calcRepo);
            var start = new TimeStep(1, 0, false);
            var end   = new TimeStep(11, 0, false);

            ctd.Activate(start, 10, srcSite, dstSite, "myroute", "myperson", start, end);

            ctd.AvailableRangeInMeters.Should().Be(10000);
            //TODO: fix this and comment out
            //station.IsAvailable = false;
            double prevrange = 0;

            for (var i = 1; i < 11; i++)
            {
                var ts = new TimeStep(i, 0, false);
                ctd.DriveAndCharge(ts);
                odap.ProcessOneTimestep(ts);
                var diffRange = prevrange - ctd.AvailableRangeInMeters;
                Logger.Info("timestep: " + i + " Range: " + ctd.AvailableRangeInMeters + " diff:" + diffRange);
                prevrange = ctd.AvailableRangeInMeters;
                ctd.Currentsite.Should().BeNull();
            }

            //no charging
            ctd.AvailableRangeInMeters.Should().Be(10000 - 10 * 60 * 10); //10m/s = 600m/minute
            Logger.Info("currentSite:" + ctd.Currentsite?.Name);

            //station.IsAvailable = true;
            for (var i = 11; i < 50; i++)
            {
                var ts = new TimeStep(i, 0, false);
                ctd.DriveAndCharge(ts);
                odap.ProcessOneTimestep(ts);
                Logger.Info("timestep: " + i + " Range: " + ctd.AvailableRangeInMeters);
            }

            ctd.Currentsite.Should().Be(dstSite);

            //  wd.CleanUp(1);
        }
        private static CalcRepo SetupFullWorkingTransportationExample([NotNull] WorkingDir wd, [NotNull] Random rnd, [NotNull] out NormalRandom nr,
                                                                      [NotNull] out CalcLocation srcloc, [NotNull] out CalcLocation dstloc, [NotNull] out CalcSite dstSite,
                                                                      [NotNull] out TransportationHandler transportationHandler, [NotNull] out AffordanceBaseTransportDecorator abt, [NotNull] CalcParameters calcParameters,
                                                                      [NotNull] HouseholdKey key)
        {
            Config.IsInUnitTesting = true;
            CalcAffordance.DoubleCheckBusyArray = true;
            nr = new NormalRandom(0, 0.1, rnd);
            var calcprofilevalues = new List <double> {
                10,
                20,
                30
            };

            var cp = new CalcProfile("calcprofile", Guid.NewGuid().ToStrGuid(), calcprofilevalues, ProfileType.Absolute, "syn");

            srcloc = new CalcLocation("srclocation", Guid.NewGuid().ToStrGuid());
            dstloc = new CalcLocation("dstlocation", Guid.NewGuid().ToStrGuid());
            var calcdesire =
                new CalcDesire("calcdesire", 1, 0.5m, 10, 1, 1, 60, 0.1m, null, "sourcetrait", "desirecat");
            var calcdesires = new List <CalcDesire> {
                calcdesire
            };
            CalcVariableRepository crv = new CalcVariableRepository();
            Mock <IOnlineDeviceActivationProcessor> iodap = new Mock <IOnlineDeviceActivationProcessor>();
            var old = new Mock <IOnlineLoggingData>();

            using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hh0", wd.InputDataLogger))
            {
                using (var lf = new LogFile(calcParameters, fft, true))
                {
                    var      calcRepo = new CalcRepo(odap: iodap.Object, calcParameters: calcParameters, rnd: rnd, normalRandom: nr, onlineLoggingData: old.Object, lf: lf);
                    BitArray isBusy   = new BitArray(calcParameters.InternalTimesteps, false);
                    var      ca       = new CalcAffordance("calcaffordance", cp, dstloc, false, calcdesires,
                                                           18, 50, PermittedGender.All, false, 0.1, LPGColors.Blue, "affordance category", false,
                                                           false, new List <CalcAffordanceVariableOp>(), new List <VariableRequirement>(),
                                                           ActionAfterInterruption.GoBackToOld, "timelimitname", 1, false,
                                                           "srctrait",
                                                           Guid.NewGuid().ToStrGuid(), crv, new List <CalcAffordance.DeviceEnergyProfileTuple>(),
                                                           isBusy, BodilyActivityLevel.Low, calcRepo);

                    var srcSite = new CalcSite("srcsite", Guid.NewGuid().ToStrGuid(), key);
                    srcSite.Locations.Add(srcloc);
                    dstSite = new CalcSite("dstSite", Guid.NewGuid().ToStrGuid(), key);
                    dstSite.Locations.Add(dstloc);
                    fft.RegisterHousehold(new HouseholdKey("hh0"), "hh0-prettyname", HouseholdKeyType.Household,
                                          "Desc", null, null);
                    transportationHandler = new TransportationHandler();
                    transportationHandler.AddSite(srcSite);
                    abt = new AffordanceBaseTransportDecorator(ca, dstSite, transportationHandler,
                                                               "travel to dstsite", new HouseholdKey("hh0"), Guid.NewGuid().ToStrGuid(), calcRepo);
                    dstloc.AddTransportationAffordance(abt);

                    var ctr = new CalcTravelRoute("myRoute1", srcSite, dstSite,
                                                  transportationHandler.VehicleDepot, transportationHandler.LocationUnlimitedDevices,
                                                  new HouseholdKey("hh0"), Guid.NewGuid().ToStrGuid(), calcRepo);
                    var myCategory = new CalcTransportationDeviceCategory("mycategory", false, Guid.NewGuid().ToStrGuid());
                    ctr.AddTravelRouteStep("driving", myCategory, 1, 36000, Guid.NewGuid().ToStrGuid());
                    transportationHandler.TravelRoutes.Add(ctr);
                    CalcLoadType    chargingloadtype = new CalcLoadType("chargingloadtype", "W", "kwh", 1, true, Guid.NewGuid().ToStrGuid());
                    List <CalcSite> calcSites        = new List <CalcSite>
                    {
                        srcSite,
                        dstSite
                    };
                    var            list = new List <CalcDeviceLoad>();
                    CalcDeviceLoad cdl  = new CalcDeviceLoad("bla", 1, chargingloadtype, 1, 1);
                    list.Add(cdl);
                    CalcDeviceDto cdd = new CalcDeviceDto("bus", myCategory.Guid,
                                                          new HouseholdKey("hh1"), OefcDeviceType.Transportation, myCategory.Name, string.Empty,
                                                          Guid.NewGuid().ToStrGuid(), string.Empty.ToStrGuid(), string.Empty);
                    var transportationDevice =
                        new CalcTransportationDevice(myCategory, 1, list, 100,
                                                     10, 1000, chargingloadtype, calcSites,
                                                     cdd, calcRepo);
                    transportationHandler.LocationUnlimitedDevices.Add(transportationDevice);
                    return(calcRepo);
                }
            }
        }
Пример #21
0
        public CalcTransportationDevice(
            [NotNull] CalcTransportationDeviceCategory category,
            double averageSpeedInMPerS, [NotNull][ItemNotNull] List <CalcDeviceLoad> loads,
            double fullRangeInMeters,
            double energyToDistanceFactor,
            double maxChargingPower,
            [CanBeNull] CalcLoadType chargingCalcLoadType,
            [NotNull][ItemNotNull] List <CalcSite> allCalcSites,
            [NotNull] CalcDeviceDto calcDeviceDto, [NotNull] CalcRepo calcRepo)
            : base(calcDeviceDto.Name, calcDeviceDto.Guid)
        {
            _dsc                    = new DateStampCreator(calcRepo.CalcParameters);
            _loads                  = loads;
            _fullRangeInMeters      = fullRangeInMeters;
            _energyToDistanceFactor = energyToDistanceFactor;
            _maxChargingPower       = maxChargingPower;
            _chargingCalcLoadType1  = chargingCalcLoadType;
            _availableRangeInMeters = fullRangeInMeters;
            Category                = category;
            AverageSpeedInMPerS     = averageSpeedInMPerS;
            _calcDeviceDto          = calcDeviceDto;
            _calcRepo               = calcRepo;
            if (_calcRepo.CalcParameters.InternalTimesteps == 0)
            {
                throw new LPGException("Time steps were not initialized.");
            }

            _isBusyArray = new BitArray(_calcRepo.CalcParameters.InternalTimesteps);
            //not all devices need to have load types. busses for example have no load
            //if (loads.Count == 0) {
            //throw new DataIntegrityException("The transportation device " + pName +
            //" seems to have no load types. That is not very useful. Please fix.");
            //}
            var vehiclePoolGuid = "8C426E95-B269-402E-9806-C3785D6C8433".ToStrGuid();

            _calcDeviceDto.LocationGuid = vehiclePoolGuid;
            _calcDeviceDto.LocationName = "Vehicle Pool";
            if (calcDeviceDto.LocationGuid == null)
            {
                throw new LPGException("Trying to initalize with empty location guid");
            }
            foreach (CalcDeviceLoad deviceLoad in loads)
            {
                //TODO: check if -1 is a good location guid
                //OefcKey key = new OefcKey(_calcDeviceDto.HouseholdKey, OefcDeviceType.Transportation, Guid, "-1", deviceLoad.LoadType.Guid, "Transportation");
                var key = _calcRepo.Odap.RegisterDevice(deviceLoad.LoadType.ConvertToDto(), calcDeviceDto);
                _keysByLocGuidAndLoadtype.Add(calcDeviceDto.LocationGuid, new Dictionary <CalcLoadType, OefcKey>());
                _keysByLocGuidAndLoadtype[calcDeviceDto.LocationGuid].Add(deviceLoad.LoadType, key);
            }

            if (chargingCalcLoadType != null)
            {
                var key2 = _calcRepo.Odap.RegisterDevice(chargingCalcLoadType.ConvertToDto(), calcDeviceDto);
                if (!_keysByLocGuidAndLoadtype.ContainsKey(calcDeviceDto.LocationGuid))
                {
                    _keysByLocGuidAndLoadtype.Add(calcDeviceDto.LocationGuid, new Dictionary <CalcLoadType, OefcKey>());
                }
                var dict = _keysByLocGuidAndLoadtype[calcDeviceDto.LocationGuid];
                if (!dict.ContainsKey(chargingCalcLoadType))
                {
                    dict.Add(chargingCalcLoadType, key2);
                }
            }

            RegisterForAllCalcSites(allCalcSites);
        }
Пример #22
0
        public void PostProcessingTestTwoActivation()
        {
            var startdate      = new DateTime(2018, 1, 1);
            var enddate        = startdate.AddMinutes(100);
            var calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate).EnableShowSettlingPeriod();
            //CalculationProfiler calculationProfiler = new CalculationProfiler();

            var rnd = new Random(1);
            var nr  = new NormalRandom(0, 1, rnd);

            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) {
                calcParameters.Enable(CalcOption.HouseSumProfilesFromDetailedDats);
                calcParameters.Enable(CalcOption.DeviceProfilesIndividualHouseholds);
                calcParameters.Enable(CalcOption.TotalsPerDevice);
                calcParameters.Enable(CalcOption.TotalsPerLoadtype);
                calcParameters.Enable(CalcOption.DeviceActivations);
                calcParameters.Enable(CalcOption.DetailedDatFiles);
                Config.IsInUnitTesting = true;
                wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcParameterLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcLoadTypeDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcObjectInformationLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new DeviceActivationEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcPersonDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new DeviceTaggingSetLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.Save(calcParameters);
                using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hh1", wd.InputDataLogger)) {
                    fft.RegisterHousehold(Constants.GeneralHouseholdKey, "general", HouseholdKeyType.General, "desc", null, null);
                    //fft.RegisterHousehold(Constants.GeneralHouseholdKey, "general", HouseholdKeyType.General,"desc");
                    //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 coi = new CalcObjectInformation(CalcObjectType.ModularHousehold, "objname", wd.WorkingDirectory);
                        wd.InputDataLogger.Save(coi);
                        using (var lf = new LogFile(calcParameters, fft)) {
                            var key = new HouseholdKey("hh1");
                            fft.RegisterHousehold(key, "hh1 key", HouseholdKeyType.Household, "Description", null, null);
                            var odap      = new OnlineDeviceActivationProcessor(old, calcParameters, fft);
                            var clt       = new CalcLoadType("lt1", "W", "kWh", 3, true, Guid.NewGuid().ToStrGuid());
                            var loadTypes = new List <CalcLoadTypeDto> {
                                clt.ConvertToDto()
                            };
                            wd.InputDataLogger.Save(loadTypes);
                            var cdl         = new CalcDeviceLoad("devload1", 10, clt, 666, 0);
                            var deviceLoads = new List <CalcDeviceLoad> {
                                cdl
                            };
                            var cloc            = new CalcLocation("locname", Guid.NewGuid().ToStrGuid());
                            var devguid         = Guid.NewGuid().ToStrGuid();
                            var devcategoryguid = Guid.NewGuid().ToStrGuid();
                            var cdto            = new CalcDeviceDto("devicename", devcategoryguid, key, OefcDeviceType.Device, "category", "", devguid,
                                                                    cloc.Guid, cloc.Name);
                            var devices = new List <IHouseholdKey> {
                                cdto
                            };
                            wd.InputDataLogger.SaveList(devices);
                            using (var calcRepo = new CalcRepo(odap, calcParameters: calcParameters, rnd: rnd, normalRandom: nr)) {
                                var device = new CalcDevice(deviceLoads, cloc, cdto, calcRepo);
                                //var devices = new List<CalcDevice> {device};
                                var cp = new CalcProfile("profile1", Guid.NewGuid().ToStrGuid(), new TimeSpan(0, 1, 0), ProfileType.Absolute,
                                                         "custom");
                                cp.AddNewTimepoint(new TimeSpan(0), 0);
                                cp.AddNewTimepoint(new TimeSpan(0, 1, 0), 10);
                                cp.AddNewTimepoint(new TimeSpan(0, 2, 0), 0);
                                cp.ConvertToTimesteps();
                                //var locations = new List<CalcLocation> {cloc};
                                var ts = new TimeStep(0, calcParameters);
                                device.SetTimeprofile(cp, ts, clt, "affordanceName", "activatorName", 1, false);
                                device.SetTimeprofile(cp, ts.AddSteps(5), clt, "affordanceName", "activatorName", 1, false);
                                device.SetTimeprofile(cp.CompressExpandDoubleArray(0.5), ts.AddSteps(8), clt, "affordanceName", "activatorName", 1,
                                                      false);
                                device.SetTimeprofile(cp.CompressExpandDoubleArray(2), ts.AddSteps(10), clt, "affordanceName", "activatorName", 1,
                                                      false);
                            }

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

                            //var autoDevs = new List<CalcAutoDev>();
                            //var ps = new Postprocessor(lf.FileFactoryAndTracker, calculationProfiler,calcParameters);
                            //var householdKeys = new HashSet<string> {"1"};
                            //var calcAffordanceTaggingSets = new List<CalcAffordanceTaggingSet>();
                            var deviceTaggingSetInformation = new DeviceTaggingSetInformation("name");
                            var taggingsets = new List <DeviceTaggingSetInformation> {
                                deviceTaggingSetInformation
                            };

                            wd.InputDataLogger.Save(taggingsets);
                            //var householdPlans = new List<CalcHouseholdPlan>();
                            //var householdNamesByNumber = new Dictionary<string, string> {["HH1"] = "household"};
                            //var affordanceEnergyUseFile = new AffordanceEnergyUseFile(lf.FileFactoryAndTracker,calcParameters);
                            //lf.Close(null); // needed to free file access
                            //var results = new Dictionary<string, double>();
                            var persons = new List <CalcPersonDto>();
                            var dto     = new CalcPersonDto("name", Guid.NewGuid().ToStrGuid(), 18, PermittedGender.Female, key, new List <DateSpan>(),
                                                            new List <DateSpan>(), 1, "tag", "hhname");
                            persons.Add(dto);
                            wd.InputDataLogger.SaveList(persons.ConvertAll(x => (IHouseholdKey)x));
                            //var deviceNamesToCategory = new Dictionary<string, string>();
                            old.FinalSaveToDatabase();
                            lf.Dispose();
                            fft.Dispose();
                            var cprof = new CalculationProfiler();
                            var ppm   = new PostProcessingManager(cprof, fft);
                            ppm.Run(wd.WorkingDirectory);
                            var tel     = new TotalsPerLoadtypeEntryLogger(wd.SqlResultLoggingService);
                            var results = tel.Read(key);
                            results[0].Value.Should().Be(150);
                        }
                    }
                }

                Logger.Info(wd.WorkingDirectory);
                wd.CleanUp();
            }
        }
Пример #23
0
        public void PostProcessingTestSingleActivation()
        {
            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) {
                wd.InputDataLogger.AddSaver(new CalcParameterLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new DeviceActivationEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcLoadTypeDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcPersonDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new DeviceTaggingSetLogger(wd.SqlResultLoggingService));
                var calculationProfiler = new CalculationProfiler();

                var startdate      = new DateTime(2018, 1, 1);
                var enddate        = startdate.AddMinutes(1000);
                var calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate).EnableShowSettlingPeriod();

                var rnd = new Random(1);
                var nr  = new NormalRandom(0, 1, rnd);

                calcParameters.Enable(CalcOption.HouseSumProfilesFromDetailedDats);
                calcParameters.Enable(CalcOption.DeviceProfilesIndividualHouseholds);
                calcParameters.Enable(CalcOption.TotalsPerDevice);
                calcParameters.Enable(CalcOption.TotalsPerLoadtype);
                calcParameters.Enable(CalcOption.DetailedDatFiles);
                calcParameters.Enable(CalcOption.DeviceActivations);
                var key = new HouseholdKey("hh1");

                wd.InputDataLogger.Save(calcParameters);

                using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hhname", wd.InputDataLogger)) {
                    //wd.InputDataLogger.AddSaver(new CalcDeviceDtoLogger(wd.SqlResultLoggingService));
                    var dsc = new DateStampCreator(calcParameters);
                    using (IOnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters)) {
                        var calcPersonDto = new CalcPersonDto("blub", "personguid".ToStrGuid(), 1, PermittedGender.Male, key, new List <DateSpan>(),
                                                              new List <DateSpan>(), 1, "traittag", "householdname");
                        var persons = new List <CalcPersonDto> {
                            calcPersonDto
                        };
                        wd.InputDataLogger.SaveList(persons.ConvertAll(x => (IHouseholdKey)x));

                        using (var lf = new LogFile(calcParameters, fft)) {
                            fft.RegisterHousehold(key, "test hh", HouseholdKeyType.Household, "Description", null, null);
                            fft.RegisterHousehold(Constants.GeneralHouseholdKey, "General", HouseholdKeyType.General, "Description", null, null);
                            var odap         = new OnlineDeviceActivationProcessor(old, calcParameters, fft);
                            var clt          = new CalcLoadType("lt1", "W", "kWh", 3, true, Guid.NewGuid().ToStrGuid());
                            var loadTypeDtos = new List <CalcLoadTypeDto> {
                                clt.ConvertToDto()
                            };
                            wd.InputDataLogger.Save(loadTypeDtos);
                            //var loadTypes = new List<CalcLoadType> {clt};
                            var cdl         = new CalcDeviceLoad("devload1", 10, clt, 666, 0);
                            var deviceLoads = new List <CalcDeviceLoad> {
                                cdl
                            };
                            var cloc = new CalcLocation("locname", Guid.NewGuid().ToStrGuid());
                            var deviceCategoryGuid = Guid.NewGuid().ToStrGuid();
                            var calcDeviceDto      = new CalcDeviceDto("devicename", deviceCategoryGuid, key, OefcDeviceType.Device, "category",
                                                                       string.Empty, Guid.NewGuid().ToStrGuid(), cloc.Guid, cloc.Name);
                            var calcDeviceDtos = new List <CalcDeviceDto> {
                                calcDeviceDto
                            };
                            wd.InputDataLogger.SaveList(calcDeviceDtos.ConvertAll(x => (IHouseholdKey)x));
                            //device tagging set for the post processing
                            var cdts = new List <DeviceTaggingSetInformation>();
                            var dtsi = new DeviceTaggingSetInformation("myset");
                            dtsi.AddTag(calcDeviceDto.Name, "testTag ");
                            cdts.Add(dtsi);
                            wd.InputDataLogger.Save(cdts);
                            //device
                            using (var calcRepo = new CalcRepo(calcParameters: calcParameters, odap: odap, rnd: rnd, normalRandom: nr)) {
                                var device = new CalcDevice(deviceLoads, cloc, calcDeviceDto, calcRepo);
                                //var devices = new List<CalcDevice> {device};
                                double[] resultValues = { 0, 100.0, 0, 0, 0, 0, 0, 0, 0, 0 };
                                var      cp           = new CalcProfile("profile1", Guid.NewGuid().ToStrGuid(), new TimeSpan(0, 1, 0), ProfileType.Absolute,
                                                                        "custom");
                                cp.AddNewTimepoint(new TimeSpan(0), 0);
                                cp.AddNewTimepoint(new TimeSpan(0, 1, 0), 10);
                                cp.AddNewTimepoint(new TimeSpan(0, 2, 0), 0);
                                cp.ConvertToTimesteps();
                                //var locations = new List<CalcLocation> {cloc};
                                var ts1 = new TimeStep(0, calcParameters);
                                device.SetTimeprofile(cp, ts1, clt, "affordanceName", "activatorName", 10, false);
                                for (var i = 0; i < 10; i++)
                                {
                                    var ts       = new TimeStep(i, calcParameters);
                                    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));
                                    filerows[0].EnergyEntries[0].Should().Be(resultValues[i]);
                                    foreach (var fileRow in filerows)
                                    {
                                        fileRow.Save(odap.BinaryOutStreams[fileRow.LoadType]);
                                    }
                                }
                            }
                            old.FinalSaveToDatabase();
                            fft.Dispose();
                            lf.Dispose(); // needed to free the file access
                            //var autoDevs = new List<CalcAutoDev>();
                            //var ps = new Postprocessor(lf.FileFactoryAndTracker, calculationProfiler,calcParameters );
                            //var householdKeys = new HashSet<string> {"1"};
                            //var calcAffordanceTaggingSets = new List<CalcAffordanceTaggingSet>();
                            //var calcDeviceTaggingSets = new List<CalcDeviceTaggingSet>();
                            //var calcDeviceTaggingSets = new List<DeviceTaggingSetInformation>();
                            //var householdPlans = new List<CalcHouseholdPlan>();
                            //var householdNamesByNumber = new Dictionary<string, string> {["HH1"] = "household"};
                            //var affordanceEnergyUseFile = new AffordanceEnergyUseFile(lf.FileFactoryAndTracker,calcParameters);

                            //var results = new Dictionary<string, double>();
                            //BitArray isSick = new BitArray(calcParameters.InternalTimesteps);
                            //BitArray isOnVacation = new BitArray(calcParameters.InternalTimesteps);
                            //CalcPersonDto cpd = new CalcPersonDto("personname", Guid.NewGuid().ToStrGuid(),18,PermittedGender.Female,key,new List<DateSpan>(),new List<DateSpan>(),1,"traittag","hhname"  );
                            //var persons = new List<CalcPerson> {new CalcPerson(cpd, new Random(), lf,cloc,calcParameters,isSick,isOnVacation)};
                            //var deviceNamesToCategory = new Dictionary<string, string>();
                            //CalcDeviceTaggingSets calcDeviceTaggingSets = new CalcDeviceTaggingSets();
                            var cpp = new PostProcessingManager(calculationProfiler, fft);
                            cpp.Run(wd.WorkingDirectory);

                            /*ps.EndOfSimulationProcessing(devices, locations, autoDevs, loadTypes, odap.Oefc, householdKeys
                             *  ,calcAffordanceTaggingSets, calcDeviceTaggingSets, householdPlans, householdNamesByNumber
                             *  ,affordanceEnergyUseFile, results, CalcObjectType.ModularHousehold, persons, deviceNamesToCategory,10);*/
                            //var dstpath = Path.Combine(wd.WorkingDirectory,DirectoryNames.CalculateTargetdirectory(TargetDirectory.Reports),"DeviceSums." + clt.Name + ".csv");
                            lf.Dispose(); // needed to free the file access
                            var di  = new DirectoryInfo(wd.WorkingDirectory);
                            var fis = di.GetFiles("DeviceSums.*", SearchOption.AllDirectories);

                            if (fis.Length == 0)
                            {
                                throw new LPGException("No Sum File was generated");
                            }
                            fft.Dispose();
                            using (var sr = new StreamReader(fis[0].FullName)) {
                                sr.ReadLine();              //header
                                var result = sr.ReadLine(); //0
                                if (result == null)
                                {
                                    throw new LPGException("Result was null");
                                }

                                var arr = result.Split(';');
                                Assert.Equal("300", arr[1]);
                            }
                        }
                    }
                }

                Logger.Info(wd.WorkingDirectory);
                wd.CleanUp();
            }
        }
Пример #24
0
        public void OnlineDeviceActivationProcessorSetToZeroTest()
        {
            var rnd            = new Random(1);
            var nr             = new NormalRandom(0, 1, rnd);
            var startdate      = new DateTime(2018, 1, 1);
            var enddate        = startdate.AddMinutes(100);
            var calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate).EnableShowSettlingPeriod();

            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) {
                wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
                //calcParameters.Enable(CalcOption.ActionsLogfile);
                calcParameters.Enable(CalcOption.DeviceProfilesIndividualHouseholds);
                Config.ExtraUnitTestChecking = true;
                // calcProfile
                var profileWith100 = new CalcProfile("calcProfile", Guid.NewGuid().ToStrGuid(), new TimeSpan(0, 1, 0), ProfileType.Absolute, "blub");
                profileWith100.AddNewTimepoint(new TimeSpan(0), 100);
                profileWith100.AddNewTimepoint(new TimeSpan(0, 5, 0), 100);
                profileWith100.ConvertToTimesteps();
                var profileWith50 = new CalcProfile("calcProfile2", Guid.NewGuid().ToStrGuid(), new TimeSpan(0, 1, 0), ProfileType.Absolute, "blub");
                profileWith50.AddNewTimepoint(new TimeSpan(0), 50);
                profileWith50.AddNewTimepoint(new TimeSpan(0, 3, 0), 50);
                profileWith50.ConvertToTimesteps();
                // Loadtype
                var clt = new CalcLoadType("lt1", "W", "kWh", 1, true, Guid.NewGuid().ToStrGuid());
                // Location
                var cloc = new CalcLocation("Location", Guid.NewGuid().ToStrGuid());
                // devices

                var cdl     = new CalcDeviceLoad("lt1", 100, clt, 100, 0);
                var loads   = new List <CalcDeviceLoad>();
                var results = new List <string> {
                    "100;0;", "100;0;",
                    "100;0;",
                    "100;0;",
                    "100;0;",
                    "100;0;",
                    "0;50;",
                    "0;50;",
                    "0;50;",
                    "100;0;",
                    "100;0;",
                    "100;0;",
                    "100;0;",
                    "100;0;",
                    "100;0;"
                };
                loads.Add(cdl);
                using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hh1", wd.InputDataLogger)) {
                    fft.RegisterHousehold(Constants.GeneralHouseholdKey, "general", HouseholdKeyType.General, "desc", null, null);
                    //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 odap = new OnlineDeviceActivationProcessor(old, calcParameters, fft);
                            using (var calcRepo = new CalcRepo(calcParameters: calcParameters, odap: odap, rnd: rnd, normalRandom: nr)) {
                                var requirements = new List <VariableRequirement>();
                                var devCatGuid   = Guid.NewGuid().ToStrGuid();
                                var key          = new HouseholdKey("HH1");
                                var cddauto      = new CalcDeviceDto("devicename", devCatGuid, key, OefcDeviceType.Device, "device category",
                                                                     " (autonomous)", Guid.NewGuid().ToStrGuid(), cloc.Guid, cloc.Name);
                                var autodev = new CalcAutoDev(profileWith100, clt, loads, 0, 1, cloc, requirements, cddauto, calcRepo);
                                var cdd     = new CalcDeviceDto("devicename", devCatGuid, key, OefcDeviceType.Device, "device category", "",
                                                                Guid.NewGuid().ToStrGuid(), cloc.Guid, cloc.Name);
                                var device   = new CalcDevice(loads, cloc, cdd, calcRepo);
                                var autoDevs = new List <CalcAutoDev> {
                                    autodev
                                };
                                var devices = new List <CalcDevice> {
                                    device
                                };
                                CalcHousehold.MatchAutonomousDevicesWithNormalDevices(autoDevs, devices);
                                if (device.MatchingAutoDevs.Count == 0)
                                {
                                    throw new LPGException("Matching devices didn't work");
                                }

                                foreach (var pair in odap.Oefc.ColumnEntriesByLoadTypeByDeviceKey)
                                {
                                    Logger.Info(pair.Key.Name);
                                    foreach (var entry in pair.Value)
                                    {
                                        Logger.Info(entry.Key + " - " + entry.Value.Name);
                                    }
                                }

                                for (var i = 0; i < 15; i++)
                                {
                                    var ts = new TimeStep(i, 0, true);
                                    if (!autodev.IsBusyDuringTimespan(ts, 1, 1, clt))
                                    {
                                        autodev.Activate(ts);
                                    }

                                    if (i == 6)
                                    {
                                        device.SetTimeprofile(profileWith50, ts, clt, "blub", "Person", 1, false);
                                    }

                                    var filerows = odap.ProcessOneTimestep(ts);
                                    filerows.Count.Should().Be(1);
                                    filerows[0].EnergyEntries.Count.Should().Be(2);
                                    var entries = string.Empty;

                                    foreach (var d in filerows[0].EnergyEntries)
                                    {
                                        entries += d.ToString(CultureInfo.CurrentCulture) + ";";
                                    }

                                    Logger.Info(entries);
                                    results[i].Should().Be(entries);
                                }
                            }
                        }
                    }
                }

                wd.CleanUp();
            }
        }
Пример #25
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 void TestCalcSite()
 {
     using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
     {
         wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
         wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
         CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(2018, 1, 1).SetEndDate(2018, 2, 1).SetSettlingDays(0).EnableShowSettlingPeriod();
         HouseholdKey   hhkey          = new HouseholdKey("hh0");
         using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hhname0", wd.InputDataLogger))
         {
             fft.RegisterHousehold(hhkey, "hhname0", HouseholdKeyType.Household, "desc", null, null);
             fft.RegisterGeneralHouse();
             OnlineLoggingData old = new OnlineLoggingData(new DateStampCreator(calcParameters), wd.InputDataLogger, calcParameters);
             using (LogFile lf = new LogFile(calcParameters,
                                             fft, true))
             {
                 Random   r               = new Random(1);
                 CalcSite src             = new CalcSite("src", Guid.NewGuid().ToStrGuid(), hhkey);
                 CalcSite dst             = new CalcSite("dst", Guid.NewGuid().ToStrGuid(), hhkey);
                 TransportationHandler th = new TransportationHandler();
                 //List<CalcTravelRoute> routes = src.GetViableTrafficRoutes(dst);
                 //Assert.That(routes.Count,Is.EqualTo( 0));
                 var iodap = new Mock <IOnlineDeviceActivationProcessor>();
                 using (CalcRepo calcRepo = new CalcRepo(odap: iodap.Object, lf: lf, rnd: r, calcParameters: calcParameters, onlineLoggingData: old))
                 {
                     CalcTravelRoute firstRoute = new CalcTravelRoute("route1", src, dst, th.VehicleDepot,
                                                                      th.LocationUnlimitedDevices, hhkey, Guid.NewGuid().ToStrGuid(), calcRepo);
                     CalcTransportationDeviceCategory transcategory =
                         new CalcTransportationDeviceCategory("car-category", true, Guid.NewGuid().ToStrGuid());
                     firstRoute.AddTravelRouteStep("step1", transcategory, 1, 3600, Guid.NewGuid().ToStrGuid());
                     src.AddRoute(firstRoute);
                     //List<CalcTravelRoute> routes2 = src.GetViableTrafficRoutes(dst);
                     //Assert.That(routes2.Count,Is.EqualTo(0));
                     const double    distanceToEnergyFactor = 1;
                     List <CalcSite> calcSites = new List <CalcSite>
                     {
                         src,
                         dst
                     };
                     CalcLoadType   chargingLoadType = new CalcLoadType("chargingloadtype", "w", "kwh", 1, false, Guid.NewGuid().ToStrGuid());
                     var            cdls             = new List <CalcDeviceLoad>();
                     CalcDeviceLoad cdl = new CalcDeviceLoad("name", 1, chargingLoadType, 1, 1);
                     cdls.Add(cdl);
                     CalcDeviceDto dto = new CalcDeviceDto("car-device", transcategory.Guid,
                                                           hhkey, OefcDeviceType.Transportation, transcategory.Name, string.Empty,
                                                           Guid.NewGuid().ToStrGuid(), StrGuid.Empty, string.Empty);
                     CalcTransportationDevice ctd = new CalcTransportationDevice(transcategory, 1,
                                                                                 cdls, 100, distanceToEnergyFactor,
                                                                                 1000, chargingLoadType,
                                                                                 calcSites, dto, calcRepo);
                     th.VehicleDepot.Add(ctd);
                     //List<CalcTravelRoute> routes3 = src.GetViableTrafficRoutes(dst);
                     //(1).Should().Be(routes3.Count);
                     TimeStep ts       = new TimeStep(1, 0, false);
                     int?     duration = firstRoute.GetDuration(ts, "name", new List <CalcTransportationDevice>());
                     Logger.Info("Duration: " + duration);
                     duration.Should().Be(60);        // 3600 m bei 1 m/s
                     int?duration2 = firstRoute.GetDuration(ts, "name", new List <CalcTransportationDevice>());
                     duration.Should().Be(duration2); // 3600 m bei 1 m/s*/
                 }
             }
         }
         wd.CleanUp();
     }
 }
        public void TestInterruptionTest()
        {
            using var wd = new WorkingDir(Utili.GetCurrentMethodAndClass());
            DateTime       startdate      = new DateTime(2018, 1, 1);
            DateTime       enddate        = startdate.AddMinutes(100);
            CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate).SetSettlingDays(0).EnableShowSettlingPeriod().DisableShowSettlingPeriod().SetAffordanceRepetitionCount(1);
            //var r = new Random(1);
            //var nr = new NormalRandom(0, 1, r);
            var desire1 = new CalcDesire("desire1", 1, 0.5m, 4, 1, 1, 60, -1, null, "", "");
            var lt      = new CalcLoadType("calcLoadtype1", "kwh", "W", 1, true, Guid.NewGuid().ToStrGuid());

            //var variableOperator = new VariableOperator();
            using var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "blub", wd.InputDataLogger);
            var key = new HouseholdKey("HH1");

            wd.InputDataLogger.AddSaver(new ActionEntryLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new LocationEntryLogger(wd.SqlResultLoggingService));
            fft.RegisterHousehold(key, "hh1", HouseholdKeyType.Household, "desc", null, null);
            fft.RegisterHousehold(Constants.GeneralHouseholdKey, "General", HouseholdKeyType.General, "Desc", null, null);
            //SqlResultLoggingService srls = new SqlResultLoggingService(wd.WorkingDirectory);
            DateStampCreator dsc = new DateStampCreator(calcParameters);

            using OnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters);
            using var lf = new LogFile(calcParameters, fft);
            var           cloc         = new CalcLocation("loc1", Guid.NewGuid().ToStrGuid());
            BitArray      isSick       = new BitArray(calcParameters.InternalTimesteps);
            BitArray      isOnVacation = new BitArray(calcParameters.InternalTimesteps);
            CalcPersonDto calcPerson   = CalcPersonDto.MakeExamplePerson();
            var           odap         = new OnlineDeviceActivationProcessor(old, calcParameters, fft);
            Random        rnd          = new Random();
            NormalRandom  nr           = new NormalRandom(0, 1, rnd);

            using CalcRepo calcRepo = new CalcRepo(lf: lf, odap: odap, calcParameters: calcParameters, rnd: rnd, normalRandom: nr, onlineLoggingData: old);
            var cp = new CalcPerson(calcPerson, cloc, isSick, isOnVacation, calcRepo);

            //"blub", 1, 1, r,20, PermittedGender.Male, lf, "HH1", cloc,"traittag","hhname0", calcParameters,isSick, Guid.NewGuid().ToStrGuid());
            cp.PersonDesires.AddDesires(desire1);
            cp.SicknessDesires.AddDesires(desire1);
            var deviceLoads = new List <CalcDeviceLoad>
            {
                new CalcDeviceLoad("devload1", 1, lt, 100, 1)
            };
            var           devCategoryGuid = Guid.NewGuid().ToStrGuid();
            CalcDeviceDto cdd1            = new CalcDeviceDto("cdevice1", devCategoryGuid, key,
                                                              OefcDeviceType.Device, "category", "", Guid.NewGuid().ToStrGuid(),
                                                              cloc.Guid, cloc.Name);
            var           cdev1 = new CalcDevice(deviceLoads, cloc, cdd1, calcRepo);
            CalcDeviceDto cdd2  = new CalcDeviceDto("cdevice2", devCategoryGuid, key,
                                                    OefcDeviceType.Device, "category", "", Guid.NewGuid().ToStrGuid(),
                                                    cloc.Guid, cloc.Name);
            var           cdev2 = new CalcDevice(deviceLoads, cloc, cdd2, calcRepo);
            CalcDeviceDto cdd3  = new CalcDeviceDto("cdevice3", devCategoryGuid, key,
                                                    OefcDeviceType.Device, "category", "", Guid.NewGuid().ToStrGuid(),
                                                    cloc.Guid, cloc.Name);
            var cdev3 = new CalcDevice(deviceLoads, cloc, cdd3, calcRepo);

            cloc.Devices.Add(cdev1);
            cloc.Devices.Add(cdev2);
            cloc.Devices.Add(cdev3);
            var daylight = new BitArray(100);

            daylight.SetAll(true);
            DayLightStatus dls = new DayLightStatus(daylight);

            double[] newValues = { 1, 1, 1.0, 1, 1, 1, 1, 1 };
            var      newList   = new List <double>(newValues);
            var      cprof     = new CalcProfile("cp1", Guid.NewGuid().ToStrGuid(), newList, ProfileType.Relative, "bla");

            var desires = new List <CalcDesire>
            {
                desire1
            };
            var color = new ColorRGB(255, 0, 0);
            CalcVariableRepository crv = new CalcVariableRepository();
            BitArray isBusy            = new BitArray(calcParameters.InternalTimesteps, false);
            var      aff1 = new CalcAffordance("aff1", cprof, cloc, false, desires, 1, 100,
                                               PermittedGender.All, false, 0, color, "aff category", true, false,
                                               new List <CalcAffordanceVariableOp>(), new List <VariableRequirement>(),
                                               ActionAfterInterruption.GoBackToOld, "bla", 100, false, "",
                                               Guid.NewGuid().ToStrGuid(), crv
                                               , new List <CalcAffordance.DeviceEnergyProfileTuple>(), isBusy, BodilyActivityLevel.Low, calcRepo);

            aff1.AddDeviceTuple(cdev1, cprof, lt, 0, calcParameters.InternalStepsize, 1, 1);
            cloc.AddAffordance(aff1);
            var aff2 = new CalcAffordance("aff2", cprof, cloc, false, desires, 1, 100,
                                          PermittedGender.All, false, 0, color, "aff category", false, false,
                                          new List <CalcAffordanceVariableOp>(), new List <VariableRequirement>(),
                                          ActionAfterInterruption.GoBackToOld, "bla", 100, false, "", Guid.NewGuid().ToStrGuid(), crv
                                          , new List <CalcAffordance.DeviceEnergyProfileTuple>(), isBusy, BodilyActivityLevel.Low, calcRepo);

            aff2.AddDeviceTuple(cdev2, cprof, lt, 0, calcParameters.InternalStepsize, 1, 1);
            cloc.AddAffordance(aff2);
            var clocs = new List <CalcLocation>
            {
                cloc
            };
            BitArray isBusySub         = new BitArray(calcParameters.InternalTimesteps, false);
            var      calcSubAffordance = new CalcSubAffordance("subaffname", cloc, desires, 0,
                                                               100, 1,
                                                               PermittedGender.All, "subaff", false, true,
                                                               aff1, new List <CalcAffordanceVariableOp>(), 100,
                                                               "testing", Guid.NewGuid().ToStrGuid(), isBusySub, crv, BodilyActivityLevel.Low,
                                                               calcRepo);

            aff2.SubAffordances.Add(calcSubAffordance);
            calcSubAffordance.SetDurations(2);
            var persons = new List <CalcPerson>
            {
                cp
            };

            for (var i = 0; i < 100; i++)
            {
                TimeStep ts = new TimeStep(i, 0, true);
                cp.NextStep(ts, clocs, dls, new HouseholdKey("hh1"), persons, 1);
            }

            //wd.CleanUp();
        }
Пример #28
0
 public List <CalcChargingStation> CollectChargingDevicesFor([NotNull] CalcTransportationDeviceCategory category, [NotNull] CalcLoadType carLoadType)
 {
     return(ChargingDevices.Where(x => x.DeviceCategory == category && x.CarChargingLoadType == carLoadType).ToList());
 }
Пример #29
0
 public OutputLoadType([NotNull] CalcLoadType loadType, double valueScalingFactor, TransformationOutputFactorType factorType)
 {
     LoadType           = loadType;
     ValueScalingFactor = valueScalingFactor;
     FactorType         = factorType;
 }
        public void ProcessOneEnergyStorageTimestepTest()
        {
            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));
                CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults();
                calcParameters.ShowSettlingPeriodTime = true;
                using (OnlineLoggingData old = new OnlineLoggingData(new DateStampCreator(calcParameters), wd.InputDataLogger, calcParameters))
                {
                    using (FileFactoryAndTracker fft = new FileFactoryAndTracker(wd.WorkingDirectory, "name", wd.InputDataLogger))
                    {
                        fft.RegisterGeneralHouse();
                        var           odap         = new OnlineDeviceActivationProcessor(old, calcParameters, fft);
                        var           clt          = new CalcLoadType("clt1", "W", "kWh", 1, true, Guid.NewGuid().ToStrGuid());
                        var           deviceGuid   = Guid.NewGuid().ToStrGuid();
                        HouseholdKey  hhkey        = new HouseholdKey("HH1");
                        var           locationGuid = Guid.NewGuid().ToStrGuid();
                        CalcDeviceDto cdd          = new CalcDeviceDto("dev1", "devcatguid".ToStrGuid(),
                                                                       hhkey, OefcDeviceType.Device, "devcatname", "", deviceGuid, locationGuid, "loc");
                        var key = new OefcKey(cdd, clt.Guid);
                        odap.RegisterDevice(clt.ConvertToDto(), cdd);
                        double[] timestepValue  = { 1.0, 0 };
                        var      timestepValues = new List <double>(timestepValue);
                        var      cp             = new CalcProfile("myCalcProfile", Guid.NewGuid().ToStrGuid(), timestepValues,
                                                                  ProfileType.Absolute, "synthetic");
                        CalcDeviceLoad cdl1 = new CalcDeviceLoad("", -10, clt, 0, 0);
                        var            rvp  = RandomValueProfile.MakeStepValues(cp.StepValues.Count, NormalRandom, 0);
                        StepValues     sv1  = StepValues.MakeStepValues(cp, 1, rvp, cdl1);
                        odap.AddNewStateMachine(new TimeStep(1, 0, true),
                                                clt.ConvertToDto(), "name1", "p1", key, cdd, sv1);
                        CalcDeviceLoad cdl2 = new CalcDeviceLoad("", -100, clt, 0, 0);
                        StepValues     sv2  = StepValues.MakeStepValues(cp, 1, rvp, cdl2);
                        odap.AddNewStateMachine(new TimeStep(3, 0, true),
                                                clt.ConvertToDto(), "name2", "syn", key, cdd, sv2);
                        CalcDeviceLoad cdl3 = new CalcDeviceLoad("", -10, clt, 0, 0);
                        StepValues     sv3  = StepValues.MakeStepValues(cp, 1, rvp, cdl3);
                        odap.AddNewStateMachine(new TimeStep(5, 0, true),
                                                clt.ConvertToDto(), "name3", "syn", key, cdd, sv3);
                        CalcDeviceLoad cdl4 = new CalcDeviceLoad("", 100, clt, 0, 0);
                        StepValues     sv4  = StepValues.MakeStepValues(cp, 1, rvp, cdl4);
                        odap.AddNewStateMachine(new TimeStep(7, 0, true),
                                                clt.ConvertToDto(), "name4", "syn", key, cdd, sv4);
                        double[] resultValues = { 0, -10.0, 0, -100, 0, 10, 0, 100, 0, 0 };
                        var      ces          = new CalcEnergyStorage(odap, clt.ConvertToDto(),
                                                                      100, 7, 0, 0, 5, 20, null,
                                                                      cdd);
                        List <OnlineEnergyFileRow> rawRows = new List <OnlineEnergyFileRow>();
                        int keyidx = 0;
                        foreach (var keys in odap.Oefc.ColumnEntriesByLoadTypeByDeviceKey.Values)
                        {
                            foreach (KeyValuePair <OefcKey, ColumnEntry> pair in keys)
                            {
                                Logger.Info("Key " + keyidx + " " + pair.Key.ToString() + " - " + pair.Value);
                                keyidx++;
                            }
                        }
                        for (var i = 0; i < 10; i++)
                        {
                            TimeStep ts       = new TimeStep(i, 0, true);
                            var      filerows = odap.ProcessOneTimestep(ts);
                            rawRows.Add(filerows[0]);
                            filerows.Count.Should().Be(1);
                            filerows[0].EnergyEntries.Count.Should().Be(1);
                            var sb = new StringBuilder("row0 before:");
                            sb.Append(filerows[0].EnergyEntries[0]);
                            sb.Append(" : ");
                            //sb.Append(filerows[0].EnergyEntries[1]);
                            //filerows[0].EnergyEntries[0].Should().Be(resultValues[i]);
                            for (var j = 0; j < 5; j++)
                            {
                                ces.ProcessOneTimestep(filerows, ts, null);
                            }

                            sb.Append(" row0 after:");
                            sb.Append(filerows[0].EnergyEntries[0]);
                            sb.Append(" : ");
                            //sb.Append(filerows[0].EnergyEntries[1]);
                            sb.Append(" :StorageLevel ");
                            sb.Append(ces.PreviousFillLevel);
                            sb.Append(" :Expected ");
                            sb.Append(resultValues[i]);
                            Logger.Info(sb.ToString());
                        }
                        rawRows.Count.Should().Be(10);
                    }
                }
                wd.CleanUp();
            }
        }