Exemple #1
0
 public CalcRepo(
     [CanBeNull] IOnlineDeviceActivationProcessor odap = null,
     [CanBeNull] Random rnd = null,
     [CanBeNull] CalcParameters calcParameters        = null,
     [CanBeNull] IOnlineLoggingData onlineLoggingData = null,
     [CanBeNull] NormalRandom normalRandom            = null,
     [CanBeNull] ILogFile lf = null,
     [CanBeNull] SqlResultLoggingService srls            = null,
     [CanBeNull] IInputDataLogger inputDataLogger        = null,
     [CanBeNull] CalculationProfiler calculationProfiler = null,
     [CanBeNull] FileFactoryAndTracker fft = null,
     [CanBeNull] DateStampCreator dsc      = null)
 {
     _dateStampCreator = dsc;
     _fft               = fft;
     _odap              = odap;
     _rnd               = rnd;
     _calcParameters    = calcParameters;
     _onlineLoggingData = onlineLoggingData;
     _normalRandom      = normalRandom;
     _lf                  = lf;
     _srls                = srls;
     _inputDataLogger     = inputDataLogger;
     _calculationProfiler = calculationProfiler;
 }
 // G - переменная от 0 до 10,по сути величина, выпадающая чаще всего
 public CEquipmentGenerator(int id, CCultivator.CStats min, CCultivator.CStats max, double G)
 {
     Id       = id;
     MinStats = min;
     MaxStats = max;
     Gaus     = new NormalRandom(2.2, G);
 }
Exemple #3
0
        public void OnlineDeviceActivationProcessorArrayTest()
        {
            var rnd = new Random(1);
            var nr  = new NormalRandom(0, 1, rnd);

            using (var 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));
                var calcParameters = CalcParametersFactory.MakeGoodDefaults().EnableShowSettlingPeriod();
                //calcParameters.Enable(CalcOption.ActionsLogfile);
                calcParameters.Enable(CalcOption.DeviceProfilesIndividualHouseholds);
                calcParameters.Enable(CalcOption.DetailedDatFiles);
                using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hh1", wd.InputDataLogger)) {
                    //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 hhkey = new HouseholdKey("HH1");
                        fft.RegisterHousehold(Constants.GeneralHouseholdKey, "generalhousehold", HouseholdKeyType.General, "Description", null, null);
                        fft.RegisterHousehold(hhkey, "hh1", HouseholdKeyType.Household, "Description", null, null);
                        var odap         = new OnlineDeviceActivationProcessor(old, calcParameters, fft);
                        var deviceGuid   = "devguid".ToStrGuid();
                        var locationGuid = "locationGuid".ToStrGuid();
                        var loadtypeGuid = "ltguid".ToStrGuid();
                        var cdd          = new CalcDeviceDto("devicename", "devcatguid".ToStrGuid(), hhkey, OefcDeviceType.Device, "devcatname", "",
                                                             deviceGuid, locationGuid, "loc");

                        var key = new OefcKey(cdd, loadtypeGuid);
                        var clt = new CalcLoadType("lt1", "W", "kWh", 1, true, loadtypeGuid);
                        odap.RegisterDevice(clt.ConvertToDto(), cdd);
                        double[] stepValues = { 1.0, 0 };
                        var      valueList  = new List <double>(stepValues);
                        var      cp         = new CalcProfile("myCalcProfile", Guid.NewGuid().ToStrGuid(), valueList, ProfileType.Absolute, "synthetic");
                        var      ts1        = new TimeStep(1, 0, false);
                        var      cdl        = new CalcDeviceLoad("", 1, clt, 0, 0);
                        var      sv         = StepValues.MakeStepValues(cp, 10, RandomValueProfile.MakeStepValues(cp.StepValues.Count, nr, 0), cdl);
                        odap.AddNewStateMachine(ts1, clt.ConvertToDto(), "name1", "p1", key, cdd, sv);
                        double[] resultValues = { 0, 10.0, 0, 0, 0, 0, 0, 0, 0, 0 };

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

                Logger.Info(wd.WorkingDirectory);
                wd.CleanUp();
            }
        }
Exemple #4
0
        public static Universe StartGalaxySystem(int numberOfBodies)
        {
            int                  i;
            double               radiusScale = 5e15, currVelocity, currRadius, massScale = 2e30;
            Universe             result = new Universe();
            NormalRandom         rnd1   = new NormalRandom();
            List <MaterialPoint> bodies = new List <MaterialPoint>();

            for (i = 0; i < numberOfBodies; i++)
            {
                currRadius   = Math.Abs(radiusScale * (rnd1.NextDouble() / 5 + 0.6));
                currVelocity = Math.Sqrt(result.G * 0.5 * massScale * numberOfBodies / radiusScale);

                bodies.Add(new PhysicalBody(
                               coordinates: new Vector(currRadius * Math.Sin(2 * Math.PI / numberOfBodies * i), currRadius * Math.Cos(2 * Math.PI / numberOfBodies * i)),
                               mass: rnd.NextDouble() * massScale,
                               velocity: new Vector(currVelocity * Math.Cos(2 * Math.PI / numberOfBodies * i), -currVelocity * Math.Sin(2 * Math.PI / numberOfBodies * i)),
                               diameter: 5e13
                               ));
            }

            result = new Universe(bodies.ToArray())
            {
                Name           = "Galaxy System",
                CameraFOV      = 1e16,
                CollisionsType = CollisionType.InelasticCollisions,
                DeltaTime      = 3.1536e9, /* 100 * 365 * 24 * 3600 s*/
                EnableTracers  = true
            };

            return(result);
        }
