Exemplo n.º 1
0
        protected override void RunChartMaking()
        {
            var slice         = Constants.PresentSlice;
            var dbSrcProfiles = Services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Raw, Constants.PresentSlice);
            var bkws          = dbSrcProfiles.Fetch <BkwProfile>();
            var bkw           = bkws[0];
            var rlms          = dbSrcProfiles.Fetch <RlmProfile>();
            var emptyArr      = new double[rlms[0].Profile.Values.Count];
            var allRlmsVals   = new List <double>();

            allRlmsVals.AddRange(emptyArr);
            var allLocalElectricityVals = new List <double>();

            allLocalElectricityVals.AddRange(emptyArr);
            var allLocalElectricity = new Profile("Locally Generated", allLocalElectricityVals.AsReadOnly(), EnergyOrPower.Power);
            var allRlms             = new Profile("All RLMs", allRlmsVals.AsReadOnly(), EnergyOrPower.Power);

            foreach (var rlm in rlms)
            {
                Profile profile = new Profile(rlm.Name, rlm.Profile.Values, rlm.Profile.EnergyOrPower);
                var     onlyPos = profile.GetOnlyPositive(rlm.Name);

                if (onlyPos.Values.Sum() > 1)
                {
                    allRlms = allRlms.Add(onlyPos, "all Rlms");
                }
                else
                {
                    var onlyNeg = profile.GetOnlyNegative(rlm.Name);
                    allLocalElectricity = allLocalElectricity.Add(onlyNeg, "Locally Generated");
                }
            }

            var bkwProfile = new Profile(bkw.Profile);

            allLocalElectricity = allLocalElectricity.MultiplyWith(-1, "Locally Generated");
            var          residual             = bkwProfile.Minus(allRlms, "Residual");
            const double fac                  = 1_000_000;
            var          rlmTotal             = allRlms.EnergySum() / fac;
            var          bkwTotal             = bkwProfile.EnergySum() / fac;
            var          localGenerationTotal = allLocalElectricity.EnergySum() / fac;
            var          cityTotal            = localGenerationTotal + bkwTotal;
            var          residualTotal        = residual.EnergySum() / fac + localGenerationTotal;
            var          arrows               = new List <SingleSankeyArrow>();
            var          ssa1                 = new SingleSankeyArrow("Erzeugung", 500, MyStage, SequenceNumber, Name, slice, Services);

            ssa1.AddEntry(new SankeyEntry("Lokale Erzeugung", localGenerationTotal, 200, Orientation.Up));
            ssa1.AddEntry(new SankeyEntry("BKW", bkwTotal, 200, Orientation.Straight));
            ssa1.AddEntry(new SankeyEntry("Burgdorf Strom [GWh]", cityTotal * -1, 200, Orientation.Straight));
            arrows.Add(ssa1);
            var ssa2 = new SingleSankeyArrow("Verbrauch", 500, MyStage, SequenceNumber, Name, slice, Services);

            ssa2.AddEntry(new SankeyEntry("", cityTotal, 200, Orientation.Straight));
            ssa2.AddEntry(new SankeyEntry("Residual", residualTotal * -1, 200, Orientation.Up));
            ssa2.AddEntry(new SankeyEntry("RLM", rlmTotal * -1, 200, Orientation.Straight));
            arrows.Add(ssa2);

            Services.PlotMaker.MakeSankeyChart(arrows);
            MakeBarCharts(allRlms, residual, allLocalElectricity);
        }
Exemplo n.º 2
0
        public ImageInfo(Metadata metadata, ImageServer conf, int maxWidth, int maxHeight, int maxArea) : this()
        {
            Height = metadata.Height;
            Width  = metadata.Width;

            var tile = new Tile()
            {
                Width        = Math.Min(metadata.TileWidth, maxWidth),
                Height       = Math.Min(metadata.TileHeight, maxHeight),
                ScaleFactors = new List <int>()
            };

            for (int i = 0; i < metadata.ScalingLevels; i++)
            {
                tile.ScaleFactors.Add(Convert.ToInt32(Math.Pow(2, i)));
            }
            Tiles = new List <Tile> {
                tile
            };

            Profile.Add(new ServiceProfile(conf.AllowSizeAboveFull)
            {
                MaxWidth  = maxWidth == int.MaxValue ? default(int) : maxWidth,
                MaxHeight = maxHeight == int.MaxValue ? default(int) : maxHeight,
                MaxArea   = maxArea == int.MaxValue ? default(int) : maxArea,
                Formats   = conf.AdditionalOutputFormats.Count == 0 ? null : conf.AdditionalOutputFormats
            });
        }
