private Prosumer MakeSlpProfile([NotNull] Household household, [NotNull] Hausanschluss ha)
        {
            var slpprofile = _slpProvider.Run("H0", household.EffectiveEnergyDemand);

            if (slpprofile == null)
            {
                throw new FlaException("No profile? Why?");
            }

            var prosumer = new Prosumer(household.HouseGuid,
                                        household.Name,
                                        HouseComponentType.Household,
                                        household.SourceGuid,
                                        household.FinalIsn,
                                        household.HausAnschlussGuid,
                                        ha.ObjectID,
                                        GenerationOrLoad.Load,
                                        ha.Trafokreis,
                                        Name + " - SLP H0 Substitute Profile",
                                        "H0")
            {
                Profile = slpprofile
            };

            return(prosumer);
        }
        private bool MakeErzeugerLastgang([NotNull][ItemNotNull] List <House> houses, [NotNull] LastgangBusinessAssignment assignment, [NotNull][ItemNotNull] List <RlmProfile> profiles,
                                          [NotNull] SaveableEntry <Prosumer> sa)
        {
            var selectedhouses = houses.Where(x => x.ErzeugerIDs.Contains(assignment.ErzeugerID)).ToList();

            if (selectedhouses.Count != 1)
            {
                if (selectedhouses.Count == 0)
                {
                    Log(MessageType.Info, "No house found for " + assignment.ErzeugerID);
                    return(true);
                }

                throw new Exception(selectedhouses.Count + " houses for erzeuger id " + assignment.ErzeugerID);
            }

            Hausanschluss ha = selectedhouses[0].Hausanschluss[0];
            //odo: adjust with new factors
            var rlmrprofile = profiles.Single(x => x.Name == assignment.RlmFilename);
            var pa          = new Prosumer(selectedhouses[0].HouseGuid, assignment.RlmFilename,
                                           ProsumerType.LastgangGeneration, null, selectedhouses[0].GebäudeObjectIDs[0], ha.HausanschlussGuid, ha.ObjectID)
            {
                Profile = rlmrprofile.Profile
            };

            sa.AddRow(pa);
            return(false);
        }
        private Prosumer MakeFlatProfile([NotNull] CarDistanceEntry carDistance, [NotNull] Hausanschluss ha, [NotNull] Household household)
        {
            var slpprofile = Profile.MakeConstantProfile(carDistance.EnergyEstimate, carDistance.Name, Profile.ProfileResolution.QuarterHour);

            if (slpprofile == null)
            {
                throw new FlaException("No profile? Why?");
            }

            var prosumer = new Prosumer(household.HouseGuid,
                                        carDistance.Name,
                                        carDistance.HouseComponentType,
                                        household.SourceGuid,
                                        household.FinalIsn,
                                        household.HausAnschlussGuid,
                                        ha.ObjectID,
                                        GenerationOrLoad.Load,
                                        ha.Trafokreis,
                                        Name + " - Flat Substitute Profile",
                                        "Flat Substitute Profile due to missing LPG profile")
            {
                Profile = slpprofile
            };

            return(prosumer);
        }
        public HausAnschlussRo AddHausanschluss([NotNull] House house, [NotNull] Hausanschluss hausanschluss, [NotNull] string haStatus)
        {
            string  housename         = house.ComplexName;
            string  hausanschlussName = hausanschluss.Adress;
            string  objectId          = hausanschluss.ObjectID;
            string  trafokreis        = hausanschluss.Trafokreis;
            string  hausanschlussGuid = hausanschluss.Guid;
            HouseRo housero           = Houses.Single(x => x.HouseName == housename);

            if (housero.HausAnschlussList.Any(x => x.HausanschlussGuid == hausanschlussGuid))
            {
                throw new FlaException("Hausanschluss already exists:" + objectId);
            }

            HausAnschlussRo haro = new HausAnschlussRo(hausanschlussName, objectId, trafokreis, hausanschlussGuid, hausanschluss.Isn.ToString(),
                                                       hausanschluss.Lon, hausanschluss.Lat, haStatus, hausanschluss.Standort);

            housero.HausAnschlussList.Add(haro);
            haro.AssignmentMethod   = hausanschluss.MatchingType.ToString();
            haro.AssignmentDistance = hausanschluss.Distance;
            if (!_hausanschlussByObjectId.ContainsKey(objectId))
            {
                _hausanschlussByObjectId.Add(objectId, new List <HausAnschlussRo>());
            }
            _hausanschlussByObjectId[objectId].Add(haro);
            return(haro);
        }
        protected override Prosumer ProvidePrivateProfile([NotNull] ProviderParameterDto ppdto)
        {
            BuildingInfrastructure be = (BuildingInfrastructure)ppdto.HouseComponent;

            if (be.HouseComponentType == HouseComponentType.Infrastructure)
            {
                Hausanschluss ha = _dbDto.Hausanschlusse.Single(x => x.Guid == be.HausAnschlussGuid);
                var           pa = new Prosumer(be.HouseGuid,
                                                be.Standort ?? "nameless house infrastructure",
                                                be.HouseComponentType,
                                                be.SourceGuid,
                                                be.FinalIsn,
                                                be.HausAnschlussGuid,
                                                ha.ObjectID,
                                                GenerationOrLoad.Load,
                                                ha.Trafokreis, Name, "Flat House Infrastructure");
                pa.Profile = Profile.MakeConstantProfile(be.EffectiveEnergyDemand, "Flat House Infrastucture", Profile.ProfileResolution.QuarterHour);
                if (pa.Profile.EnergyOrPower == EnergyOrPower.Power)
                {
                    pa.Profile = pa.Profile.ConvertFromPowerToEnergy();
                }

                pa.SumElectricityPlanned = be.EffectiveEnergyDemand;
                return(pa);
            }
            throw new FlaException("No profile could be created");
        }