Exemple #5
0
 public CalcPersonDtoFactory([NotNull] CalcParameters calcParameters, [NotNull] Random random, [NotNull] NormalRandom normalRandom, [NotNull] VacationDtoFactory vacationDtoFactory)
 {
     _calcParameters     = calcParameters;
     _random             = random;
     _normalRandom       = normalRandom;
     _vacationDtoFactory = vacationDtoFactory;
 }
        public void CalcAffordanceVariableTestSet()
        {
            var deviceCategoryGuid = Guid.NewGuid().ToStrGuid();
            //var r = new Random(0);
            //var nr = new NormalRandom(0, 0.1, r);
            const int stepcount = 150;

            Config.IsInUnitTesting = true;
            DateTime startdate = new DateTime(2018, 1, 1);
            DateTime enddate   = startdate.AddMinutes(stepcount);
            //_calcParameters.InitializeTimeSteps(startdate, enddate, new TimeSpan(0, 1, 0), 3, false);
            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 variables    = new List <CalcAffordanceVariableOp>();
            var variableReqs = new List <VariableRequirement>();
            var loc          = new CalcLocation("loc", Guid.NewGuid().ToStrGuid());
            CalcVariableRepository calcVariableRepository = new CalcVariableRepository();
            var          variableGuid = Guid.NewGuid().ToStrGuid();
            HouseholdKey key          = new HouseholdKey("hh1");
            CalcVariable cv           = new CalcVariable("varname", variableGuid, 0, loc.Name, loc.Guid, key);

            calcVariableRepository.RegisterVariable(cv);
            variables.Add(new CalcAffordanceVariableOp(cv.Name, 1, loc, VariableAction.SetTo,
                                                       VariableExecutionTime.Beginning, variableGuid));
            BitArray     isBusy = new BitArray(100, false);
            Random       rnd    = new Random();
            NormalRandom nr     = new NormalRandom(0, 1, rnd);

            using CalcRepo calcRepo = new CalcRepo(calcParameters: calcParameters, odap: new Mock <IOnlineDeviceActivationProcessor>().Object, normalRandom: nr, rnd: rnd);
            var aff = new CalcAffordance("bla", cp, loc, false, new List <CalcDesire>(), 0, 99,
                                         PermittedGender.All, false, 0.1, new ColorRGB(0, 0, 0), "bla", false, false, variables, variableReqs,
                                         ActionAfterInterruption.GoBackToOld, "bla", 100, false, "", Guid.NewGuid().ToStrGuid(),
                                         calcVariableRepository,
                                         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 devloads = new List <CalcDeviceLoad> {
                cdl
            };
            CalcDeviceDto cdd = new CalcDeviceDto("device", deviceCategoryGuid, key,
                                                  OefcDeviceType.Device, "category", string.Empty,
                                                  Guid.NewGuid().ToStrGuid(), loc.Guid, loc.Name);
            var cd = new CalcDevice(devloads, loc,
                                    cdd, calcRepo);

            //loc.Variables.Add("Variable1", 0);
            aff.AddDeviceTuple(cd, cp, lt, 0, timeStep, 10, 1);
            TimeStep ts = new TimeStep(0, 0, false);

            aff.IsBusy(ts, loc, "name");
            //var variableOperator = new VariableOperator();
            aff.Activate(ts, "blub", loc, out var _);
            calcVariableRepository.GetValueByGuid(variableGuid).Should().Be(1);
        }
Exemple #7
0
 public PopulationMinOptimumEvStartegy(int dimentionsCount, int chromosomeLength,
                                       double minX, double maxX)
     : base(chromosomeLength, 0, 1)
 {
     _dimentionsCount  = dimentionsCount;
     _chromosomeLength = chromosomeLength;
     _minX             = minX;
     _maxX             = maxX;
     _nr = new NormalRandom();
 }
Exemple #8
0
        private List <double> Gauss()
        {
            List <double> randoms = new List <double>();
            NormalRandom  nr      = new NormalRandom();

            for (int i = 0; i < Convert.ToInt32(NumBox.Text); i++)
            {
                randoms.Add((nr.NextDouble() * Convert.ToDouble(additionalBox1.Text)) + Convert.ToDouble(additionalBox2.Text));
            }
            return(randoms);
        }
Exemple #9
0
        public void OnlineDeviceStateMachineTest()
        {
            var            startdate      = new DateTime(2018, 1, 1);
            var            enddate        = startdate.AddMinutes(200);
            CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults()
                                            .SetStartDate(startdate).SetEndDate(enddate).SetSettlingDays(0).EnableShowSettlingPeriod();
            var values = new double[10];

            for (var i = 0; i < values.Length; i++)
            {
                values[i] = i + 1;
                Logger.Info(values[i].ToString(CultureInfo.CurrentCulture));
            }

            var valueList     = new List <double>(values);
            var r             = new Random(1);
            var nr            = new NormalRandom(0, 1, r);
            var devGuid       = Guid.NewGuid().ToStrGuid();
            var locGuid       = Guid.NewGuid().ToStrGuid();
            var clt           = new CalcLoadType("lt", "kWh", "W", 1, true, Guid.NewGuid().ToStrGuid());
            var calcDeviceDto = new CalcDeviceDto("device", devGuid, new HouseholdKey("hh1"), OefcDeviceType.Device,
                                                  "mycategory", "", devGuid, locGuid, "locname");
            var            key  = new OefcKey(calcDeviceDto, locGuid);
            var            cp   = new CalcProfile("mycalcprofile", Guid.NewGuid().ToStrGuid(), valueList, ProfileType.Absolute, "bla");
            TimeStep       ts   = new TimeStep(5, 0, false);
            CalcDeviceLoad cdl  = new CalcDeviceLoad("", 1, clt, 0, 0);
            StepValues     sv   = StepValues.MakeStepValues(cp, 1, RandomValueProfile.MakeStepValues(cp.StepValues.Count, nr, 0), cdl);
            var            odsm = new OnlineDeviceStateMachine(ts, clt.ConvertToDto(), "device", key, "affordance",
                                                               calcParameters, sv, 0);

            calcParameters.SetDummyTimeSteps(0);
            odsm.CalculateOfficialEnergyUse().Should().Be(55); // all
            calcParameters.SetDummyTimeSteps(6);
            odsm.CalculateOfficialEnergyUse().Should().Be(54); // not the first
            //_calcParameters.InternalTimesteps = 20;
            calcParameters.SetDummyTimeSteps(15);
            odsm.CalculateOfficialEnergyUse().Should().Be(0);  // none
            calcParameters.SetDummyTimeSteps(14);
            odsm.CalculateOfficialEnergyUse().Should().Be(10); // only the last
            Logger.Info(odsm.CalculateOfficialEnergyUse().ToString(CultureInfo.CurrentCulture));
            startdate = new DateTime(2018, 1, 1);
            enddate   = startdate.AddMinutes(10);
            calcParameters.DisableShowSettlingPeriod();
            calcParameters.SetStartDate(startdate).SetEndDate(enddate)
            .SetDummyTimeSteps(5);
            odsm.CalculateOfficialEnergyUse().Should().Be(15); // only the first 5
            //_calcParameters.InternalTimesteps = 10; // only 5
            calcParameters.SetDummyTimeSteps(9);
            var val = odsm.CalculateOfficialEnergyUse();

            val.Should().Be(5); // only #5

            Logger.Info(odsm.CalculateOfficialEnergyUse().ToString(CultureInfo.CurrentCulture));
        }
Exemple #10
0
        /// <summary>
        /// Метод для генерации последовательнсоти псевдослучайных чисел с учетом номрального распредления
        /// </summary>
        /// <param name="seed">Значение ининциализатора пседвослучайных чисел</param>
        /// <param name="dataCount">Количество генерируемых данных</param>
        /// <returns>Сгенерированный массив</returns>
        public double[] GetNormalDistributionData(int seed, int dataCount)
        {
            var rnd      = new NormalRandom(seed);
            var rndArray = new double[dataCount];

            for (int i = 0; i < rndArray.Length; i++)
            {
                rndArray[i] = rnd.Next(10, 2);
            }

            return(rndArray);
        }
        public void AddMoreDesiresTest()
        {
            Config.IsInUnitTesting = true;
            CalcParameters parameters = CalcParametersFactory.MakeGoodDefaults();
            HouseholdKey   key        = new HouseholdKey("hh5");
            var            persons    = new List <ModularHouseholdPerson>();
            var            p          = new Person("blub", 1, 1, 1, 1,
                                                   PermittedGender.Male, string.Empty, string.Empty, Guid.NewGuid().ToStrGuid());
            var tt  = new TraitTag("traittag", "", TraitLimitType.NoLimit, TraitPriority.All, Guid.NewGuid().ToStrGuid());
            var mhp = new ModularHouseholdPerson(null, -1, p.PrettyName, "", p, tt, Guid.NewGuid().ToStrGuid());

            persons.Add(mhp);
            var          hhVacations = new List <VacationTimeframe>();
            Random       r           = new Random(1);
            NormalRandom nr          = new NormalRandom(0, 1, r);
            //DeviceCategoryPicker picker = new DeviceCategoryPicker(r,null);
            //var parameters = new CalcFactoryParameters(picker);
            //CalcFactoryParameters.SetSkipChecking(true);
            //var cloc = new CalcLocation("cloc", 1, Guid.NewGuid().ToStrGuid());
            //var mock = new Mock<ILogFile>();
            CalcParameters       calcParameters = CalcParametersFactory.MakeGoodDefaults();
            VacationDtoFactory   vfac           = new VacationDtoFactory(calcParameters, r);
            CalcPersonDtoFactory cpf            = new CalcPersonDtoFactory(parameters, r, nr, vfac);
            var hhtDesires =
                new List <ModularHousehold.PersonTraitDesireEntry>();
            var d         = new Desire("desire", 1, 1, 1, string.Empty, 1, false, 1, "", Guid.NewGuid().ToStrGuid());
            var hhtDesire = new HHTDesire(1, 1, 1, d, HealthStatus.Healthy, 1, 1, string.Empty, "name", 1, 100,
                                          PermittedGender.All, Guid.NewGuid().ToStrGuid());
            var hht = new HouseholdTrait("blub", null, "", "", "", 1, 1, 1, 1, 1, TimeType.Day, 1, 1, TimeType.Day, 1,
                                         1, EstimateType.FromCalculations,
                                         "", Guid.NewGuid().ToStrGuid());

            hhtDesires.Add(
                new ModularHousehold.PersonTraitDesireEntry(
                    ModularHouseholdTrait.ModularHouseholdTraitAssignType.Age, null, hhtDesire, hht));
            //var sharedDesireValues = new Dictionary<Desire, SharedDesireValue>();
            var cpersons = cpf.MakePersonDtos(persons, key, hhVacations, hhtDesires, "hhname");

            cpersons.Count.Should().Be(1);
            var cp = cpersons[0];

            //CalcPersonFactory.AddTraitDesires(hhtDesires, cpersons, 1, "name", sharedDesireValues);
            cp.Desires.Count.Should().Be(1);
            cp.Desires.Count.Should().Be(1);
            p.PrettyName.Should().Be(cp.Name);
            p.Age.Should().Be(cp.Age);
            // id 1 for the dictionary
            Assert.Equal(d.PrettyName, cp.Desires[0].Name);
        }
        /// <summary>コンストラクタ</summary>
        public LimitedNormal(Tensor tensor, Random random, float scale, float limitsigma)
            : base(tensor)
        {
            this.generator = new NormalRandom(tensor.Shape, random);

            InputNode    inputnode = tensor;
            VariableNode node      = Clip(inputnode, -limitsigma, limitsigma) * scale;

            node.Update(inputnode);

            this.flow = Flow.FromInputs(inputnode);

            this.Scale      = scale;
            this.LimitSigma = limitsigma;
        }
Exemple #13
0
        public static CalcRepo Make([NotNull] CalcParameters calcParameters, [NotNull] IInputDataLogger idl,
                                    [NotNull] string resultPath, [NotNull] string calcObjectName,
                                    CalculationProfiler calculationProfiler)
        {
            DateStampCreator      dsc = new DateStampCreator(calcParameters);
            OnlineLoggingData     old = new OnlineLoggingData(dsc, idl, calcParameters);
            FileFactoryAndTracker fft = new FileFactoryAndTracker(resultPath, calcObjectName, idl);
            LogFile lf = new LogFile(calcParameters, fft);
            OnlineDeviceActivationProcessor odap = new OnlineDeviceActivationProcessor(old, calcParameters, fft);
            Random                  rnd          = new Random(calcParameters.ActualRandomSeed);
            NormalRandom            nr           = new NormalRandom(0, 0.1, rnd);
            SqlResultLoggingService srls         = new SqlResultLoggingService(resultPath);
            CalcRepo                cr           = new CalcRepo(odap, rnd, calcParameters, old, nr, lf, srls,
                                                                idl, calculationProfiler, fft, dsc);

            return(cr);
        }
Exemple #14
0
 public void BasicTest()
 {
     using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()))
     {
         wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
         wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
         CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().EnableShowSettlingPeriod().SetSettlingDays(5);
         using (FileFactoryAndTracker fft = new FileFactoryAndTracker(wd.WorkingDirectory, "blub", wd.InputDataLogger))
         {
             fft.RegisterGeneralHouse();
             fft.RegisterHousehold(new HouseholdKey("HH1"), "test", HouseholdKeyType.Household, "desc",
                                   null, null);
             ThoughtsLogFile tlf = new ThoughtsLogFile(fft, calcParameters);
             Random          rnd = new Random();
             //NormalRandom nr = new NormalRandom(0, 0.1, rnd);
             // this array is pure nonsense and only to make it stop crashing the unit test
             //_calcParameters.InternalDateTimeForSteps = new List<DateTime>(4);
             //for (int i = 0; i < 4; i++)
             //{
             //  _calcParameters.InternalDateTimeForSteps.Add(DateTime.Now);
             //}
             CalcLocation    cloc         = new CalcLocation("cloc", Guid.NewGuid().ToStrGuid());
             BitArray        isSick       = new BitArray(calcParameters.InternalTimesteps);
             BitArray        isOnVacation = new BitArray(calcParameters.InternalTimesteps);
             CalcPersonDto   dto          = CalcPersonDto.MakeExamplePerson();
             Mock <ILogFile> lf           = new Mock <ILogFile>();
             NormalRandom    nr           = new NormalRandom(0, 0.1, rnd);
             using (CalcRepo calcRepo = new CalcRepo(rnd: rnd, lf: lf.Object, calcParameters: calcParameters, normalRandom: nr))
             {
                 CalcPerson cp = new CalcPerson(dto,
                                                cloc, isSick, isOnVacation, calcRepo);
                 //"personName", 0, 1, rnd, 1, PermittedGender.Male, null, "HH1" ,cloc,"traittag", "hhname0",calcParameters,isSick,Guid.NewGuid().ToStrGuid());
                 TimeStep     ts = new TimeStep(0, 0, false);
                 ThoughtEntry te = new ThoughtEntry(cp, ts, "blua");
                 calcParameters.SetSettlingDays(0);
                 tlf.WriteEntry(te, new HouseholdKey("HH1"));
             }
             tlf.Dispose();
         }
         wd.CleanUp();
     }
 }