Exemplo n.º 3
0
        private async Task ExecuteGetCPFeedCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            GetCPFeedCommand.ChangeCanExecute();

            try
            {
                myProfile = await cpFeed.GetMyProfile("stanley_alves", "cqzp798371@");

                this.Avatar      = myProfile.avatar;
                this.DisplayName = myProfile.displayName;
                Profile.Add(myProfile);
                // avatar.Add(profiles.avatar);
                IsBusy = false;
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 4
0
        public void SaveProfilesTest()
        {
            List <Profile> profiles = new List <Profile>();

            for (int i = 0; i < 3; i++)
            {
                Profile p = new Profile("Profile" + i.ToString());
                for (int j = 0; j < 5; j++)
                {
                    p.Add(j.ToString(), "Schedule" + j.ToString());
                }

                profiles.Add(p);
            }

            Data d = new Data();

            d.SaveProfiles(profiles);
            List <Profile> profiles2 = d.LoadProfiles();

            Assert.AreEqual(profiles.Count, profiles2.Count);

            for (int i = 0; i < profiles.Count; i++)
            {
                Assert.AreEqual(profiles[i].Name, profiles2[i].Name);
                for (int j = 0; j < profiles[i].HeaterIdSchedule.Count; j++)
                {
                    var a = profiles[i].HeaterIdSchedule.ElementAt(j);
                    var b = profiles2[i].HeaterIdSchedule.ElementAt(j);
                    Assert.AreEqual(a.Key, b.Key);
                    Assert.AreEqual(a.Value, b.Value);
                }
            }
        }
Exemplo n.º 5
0
        //Called from the Razor-Views or master page
        public static Scripts KraftScripts(this Profile profile, string moduleDepStartFile = RESOURCEDEPENDENCY_FILE_NAME, string rootVirtualPath = "/modules")
        {
            if (!profile.HasScriptBundle(profile.Key + "-scripts"))
            {
                ScriptBundle  scriptBundle     = new ScriptBundle(profile.Key + "-scripts", new PhysicalFileProvider(_ModulesCollection.KraftGlobalConfigurationSettings.EnvironmentSettings.ContentRootPath), null, new List <IBundleTransform>(), false);
                StringBuilder contentTemplates = new StringBuilder(10000);
                bool          appendDiv        = false;

                //try to get the target module
                KraftModule profileTargetModule = _ModulesCollection.GetModule(profile.Key);
                if (profileTargetModule == null)
                {
                    throw new Exception($"No CoreKraft module found for bundle target \"{profile.Key}\"!");
                }

                HashSet <KraftModule> targetDeps = new HashSet <KraftModule>();
                Dive(profileTargetModule, targetDeps);
                List <KraftModule> targetDepsSorted = targetDeps.OrderBy(x => x.DependencyOrderIndex).ToList <KraftModule>();

                foreach (KraftModule kraftDepModule in targetDepsSorted)
                {
                    kraftDepModule.ConstructResources(_CachingService, kraftDepModule.DirectoryName, moduleDepStartFile, true);
                    if (kraftDepModule.ScriptKraftBundle != null)
                    {
                        using (KraftProfiler.Current.Step($"Time loading {kraftDepModule.Key}: "))
                        {
                            scriptBundle.Include(new KraftRequireTransformation().Process(kraftDepModule.ScriptKraftBundle, kraftDepModule.ModulePath, kraftDepModule.Key, rootVirtualPath, _Logger));
                            scriptBundle.Transforms.Add(new JsCleanupTransformation());
                        }
                    }

                    if (kraftDepModule.TemplateKraftBundle != null && kraftDepModule.TemplateKraftBundle.TemplateFiles.Count > 0)
                    {
                        if (appendDiv)
                        {
                            contentTemplates.Append(",");
                        }
                        else
                        {
                            appendDiv = true;
                        }
                        HtmlTransformation htmlTransformation = new HtmlTransformation();
                        Func <StringBuilder, ILogger, StringBuilder> minifyHtml = htmlTransformation.Process;
                        contentTemplates.Append(new KraftHtml2JsAssocArrayTransformation().Process(kraftDepModule.TemplateKraftBundle, minifyHtml, _Logger));
                    }
                }

                scriptBundle.IncludeContent("Registers.addRegister(new TemplateRegister(\"module_templates\")); Registers.getRegister(\"module_templates\").$collection= {" + contentTemplates.Append("}"));

                profile.Add(scriptBundle);
                return(profile.Scripts);
            }
            else
            {
                return(profile.Scripts);
            }
        }
Exemplo n.º 6
0
        public void EqualsTest_DifferentMembers()
        {
            Profile p1 = new Profile("Winter");
            Profile p2 = new Profile("Winter");

            p1.Add("ab", "Work");
            Assert.AreEqual(p1, p2);

            p2.Add("ac", "Weekend");
            Assert.AreEqual(p1, p2);
        }
Exemplo n.º 7
0
        public static Profile ToSAM(this ScheduleDay scheduleDay)
        {
            if (scheduleDay == null)
            {
                return(null);
            }

            List <double> values = scheduleDay.Values;

            if (values == null)
            {
                return(null);
            }

            Profile result = new Profile(scheduleDay.Identifier, scheduleDay.Type);

            if (values.Count == 1)
            {
                result.Add(new Core.Range <int>(0, 23), values[0]);
            }
            else
            {
                List <List <int> > times = scheduleDay.Times;
                if (times.Count == values.Count)
                {
                    for (int i = 1; i < times.Count; i++)
                    {
                        int min = times[i - 1][0];
                        int max = times[i][0];

                        result.Add(new Core.Range <int>(min, max - 1), values[i - 1]);
                    }

                    int index = times.Count - 1;
                    result.Add(new Core.Range <int>(times[index][0], 23), values[index]);
                }
            }

            return(result);
        }
Exemplo n.º 8
0
        //Called from the Razor-Views or master page
        public static Styles KraftStyles(this Profile profile, string moduleDepStartFile = RESOURCEDEPENDENCY_FILE_NAME)
        {
            if (!profile.HasStyleBundle(profile.Key + "-css"))
            {
                StyleBundle styleBundle = new StyleBundle(profile.Key + "-css", new PhysicalFileProvider(_ModulesCollection.KraftGlobalConfigurationSettings.EnvironmentSettings.ContentRootPath));
                styleBundle.RemoveTransformationType(typeof(LessTransformation));
                StringBuilder contentTemplates = new StringBuilder(10000);

                //try to get the target module
                KraftModule profileTargetModule = _ModulesCollection.GetModule(profile.Key);
                if (profileTargetModule == null)
                {
                    throw new Exception($"No CoreKraft module found for bundle target \"{profile.Key}\"!");
                }

                void Dive(KraftModule kmodule, HashSet <KraftModule> deps)
                {
                    foreach (var dep in kmodule.Dependencies)
                    {
                        Dive(dep.Value as KraftModule, deps);
                    }
                    deps.Add(kmodule);
                }

                HashSet <KraftModule> targetDeps = new HashSet <KraftModule>();
                Dive(profileTargetModule, targetDeps);
                List <KraftModule> targetDepsSorted = targetDeps.OrderBy(x => x.DependencyOrderIndex).ToList <KraftModule>();

                foreach (KraftModule kraftDepModule in targetDepsSorted)
                {
                    kraftDepModule.ConstructResources(_CachingService, _KraftGlobalConfigurationSettings, moduleDepStartFile, false);
                    if (kraftDepModule.StyleKraftBundle != null)
                    {
                        styleBundle.Include(new KraftRequireTransformation().Process(kraftDepModule.StyleKraftBundle, _Logger));
                    }
                }

                profile.Add(styleBundle);
                return(profile.Styles);
            }
            else
            {
                return(profile.Styles);
            }
        }
Exemplo n.º 9
0
        public void Run()
        {
            PrepareUnitTest();

            // ReSharper disable AssignNullToNotNullAttribute
            ServiceRepository sp = new ServiceRepository(null, null, Logger, Config, new Random());

            // ReSharper restore AssignNullToNotNullAttribute
            var             slice   = Constants.PresentSlice;
            var             dbHouse = sp.SqlConnectionPreparer.GetDatabaseConnection(Stage.Houses, slice);
            var             airconditioningEntries = dbHouse.Fetch <AirConditioningEntry>();
            var             hausanschlusses        = dbHouse.Fetch <Hausanschluss>();
            DBDto           dbDto = new DBDto(new List <House>(), hausanschlusses, new List <Car>(), new List <Household>(), new List <RlmProfile>());
            CoolingProvider hp    = new CoolingProvider(sp, slice, dbDto);

            Info("total hse: " + airconditioningEntries.Count);
            Profile sumProfile = Profile.MakeConstantProfile(0, "Sum", Profile.ProfileResolution.QuarterHour);

            foreach (var entry in airconditioningEntries)
            {
                (entry.HouseComponentType == HouseComponentType.Cooling).Should().BeTrue();
                hp.IsCorrectProvider(entry).Should().BeTrue();
                HouseComponentRo     hro = new HouseComponentRo(string.Empty, string.Empty, 1, 1, string.Empty, string.Empty, string.Empty, 0);
                ProviderParameterDto ppd = new ProviderParameterDto(entry, string.Empty, hro);
                hp.PrepareLoadProfileIfNeeded(ppd);
                var prof = hp.ProvideProfile(ppd);
                if (prof != null)
                {
                    if (prof.Profile == null)
                    {
                        throw new FlaException("Profile was null");
                    }

                    prof.Profile.EnergySum().Should().BeApproximately(entry.EffectiveEnergyDemand, entry.EffectiveEnergyDemand * 0.1);
                    sumProfile = sumProfile.Add(prof.Profile.Values);
                }
            }

            string fn = WorkingDirectory.Combine("Profiletest_cooling.xlsx");

            XlsxDumper.DumpProfilesToExcel(fn, 2050, 15, new ProfileWorksheetContent("Sum", "Last", 240, sumProfile));
            Info("Wrote to " + fn);
        }
        public void Run()
        {
            PrepareUnitTest();
            // ReSharper disable AssignNullToNotNullAttribute
            ServiceRepository sp = new ServiceRepository(null, null, Logger, Config, new Random());
            // ReSharper restore AssignNullToNotNullAttribute

            var             utopiaSlice          = new ScenarioSliceParameters(Scenario.FromEnum(ScenarioEnum.Utopia), 2050, null);
            var             dbHouse              = sp.SqlConnectionPreparer.GetDatabaseConnection(Stage.Houses, utopiaSlice);
            var             heatingSystemEntries = dbHouse.Fetch <HeatingSystemEntry>();
            var             hausanschlusses      = dbHouse.Fetch <Hausanschluss>();
            DBDto           dbDto = new DBDto(new List <House>(), hausanschlusses, new List <Car>(), new List <Household>(), new List <RlmProfile>());
            HeatingProvider hp    = new HeatingProvider(sp, utopiaSlice, dbDto);

            Info("total hse: " + heatingSystemEntries.Count);
            Profile sumProfile = Profile.MakeConstantProfile(0, "Sum", Profile.ProfileResolution.QuarterHour);

            foreach (var entry in heatingSystemEntries)
            {
                (entry.HouseComponentType == HouseComponentType.Heating).Should().BeTrue();
                hp.IsCorrectProvider(entry).Should().BeTrue();
                HouseComponentRo     hro = new HouseComponentRo("", "", 1, 1, "", "", "", 0);
                ProviderParameterDto ppd = new ProviderParameterDto(entry, "", hro);
                hp.PrepareLoadProfileIfNeeded(ppd);
                var prof = hp.ProvideProfile(ppd);
                if (prof != null)
                {
                    if (prof.Profile == null)
                    {
                        throw new FlaException("Profile was null");
                    }

                    prof.Profile.EnergySum().Should().BeApproximately(entry.EffectiveEnergyDemand / 3, entry.EffectiveEnergyDemand * 0.1);
                    sumProfile = sumProfile.Add(prof.Profile.Values);
                }
            }

            var fn = Path.Combine(WorkingDirectory.Dir, "Profiletest.xlsx");

            XlsxDumper.DumpProfilesToExcel(fn, 2050, 15, new ProfileWorksheetContent("Sum", "Last", 240, sumProfile));
        }
        public void RunMultiHpTest()
        {
            PrepareUnitTest();
            // ReSharper disable twice AssignNullToNotNullAttribute
            ServiceRepository services = new ServiceRepository(null, null, Logger, Config, new Random());
            var dbRaw   = services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Raw, Constants.PresentSlice);
            var dbHouse = services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Houses,
                                                                               new ScenarioSliceParameters(Scenario.FromEnum(ScenarioEnum.Utopia), 2050, null));
            var     temperatures            = dbRaw.Fetch <TemperatureProfileImport>();
            var     heatPumpEntries         = dbHouse.Fetch <HeatingSystemEntry>();
            Profile temperaturProfileHourly = new Profile(temperatures[0].Profile ?? throw new FlaException("was null"));
            Random  rnd = new Random();
            //make heatpumpprofile
            Profile        houseEnergy             = Profile.MakeConstantProfile(0, "House Energy", Profile.ProfileResolution.QuarterHour);
            Profile        heatPumpEnergysupply    = Profile.MakeConstantProfile(0, "Heat pump Energy supply", Profile.ProfileResolution.QuarterHour);
            Profile        heatPumpEnergyDemand    = Profile.MakeConstantProfile(0, "Heat pump Energy Demand", Profile.ProfileResolution.QuarterHour);
            Profile        temperatureProfile15Min = null;
            List <Profile> allHouseDemandProfiles  = new List <Profile>();

            foreach (var entry in heatPumpEntries)
            {
                HeatpumpProfileGenerator chp = new HeatpumpProfileGenerator(temperaturProfileHourly, 15, 20, Logger);
                var hpcp = HeatpumpCalculationParameters.MakeDefaults();
                hpcp.StartingTimeStepEvenings           = (21 * 4) + rnd.Next(12);
                hpcp.StoppingTimeStepMorning            = (4 * 4) + rnd.Next(12);
                hpcp.HouseMinimumEnergyTriggerinPercent = 0.70 - rnd.NextDouble() * 0.2;
                hpcp.TargetMaximumRuntimePerDay         = 16 + rnd.NextDouble() * 4;
                hpcp.TimingMode        = HeatPumpTimingMode.OverTheEntireDay;
                hpcp.StartLevelPercent = 1 - rnd.NextDouble() * .5;
                HeatPumpResult hpr    = chp.Run(hpcp, entry.EffectiveEnergyDemand, rnd);
                var            result = hpr.GetEnergyDemandProfile();
                result.Name += entry.Standort;
                allHouseDemandProfiles.Add(result);
                result.Values.Sum().Should().BeApproximately(entry.EffectiveEnergyDemand * .333, entry.EffectiveEnergyDemand * 0.1);
                heatPumpEnergyDemand = heatPumpEnergyDemand.Add(result, heatPumpEnergyDemand.Name);
                houseEnergy          = houseEnergy.Add(hpr.HouseEnergyTracker.AsReadOnly());
                heatPumpEnergysupply = heatPumpEnergysupply.Add(hpr.HeatpumpEnergySupply.AsReadOnly());
                if (temperatureProfile15Min == null)
                {
                    temperatureProfile15Min = new Profile("Temperatures", hpr.DailyAvgTemperatures15Min.ToList().AsReadOnly(), EnergyOrPower.Energy);
                }
            }

            allHouseDemandProfiles.Sort((x, y) => y.EnergySum().CompareTo(x.EnergySum()));
            var profilesToShow  = allHouseDemandProfiles.Take(5).ToList();
            var profilesToMerge = allHouseDemandProfiles.Skip(6).ToList();
            var mergedProfiles  = allHouseDemandProfiles[5].Add(profilesToMerge, "MergedProfiles");

            if (temperatureProfile15Min == null)
            {
                throw new FlaException("no temperatures");
            }

            ProfileWorksheetContent biggestConsumers = new ProfileWorksheetContent("Biggest Consumers", "Last", profilesToShow);

            biggestConsumers.Profiles.Add(mergedProfiles);
            string fullFileName = WorkingDirectory.Combine("heatpump_profiles_multi-WithChart.xlsx");

            XlsxDumper.DumpProfilesToExcel(fullFileName,
                                           2017,
                                           15,
                                           new ProfileWorksheetContent("Energy Demand", "Last", 240, heatPumpEnergyDemand),
                                           new ProfileWorksheetContent("Energy Supply", "Energieversorgung", 240, heatPumpEnergysupply),
                                           new ProfileWorksheetContent("Temperatures", "Temperatur", 240, temperatureProfile15Min),
                                           new ProfileWorksheetContent("House Energy", "Haus Energiegehalt", 240, houseEnergy),
                                           biggestConsumers);
            //WriteProfilesToExcel(temperatureProfile15Min, houseEnergy, heatPumpEnergysupply,file);
        }
