Example #1
0
        // contains the algorithms of updating properties, convergence checking and time cut off.
        private static int Update(SimulationData data, double[] convergenceError, double[] delta, int counter)
        {
            UpdatePropertiesFromNewP(data, delta);

            // check convergence errors.
            bool repeat = CheckConvergence(data, convergenceError);

            //bool repeat = false;

            if (!repeat && (data.maximumNonLinearIterations - counter) != 1)
            {
                // increment the counter.
                counter += 1;
            }
            else
            {
                data.timeStep *= data.timeStepSlashingFactor;

                for (int i = 0; i < data.grid.Length; i++)
                {
                    data.grid[i].Reset(data);
                }

                // reset the convergenceError array so that it violates the convergence criteria
                convergenceError[0] = 0;
                convergenceError[1] = data.MBE_Tolerance;
                //convergenceError[1] = 0;

                // reset the counter.
                // this way we begin repeating the same time step with all the number of non linear iterations.
                counter = 0;
            }

            return(counter);
        }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseWell"/> class.
        /// </summary>
        /// <param name="data">The <see cref="SimulationData"/>.</param>
        /// <param name="index">The index of the block the well is located into.</param>
        /// <param name="type">The well type<see cref="Global.WellType"/>.</param>
        /// <param name="control">The well control method <see cref="Global.WellControl"/>.</param>
        /// <param name="radius">The well radius.</param>
        /// <param name="skin">The skin factor.</param>
        /// <param name="specifiedMinimumBHP">The specified_minimum BHP.</param>
        /// <param name="specifiedFlowRate">The specified flow rate.</param>
        /// <param name="method">The well rate method used <see cref="Global.WellRateCalculation"/>.</param>
        public BaseWell(SimulationData data, int index, Global.WellType type, Global.WellControl control, double radius, double skin, double specifiedMinimumBHP = 0, double specifiedFlowRate = 0, Global.WellRateCalculation method = Global.WellRateCalculation.Explicit)
        {
            this.index            = index;
            this.type             = type;
            this.control          = control;
            this.method           = method;
            data.grid[index].type = Global.BlockType.WellBlock;
            this.radius           = radius;
            this.skin             = skin;
            this.R_equivalent     = GetR_Equivalent(data.grid[index], data.grid);
            this.WI = GetWI(data.grid[index]);
            this.specifiedMinimumBHP = specifiedMinimumBHP;

            this.specifiedFlowRate = specifiedFlowRate;
            if (type == Global.WellType.Injection)
            {
                this.specifiedFlowRate = -1 * specifiedFlowRate;
            }

            this.BHP            = new double[Global.STEPS_MEMORY];
            this.q_oil          = new double[Global.STEPS_MEMORY];
            this.q_free_gas     = new double[Global.STEPS_MEMORY];
            this.q_solution_gas = new double[Global.STEPS_MEMORY];
            this.q_water        = new double[Global.STEPS_MEMORY];
        }
        /// <summary>
        /// Deinitialization method cleaning all the created objects
        /// </summary>
        public async Task Deinitialize()
        {
            //Client should wait for master to break the connection
            if (IsClient)
            {
                while (Client.Connection.ConnectedPeersCount > 0)
                {
                    await Task.Delay(20);
                }
            }
            StopConnection();

            var type = Type;
            var clearObjectsAction = new Action(() =>
            {
                ClearNetworkObjects(type);
            });

            ThreadingUtilities.DispatchToMainThread(clearObjectsAction);

            LocalAddresses.Clear();
            MasterAddresses.Clear();
            Type = ClusterNodeType.NotClusterNode;
            CurrentSimulation = null;
            Log.Info("Deinitialized the Simulation Network data.");
        }
    public void callTrackingDelegate()
    {
        stopTrack();
        if (sendTrack)
        {
            Debug.Log("<color=green>Sending Track</color>");

            string date = DateTime.Now.ToString();
            sendText.enabled = true;
            simData          = new SimulationData(date, user, targetInfo, cube, vPath, headTrackingList.ToArray(), toolTrackingList.ToArray(), timeout, LoginManager.GetComponent <LoginScript>().debugging);
            string url     = "https://api.mlab.com/api/1/databases/medicart/collections/simulations?apiKey=SmvExKbpTZ9D_lSWBX9WEEo_nEboqR6q";
            string json    = JsonUtility.ToJson(simData);
            WWW    request = POST(json, url);

            simHeader = new SimulationHeader(user, date, toolTrackingList [toolTrackingList.Count - 1].time - toolTrackingList [0].time);
            string url2     = "https://api.mlab.com/api/1/databases/medicart/collections/simheaders?apiKey=SmvExKbpTZ9D_lSWBX9WEEo_nEboqR6q";
            string json2    = JsonUtility.ToJson(simHeader);
            WWW    request2 = POST(json2, url2);
        }
        sendText.enabled = false;
        sendTrack        = false;
        timeout          = false;
        vPath            = Vector3.zero;
        officialStart    = 100000f;
    }
