public void RunColumnEntryLoggerTest()
 {
     using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
     {
         ColumnEntryLogger     ael    = new ColumnEntryLogger(wd.SqlResultLoggingService);
         HouseholdKey          key    = new HouseholdKey("hhkey");
         List <IDataSaverBase> savers = new List <IDataSaverBase>
         {
             ael
         };
         InputDataLogger    idl  = new InputDataLogger(savers.ToArray());
         CalcLoadTypeDto    cltd = new CalcLoadTypeDto("ltname", "kw", "kwh", 1, false, "guid".ToStrGuid());
         CalcDeviceDto      cdd  = new CalcDeviceDto("device", "guid".ToStrGuid(), key, OefcDeviceType.Device, "devcatname", "", "guid".ToStrGuid(), "guid".ToStrGuid(), "loc");
         ColumnEntry        ce   = new ColumnEntry("name", 1, "locname", "guid".ToStrGuid(), key, cltd, "oefckey", "devicecategory", cdd);
         List <ColumnEntry> aes  = new List <ColumnEntry>
         {
             ce
         };
         idl.Save(aes);
         var res = ael.Read(key);
         var s1  = JsonConvert.SerializeObject(aes, Formatting.Indented);
         var s2  = JsonConvert.SerializeObject(res, Formatting.Indented);
         File.WriteAllText(wd.Combine("original.json"), s1);
         File.WriteAllText(wd.Combine("deserialized.json"), s2);
         s1.Should().Be(s2);
     }
     //wd.CleanUp();
 }
        public void AddColumnEntry([NotNull] string name, OefcKey key,
                                   [NotNull] string locationName, [NotNull] CalcLoadTypeDto lt, StrGuid deviceGuid,
                                   [NotNull] HouseholdKey householdKey, [NotNull] string deviceCategory, [NotNull] CalcDeviceDto calcDeviceDto)
        {
            if (!ColumnCountByLoadType.ContainsKey(lt))
            {
                ColumnCountByLoadType.Add(lt, 0);
            }
            var dstcolum = ColumnCountByLoadType[lt];

            var ce = new ColumnEntry(name, dstcolum, locationName, deviceGuid,
                                     householdKey, lt, key.ToString(), deviceCategory, calcDeviceDto);

            if (!_columnEntriesByLoadTypeByDeviceKey.ContainsKey(lt))
            {
                _columnEntriesByLoadTypeByDeviceKey.Add(lt, new Dictionary <OefcKey, ColumnEntry>());
                _columnEntriesByColumn.Add(lt, new Dictionary <int, ColumnEntry>());
            }
            if (!_columnEntriesByLoadTypeByDeviceKey[lt].ContainsKey(key))
            {
                _columnEntriesByLoadTypeByDeviceKey[lt].Add(key, ce);
                _columnEntriesByColumn[lt].Add(dstcolum, ce);
                ColumnCountByLoadType[lt]++;
                _old.AddColumnEntry(ce);
            }
        }