Exemplo n.º 12
0
        protected void Initialize(int index, bool showDialog = false)
        {
            Profile.Clear();
            double[,] v;

            switch (index)
            {
            case 0:     // Wine 1
                v = new double[, ]
                {
                    { 0.0, 69.0 },
                    { 3.0, 71.0 },
                    { 6.0, 74.0 },
                    { 180.0, 74.0 },
                    { 190.0, 73.0 },
                    { 200.0, 67.0 },
                    { 205, 59.0 },
                    { 210.0, 52.0 },
                    { 215.0, 37.0 },
                    { 217.0, 34.0 },
                    { 220.0, 32.0 },
                    { 230.0, 30.5 },
                    { 285.0, 27.6 },
                    { 286.0, 29.6 },
                    { 295.0, 29.6 },
                    { 300.0, 27.3 },
                    { 301.0, 25.0 }
                };
                break;

            case 1:     // Wine 2
                v = new double[, ]
                {
                    { 0.0, 65.0 },
                    { 2.0, 68.0 },
                    { 5.0, 72.0 },
                    { 10.0, 75.0 },
                    { 120.0, 75.0 },
                    { 135.0, 74.0 },
                    { 160.0, 69.0 },
                    { 185.0, 60.0 },
                    { 210.0, 51.0 },
                    { 250.0, 36.0 },
                    { 314.0, 28.0 },
                    { 315.0, 30.0 },
                    { 325.0, 30.0 },
                    { 326.0, 28.0 },
                    { 329.0, 28.0 },
                    { 330.0, 27.0 }
                };
                break;

            case 2:     // Milk
                v = new double[, ]
                {
                    { 0.0, 70.0 },
                    { 2.0, 78.0 },
                    { 10.0, 84.0 },
                    { 20.0, 90.0 },
                    { 140.0, 90.0 },
                    { 160.0, 85.0 },
                    { 190.0, 60.0 },
                    { 220.0, 47.0 },
                    { 221.0, 48.0 },
                    { 240.0, 48.0 },
                    { 243.0, 43.0 }
                };
                break;

            case 3:     // Water
                v = new double[, ]
                {
                    { 0.0, 70.0 },
                    { 10.0, 76.0 },
                    { 40.0, 84.0 },
                    { 120.0, 84.0 },
                    { 150.0, 77.0 },
                    { 170.0, 63.0 },
                    { 195.0, 70.0 },
                    { 220.0, 83.0 },
                    { 241.0, 72.0 },
                    { 260.0, 49.0 },
                    { 272.0, 27.0 },
                    { 280.0, 27.0 },
                    { 281.0, 30.0 },
                    { 294.0, 30.0 },
                    { 295.0, 29.0 }
                };
                break;

            case 4:     // coca-cola can
                v = new double[, ]
                {
                    { 0.0, 50.0 },
                    { 7.0, 64.0 },
                    { 100.0, 64.0 },
                    { 110.0, 53.0 },
                    { 111.0, 53.0 },
                    { 112.0, 54.0 },
                    { 115.0, 54.0 }
                };
                break;

            default:
                v = new double[, ]
                {
                    { 0.0, 69.0 },
                    { 3.0, 71.0 },
                    { 6.0, 74.0 },
                    { 180.0, 74.0 },
                    { 190.0, 73.0 },
                    { 200.0, 67.0 },
                    { 205, 59.0 },
                    { 210.0, 52.0 },
                    { 215.0, 37.0 },
                    { 217.0, 34.0 },
                    { 220.0, 32.0 },
                    { 230.0, 30.5 },
                    { 285.0, 27.6 },
                    { 286.0, 29.6 },
                    { 295.0, 29.6 },
                    { 300.0, 27.3 },
                    { 301.0, 25.0 }
                };
                break;
            }

            var profile = new List <Vector2D>();

            for (int i = 0; i < v.Length / 2; ++i)
            {
                profile.Add(
                    new Vector2D(
                        UnitsManager.ConvertLengthFrom(v[i, 0], UnitsManager.UnitSystem.UNIT_METRIC1),
                        UnitsManager.ConvertLengthFrom(v[i, 1], UnitsManager.UnitSystem.UNIT_METRIC1)
                        )
                    );
            }

            // get maxDiameter and maxHeight to apply
            double maxDiameterInit = profile.Max(p => p.Y);
            double maxHeightInit   = profile.Max(p => p.X);
            double maxDiameter     = maxDiameterInit;
            double maxHeight       = maxHeightInit;

            if (showDialog)
            {
                using (var form = new FormBottleInitialize()
                {
                    MaxDiameter = maxDiameter, MaxHeight = maxHeight
                })
                {
                    if (DialogResult.OK == form.ShowDialog())
                    {
                        maxDiameter = form.MaxDiameter;
                        maxHeight   = form.MaxHeight;
                    }
                }
            }

            Profile.Clear();
            foreach (var vec in profile)
            {
                Profile.Add(new Vector2D(vec.X * maxHeight / maxHeightInit, vec.Y * maxDiameter / maxDiameterInit));
            }

            FillGrid();
        }