Exemple #15
0
        protected void SetUp()
        {
            var st            = new StackTrace(1);
            var sf            = st.GetFrame(0);
            var declaringType = sf?.GetMethod()?.DeclaringType;

            if (declaringType == null)
            {
                throw new LPGException("type was null.");
            }

            // ReSharper disable once ConstantConditionalAccessQualifier
            var msg = declaringType.FullName + "." + sf?.GetMethod()?.Name;
            var rnd = new Random();

            NormalRandom = new NormalRandom(0, 1, rnd);
            Logger.Info("locked by " + msg);

            Monitor.Enter(MyLock.Locker);
        }
        private double GetMaxExpansionFactor(double standardeviation, Random rnd)
        {
            if (_expansionFactorsByDeviation.ContainsKey(standardeviation))
            {
                return(_expansionFactorsByDeviation[standardeviation]);
            }
            var    nr        = new NormalRandom(1, 0.1, rnd);
            double maxfactor = 1;

            for (var i = 0; i < 100; i++)
            {
                var val = nr.NextDouble(1, standardeviation);
                if (val > maxfactor)
                {
                    maxfactor = val;
                }
            }
            _expansionFactorsByDeviation.Add(standardeviation, maxfactor);
            return(maxfactor);
        }
        /// <summary>コンストラクタ</summary>
        public Normal(Tensor tensor, Random random, float scale = 1f)
            : base(tensor)
        {
            this.generator = new NormalRandom(tensor.Shape, random);

            if (scale != 1)
            {
                InputNode    inputnode = tensor;
                VariableNode node      = inputnode * scale;
                node.Update(inputnode);

                this.flow = Flow.FromInputs(inputnode);
            }
            else
            {
                this.flow = null;
            }

            this.Scale = scale;
        }
        public void CheckOrderStatistics03()
        {
            double mean   = 100;
            double stdDev = 25;

            NormalRandom rand = new NormalRandom(mean, stdDev, new Random());

            double[] values = new double[maxNumbers];
            for (int i = 0; i < maxNumbers; i++)
            {
                values[i] = rand.Next();
            }

            double average = values.Average();

            Assert.AreEqual(mean, average, tolerance * mean);
            double sumOfSquaresOfDifferences = values.Select(val => (val - average) * (val - average)).Sum();
            double sd = Math.Sqrt(sumOfSquaresOfDifferences / values.Length);

            Assert.AreEqual(stdDev, sd, tolerance);
        }
        public void SpeedTest()
        {
            int length = 65535 * 16;

            Shape shape = Shape.Vector(length);

            OverflowCheckedTensor v1 = new OverflowCheckedTensor(shape);

            NormalRandom ope = new NormalRandom(shape, new Random(1234));

            Stopwatch sw = new Stopwatch();

            sw.Start();

            ope.Execute(v1);
            ope.Execute(v1);
            ope.Execute(v1);
            ope.Execute(v1);

            sw.Stop();

            Console.WriteLine($"{sw.ElapsedMilliseconds / 4} msec");
        }