Exemplo n.º 3
0
        public void AddNewStateMachine(TimeStep startTimeStep,
                                       CalcLoadTypeDto loadType, string affordanceName, string activatorName,
                                       OefcKey oefckey, [NotNull] CalcDeviceDto calcDeviceDto, [NotNull] StepValues sv)
        {
            Oefc.IsDeviceRegistered(loadType, oefckey);
            //OefcKey oefckey = new OefcKey(householdKey, deviceType, deviceID, locationID, loadType.ID);
            // this is for logging the used time profiles which gets dumped to the time profile log
            ProfileActivationEntry.ProfileActivationEntryKey key =
                new ProfileActivationEntry.ProfileActivationEntryKey(calcDeviceDto.Name, sv.Name, sv.DataSource,
                                                                     loadType.Name);
            if (!_profileEntries.ContainsKey(key))
            {
                ProfileActivationEntry entry = new ProfileActivationEntry(calcDeviceDto.Name, sv.Name, sv.DataSource,
                                                                          loadType.Name, _calcParameters);
                _profileEntries.Add(entry.GenerateKey(), entry);
            }
            _profileEntries[key].ActivationCount++;
            // do the device activiation
            var columnNumber = Oefc.GetColumnNumber(loadType, oefckey);
            var dsm          = new OnlineDeviceStateMachine(startTimeStep,
                                                            loadType, calcDeviceDto.Name, oefckey, affordanceName, _calcParameters, sv, columnNumber);

            //_statemachines.Add(dsm);
            _stateMachinesByLoadtype[loadType].Add(dsm);
            // log the affordance energy use.
            if (_calcParameters.IsSet(CalcOption.DeviceActivations))
            {
                double totalPowerSum  = dsm.CalculateOfficialEnergyUse();
                double totalEnergysum = loadType.ConversionFactor * totalPowerSum;
                var    entry          = new DeviceActivationEntry(dsm.AffordanceName,
                                                                  dsm.LoadType, totalEnergysum, activatorName, sv.Values.Count,
                                                                  startTimeStep, calcDeviceDto); // dsm.StepValues.ToArray(),
                _old.RegisterDeviceActivation(entry);
            }
        }
        public CalcEnergyStorage([NotNull] IOnlineDeviceActivationProcessor odap,
                                 [NotNull] CalcLoadTypeDto loadType,
                                 double maximumStorageRate, double maximumWithdrawRate, double minimumStorageRate,
                                 double minimumWithdrawRate,
                                 double initialFill, double storageCapacity, [CanBeNull] EnergyStorageLogfile elf,
                                 [NotNull] CalcDeviceDto deviceDto)
            : base(deviceDto.Name, deviceDto.Guid)
        {
            //_devProcessorKey = new OefcKey(householdKey, OefcDeviceType.Storage, guid, "-1", loadType.Guid,"Energy Storage");
            _odap            = odap;
            _inputLoadType   = loadType;
            _deviceDto       = deviceDto;
            _devProcessorKey = _odap.RegisterDevice(_inputLoadType, deviceDto);

            _maximumStorageRate  = maximumStorageRate;
            _maximumWithdrawRate = maximumWithdrawRate;
            _minimumStorageRate  = minimumStorageRate;
            _minimumWithdrawRate = minimumWithdrawRate;
            var correctInitialFill = initialFill / _inputLoadType.ConversionFactor;

            PreviousFillLevel = correctInitialFill;
            _storageCapacity  = storageCapacity / _inputLoadType.ConversionFactor;
            _currentFillLevel = correctInitialFill;
            _elf = elf;
            var capacity = storageCapacity + " " + loadType.UnitOfSum + " - initial fill " + initialFill + " " +
                           loadType.UnitOfSum;

            _headerEntry = new EnergyStorageHeaderEntry(Name, capacity, _inputLoadType.FileName);

            _elf?.RegisterStorage(Name, _headerEntry);
        }
        public string GetTotalHeaderString([NotNull] CalcLoadTypeDto lt, [CanBeNull] List <int> usedColumns)
        {
            var headerstring = new StringBuilder();
            var columns      = _columnEntries.Where(x => x.LoadType == lt);

            if (usedColumns == null || usedColumns.Count == 0)
            {
                foreach (var entry in columns)
                {
                    headerstring.Append(entry.HeaderString(lt, _calcParameters));
                }
            }
            else
            {
                foreach (var entry in columns)
                {
                    if (usedColumns.Contains(entry.Column))
                    {
                        headerstring.Append(entry.HeaderString(lt, _calcParameters));
                    }
                }
            }
            if (headerstring[headerstring.Length - 1] == _calcParameters.CSVCharacter[0])
            {
                headerstring.Length--;
            }
            return(headerstring.ToString());
        }
        public string HeaderString([NotNull] CalcLoadTypeDto lt, [NotNull] CalcParameters calcParameters)
        {
            if (calcParameters.DeviceProfileHeaderMode == DeviceProfileHeaderMode.Standard)
            {
                while (Name.EndsWith(calcParameters.CSVCharacter, StringComparison.Ordinal))
                {
                    Name = Name.Substring(0, Name.Length - 1);
                }

                var housenumber = HouseholdKey + " - ";
                if (LocationName.Length > 0 && Name.Length > 0)
                {
                    return(housenumber + LocationName + " - " + Name + " [" + lt.UnitOfSum + "]" + calcParameters.CSVCharacter);
                }

                if (LocationName.Length == 0 && Name.Length > 0)
                {
                    return(Name + " [" + lt.UnitOfSum + "]" + calcParameters.CSVCharacter);
                }

                return(housenumber + LocationName + " - (none) [" + lt.UnitOfSum + "]" + calcParameters.CSVCharacter);
            }

            if (calcParameters.DeviceProfileHeaderMode == DeviceProfileHeaderMode.OnlyDeviceCategories)
            {
                return(DeviceCategory + " [" + lt.UnitOfSum + "]" + calcParameters.CSVCharacter);
            }
            throw new LPGException("Forgotten Device Profile Header Mode");
        }
        private Dictionary <int, OnlineEnergyFileRow> MakeSumsPerMonth([NotNull] CalcLoadTypeDto dstLoadType,
                                                                       [ItemNotNull][NotNull] List <OnlineEnergyFileRow> energyFileRows,
                                                                       DateTime curDate,
                                                                       [NotNull] OnlineEnergyFileRow sum,
                                                                       int rowlength)
        {
            var    calcParameters = Repository.CalcParameters;
            var    sumsPerMonth   = new Dictionary <int, OnlineEnergyFileRow>();
            double runningtotal   = 0;

            foreach (var efr in energyFileRows)
            {
                curDate += calcParameters.InternalStepsize;
                sum.AddValues(efr);
                if (Config.IsInUnitTesting && Config.ExtraUnitTestChecking)
                {
                    runningtotal += efr.SumFresh();
                }

                if (Config.IsInUnitTesting && Config.ExtraUnitTestChecking && Math.Abs(runningtotal - sum.SumFresh()) > 0.000001)
                {
                    throw new LPGException("Unknown bug while generating the device totals. Sums don't match.");
                }

                if (!sumsPerMonth.ContainsKey(curDate.Month))
                {
                    var ts = new TimeStep(0, 0, true);
                    sumsPerMonth.Add(curDate.Month, new OnlineEnergyFileRow(ts, new List <double>(new double[rowlength]), dstLoadType));
                }

                sumsPerMonth[curDate.Month].AddValues(efr);
            }

            return(sumsPerMonth);
        }
 public void ReadTest()
 {
     using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
     {
         DeviceActivationEntryLogger ael = new DeviceActivationEntryLogger(wd.SqlResultLoggingService);
         HouseholdKey          key       = new HouseholdKey("hhkey");
         List <IDataSaverBase> savers    = new List <IDataSaverBase>
         {
             ael
         };
         InputDataLogger idl   = new InputDataLogger(savers.ToArray());
         CalcLoadTypeDto cldto = new CalcLoadTypeDto("loadtype", "kw", "kwh", 1, true, "guid".ToStrGuid());
         TimeStep        ts    = new TimeStep(1, 1, true);
         CalcDeviceDto   cdd   = new CalcDeviceDto("devicename", "device".ToStrGuid(),
                                                   key, OefcDeviceType.Device, "devicecategoryname",
                                                   "additionalname", "deviceguid".ToStrGuid(), "locationguid".ToStrGuid(), "locationname");
         DeviceActivationEntry ae1 = new DeviceActivationEntry("affordancename",
                                                               cldto, 1, "activator", 1, ts, cdd);
         List <IHouseholdKey> aes = new List <IHouseholdKey>
         {
             ae1
         };
         idl.SaveList(aes);
         var res = ael.Read(key);
         var s1  = JsonConvert.SerializeObject(aes, Formatting.Indented);
         var s2  = JsonConvert.SerializeObject(res, Formatting.Indented);
         s1.Should().Be(s2);
         wd.CleanUp();
     }
 }
        private void Run([NotNull] CalcLoadTypeDto dstLoadType, [NotNull][ItemNotNull] List <OnlineEnergyFileRow> energyFileRows,
                         [NotNull] IFileFactoryAndTracker fft)
        {
            var calcParameters     = Repository.CalcParameters;
            var dailyValues        = new Dictionary <int, Dictionary <int, double> >();
            var dailyValuesbyMonth =
                new Dictionary <int, Dictionary <int, Dictionary <int, double> > >();
            var dailyValuesbySeason =
                new Dictionary <int, Dictionary <int, double> >();
            var dayCount = new Dictionary <DayOfWeek, int>();

            var seasonDayCount = new Dictionary <int, int>();

            ReadFile(energyFileRows, dailyValues, dailyValuesbyMonth, dailyValuesbySeason, dayCount, seasonDayCount);

            var resultfile = fft.MakeFile <StreamWriter>("WeekdayProfiles." + dstLoadType.Name + ".csv",
                                                         "Averaged profiles for each weekday for " + dstLoadType.Name, true,
                                                         ResultFileID.WeekdayLoadProfileID, Constants.GeneralHouseholdKey, TargetDirectory.Reports,
                                                         calcParameters.InternalStepsize, CalcOption.WeekdayProfiles,
                                                         dstLoadType.ConvertToLoadTypeInformation());
            var valuecount = WriteNormalPart(dstLoadType, resultfile, dailyValues, dayCount);

            WriteByMonth(resultfile, dailyValuesbyMonth, valuecount);
            WriteBySeason(resultfile, valuecount, dailyValuesbySeason, seasonDayCount);
            resultfile.Flush();
            resultfile.Close();
        }