Exemplo n.º 13
0
        protected override void OnAccept(GumpButton button)
        {
            base.OnAccept(button);

            if (LockMode)
            {
                Close();
                return;
            }

            if (String.IsNullOrWhiteSpace(TemplateName))
            {
                Send(
                    new NoticeDialogGump(User, Hide(true))
                {
                    Title         = "Choose a Template Name",
                    Html          = "Your template must have a name!",
                    AcceptHandler = b => Refresh(true)
                });
                return;
            }

            if (TemplateSkills.Length < 7)
            {
                Send(
                    new NoticeDialogGump(User, Hide(true))
                {
                    Title         = "Choose 7 Skills",
                    Html          = "You must choose 7 unique skills to create a template.",
                    AcceptHandler = b => Refresh(true)
                });
                return;
            }

            if (TemplateStr <= 0 || TemplateDex <= 0 || TemplateInt <= 0)
            {
                Send(
                    new NoticeDialogGump(User, Hide(true))
                {
                    Title         = "Choose 3 Stats",
                    Html          = "You must specify your three character stats.",
                    AcceptHandler = b => Refresh(true)
                });
                return;
            }

            if (TemplateStr + TemplateDex + TemplateInt > 225)
            {
                Send(
                    new NoticeDialogGump(User, Hide(true))
                {
                    Title = "Stat Failure",
                    Html  =
                        "Either one of your stats is above the 100 limit, " +
                        "or you have exceeded the overall limit of 225 stat points with your current allocation.",
                    AcceptHandler = b => Refresh(true)
                });
                return;
            }

            Dictionary <SkillName, double> skills = Profile.Owner.Skills.Not(sk => sk == null)
                                                    .ToDictionary(sk => sk.SkillName, sk => TemplateSkills.Contains(sk.SkillName) ? 100.0 : 0.0);
            var stats = new Dictionary <StatType, int>
            {
                {
                    StatType.Str, TemplateStr
                },
                {
                    StatType.Dex, TemplateDex
                },
                {
                    StatType.Int, TemplateInt
                }
            };

            if (EditMode)
            {
                Template.Name   = TemplateName;
                Template.Notes  = TemplateNotes;
                Template.Skills = skills;
                Template.Stats  = stats;

                Profile.Add(Template);
            }
            else
            {
                Template = Profile.Create(TemplateName, TemplateNotes, skills, stats);
                if (Profile.Selected == null)
                {
                    Profile.Select(Template);
                }
            }
            Close();
        }
 public void WhenIClickOnAddButton()
 {
     Profileobj.Add();
 }
