コード例 #1
0
        public CalcManager GetCalcManager([NotNull] Simulator sim,
                                          [NotNull] CalcStartParameterSet csps, bool forceRandom)
        //, ICalcObject hh,
        //bool forceRandom, TemperatureProfile temperatureProfile,
        //GeographicLocation geographicLocation, EnergyIntensityType energyIntensity,
        //string fileVersion, LoadTypePriority loadTypePriority, [CanBeNull] DeviceSelection deviceSelection,
        //TransportationDeviceSet transportationDeviceSet, TravelRouteSet travelRouteSet,
        //)
        {
            csps.CalculationProfiler.StartPart(Utili.GetCurrentMethodAndClass() + " Initializing");
            if (sim == null)
            {
                throw new LPGException("Simulation was null");
            }

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

            CalcManager cm = null;

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

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

                var chh = csps.CalcTarget as ModularHousehold;

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

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

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

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

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

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

                    //LogSeed(calcParameters.ActualRandomSeed, lf.FileFactoryAndTracker, calcParameters);
                    csps.CalculationProfiler.StopPart(Utili.GetCurrentMethodAndClass() + " Generating Model");
                    return(cm);
                }
            }
            catch
            {
                cm?.Dispose();
                throw;
            }
        }
コード例 #2
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();
            }
        }