Example #5
0
    // Start is called before the first frame update
    void Start()
    {
        transform.position = new Vector3(-3.53f, 0.05f, -2);
        //EndingText = GameObject.Find("TimeOrCrashed");
        infoObject = (InfoObject)UnityEngine.Object.FindObjectOfType(typeof(InfoObject));
        SimulationData simData = infoObject.simulationData;

        History = simData.history;
        score   = simData.score;
        tps     = History.tps;
        history = History.history;
        //crashed = (score.successful==false);
        crashed = true;
        swpl    = history.Length;
        time    = score.time;
        secTime = time / tps;
        sentwps = new float[swpl, 2];



        Vector2 currentPosition = this.transform.position;
        var     i = 0;

        while (i < swpl)
        {
            var temp = ConvertPos(history[i].pos, currentPosition);
            sentwps[i, 0] = temp[0];
            sentwps[i, 1] = temp[1];
            i++;
        }
    }
Example #6
0
        // the iteration cycle
        private static void IterativeSolver(SimulationData data, double[][] Jacobi, double[] minusR, double[] delta)
        {
            // an array containing previous "index 0" and current "index 1" material balance errors.
            double[] MBE = new double[2];

            // resets time step to its original value at the beginning of each new time step.
            ResetTimeStep(data);

            // reset relaxation factor.
            data.relaxationFactor = data.originalRelaxationFactor;

            // non-linear iteration counter.
            int counter = 0;

            do
            {
                // formulation.
                NumericalPerturbation.CalculateMinusR_Matrix(data, minusR);
                NumericalPerturbation.CalculateJacobi_Matrix(data, minusR, Jacobi);
                WellTerms.Add(data, Jacobi, minusR);

                // solving the equations.
                delta = SolveForDelta(Jacobi, minusR);

                // update properties with better approximations.
                counter = Update(data, MBE, delta, counter);

                // repeat the cycle if the material balance error is larger than the tolerance specified.
                // as long as the repetitions are smaller than the maximum number of non-linear iterations specified.
            } while (MBE[1] >= data.MBE_Tolerance && counter <= data.maximumNonLinearIterations);

            // update properties of the new time step after successful convergence.
            UpdateProperties(data);
        }
Example #7
0
        // updates the n1 time level properties with better approximation after solving the Ax=B equation.
        private static void UpdatePropertiesFromDeltas(SimulationData data, double[] delta)
        {
            double P, So, Sg, Sw;

            int counter = 0;

            for (int i = 0; i < data.grid.Length; i++)
            {
                P = data.grid[i].P[1] + delta[counter];
                // assert p is always greater than 0.
                P = P > 0 ? P : 0;

                Sg = data.grid[i].Sg[1] + delta[counter + 1];
                // assert Sg is always greater than 0.
                Sg = Sg > 0 ? Sg : 0;

                Sw = data.grid[i].Sw[1] + delta[counter + 2];
                // assert Sw is always greater than 0.
                Sw = Sw > 0 ? Sw : 0;

                So = 1 - Sw - Sg;

                data.grid[i].UpdateProperties(data, P, Sw, Sg, So, 1);

                counter += data.phases.Length;
            }
        }
        private SimulationData CreateSimulationData()
        {
            var tempSimulationData = new SimulationData
            {
                CodingMode = new SimulationData.Mode
                {
                    Name  = CodingModes[CodingIndex],
                    Index = CodingIndex
                },
                ModulationMode = new SimulationData.Mode
                {
                    Name  = ModulationModes[ModulationIndex],
                    Index = ModulationIndex
                },
                FrameLength       = this.FrameLength,
                DecisionDepth     = this.DecisionDepth,
                SNR               = this.SNR,
                TransmitterAuthor = CurrTrans,
                ReceiverAuthor    = CurrReceiv,
                BitsSend          = 0,
                BitsLost          = 0
            };


            return(tempSimulationData);
        }
Example #9
0
        public SimulationConfig(SimulationData simulation)
        {
            Name           = simulation.Name;
            Clusters       = simulation.Cluster != null && simulation.Cluster.Instances.Length > 1 ? simulation.Cluster.Instances.SelectMany(i => i.Ip).ToArray() : new string[] { };
            ClusterName    = simulation.Cluster.Name;
            ApiOnly        = simulation.ApiOnly;
            Headless       = simulation.Headless;
            Interactive    = simulation.Interactive;
            TimeOfDay      = simulation.TimeOfDay;
            Rain           = simulation.Rain;
            Fog            = simulation.Fog;
            Wetness        = simulation.Wetness;
            Cloudiness     = simulation.Cloudiness;
            Damage         = simulation.Damage;
            UseTraffic     = simulation.UseTraffic;
            UsePedestrians = simulation.UsePedestrians;
            Seed           = simulation.Seed;
            if (simulation.Vehicles == null || simulation.Vehicles.Length == 0 || simulation.ApiOnly)
            {
                Agents = Array.Empty <AgentConfig>();
            }
            else
            {
                Agents = simulation.Vehicles.Select(v => new AgentConfig(v)).ToArray();
            }

            TestReportId = simulation.TestReportId;
        }
        private void SelectSnapshot(int offset)
        {
            if (offset != 0)
            {
                SimDateTime actualSdt = null;

                if (offset == short.MinValue)
                {
                    actualSdt = _min;
                }
                else if (offset == short.MaxValue)
                {
                    actualSdt = _max;
                }
                else if (offset == -3)
                {
                    actualSdt = SimulationData.SelectPreviousSnapshot(_crtSnapshot);
                }
                else if (offset == 3)
                {
                    actualSdt = SimulationData.SelectNextSnapshot(_crtSnapshot);
                }
                else
                {
                    SimDateTime sdt = _crtSnapshot.AddHours(offset);
                    actualSdt = SimulationData.SelectNearestSnapshot(sdt);
                }

                cmbSnapshots.SelectedItem = actualSdt;
            }
        }