Exemplo n.º 10
0
        protected override void PerformActualStep(IStepParameters parameters)
        {
            LoadtypeStepParameters p       = (LoadtypeStepParameters)parameters;
            var             dsc            = new DateStampCreator(Repository.CalcParameters);
            var             calcParameters = Repository.CalcParameters;
            CalcLoadTypeDto dstLoadType    = p.LoadType;
            var             householdKey   = Constants.GeneralHouseholdKey;
            var             sumfile        = _fft.MakeFile <StreamWriter>("SumProfiles." + dstLoadType.Name + ".csv",
                                                                          "Summed up energy profile for all devices for " + dstLoadType.Name, true,
                                                                          ResultFileID.CSVSumProfile, householdKey, TargetDirectory.Results,
                                                                          calcParameters.InternalStepsize, CalcOption.HouseSumProfilesFromDetailedDats,
                                                                          dstLoadType.ConvertToLoadTypeInformation());

            sumfile.WriteLine(dstLoadType.Name + "." + dsc.GenerateDateStampHeader() + "Sum [" +
                              dstLoadType.UnitOfSum + "]");
            foreach (var efr in p.EnergyFileRows)
            {
                if (!efr.Timestep.DisplayThisStep)
                {
                    continue;
                }

                var time      = dsc.MakeTimeString(efr.Timestep);
                var sumstring = time + (efr.SumCached * dstLoadType.ConversionFactor).ToString(Config.CultureInfo);
                sumfile.WriteLine(sumstring);
            }
        }
