public override void Activate(TimeStep startTime, string activatorName, CalcLocation personSourceLocation,
                                      out ICalcProfile personTimeProfile)
        {
            for (var i = 0; i < PersonProfileDuration && i + startTime.InternalStep < IsBusyArray.Length; i++)
            {
                IsBusyArray[i + startTime.InternalStep] = true;
            }
            foreach (var op in _variableOps)
            {
                // figure out end time
                TimeStep time;
                switch (op.ExecutionTime)
                {
                case VariableExecutionTime.Beginning:
                    time = startTime;
                    break;

                case VariableExecutionTime.EndOfPerson:
                case VariableExecutionTime.EndofDevices:
                    time = startTime.AddSteps(PersonProfileDuration);
                    break;

                default:
                    throw new LPGException("Forgotten Variable Execution Time");
                }
                _repository.AddExecutionEntry(op.Name, op.Value, op.CalcLocation, op.VariableAction, time, op.VariableGuid);
            }
            personTimeProfile = new CalcSubAffTimeProfile(_durations,
                                                          _durations + " timesteps Person profile");
        }
 public bool IsExpired([NotNull] TimeStep timestep)
 {
     if (timestep >= _startTimeStep.AddSteps(StepValues.Values.Count))
     {
         return(true);
     }
     return(false);
 }
Esempio n. 3
0
        private void CleanZeroValueEntries([NotNull] TimeStep currentTime)
        {
            TimeStep nextStep     = currentTime.AddSteps(1);
            var      items2Delete = _zeroEntries.Where(x => x.EndTime < nextStep).ToList();

            foreach (var entry in items2Delete)
            {
                _zeroEntries.Remove(entry);
            }
        }
        public TimeStep SetTimeprofile([NotNull] CalcProfile calcProfile, [NotNull] TimeStep startTimeStep, [NotNull] CalcLoadType loadType,
                                       [NotNull] string affordanceName, [NotNull] string activatingPersonName, double multiplier, bool activateDespiteBeingBusy)
        {
            if (calcProfile.StepValues.Count == 0)
            {
                throw new LPGException("Trying to set empty device profile. This is a bug. Please report.");
            }

            CalcDeviceLoad cdl = _deviceLoadsBy[loadType];

            if (cdl == null)
            {
                throw new LPGException("It was tried to activate the loadtype " + loadType.Name +
                                       " even though that one is not set for the device " + Name);
            }

            /*if (Math.Abs(cdl.Value) < 0.00000001 ) {
             *  throw new LPGException("Trying to calculate with a power consumption factor of 0. This is wrong.");
             * }*/
            if (CalcRepo.Odap == null && !Config.IsInUnitTesting)
            {
                throw new LPGException("ODAP was null. Please report");
            }
            var totalDuration = calcProfile.StepValues.Count; //.GetNewLengthAfterCompressExpand(timefactor);
            //calcProfile.CompressExpandDoubleArray(timefactor,allProfiles),
            var key = _keyByLoad[cdl.LoadType];

            RandomValueProfile rvp = GetRandomValueProfile(calcProfile.StepValues.Count, cdl, startTimeStep);
            StepValues         sv  = StepValues.MakeStepValues(calcProfile,
                                                               multiplier, rvp, cdl);

            CalcRepo.Odap.AddNewStateMachine(
                startTimeStep,
                cdl.LoadType.ConvertToDto(),
                affordanceName,
                activatingPersonName,
                key,
                _calcDeviceDto, sv);

            if (MatchingAutoDevs.Count > 0)
            {
                foreach (CalcAutoDev matchingAutoDev in MatchingAutoDevs)
                {
                    if (matchingAutoDev._keyByLoad.ContainsKey(cdl.LoadType))
                    {
                        var zerokey = matchingAutoDev._keyByLoad[cdl.LoadType];
                        CalcRepo.Odap.AddZeroEntryForAutoDev(zerokey,
                                                             startTimeStep,
                                                             totalDuration);
                    }
                }
            }
            SetBusy(startTimeStep, totalDuration, loadType, activateDespiteBeingBusy);
            return(startTimeStep.AddSteps(totalDuration));
        }
        public int Activate([NotNull] TimeStep currentTimeStep, [NotNull] string calcPersonName,
                            [NotNull][ItemNotNull] out List <CalcTravelDeviceUseEvent> usedDeviceEvents)
        {
            if (_mypicks.Timestep != currentTimeStep || _mypicks.CalcPersonName != calcPersonName)
            {
                throw new LPGException("Device was not previously picked?");
            }

            if (currentTimeStep.InternalStep == 14095)
            {
                Logger.Info("timestep 14095");
            }

            //_mypicks = new PreviouslyPickedDevices(calcPersonName, currentTimeStep);
            int totalDuration = 0;

            //int slidingTimeStep = currentTimeStep;
            _calcRepo.OnlineLoggingData.AddTransportationStatus(new TransportationStatus(
                                                                    currentTimeStep,
                                                                    _householdkey, "\tActivating " + Name));
            usedDeviceEvents = new List <CalcTravelDeviceUseEvent>();

            foreach (CalcTravelRouteStep step in Steps)
            {
                int pickedDuration = _mypicks.PickedDurations[step];
                totalDuration += pickedDuration;
            }

            TimeStep transportationEventEndTimestep = currentTimeStep.AddSteps(totalDuration);
            TimeStep timeStepOfThisStep             = currentTimeStep;

            foreach (CalcTravelRouteStep step in Steps)
            {
                var device         = _mypicks.PickedDevices[step];
                int pickedDuration = _mypicks.PickedDurations[step];
                usedDeviceEvents.Add(new CalcTravelDeviceUseEvent(device, pickedDuration, step.DistanceOfStepInM));
                //step.CalculateDurationInTimestepsAndPickDevice(slidingTimeStep, out CalcTransportationDevice pickedDevice,
                //out int durationForPickedDeviceInTimesteps, SiteA, _vehiclePool, _locationUnlimitedDevices, rnd);
                _calcRepo.OnlineLoggingData.AddTransportationStatus(new TransportationStatus(
                                                                        currentTimeStep,
                                                                        _householdkey,
                                                                        "\tActiviating step " + step.Name + " Device " + device.Name + " Distance: "
                                                                        + step.DistanceOfStepInM + " Step Duration: " + pickedDuration));
                //slidingTimeStep += pickedDuration;
                //_mypicks.PickedDevices.Add(step, pickedDevice);
                step.ActivateStep(timeStepOfThisStep, device, pickedDuration,
                                  SiteA, SiteB, Name, calcPersonName, currentTimeStep,
                                  transportationEventEndTimestep);
                timeStepOfThisStep = timeStepOfThisStep.AddSteps(pickedDuration);
            }
            _mypicks.PreviouslyCalculatedTimeSteps = totalDuration;
            return(totalDuration);
        }