Example #11
0
        private IEnumerator LoadScene()
        {
            simulationData = ScriptableObject.CreateInstance <SimulationData>();
            simulationData.populationDensity           = (uint)populationDensitySlider.value;
            simulationData.infectivity                 = infectivitySlider.value;
            simulationData.launchSickNumber            = launchSickNumberSlider.value;
            simulationData.launchImmunedNumber         = launchImmunedNumberSlider.value;
            simulationData.diseaseDuration             = (uint)diseaseDurationSlider.value;
            simulationData.deathStatistic              = deathStatisticSlider.value;
            simulationData.diseaseTransmissionDistance = transmissionDistanceSlider.value;

            yield return(null);

            m_openSimulationScene = SceneManager.LoadSceneAsync(simulationSceneName);
            m_openSimulationScene.allowSceneActivation = false;

            while (!m_openSimulationScene.isDone)
            {
                //Output the current progress
                Debug.Log("Loading progress: " + (m_openSimulationScene.progress * 100).ToString() + "%");

                // Check if the load has finished
                if (m_openSimulationScene.progress >= 0.9f)
                {
                    m_openSimulationScene.allowSceneActivation = true;
                }

                yield return(null);
            }
        }
Example #12
0
        // the iteration cycle
        private static void IterativeSolver(SimulationData data, double[][] pressureCoefficients, double[] constants, double[] deltaP)
        {
            // an array containing previous "index 0" and current "index 1" material balance errors.
            double[] MBE = new double[2];

            // resets time step to its original value at the beginning of each new time step.
            ResetTimeStep(data);

            // non-linear iteration counter.
            int counter = 0;

            do
            {
                // formulation.
                IMPES_Preparation.CalculateConstantsMatrix(data, constants);
                IMPES_Preparation.CalculatePressureCoefficientsMatrix(data, pressureCoefficients);
                IMPES_Preparation.AddWellTerms(data, pressureCoefficients, constants);

                // solving the equations.
                deltaP = SolveForNewP(pressureCoefficients, constants);

                // update properties with better approximations.
                counter = Update(data, MBE, deltaP, counter);

                // repeat the cycle if the material balance error is larger than the tolerance specified.
                // as long as the repetitions are smaller than the maximum number of non-linear iterations specified.
            } while (MBE[1] >= data.MBE_Tolerance && counter <= data.maximumNonLinearIterations);

            // update properties of the new time step after successful convergence.
            UpdateProperties(data);
        }
        void OnEnable()
        {
            Instance = this;
            EditorApplication.playModeStateChanged += HandlePlayMode;
            EditorApplication.update += OnEditorUpdate;

            Settings = (DevelopmentSettingsAsset)AssetDatabase.LoadAssetAtPath("Assets/Resources/Editor/DeveloperSettings.asset", typeof(DevelopmentSettingsAsset));
            if (Settings == null)
            {
                Settings = (DevelopmentSettingsAsset)CreateInstance(typeof(DevelopmentSettingsAsset));
                Debug.Log("Initialized new developer settings");
                Settings.VersionOverride = Application.version;
                AssetDatabase.CreateAsset(Settings, "Assets/Resources/Editor/DeveloperSettings.asset");
            }

            if (Settings.developerSimulationJson != null)
            {
                DeveloperSimulation = JsonConvert.DeserializeObject <SimulationData>(Settings.developerSimulationJson);
            }

            if (DeveloperSimulation == null)
            {
                DeveloperSimulation = new SimulationData()
                {
                    Name      = "DeveloperSettings",
                    TimeOfDay = DateTime.Now,
                };
            }

            Refresh();
        }
Example #14
0
        public void reportStatus(SimulatorStatus value, string message = "")
        {
            Console.WriteLine($"[LOADER] Update simulation status {status} -> {value}");

            var previous  = reportedStatus(status);
            var newStatus = reportedStatus(value);

            status = value;

            if (value == SimulatorStatus.Error && SimulatorManager.InstanceAvailable)
            {
                SimulatorManager.Instance.AnalysisManager.AddErrorEvent(message);
            }

            if (previous == newStatus)
            {
                return;
            }

            if (ConnectionManager.instance != null)
            {
                ConnectionManager.instance.UpdateStatus(newStatus, CurrentSimulation.Id, message);
            }

            if (value == SimulatorStatus.Idle)
            {
                currentSimulation = null;
            }

            if (status == SimulatorStatus.Running)
            {
                WindowFlasher.Flash();
            }
        }
