/*
         * public static List<BusyEntry> MakeBusyEntries(BitArray isBusy)
         * {
         *  var busy = false;
         *  var start = 0;
         *  var entries = new List<BusyEntry>();
         *  for (var i = 0; i < isBusy.Length; i++) {
         *      if (isBusy[i] && !busy) {
         *          start = i;
         *          busy = true;
         *      }
         *      if (busy && !isBusy[i]) {
         *          busy = false;
         *          var be = new BusyEntry(start, i - 1);
         *          entries.Add(be);
         *      }
         *  }
         *  if (busy) {
         *      var be = new BusyEntry(start, isBusy.Length);
         *      entries.Add(be);
         *  }
         *  return entries;
         * }*/

        public void SetAllLoadTypesToTimeprofile([NotNull] CalcProfile tbp, [NotNull] TimeStep startidx,
                                                 [NotNull] string affordanceName, [NotNull] string activatorName, double multiplier)
        {
            foreach (var calcDeviceLoad in _deviceLoadsBy.Values)
            {
                SetTimeprofile(tbp, startidx, calcDeviceLoad.LoadType, affordanceName, activatorName,
                               multiplier, false);
            }
        }
        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));
        }
Example #3
0
        public void AddDeviceTuple([NotNull] CalcDevice dev,
                                   [NotNull] CalcProfile newprof,
                                   [NotNull] CalcLoadType lt,
                                   decimal timeoffset,
                                   TimeSpan internalstepsize,
                                   double multiplier,
                                   double probability)
        {
            //TODO: remove this, it is only used in unit testing
            var calctup = new DeviceEnergyProfileTuple(dev, newprof, lt, timeoffset, internalstepsize, multiplier, probability);

            Energyprofiles.Add(calctup);
        }
        public bool IsBusyDuringTimespan([NotNull] TimeStep startidx, int duration, double timefactor, [NotNull] CalcLoadType lt)
        {
            var dstduration = CalcProfile.GetNewLengthAfterCompressExpand(duration, timefactor);
            var lastbit     = startidx.InternalStep + dstduration;

            for (var i = startidx.InternalStep; i < lastbit && i < _isBusyForLoadType[lt].Length; i++)
            {
                if (_isBusyForLoadType[lt][i])
                {
                    return(true);
                }
            }
            return(false);
        }
Example #5
0
        private static TimeSpan FindShortestTimeSpan([NotNull] CalcProfile cp)
        {
            var shortest = TimeSpan.MaxValue;

            if (cp._datapoints == null)
            {
                throw new LPGException("Datapoints was null");
            }
            for (var i = 0; i < cp._datapoints.Count - 1; i++)
            {
                if (shortest > cp._datapoints[i + 1].Time - cp._datapoints[i].Time)
                {
                    shortest = cp._datapoints[i + 1].Time - cp._datapoints[i].Time;
                }
            }
            return(shortest);
        }
Example #6
0
            public DeviceEnergyProfileTuple([NotNull] CalcDevice pdev,
                                            [NotNull] CalcProfile ep,
                                            [NotNull] CalcLoadType pLoadType,
                                            decimal timeOffset,
                                            TimeSpan stepsize,
                                            double multiplier,
                                            double probability)
            {
                _calcDevice = pdev;
                TimeProfile = ep;
                LoadType    = pLoadType;
                TimeOffset  = timeOffset;
                _multiplier = multiplier;
                var minutesperstep = (decimal)stepsize.TotalMinutes;

                TimeOffsetInSteps = (int)(timeOffset / minutesperstep);
                Probability       = probability;
            }
 public CalcAutoDev([NotNull] CalcProfile pCalcProfile, [NotNull] CalcLoadType loadType,
                    [NotNull][ItemNotNull] List <CalcDeviceLoad> loads, double timeStandardDeviation,
                    double multiplier,
                    [NotNull] CalcLocation calclocation,
                    [NotNull][ItemNotNull] List <VariableRequirement> requirements, [NotNull] CalcDeviceDto autoDevDto, [NotNull] CalcRepo calcRepo)
     : base(
         loads, calclocation, autoDevDto, calcRepo)
 {
     _earliestNextStart     = new TimeStep(-1, 0, true);
     _calcProfile           = pCalcProfile;
     LoadType               = loadType;
     _timeStandardDeviation = timeStandardDeviation;
     _multiplier            = multiplier;
     _calcLocation          = calclocation;
     if (requirements.Count > 0) // initialize the whole variable thing
     {
         _requirements.AddRange(requirements);
     }
 }