Exemple #20
0
        internal static List <Quaternion> QuaternionQuTEMSampling(Chain chain, double[] pg, int samples)
        {
            //s1=s2=s3 =>uniform Sampling
            //var r = new NormalD_Random();
            var r = new NormalRandom();

            double[][] x = r.NextNormalRandomMatrix(0, 1, samples, 3); //r.Next(0, 1, samples, 3); // normrnd(0,1,[samples,3]);%2
            for (int i = 0; i < samples; i++)                          //for i = 1:samples%3
            {
                for (int j = 0; j < 3; j++)
                {
                    x[i][j] = x[i][j] / MathUtils.euclidianNorm(x[i].ToArray()); //x(i,:)=x(i,:)/norm(x(i,:));
                }
            }

            var N = new double[x.GetLength(0)][];

            for (int i = 0; i < samples; i++)
            {
                var n = new[] { pg[1] * x[i][0], pg[2] * x[i][1], pg[3] * x[i][2] };
                N[i] = n;
            }
            double[] theta = r.NextNormalRandomMatrix(0, pg[0], samples); // r.Next(0, pg[0], samples);
            var      qs    = new List <Quaternion>();

            for (int i = 0; i < samples; i++)
            {
                var K = new double[3];
                for (int j = 0; j < 3; j++)
                {
                    K[j] = N[i][j] * theta[i]; //[N(i, :)*theta(i)]
                }
                Quaternion q = QuaternionProduct(chain.Qs[i], QuaternionExponentialMap(K));
                qs.Add(q);
            }
            return(qs);
        }
        public static RandomValueProfile MakeStepValues(int stepCount, [NotNull] NormalRandom nr, double powerStandardDeviation)
        {
            if (stepCount == 0)
            {
                throw new LPGException("stepcount was 0");
            }
            var values = new List <double>(new double[stepCount]);

            if (Math.Abs(powerStandardDeviation) > 0.00000001)
            {
                for (var i = 0; i < stepCount; i++)
                {
                    values[i] = nr.NextDouble(1, powerStandardDeviation);
                }
            }
            else
            {
                for (var i = 0; i < stepCount; i++)
                {
                    values[i] = 1;
                }
            }
            return(new RandomValueProfile(values));
        }
        public void ExecuteTest()
        {
            int length = 65535 * 63;

            Shape shape = Shape.Vector(length);

            OverflowCheckedTensor v1 = new OverflowCheckedTensor(shape);

            NormalRandom ope = new NormalRandom(shape, new Random(1234));

            ope.Execute(v1);

            float[] y = v1.State;

            {
                double sq_sum = 0, sum = 0;
                int[]  cnt = new int[4];

                foreach (float v in y)
                {
                    sq_sum += v * v;
                    sum    += v;

                    float abs_v = Math.Abs(v);

                    if (abs_v < 4)
                    {
                        cnt[(int)Math.Floor(abs_v)]++;
                    }
                }

                double mean = sum / length;

                double variance = sq_sum / length - mean * mean;

                Assert.AreEqual(0, mean, 2e-3, "mean");
                Assert.AreEqual(1, variance, 2e-3, "variance");

                Assert.AreEqual(0.682689492, (double)cnt[0] / length, 1e-3, "sigma1");
                Assert.AreEqual(0.271810244, (double)cnt[1] / length, 1e-3, "sigma2");
                Assert.AreEqual(0.042800468, (double)cnt[2] / length, 1e-3, "sigma3");
                Assert.AreEqual(0.002636456, (double)cnt[3] / length, 1e-3, "sigma4");
            }

            {
                double sq_sum = 0, sum = 0;
                int[]  cnt = new int[8];

                double xy_sum = 0;

                for (int i = 1; i < y.Length; i++)
                {
                    float v = y[i] - y[i - 1];

                    xy_sum += y[i] * y[i - 1];

                    sq_sum += v * v;
                    sum    += v;

                    float abs_v = Math.Abs(v);

                    if (abs_v < 8)
                    {
                        cnt[(int)Math.Floor(abs_v)]++;
                    }
                }

                double mean = sum / length;

                double variance = sq_sum / length - mean * mean;

                Assert.AreEqual(0, mean, 1e-2, "mean");
                Assert.AreEqual(2, variance, 1e-2, "variance");
                Assert.AreEqual(0, xy_sum / (length - 1), 1e-2, "cov");

                Assert.AreEqual(0.520499878, (double)cnt[0] / (length - 1), 2e-2, "sigma1");
                Assert.AreEqual(0.322200915, (double)cnt[1] / (length - 1), 2e-2, "sigma2");
                Assert.AreEqual(0.123404354, (double)cnt[2] / (length - 1), 2e-2, "sigma3");
                Assert.AreEqual(0.029217119, (double)cnt[3] / (length - 1), 2e-2, "sigma4");
                Assert.AreEqual(0.004270783, (double)cnt[4] / (length - 1), 2e-2, "sigma5");
                Assert.AreEqual(0.000384861, (double)cnt[5] / (length - 1), 2e-2, "sigma6");
            }
        }