Exemplo n.º 11
0
 public void RegisterDeviceActivationTest()
 {
     using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
     {
         wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
         wd.InputDataLogger.AddSaver(new DeviceActivationEntryLogger(wd.SqlResultLoggingService));
         wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
         CalcParameters cp = CalcParametersFactory.MakeGoodDefaults().EnableShowSettlingPeriod();
         using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hhname", wd.InputDataLogger))
         {
             var key = new HouseholdKey(" hh1");
             fft.HouseholdRegistry.RegisterHousehold(key, "hh key", HouseholdKeyType.Household, wd.InputDataLogger, "desc", null, null);
             fft.HouseholdRegistry.RegisterHousehold(Constants.GeneralHouseholdKey, "general", HouseholdKeyType.General, wd.InputDataLogger, "desc", null, null);
             DateStampCreator dsc = new DateStampCreator(cp);
             using OnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, cp);
             fft.HouseholdRegistry.RegisterHousehold(key, "hh key", HouseholdKeyType.Household, wd.InputDataLogger, "desc", null, null);
             CalcLoadTypeDto clt = new CalcLoadTypeDto("lt", "unitofpower", "unitofsum", 1, true, "guid".ToStrGuid());
             TimeStep        ts  = new TimeStep(1, 1, true);
             CalcDeviceDto   cdd = new CalcDeviceDto("devname", "".ToStrGuid(), key,
                                                     OefcDeviceType.Device, "devcatname", "", Guid.NewGuid().ToStrGuid(), "locguid".ToStrGuid(), "locname");
             DeviceActivationEntry aeue = new DeviceActivationEntry("affname", clt, 1, "activatorname", 1, ts, cdd);
             old.RegisterDeviceActivation(aeue);
             old.FinalSaveToDatabase();
         }
         wd.CleanUp();
     }
 }
 public OnlineEnergyFileRow([NotNull] TimeStep timestep, [NotNull] List <double> energyEntries, [NotNull] CalcLoadTypeDto loadType)
 {
     Timestep       = timestep;
     _sum           = null;
     _energyEntries = energyEntries;
     _loadType      = loadType;
 }
        private static Dictionary <StrGuid, Dictionary <int, double> > MakeSumPerMonthPerDeviceID(
            [NotNull] CalcLoadTypeDto dstLoadType,
            [NotNull] EnergyFileColumns efc,
            [NotNull] Dictionary <int, OnlineEnergyFileRow> sumsPerMonth,
            [NotNull] out Dictionary <int, ColumnEntry> columns)
        {
            var sumPerMonthPerDeviceID = new Dictionary <StrGuid, Dictionary <int, double> >();

            columns = efc.ColumnEntriesByColumn[dstLoadType];
            foreach (var onlineEnergyFileRow in sumsPerMonth)
            {
                var month = onlineEnergyFileRow.Key;

                //var monthsum = onlineEnergyFileRow.Value;
                foreach (var pair in columns)
                {
                    var ce = pair.Value;
                    if (!sumPerMonthPerDeviceID.ContainsKey(ce.DeviceGuid))
                    {
                        sumPerMonthPerDeviceID.Add(ce.DeviceGuid, new Dictionary <int, double>());
                    }

                    if (!sumPerMonthPerDeviceID[ce.DeviceGuid].ContainsKey(month))
                    {
                        sumPerMonthPerDeviceID[ce.DeviceGuid].Add(month, 0);
                    }

                    sumPerMonthPerDeviceID[ce.DeviceGuid][month] += sumsPerMonth[month].EnergyEntries[pair.Key];
                }
            }

            return(sumPerMonthPerDeviceID);
        }
Exemplo n.º 14
0
 public TotalsPerLoadtypeEntry([NotNull] HouseholdKey key, [NotNull] CalcLoadTypeDto loadtype, double value, int numberOfPersons, double totalDays)
 {
     HouseholdKey    = key;
     Loadtype        = loadtype;
     Value           = value;
     NumberOfPersons = numberOfPersons;
     TotalDays       = totalDays;
 }
        public OnlineEnergyFileRow([NotNull] OnlineEnergyFileRow other)
        {
            Timestep = other.Timestep;
            var otherEntries = new List <double>(other._energyEntries);

            _energyEntries = otherEntries;
            _loadType      = other.LoadType;
            _sum           = null;
        }
        //[NotNull] public Dictionary<CalcLoadTypeDto, Dictionary<int, ColumnEntry>> ColumnEntriesByColumn => _columnEntriesByColumn;

        public bool IsDeviceRegistered([NotNull] CalcLoadTypeDto loadtype, OefcKey key)
        {
            if (_columnEntriesByLoadTypeByDeviceKey.ContainsKey(loadtype) &&
                ColumnEntriesByLoadTypeByDeviceKey[loadtype].ContainsKey(key))
            {
                return(true);
            }
            throw new LPGException("Forgotten device registration: " + key);
        }