Example #8
0
        public CalcProfile CompressExpandDoubleArray(double timeFactor)
        {
            timeFactor = Math.Round(timeFactor, 2);
            if (ChangedProfiles.ContainsKey(timeFactor))
            {
                return(ChangedProfiles[timeFactor]);
            }

            var newlength            = GetNewLengthAfterCompressExpand(StepValues.Count, timeFactor);
            var stepvaluesCompressed = new double[newlength];

            if (timeFactor < 1)
            {
                for (var timeidx = 0; timeidx < StepValues.Count; timeidx++)
                {
                    stepvaluesCompressed[(int)(timeidx * timeFactor)] = StepValues[timeidx];
                }
                if (Math.Abs(stepvaluesCompressed[newlength - 1]) < Constants.Ebsilon)
                {
                    stepvaluesCompressed[newlength - 1] = StepValues[StepValues.Count - 1];
                }
                CalcProfile newcp = new CalcProfile(Name, System.Guid.NewGuid().ToStrGuid(), stepvaluesCompressed.ToList(), ProfileType, DataSource);
                ChangedProfiles.Add(timeFactor, newcp);
                return(newcp);
            }
            var lastidx = 0;

            for (var timeidx = 0; timeidx < StepValues.Count; timeidx++)
            {
                var nextidx = (int)((timeidx + 1) * timeFactor);
                for (var i = lastidx; i <= nextidx && i < stepvaluesCompressed.Length; i++)
                {
                    stepvaluesCompressed[i] = StepValues[timeidx];
                }
                lastidx = nextidx;
            }
            CalcProfile cp = new CalcProfile(Name, System.Guid.NewGuid().ToStrGuid(), stepvaluesCompressed.ToList(), ProfileType, DataSource);

            ChangedProfiles.Add(timeFactor, cp);
            return(cp);
        }
        public void Activate([NotNull] TimeStep time)
        {
            if (time < _earliestNextStart)
            {
                return;
            }
            var shouldExecute = AreVariableRequirementsMet();

            //double check because first check needs to be if a variable is even set.
            if (shouldExecute)
            {
                var timefactor = CalcRepo.NormalRandom.NextDouble(1, _timeStandardDeviation);
                while (timefactor < 0 || timefactor > 5)
                {
                    timefactor = CalcRepo.NormalRandom.NextDouble(1, _timeStandardDeviation);
                }

                CalcProfile adjustedProfile = _calcProfile.CompressExpandDoubleArray(timefactor);
                _earliestNextStart = SetTimeprofile(adjustedProfile, time, LoadType,
                                                    "(autonomous)", "(autonomous)", _multiplier, true);
            }
        }