Exemple #23
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 RunMakeCalcTest()
        {
            //TODO: fix the container registering
            var builder = new ContainerBuilder();

            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) {
                var path        = wd.WorkingDirectory;
                var inputlogger = wd.InputDataLogger;
                wd.InputDataLogger.AddSaver(new CalcPersonDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcAffordanceDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcVariableDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new BridgeDayEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new HouseholdDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcSiteDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcTransportationDeviceDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new CalcTravelRouteDtoLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new TransportationStatusLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new TransportationEventLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));

                using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) {
                    var sim = new Simulator(db.ConnectionString);

                    var mhh       = sim.ModularHouseholds[0];
                    var r         = new Random(1);
                    var dcp       = new DeviceCategoryPicker(r, null);
                    var ltdtoDict = CalcLoadTypeDtoFactory.MakeLoadTypes(sim.LoadTypes.It, new TimeSpan(0, 1, 0),
                                                                         LoadTypePriority.RecommendedForHouseholds);
                    var ltdict = CalcLoadTypeFactory.MakeLoadTypes(ltdtoDict);
                    //var picker = new DeviceCategoryPicker(r,null);
                    var nr         = new NormalRandom(0, 0.1, r);
                    var parameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(2018, 1, 1)
                                     .SetEndDate(new DateTime(2018, 1, 1, 2, 0, 0)).SetSettlingDays(0).EnableShowSettlingPeriod();
                    builder.Register(x => parameters).As <CalcParameters>().SingleInstance();
                    builder.Register(x => new DateStampCreator(parameters)).As <DateStampCreator>().SingleInstance();
                    builder.Register(c => ltdict).As <CalcLoadTypeDictionary>().SingleInstance();
                    builder.Register(c => ltdtoDict).As <CalcLoadTypeDtoDictionary>().SingleInstance();
                    builder.Register(c => new NormalRandom(0, 1, r)).As <NormalRandom>().SingleInstance();
                    builder.Register(c => new FileFactoryAndTracker(path, mhh.Name, inputlogger))
                    .As <FileFactoryAndTracker>().SingleInstance();
                    builder.Register(c => new SqlResultLoggingService(path)).As <SqlResultLoggingService>()
                    .SingleInstance();
                    builder.Register(c => inputlogger).As <IInputDataLogger>().As <InputDataLogger>().SingleInstance();

                    builder.Register(c => new OnlineLoggingData(c.Resolve <DateStampCreator>(),
                                                                c.Resolve <IInputDataLogger>(), c.Resolve <CalcParameters>())).As <OnlineLoggingData>().As <IOnlineLoggingData>()
                    .SingleInstance();

                    builder.Register(c => new LogFile(parameters, c.Resolve <FileFactoryAndTracker>())).As <ILogFile>()
                    .SingleInstance();
                    builder.RegisterType <OnlineDeviceActivationProcessor>().As <IOnlineDeviceActivationProcessor>()
                    .SingleInstance();
                    builder.RegisterType <CalcModularHouseholdFactory>().As <CalcModularHouseholdFactory>()
                    .SingleInstance();
                    builder.Register(x => new DeviceCategoryPicker(r, null)).As <IDeviceCategoryPicker>()
                    .SingleInstance();

                    builder.Register(x => r).As <Random>().SingleInstance();
                    builder.RegisterType <CalcDeviceFactory>().As <CalcDeviceFactory>().SingleInstance();
                    builder.RegisterType <CalcDeviceDtoFactory>().As <CalcDeviceDtoFactory>().SingleInstance();
                    builder.RegisterType <CalcLocationFactory>().As <CalcLocationFactory>().SingleInstance();
                    builder.RegisterType <CalcLocationDtoFactory>().As <CalcLocationDtoFactory>().SingleInstance();
                    builder.RegisterType <CalcPersonFactory>().As <CalcPersonFactory>().SingleInstance();
                    builder.RegisterType <CalcPersonDtoFactory>().As <CalcPersonDtoFactory>().SingleInstance();
                    builder.RegisterType <CalcAffordanceFactory>().As <CalcAffordanceFactory>().SingleInstance();
                    builder.RegisterType <CalcAffordanceDtoFactory>().As <CalcAffordanceDtoFactory>().SingleInstance();
                    builder.RegisterType <CalcTransportationFactory>().As <CalcTransportationFactory>().SingleInstance();
                    builder.RegisterType <CalcModularHouseholdDtoFactory>().As <CalcModularHouseholdDtoFactory>()
                    .SingleInstance();
                    builder.RegisterType <CalcVariableDtoFactory>().As <CalcVariableDtoFactory>().SingleInstance();
                    builder.RegisterType <CalcTransportationDtoFactory>().As <CalcTransportationDtoFactory>()
                    .SingleInstance();
                    builder.RegisterType <VacationDtoFactory>().As <VacationDtoFactory>().SingleInstance();
                    builder.RegisterType <AvailabilityDtoRepository>().As <AvailabilityDtoRepository>().SingleInstance();
                    builder.RegisterType <CalcVariableRepository>().As <CalcVariableRepository>().SingleInstance();
                    builder.RegisterType <CalcRepo>().As <CalcRepo>().SingleInstance();
                    var container = builder.Build();
                    using (var scope = container.BeginLifetimeScope()) {
                        var hhdtofac = scope.Resolve <CalcModularHouseholdDtoFactory>();

                        var tds = sim.TransportationDeviceSets[0];
                        tds.SaveToDB();
                        var trs = sim.TravelRouteSets[0];
                        trs.SaveToDB();
                        var css = sim.ChargingStationSets[0];
                        css.SaveToDB();

                        /*Site home = sim.Sites.CreateNewItem(sim.ConnectionString);
                         * home.Name = "home";
                         * home.SaveToDB();
                         * Site outside = sim.Sites.CreateNewItem(sim.ConnectionString);
                         * outside.Name = "outside";
                         * outside.SaveToDB();
                         * home.AddLocation(sim.Locations.SafeFindByName("Living room", FindMode.IgnoreCase));
                         * home.AddLocation(sim.Locations.SafeFindByName("Kitchen", FindMode.IgnoreCase));
                         * home.AddLocation(sim.Locations.SafeFindByName("Bath", FindMode.IgnoreCase));
                         * home.AddLocation(sim.Locations.SafeFindByName("Bedroom", FindMode.IgnoreCase));
                         * home.AddLocation(sim.Locations.SafeFindByName("Children's room", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("Dance Studio", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("Supermarket", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("Garden", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("Museum", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("School", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("Food Market", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("Sidewalk", FindMode.IgnoreCase));
                         * outside.AddLocation(sim.Locations.SafeFindByName("Office Workplace 1", FindMode.IgnoreCase));
                         * TravelRoute tr = new TravelRoute(null, db.ConnectionString, "tr1", "desc", home, outside);
                         * tr.SaveToDB();
                         * trs.AddRoute(tr);*/
                        var fft = scope.Resolve <FileFactoryAndTracker>();
                        fft.RegisterGeneralHouse();
                        var ctf = scope.Resolve <CalcTransportationFactory>();
                        //LogFile lf = new LogFile(wd.WorkingDirectory, "hh1", true);
                        //lf.RegisterKey("hh1", "hh1-prettyname");
                        var dtohh = hhdtofac.MakeCalcModularHouseholdDto(sim, mhh,
                                                                         sim.TemperatureProfiles[0], new HouseholdKey("hh1"), sim.GeographicLocations[0],
                                                                         out var dtolocs, tds, trs,
                                                                         EnergyIntensityType.Random, css);
                        var cvdto = scope.Resolve <CalcVariableDtoFactory>();
                        var cvr   = scope.Resolve <CalcVariableRepository>();
                        foreach (var v in cvdto.VariableDtos.Values)
                        {
                            cvr.RegisterVariable(new CalcVariable(v.Name, v.Guid, v.Value,
                                                                  v.LocationName, v.LocationGuid, v.HouseholdKey));
                        }

                        var cmhf = scope.Resolve <CalcModularHouseholdFactory>();
                        //CalcTransportationDtoFactory dtoFactory = new CalcTransportationDtoFactory(ltdtoDict);
                        //dtoFactory.MakeTransportationDtos(sim, sim.ModularHouseholds[0], tds, trs, out var sites,out var transportationDevices, out var routes, dtohh.LocationDtos, dtohh.HouseholdKey);
                        var calcRepo = scope.Resolve <CalcRepo>();
                        var chh      = cmhf.MakeCalcModularHousehold(dtohh, out var dtoCalcLocationDict, null, null,
                                                                     calcRepo);
                        //ctf.MakeTransportation(dtohh,dtoCalcLocationDict,chh);
                        if (chh.TransportationHandler == null)
                        {
                            throw new LPGException("no transportation handler");
                        }

                        var          src        = chh.TransportationHandler.CalcSites[0].Locations[0];
                        var          dst        = chh.TransportationHandler.CalcSites[1].Locations[0];
                        const string personname = "personname";
                        var          ts         = new TimeStep(1, parameters);
                        dst.Affordances[0].IsBusy(ts, src, personname, false);
                        dst.Affordances[0].Activate(ts, personname, src, out var personTimeProfile);
                        fft.Dispose();
                    }

                    db.Cleanup();
                }

                wd.CleanUp();
            }
        }