Example #15
0
 public BaseSceneContext(SimulationData data)
 {
     this.data                   = data;
     this.backgroundLayer        = LayerMask.NameToLayer(backgroundLayerName);
     this.staticForegroundLayer  = LayerMask.NameToLayer(staticForegroundLayerName);
     this.dynamicForegroundLayer = LayerMask.NameToLayer(dynamicForegroundLayerName);
 }
Example #16
0
        // miscellaneous internal helper methods

        // returns the absolute value of the gas material balance error of the whole model.
        private static bool CheckConvergence(SimulationData data, double[] convergenceError)
        {
            bool firstIteration = convergenceError[0] == 0;

            convergenceError[0] = convergenceError[1];

            data.MBE_Oil   = Math.Abs(MBE.CheckOil(data));
            data.MBE_Gas   = Math.Abs(MBE.CheckGas(data));
            data.MBE_Water = Math.Abs(MBE.CheckWater(data));

            convergenceError[1] = Math.Max(data.MBE_Gas, Math.Max(data.MBE_Oil, data.MBE_Water));

            bool MBE_Increasing = (convergenceError[1] > convergenceError[0]);

            //bool slowConvergence = convergenceError[1] / convergenceError[0] > data.maximumConvergenceErrorRatio;

            // if this is not the first iteration and either one of the following conditions is true:
            // 1- material balance error is increasing not decreasing.
            // 2- the rate of convergence is slow.
            if (!firstIteration && (MBE_Increasing /*|| slowConvergence*/))
            {
                return(true);
            }

            return(false);
        }
Example #17
0
        /// <summary>
        /// Add the well terms "flow rates and derivatives" of each phase to their respective position in the Jacobi and the minus R matrices.
        /// </summary>
        /// <param name="data">The <see cref="SimulationData"/> data.</param>
        /// <param name="Jacobi">The Jacobi matrix.</param>
        /// <param name="minusR">The minus R matrix.</param>
        public static void Add(SimulationData data, double[][] Jacobi, double[] minusR)
        {
            int index = 0;

            for (int i = 0; i < data.wells.Length; i++)
            {
                index = 3 * data.wells[i].index;

                minusR[index]     += data.wells[i].q_oil[1];
                minusR[index + 1] += data.wells[i].q_free_gas[1] + data.wells[i].q_solution_gas[1];
                minusR[index + 2] += data.wells[i].q_water[1];
            }

            for (int i = 0; i < data.wells.Length; i++)
            {
                index = 3 * data.wells[i].index;

                Jacobi[index][index]     -= data.wells[i].dq_oil_dP;
                Jacobi[index][index + 1] -= data.wells[i].dq_oil_dSg;
                Jacobi[index][index + 2] -= data.wells[i].dq_oil_dSw;

                Jacobi[index + 1][index]     -= (data.wells[i].dq_free_gas_dP + data.wells[i].dq_solution_gas_dP);
                Jacobi[index + 1][index + 1] -= (data.wells[i].dq_free_gas_dSg + data.wells[i].dq_solution_gas_dSg);
                Jacobi[index + 1][index + 2] -= (data.wells[i].dq_free_gas_dSw + data.wells[i].dq_solution_gas_dSw);

                Jacobi[index + 2][index]     -= data.wells[i].dq_water_dP;
                Jacobi[index + 2][index + 1] -= data.wells[i].dq_water_dSg;
                Jacobi[index + 2][index + 2] -= data.wells[i].dq_water_dSw;
            }
        }
Example #18
0
        void simulation_MarkServer(object sender, MarkServerEventArgs e)
        {
            Node serverNode;

            NodeIdMap.TryGetValue(e.Id, out serverNode);

            if (serverNode != null)
            {
                serverNode.Highlight = true;
                SimulationServerNode = serverNode;

                var nodeIds = GetNodeIds();
                foreach (var id in nodeIds)
                {
                    if (id == SimulationServerNode.Id)
                    {
                        SimulationData.Add(id, new List <int>());
                        continue;
                    }

                    var data = new List <int>();
                    data.Add(id);
                    SimulationData.Add(id, data);
                }
            }
        }
Example #19
0
        /// <summary>
        /// Extract the data
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public override double Extract(SimulationData data)
        {
            IParameterized c = (IParameterized)data.GetObject(Component);

            return(c.Ask(Parameter, data.Circuit));
            // return c.Ask(Parameter);
        }
Example #20
0
 public void Add(SimulationData data)
 {
     using (var db = DatabaseManager.Open())
     {
         db.Insert(data);
     }
 }
Example #21
0
        void Start()
        {
            var env = GameObject.FindGameObjectWithTag("AgentEnvironment");

            if (!env)
            {
                return;
            }

            var agentEnvironment = env.GetComponent <AgentEnvironment>();

            if (agentEnvironment)
            {
                m_environment = agentEnvironment;
            }

            m_simulationData         = ScriptableObject.FindObjectOfType <SimulationData>();
            simulationDataText.text += "\n" +
                                       $"Density : {m_simulationData.populationDensity.ToString()} \n " +
                                       $"Infectivity : {m_simulationData.infectivity.ToString()} \n " +
                                       $"Launch Sick nb : {m_simulationData.launchSickNumber.ToString()} \n " +
                                       $"Launch Immuned nb :  {m_simulationData.launchImmunedNumber.ToString()} \n " +
                                       $"Disease duration :  {m_simulationData.diseaseDuration.ToString()} \n " +
                                       $"Death statistic :  {m_simulationData.deathStatistic.ToString()} \n " +
                                       $"Disease transmission distance :  {m_simulationData.diseaseTransmissionDistance.ToString()} \n ";

            m_bastCitizensStatText = currentCitizensStatText.text;
            m_bastMayorStatText    = currentMayorStatText.text;
        }