Exemplo n.º 17
0
        private List <CalcSiteDto> MakeCalcSiteDtos([NotNull][ItemNotNull] List <Site> householdSites,
                                                    [NotNull][ItemNotNull] List <CalcLocationDto> calcLocations,
                                                    [NotNull] Dictionary <TransportationDeviceCategory,
                                                                          CalcTransportationDeviceCategoryDto> categoriesDict,
                                                    [NotNull] HouseholdKey householdKey,
                                                    [CanBeNull] ChargingStationSet chargingStationSet)
        {
            List <CalcSiteDto> calcSites = new List <CalcSiteDto>();

            //create the calcsites
            foreach (Site site in householdSites)
            {
                CalcSiteDto calcSite = new CalcSiteDto(site.Name, site.IntID, Guid.NewGuid().ToStrGuid(), householdKey);
                if (chargingStationSet != null)
                {
                    var chargingStationsAtSite =
                        chargingStationSet.ChargingStations.Where(x => x.Site == site).ToList();
                    foreach (var chargingStationSetEntry in chargingStationsAtSite)
                    {
                        if (chargingStationSetEntry.CarChargingLoadType == null)
                        {
                            throw new LPGException("Car charging load type was null");
                        }
                        if (chargingStationSetEntry.GridChargingLoadType == null)
                        {
                            throw new LPGException("Grid charging load type was null");
                        }

                        CalcLoadTypeDto carlt  = _loadTypeDict.Ltdtodict[chargingStationSetEntry.CarChargingLoadType];
                        CalcLoadTypeDto gridlt = _loadTypeDict.Ltdtodict[chargingStationSetEntry.GridChargingLoadType];
                        if (chargingStationSetEntry.TransportationDeviceCategory == null)
                        {
                            throw new LPGException("charging device category was null");
                        }

                        CalcTransportationDeviceCategoryDto cat =
                            categoriesDict[chargingStationSetEntry.TransportationDeviceCategory];
                        calcSite.AddChargingStation(gridlt, cat, chargingStationSetEntry.MaxChargingPower, carlt);
                    }
                }

                foreach (var calcloc in calcLocations)
                {
                    foreach (SiteLocation location in site.Locations)
                    {
                        if (calcloc.ID == location.Location.IntID)
                        {
                            calcSite.AddLocation(calcloc);
                        }
                    }
                }
                calcSites.Add(calcSite);
            }
            return(calcSites);
        }
        /*
         * public void RunIndividualHouseholdsPolysun([JetBrains.Annotations.NotNull] CalcLoadTypeDto dstLoadType,
         *  [JetBrains.Annotations.NotNull][ItemNotNull] List<OnlineEnergyFileRow> energyFileRows, [JetBrains.Annotations.NotNull] FileFactoryAndTracker fft, [JetBrains.Annotations.NotNull] EnergyFileColumns efc)
         * {
         *  var fifteenmin = new TimeSpan(0, 15, 0);
         *  var externalfactor =
         *      (int) (fifteenmin.TotalSeconds / _calcParameters.InternalStepsize.TotalSeconds);
         *  if (externalfactor == 1) {
         *      return;
         *  }
         *  var externalFileName = fifteenmin.TotalSeconds.ToString(CultureInfo.InvariantCulture);
         *  var householdNumbers =
         *      (efc.ColumnEntriesByColumn[dstLoadType].Values.Select(entry => entry.HouseholdKey)).Distinct()
         *      .ToList();
         *  var householdNames = Repository.HouseholdKeys;
         *  Dictionary<HouseholdKey, string> householdNamesByKey = new Dictionary<HouseholdKey, string>();
         *  foreach (HouseholdKeyEntry entry in householdNames) {
         *      householdNamesByKey.Add(entry.HouseholdKey,entry.HouseholdName);
         *  }
         *  if (householdNumbers.Count > 1) {
         *      foreach (var hhnum in householdNumbers) {
         *          if (!householdNamesByKey.ContainsKey(hhnum)) {
         *              continue;
         *          }
         *          var columns =
         *          (from entry in efc.ColumnEntriesByColumn[dstLoadType].Values
         *              where entry.HouseholdKey == hhnum
         *              select entry.Column).ToList();
         *          var hhname = "." + hhnum + ".";
         *
         *          var sumfile =
         *              fft.MakeFile<StreamWriter>(
         *                  "ImportProfile_" + externalFileName + "s" + hhname + dstLoadType.Name + ".csv",
         *                  "Summed up energy profile without timestamp for " + externalFileName + "s " +
         *                  dstLoadType.Name + " and HH" + hhnum, true,
         *                  ResultFileID.PolysunImportFileHH, hhnum, TargetDirectory.Results, fifteenmin,
         *                  dstLoadType.ConvertToLoadTypeInformation());
         *          WritePolysunHeader(sumfile, householdNamesByKey[hhnum], dstLoadType);
         *          var timestepcount = 0;
         *          var ts = TimeSpan.Zero;
         *          for (var outerIndex = 0; outerIndex < energyFileRows.Count; outerIndex += externalfactor) {
         *              var efr = energyFileRows[outerIndex];
         *              if (!efr.Timestep.DisplayThisStep) {
         *                  continue;
         *              }
         *              double sum = 0;
         *
         *              for (var innerIndex = outerIndex;
         *                  innerIndex < outerIndex + externalfactor && innerIndex < energyFileRows.Count;
         *                  innerIndex++) {
         *                  var efr2 = energyFileRows[innerIndex];
         *                  sum += efr2.GetSumForCertainCols(columns);
         *                  timestepcount++;
         *                  ts = ts.Add(_calcParameters.InternalStepsize);
         *              }
         *              sum = sum * dstLoadType.ConversionFactor;
         *              var normalstr = ts.TotalSeconds + _calcParameters.CSVCharacter +
         *                              sum.ToString("N4", CultureInfo.InvariantCulture);
         *              sumfile.WriteLine(normalstr);
         *          }
         *          if (timestepcount != energyFileRows.Count) {
         *              throw new LPGException("Importfilecreator seems to be broken! Please report!");
         *          }
         *      }
         *  }
         * }*/

        public void RunPolysun([NotNull] CalcLoadTypeDto dstLoadType,
                               [NotNull][ItemNotNull] List <OnlineEnergyFileRow> energyFileRows,
                               [NotNull] IFileFactoryAndTracker fft,
                               [NotNull] string housename)
        {
            var calcParameters = Repository.CalcParameters;
            var fifteenMin     = new TimeSpan(0, 15, 0);
            var externalfactor = (int)(fifteenMin.TotalSeconds / calcParameters.InternalStepsize.TotalSeconds);

            if (externalfactor == 1)
            {
                return;
            }

            var externalFileName = fifteenMin.TotalSeconds.ToString(CultureInfo.InvariantCulture);
            var sumfile          = fft.MakeFile <StreamWriter>("ImportProfile." + externalFileName + "s." + dstLoadType.Name + ".csv",
                                                               "Sum energy profile with timestamp for import in Polysun " + externalFileName + "s " + dstLoadType.Name,
                                                               true,
                                                               ResultFileID.PolysunImportFile,
                                                               Constants.GeneralHouseholdKey,
                                                               TargetDirectory.Results,
                                                               fifteenMin, CalcOption.PolysunImportFiles,
                                                               dstLoadType.ConvertToLoadTypeInformation());
            //var count = energyFileRows[0].EnergyEntries.Count;
            var ts = TimeSpan.Zero;

            //var timestepcount = 0;
            WritePolysunHeader(sumfile, housename, dstLoadType);

            for (var outerIndex = 0; outerIndex < energyFileRows.Count; outerIndex += externalfactor)
            {
                var efrOuter = energyFileRows[outerIndex];
                if (!efrOuter.Timestep.DisplayThisStep)
                {
                    continue;
                }

                double sum = 0;
                for (var innerIndex = outerIndex; innerIndex < outerIndex + externalfactor && innerIndex < energyFileRows.Count; innerIndex++)
                {
                    var efr2 = energyFileRows[innerIndex];
                    sum += efr2.SumCached;
                    //      timestepcount++;
                }

                var sumPower  = sum * dstLoadType.ConversionFactor; // change to power
                var normalstr = ts.TotalSeconds + calcParameters.CSVCharacter + sumPower.ToString("N8", CultureInfo.InvariantCulture);
                sumfile.WriteLine(normalstr);
            }
            //  if (timestepcount != energyFileRows.Count) { //this does not consider the hidden time steps
            //    throw new LPGException("Importfilecreator seems to be broken! Please report!");
            //}
            sumfile.Flush();
        }
 public void RunCalcLoadtypeDtoLoggerTest()
 {
     using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
     {
         CalcLoadTypeDtoLogger  cldtl    = new CalcLoadTypeDtoLogger(wd.SqlResultLoggingService);
         CalcLoadTypeDto        cdls     = new CalcLoadTypeDto("name", "unit", "unit", 5, true, "guid".ToStrGuid());
         List <CalcLoadTypeDto> cdlsList = new List <CalcLoadTypeDto>();
         cdlsList.Add(cdls);
         cldtl.Run(Constants.GeneralHouseholdKey, cdlsList);
         cldtl.Load();
     }
 }
        private static OnlineEnergyFileRow GetRowForLoadType([NotNull] CalcLoadTypeDto lt,
                                                             [NotNull][ItemNotNull] List <OnlineEnergyFileRow> fileRows)
        {
            foreach (var onlineEnergyFileRow in fileRows)
            {
                if (onlineEnergyFileRow.LoadType == lt)
                {
                    return(onlineEnergyFileRow);
                }
            }

            return(null);
        }
        private void MakeSumsForJson([NotNull] CalcLoadTypeDto dstLoadType,
                                     [NotNull][ItemNotNull] List <OnlineEnergyFileRow> energyFileRows,
                                     [NotNull] EnergyFileColumns efc,
                                     [NotNull] HouseholdKey key)
        {
            var calcParameters = Repository.CalcParameters;
            var dsc            = new DateStampCreator(calcParameters);

            if (!efc.ColumnEntriesByColumn.ContainsKey(dstLoadType))
            {
                return;
            }

            var cols = efc.ColumnEntriesByColumn[dstLoadType];
            var tdp  = new Dictionary <int, TotalsPerDeviceEntry>();

            foreach (var pair in cols)
            {
                var tpde = new TotalsPerDeviceEntry(key, pair.Value.CalcDeviceDto, dstLoadType);
                tdp.Add(pair.Key, tpde);
            }

            foreach (var row in energyFileRows)
            {
                if (!row.Timestep.DisplayThisStep)
                {
                    continue;
                }

                var month = dsc.MakeDateFromTimeStep(row.Timestep).Month;
                foreach (var pair in cols)
                {
                    // ReSharper disable once CompareOfFloatsByEqualityOperator
                    if (row.EnergyEntries[pair.Key] == 0)
                    {
                        continue;
                    }

                    tdp[pair.Key].AddConsumptionValue(month, row.EnergyEntries[pair.Key]);
                }
            }

            foreach (var value in tdp.Values)
            {
                value.Value          *= value.Loadtype.ConversionFactor;
                value.NegativeValues *= value.Loadtype.ConversionFactor;
                value.PositiveValues *= value.Loadtype.ConversionFactor;
            }

            _inputDataLogger.SaveList(tdp.Values.ToList().ConvertAll(x => (IHouseholdKey)x));
        }
        private CalcAirConditioningDto MakeAirConditioning([NotNull] TemperatureProfile temperatureProfile,
                                                           [NotNull] HouseType houseType,
                                                           [NotNull] HouseholdKey householdKey,
                                                           [CanBeNull] out CalcLocationDto airConditioningLocation)
        {
            var coolingParameter = MakeCoolingParameters(temperatureProfile, houseType);

            if (coolingParameter == null)
            {
                airConditioningLocation = null;
                return(null);
            }

            var degreeHourDict = new List <CalcDegreeHourDto>();

            foreach (var degreeHour in coolingParameter.DegreeHours)
            {
                var cdd = new CalcDegreeHourDto(degreeHour.Date.Year,
                                                degreeHour.Date.Month,
                                                degreeHour.Date.Day,
                                                degreeHour.Date.Hour,
                                                degreeHour.CoolingAmount);
                degreeHourDict.Add(cdd);
            }

            CalcLoadTypeDto lt  = _ltDict.GetLoadtypeDtoByLoadType(coolingParameter.CoolingLoadType);
            var             cdl = new CalcDeviceLoadDto(coolingParameter.CoolingLoadType.Name,
                                                        -1,
                                                        lt.Name,
                                                        lt.Guid,
                                                        coolingParameter.YearlyConsumption,
                                                        0,
                                                        Guid.NewGuid().ToStrGuid(),
                                                        1);
            var cdls = new List <CalcDeviceLoadDto> {
                cdl
            };

            airConditioningLocation = new CalcLocationDto("Air Conditioning", -100, Guid.NewGuid().ToStrGuid());
            var csh = new CalcAirConditioningDto("Air Conditioning",
                                                 -1,
                                                 cdls,
                                                 degreeHourDict,
                                                 householdKey,
                                                 airConditioningLocation.Name,
                                                 airConditioningLocation.Guid,
                                                 Guid.NewGuid().ToStrGuid());

            return(csh);
        }
 public ColumnEntry([NotNull] string name, int dstcolumn, [NotNull] string locationName, StrGuid deviceGuid, [NotNull] HouseholdKey householdKey,
                    [NotNull] CalcLoadTypeDto loadType, [NotNull] string oefckey, [NotNull] string deviceCategory,
                    [NotNull] CalcDeviceDto calcDeviceDto)
 {
     Name = name;
     // Key = key,
     Column         = dstcolumn;
     LocationName   = locationName;
     DeviceGuid     = deviceGuid;
     HouseholdKey   = householdKey;
     LoadType       = loadType;
     Oefckey        = oefckey;
     DeviceCategory = deviceCategory;
     CalcDeviceDto  = calcDeviceDto;
 }
 public CalcLoadType([NotNull] string pName, [NotNull] string unitOfPower, [NotNull] string unitOfSum, double conversionFactor,
                     bool showInCharts, StrGuid guid)
     : base(pName, guid)
 {
     UnitOfPower      = unitOfPower;
     UnitOfSum        = unitOfSum;
     ConversionFactor = conversionFactor;
     ShowInCharts     = showInCharts;
     _fileName        = AutomationUtili.CleanFileName(pName);
     while (_fileName.Contains("  "))
     {
         _fileName = _fileName.Replace("  ", " ");
     }
     _lti = new LoadTypeInformation(Name, UnitOfSum, UnitOfPower, ConversionFactor, ShowInCharts, _fileName, Guid);
     _dto = new CalcLoadTypeDto(pName, unitOfPower, unitOfSum, conversionFactor, ShowInCharts, guid);
 }