Exemple #25
0
        public void OnlineDeviceActivationProcessorSetToZeroTest()
        {
            var rnd            = new Random(1);
            var nr             = new NormalRandom(0, 1, rnd);
            var startdate      = new DateTime(2018, 1, 1);
            var enddate        = startdate.AddMinutes(100);
            var calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate).EnableShowSettlingPeriod();

            using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) {
                wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
                wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
                //calcParameters.Enable(CalcOption.ActionsLogfile);
                calcParameters.Enable(CalcOption.DeviceProfilesIndividualHouseholds);
                Config.ExtraUnitTestChecking = true;
                // calcProfile
                var profileWith100 = new CalcProfile("calcProfile", Guid.NewGuid().ToStrGuid(), new TimeSpan(0, 1, 0), ProfileType.Absolute, "blub");
                profileWith100.AddNewTimepoint(new TimeSpan(0), 100);
                profileWith100.AddNewTimepoint(new TimeSpan(0, 5, 0), 100);
                profileWith100.ConvertToTimesteps();
                var profileWith50 = new CalcProfile("calcProfile2", Guid.NewGuid().ToStrGuid(), new TimeSpan(0, 1, 0), ProfileType.Absolute, "blub");
                profileWith50.AddNewTimepoint(new TimeSpan(0), 50);
                profileWith50.AddNewTimepoint(new TimeSpan(0, 3, 0), 50);
                profileWith50.ConvertToTimesteps();
                // Loadtype
                var clt = new CalcLoadType("lt1", "W", "kWh", 1, true, Guid.NewGuid().ToStrGuid());
                // Location
                var cloc = new CalcLocation("Location", Guid.NewGuid().ToStrGuid());
                // devices

                var cdl     = new CalcDeviceLoad("lt1", 100, clt, 100, 0);
                var loads   = new List <CalcDeviceLoad>();
                var results = new List <string> {
                    "100;0;", "100;0;",
                    "100;0;",
                    "100;0;",
                    "100;0;",
                    "100;0;",
                    "0;50;",
                    "0;50;",
                    "0;50;",
                    "100;0;",
                    "100;0;",
                    "100;0;",
                    "100;0;",
                    "100;0;",
                    "100;0;"
                };
                loads.Add(cdl);
                using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hh1", wd.InputDataLogger)) {
                    fft.RegisterHousehold(Constants.GeneralHouseholdKey, "general", HouseholdKeyType.General, "desc", null, null);
                    //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 odap = new OnlineDeviceActivationProcessor(old, calcParameters, fft);
                            using (var calcRepo = new CalcRepo(calcParameters: calcParameters, odap: odap, rnd: rnd, normalRandom: nr)) {
                                var requirements = new List <VariableRequirement>();
                                var devCatGuid   = Guid.NewGuid().ToStrGuid();
                                var key          = new HouseholdKey("HH1");
                                var cddauto      = new CalcDeviceDto("devicename", devCatGuid, key, OefcDeviceType.Device, "device category",
                                                                     " (autonomous)", Guid.NewGuid().ToStrGuid(), cloc.Guid, cloc.Name);
                                var autodev = new CalcAutoDev(profileWith100, clt, loads, 0, 1, cloc, requirements, cddauto, calcRepo);
                                var cdd     = new CalcDeviceDto("devicename", devCatGuid, key, OefcDeviceType.Device, "device category", "",
                                                                Guid.NewGuid().ToStrGuid(), cloc.Guid, cloc.Name);
                                var device   = new CalcDevice(loads, cloc, cdd, calcRepo);
                                var autoDevs = new List <CalcAutoDev> {
                                    autodev
                                };
                                var devices = new List <CalcDevice> {
                                    device
                                };
                                CalcHousehold.MatchAutonomousDevicesWithNormalDevices(autoDevs, devices);
                                if (device.MatchingAutoDevs.Count == 0)
                                {
                                    throw new LPGException("Matching devices didn't work");
                                }

                                foreach (var pair in odap.Oefc.ColumnEntriesByLoadTypeByDeviceKey)
                                {
                                    Logger.Info(pair.Key.Name);
                                    foreach (var entry in pair.Value)
                                    {
                                        Logger.Info(entry.Key + " - " + entry.Value.Name);
                                    }
                                }

                                for (var i = 0; i < 15; i++)
                                {
                                    var ts = new TimeStep(i, 0, true);
                                    if (!autodev.IsBusyDuringTimespan(ts, 1, 1, clt))
                                    {
                                        autodev.Activate(ts);
                                    }

                                    if (i == 6)
                                    {
                                        device.SetTimeprofile(profileWith50, ts, clt, "blub", "Person", 1, false);
                                    }

                                    var filerows = odap.ProcessOneTimestep(ts);
                                    filerows.Count.Should().Be(1);
                                    filerows[0].EnergyEntries.Count.Should().Be(2);
                                    var entries = string.Empty;

                                    foreach (var d in filerows[0].EnergyEntries)
                                    {
                                        entries += d.ToString(CultureInfo.CurrentCulture) + ";";
                                    }

                                    Logger.Info(entries);
                                    results[i].Should().Be(entries);
                                }
                            }
                        }
                    }
                }

                wd.CleanUp();
            }
        }