Example #10
0
        private static void ConvertToTimesteps([NotNull] CalcProfile cp)
        {
            if (cp._datapoints == null)
            {
                throw new LPGException("Datapoints was null");
            }
            if (cp.TimeSpanDataPoints.Count < 2)
            {
                throw new DataIntegrityException("Less than two datapoints for " + cp.Name);
            }
            var totaltime = cp._datapoints[cp._datapoints.Count - 1].Time;

            if (totaltime.TotalSeconds < cp._stepSize.TotalSeconds)
            {
                throw new DataIntegrityException("Internal time resolution is " + cp._stepSize.TotalSeconds +
                                                 " seconds while the shortest profile + " + cp.Name +
                                                 " only has a duration of " + totaltime.TotalSeconds +
                                                 " seconds. The time resolution must be at least as long as the shortest profile. Please fix.");
            }
            var stepsAsDouble = totaltime.TotalSeconds / cp._stepSize.TotalSeconds;
            var discreetSteps = (int)Math.Ceiling(stepsAsDouble);

            for (var i = 0; i < discreetSteps; i++)
            {
                cp.StepValues.Add(0);
            }
            double divfactor = 100;

            // divide by 100 for relative profile to convert to %, but don't change for absolute profiles
            if (cp._profileType == ProfileType.Absolute)
            {
                divfactor = 1;
            }
            // array mit den sekunden f�r jeden zeitschritt f�llen

            var timeRatio = FindShortestTimeSpan(cp).TotalSeconds / cp._stepSize.TotalSeconds;

            if (timeRatio >= 1) // for example shortest = 10 min, stepsize 1 min
            {
                var timeStepArray = new double[discreetSteps];
                timeStepArray[0] = 0;
                for (var idx = 1; idx < discreetSteps; idx++)
                {
                    timeStepArray[idx] = timeStepArray[idx - 1] + cp._stepSize.TotalSeconds;
                }
                // richtige werte einsetzen

                cp.StepValues[0] = cp._datapoints[0].Value / divfactor;
                var datapointidx = 1;
                for (var idx = 1; idx < discreetSteps; idx++)
                {
                    if (cp._datapoints[datapointidx].Time.TotalSeconds > timeStepArray[idx])
                    {
                        cp.StepValues[idx] = cp.StepValues[idx - 1];
                    }
                    else
                    {
                        cp.StepValues[idx] = cp._datapoints[datapointidx].Value / divfactor;
                        datapointidx++;
                    }
                }
            }
            else
            {
                var timeStepArray = new double[discreetSteps + 1];
                timeStepArray[0] = 0;
                for (var idx = 1; idx < discreetSteps + 1; idx++)
                {
                    timeStepArray[idx] = timeStepArray[idx - 1] + cp._stepSize.TotalSeconds;
                }

                var dstTimeStep = 1;

                var newList = new List <CalcTimeDataPoint>
                {
                    cp._datapoints[0]
                };
                var srcTimeStep = 1;
                while (srcTimeStep < cp._datapoints.Count)
                // first build a  list that is guaranteed to contain a value for every dst Timestep
                {
                    while (timeStepArray[dstTimeStep] < cp._datapoints[srcTimeStep].Time.TotalSeconds)
                    // solange wir noch nicht den n�chsten punkt erreicht haben, weitere st�tzpunkte einf�gen
                    {
                        var ts = TimeSpan.FromSeconds(timeStepArray[dstTimeStep]);
                        newList.Add(new CalcTimeDataPoint(ts, cp._datapoints[srcTimeStep - 1].Value));
                        dstTimeStep++;
                    }
                    if (Math.Abs(timeStepArray[dstTimeStep] - cp._datapoints[srcTimeStep].Time.TotalSeconds) <
                        Constants.Ebsilon)
                    // skip identical entries
                    {
                        dstTimeStep++;
                    }
                    newList.Add(cp._datapoints[srcTimeStep]);
                    srcTimeStep++;
                }
                // abschlusspunkt ggf einf�gen
                if (Math.Abs(timeStepArray[timeStepArray.Length - 1] - newList[newList.Count - 1].Time.TotalSeconds) >
                    Constants.Ebsilon)
                {
                    // abschlusspunkt ben�tigt
                    var ts    = TimeSpan.FromSeconds(timeStepArray[timeStepArray.Length - 1]);
                    var value = newList[newList.Count - 1].Value;
                    newList.Add(new CalcTimeDataPoint(ts, value));
                }

                dstTimeStep = 1;
                srcTimeStep = 1;
                if (Config.IsInUnitTesting)
                {
                    foreach (var calcTimeDataPoint in newList)
                    {
                        Logger.Info(calcTimeDataPoint.ToString());
                    }
                }

                while (dstTimeStep < timeStepArray.Length)
                {
                    // collect the entries
                    double totalSeconds = 0;
                    double sum          = 0;
                    while (srcTimeStep < newList.Count &&
                           newList[srcTimeStep].Time.TotalSeconds <= timeStepArray[dstTimeStep])
                    {
                        var seconds = newList[srcTimeStep].Time.TotalSeconds -
                                      newList[srcTimeStep - 1].Time.TotalSeconds;
                        sum          += newList[srcTimeStep - 1].Value * seconds;
                        totalSeconds += seconds;
                        srcTimeStep++;
                    }
                    cp.StepValues[dstTimeStep - 1] = sum / totalSeconds;
                    dstTimeStep++;
                }
                if (Config.IsInUnitTesting)
                {
                    for (var i = 0; i < cp.StepValues.Count; i++)
                    {
                        Logger.Info(timeStepArray[i] + " " + cp.StepValues[i]);
                    }
                }
            }
        }