Esempio n. 6
0
        public bool IsBusy(TimeStep time,
                           CalcLocation srcLocation, string calcPersonName,
                           bool clearDictionaries = true)
        {
            if (_myLastTimeEntry.TimeOfLastEvalulation != time || _myLastTimeEntry.PersonName != calcPersonName)
            {
                _myLastTimeEntry = new LastTimeEntry(calcPersonName, time);
            }

            CalcTravelRoute route;

            if (_myLastTimeEntry.PreviouslySelectedRoutes.ContainsKey(srcLocation))
            {
                route = _myLastTimeEntry.PreviouslySelectedRoutes[srcLocation];
            }
            else
            {
                route = _transportationHandler.GetTravelRouteFromSrcLoc(srcLocation, Site, time, calcPersonName, _calcRepo);
                _myLastTimeEntry.PreviouslySelectedRoutes.Add(srcLocation, route);
            }

            if (route == null)
            {
                return(true);
            }

            // ReSharper disable once PossibleInvalidOperationException
            int?travelDurationN = (int)route.GetDuration(time, calcPersonName, _transportationHandler.AllMoveableDevices);

            if (travelDurationN == null)
            {
                throw new LPGException("Bug: couldn't calculate travel duration for route.");
            }

            TimeStep dstStartTime = time.AddSteps(travelDurationN.Value);

            if (dstStartTime.InternalStep > _calcRepo.CalcParameters.InternalTimesteps)
            {
                //if the end of the activity is after the simulation, everything is ok.
                return(false);
            }
            bool result = _sourceAffordance.IsBusy(dstStartTime, srcLocation, calcPersonName,
                                                   clearDictionaries);

            _calcRepo.OnlineLoggingData.AddTransportationStatus(new TransportationStatus(
                                                                    time,
                                                                    _householdkey, "\t\t" + time + " @" + srcLocation + " by " + calcPersonName
                                                                    + "Checking " + Name + " for busyness: " + result + " @time " + dstStartTime
                                                                    + " with the route " + route.Name + " and a travel duration of " + travelDurationN));
            return(result);
        }
        public int?GetDuration([NotNull] TimeStep currentTimeStep, [NotNull] string calcPersonName,
                               [ItemNotNull][NotNull] List <CalcTransportationDevice> allTransportationDevices)
        {
            if (_mypicks.Timestep == currentTimeStep && _mypicks.CalcPersonName == calcPersonName)
            {
                return(_mypicks.PreviouslyCalculatedTimeSteps);
            }

            var      picks           = new PreviouslyPickedDevices(calcPersonName, currentTimeStep);
            int      totalDuration   = 0;
            TimeStep slidingTimeStep = currentTimeStep;
            var      deviceAtSrc     = allTransportationDevices.Where(x => x.Currentsite == SiteA).ToList();

            foreach (CalcTravelRouteStep step in Steps)
            {
                bool success = step.CalculateDurationInTimestepsAndPickDevice(slidingTimeStep,
                                                                              out CalcTransportationDevice pickedDevice,
                                                                              out int?durationForPickedDeviceInTimesteps,
                                                                              _vehiclePool,
                                                                              _locationUnlimitedDevices, deviceAtSrc);
                if (!success)
                {
                    //this travel route step not now available, thus the entire route is invalid.
                    return(null);
                }

                if (pickedDevice?.Category != step.TransportationDeviceCategory)
                {
                    throw new LPGException("Invalid device was picked.");
                }

                if (durationForPickedDeviceInTimesteps == null)
                {
                    throw new LPGException("Failed Travel duration calculation!");
                }

                slidingTimeStep = slidingTimeStep.AddSteps((int)durationForPickedDeviceInTimesteps);
                totalDuration  += (int)durationForPickedDeviceInTimesteps;
                picks.PickedDevices.Add(step, pickedDevice);
                picks.PickedDurations.Add(step, (int)durationForPickedDeviceInTimesteps);
            }

            picks.PreviouslyCalculatedTimeSteps = totalDuration;
            _mypicks = picks;
            _calcRepo.OnlineLoggingData.AddTransportationStatus(new TransportationStatus(
                                                                    currentTimeStep,
                                                                    _householdkey,
                                                                    "\t\t\tCalculated a duration for the route of " + totalDuration));
            return(totalDuration);
        }
