public void RunTest()
        {
            using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                HouseholdKeyLogger    ael    = new HouseholdKeyLogger(wd.SqlResultLoggingService);
                HouseholdKey          key    = new HouseholdKey("hhkey");
                List <IDataSaverBase> savers = new List <IDataSaverBase>
                {
                    ael
                };
                InputDataLogger   idl = new InputDataLogger(savers.ToArray());
                HouseholdKeyEntry ae1 = new HouseholdKeyEntry(key, "hhname", HouseholdKeyType.House, "desc", null, null);
                idl.Save(ae1);

                List <HouseholdKeyEntry> aes = new List <HouseholdKeyEntry>
                {
                    ae1
                };
                var res = ael.Load();
                var s1  = JsonConvert.SerializeObject(aes, Formatting.Indented);
                var s2  = JsonConvert.SerializeObject(res, Formatting.Indented);
                s1.Should().Be(s2);
                wd.CleanUp();
            }
        }
Ejemplo n.º 2
0
        public void GetDuplicateCalcManagerHouseholdTest()
        {
            using (var wd1 = new WorkingDir("GetDuplicateCalcManagerHouseholdTest1"))
            {
                CalculateOneHousehold(wd1.WorkingDirectory);
                using (var wd2 = new WorkingDir("GetDuplicateCalcManagerHouseholdTest2"))
                {
                    CalculateOneHousehold(wd2.WorkingDirectory);

                    var hhkeys   = HouseholdKeyLogger.Load(wd1.SqlResultLoggingService);
                    var afts1    = new CalcDeviceDtoLogger(wd1.SqlResultLoggingService);
                    var aft1     = afts1.Load(hhkeys.Where(x => x.KeyType == HouseholdKeyType.Household).ToList());
                    var afts2    = new CalcDeviceDtoLogger(wd2.SqlResultLoggingService);
                    var aft2     = afts2.Load(hhkeys.Where(x => x.KeyType == HouseholdKeyType.Household).ToList());
                    var devices1 = aft1.Select(x => x.Name).OrderBy(x => x).ToList();
                    var devices2 = aft2.Select(x => x.Name).OrderBy(x => x).ToList();
                    devices1.Should().BeEquivalentTo(devices2);

                    var rfel1 = new ResultFileEntryLogger(wd1.SqlResultLoggingService);
                    var rfes1 = rfel1.Load();
                    var rfel2 = new ResultFileEntryLogger(wd2.SqlResultLoggingService);
                    var rfes2 = rfel2.Load();
                    rfes1.Should().BeEquivalentTo(rfes2, o => o.Excluding(
                                                      x => x.SelectedMemberPath.EndsWith("FullFileName", StringComparison.InvariantCultureIgnoreCase)));

                    CompareCsv(rfes1, rfes2);
                    wd1.CleanUp();
                    wd2.CleanUp();
                }
            }
        }
        public void ReadExistingFilesFromSql()
        {
            SqlResultLoggingService srls        = new SqlResultLoggingService(_baseResultpath);
            HouseholdKeyLogger      hhKeyLogger = new HouseholdKeyLogger(srls);
            var hhkes = hhKeyLogger.Load();

            foreach (HouseholdKeyEntry entry in hhkes)
            {
                HouseholdRegistry.AddSavedEntry(entry);
            }

            var rfel = new ResultFileEntryLogger(srls);
            var rfes = rfel.Load();

            ResultFileList.AddExistingEntries(rfes);
            _inputDataLogger.AddSaver(rfel);
        }