示例#6
0
        protected override void RunActualProcess([NotNull] ScenarioSliceParameters parameters)
        {
            var dbDstProfiles = Services.SqlConnection.GetDatabaseConnection(Stage.ProfileGeneration, parameters);
            var dbSrcProfiles = Services.SqlConnection.GetDatabaseConnection(Stage.ProfileImport, Constants.PresentSlice).Database;
            var vdewvals      = dbSrcProfiles.Fetch <VDEWProfileValues>();
            var dbHouses      = Services.SqlConnection.GetDatabaseConnection(Stage.Houses, parameters).Database;
            var houses        = dbHouses.Fetch <House>();

            Prosumer.ClearProsumerTypeFromDB(Services.SqlConnection.GetDatabaseConnection(Stage.ProfileGeneration,
                                                                                          parameters), ProsumerType.Household, TableType.HousePart);
            var slp = new SLPProvider(parameters.DstYear);
            //var houses = dbHouses.Fetch<House>();
            var households = dbHouses.Fetch <Household>();

            //var trafoKreise = dbDstProfiles.Database.Fetch<TrafoKreisResult>();
            Log(MessageType.Info, "making " + households.Count + " households");
            var sa = Prosumer.GetSaveableEntry(dbDstProfiles, TableType.HousePart);
            // && idx < 20
            double totalHouseholdEnergy = 0;
            double totalProfileEnergy   = 0;

            for (var idx = 0; idx < households.Count; idx++)
            {
                var           household = households[idx];
                House         house     = houses.Single(x => x.HouseGuid == household.HouseGuid);
                Hausanschluss ha        = house.Hausanschluss.Single(x => x.HausanschlussGuid == household.HausAnschlussGuid);
                // ReSharper disable once UseObjectOrCollectionInitializer
                var pa = new Prosumer(household.HouseGuid, household.StandortIDsAsJson,
                                      ProsumerType.Household, household.HouseholdGuid,
                                      household.FinalIsn, household.HausAnschlussGuid, ha.ObjectID);
                pa.Profile = slp.Run(vdewvals, "H0", household.LowVoltageYearlyTotalElectricityUse);
                pa.SumElectricityPlanned = household.LowVoltageYearlyTotalElectricityUse;
                sa.RowEntries.Add(pa.GetRow());
                totalHouseholdEnergy += pa.SumElectricityPlanned;
                totalProfileEnergy   += pa.Profile?.EnergySum() ?? 0;
                if (sa.RowEntries.Count > 1000)
                {
                    sa.SaveDictionaryToDatabase();
                }
            }
            sa.SaveDictionaryToDatabase();
            if (Math.Abs(totalHouseholdEnergy - totalProfileEnergy) > 1)
            {
                throw new FlaException("energy sums not equal between planned energy and energy in profiles");
            }
            Info("Total Household energy: " + totalHouseholdEnergy);

            /*
             * var loadedProsumers = Prosumer.LoadProsumers(dbDstProfiles, TableType.HousePart);
             * foreach (Prosumer loadedProsumer in loadedProsumers) {
             * Log(MessageType.Info,loadedProsumer.Name + " - " + loadedProsumer.SumElectricityFromProfile + " - " + loadedProsumer.Profile?.Values.Sum() );
             * }*/
            //dbDstProfiles.Database.CompleteTransaction();
        }
        private static Row MakeHausanschlussRow([NotNull] Hausanschluss ha)
        {
            var rbh = RowBuilder.Start("HA Adress", ha.Adress);

            rbh.Add("Trafokreis", ha.Trafokreis);
            rbh.Add("MatchingType", ha.MatchingType.ToString());
            rbh.Add("Distance", ha.Distance);
            rbh.Add("ObjektID", ha.ObjectID);
            rbh.Add("Isn", ha.Isn);
            return(rbh.GetRow());
        }
        protected override Prosumer ProvidePrivateProfile([NotNull] ProviderParameterDto ppdto)
        {
            BusinessEntry be = (BusinessEntry)ppdto.HouseComponent;

            if (be.BusinessType == BusinessType.Unknown)
            {
                throw new FlaException("unknown business type");
            }

            ppdto.HouseComponentResultObject.BusinessCategory = be.BusinessType.ToString();
            //string profileToUse = GetCorrectProfile(be.BusinessType);
            if (be.HouseComponentType == HouseComponentType.BusinessNoLastgangLowVoltage)
            {
                Hausanschluss ha      = _dbDto.Hausanschlusse.Single(x => x.Guid == be.HausAnschlussGuid);
                var           profile = GetCorrectProfile(be.BusinessType, be.EffectiveEnergyDemand, be);
                var           pa      = new Prosumer(be.HouseGuid,
                                                     be.Standort,
                                                     be.HouseComponentType,
                                                     be.Guid,
                                                     be.FinalIsn,
                                                     be.HausAnschlussGuid,
                                                     ha.ObjectID,
                                                     GenerationOrLoad.Load,
                                                     ha.Trafokreis,
                                                     Name,
                                                     profile.Name);
                pa.Profile = profile;
                pa.SumElectricityPlanned = be.EffectiveEnergyDemand;
                return(pa);
            }

            if (be.HouseComponentType == HouseComponentType.BusinessNoLastgangHighVoltage)
            {
                Hausanschluss ha      = _dbDto.Hausanschlusse.Single(x => x.Guid == be.HausAnschlussGuid);
                var           profile = GetCorrectProfile(be.BusinessType, be.EffectiveEnergyDemand, be);
                var           pa      = new Prosumer(be.HouseGuid,
                                                     be.Standort,
                                                     be.HouseComponentType,
                                                     be.Guid,
                                                     be.FinalIsn,
                                                     be.HausAnschlussGuid,
                                                     ha.ObjectID,
                                                     GenerationOrLoad.Load,
                                                     ha.Trafokreis,
                                                     Name,
                                                     profile.Name);
                pa.Profile = GetCorrectProfile(be.BusinessType, be.EffectiveEnergyDemand, be);
                pa.SumElectricityPlanned = be.EffectiveEnergyDemand;
                ppdto.HouseComponentResultObject.ProcessingStatus = "High Voltage Supplied Business without RLM";
                return(pa);
            }

            throw new FlaException("No profile could be created");
        }
        private static void LogAssignment([NotNull][ItemNotNull] List <LastgangZuordnung> lgzs,
                                          [NotNull] string rlmfn,
                                          [NotNull] Hausanschluss ha,
                                          [NotNull][ItemNotNull] List <LastgangZuordnung> successfullAssignments,
                                          [NotNull] RowCollection rc,
                                          [NotNull] string name,
                                          [NotNull] string standort,
                                          [NotNull][ItemNotNull] List <HausanschlussImportSupplement> supps,
                                          [NotNull] string srctype,
                                          double targetSum,
                                          double assignedSum,
                                          [NotNull] string housename,
                                          int isn)
        {
            var lgz = lgzs.First(x => rlmfn.Contains(x.FileName));

            successfullAssignments.Add(lgz);
            RowBuilder rb = new RowBuilder();

            rc.Add(rb);
            rb.Add("Typ", srctype);
            rb.Add("Name", name);
            rb.Add("Hausname", housename);
            rb.Add("Standort", standort);
            rb.Add("ISN", isn);
            rb.Add("Zugeordnete ObjektID", ha.ObjectID);
            rb.Add("MyFile", rlmfn);
            rb.Add("Profilename", lgz.FileName);
            rb.Add("Diren Knoten", lgz.Knoten);
            rb.Add("Abrechnungssumme", targetSum);
            rb.Add("Profilesumme", assignedSum);
            rb.Add("Skalierungsfaktor", targetSum / assignedSum);
            if (!string.Equals(ha.ObjectID, lgz.Knoten, StringComparison.CurrentCultureIgnoreCase))
            {
                rb.Add("Zuordnung", "Anders");
            }

            var supp = supps.FirstOrDefault(x => x.TargetStandort == standort);

            if (supp != null)
            {
                rb.Add("Explizite Zuordnung", "ja");
            }
        }
        private Prosumer ProvideLPGProfile([NotNull] ProviderParameterDto parameters,
                                           [NotNull] Hausanschluss ha,
                                           [NotNull] Household household,
                                           [NotNull] CarDistanceEntry carDistanceEntry)
        {
            string prosumerName = household.Name;
            string sourceGuid   = household.SourceGuid;
            string householdKey = household.HouseholdKey;
            long   isn          = household.FinalIsn;

            try {
                var prosumer = _lpgProfileLoader.LoadProsumer(parameters,
                                                              ha,
                                                              prosumerName,
                                                              carDistanceEntry.HouseComponentType,
                                                              LoadtypetoSearchFor,
                                                              _saveableEntry,
                                                              sourceGuid,
                                                              householdKey,
                                                              household.HouseGuid,
                                                              isn,
                                                              Services.RunningConfig);
                if (prosumer == null)
                {
                    return(null);
                }

                if (prosumer.Profile == null)
                {
                    throw new FlaException("Profile was null");
                }

                parameters.HouseComponentResultObject.ActualDrivingDistance = prosumer.Profile.EnergySum() / 15.0 * 100;
                return(prosumer);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex) {
#pragma warning restore CA1031 // Do not catch general exception types
                Error(ex.Message);
                parameters.HouseComponentResultObject.ErrorMessage = ex.Message;
            }

            return(null);
        }
        protected override void RunActualProcess()
        {
            var dbHouse = Services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Houses, Constants.PresentSlice);

            dbHouse.RecreateTable <BuildingInfrastructure>();
            //load data
            var potentialBuildingInfrastructures = dbHouse.Fetch <PotentialBuildingInfrastructure>();
            var houses          = dbHouse.Fetch <House>();
            var hausanschlusses = dbHouse.Fetch <Hausanschluss>();

            dbHouse.BeginTransaction();
            int    count       = 0;
            double totalEnergy = 0;

            foreach (var pb in potentialBuildingInfrastructures)
            {
                House         house = houses.Single(x => x.Guid == pb.HouseGuid);
                Hausanschluss ha    = house.GetHausanschlussByIsn(pb.Isns, pb.Standort, hausanschlusses, Services.Logger) ??
                                      throw new FlaException("no hausanschluss");
                if (pb.Isns.Count == 0)
                {
                    throw new FlaException("Not a single isn");
                }

                var bi = new BuildingInfrastructure(pb.Geschäftspartner,
                                                    pb.LowVoltageTotalElectricityDemand,
                                                    pb.HighVoltageTotalElectricityDemand,
                                                    pb.Isns,
                                                    pb.Isns[0],
                                                    pb.HouseGuid,
                                                    ha.Guid,
                                                    pb.Guid,
                                                    pb.Standort,
                                                    pb.Geschäftspartner);
                count++;
                totalEnergy += bi.EffectiveEnergyDemand;
                dbHouse.Save(bi);
            }

            dbHouse.CompleteTransaction();
            Info("Infrastructure: " + count);
            Info("Energy: " + totalEnergy.ToString("N1"));
        }
        public void AddHouseComponent([NotNull] House house, [NotNull] Hausanschluss hausanschluss, [NotNull] IHouseComponent component)
        {
            string houseName         = house.ComplexName;
            string hausanschlussGuid = hausanschluss.Guid;
            string name = component.Name;
            var    housecomponenetType = component.HouseComponentType;
            double lowVoltageEnergy    = component.LocalnetLowVoltageYearlyTotalElectricityUse;
            double highVoltageEnergy   = component.LocalnetHighVoltageYearlyTotalElectricityUse;

            const string     processingStatus = "unkown;";
            var              houseRo          = Houses.Single(x => x.HouseName == houseName);
            var              hausanschlussRo  = houseRo.HausAnschlussList.Single(x => x.HausanschlussGuid == hausanschlussGuid);
            HouseComponentRo hc = new HouseComponentRo(
                name, housecomponenetType.ToString(), lowVoltageEnergy,
                highVoltageEnergy, processingStatus,
                JsonConvert.SerializeObject(component.OriginalISNs, Formatting.Indented), component.Standort, component.EffectiveEnergyDemand);

            hausanschlussRo.HouseComponents.Add(hc);
            _houseComponenetsRosByComponent.Add(component, hc);
        }