Exemplo n.º 25
0
        private List <CalcTransportationDeviceDto> MakeTransportationDevices([NotNull][ItemNotNull] List <TransportationDevice> transportationDevices,
                                                                             [NotNull] Dictionary <TransportationDeviceCategory, CalcTransportationDeviceCategoryDto> categoriesDict, [NotNull] HouseholdKey key)
        {
            List <CalcTransportationDeviceDto> transportationDeviceDtos = new List <CalcTransportationDeviceDto>();

            foreach (var transportationDevice in transportationDevices)
            {
                var loads = new List <CalcDeviceLoadDto>();
                foreach (TransportationDeviceLoad load in transportationDevice.Loads)
                {
                    VLoadType lt = load.LoadType;
                    if (lt == null)
                    {
                        throw new LPGException("Loadtype was null. This should never happen. Please report");
                    }

                    if (_loadTypeDict.SimulateLoadtype(lt))
                    {
                        CalcLoadTypeDto loadType = _loadTypeDict.GetLoadtypeDtoByLoadType(lt);
                        loads.Add(new CalcDeviceLoadDto(transportationDevice.Name + " - " + lt.Name,
                                                        transportationDevice.IntID, loadType.Name, loadType.Guid,
                                                        0, 0, Guid.NewGuid().ToStrGuid(), load.MaxPower));
                    }
                }

                double          distanceToEnergyFactor = 0;
                CalcLoadTypeDto chargingLoadType       = null;
                if (transportationDevice.ChargingDistanceAmount > 0 && transportationDevice.ChargingLoadType != null)
                {
                    distanceToEnergyFactor = DistanceToPowerFactor(transportationDevice.ChargingDistanceAmount, transportationDevice.ChargingEnergyAmount, transportationDevice.ChargingLoadType.ConversionFaktorPowerToSum);
                    chargingLoadType       = _loadTypeDict.Ltdtodict[transportationDevice.ChargingLoadType];
                }

                if (transportationDevice.TransportationDeviceCategory == null)
                {
                    throw new LPGException("Transportation device category was null");
                }
                CalcTransportationDeviceDto cd = new CalcTransportationDeviceDto(transportationDevice.Name,
                                                                                 transportationDevice.IntID, categoriesDict[transportationDevice.TransportationDeviceCategory],
                                                                                 transportationDevice.SpeedInMPerSecond, loads, key, transportationDevice.TotalRangeInMeters,
                                                                                 distanceToEnergyFactor, transportationDevice.ChargingPower, chargingLoadType?.Name, chargingLoadType?.Guid, Guid.NewGuid().ToStrGuid(),
                                                                                 transportationDevice.TransportationDeviceCategory.IsLimitedToSingleLocation);
                transportationDeviceDtos.Add(cd);
            }

            return(transportationDeviceDtos);
        }
        public static CalcLoadTypeDtoDictionary MakeLoadTypes(
            [NotNull][ItemNotNull] ObservableCollection <VLoadType> loadTypes, TimeSpan internalTimeResolution,
            LoadTypePriority priority)
        {
            var ltDtoDict = new Dictionary <VLoadType, CalcLoadTypeDto>();

            foreach (var lt in loadTypes)
            {
                // ReSharper disable once ReplaceWithSingleAssignment.True
                if (lt.Priority <= priority)
                {
                    var guid            = Guid.NewGuid().ToStrGuid();
                    var calcLoadTypeDto = new CalcLoadTypeDto(lt.Name, lt.UnitOfPower, lt.UnitOfSum,
                                                              lt.ConvertPowerValueWithTime(1, internalTimeResolution), lt.ShowInCharts, guid);
                    ltDtoDict.Add(lt, calcLoadTypeDto);
                }
            }
            return(new CalcLoadTypeDtoDictionary(ltDtoDict));
        }
        public static OnlineEnergyFileRow Read([NotNull] BinaryReader br, [NotNull] CalcLoadTypeDto lt,
                                               [NotNull] CalcParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            var timestep = new TimeStep(br.ReadInt32(), parameters);
            var length   = br.ReadInt32();
            var valuearr = new List <double>(new double[length]);

            for (var i = 0; i < length; i++)
            {
                valuearr[i] = br.ReadDouble();
            }
            var efr = new OnlineEnergyFileRow(timestep, valuearr, lt);

            return(efr);
        }
 public DeviceActivationEntry(
     [NotNull] string affordanceName,
     [NotNull] CalcLoadTypeDto loadType,
     double value,
     [NotNull] string activatorName,
     int durationInSteps,
     TimeStep timestep, [NotNull] CalcDeviceDto calcDeviceDto)
 {
     if (calcDeviceDto == null)
     {
         throw new LPGException("Calcdevicedto was null");
     }
     AffordanceName  = affordanceName;
     LoadTypeGuid    = loadType.Guid;
     LoadTypeName    = loadType.Name;
     TotalEnergySum  = value;
     ActivatorName   = activatorName;
     Timestep        = timestep;
     CalcDeviceDto   = calcDeviceDto;
     DurationInSteps = durationInSteps;
 }
        public void SetValue([NotNull] string name, double value, [NotNull] TimeStep timestep, [NotNull] HouseholdKey householdKey,
                             [NotNull] CalcLoadTypeDto loadType)
        {
            if (timestep != _currentTimeStep)
            {
                if (_currentEntry != null)
                {
                    WriteEntry(_currentEntry, householdKey);
                }

                _currentEntry    = new EnergyStorageEntry(timestep, this, _calcParameters.CSVCharacter, _dsc);
                _currentTimeStep = timestep;
            }

            if (_currentEntry == null)
            {
                throw new LPGException("Currententry was null");
            }

            _currentEntry.AddValue(name, value * loadType.ConversionFactor);
        }
        private int WriteNormalPart([NotNull] CalcLoadTypeDto dstLoadType, [NotNull] StreamWriter resultfile,
                                    [NotNull] Dictionary <int, Dictionary <int, double> > dailyValues, [NotNull] Dictionary <DayOfWeek, int> dayCount)
        {
            var calcParameters = Repository.CalcParameters;
            var headerdays     = string.Empty;

            foreach (DayOfWeek day in Enum.GetValues(typeof(DayOfWeek)))
            {
                headerdays += day.ToString();
                headerdays += calcParameters.CSVCharacter;
            }
            resultfile.WriteLine(dstLoadType.Name + ".Time;Calender;Calender for Excel" +
                                 calcParameters.CSVCharacter + headerdays);

            var valuecount = dailyValues.Values.First().Count;

            for (var i = 0; i < valuecount; i++)
            {
                var time = MakeWriteableString(i);
                foreach (DayOfWeek day in Enum.GetValues(typeof(DayOfWeek)))
                {
                    double value = 0;
                    if (dailyValues.ContainsKey((int)day))
                    {
                        value = dailyValues[(int)day][i];
                    }
                    if (dayCount.ContainsKey(day))
                    {
                        time += value / dayCount[day] + calcParameters.CSVCharacter;
                    }
                    else
                    {
                        time += calcParameters.CSVCharacter;
                    }
                }
                resultfile.WriteLine(time);
            }
            return(valuecount);
        }