Ejemplo n.º 4
0
        private static void CheckForOverdoneOffsets([NotNull] string path, [NotNull] SqlResultLoggingService srls)
        {
            //var actionsName = Path.Combine(path, "Reports", "ActionsEachStep.HH1.csv");
            var wwDeviceProfiles   = Path.Combine(path, "Results", "DeviceProfiles.Warm Water.csv");
            HouseholdKeyLogger hkl = new HouseholdKeyLogger(srls);
            var hhkeys             = hkl.Load();

            if (hhkeys.Count != 2)
            {
                throw new LPGException("Unknown key");
            }
            var selectedKey = hhkeys[1].HHKey;
            //SingleTimestepActionEntryLogger stael = new SingleTimestepActionEntryLogger(srls);
            ActionEntryLogger ael = new ActionEntryLogger(srls);
            // var actionEachStep = stael.Read(selectedKey);
            var actions = ael.Read(selectedKey);

            List <EnergyUseEntry> eues;

            using (var sr2 = new StreamReader(wwDeviceProfiles)) {
                eues = new List <EnergyUseEntry>();
                var header = sr2.ReadLine();
                if (header == null)
                {
                    throw new LPGException("Readline failed");
                }
                var headerarr = header.Split(';');

                while (!sr2.EndOfStream)
                {
                    var s = sr2.ReadLine();
                    if (s == null)
                    {
                        throw new LPGException("readline fail");
                    }
                    var eue = new EnergyUseEntry(s, headerarr);
                    eues.Add(eue);
                }
                sr2.Close();
            }
            var breakfast  = actions.First(x => x.AffordanceName == "eat breakfast (1 h)");
            var brtimestep = breakfast.TimeStep.ExternalStep + 2; //+2 to cover varying duration.

            for (var i = 0; i < eues.Count; i++)
            {
                if (eues[i].Timestep != i)
                {
                    throw new LPGException("Invalid timestep.");
                }
            }
            var          stepcount = 2;
            const string sinkname  = "HH1 - Kitchen - Kitchen Sink (5L/min) [L]";

            while (Math.Abs(eues[brtimestep + stepcount].Values[sinkname]) < Constants.Ebsilon)
            {
                stepcount++;
            }
            if (stepcount > 25)
            {
                throw new LPGException("Stepcount between two warm water uses during breakfast was : " + stepcount +
                                       ", but it should be about 20. Timestep: " + brtimestep);
            }
        }
        // ReSharper disable once CollectionNeverUpdated.Local


        public static void CheckForResultfile(string wd, CalcOption option)
        {
            var srls         = new SqlResultLoggingService(wd);
            var rfel         = new ResultFileEntryLogger(srls);
            var rfes         = rfel.Load();
            var foundOptions = new List <CalcOption>();

            //collect all the file keys

            foreach (var rfe in rfes)
            {
                if (!File.Exists(rfe.FullFileName))
                {
                    throw new LPGException("File " + rfe.FullFileName +
                                           " was registered, but is not actually present.");
                }

                foundOptions.Add(rfe.EnablingCalcOption);
            }

            // ReSharper disable once CollectionNeverQueried.Local
            var allTables   = new List <ResultTableDefinition>();
            var hhKeyLogger = new HouseholdKeyLogger(srls);
            var keys        = hhKeyLogger.Load();

            foreach (var key in keys)
            {
                if (!srls.FilenameByHouseholdKey.ContainsKey(key.HHKey))
                {
                    continue;
                }

                var fn = srls.FilenameByHouseholdKey[key.HHKey];
                if (!File.Exists(fn.Filename))
                {
                    continue;
                }

                var tables = srls.LoadTables(key.HHKey);
                allTables.AddRange(tables);
                foreach (var table in tables)
                {
                    foundOptions.Add(table.EnablingOption);
                }
            }

            foundOptions = foundOptions.Distinct().ToList();

            var optionsThatDontResultInFiles = new List <CalcOption>();

            optionsThatDontResultInFiles.Add(CalcOption.MakePDF);
            optionsThatDontResultInFiles.Add(CalcOption.ActionCarpetPlot);
            optionsThatDontResultInFiles.Add(CalcOption.HouseholdPlan);
            optionsThatDontResultInFiles.Add(CalcOption.CalculationFlameChart);
            optionsThatDontResultInFiles.Add(CalcOption.MakeGraphics);
            optionsThatDontResultInFiles.Add(CalcOption.LogErrorMessages);
            optionsThatDontResultInFiles.Add(CalcOption.EnergyCarpetPlot);
            optionsThatDontResultInFiles.Add(CalcOption.DurationCurve);
            optionsThatDontResultInFiles.Add(CalcOption.TransportationDeviceCarpetPlot);
            optionsThatDontResultInFiles.Add(CalcOption.LocationCarpetPlot);
            if (!optionsThatDontResultInFiles.Contains(option))
            {
                if (!foundOptions.Contains(option))
                {
                    throw new LPGException("Option found that doesn't result in any files");
                }
            }

            var fftd           = new FileFactoryAndTrackerDummy();
            var cp             = new CalculationProfiler();
            var container      = PostProcessingManager.RegisterEverything(wd, cp, fftd);
            var enabledOptions = new HashSet <CalcOption>();

            enabledOptions.Add(option);
            using (var scope = container.BeginLifetimeScope()) {
                var odm = scope.Resolve <OptionDependencyManager>();
                odm.EnableRequiredOptions(enabledOptions);
            }

            foreach (var enabledOption in enabledOptions)
            {
                foundOptions.Remove(enabledOption);
            }

            if (foundOptions.Contains(CalcOption.BasicOverview))
            {
                foundOptions.Remove(CalcOption.BasicOverview);
            }

            if (foundOptions.Count > 0)
            {
                var s = string.Join("\n", foundOptions.Select(x => x.ToString()));
                throw new LPGException("found stuff that was not requested:" + s);
            }

            var filesthatdontneedtoregister = new List <string>();

            filesthatdontneedtoregister.Add("finished.flag");
            filesthatdontneedtoregister.Add("log.commandlinecalculation.txt");
            filesthatdontneedtoregister.Add("results.general.sqlite");
            filesthatdontneedtoregister.Add("results.general.sqlite-wal");
            filesthatdontneedtoregister.Add("results.general.sqlite-shm");
            filesthatdontneedtoregister.Add("results.hh1.sqlite");
            filesthatdontneedtoregister.Add("results.hh1.sqlite-shm");
            filesthatdontneedtoregister.Add("results.hh1.sqlite-wal");
            filesthatdontneedtoregister.Add("results.house.sqlite");
            filesthatdontneedtoregister.Add("results.house.sqlite-shm");
            filesthatdontneedtoregister.Add("results.house.sqlite-wal");
            filesthatdontneedtoregister.Add("calculationprofiler.json");
            //check if all files are registered
            var di              = new DirectoryInfo(wd);
            var files           = di.GetFiles("*.*", SearchOption.AllDirectories);
            var registeredFiles = rfes.Select(x => x.FullFileName).ToList();

            foreach (var file in files)
            {
                if (filesthatdontneedtoregister.Contains(file.Name.ToLower(CultureInfo.InvariantCulture)))
                {
                    continue;
                }

                if (!registeredFiles.Contains(file.FullName))
                {
                    throw new LPGException("Found unregistered file: " + file.FullName);
                }
            }


            //foundKeys = foundKeys.Distinct().ToList();
            //if (_resultFileIdsByCalcOption.ContainsKey(option)) {
            //    var rl = _resultFileIdsByCalcOption[option];
            //    foreach (var key in rl.ResultKeys) {
            //        if (!foundKeys.Contains(key)) {
            //            throw new LPGException("in the found keys the file " + key + " is missing.");
            //        }
            //    }

            //    foreach (var key in foundKeys) {
            //        if (!rl.ResultKeys.Contains(key)) {
            //            throw new LPGException("in the result list keys the file " + key + " is missing.");
            //        }
            //    }
            //}

            //else {
            //    //todo: this needs to be done differently. need to disable as much as possible except the given calc option first.
            //    var sb = new StringBuilder();
            //    sb.Append("--------------");
            //    sb.AppendLine();
            //    sb.Append("_resultFileIdsByCalcOption.Add(CalcOption." + option + ",  ResultList.Make(CalcOption.");
            //    sb.Append(option).Append(", ");
            //    foreach (var key in foundKeys) {
            //        sb.AppendLine();
            //        sb.Append("\"").Append(key).Append("\", ");
            //    }

            //    sb.Remove(sb.Length - 2, 2);
            //    sb.Append("));");
            //    sb.AppendLine();
            //    sb.Append("--------------");
            //    Logger.Info(sb.ToString());
            //    //throw new LPGException(sb.ToString());
            //}
        }
        public void HouseJobForHouseTypes()
        {
            //setup
            Logger.Get().StartCollectingAllMessages();
            using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) {
                Simulator sim = new Simulator(db.ConnectionString);
                using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) {
                    var count = 0;
                    foreach (var houseType in sim.HouseTypes.It)
                    {
                        count++;
                        if (count < 22)
                        {
                            continue;
                        }

                        Logger.Info("================================================");
                        Logger.Info("================================================");
                        Logger.Info("================================================");
                        Logger.Info("Starting " + houseType.Name);
                        Logger.Info("================================================");
                        Logger.Info("================================================");
                        Logger.Info("================================================");
                        Logger.Get().StartCollectingAllMessages();
                        string htcode = houseType.Name.Substring(0, 4);
                        //housedata
                        const int targetheatdemand = 10000;
                        HouseData houseData        = new HouseData(Guid.NewGuid().ToStrGuid(), htcode, targetheatdemand, 1000,
                                                                   "HouseGeneratorJobHouse");
                        HouseCreationAndCalculationJob houseJob = new HouseCreationAndCalculationJob("present", "2019",
                                                                                                     "trafokreis", HouseDefinitionType.HouseData);
                        houseJob.House = houseData;

                        houseJob.CalcSpec = new JsonCalcSpecification {
                            DefaultForOutputFiles = OutputFileDefault.Reasonable,
                            StartDate             = new DateTime(2017, 1, 1),
                            EndDate            = new DateTime(2017, 12, 31),
                            GeographicLocation = sim.GeographicLocations.FindFirstByName("Berlin", FindMode.Partial)
                                                 ?.GetJsonReference() ??
                                                 throw new LPGException("No Berlin in the DB"),
                                                       TemperatureProfile = sim.TemperatureProfiles[0].GetJsonReference(),
                                                       OutputDirectory    = wd.Combine("Results." + htcode),
                                                       SkipExisting       = false,

                                                       CalcOptions = new List <CalcOption> {
                                                           CalcOption.HouseSumProfilesFromDetailedDats, CalcOption.DeviceProfilesIndividualHouseholds,
                                                           CalcOption.EnergyStorageFile, CalcOption.EnergyCarpetPlot,
                                                           CalcOption.HouseholdContents, CalcOption.TotalsPerLoadtype
                                                       },
                                                       DeleteDAT = false
                        };
                        StartHouseJob(houseJob, wd, htcode);
                        SqlResultLoggingService srls       = new SqlResultLoggingService(houseJob.CalcSpec.OutputDirectory);
                        HouseholdKeyLogger      hhkslogger = new HouseholdKeyLogger(srls);
                        var hhks = hhkslogger.Load();
                        TotalsPerLoadtypeEntryLogger tel = new TotalsPerLoadtypeEntryLogger(srls);
                        foreach (var entry in hhks)
                        {
                            if (entry.KeyType == HouseholdKeyType.General)
                            {
                                continue;
                            }

                            Logger.Info(entry.HHKey.ToString());
                            var res = tel.Read(entry.HHKey);
                            foreach (var totalsEntry in res)
                            {
                                Logger.Info(totalsEntry.Loadtype + ": " + totalsEntry.Value);
                                if (totalsEntry.Loadtype.Name == "Space Heating")
                                {
                                    if (Math.Abs(totalsEntry.Value - targetheatdemand) > 10)
                                    {
                                        throw new LPGException("Target heat demand didn't match for " + houseType.Name);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }