private void MakeHeating([NotNull] CalcHouseDto house,
                                 [NotNull] CalcHouse calchouse,
                                 [NotNull] HouseholdKey householdKey,
                                 [NotNull][ItemNotNull] List <CalcLocation> locations) //, List<CalcDeviceTaggingSet> deviceTaggingSets)
        {
            if (house.SpaceHeating == null)
            {
                return;
            }

            var heating = house.SpaceHeating;

            //var isNan = false;
            foreach (var degreeHour in heating.CalcDegreeDays)
            {
                if (double.IsNaN(degreeHour.HeatingAmount))
                {
                    throw new LPGException(
                              "Heating degree days contain not-a-number. Check the temperature profile and your space heating settings.");
                }
            }

            var degreeDayDict = new Dictionary <Tuple <int, int, int>, CalcDegreeDay>();

            foreach (var degreeDay in heating.CalcDegreeDays)
            {
                var cdd = new CalcDegreeDay {
                    HeatingAmount = degreeDay.HeatingAmount,
                    Year          = degreeDay.Year,
                    Month         = degreeDay.Month,
                    Day           = degreeDay.Day
                };
                degreeDayDict.Add(new Tuple <int, int, int>(cdd.Year, cdd.Month, cdd.Day), cdd);
            }

            var load = heating.PowerUsage[0];
            var lt   = _ltDict.GetLoadtypeByGuid(load.LoadTypeGuid);
            var cdl  = new CalcDeviceLoad(lt.Name, load.MaxPower, lt, load.AverageYearlyConsumption, load.PowerStandardDeviation);
            var cdls = new List <CalcDeviceLoad> {
                cdl
            };
            var           heatloc       = locations.Single(x => heating.CalcLocationGuid == x.Guid);
            CalcDeviceDto calcDeviceDto = new CalcDeviceDto("Space Heating",
                                                            Guid.NewGuid().ToStrGuid(),
                                                            householdKey, OefcDeviceType.SpaceHeating, "Space Heating",
                                                            string.Empty, Guid.NewGuid().ToStrGuid(),
                                                            heatloc.Guid, heatloc.Name);
            var csh = new CalcSpaceHeating(cdls,
                                           degreeDayDict,
                                           heatloc,
                                           calcDeviceDto, _calcRepo);

            //foreach (var calcDeviceTaggingSet in taggingSets) {
            //calcDeviceTaggingSet.AddTag("Space Heating","House Device");
            //}

            calchouse.SetSpaceHeating(csh); //,deviceTaggingSets
        }
        private void SetAirConditioningOnHouse([NotNull] CalcHouseDto house,
                                               [NotNull] CalcHouse calcHouse,
                                               [NotNull][ItemNotNull] List <CalcLocation> calcLocations)
        {
            if (house.AirConditioning == null)
            {
                return;
            }

            var acdto          = house.AirConditioning;
            var degreeHourDict = new Dictionary <Tuple <int, int, int, int>, CalcDegreeHour>();

            foreach (CalcDegreeHourDto dto in acdto.CalcDegreeHours)
            {
                degreeHourDict.Add(new Tuple <int, int, int, int>(dto.Year, dto.Month, dto.Day, dto.Hour),
                                   new CalcDegreeHour(dto.Year, dto.Month, dto.Day, dto.Hour, dto.CoolingAmount));
            }

            //var isNan = false;
            foreach (var degreeHour in degreeHourDict.Values)
            {
                if (double.IsNaN(degreeHour.CoolingAmount))
                {
                    throw new LPGException("Cooling degree hour was not-a-number. Check the air conditioning and temperature profile.");
                }
            }

            var deviceLoad = acdto.DeviceLoads[0];
            var loadtype   = _ltDict.GetLoadtypeByGuid(deviceLoad.LoadTypeGuid);
            var cdl        = new CalcDeviceLoad(deviceLoad.Name,
                                                deviceLoad.MaxPower,
                                                loadtype,
                                                deviceLoad.AverageYearlyConsumption,
                                                deviceLoad.PowerStandardDeviation);
            var cdls = new List <CalcDeviceLoad> {
                cdl
            };

            var           acloc    = calcLocations.Single(x => x.Guid == acdto.CalcLocationGuid);
            CalcDeviceDto acDevdto = new CalcDeviceDto("Air Conditioning",
                                                       Guid.NewGuid().ToStrGuid(),
                                                       house.HouseKey, OefcDeviceType.AirConditioning,
                                                       "Air Conditioning",
                                                       string.Empty, Guid.NewGuid().ToStrGuid(),
                                                       acloc.Guid, acloc.Name);
            var csh = new CalcAirConditioning(
                cdls,
                degreeHourDict,
                acloc,
                acDevdto, _calcRepo);

            calcHouse.SetAirConditioning(csh);
        }
        private void SetEnergyStoragesOnHouse([NotNull][ItemNotNull] List <CalcEnergyStorageDto> energyStorages,
                                              [NotNull] HouseholdKey householdKey,
                                              [NotNull] CalcHouse calchouse, CalcVariableRepository calcVariableRepository
                                              ) //, List<CalcDeviceTaggingSet> deviceTaggingSets)
        {
            var cess           = new List <CalcEnergyStorage>();
            var esCategoryGuid = Guid.NewGuid().ToStrGuid();
            var esLocGuid      = Guid.NewGuid().ToStrGuid();

            foreach (var es in energyStorages)
            {
                //foreach (DeviceTaggingSet set in deviceTaggingSets) {
                //set.AddTag(es.Name,"House Device");
                //}
                var           lti       = _ltDict.GetCalcLoadTypeByLoadtype(es.InputLoadType).ConvertToDto();
                CalcDeviceDto deviceDto = new CalcDeviceDto(es.Name, esCategoryGuid, householdKey, OefcDeviceType.Storage,
                                                            "Energy Storage", "", es.Guid, esLocGuid, "Energy Storages");
                var ces = new CalcEnergyStorage(_calcRepo.Odap,
                                                lti,
                                                es.MaximumStorageRate,
                                                es.MaximumWithdrawRate,
                                                es.MinimumStorageRate,
                                                es.MinimumWithdrawRate,
                                                es.InitialFill,
                                                es.StorageCapacity,
                                                _calcRepo.Logfile.EnergyStorageLogfile,
                                                deviceDto
                                                );
                foreach (var signal in es.Signals)
                {
                    CalcVariable cv     = calcVariableRepository.GetVariableByGuid(signal.CalcVariableDto.Guid);
                    var          cessig = new CalcEnergyStorageSignal(signal.Name,
                                                                      signal.TriggerOffPercent,
                                                                      signal.TriggerOnPercent,
                                                                      signal.Value,
                                                                      cv,
                                                                      signal.Guid);
                    ces.AddSignal(cessig);
                }

                cess.Add(ces);
                if (ces.Signals.Count != es.Signals.Count)
                {
                    throw  new LPGException("Signal not initialized correctly");
                }
            }

            var calcEnergyStorages = cess; //,deviceTaggingSets);

            calchouse.SetStorages(calcEnergyStorages);
            //return calcEnergyStorages;
        }
        private void MakeAllTransformationDevices([NotNull] CalcHouseDto house,
                                                  [NotNull] CalcHouse calchouse,
                                                  [NotNull] HouseholdKey householdKey) //List<CalcDeviceTaggingSet> taggingSets,
        {
            var ctds            = new List <CalcTransformationDevice>();
            var devcategoryGuid = Guid.NewGuid().ToStrGuid();
            var trafolocGuid    = Guid.NewGuid().ToStrGuid();

            foreach (var trafo in house.TransformationDevices)
            {
                foreach (var set in _calcDeviceTaggingSets.AllCalcDeviceTaggingSets)
                {
                    set.AddTag(trafo.Name, "House Device");
                }
                CalcDeviceDto cdd = new CalcDeviceDto(trafo.Name, devcategoryGuid, householdKey,
                                                      OefcDeviceType.Transformation, "Transformation Devices", "", trafo.Guid, trafolocGuid, "Transformation Devices");
                var ctd = new CalcTransformationDevice(_calcRepo.Odap,
                                                       trafo.MinValue,
                                                       trafo.MaxValue,
                                                       trafo.MinPower,
                                                       trafo.MaxPower,
                                                       cdd, _ltDict.GetLoadtypeByGuid(trafo.InputLoadType.Guid));
                foreach (var outlt in trafo.OutputLoadTypes)
                {
                    ctd.AddOutputLoadType(_ltDict.GetLoadtypeByGuid(outlt.LoadType.Guid), outlt.ValueScalingFactor, outlt.FactorType);
                }

                if (ctd.OutputLoadTypes.Count > 0)
                {
                    if (trafo.Datapoints != null)
                    {
                        foreach (var datapoint in trafo.Datapoints)
                        {
                            ctd.AddDatapoint(datapoint.Ref, datapoint.Val);
                        }
                    }

                    foreach (var condition in trafo.Conditions)
                    {
                        var variable = _variableRepository.GetVariableByGuid(condition.CalcVariableDto.Guid);
                        ctd.AddCondition(condition.Name, variable, condition.MinValue, condition.MaxValue, condition.Guid);
                    }

                    ctds.Add(ctd);
                }
            }

            calchouse.SetTransformationDevices(ctds);
        }
        public CalcHouse MakeCalcHouse([NotNull] CalcHouseDto calcHouseDto, CalcRepo calcRepo)
        {
            HouseholdKey        houseKey       = Constants.HouseKey;
            var                 calchouse      = new CalcHouse(calcHouseDto.HouseName, calcHouseDto.HouseKey, calcRepo);
            List <CalcLocation> houseLocations = new List <CalcLocation>();

            foreach (var houseLoc in calcHouseDto.HouseLocations)
            {
                CalcLocation cl = new CalcLocation(houseLoc.Name, houseLoc.Guid);
                houseLocations.Add(cl);
            }

            var calcAbleObjects = new List <ICalcAbleObject>();

            //var globalLocationDict = new Dictionary<CalcLocationDto, CalcLocation>();
            foreach (var householddto in calcHouseDto.Households)
            {
                var hh = _cmhf.MakeCalcModularHousehold(householddto, out var _,
                                                        calcHouseDto.HouseName, calcHouseDto.Description, _calcRepo);
                calcAbleObjects.Add(hh);

                //    foreach (var pair in dtoCalcLocationDict.LocationDtoDict) {
                //      if (!globalLocationDict.ContainsKey(pair.Key)) {
                //        globalLocationDict.Add(pair.Key,  pair.Value);
                //  }
                //}
            }

            calchouse.SetHouseholds(calcAbleObjects);
            MakeHeating(calcHouseDto, calchouse, houseKey, houseLocations); //, taggingSets);

            SetAirConditioningOnHouse(calcHouseDto, calchouse, houseLocations);
            var autodevs2 = MakeCalcAutoDevsFromHouse(calcHouseDto, houseLocations);

            calchouse.SetAutoDevs(autodevs2);
            // energy Storage
            SetEnergyStoragesOnHouse(calcHouseDto.EnergyStorages, houseKey, calchouse,
                                     _variableRepository);                   //, taggingSets);
            // transformation devices
            MakeAllTransformationDevices(calcHouseDto, calchouse, houseKey); //taggingSets,

            // generators
            calchouse.SetGenerators(MakeGenerators(calcHouseDto.Generators, houseKey)); //taggingSets,

            return(calchouse);
        }
        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;
            }
        }