Exemplo n.º 15
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"));
        }
Exemplo n.º 16
0
        //Called from the Razor-Views or master page
        public static Scripts KraftScripts(this Profile profile)
        {
            if (!profile.HasScriptBundle(profile.Key + "-scripts"))
            {
                KraftModuleCollection modulesCollection = _Builder.ApplicationServices.GetService <KraftModuleCollection>();
                ScriptBundle          scriptBundle      = new ScriptBundle(profile.Key + "-scripts", new PhysicalFileProvider(modulesCollection.KraftGlobalConfigurationSettings.EnvironmentSettings.ContentRootPath));
                StringBuilder         contentTemplates  = new StringBuilder(10000);
                bool appendDiv = false;

                //try to get the target module
                KraftModule profileTargetModule = modulesCollection.GetModule(profile.Key);
                if (profileTargetModule == null)
                {
                    throw new Exception($"No CoreKraft module found for bundle target \"{profile.Key}\"!");
                }


                void Dive(KraftModule kmodule, HashSet <KraftModule> deps)
                {
                    foreach (var dep in kmodule.Dependencies)
                    {
                        Dive(dep.Value as KraftModule, deps);
                    }
                    deps.Add(kmodule);
                }

                HashSet <KraftModule> targetDeps = new HashSet <KraftModule>();
                Dive(profileTargetModule, targetDeps);
                List <KraftModule> targetDepsSorted = targetDeps.OrderBy(x => x.DependencyOrderIndex).ToList <KraftModule>();

                foreach (KraftModule kraftDepModule in targetDepsSorted)
                {
                    if (kraftDepModule.ScriptKraftBundle != null)
                    {
                        using (KraftProfiler.Current.Step($"Time loading {kraftDepModule.Key}: "))
                        {
                            scriptBundle.Include(new KraftRequireTransformation().Process(kraftDepModule.ScriptKraftBundle, _Logger));
                        }
                    }

                    if (kraftDepModule.TemplateKraftBundle != null && kraftDepModule.TemplateKraftBundle.TemplateFiles.Count > 0)
                    {
                        if (appendDiv)
                        {
                            contentTemplates.Append(",");
                        }
                        else
                        {
                            appendDiv = true;
                        }
                        HtmlTransformation htmlTransformation = new HtmlTransformation();
                        Func <StringBuilder, ILogger, StringBuilder> minifyHtml = htmlTransformation.Process;
                        contentTemplates.Append(new KraftHtml2JsAssocArrayTransformation().Process(kraftDepModule.TemplateKraftBundle, minifyHtml, _Logger));
                    }
                }

                scriptBundle.IncludeContent("Registers.addRegister(new TemplateRegister(\"module_templates\")); Registers.getRegister(\"module_templates\").$collection= {" + contentTemplates.Append("}"));

                profile.Add(scriptBundle);
                return(profile.Scripts);
            }
            else
            {
                return(profile.Scripts);
            }
        }
        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);
        }