Esempio n. 8
0
        public void SetTimeprofileTest()
        {
            DateTime       startdate      = new DateTime(2018, 1, 1);
            DateTime       enddate        = startdate.AddMinutes(10);
            CalcParameters calcParameters =
                CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate);

            CalcLoadType          clt  = MakeCalcLoadType();
            CalcLocation          cloc = new CalcLocation("blub", Guid.NewGuid().ToStrGuid());
            CalcDeviceLoad        cdl  = new CalcDeviceLoad("cdl1", 1, clt, 1, 0.1);
            List <CalcDeviceLoad> cdls = new List <CalcDeviceLoad>();

            using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
            {
                wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                using (FileFactoryAndTracker fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hh1", wd.InputDataLogger))
                {
                    fft.RegisterHousehold(Constants.GeneralHouseholdKey, "General", HouseholdKeyType.General, "desc", null, null);
                    //SqlResultLoggingService srls = new SqlResultLoggingService(wd.WorkingDirectory);
                    DateStampCreator dsc = new DateStampCreator(calcParameters);

                    using (IOnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters))
                    {
                        cdls.Add(cdl);

                        OnlineDeviceActivationProcessor odap =
                            new OnlineDeviceActivationProcessor(old, calcParameters, fft);
                        var           deviceCategoryGuid = Guid.NewGuid().ToStrGuid();
                        CalcDeviceDto cdd = new CalcDeviceDto("bla", deviceCategoryGuid
                                                              , new HouseholdKey("HH-6"), OefcDeviceType.Device, "category",
                                                              string.Empty, Guid.NewGuid().ToStrGuid(), cloc.Guid, cloc.Name);
                        using CalcRepo calcRepo = new CalcRepo(odap: odap, calcParameters: calcParameters, normalRandom: NormalRandom);
                        CalcDevice cd = new CalcDevice(cdls, cloc,
                                                       cdd, calcRepo);
                        CalcProfile cp  = MakeCalcProfile5Min100();
                        TimeStep    ts1 = new TimeStep(1, calcParameters);
                        cd.SetAllLoadTypesToTimeprofile(cp, ts1, "test", "name1", 1);
                        TimeStep ts = new TimeStep(0, calcParameters);
                        cd.IsBusyDuringTimespan(ts, 1, 1, clt).Should().BeFalse();
                        cd.IsBusyDuringTimespan(ts.AddSteps(1), 1, 1, clt).Should().BeTrue();
                        cd.IsBusyDuringTimespan(ts.AddSteps(2), 1, 1, clt).Should().BeTrue();
                        cd.IsBusyDuringTimespan(ts.AddSteps(3), 1, 1, clt).Should().BeTrue();
                        cd.IsBusyDuringTimespan(ts.AddSteps(4), 1, 1, clt).Should().BeTrue();
                        cd.IsBusyDuringTimespan(ts.AddSteps(5), 1, 1, clt).Should().BeTrue();
                        cd.IsBusyDuringTimespan(ts.AddSteps(6), 0, 1, clt).Should().BeFalse();
                    }
                }

                wd.CleanUp();
            }
        }
        public void AddTransportationEvent(HouseholdKey householdkey,
                                           string person, TimeStep timestep,
                                           string srcSite,
                                           string dstSite,
                                           string route,
                                           string transportationDevice,
                                           int transportationDuration,
                                           int affordanceDuration,
                                           string affordanceName,
                                           List <CalcTravelRoute.CalcTravelDeviceUseEvent> travelDeviceUseEvents
                                           )
        {
            if (!_calcParameters.Options.Contains(CalcOption.TransportationStatistics))
            {
                return;
            }

            //put all the individual travel device uses in as events
            if (transportationDuration > 0)
            {
                TimeStep mytimestep = timestep;
                foreach (CalcTravelRoute.CalcTravelDeviceUseEvent calcTravelDeviceUseEvent in travelDeviceUseEvents)
                {
                    string description = route + " with " + transportationDevice + " for " + transportationDuration +
                                         " steps to " +
                                         affordanceName + " - " + calcTravelDeviceUseEvent.Device.Name;

                    TransportationEventEntry tee = new TransportationEventEntry(householdkey, person, mytimestep,
                                                                                srcSite, dstSite,
                                                                                CurrentActivity.InTransport, description, calcTravelDeviceUseEvent.Device.Name,
                                                                                transportationDuration, calcTravelDeviceUseEvent.TotalDistance);
                    _transportationEvents.Add(tee);
                    mytimestep = mytimestep.AddSteps(calcTravelDeviceUseEvent.DurationInSteps);
                }
            }

            //write the arrival
            TransportationEventEntry tee2 = new TransportationEventEntry(householdkey, person,
                                                                         timestep.AddSteps(transportationDuration),
                                                                         dstSite, dstSite,
                                                                         CurrentActivity.InAffordance, affordanceName, string.Empty,
                                                                         0, 0);

            _transportationEvents.Add(tee2);
        }