示例#13
0
        protected override Prosumer ProvidePrivateProfile([NotNull] ProviderParameterDto ppdto)
        {
            DHWHeaterEntry dhw = (DHWHeaterEntry)ppdto.HouseComponent;

            if (dhw.HouseComponentType != HouseComponentType.Dhw)
            {
                throw new FlaException("Wrong type");
            }

            ppdto.HouseComponentResultObject.DhwSystemType = dhw.DhwHeatingSystemType.ToString();
            if (dhw.DhwHeatingSystemType != DhwHeatingSystem.Electricity && dhw.DhwHeatingSystemType != DhwHeatingSystem.Heatpump)
            {
                ppdto.HouseComponentResultObject.HeatingSystemMessage = "Not electric heating";
                return(null);
            }

            Hausanschluss ha = _dbDto.Hausanschlusse.Single(x => x.Guid == dhw.HausAnschlussGuid);
            var           pa = new Prosumer(dhw.HouseGuid,
                                            dhw.Name,
                                            dhw.HouseComponentType,
                                            dhw.SourceGuid,
                                            dhw.FinalIsn,
                                            dhw.HausAnschlussGuid,
                                            ha.ObjectID,
                                            GenerationOrLoad.Load,
                                            ha.Trafokreis,
                                            Name,
                                            "DHW Profile Generator");
            //todo: randomize this with buckets and/or simulate a central control
            int startTime = 2 * 4 + Services.Rnd.Next(12);
            int stopTime  = startTime + 3 * 4 + Services.Rnd.Next(12);
            //double targetRuntimePerDay = 3*4 + Services.Rnd.NextDouble() * 4;
            double trigger = 1 - 0.05 * Services.Rnd.NextDouble();
            DhwCalculationParameters dhwCalculationParameters = new DhwCalculationParameters(startTime, stopTime, trigger);
            var dhwResult = _dhw.Run(dhwCalculationParameters, dhw.EffectiveEnergyDemand, Services.Rnd);

            pa.Profile = dhwResult.GetEnergyDemandProfile();
            return(pa);
        }
        protected override Prosumer ProvidePrivateProfile([NotNull] ProviderParameterDto ppdto)
        {
            AirConditioningEntry hse = (AirConditioningEntry)ppdto.HouseComponent;

            if (hse.HouseComponentType != HouseComponentType.Cooling)
            {
                throw new FlaException("Wrong type");
            }

            Hausanschluss ha = _dbDto.Hausanschlusse.Single(x => x.Guid == hse.HausAnschlussGuid);
            var           pa = new Prosumer(hse.HouseGuid,
                                            hse.Standort,
                                            hse.HouseComponentType,
                                            hse.SourceGuid,
                                            hse.FinalIsn,
                                            hse.HausAnschlussGuid,
                                            ha.ObjectID,
                                            GenerationOrLoad.Load,
                                            ha.Trafokreis,
                                            Name,
                                            "Cooling State Engine");

            // todo: randomize this with buckets and/or simulate a central control
            double targetRuntimePerDay       = 2 + Services.Rnd.NextDouble() * 2;
            double trigger                   = 1 - Services.Rnd.NextDouble() * 0.1;
            CoolingCalculationParameters hpc = new CoolingCalculationParameters(targetRuntimePerDay, trigger);
            var hpr = _coolingProfileGeneratorsByType[hse.AirConditioningType].Run(hpc, hse.EffectiveEnergyDemand, Services.Rnd);

            ppdto.HouseComponentResultObject.CoolingType = hse.AirConditioningType.ToString();
            pa.Profile = hpr.GetEnergyDemandProfile().ScaleToTargetSum(hse.EffectiveEnergyDemand, "Air Conditioning Profile", out var _);
            if (Math.Abs(pa.Profile.EnergySum() - hse.EffectiveEnergyDemand) > 1)
            {
                throw new FlaException("Energy sum from the cooling is all wrong. Should be " + hse.EffectiveEnergyDemand + " but was " +
                                       pa.Profile.EnergySum());
            }

            return(pa);
        }
        public bool PrepareLoadProfileIfNeeded([NotNull] ProviderParameterDto parameters)
        {
            CarDistanceEntry cde = (CarDistanceEntry)parameters.HouseComponent;
            Car myCar            = _dbDto.Cars.Single(x => x.Guid == cde.CarGuid);

            parameters.HouseComponentResultObject.CarStatus = "Gasoline, not analyzed further";

            if (myCar.RequiresProfile == CarProfileRequirement.NoProfile)
            {
                return(true);
            }

            Hausanschluss ha = _dbDto.Hausanschlusse.Single(x => x.Guid == cde.HausAnschlussGuid);

            parameters.HouseComponentResultObject.CarStatus            = "Electric";
            parameters.HouseComponentResultObject.CommutingDistance    = cde.CommutingDistance;
            parameters.HouseComponentResultObject.OtherDrivingDistance = cde.FreizeitDistance;
            Household flaHousehold = _dbDto.Households.FirstOrDefault(x => x.Guid == cde.HouseholdGuid);

            if (flaHousehold == null)
            {
                parameters.HouseComponentResultObject.CarStatus += ", no household";
                throw new FlaException("no household found");
            }

            var house = _dbDto.Houses.FirstOrDefault(x => x.HouseGuid == cde.HouseGuid);

            if (house == null)
            {
                throw new FlaException("no house found");
            }

            HouseholdData householdData = null;

            if (_housesToBeCreated.Count > 0)
            {
                var houseJob = _housesToBeCreated.FirstOrDefault(x => x.House.HouseGuid == ha.HouseGuid);
                if (houseJob == null)
                {
                    parameters.HouseComponentResultObject.CarStatus += ", no house";

                    throw new FlaException("no house found");
                }

                householdData = houseJob.House.Households.FirstOrDefault(x => x.HouseholdGuid == flaHousehold.HouseholdKey);
                if (householdData == null)
                {
                    parameters.HouseComponentResultObject.CarStatus += ", no household guid";
                    throw new FlaException("no household for household guid " + cde.HouseholdGuid);
                }


                //set lpg parameters
                householdData.UseElectricCar = ElectricCarUse.UseElectricCar;

                //find number of cars
                var householdCars = _dbDto.Cars.Where(x => x.HouseholdGuid == cde.HouseholdGuid).ToList();
                switch (householdCars.Count)
                {
                case 1:
                    //use lpg profile for a single car
                    householdData.TransportationDeviceSet = TransportationDevicesTwoCar;
                    break;

                case 2:
                    //use lpg profile for a single car
                    householdData.TransportationDeviceSet = TransportationDevicesTwoCar;
                    break;

                case 3:
                    // use lpg profile for a single car
                    // todo: fix this and put in the right transportation device set
                    householdData.TransportationDeviceSet = TransportationDevicesTwoCar;
                    break;

                case 4:
                    //use lpg profile for a single car
                    //todo: fix this and put in the right transportation device set
                    householdData.TransportationDeviceSet = TransportationDevicesTwoCar;
                    break;

                default: throw new FlaException("Household with " + householdCars.Count + " cars is missing");
                }

                householdData.TravelRouteSet     = TravelRouteSet;
                householdData.ChargingStationSet = ChargingStationSet;
                if (householdData.TransportationDistanceModifiers == null)
                {
                    householdData.TransportationDistanceModifiers = new List <TransportationDistanceModifier>();
                }

                householdData.TransportationDistanceModifiers.Add(new TransportationDistanceModifier("Work", "Car", cde.CommutingDistance * 1000));
                householdData.TransportationDistanceModifiers.Add(new TransportationDistanceModifier("Entertainment",
                                                                                                     "Car",
                                                                                                     cde.FreizeitDistance * 1000));
                parameters.HouseComponentResultObject.CarStatus += ", asking for repare with distances commuting: " + cde.CommutingDistance +
                                                                   ", free time: " + cde.FreizeitDistance + " km";
            }

            if (Services.RunningConfig.LpgPrepareMode == LpgPrepareMode.PrepareWithFullLpgLoad)
            {
                Profile lpgProfile = null;
                try {
                    lpgProfile = _lpgProfileLoader.LoadLPGProfile(parameters,
                                                                  ha.Trafokreis,
                                                                  LoadtypetoSearchFor,
                                                                  _saveableEntry,
                                                                  flaHousehold.HouseholdKey,
                                                                  out _,
                                                                  house.ComplexName,
                                                                  Services.RunningConfig);
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch (Exception ex) {
#pragma warning restore CA1031 // Do not catch general exception types
                    Error("trying to load lpg profile: " + ex.Message);
                    parameters.HouseComponentResultObject.LPGErrors = "trying to load lpg profile failed: " + ex.Message;
                }

                // ReSharper disable PossibleNullReferenceException
                if (_housesToBeCreated.Count > 0)
                {
                    if (lpgProfile != null)
                    {
                        householdData.IsCarProfileCalculated = true;
                        parameters.HouseComponentResultObject.ProcessingStatus = "Found LPG profile on full check";
                    }
                    else
                    {
                        householdData.IsCarProfileCalculated = false;
                        parameters.HouseComponentResultObject.ProcessingStatus = "Missing LPG profile on full check";
                    }
                }
                // ReSharper restore PossibleNullReferenceException
            }
            else if (Services.RunningConfig.LpgPrepareMode == LpgPrepareMode.PrepareWithOnlyNamecheck)
            {
                // ReSharper disable PossibleNullReferenceException
                if (_housesToBeCreated.Count > 0)
                {
                    if (_saveableEntry.CheckForName(flaHousehold.HouseholdKey, Services.Logger))
                    {
                        householdData.IsHouseholdProfileCalculated             = true;
                        parameters.HouseComponentResultObject.ProcessingStatus = "Found LPG profile on name check";
                    }
                    else
                    {
                        householdData.IsHouseholdProfileCalculated             = false;
                        parameters.HouseComponentResultObject.ProcessingStatus = "Miissing LPG profile on name check";
                    }
                }
                // ReSharper restore PossibleNullReferenceException
            }
            else
            {
                throw new FlaException("Unknown lpg prepare mode");
            }

            return(true);
        }
        protected override Prosumer ProvidePrivateProfile([NotNull] ProviderParameterDto ppdto)
        {
            HeatingSystemEntry hse = (HeatingSystemEntry)ppdto.HouseComponent;

            if (hse.HouseComponentType != HouseComponentType.Heating)
            {
                throw new FlaException("Wrong type");
            }

            ppdto.HouseComponentResultObject.HeatingSystemType = hse.SynthesizedHeatingSystemType;
            if (hse.SynthesizedHeatingSystemType != HeatingSystemType.Heatpump && hse.SynthesizedHeatingSystemType != HeatingSystemType.Electricity)
            {
                ppdto.HouseComponentResultObject.HeatingSystemMessage = "Not electric heating";
                return(null);
            }

            if (!hse.ProvideProfile)
            {
                return(null);
            }

            if (hse.HausAnschlussGuid == null)
            {
                return(null);
            }

            Hausanschluss ha = _dbDto.Hausanschlusse.Single(x => x.Guid == hse.HausAnschlussGuid);

            if (ha.ObjectID.ToLower().Contains("kleinanschluss"))
            {
                throw new FlaException("Heizung am kleinanschluss?");
            }

            var pa = new Prosumer(hse.HouseGuid,
                                  hse.Standort,
                                  hse.HouseComponentType,
                                  hse.SourceGuid,
                                  hse.FinalIsn,
                                  hse.HausAnschlussGuid,
                                  ha.ObjectID,
                                  GenerationOrLoad.Load,
                                  ha.Trafokreis,
                                  Name,
                                  "Heatpump Profile Generator");
            //todo: randomize this with buckets and/or simulate a central control
            int    morningTime                = 4 * 4 + Services.Rnd.Next(8);
            int    eveningTime                = 20 * 4 + Services.Rnd.Next(8);
            double targetRuntimePerDay        = 16 + Services.Rnd.NextDouble() * 4;
            double trigger                    = 1 - Services.Rnd.NextDouble() * 0.1;
            HeatpumpCalculationParameters hpc = new HeatpumpCalculationParameters(HeatPumpTimingMode.OverTheEntireDay,
                                                                                  morningTime,
                                                                                  eveningTime,
                                                                                  targetRuntimePerDay,
                                                                                  trigger,
                                                                                  1);

            hpc.StartLevelPercent = 1 - Services.Rnd.NextDouble() * .5;
            var hpr = _hpg.Run(hpc, hse.EffectiveEnergyDemand, Services.Rnd);

            pa.Profile = hpr.GetEnergyDemandProfile();
            return(pa);
        }
        protected override void RunActualProcess([NotNull] ScenarioSliceParameters slice)
        {
            var dbSrcHouses = Services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Houses, slice.PreviousSliceNotNull);
            var dbDstHouses = Services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Houses, slice);

            dbDstHouses.RecreateTable <AirConditioningEntry>();
            var srcAirconditioningEntries = dbSrcHouses.Fetch <AirConditioningEntry>();
            var srcHouses       = dbSrcHouses.Fetch <House>();
            var airConGuids     = srcAirconditioningEntries.Select(x => x.HouseGuid).ToList();
            var hausanschlusess = dbSrcHouses.Fetch <Hausanschluss>();
            var businesses      = dbDstHouses.Fetch <BusinessEntry>();
            var housesWithoutAirconditioning1 = srcHouses.Where(x => !airConGuids.Contains(x.Guid)).ToList();

            if (housesWithoutAirconditioning1.Count == 0)
            {
                throw new FlaException("no houses left without airconditioning");
            }

            foreach (var conditioningEntry in srcAirconditioningEntries)
            {
                conditioningEntry.HausAnschlussGuid.Should().NotBeNullOrWhiteSpace();
                var ha = hausanschlusess.First(x => x.Guid == conditioningEntry.HausAnschlussGuid);
                if (ha.ObjectID.ToLower().Contains("kleinanschluss"))
                {
                    throw new FlaException("No ac at kleinanschluss");
                }
            }

            // ReSharper disable once ArrangeLocalFunctionBody
            double CalculateYearlyAirConditioningEnergyConsumption(House h) =>
            h.EnergieBezugsFläche * slice.AirConditioningEnergyIntensityInKWhPerSquareMeter;

            double totalEbf = srcHouses.Sum(x => x.EnergieBezugsFläche);
            double totalTargetAirConditioning =
                totalEbf * slice.PercentageOfAreaWithAirConditioning * slice.AirConditioningEnergyIntensityInKWhPerSquareMeter;
            double currentAirConditioning = srcAirconditioningEntries.Sum(x => x.EffectiveEnergyDemand);
            double newlyInstealledEnergyForAirconditioning = totalTargetAirConditioning - currentAirConditioning;

            if (newlyInstealledEnergyForAirconditioning < 0)
            {
                throw new FlaException("Negative air conditioning target. Currently installed in " + slice + " are " +
                                       currentAirConditioning / (totalEbf * slice.AirConditioningEnergyIntensityInKWhPerSquareMeter));
            }

            bool failOnOver = slice.DstYear != 2050;
            WeightedRandomAllocator <House> allocator = new WeightedRandomAllocator <House>(Services.Rnd, Services.Logger);
            var housesForAirConditioning = allocator.PickObjectUntilLimit(housesWithoutAirconditioning1,
                                                                          x => x.EnergieBezugsFläche,
                                                                          CalculateYearlyAirConditioningEnergyConsumption,
                                                                          newlyInstealledEnergyForAirconditioning,
                                                                          failOnOver);
            var dstAirConditioningEntries = new List <AirConditioningEntry>();

            foreach (var house in housesForAirConditioning)
            {
                var businessesInHouse   = businesses.Where(x => x.HouseGuid == house.Guid).ToList();
                AirConditioningType act = AirConditioningType.Commercial;
                if (businessesInHouse.Count == 0)
                {
                    act = AirConditioningType.Residential;
                }

                foreach (var entry in businessesInHouse)
                {
                    if (entry.BusinessType == BusinessType.Industrie)
                    {
                        act = AirConditioningType.Industrial;
                    }
                }

                Hausanschluss ha = house.GetHausanschlussByIsn(new List <int>(), null, hausanschlusess, MyLogger, false);
                if (ha != null && ha.ObjectID.ToLower().Contains("kleinanschluss"))
                {
                    ha = null;
                }

                if (ha != null)
                {
                    var ace = new AirConditioningEntry(house.Guid,
                                                       Guid.NewGuid().ToString(),
                                                       CalculateYearlyAirConditioningEnergyConsumption(house),
                                                       1,
                                                       act,
                                                       ha.Guid,
                                                       house.ComplexName + " - Air Conditioning",
                                                       "");
                    dstAirConditioningEntries.Add(ace);
                }
            }

            foreach (var airconditioningEntry in srcAirconditioningEntries)
            {
                airconditioningEntry.ID = 0;
                dstAirConditioningEntries.Add(airconditioningEntry);
            }

            //final checks
            foreach (var dstAirConditioningEntry in dstAirConditioningEntries)
            {
                dstAirConditioningEntry.HausAnschlussGuid.Should().NotBeNullOrWhiteSpace();
                var ha = hausanschlusess.First(x => x.Guid == dstAirConditioningEntry.HausAnschlussGuid);
                if (ha.ObjectID.ToLower().Contains("kleinanschluss"))
                {
                    throw new FlaException("No ac at kleinanschluss");
                }
            }

            dbDstHouses.BeginTransaction();
            foreach (var airConditioningEntry in dstAirConditioningEntries)
            {
                dbDstHouses.Save(airConditioningEntry);
            }

            dbDstHouses.CompleteTransaction();
        }
        private Prosumer ProvideLPGProfile([NotNull] ProviderParameterDto parameters, [NotNull] Hausanschluss ha, [NotNull] Household household)
        {
            string prosumerName = household.Name;
            const HouseComponentType houseComponentType = HouseComponentType.Household;
            string sourceGuid   = household.SourceGuid;
            string householdKey = household.HouseholdKey;
            long   isn          = household.FinalIsn;

            return(_lpgloader.LoadProsumer(parameters,
                                           ha,
                                           prosumerName,
                                           houseComponentType,
                                           LoadtypetoSearchFor,
                                           _saveableEntry,
                                           sourceGuid,
                                           householdKey,
                                           household.HouseGuid,
                                           isn,
                                           Services.RunningConfig));
        }