Example #22
0
 /// <summary>
 /// Store the result of the AC simulation
 /// </summary>
 /// <param name="sender">Simulation invoking the event</param>
 /// <param name="data">Simulation data</param>
 private void StoreResult(object sender, SimulationData data)
 {
     for (int i = 0; i < Analysis.Sweeps.Count; i++)
     {
         Sweeps[i].Add(Analysis.Sweeps[i].CurrentValue);
     }
     Results.Add(extractsim(data));
 }
 public MatrixBuilder(Mesh mesh, SimulationData simulationData)
 {
     _points         = new IntegrationPoints();
     _deviratives    = new Deviratives(_points);
     _mesh           = mesh;
     _simulationData = simulationData;
     buildJacobianMatrix();
     initializeLocalMatrixes();
 }
Example #24
0
 public void RenderSimState(SimulationData simulationData, SimulationState stateToRender)
 {
     RenderVehicles(simulationData, stateToRender.Vehicles, stateToRender.IndexToID);
     foreach (var list in stateToRender.Projectiles)
     {
         RenderProjectiles(list);
     }
     mPrimitiveRenderer.Render();
 }
Example #25
0
        public static WeatherYear WeatherYear(this SimulationData simulationData, int year = 2018)
        {
            if (simulationData == null)
            {
                return(null);
            }

            return(WeatherYear(simulationData.GetBuildingData(), year));
        }
Example #26
0
        /// <summary>
        /// Gets the CGG term.
        /// </summary>
        /// <param name="block">The block.</param>
        /// <param name="data">The <seealso cref="SimulationData"/> data.</param>
        /// <returns></returns>
        public static double GetCGG(this BaseBlock block, SimulationData data)
        {
            CGG = 1 / (Global.a * data.timeStep) * (block.Vp[1] / block.Bg[1] - (block.Vp[1] / block.Bo[1]) * block.Rso[1]);

            //bhp = Well.WellData.calculatePwf(block, block.P[1], block.Kro[2], block.viscosityOil[1], block.Bo[1]);
            //temp = (Well.WellData.calculateFlow_Rate(block.P[1], bhp, block.Krg[2], block.viscosityGas[1], block.WI, block.Bg[1]) - block.q_gas[1]) / (block.Sg[2] - block.Sg[1]);

            return(CGG + temp);
        }
Example #27
0
        // get data from input data file.

        private static void InitializeRUNSPEC(SimulationData data, List <string> section)
        {
            int index;
            // first : single-line keywords

            // phases
            List <Global.Phase> phases = new List <Global.Phase>();

            if (section.Contains("OIL"))
            {
                phases.Add(Global.Phase.Oil);
            }
            if (section.Contains("WATER"))
            {
                phases.Add(Global.Phase.Water);
            }
            if (section.Contains("GAS"))
            {
                phases.Add(Global.Phase.Gas);
            }
            if (section.Contains("DISGAS"))
            {
                //phases.Add(Global.Phase.DissolvedGas);
                data.solubleGasPresent = true;
            }

            data.phases = phases.ToArray();

            if (section.Contains("IMPES"))
            {
                data.solutionProcedure = Global.SolutionProcedure.IMPES;
            }
            else
            {
                data.solutionProcedure = Global.SolutionProcedure.FullyImplicit;
            }


            // second : two-lines keywords

            // title
            index      = section.FindIndex(x => x.Contains("TITLE"));
            data.title = section[index + 1];

            // grid dimensions
            index = section.FindIndex(x => x.Contains("DIMENS"));
            string[] dimens = section[index + 1].Split(new char[] { }, StringSplitOptions.RemoveEmptyEntries);
            data.x = int.Parse(dimens[0]);
            data.y = int.Parse(dimens[1]);
            data.z = int.Parse(dimens[2]);

            // well dimensions
            index      = section.FindIndex(x => x.Contains("WELLDIMS"));
            dimens     = section[index + 1].Split(new char[] { }, StringSplitOptions.RemoveEmptyEntries);
            data.wells = new Well.BaseWell[int.Parse(dimens[0])];
        }
Example #28
0
        private void simulation_End(object sender, EventArgs e)
        {
            UnmarkSimulationParticpants();
            if (SimulationServerNode != null)
            {
                SimulationServerNode.Highlight = false;
            }

            SimulationData.Clear();
        }
        private StrategySimulationData GetSimulationData(object ti)
        {
            StrategySimulationData data;

            if (SimulationData.TryGetValue(ti, out data))
            {
                return(data);
            }
            return(null);
        }