Esempio n. 10
0
        //BitArray ICalcAffordanceBase.IsBusyArray { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

        public void Activate(TimeStep startTime, string activatorName, CalcLocation personSourceLocation,
                             out ICalcProfile personTimeProfile)
        {
            if (_myLastTimeEntry.TimeOfLastEvalulation != startTime)
            {
                throw new LPGException("trying to activate without first checking if the affordance is busy is a bug. Please report.");
            }

            CalcTravelRoute route         = _myLastTimeEntry.PreviouslySelectedRoutes[personSourceLocation];
            int             routeduration = route.Activate(startTime, activatorName, out var usedDevices);

            if (routeduration == 0)
            {
                _calcRepo.OnlineLoggingData.AddTransportationStatus(
                    new TransportationStatus(startTime, _householdkey,
                                             "\tActivating " + Name + " at " + startTime + " with no transportation and moving from " + personSourceLocation + " to " + _sourceAffordance.ParentLocation.Name + " for affordance " + _sourceAffordance.Name));
            }
            else
            {
                _calcRepo.OnlineLoggingData.AddTransportationStatus(new TransportationStatus(
                                                                        startTime,
                                                                        _householdkey,
                                                                        "\tActivating " + Name + " at " + startTime + " with a transportation duration of " + routeduration + " for moving from " + personSourceLocation + " to " + _sourceAffordance.ParentLocation.Name));
            }

            TimeStep affordanceStartTime = startTime.AddSteps(routeduration);

            if (affordanceStartTime.InternalStep < _calcRepo.CalcParameters.InternalTimesteps)
            {
                _sourceAffordance.Activate(affordanceStartTime, activatorName, personSourceLocation,
                                           out var sourcePersonProfile);
                CalcProfile newPersonProfile = new CalcProfile(
                    "Travel Profile for Route " + route.Name + " to affordance " + _sourceAffordance.Name,
                    System.Guid.NewGuid().ToStrGuid(),
                    CalcProfile.MakeListwithValue1AndCustomDuration(routeduration), ProfileType.Absolute,
                    sourcePersonProfile.DataSource);
                newPersonProfile.AppendProfile(sourcePersonProfile);
                personTimeProfile = newPersonProfile;
                string usedDeviceNames = String.Join(", ", usedDevices.Select(x => x.Device.Name + "(" + x.DurationInSteps + ")"));
                _calcRepo.OnlineLoggingData.AddTransportationEvent(_householdkey, activatorName, startTime, personSourceLocation.CalcSite?.Name ?? "",
                                                                   Site.Name,
                                                                   route.Name, usedDeviceNames, routeduration, sourcePersonProfile.StepValues.Count,
                                                                   _sourceAffordance.Name, usedDevices);
            }
            else
            {
                //this is if the simulation ends during a transport
                CalcProfile newPersonProfile = new CalcProfile(
                    "Travel Profile for Route " + route.Name + " to affordance " + _sourceAffordance.Name,
                    System.Guid.NewGuid().ToStrGuid(),
                    CalcProfile.MakeListwithValue1AndCustomDuration(routeduration), ProfileType.Absolute,
                    _sourceAffordance.Name);
                personTimeProfile = newPersonProfile;
                string usedDeviceNames = String.Join(", ", usedDevices.Select(x => x.Device.Name + "(" + x.DurationInSteps + ")"));
                _calcRepo.OnlineLoggingData.AddTransportationEvent(_householdkey, activatorName, startTime,
                                                                   personSourceLocation.CalcSite?.Name ?? "",
                                                                   Site.Name,
                                                                   route.Name, usedDeviceNames, routeduration, newPersonProfile.StepValues.Count,
                                                                   _sourceAffordance.Name, usedDevices);
            }
        }