示例#19
0
        private Household MakeSingleNewHousehold([NotNull] ScenarioSliceParameters slice,
                                                 [NotNull][ItemNotNull]
                                                 List <Hausanschluss> hausanschlusses,
                                                 int i,
                                                 [NotNull] MyDb persistenceDb,
                                                 [NotNull][ItemNotNull]
                                                 List <HouseWithHouseholds> allhwhs,
                                                 [NotNull][ItemNotNull]
                                                 List <Household> newHouseholds)
        {
            if (allhwhs == null)
            {
                throw new ArgumentNullException(nameof(allhwhs));
            }

            var filteredhwhs = allhwhs.Where(x => x.RemainingOpenHouseholds > 0).ToList();

            if (filteredhwhs.Count == 0)
            {
                var potentialHwhForExpansion = allhwhs.Where(x => x.Households.Count > 0 && x.RemainingOpenHouseholds == 0).ToList();
                if (potentialHwhForExpansion.Count == 0)
                {
                    potentialHwhForExpansion = allhwhs.Where(x => x.Households.Count > 0).ToList();
                    if (potentialHwhForExpansion.Count == 0)
                    {
                        throw new FlaException("Could not find anything for adding hhs");
                    }
                }

                var    pickedhwh = potentialHwhForExpansion[Services.Rnd.Next(potentialHwhForExpansion.Count)];
                double avgEbf    = pickedhwh.House.Appartments.Average(x => x.EnergieBezugsFläche);
                while (pickedhwh.RemainingOpenHouseholds < 1)
                {
                    pickedhwh.House.Appartments.Add(new AppartmentEntry(Guid.NewGuid().ToString(), avgEbf, true, slice.DstYear));
                }

                pickedhwh.House.Appartments.Add(new AppartmentEntry(Guid.NewGuid().ToString(), avgEbf, true, slice.DstYear));
                filteredhwhs = allhwhs.Where(x => x.RemainingOpenHouseholds > 0).ToList();
                if (filteredhwhs.Count == 0)
                {
                    throw new FlaException("?");
                }
            }

            var           hwh           = filteredhwhs[Services.Rnd.Next(filteredhwhs.Count)];
            Hausanschluss hausanschluss = hwh.House.GetHausanschlussByIsn(new List <int>(), null, hausanschlusses, MyLogger) ??
                                          throw new FlaException("no hausanschluss");
            var hh = new Household("new hh " + i + " from " + slice,
                                   hwh.House.Guid,
                                   hausanschluss.Guid,
                                   hwh.House.ComplexName,
                                   hausanschluss.Standort,
                                   Guid.NewGuid().ToString());
            PersistenceMigrationHouseholdEntry nhhe = new PersistenceMigrationHouseholdEntry(hwh.House.ComplexName, hh.Name, hausanschluss.ObjectID);

            persistenceDb.Save(nhhe);
            hwh.Households.Add(hh);

            newHouseholds.Add(hh);
            return(hh);
        }
 public HouseComponentEntry([NotNull] IHouseComponent component, [NotNull] Hausanschluss hausanschluss, [NotNull] House house)
 {
     Component     = component;
     Hausanschluss = hausanschluss;
     House         = house;
 }
        protected override void RunActualProcess(ScenarioSliceParameters slice)
        {
            if (!slice.Equals(Constants.PresentSlice))
            {
                return;
            }

            var dbHouses = Services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Houses, slice);

            Info("using house db in  " + dbHouses.ConnectionString);
            var houses = dbHouses.Fetch <House>();
            HouseComponentRepository hcr = new HouseComponentRepository(dbHouses);
            var hausanschlusses          = dbHouses.Fetch <Hausanschluss>();
            var dbRaw                   = Services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Raw, Constants.PresentSlice);
            var suppIsn                 = dbRaw.Fetch <HausanschlussImportSupplement>();
            var standortDict            = new Dictionary <string, string>();
            var rlms                    = dbRaw.Fetch <RlmProfile>();
            List <AssignmentEntry> ases = new List <AssignmentEntry>();

            foreach (var supplement in suppIsn)
            {
                if (!string.IsNullOrWhiteSpace(supplement.TargetStandort))
                {
                    if (standortDict.ContainsKey(supplement.TargetStandort))
                    {
                        throw new FlaException("Already contains standort " + supplement.TargetStandort);
                    }

                    standortDict.Add(supplement.TargetStandort, supplement.HaObjectid);
                }

                AssignmentEntry ase = ases.FirstOrDefault(x => x.ObjectId == supplement.HaObjectid);
                if (ase == null)
                {
                    ase = new AssignmentEntry(supplement.HaObjectid);
                    ases.Add(ase);
                }

                ase.Targets.Add(supplement.TargetStandort);
                ase.TargetCount++;
            }

            List <string>        checkedStandorte       = new List <string>();
            var                  lgzs                   = ReadZuordnungLastgänge();
            var                  successfullAssignments = new List <LastgangZuordnung>();
            RowCollection        rc = new RowCollection("sheet", "Sheet1");
            List <PvSystemEntry> assignedPVsystems = new List <PvSystemEntry>();
            List <PvSystemEntry> otherPVsystems    = new List <PvSystemEntry>();

            foreach (House house in houses)
            {
                var houseComponents = house.CollectHouseComponents(hcr);
                foreach (var component in houseComponents)
                {
                    if (component.Standort == null)
                    {
                        continue;
                    }

                    if (standortDict.ContainsKey(component.Standort))
                    {
                        Hausanschluss ha             = hausanschlusses.Single(x => x.Guid == component.HausAnschlussGuid);
                        string        targetObjectID = standortDict[component.Standort];
                        if (ha.ObjectID != targetObjectID)
                        {
                            throw new FlaException("Incorrect hausanschluss for " + component.Name + ": was supposed to be " + targetObjectID +
                                                   " but instead was " + ha.ObjectID + " (standort: " + component.Standort);
                        }

                        var ase = ases.Single(x => x.ObjectId == ha.ObjectID);
                        ase.AssignedCount++;
                        ase.Assigned.Add(component.Standort);
                        checkedStandorte.Add(component.Standort);
                    }

                    if (component.HouseComponentType == HouseComponentType.BusinessWithLastgangHighVoltage)
                    {
                        var businessEntry = (BusinessEntry)component;
                        var rlmfn         = businessEntry.RlmProfileName ?? throw new FlaException("No file");
                        var ha            = hausanschlusses.First(x => x.Guid == businessEntry.HausAnschlussGuid);
                        var rlm           = rlms.Single(x => x.Name == businessEntry.RlmProfileName);
                        var energysum     = new Profile(rlm.Profile).EnergySum();
                        LogAssignment(lgzs,
                                      rlmfn,
                                      ha,
                                      successfullAssignments,
                                      rc,
                                      businessEntry.Name,
                                      businessEntry.Standort,
                                      suppIsn,
                                      "HS",
                                      businessEntry.EffectiveEnergyDemand,
                                      energysum,
                                      house.ComplexName,
                                      businessEntry.FinalIsn);
                    }

                    if (component.HouseComponentType == HouseComponentType.BusinessWithLastgangLowVoltage)
                    {
                        var businessEntry = (BusinessEntry)component;
                        var rlmfn         = businessEntry.RlmProfileName ?? throw new FlaException("no file?");
                        var ha            = hausanschlusses.First(x => x.Guid == businessEntry.HausAnschlussGuid);
                        var rlm           = rlms.Single(x => x.Name == businessEntry.RlmProfileName);
                        var energysum     = new Profile(rlm.Profile).EnergySum();
                        LogAssignment(lgzs,
                                      rlmfn,
                                      ha,
                                      successfullAssignments,
                                      rc,
                                      businessEntry.Name,
                                      businessEntry.Standort,
                                      suppIsn,
                                      "NS",
                                      businessEntry.EffectiveEnergyDemand,
                                      energysum,
                                      house.ComplexName,
                                      businessEntry.FinalIsn);
                    }

                    if (component.HouseComponentType == HouseComponentType.Kwkw)
                    {
                        var kwkw      = (KleinWasserkraft)component;
                        var rlmfn     = kwkw.RlmProfileName;
                        var ha        = hausanschlusses.First(x => x.Guid == kwkw.HausAnschlussGuid);
                        var rlm       = rlms.Single(x => x.Name == kwkw.RlmProfileName);
                        var energysum = new Profile(rlm.Profile).EnergySum();
                        LogAssignment(lgzs,
                                      rlmfn,
                                      ha,
                                      successfullAssignments,
                                      rc,
                                      kwkw.Name,
                                      kwkw.Standort,
                                      suppIsn,
                                      "WKW",
                                      kwkw.EffectiveEnergyDemand,
                                      energysum,
                                      house.ComplexName,
                                      kwkw.FinalIsn);
                    }

                    if (component.HouseComponentType == HouseComponentType.Photovoltaik)
                    {
                        var ha = hausanschlusses.First(x => x.Guid == component.HausAnschlussGuid);
                        if (lgzs.Any(x => string.Equals(x.Knoten.ToLower(), ha.ObjectID.ToLower(), StringComparison.InvariantCultureIgnoreCase)))
                        {
                            assignedPVsystems.Add((PvSystemEntry)component);
                        }
                        else
                        {
                            otherPVsystems.Add((PvSystemEntry)component);
                        }
                    }
                }
            }

            foreach (var zuordnung in lgzs)
            {
                if (!successfullAssignments.Contains(zuordnung))
                {
                    RowBuilder rb         = RowBuilder.Start("Lastgang", zuordnung.FileName).Add("Diren Profilename", zuordnung.Knoten);
                    var        has        = hausanschlusses.Where(x => x.ObjectID == zuordnung.Knoten).ToList();
                    var        haguids    = has.Select(x => x.Guid).Distinct().ToList();
                    var        pvs        = assignedPVsystems.Where(x => haguids.Contains(x.HausAnschlussGuid)).ToList();
                    var        houseGuids = has.Select(x => x.HouseGuid).Distinct().ToList();
                    var        otherPV    = otherPVsystems.Where(x => houseGuids.Contains(x.HouseGuid));
                    rb.Add("PV Systems", string.Join(";", pvs.Select(x => x.Name)));
                    rb.Add("Other PV Systems@house", string.Join(";", otherPV.Select(x => x.Name)));
                    var rlm = rlms.Where(x => x.Name.Contains(zuordnung.FileName)).ToList();
                    for (int i = 0; i < rlm.Count; i++)
                    {
                        var energysum = new Profile(rlm[i].Profile).EnergySum();
                        rb.Add("Profilesumme " + i, energysum);
                    }

                    rc.Add(rb);
                    if (has.Count > 0)
                    {
                        List <string> housenames = new List <string>();
                        foreach (var ha in has)
                        {
                            var house = houses.First(x => x.Guid == ha.HouseGuid);
                            housenames.Add(house.ComplexName);
                        }

                        rb.Add("Hausname", string.Join(",", housenames.Distinct()));
                    }
                }
            }

            foreach (var pVsystem in otherPVsystems)
            {
                House house = houses.First(x => x.Guid == pVsystem.HouseGuid);
                var   rb    = RowBuilder.Start("Hausname", house.ComplexName);
                rb.Add("Effective Energy", pVsystem.EffectiveEnergyDemand);
                rb.Add("Planned Energy", pVsystem.EffectiveEnergyDemand);
                var ha = hausanschlusses.First(x => x.Guid == pVsystem.HausAnschlussGuid);
                rb.Add("Zugeordnete ObjektID", ha.ObjectID);
                rc.Add(rb);
            }

            var fn = MakeAndRegisterFullFilename("WrongAssignments.xlsx", slice);

            XlsxDumper.WriteToXlsx(fn, rc);

            var missingAssigments = lgzs.Where(x => !successfullAssignments.Contains(x)).ToList();

            if (missingAssigments.Count > 0)
            {
                Info("Missing assignments: " + string.Join("\n", missingAssigments.Select(x => x.FileName)));
            }

            foreach (var pair in standortDict)
            {
                if (!checkedStandorte.Contains(pair.Key))
                {
                    //throw new FlaException("Didn't find supplemental standort " + pair.Value + " in the list of components. Typo?");
                }
            }

            foreach (var ase in ases)
            {
                foreach (var target in ase.Targets)
                {
                    if (!ase.Assigned.Contains(target))
                    {
                        //  throw new FlaException("Missing " + target + " from the list of assigned standorts");
                    }
                }

                foreach (var assigned in ase.Assigned)
                {
                    if (!ase.Targets.Contains(assigned))
                    {
                        //throw new FlaException("Missing " + assigned + " from the list of target standorts");
                    }
                }
            }
        }
        public bool PrepareLoadProfileIfNeeded([NotNull] ProviderParameterDto parameters)
        {
            if (parameters.HouseComponent.HouseComponentType != HouseComponentType.Household)
            {
                throw new FlaException("Was not household: " + parameters.HouseComponent.HouseComponentType);
            }

            Household     hh       = (Household)parameters.HouseComponent;
            Hausanschluss ha       = _dbDto.Hausanschlusse.Single(x => x.Guid == hh.HausAnschlussGuid);
            var           houseJob = _housesToBeCreated.FirstOrDefault(x => x.House.HouseGuid == hh.HouseGuid);

            if (houseJob == null)
            {
                var flahouse = _dbDto.Houses.Single(x => x.Guid == hh.HouseGuid);
                houseJob       = new HouseCreationAndCalculationJob(Slice.DstScenario.ToString(), Slice.DstYear.ToString(), ha.Trafokreis);
                houseJob.House = new HouseData(hh.HouseGuid, "HT01", 0, 0, flahouse.ComplexName);
                _housesToBeCreated.Add(houseJob);
            }

            HouseholdData hd = new HouseholdData(hh.HouseholdKey,
                                                 hh.EffectiveEnergyDemand,
                                                 ElectricCarUse.NoElectricCar,
                                                 hh.Name,
                                                 null,
                                                 null,
                                                 null,
                                                 null,
                                                 HouseholdDataSpecifictionType.ByPersons);

            hd.IsCarProfileCalculated           = true;
            hd.HouseholdDataPersonSpecification = new HouseholdDataPersonSpecification(new List <PersonData>());
            if (hh.Occupants.Count == 0)
            {
                throw new FlaException("No occupants in the household " + hh.Name);
            }

            foreach (var occupant in hh.Occupants)
            {
                hd.HouseholdDataPersonSpecification.Persons.Add(new PersonData(occupant.Age, (Gender)occupant.Gender));
            }

            House house = _dbDto.Houses.First(x => x.Guid == hh.HouseGuid);

            if (Services.RunningConfig.LpgPrepareMode == LpgPrepareMode.PrepareWithFullLpgLoad)
            {
                Profile lpgProfile = null;
                try {
                    lpgProfile = _lpgloader.LoadLPGProfile(parameters,
                                                           ha.Trafokreis,
                                                           LoadtypetoSearchFor,
                                                           _saveableEntry,
                                                           hh.HouseholdKey,
                                                           out _,
                                                           house.ComplexName,
                                                           Services.RunningConfig);
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch (Exception ex) {
#pragma warning restore CA1031 // Do not catch general exception types
                    parameters.HouseComponentResultObject.LPGErrors = "trying to load lpg profile failed: " + ex.Message;
                    Error("trying to load lpg profile: " + ex.Message);
                }

                if (lpgProfile != null)
                {
                    hd.IsHouseholdProfileCalculated = true;
                }
                else
                {
                    hd.IsHouseholdProfileCalculated = false;
                }
            }
            else if (Services.RunningConfig.LpgPrepareMode == LpgPrepareMode.PrepareWithOnlyNamecheck)
            {
                if (_saveableEntry.CheckForName(hh.HouseholdKey, Services.Logger))
                {
                    hd.IsHouseholdProfileCalculated = true;
                }
                else
                {
                    hd.IsHouseholdProfileCalculated = false;
                }
            }
            else
            {
                throw new FlaException("Unknown lpg prepare mode");
            }

            houseJob.House.Households.Add(hd);
            return(true);
        }
        protected override Prosumer ProvidePrivateProfile([NotNull] ProviderParameterDto ppdto)
        {
            Module.SetPrint(0);
            //var relevantPotentials = _pvPotentials.Where(x => x.HouseGuid == houseComponent.HouseGuid);
            PvSystemEntry entry = (PvSystemEntry)ppdto.HouseComponent;

            if (_dbDto.Hausanschlusse == null)
            {
                throw new FlaException("hausanschlüsse were not initalized");
            }
            if (_dbDto.Hausanschlusse.Count == 0)
            {
                throw new FlaException("not a single hausanschluss");
            }

            Hausanschluss hausanschluss = _dbDto.Hausanschlusse.FirstOrDefault(x => x.Guid == entry.HausAnschlussGuid);

            if (hausanschluss == null)
            {
                throw new FlaException("No hausanschluss found for guid: " + entry.HausAnschlussGuid);
            }

            if (hausanschluss.ObjectID.ToLower().Contains("leuchte"))
            {
                throw new FlaException("PV anlage an einer leuchte! " + hausanschluss.ObjectID + " - " + entry.Name);
            }
            //TODO: change this to use pv system areas from the pvsystem entry
            Profile sumProf = Profile.MakeConstantProfile(0, ppdto.HouseComponent.Name, Profile.ProfileResolution.QuarterHour);

            if (Math.Abs(entry.PVAreas.Sum(x => x.Energy) - entry.EffectiveEnergyDemand) > 0.1)
            {
                throw new FlaException("Sum of the pv areas did not match pv entry sum");
            }
            foreach (var area in entry.PVAreas)
            {
                var key          = MakeKeyFromPVArea(area);
                var keystr       = key.GetKey();
                var areaProfiles = _saveableEntries.LoadAllOrMatching("Name", keystr);
                if (areaProfiles.Count != 1)
                {
                    throw new FlaException("Invalid count");
                }

                var areaProfile = areaProfiles[0];
                areaProfile.EnergyOrPower = EnergyOrPower.Energy;
                areaProfile = areaProfile.ScaleToTargetSum(area.Energy, entry.Name, out var _);
                sumProf     = sumProf.Add(areaProfile, entry.Name);
            }

            if (Math.Abs(Slice.PVCurtailToXPercent) < 0.00001)
            {
                throw new FlaException("Found curtailment to 0");
            }

            if (sumProf.EnergySum() < 0)
            {
                throw new FlaException("Negative PV Power");
            }

            if (Slice.PVCurtailToXPercent < 1)
            {
                sumProf = sumProf.LimitPositiveToPercentageOfMax(Slice.PVCurtailToXPercent);
            }

            var prosumer = new Prosumer(entry.HouseGuid, entry.Name,
                                        HouseComponentType.Photovoltaik, entry.SourceGuid, entry.FinalIsn, entry.HausAnschlussGuid, hausanschluss.ObjectID,
                                        GenerationOrLoad.Generation,
                                        hausanschluss.Trafokreis, Name, "PV Profile")
            {
                Profile = sumProf
            };

            if (Math.Abs(Slice.PVCurtailToXPercent - 1) < 0.01 && Math.Abs(sumProf.EnergySum() - entry.EffectiveEnergyDemand) > 0.1)
            {
                throw new FlaException("PV Energy result is wrong");
            }
            return(prosumer);
        }
示例#24
0
        protected override void RunActualProcess([NotNull] ScenarioSliceParameters parameters)
        {
            var dbHouse       = Services.SqlConnection.GetDatabaseConnection(Stage.Houses, parameters);
            var dbDstProfiles = Services.SqlConnection.GetDatabaseConnection(Stage.ProfileGeneration, parameters);
            //var dbSrcProfiles = Services.SqlConnection.GetDatabaseConnection(Stage.ProfileImport, Constants.PresentSlice).Database;
            var dbPVProfiles = Services.SqlConnection.GetDatabaseConnection(Stage.ProfileGenerationPV, Constants.PresentSlice);
            int profileCount = Profile.CountProfiles(dbPVProfiles, TableType.PVGeneration);

            if (profileCount < 100)
            {
                throw new FlaException("No profiles in the database. Not generated for this slice perhaps?");
            }
            var pvsystems = dbHouse.Database.Fetch <PvSystemEntry>();
            var dbHouses  = Services.SqlConnection.GetDatabaseConnection(Stage.Houses, parameters).Database;
            var houses    = dbHouses.Fetch <House>();

            Prosumer.ClearProsumerTypeFromDB(Services.SqlConnection.GetDatabaseConnection(Stage.ProfileGeneration,
                                                                                          parameters), ProsumerType.PV, TableType.HousePart);
            if (pvsystems.Count == 0)
            {
                throw new FlaException("No pv systems found");
            }
            Log(MessageType.Info, "Making " + pvsystems.Count + " pvsystems");
            var sa = Prosumer.GetSaveableEntry(dbDstProfiles, TableType.HousePart);

            //count total number of unique systems
            List <string> allKeys = new List <string>();

            foreach (PvSystemEntry pvsystem in pvsystems)
            {
                foreach (PVSystemArea area in pvsystem.PVAreas)
                {
                    int myazimut = (int)area.Azimut + 180;
                    if (myazimut == 360)
                    {
                        myazimut = 0;
                    }

                    G_PVProfileGeneration.PVSystemKey pvk = new G_PVProfileGeneration.PVSystemKey(myazimut, (int)area.Tilt);
                    allKeys.Add(pvk.GetKey());
                }
            }

            var keys = allKeys.Distinct().OrderBy(x => x);

            Info("Total unique keys: " + keys.Count());

            //dumping for debugging
            var fn = MakeAndRegisterFullFilename("MyKeys.csv", Name, "", parameters);

            File.WriteAllText(fn, JsonConvert.SerializeObject(keys, Formatting.Indented));


            var fn2        = MakeAndRegisterFullFilename("MyKeysPredefined.csv", Name, "", parameters);
            var presetKeys = Profile.LoadAllKeys(dbPVProfiles, TableType.PVGeneration);

            File.WriteAllText(fn2, JsonConvert.SerializeObject(presetKeys, Formatting.Indented));

            Info("Wrote keys to " + fn);
            double totalEnergyFromAllSystems = 0;
            double totalProfileEnergy        = 0;

            for (var idx = 0; idx < pvsystems.Count; idx++)
            {
                var pvsystem = pvsystems[idx];
                if (pvsystem.PVAreas.Count == 0)
                {
                    throw new FlaException("No PV Areas were defined.");
                }
                House         house = houses.Single(x => x.HouseGuid == pvsystem.HouseGuid);
                Hausanschluss ha    = house.Hausanschluss.Single(x => x.HausanschlussGuid == pvsystem.HausAnschlussGuid);

                var pa = new Prosumer(pvsystem.HouseGuid, house.ComplexName,
                                      ProsumerType.PV, pvsystem.PvGuid,
                                      pvsystem.FinalIsn, pvsystem.HausAnschlussGuid, ha.ObjectID);
                Profile p = null;
                double  totalEnergyForThisSystem = 0;
                foreach (PVSystemArea area in pvsystem.PVAreas)
                {
                    G_PVProfileGeneration.PVSystemKey pvk = new G_PVProfileGeneration.PVSystemKey((int)area.Azimut + 180, (int)area.Tilt);
                    totalEnergyForThisSystem += area.Energy;
                    var singleProfile = Profile.LoadProfile(dbPVProfiles, TableType.PVGeneration, pvk.GetKey());
                    if (singleProfile.Count == 0)
                    {
                        throw new FlaException("No profile was found: " + pvk.GetKey());
                    }
                    if (singleProfile.Count > 1)
                    {
                        throw new FlaException("too many profiles found: " + pvk.GetKey());
                    }

                    singleProfile[0].ProfileType = ProfileType.Energy;
                    singleProfile[0]             = singleProfile[0].ScaleToTargetSum(area.Energy, singleProfile[0].Name);
                    if (Math.Abs(singleProfile[0].EnergySum() - area.Energy) > 0.1)
                    {
                        throw new FlaException("invalid energy");
                    }
                    if (p == null)
                    {
                        p = singleProfile[0];
                    }
                    else
                    {
                        p = p.Add(singleProfile[0], p.Name);
                    }
                }

                if (Math.Abs(totalEnergyForThisSystem) < 1)
                {
                    throw new FlaException("PV profile with 0 energy found.");
                }

                if (p == null)
                {
                    throw new FlaException("No profile for " + pvsystem.Name + (" idx:" + idx));
                }
                pa.Profile = p;
                pa.SumElectricityPlanned   = totalEnergyForThisSystem;
                totalEnergyFromAllSystems += totalEnergyForThisSystem;
                sa.RowEntries.Add(pa.GetRow());
                if (pa.Profile == null)
                {
                    throw new FlaException("No profile");
                }
                totalProfileEnergy += pa.Profile.EnergySum();
                if (Math.Abs(totalEnergyFromAllSystems - totalProfileEnergy) > 1)
                {
                    throw new FlaException("energy sums not equal between planned energy and energy in profiles");
                }
                if (sa.RowEntries.Count > 100)
                {
                    sa.SaveDictionaryToDatabase();
                }
            }
            sa.SaveDictionaryToDatabase();
            if (Math.Abs(totalEnergyFromAllSystems - totalProfileEnergy) > 1)
            {
                throw new FlaException("energy sums not equal between planned energy and energy in profiles");
            }
            Info("Total energy from all pv systems: " + totalEnergyFromAllSystems.ToString("N"));
        }