Example #30
0
 /// <summary>
 /// this method detects oscillations or stagnations and applies relaxation if needed.
 /// </summary>
 /// <remarks>
 /// The only time this method triggered was when i ran the model using <see cref="AccumulationTermExpansion"/> near the bubble point pressure.
 /// </remarks>
 /// <param name="data">the <see cref="SimulationData"/>.</param>
 /// <param name="delta_x">The result of solving the Ax=B equation</param>
 /// <param name="convergenceError">
 /// <para>An array containing previous and current iteration material balance error.</para>
 /// <para>This way we can detect oscillations or stagnation based on comparing current and previous iteration values.</para>
 /// </param>
 /// <returns>
 /// <para>True if relaxation fails. This requires repition of the step using a different time step</para>
 /// <para>False if relaxation is applied.</para>
 /// </returns>
 /// <seealso cref="SimulationData.timeStepSlashingFactor"/>.
 private static void StabilizeNewton(SimulationData data, double[] delta_x, double[] convergenceError)
 {
     if (data.relaxationFactor != 1)
     {
         for (int i = 0; i < delta_x.Length; i++)
         {
             delta_x[i] = data.relaxationFactor * delta_x[i];
         }
     }
 }
Example #31
0
        public unsafe override void PerformSimulationStage(SimulationData data)
        {
            _data = data;
            Disease disease = _data.DiseaseToSimulate;

            if (_arrayHeight == 0 /* || _arrayWidth == 0 */) //Checking one value should be enough, only happens in first round
            {
                _arrayHeight = _data.ImageHeight;
                _arrayWidth = _data.ImageWidth;
                _arrayMaxIndex = _arrayHeight * _arrayWidth;
            }

            //Let each Cell calculate its probability
            for (int index = 0; index < data.Cells.Length; ++index)
            {
                PopulationCell cell = data.Cells[index];
                if (cell != null)
                    cell.Probability = CalculateProbability(index, disease.Transferability);
            }

            //Let Humans get Infected by chance
            fixed (Human* humanptr = data.Humans)
            {
                Human* startPtr = humanptr;

                Parallel.For(0, _data.Humans.Length, Constants.DEFAULT_PARALLELOPTIONS,
                    index =>
                    {
                        Human* ptr = startPtr + index;

                        if (!ptr->IsDead() && !ptr->IsInfected())
                        {
                            int probability = 0;
                            lock (_data.Cells[ptr->CurrentCell])
                                probability = _data.Cells[ptr->CurrentCell].Probability;

                            TryInfection(ptr, disease, probability);
                        }
                    });
                //TODO: Old code for speed boost reference.. DELETE when done
                //for (Human* ptr = humanptr; ptr < humanptr + _data.Humans.Length; ++ptr)
                //{
                //    if (!ptr->IsDead() && !ptr->IsInfected())
                //    {
                //        TryInfection(ptr, disease, _data.Cells[ptr->CurrentCell].Probability);
                //    }
                //}
            }
        }
Example #32
0
        public unsafe override void PerformSimulationStage(SimulationData data)
        {
            if (_currentDay != data.CurrentDay)
                _currentDay = data.CurrentDay;
            else
                return;

            fixed (Human* humanptr = data.Humans)
            {
                Human* startPtr = humanptr;
                Parallel.For(0, data.Humans.Length, Constants.DEFAULT_PARALLELOPTIONS,
                    index =>
                    {
                        Human* ptr = startPtr + index;

                        if (ptr->IsDead() || ptr->IsTravelling() || ptr->GetAge() == EAge.Senior || ptr->GetAge() == EAge.Baby)
                        {
                            return;
                        }

                        if (ptr->IsAtHome())
                        {
                            if (ptr->IsDiseased())
                            {
                                    ptr->SetMindset(EMindset.HomeStaying);
                            }
                            else
                            {
                                if (data.CurrentDay != DayOfWeek.Saturday && data.CurrentDay != DayOfWeek.Sunday)
                                {
                                    if (RANDOM.Next(365) < 20)
                                        ptr->SetMindset(EMindset.Vacationing);
                                    else
                                        ptr->SetMindset(EMindset.Working);
                                }
                                else
                                {
                                    if (RANDOM.Next(365) < 20)
                                        ptr->SetMindset(EMindset.Vacationing);
                                    else
                                        ptr->SetMindset(EMindset.DayOff);
                                }
                            }
                        }

                    });
            }
        }
        public unsafe override void PerformSimulationStage(SimulationData data)
        {
            _data = data;

            fixed (Human* humanptr = data.Humans)
            {
                Human* startPtr = humanptr;
                Parallel.For(0, _data.Humans.Length, Constants.DEFAULT_PARALLELOPTIONS,
                    index =>
                    {
                        Human* ptr = startPtr + index;

                        if (ptr->IsDead())
                            return;

                        //Handle each Human like the component specifies through the HandleHuman method
                        for (int i = 0; i < _simulationIntervall; i++)
                        {
                            HandleHuman(ptr);
                        }
                    });
            }
        }
 public override void PerformSimulationStage(SimulationData data)
 {
     #if DEBUG
     Console.WriteLine("DEBUG SIMULATION TICK");
     #endif
 }