Example #11
0
        public CalcAffordance([NotNull] string pName,
                              [NotNull] CalcProfile personProfile,
                              [NotNull] CalcLocation loc,
                              bool randomEffect,
                              [NotNull][ItemNotNull] List <CalcDesire> satisfactionvalues,
                              int miniumAge,
                              int maximumAge,
                              PermittedGender permittedGender,
                              bool needsLight,
                              double timeStandardDeviation,
                              ColorRGB affordanceColor,
                              [NotNull] string pAffCategory,
                              bool isInterruptable,
                              bool isInterrupting,
                              [NotNull][ItemNotNull] List <CalcAffordanceVariableOp> variableOps,
                              [NotNull][ItemNotNull] List <VariableRequirement> variableRequirements,
                              ActionAfterInterruption actionAfterInterruption,
                              [NotNull] string timeLimitName,
                              int weight,
                              bool requireAllDesires,
                              [NotNull] string srcTrait,
                              StrGuid guid,
                              [NotNull] CalcVariableRepository variableRepository,
                              [NotNull][ItemNotNull] List <DeviceEnergyProfileTuple> energyprofiles,
                              [ItemNotNull][NotNull] BitArray isBusy, BodilyActivityLevel bodilyActivityLevel,
                              [NotNull] CalcRepo calcRepo) : base(pName,
                                                                  loc,
                                                                  satisfactionvalues,
                                                                  miniumAge,
                                                                  maximumAge,
                                                                  permittedGender,
                                                                  needsLight,
                                                                  randomEffect,
                                                                  pAffCategory,
                                                                  isInterruptable,
                                                                  isInterrupting,
                                                                  actionAfterInterruption,
                                                                  weight,
                                                                  requireAllDesires,
                                                                  CalcAffordanceType.Affordance,
                                                                  guid,
                                                                  isBusy, bodilyActivityLevel, calcRepo)
        {
            _variableOps          = variableOps;
            _variableRequirements = variableRequirements;
            _variableRepository   = variableRepository;
            Energyprofiles        = energyprofiles;
            SourceTrait           = srcTrait;
            if (personProfile == null)
            {
#pragma warning disable IDE0016 // Use 'throw' expression
                throw new DataIntegrityException("The affordance " + Name + " has no person profile!");
#pragma warning restore IDE0016 // Use 'throw' expression
            }

            _timeStandardDeviation = timeStandardDeviation;
            SubAffordances         = new List <CalcSubAffordance>();
            _personProfile         = personProfile;
            AffordanceColor        = affordanceColor;
            TimeLimitName          = timeLimitName;
        }
Example #12
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 ;
        }