Exemplo n.º 18
0
        protected override void RunActualProcess([NotNull] ScenarioSliceParameters parameters)
        {
            //profile export
            var dbProfileExport = Services.SqlConnection.GetDatabaseConnection(Stage.ProfileExport, parameters);
            //var dbProfileGeneration = Services.SqlConnection.GetDatabaseConnection(Stage.ProfileGeneration, parameters);
            var dbHouses        = Services.SqlConnection.GetDatabaseConnection(Stage.Houses, parameters);
            var dbHousesPresent = Services.SqlConnection.GetDatabaseConnection(Stage.Houses, Constants.PresentSlice);
            var prosumers       = Prosumer.LoadProsumers(dbProfileExport, TableType.HouseLoad);

            var visualPath = Path.Combine(dbProfileExport.GetResultFullPath(SequenceNumber, Name), "Visual");

            if (!Directory.Exists(visualPath))
            {
                Directory.CreateDirectory(visualPath);
            }

            //var tkResults = dbProfileGeneration.Database.Fetch<TrafoKreisResult>();
            var houses         = dbHouses.Database.Fetch <House>();
            var houseEnergyUse = dbHousesPresent.Database.Fetch <HouseSummedLocalnetEnergyUse>();
            var trafokreise    = houses.Select(x => x.TrafoKreis).Distinct().ToList();
            var p  = new ExcelPackage();
            var ws = p.Workbook.Worksheets.Add("MySheet");

            TrafokreisStatisticsEntry.WriteHeaderToWs(ws);
            int exportRow = 2;

            //Dictionary<long, string> isnTrafokreis = new Dictionary<long, string>();//for checking for duplicate isns
            foreach (var trafokreis in trafokreise)
            {
                if (string.IsNullOrWhiteSpace(trafokreis))
                {
                    continue;
                }

                TrafokreisStatisticsEntry tkse = new TrafokreisStatisticsEntry(trafokreis)
                {
                    OriginalHouses = houses.Where(x => x.TrafoKreis == trafokreis).Count()
                };
                var originalHouseGuids = houses.Where(x => x.TrafoKreis == trafokreis).Select(x => x.HouseGuid).ToList();
                var houseEnergyUses    = houseEnergyUse.Where(x => originalHouseGuids.Contains(x.HouseGuid)).ToList();
                foreach (var energyUse in houseEnergyUses)
                {
                    tkse.OriginalElectricityUse      += energyUse.ElectricityUse;
                    tkse.OriginalElectricityUseDay   += energyUse.ElectricityUseDayLow;
                    tkse.OriginalElectricityUseNight += energyUse.ElectricityUseNightLow;
                }

                List <double> zeroes = new List <double>(new double[8760 * 4]);
                var           trafokreisSumProfile = new Profile(trafokreis, zeroes.AsReadOnly(), ProfileType.Energy);
                var           filteredProsumers    = prosumers.Where(x => x.TrafoKreis == trafokreis);
                foreach (Prosumer prosumer in filteredProsumers)
                {
                    if (prosumer.Profile == null)
                    {
                        throw new Exception("Profile was null");
                    }

//                    if (isnTrafokreis.ContainsKey(prosumer.Isn)) {
//                      throw new Exception("Duplicate ISN");
//                }
//              isnTrafokreis.Add(prosumer.Isn,trafokreis);
                    tkse.ProfileElectricityUse += prosumer.Profile.EnergySum();
                    tkse.ProfileDuringNight    += prosumer.Profile.EnergyDuringNight();
                    tkse.ProfileDuringDay      += prosumer.Profile.EnergyDuringDay();
                    if (Math.Abs(tkse.ProfileDuringNight + tkse.ProfileDuringDay - tkse.ProfileElectricityUse) > 1)
                    {
                        throw new FlaException("Invalid day/night/sum");
                    }
                    tkse.ProfileHouses++;
                    trafokreisSumProfile = trafokreisSumProfile.Add(prosumer.Profile, trafokreis);
                }

                if (Math.Abs(tkse.OriginalElectricityUse) < 1 && tkse.ProfileElectricityUse > 0)
                {
                    throw new FlaException("No energy planned, but energy allocated");
                }

                /*   if (Math.Abs(trafokreisSumProfile.EnergySum()) < 0.0001 && Math.Abs(tkse.OriginalElectricityUse) > 0.1) {
                 *     throw new Exception("trafokreis has 0 electricy exported.");
                 * }*/

                //tkse.CollectedEnergyFromHouses = tkResults.Single(x => x.TrafoKreisName == trafokreis).TotalEnergyAmount;
                tkse.WriteToWorksheet(ws, exportRow++);

                //make trafokreis chart
                var      ls            = trafokreisSumProfile.GetLineSeriesEntriesList();
                var      chartfilename = MakeAndRegisterFullFilename("Visual\\" + trafokreis + ".png", Name, "", parameters);
                FileInfo fi            = new FileInfo(chartfilename);
                Debug.Assert(fi.Directory != null, "fi.Directory != null");
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                    Thread.Sleep(500);
                }
                Services.PlotMaker.MakeLineChart(chartfilename, trafokreis, ls, new List <PlotMaker.AnnotationEntry>());
            }

            int offset = 12;

            ws.Cells[1, offset].Value       = "Summe Stromverbrauch von Localnet";
            ws.Cells[1, offset + 1].Formula = "=sum(d:d)/1000000";
            ws.Cells[1, offset + 2].Formula = "=SUMIFS(D:D,E:E,\">0\")/1000000";
            ws.Cells[2, offset].Value       = "Summe Stromverbrauch in den Exports";
            ws.Cells[2, offset + 1].Formula = "=sum(e:e)/1000000";
            ws.Cells[2, offset + 2].Formula = "=SUMIFS(E:E,E:E,\">0\")/1000000";

            ws.Cells[3, offset].Value       = "Original Nacht Nutzung";
            ws.Cells[3, offset + 1].Formula = "=sum(g:g)/1000000";
            ws.Cells[4, offset].Value       = "Original Tag Nutzung";
            ws.Cells[4, offset + 1].Formula = "=sum(h:h)/1000000";
            ws.Cells[5, offset].Value       = "Profil Nacht Nutzung";
            ws.Cells[5, offset + 1].Formula = "=sum(I:I)/1000000";
            ws.Cells[6, offset].Value       = "Profil Tag Nutzung";
            ws.Cells[6, offset + 1].Formula = "=sum(J:J)/1000000";

            ExcelChart chart = ws.Drawings.AddChart("Comparison", eChartType.ColumnClustered);

            //chart.Title.Text = "Category Chart";
            chart.SetPosition(5, 0, offset, 0);
            chart.SetSize(800, 450);
            chart.Series.Add(ws.Cells["N1:N2"], ws.Cells["L1:L2"]);
            p.SaveAs(new FileInfo(Path.Combine(dbProfileExport.GetResultFullPath(SequenceNumber, Name), "ComparisonExportvsDB.xlsx")));
            p.Dispose();
        }