Esempio n. 11
0
        public void PostProcessingTestTwoActivation()
        {
            var startdate      = new DateTime(2018, 1, 1);
            var enddate        = startdate.AddMinutes(100);
            var calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate).EnableShowSettlingPeriod();
            //CalculationProfiler calculationProfiler = new CalculationProfiler();

            var rnd = new Random(1);
            var nr  = new NormalRandom(0, 1, rnd);

            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) {
                calcParameters.Enable(CalcOption.HouseSumProfilesFromDetailedDats);
                calcParameters.Enable(CalcOption.DeviceProfilesIndividualHouseholds);
                calcParameters.Enable(CalcOption.TotalsPerDevice);
                calcParameters.Enable(CalcOption.TotalsPerLoadtype);
                calcParameters.Enable(CalcOption.DeviceActivations);
                calcParameters.Enable(CalcOption.DetailedDatFiles);
                Config.IsInUnitTesting = true;
                wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcParameterLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcLoadTypeDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcObjectInformationLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new DeviceActivationEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcPersonDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new DeviceTaggingSetLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.Save(calcParameters);
                using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hh1", wd.InputDataLogger)) {
                    fft.RegisterHousehold(Constants.GeneralHouseholdKey, "general", HouseholdKeyType.General, "desc", null, null);
                    //fft.RegisterHousehold(Constants.GeneralHouseholdKey, "general", HouseholdKeyType.General,"desc");
                    //SqlResultLoggingService srls =new SqlResultLoggingService(Path.Combine(wd.WorkingDirectory, "results.sqlite"));
                    var dsc = new DateStampCreator(calcParameters);
                    using (IOnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters)) {
                        var coi = new CalcObjectInformation(CalcObjectType.ModularHousehold, "objname", wd.WorkingDirectory);
                        wd.InputDataLogger.Save(coi);
                        using (var lf = new LogFile(calcParameters, fft)) {
                            var key = new HouseholdKey("hh1");
                            fft.RegisterHousehold(key, "hh1 key", HouseholdKeyType.Household, "Description", null, null);
                            var odap      = new OnlineDeviceActivationProcessor(old, calcParameters, fft);
                            var clt       = new CalcLoadType("lt1", "W", "kWh", 3, true, Guid.NewGuid().ToStrGuid());
                            var loadTypes = new List <CalcLoadTypeDto> {
                                clt.ConvertToDto()
                            };
                            wd.InputDataLogger.Save(loadTypes);
                            var cdl         = new CalcDeviceLoad("devload1", 10, clt, 666, 0);
                            var deviceLoads = new List <CalcDeviceLoad> {
                                cdl
                            };
                            var cloc            = new CalcLocation("locname", Guid.NewGuid().ToStrGuid());
                            var devguid         = Guid.NewGuid().ToStrGuid();
                            var devcategoryguid = Guid.NewGuid().ToStrGuid();
                            var cdto            = new CalcDeviceDto("devicename", devcategoryguid, key, OefcDeviceType.Device, "category", "", devguid,
                                                                    cloc.Guid, cloc.Name);
                            var devices = new List <IHouseholdKey> {
                                cdto
                            };
                            wd.InputDataLogger.SaveList(devices);
                            using (var calcRepo = new CalcRepo(odap, calcParameters: calcParameters, rnd: rnd, normalRandom: nr)) {
                                var device = new CalcDevice(deviceLoads, cloc, cdto, calcRepo);
                                //var devices = new List<CalcDevice> {device};
                                var cp = new CalcProfile("profile1", Guid.NewGuid().ToStrGuid(), new TimeSpan(0, 1, 0), ProfileType.Absolute,
                                                         "custom");
                                cp.AddNewTimepoint(new TimeSpan(0), 0);
                                cp.AddNewTimepoint(new TimeSpan(0, 1, 0), 10);
                                cp.AddNewTimepoint(new TimeSpan(0, 2, 0), 0);
                                cp.ConvertToTimesteps();
                                //var locations = new List<CalcLocation> {cloc};
                                var ts = new TimeStep(0, calcParameters);
                                device.SetTimeprofile(cp, ts, clt, "affordanceName", "activatorName", 1, false);
                                device.SetTimeprofile(cp, ts.AddSteps(5), clt, "affordanceName", "activatorName", 1, false);
                                device.SetTimeprofile(cp.CompressExpandDoubleArray(0.5), ts.AddSteps(8), clt, "affordanceName", "activatorName", 1,
                                                      false);
                                device.SetTimeprofile(cp.CompressExpandDoubleArray(2), ts.AddSteps(10), clt, "affordanceName", "activatorName", 1,
                                                      false);
                            }

                            for (var i = 0; i < 30; i++)
                            {
                                var ts1      = new TimeStep(i, calcParameters);
                                var filerows = odap.ProcessOneTimestep(ts1);
                                filerows.Count.Should().Be(1);
                                filerows[0].EnergyEntries.Count.Should().Be(1);
                                Logger.Info(filerows[0].EnergyEntries[0].ToString(CultureInfo.CurrentCulture));
                                foreach (var fileRow in filerows)
                                {
                                    fileRow.Save(odap.BinaryOutStreams[fileRow.LoadType]);
                                }
                            }

                            //var autoDevs = new List<CalcAutoDev>();
                            //var ps = new Postprocessor(lf.FileFactoryAndTracker, calculationProfiler,calcParameters);
                            //var householdKeys = new HashSet<string> {"1"};
                            //var calcAffordanceTaggingSets = new List<CalcAffordanceTaggingSet>();
                            var deviceTaggingSetInformation = new DeviceTaggingSetInformation("name");
                            var taggingsets = new List <DeviceTaggingSetInformation> {
                                deviceTaggingSetInformation
                            };

                            wd.InputDataLogger.Save(taggingsets);
                            //var householdPlans = new List<CalcHouseholdPlan>();
                            //var householdNamesByNumber = new Dictionary<string, string> {["HH1"] = "household"};
                            //var affordanceEnergyUseFile = new AffordanceEnergyUseFile(lf.FileFactoryAndTracker,calcParameters);
                            //lf.Close(null); // needed to free file access
                            //var results = new Dictionary<string, double>();
                            var persons = new List <CalcPersonDto>();
                            var dto     = new CalcPersonDto("name", Guid.NewGuid().ToStrGuid(), 18, PermittedGender.Female, key, new List <DateSpan>(),
                                                            new List <DateSpan>(), 1, "tag", "hhname");
                            persons.Add(dto);
                            wd.InputDataLogger.SaveList(persons.ConvertAll(x => (IHouseholdKey)x));
                            //var deviceNamesToCategory = new Dictionary<string, string>();
                            old.FinalSaveToDatabase();
                            lf.Dispose();
                            fft.Dispose();
                            var cprof = new CalculationProfiler();
                            var ppm   = new PostProcessingManager(cprof, fft);
                            ppm.Run(wd.WorkingDirectory);
                            var tel     = new TotalsPerLoadtypeEntryLogger(wd.SqlResultLoggingService);
                            var results = tel.Read(key);
                            results[0].Value.Should().Be(150);
                        }
                    }
                }

                Logger.Info(wd.WorkingDirectory);
                wd.CleanUp();
            }
        }
        public void NextStepTest()
        {
            using var wd = new WorkingDir(Utili.GetCurrentMethodAndClass());
            DateTime       startdate      = new DateTime(2018, 1, 1);
            DateTime       enddate        = startdate.AddMinutes(100);
            CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate);

            calcParameters.AffordanceRepetitionCount = 0;
            //var r = new Random(1);
            //var nr = new NormalRandom(0, 1, r);
            var desire1 = new CalcDesire("desire1", 1, 0.5m, 4, 1, 1, 60, -1, null, "", "");

            var lt = new CalcLoadType("calcLoadtype1", "kwh", "W", 1, true, Guid.NewGuid().ToStrGuid());

            wd.InputDataLogger.AddSaver(new ActionEntryLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new LocationEntryLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
            using var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "blub", wd.InputDataLogger);
            fft.RegisterHousehold(Constants.GeneralHouseholdKey, "general", HouseholdKeyType.General, "Desc", null, null);
            //SqlResultLoggingService srls = new SqlResultLoggingService(wd.WorkingDirectory);
            DateStampCreator dsc = new DateStampCreator(calcParameters);

            using OnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters);
            using (var lf = new LogFile(calcParameters, fft)) {
                var cloc  = new CalcLocation("loc1", Guid.NewGuid().ToStrGuid());
                var clocs = new List <CalcLocation>
                {
                    cloc
                };
                BitArray      isSick       = new BitArray(calcParameters.InternalTimesteps);
                BitArray      isOnVacation = new BitArray(calcParameters.InternalTimesteps);
                CalcPersonDto calcPerson   = CalcPersonDto.MakeExamplePerson();
                var           odap         = new OnlineDeviceActivationProcessor(old, calcParameters, fft);
                Random        rnd          = new Random();
                NormalRandom  nr           = new NormalRandom(0, 1, rnd);
                using CalcRepo calcRepo = new CalcRepo(lf: lf, odap: odap, calcParameters: calcParameters, rnd: rnd, normalRandom: nr, onlineLoggingData: old);
                var cp = new CalcPerson(calcPerson, cloc, isSick, isOnVacation, calcRepo);
                //20, PermittedGender.Male, lf, "HH1", cloc, "traittag","hhname0", calcParameters,isSick, Guid.NewGuid().ToStrGuid());
                cp.PersonDesires.AddDesires(desire1);
                cp.SicknessDesires.AddDesires(desire1);
                var deviceLoads = new List <CalcDeviceLoad>
                {
                    new CalcDeviceLoad("devload1", 1, lt, 100, 1)
                };
                var           deviceCategoryGuid = Guid.NewGuid().ToStrGuid();
                CalcDeviceDto cdd1 = new CalcDeviceDto("cdevice1", deviceCategoryGuid, new HouseholdKey("HH1"),
                                                       OefcDeviceType.Device, "category", "", Guid.NewGuid().ToStrGuid(),
                                                       cloc.Guid, cloc.Name);

                var cdev1 = new CalcDevice(deviceLoads, cloc, cdd1, calcRepo);

                CalcDeviceDto cdd2 = new CalcDeviceDto("cdevice2", deviceCategoryGuid, new HouseholdKey("HH1"),
                                                       OefcDeviceType.Device, "category", "", Guid.NewGuid().ToStrGuid(),
                                                       cloc.Guid, cloc.Name);
                var cdev2 = new CalcDevice(deviceLoads, cloc, cdd2, calcRepo);
                cloc.Devices.Add(cdev1);
                cloc.Devices.Add(cdev2);
                var daylight = new BitArray(calcParameters.InternalTimesteps);
                daylight.SetAll(true);
                DayLightStatus dls       = new DayLightStatus(daylight);
                double[]       newValues = { 1, 1, 1.0 };
                var            valueList = new List <double>(newValues);
                var            cprof     = new CalcProfile("cp1", Guid.NewGuid().ToStrGuid(), valueList, ProfileType.Relative, "bla");
                var            desires   = new List <CalcDesire>
                {
                    desire1
                };
                var color = new ColorRGB(255, 0, 0);
                CalcVariableRepository crv = new CalcVariableRepository();
                BitArray isBusy1           = new BitArray(calcParameters.InternalTimesteps, false);
                var      aff1 = new CalcAffordance("aff1", cprof, cloc,
                                                   false, desires, 1, 100,
                                                   PermittedGender.All, false, 0, color,
                                                   "aff category", true, false,
                                                   new List <CalcAffordanceVariableOp>(), new List <VariableRequirement>(),
                                                   ActionAfterInterruption.GoBackToOld, "blub", 100, false, "",
                                                   Guid.NewGuid().ToStrGuid(), crv, new List <CalcAffordance.DeviceEnergyProfileTuple>(),
                                                   isBusy1, BodilyActivityLevel.Low, calcRepo);
                aff1.AddDeviceTuple(cdev1, cprof, lt, 0, calcParameters.InternalStepsize, 1, 1);
                cloc.AddAffordance(aff1);
                BitArray isBusy2 = new BitArray(calcParameters.InternalTimesteps, false);
                var      aff2    = new CalcAffordance("aff2", cprof, cloc, false, desires, 1, 100,
                                                      PermittedGender.All, false, 0,
                                                      color, "aff category", false, false,
                                                      new List <CalcAffordanceVariableOp>(), new List <VariableRequirement>(),
                                                      ActionAfterInterruption.GoBackToOld, "bla", 100, false, "",
                                                      Guid.NewGuid().ToStrGuid(), crv, new List <CalcAffordance.DeviceEnergyProfileTuple>(),
                                                      isBusy2, BodilyActivityLevel.Low, calcRepo);
                aff2.AddDeviceTuple(cdev2, cprof, lt, 0, calcParameters.InternalStepsize, 1, 1);
                cloc.AddAffordance(aff2);
                var persons = new List <CalcPerson>
                {
                    cp
                };
                //var variableOperator = new VariableOperator();
                TimeStep ts = new TimeStep(0, 0, true);
                for (var i = 0; i < 100; i++)
                {
                    cp.NextStep(ts, clocs, dls, new HouseholdKey("hh1"), persons, 1);
                    ts = ts.AddSteps(1);
                }
            }
            //wd.CleanUp();
        }