Example #35
0
        private unsafe void UpdateHumanChangeToCell(Human* hptr, SimulationData data, EAge previousAge)
        {
            EAge newAge = hptr->GetAge();

            if (previousAge != newAge)
            {

                lock (data.Cells[hptr->CurrentCell])
                {
                    PopulationCell currentcell = data.Cells[hptr->CurrentCell];

                    if (hptr->GetGender() == EGender.Female)
                    {
                        if (newAge == EAge.Child)
                        {
                            --currentcell.FemaleBabies;
                            ++currentcell.FemaleChildren;
                        }
                        else if (newAge == EAge.Adult)
                        {
                            --currentcell.FemaleChildren;
                            ++currentcell.FemaleAdults;
                        }
                        else if (newAge == EAge.Senior)
                        {
                            --currentcell.FemaleAdults;
                            ++currentcell.FemaleSeniors;
                        }
                    }
                    else
                    {
                        if (newAge == EAge.Child)
                        {
                            --currentcell.MaleBabies;
                            ++currentcell.MaleChildren;
                        }
                        else if (newAge == EAge.Adult)
                        {
                            --currentcell.MaleChildren;
                            ++currentcell.MaleAdults;
                        }
                        else if (newAge == EAge.Senior)
                        {
                            --currentcell.MaleAdults;
                            ++currentcell.MaleSeniors;
                        }
                    }
                }
            }
        }
Example #36
0
        public unsafe override void PerformSimulationStage(SimulationData data)
        {
            _counter = ++_counter;

            if (_counter % TicksPerYear != 0) return;

            // Year(s) have passed
            #if DEBUG
            Console.WriteLine(YearsPerTick.ToString() + " Year(s) have passed!");
            #endif
            var deadPeople = new List<HumanSnapshot>();

            fixed (Human* humanptr = data.Humans)
            {
                Human* startPtr = humanptr;

                Parallel.For(0, data.Humans.Length, Constants.DEFAULT_PARALLELOPTIONS,
                    index =>
                    {
                        Human* human = startPtr + index;

                        if (human->IsDead())
                            return;

                        EAge previousAge = human->GetAge();

                        if (_counter % TicksPerLeapYear == 0)
                            human->DoAgeTick((byte)(YearsPerTick + 1));                 // "LeapTick" we need to increase YearsPerTick for this tick
                        else
                            human->DoAgeTick((byte)YearsPerTick);

                        UpdateHumanChangeToCell(human, data, previousAge);
                        AssignProfession(human, previousAge);

                        if (human->GetAgeInYears() <= AgeLimit) return;

                        lock (deadPeople)
                        {
                            deadPeople.Add(HumanSnapshot.InitializeFromRuntime((byte)human->GetGender(),
                                (byte)human->GetAgeInYears(), (byte)human->GetProfession(),
                                human->HomeCell, human->CurrentCell, false));
                        }

                        human->KillHuman();
                        var genderIndex = (int)human->GetGender();
                        genderIndex = genderIndex == 128 ? 0 : 4;
                        switch (human->GetAge())
                        {
                            case EAge.Baby:
                                break;
                            case EAge.Child:
                                genderIndex++;
                                break;
                            case EAge.Adult:
                                genderIndex += 2;
                                break;
                            case EAge.Senior:
                                genderIndex += 3;
                                break;
                        }

                        lock (data.Cells[human->CurrentCell])
                        {
                            PopulationCell currentCell = data.Cells[human->CurrentCell];
                            currentCell.Data[genderIndex]--;
                            if (human->IsInfected())
                            {
                                --currentCell.Infecting;

                                if (human->IsSpreading())
                                    --currentCell.Spreading;
                                if (human->IsDiseased())
                                    --currentCell.Diseased;
                            }
                        }
                    });
            }

            lock (data.Deaths)
                data.AddDeadPeople(deadPeople);
            #if DEBUG
            Console.WriteLine("Dead people this Iteration: " + deadPeople.Count);
            Console.WriteLine("Total dead people: " + data.DeathCount);
            #endif
        }