Exemple #26
0
 public static int Next(int min, int max)
 {
     lock (Lock)
         return(NormalRandom.Next(min, max));
 }
        public void TestInterruptionTest()
        {
            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).SetSettlingDays(0).EnableShowSettlingPeriod().DisableShowSettlingPeriod().SetAffordanceRepetitionCount(1);
            //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());

            //var variableOperator = new VariableOperator();
            using var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "blub", wd.InputDataLogger);
            var key = new HouseholdKey("HH1");

            wd.InputDataLogger.AddSaver(new ActionEntryLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new LocationEntryLogger(wd.SqlResultLoggingService));
            fft.RegisterHousehold(key, "hh1", HouseholdKeyType.Household, "desc", null, null);
            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());
            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);

            //"blub", 1, 1, r,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           devCategoryGuid = Guid.NewGuid().ToStrGuid();
            CalcDeviceDto cdd1            = new CalcDeviceDto("cdevice1", devCategoryGuid, key,
                                                              OefcDeviceType.Device, "category", "", Guid.NewGuid().ToStrGuid(),
                                                              cloc.Guid, cloc.Name);
            var           cdev1 = new CalcDevice(deviceLoads, cloc, cdd1, calcRepo);
            CalcDeviceDto cdd2  = new CalcDeviceDto("cdevice2", devCategoryGuid, key,
                                                    OefcDeviceType.Device, "category", "", Guid.NewGuid().ToStrGuid(),
                                                    cloc.Guid, cloc.Name);
            var           cdev2 = new CalcDevice(deviceLoads, cloc, cdd2, calcRepo);
            CalcDeviceDto cdd3  = new CalcDeviceDto("cdevice3", devCategoryGuid, key,
                                                    OefcDeviceType.Device, "category", "", Guid.NewGuid().ToStrGuid(),
                                                    cloc.Guid, cloc.Name);
            var cdev3 = new CalcDevice(deviceLoads, cloc, cdd3, calcRepo);

            cloc.Devices.Add(cdev1);
            cloc.Devices.Add(cdev2);
            cloc.Devices.Add(cdev3);
            var daylight = new BitArray(100);

            daylight.SetAll(true);
            DayLightStatus dls = new DayLightStatus(daylight);

            double[] newValues = { 1, 1, 1.0, 1, 1, 1, 1, 1 };
            var      newList   = new List <double>(newValues);
            var      cprof     = new CalcProfile("cp1", Guid.NewGuid().ToStrGuid(), newList, ProfileType.Relative, "bla");

            var desires = new List <CalcDesire>
            {
                desire1
            };
            var color = new ColorRGB(255, 0, 0);
            CalcVariableRepository crv = new CalcVariableRepository();
            BitArray isBusy            = 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, "bla", 100, false, "",
                                               Guid.NewGuid().ToStrGuid(), crv
                                               , new List <CalcAffordance.DeviceEnergyProfileTuple>(), isBusy, BodilyActivityLevel.Low, calcRepo);

            aff1.AddDeviceTuple(cdev1, cprof, lt, 0, calcParameters.InternalStepsize, 1, 1);
            cloc.AddAffordance(aff1);
            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>(), isBusy, BodilyActivityLevel.Low, calcRepo);

            aff2.AddDeviceTuple(cdev2, cprof, lt, 0, calcParameters.InternalStepsize, 1, 1);
            cloc.AddAffordance(aff2);
            var clocs = new List <CalcLocation>
            {
                cloc
            };
            BitArray isBusySub         = new BitArray(calcParameters.InternalTimesteps, false);
            var      calcSubAffordance = new CalcSubAffordance("subaffname", cloc, desires, 0,
                                                               100, 1,
                                                               PermittedGender.All, "subaff", false, true,
                                                               aff1, new List <CalcAffordanceVariableOp>(), 100,
                                                               "testing", Guid.NewGuid().ToStrGuid(), isBusySub, crv, BodilyActivityLevel.Low,
                                                               calcRepo);

            aff2.SubAffordances.Add(calcSubAffordance);
            calcSubAffordance.SetDurations(2);
            var persons = new List <CalcPerson>
            {
                cp
            };

            for (var i = 0; i < 100; i++)
            {
                TimeStep ts = new TimeStep(i, 0, true);
                cp.NextStep(ts, clocs, dls, new HouseholdKey("hh1"), persons, 1);
            }

            //wd.CleanUp();
        }
        public void CalcTransportationDeviceDriveTest()
        {
            using var wd  = new WorkingDir(Utili.GetCurrentMethodAndClass());
            using var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "blub", wd.InputDataLogger);
            wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService));
            wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService));
            //_calcParameters.CSVCharacter = ";";_calcParameters.InitializeTimeSteps(new DateTime(2018,1,1),new DateTime(2018,1,31),new TimeSpan(0,1,0),3,true  );
            var calcParameters = CalcParametersFactory.MakeGoodDefaults();

            var category = new CalcTransportationDeviceCategory("category", true, Guid.NewGuid().ToStrGuid());
            var lt2      = new CalcLoadType("driving load", "km/h", "km", 10000, false, Guid.NewGuid().ToStrGuid());
            var rnd      = new Random(1);
            var nr       = new NormalRandom(0, 0.1, rnd);
            //SqlResultLoggingService srls = new SqlResultLoggingService(wd.WorkingDirectory);
            var dsc = new DateStampCreator(calcParameters);

            using var old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters);
            using var lf  = new LogFile(calcParameters, fft, true);
            var key = new HouseholdKey("hh1");

            fft.RegisterHousehold(key, "Household", HouseholdKeyType.Household, "Description", null, null);
            fft.RegisterGeneralHouse();
            var chargingCalcLoadType = new CalcLoadType("charging load", "W", "kWh", 0.50, false, Guid.NewGuid().ToStrGuid());
            var odap = new OnlineDeviceActivationProcessor(old, calcParameters, fft);

            using var calcRepo = new CalcRepo(rnd: rnd, normalRandom: nr, lf: lf, calcParameters: calcParameters, odap: odap,
                                              onlineLoggingData: old);
            var srcSite = new CalcSite("srcsite", Guid.NewGuid().ToStrGuid(), key);
            var dstSite = new CalcSite("dstSite", Guid.NewGuid().ToStrGuid(), key);
            var station = new CalcChargingStation(category, chargingCalcLoadType, 500, "stationname", "stationguid".ToStrGuid(),
                                                  key, chargingCalcLoadType, calcRepo);

            dstSite.ChargingDevices.Add(station);
            var calcSites = new List <CalcSite> {
                srcSite,
                dstSite
            };
            var cdd = new CalcDeviceDto("transport device", category.Guid, key, OefcDeviceType.Transportation, category.Name,
                                        string.Empty, Guid.NewGuid().ToStrGuid(), StrGuid.Empty, string.Empty);
            var loads = new List <CalcDeviceLoad> {
                new CalcDeviceLoad("load1", 10, lt2, 10000, 0)
            };
            var ctd = new CalcTransportationDevice(category, 10, loads, 10000, 1, 1000, chargingCalcLoadType, calcSites, cdd,
                                                   calcRepo);
            var start = new TimeStep(1, 0, false);
            var end   = new TimeStep(11, 0, false);

            ctd.Activate(start, 10, srcSite, dstSite, "myroute", "myperson", start, end);

            ctd.AvailableRangeInMeters.Should().Be(10000);
            //TODO: fix this and comment out
            //station.IsAvailable = false;
            double prevrange = 0;

            for (var i = 1; i < 11; i++)
            {
                var ts = new TimeStep(i, 0, false);
                ctd.DriveAndCharge(ts);
                odap.ProcessOneTimestep(ts);
                var diffRange = prevrange - ctd.AvailableRangeInMeters;
                Logger.Info("timestep: " + i + " Range: " + ctd.AvailableRangeInMeters + " diff:" + diffRange);
                prevrange = ctd.AvailableRangeInMeters;
                ctd.Currentsite.Should().BeNull();
            }

            //no charging
            ctd.AvailableRangeInMeters.Should().Be(10000 - 10 * 60 * 10); //10m/s = 600m/minute
            Logger.Info("currentSite:" + ctd.Currentsite?.Name);

            //station.IsAvailable = true;
            for (var i = 11; i < 50; i++)
            {
                var ts = new TimeStep(i, 0, false);
                ctd.DriveAndCharge(ts);
                odap.ProcessOneTimestep(ts);
                Logger.Info("timestep: " + i + " Range: " + ctd.AvailableRangeInMeters);
            }

            ctd.Currentsite.Should().Be(dstSite);

            //  wd.CleanUp(1);
        }
Exemple #29
0
 private void Event_SaveGameLoaded()
 {
     lcgrnd = new LCGRandom(api.World.Seed);
     rndn   = new NormalRandom(api.World.Seed);
 }
Exemple #30
0
 public static int Next()
 {
     lock (Lock)
         return(NormalRandom.Next());
 }