Esempio n. 13
0
        public override bool IsBusy(TimeStep time,
                                    CalcLocation srcLocation,
                                    string calcPersonName,
                                    bool clearDictionaries = true)
        {
            if (!_timeFactorsForTimes.ContainsKey(time.InternalStep))
            {
                if (clearDictionaries)
                {
                    //        _timeFactorsForTimes.Clear();
                }

                _timeFactorsForTimes[time.InternalStep] = CalcRepo.NormalRandom.NextDouble(1, _timeStandardDeviation);
                if (_timeFactorsForTimes[time.InternalStep] < 0)
                {
                    throw new DataIntegrityException("The duration standard deviation on " + Name + " is too large: a negative value of " +
                                                     _timeFactorsForTimes[time.InternalStep] + " came up. The standard deviation is " +
                                                     _timeStandardDeviation);
                }
            }

            if (!_probabilitiesForTimes.ContainsKey(time.InternalStep))
            {
                if (clearDictionaries)
                {
                    //      _probabilitiesForTimes.Clear();
                }

                _probabilitiesForTimes[time.InternalStep] = CalcRepo.Rnd.NextDouble();
            }

            if (_variableRequirements.Count > 0)
            {
                foreach (var requirement in _variableRequirements)
                {
                    if (!requirement.IsMet())
                    {
                        return(true); // return is busy right now and not available.
                    }
                }
            }

            if (time.InternalStep >= IsBusyArray.Length)
            {
                return(false);
            }

            if (IsBusyArray[time.InternalStep])
            {
                return(true);
            }

            foreach (var dpt in Energyprofiles)
            {
                if (dpt.Probability > _probabilitiesForTimes[time.InternalStep])
                {
                    if (dpt.CalcDevice.IsBusyDuringTimespan(time.AddSteps(dpt.TimeOffsetInSteps),
                                                            dpt.TimeProfile.StepValues.Count,
                                                            _timeFactorsForTimes[time.InternalStep],
                                                            dpt.LoadType))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Esempio n. 14
0
        public override void Activate(TimeStep startTime,
                                      string activatorName,
                                      CalcLocation personSourceLocation,
                                      out ICalcProfile personTimeProfile)
        {
            TimeStep timeLastDeviceEnds = startTime.GetAbsoluteStep(0);

            foreach (var dpt in Energyprofiles)
            {
                if (dpt.Probability > _probabilitiesForTimes[startTime.InternalStep])
                {
                    //_calcDevice.SetTimeprofile(tbp, startidx + TimeOffsetInSteps, loadType, timeFactor, affordancename,activatorName, _multiplier);
                    CalcProfile adjustedProfile = dpt.TimeProfile.CompressExpandDoubleArray(_timeFactorsForTimes[startTime.InternalStep]);
                    var         endtime         = dpt.CalcDevice.SetTimeprofile(adjustedProfile,
                                                                                startTime.AddSteps(dpt.TimeOffsetInSteps),
                                                                                dpt.LoadType,
                                                                                Name,
                                                                                activatorName,
                                                                                dpt.Multiplier,
                                                                                false);
                    if (endtime > timeLastDeviceEnds)
                    {
                        timeLastDeviceEnds = endtime;
                    }
                }
            }

            var personsteps = CalcProfile.GetNewLengthAfterCompressExpand(_personProfile.StepValues.Count,
                                                                          _timeFactorsForTimes[startTime.InternalStep]);

            _startTimeStep = startTime;
            _endTimeStep   = startTime.AddSteps(personsteps);
            if (DoubleCheckBusyArray)
            {
                for (var i = 0; i < personsteps && i + startTime.InternalStep < CalcRepo.CalcParameters.InternalTimesteps; i++)
                {
                    if (IsBusyArray[i + startTime.InternalStep])
                    {
                        throw new LPGException("Affordance was already busy");
                    }
                }
            }

            for (var i = 0; i < personsteps && i + startTime.InternalStep < CalcRepo.CalcParameters.InternalTimesteps; i++)
            {
                IsBusyArray[i + startTime.InternalStep] = true;
            }

            if (_variableOps.Count > 0)
            {
                foreach (var op in _variableOps)
                {
                    // figure out end time
                    TimeStep time;
                    switch (op.ExecutionTime)
                    {
                    case VariableExecutionTime.Beginning:
                        time = startTime;
                        break;

                    case VariableExecutionTime.EndOfPerson:
                        time = _endTimeStep;
                        break;

                    case VariableExecutionTime.EndofDevices:
                        time = timeLastDeviceEnds;
                        break;

                    default:
                        throw new LPGException("Forgotten Variable Execution Time");
                    }

                    _variableRepository.AddExecutionEntry(op.Name, op.Value, op.CalcLocation,
                                                          op.VariableAction, time, op.VariableGuid);
                    _variableRepository.Execute(startTime);
                }
            }

            double tf = _timeFactorsForTimes[startTime.InternalStep];

            _probabilitiesForTimes.Clear();
            _timeFactorsForTimes.Clear();
            personTimeProfile = _personProfile.CompressExpandDoubleArray(tf);
            //return tf ;
        }
Esempio n. 15
0
        public void AddZeroEntryForAutoDev(OefcKey zeKey, TimeStep starttime, int totalDuration)
        {
            var stze = new SetToZeroEntry(starttime, starttime.AddSteps(totalDuration), zeKey);

            _zeroEntries.Add(stze);
        }
Esempio n. 16
0
        public void Activate([NotNull] TimeStep startTimeStep, int durationInTimesteps, [NotNull] CalcSite srcSite,
                             [NotNull] CalcSite dstSite,
                             [NotNull] string travelRouteName,
                             [NotNull] string personName, [NotNull] TimeStep transportationEventStartTimeStep,
                             [NotNull] TimeStep transportationEventEndTimeStep)
        {
            if (startTimeStep < transportationEventStartTimeStep || transportationEventEndTimeStep < startTimeStep)
            {
                throw new LPGException("Bug in the transportation module. Start time earlier than possible.");
            }

            if (durationInTimesteps == 0)
            {
                throw new LPGException("Can't activate with a duration of 0 timesteps");
            }

            _lastUsingPerson = personName;
            if (startTimeStep < _activationStopTimestep && Category.IsLimitedToSingleLocation)
            {
                throw new LPGException(
                          "Double activation of a transportation device. This seems to be a bug. Please fix.");
            }

            if (_currentSite != srcSite && _currentSite != null)
            {
                throw new LPGException("Trying to activate a device that is not at the source location");
            }

            _activationStartTimestep = startTimeStep;
            _activationStopTimestep  = startTimeStep.AddSteps(durationInTimesteps);
            if (Category.IsLimitedToSingleLocation)
            {
                _targetSiteByTimeStep.Add(startTimeStep.InternalStep, null);
                _targetSiteByTimeStep.Add(_activationStopTimestep.InternalStep, dstSite);
            }

            //_currentSite = dstSite;
            for (int i = transportationEventStartTimeStep.InternalStep;
                 i < transportationEventEndTimeStep.InternalStep && i < _isBusyArray.Length;
                 i++)
            {
                _isBusyArray[i] = true;
            }

            foreach (CalcDeviceLoad load in _loads)
            {
                var transportationDeviceProfile = new List <double>(durationInTimesteps);
                for (var i = 0; i < durationInTimesteps; i++)
                {
                    transportationDeviceProfile.Add(load.Value);
                }

                var cp = new CalcProfile(srcSite.Name + " - " + dstSite.Name + " - " + Name,
                                         System.Guid.NewGuid().ToStrGuid(),
                                         transportationDeviceProfile,
                                         ProfileType.Relative,
                                         "Synthetic for " + Name);
                SetTimeprofile(cp, startTimeStep, load.LoadType, "Transport via " + Name,
                               personName + " - " + travelRouteName, _calcDeviceDto.LocationGuid);
            }
        }
        public void RunDeviceOffsetTest()
        {
            //var r = new Random(0);
            //var nr = new NormalRandom(0, 0.1, r);
            const int stepcount       = 150;
            var       devCategoryGuid = Guid.NewGuid().ToStrGuid();

            Config.IsInUnitTesting = true;
            DateTime       startdate      = new DateTime(2018, 1, 1);
            DateTime       enddate        = startdate.AddMinutes(stepcount);
            CalcParameters calcParameters =
                CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate);
            var timeStep = new TimeSpan(0, 1, 0);
            var cp       = new CalcProfile("profile", Guid.NewGuid().ToStrGuid(), timeStep, ProfileType.Absolute, "blub");

            cp.AddNewTimepoint(new TimeSpan(0), 100);
            cp.AddNewTimepoint(new TimeSpan(0, 10, 0), 0);
            cp.ConvertToTimesteps();
            var loc = new CalcLocation(Utili.GetCurrentMethodAndClass(), Guid.NewGuid().ToStrGuid());
            CalcVariableRepository crv = new CalcVariableRepository();
            BitArray     isBusy        = new BitArray(calcParameters.InternalTimesteps, false);
            Random       rnd           = new Random();
            NormalRandom nr            = new NormalRandom(0, 1, rnd);

            using CalcRepo calcRepo = new CalcRepo(calcParameters: calcParameters, odap: new Mock <IOnlineDeviceActivationProcessor>().Object,
                                                   rnd: rnd, normalRandom: nr);
            var aff = new CalcAffordance("bla", cp, loc, false, new List <CalcDesire>(), 0, 99, PermittedGender.All,
                                         false, 0, new ColorRGB(0, 0, 0), "bla", false, false, new List <CalcAffordanceVariableOp>(),
                                         new List <VariableRequirement>(), ActionAfterInterruption.GoBackToOld, "bla", 100, false, "",
                                         Guid.NewGuid().ToStrGuid(), crv,
                                         new List <CalcAffordance.DeviceEnergyProfileTuple>(), isBusy, BodilyActivityLevel.Low, calcRepo);
            var lt  = new CalcLoadType("load", "unit1", "unit2", 1, true, Guid.NewGuid().ToStrGuid());
            var cdl = new CalcDeviceLoad("cdl", 1, lt, 1, 0.1);
            //var variableOperator = new VariableOperator();
            var devloads = new List <CalcDeviceLoad> {
                cdl
            };
            HouseholdKey  key = new HouseholdKey("HH1");
            CalcDeviceDto cdd = new CalcDeviceDto("device",
                                                  devCategoryGuid,
                                                  key,
                                                  OefcDeviceType.Device,
                                                  "category",
                                                  string.Empty,
                                                  Guid.NewGuid().ToStrGuid(),
                                                  loc.Guid,
                                                  loc.Name);
            var cd = new CalcDevice(devloads, loc, cdd, calcRepo);

            aff.AddDeviceTuple(cd, cp, lt, 20, timeStep, 10, 1);

            //bool result = aff.IsBusy(0, nr, r, loc);
            //(result).Should().BeFalse();
            CheckForBusyness(loc, aff, cd, lt);
            TimeStep ts = new TimeStep(0, 0, false);

            aff.Activate(ts.AddSteps(10), "blub", loc, out var _);
            CheckForBusyness(loc, aff, cd, lt);
            aff.IsBusy(ts.AddSteps(1), loc, "name", false).Should().BeTrue();
            aff.IsBusy(ts.AddSteps(19), loc, "name", false).Should().BeTrue();
            aff.IsBusy(ts, loc, "name", false).Should().BeFalse();
            aff.IsBusy(ts.AddSteps(20), loc, "name", false).Should().BeFalse();
        }