Example #37
0
        public override void PerformSimulationStage(SimulationData data)
        {
            _data = data;
            fixed (Human* humanptr = _data.Humans)
            {
                Human* startPtr = humanptr;

                Parallel.For(0, _data.Humans.Length, Constants.DEFAULT_PARALLELOPTIONS,
                    index =>
                    {
                        Human* ptr = startPtr + index;

                        //Stationary Mindset implies the human chosen won't move this day regardless of profession
                        //If the human is dead he won't move....
                        if (ptr->IsDead() ||
                            ptr->GetMindset() == PopulationData.EMindset.Stationary)
                        {
                            return;
                        }
                        //Travelling implies ignoring the Mindset until the human reached its Destination
                        else if (ptr->IsTravelling())
                        {
                            //reduce counter, if counter == 0 remove flag travelling else continue
                            --ptr->TravellingCounter;

                            if (ptr->TravellingCounter == 0)
                            {
                                ptr->SetTravelling(false);
                                MoveHuman(ptr, ptr->DesiredCell);
                            }
                            else
                            {
                                //CurrentPosition + DesiredPosition
                                int currentX = ptr->CurrentCell % _data.ImageWidth;
                                int currentY = ptr->CurrentCell / _data.ImageWidth;
                                int desiredX = ptr->DesiredCell % _data.ImageWidth;
                                int desiredY = ptr->DesiredCell / _data.ImageWidth;

                                //The Desiredposition might be far away, farther than the human can travel in one step
                                int travelDistanceX = Math.Abs(currentX - desiredX);
                                if (travelDistanceX > 350)
                                    travelDistanceX = 350;

                                int travelDistanceY = Math.Abs(currentY - desiredY);
                                if (travelDistanceY > 350)
                                    travelDistanceY = 350;

                                int nextCell = 0;

                                if (currentX < desiredX)
                                {
                                    if (currentY < desiredY)
                                    {
                                        nextCell = ptr->CurrentCell + travelDistanceX + travelDistanceY * _data.ImageWidth;

                                    }
                                    else
                                    {
                                        nextCell = ptr->CurrentCell + travelDistanceX - travelDistanceY * _data.ImageWidth;
                                    }
                                }
                                else
                                {
                                    //y-currentposition < y desiredposition
                                    if (currentY < desiredY)
                                    {
                                        nextCell = ptr->CurrentCell - travelDistanceX + travelDistanceY * _data.ImageWidth;
                                    }
                                    else
                                    {
                                        nextCell = ptr->CurrentCell - travelDistanceX - travelDistanceY * _data.ImageWidth;
                                    }
                                }

                                //TODO |h| Make an algorith that tries another route?
                                if (_data.Cells[nextCell] == null)
                                    nextCell = ptr->CurrentCell;

                                MoveHuman(ptr, nextCell);

                            }
                        }
                        //Staying Home doesn't vary no matter what profession the human is having.
                        else if (ptr->GetMindset() == PopulationData.EMindset.HomeStaying)
                        {
                            if (_data.CurrentHour > 6 && _data.CurrentHour < 19)
                            {
                                if (!ptr->IsAtHome())
                                {
                                    if (RANDOM.Next(3) == 0)
                                        LetHumanTravelHome(ptr);
                                }
                                else
                                {
                                    if (RANDOM.Next(5) == 0)
                                        LetHumanTravel(ptr, FindCellInReach(ptr->CurrentCell, 2, 75));
                                }
                            }
                            else if (_data.CurrentHour == 19)
                            {
                                if (!ptr->IsAtHome())
                                    LetHumanTravelHome(ptr);
                            }
                            else
                                return;
                            //chance every day to go out 1-3 hours
                            //if ill -> go to hospital
                            //if healthy wander around aimlessly in departement (short range)
                        }
                        else if (ptr->GetMindset() == EMindset.Vacationing)
                        {
                            if (_data.CurrentHour == 8 && ptr->IsAtHome())
                            {
                                LetHumanTravel(ptr, FindCellInReach(ptr->CurrentCell, 400, 800));
                            }
                            else if (_data.CurrentHour == 6 && !ptr->IsAtHome())
                            {
                                if (RANDOM.Next(14) == 13)
                                {
                                    LetHumanTravelHome(ptr);
                                }
                            }
                            else
                                return;
                        }
                        //Handle Movement for Mindsets which are dependent on the profession od the selected human
                        else
                        {
                            switch (ptr->GetProfession())
                            {
                                case EProfession.Pupil: MovePupil(ptr); break;
                                case EProfession.Student: MoveStudent(ptr); break;
                                case EProfession.Housewife: MoveHousewife(ptr); break;
                                case EProfession.Plumber: MovePlumber(ptr); break;
                                case EProfession.DeskJobber: MoveDeskJobber(ptr); break;
                                case EProfession.Commuter: MoveCommuter(ptr); break;
                                case EProfession.TravellingSalesman: MoveTravellingSalesman(ptr); break;
                                default: return;
                            }
                        }
                    });
            }
        }
Example #38
0
        // -------------------------------------------------------------------
        // Private
        // -------------------------------------------------------------------
        private SimulationStats Simulate(Simulation simulation)
        {
            Diagnostic.Info("Starting simulation for " + simulation.Class);

            // Create the struct and pass it to the logic
            ISimulationData simulationData = new SimulationData(this.data, simulation, this.randomValues);

            // Todo: choose which modules to use
            IList<ISimulationModule> modules = new List<ISimulationModule>
                                                   {
                                                       new SimulationBasicAttack()
                                                   };

            if (simulationData.Class.Skills != null)
            {
                foreach (D3Skill skill in simulationData.Class.Skills)
                {
                    modules.Add(new SimulationBasicSkill(skill.Name));
                }
            }

            foreach (ISimulationModule module in modules)
            {
                simulationData.ClearTargets();
                simulationData.CurrentTime = 0.0f;
                SimulationSampleSet sampleSet = module.Simulate(simulationData);
                if (sampleSet == null)
                {
                    Diagnostic.Warning("No sample returned for {0}", module.Name);
                    continue;
                }

                simulationData.Stats.SampleSets.Add(sampleSet);
            }

            return simulationData.Stats;
        }