Esempio n. 1
0
    private static void MakeMove(Game game, Guid playerID, string serverURL)
    {
        var mc     = new MonteCarlo();
        var column = mc.SuggestMove(game, playerID);

        API.MakeMove(playerID, serverURL, column, teamPassword);
    }
Esempio n. 2
0
        public bool PrepararSimulacion(int semilla = int.MinValue)
        {
            estado       = 0;
            TiempoActual = 0;

            if (servidores.Count() == 0)
            {
                return(false);
            }
            if (frecuencias.Count() == 0)
            {
                return(false);
            }

            clientes.Clear();

            if (semilla == int.MinValue)
            {
                MonteCarlo.RandomSeed();
            }
            else
            {
                MonteCarlo.SetSeed(semilla);
            }

            eventos = MonteCarlo.GenerarEventos(TiempoSimulado, frecuencias);
            estado  = 1;
            return(true);
        }
Esempio n. 3
0
        public void Test_Fails_Impossible_Fight_Barely()
        {
            var cards  = gsl("Bash", "Inflame", "Strike");
            var enemy  = new GenericEnemy(100, 100, 33, 33);
            var player = new Player(potions: new List <Potion>()
            {
                new StrengthPotion(), new StrengthPotion()
            },
                                    relics: new List <Relic>()
            {
                new FusionHammer()
            });
            var deck = new Deck(cards, gsl(), gsl(), gsl());
            var fs   = new MonteCarlo(deck, enemy, player, firstHand: cards);
            var node = fs.SimAfterFirstDraw();

            Assert.AreEqual(0, node.Randoms.Count);
            Assert.AreEqual(1, node.Choices.Count);
            //also assert there is only one good path.
            var best = node.Choices.Max(el => el.GetValue());

            //var bb = GetBestLeaf(node.Randoms);
            //var hh = bb.AALeafHistory();
            Assert.AreEqual(-1, best.Value);
            Assert.AreEqual(-1, node.GetValue().Value);
        }
Esempio n. 4
0
        public void Test_Random_Playouts()
        {
            for (var loop = 0; loop < 100; loop++)
            {
                var rcount = (int)Rnd.Next(10);
                var relics = GetRandomRelics(rcount);

                var ccount = (int)Rnd.Next(20) + 3;
                var cards  = GetRandomCards(ccount);

                var       player    = new Player(relics: relics);
                var       enemy     = new Cultist(70, 70);
                var       deck      = new Deck(cards);
                var       mc        = new MonteCarlo(deck, enemy, player);
                var       histories = new List <double>();
                FightNode root;
                //can there ever be decreasing values? yes, when we re-explore a random draw and get a worse result.
                //that's too bad.
                for (var ii = 0; ii < 10; ii++)
                {
                    root = mc.SimIncludingDraw(1000);
                    histories.Add(root.Value.Value);
                }
                Assert.IsTrue(histories.First() == 100 || histories.First() < histories.Last());
            }
        }
Esempio n. 5
0
        public void Test_UsingEnlightenment_ToFindPath()
        {
            var cards = gsl("Strike", "Strike", "HeavyBlade", "Enlightenment+", "Bash");

            var enemy  = new Cultist(hp: 80, hpMax: 80);
            var player = new Player(hp: 1); //player must kill turn 2.

            //best line: play e+, bash (8+vuln), hb (21), strike (9) = 38.
            //turn 2: redraw same cards but play differently.  HB (21) S(9) b(12) = 42
            var deck = new Deck(cards, gsl(), gsl(), gsl());
            var fs   = new MonteCarlo(deck, enemy, player, firstHand: cards);
            var node = fs.SimAfterFirstDraw();

            Assert.AreEqual(1, node.GetValue().Value);
            //assert the right cards were played.
            var drawNode      = node.Choices.First();
            var enlightenment = drawNode.Choices.Single(el => el.Value.Value == 1);

            Assert.AreEqual(nameof(Enlightenment), enlightenment.FightAction.CardInstance.Card.Name);
            Assert.AreEqual(1, enlightenment.FightAction.CardInstance.UpgradeCount);

            var bash = enlightenment.Choices.Single(el => el.Value.Value == 1);

            Assert.AreEqual(nameof(Bash), bash.FightAction.CardInstance.Card.Name);
            Assert.AreEqual(0, bash.FightAction.CardInstance.UpgradeCount);
        }
Esempio n. 6
0
        }         // functor class

        // La segnatura dell'attuale delegate va bene anche per questo algo:
        // struct della coppia( pwd, kkey) sia in ingresso che in uscita.
        // Ciascun passo del loop avra' la chiave dinamica aggiornata.
        // Nel giro di andata verra' randomizzata dal MonteCarlo ciascuna figura
        // della stringa-chiave. Nel giro di ritorno la stringa-chiave verra' letta
        // da db e ad ogni passo verra' scandita la figura successiva e, conseguentemente
        // invocato il core.
        // La stringa-chiave va in un campo object della struct-coppia( pwd, kkey).
        // Su db va messo in un varchar o text, che deve essere NOT NULL e DEFAULT '0'.



        /// <summary>
        /// operazione bitwise:
        /// ----------------------------------------------------------
        ///		dove sono UGUALI i bit, il risultato ha il bit ZERO
        ///		dove sono DIVERSI i bit, il risultato ha il bit UNO
        ///			schema:
        ///			 UGUALI  -> ZERO
        ///			 DIVERSI -> UNO
        ///
        /// La sequenza di bit zero e' l'elemento neutro dell'operatore xor:
        ///		i bit zero dell'altro operando vanno in zero perche' uguali
        ///		i bit uno dell'altro operando vanno in uno perche' diversi
        ///
        /// La sequenza di bit uno e' l'operando che scambia i valori di ciascun bit:
        ///		i bit zero dell'altro operando vanno in uno perche' diversi
        ///		i bit uno dell'altro operando vanno in zero perche' uguali
        ///
        ///
        /// xor
        /// -----
        /// L'uso di un operando "alpha" su un operando "x" produce un risultato
        /// "y". L'applicazione dell'operatore xor agli operandi "alpha" e "y"
        /// porta in "x". Questa ciclicita' dell'operatore e' utilizzata nel
        /// presente algoritmo.
        ///
        ///
        /// and
        /// -----
        /// Considero ora l'operatore "and". L'uso di un operando "alpha"
        /// su un operando "x" produce un risultato "y". Tale risultato e'
        /// la "saturazione" verso il basso di "x" mediante "alpha". Quindi
        /// "y" minore o uguale a "x" e le successive applicazioni di
        /// "alpha" ad "y" mediante "and" portano ancora a "y".
        ///
        /// or
        /// ------
        /// Considero ora l'operatore "or". L'uso di un operando "alpha"
        /// su un operando "x" produce un risultato "y". Tale risultato e'
        /// la "saturazione" verso l'alto di "x" mediante "alpha". Quindi
        /// "y" maggiore o uguale a "x" e le successive applicazioni di
        /// "alpha" ad "y" mediante "or" portano ancora a "y".
        ///
        ///
        ///             1110001   AND
        ///				0010100
        ///		   ---------------------
        ///			bin	0010000
        ///			dec		 16
        ///
        ///			0010100   AND
        ///			0010000
        ///			----------------
        ///			0010000 == 16 dec quindi il risultato e' saturo in AND
        ///
        ///
        ///				1110001    OR
        ///			    0010100
        ///		   ---------------------
        ///			bin	1110101
        ///			dec     117
        ///
        ///			    1110101   OR
        ///			    0010100
        ///		   ---------------------
        ///			    1110101 == 117 dec quindi il risultato e' saturo in OR
        ///
        ///
        ///			113	XOR
        ///			020
        ///		  -------
        ///			101
        ///
        ///				1110001    XOR        uguali a 0, diversi a 1
        ///			    0010100
        ///		   ---------------------
        ///			bin	1100101
        ///			dec     101
        ///
        ///
        ///
        ///
        ///
        ///
        /// </summary>


        // una specifica implementazione di una funzione di questa categoria
        internal static CryptoEngine.theReturnType xorMultiCrypto_andata(
            CryptoEngine.theReturnType input)
        {
            int        sequenceLength = input.cryptedSequence.Length;
            MonteCarlo mc             = new MonteCarlo();// seme dipendente dall'orario

            System.Text.StringBuilder kkey_accumulator = new System.Text.StringBuilder(sequenceLength);
            System.Text.StringBuilder sequence_temp    = new System.Text.StringBuilder(sequenceLength);
            for (int c = 0; c < sequenceLength; c++)
            {
                // BEGIN solo andata
                int    scalar_key     = mc.next_integer(32, 125);
                string scalar_key_str = "";
                if (100 > scalar_key)
                {
                    scalar_key_str += "0";
                }                // else e' gia' di tre cifre
                scalar_key_str += scalar_key.ToString();
                kkey_accumulator.Append(scalar_key_str);
                // END solo andata
                sequence_temp.Append((char)(input.cryptedSequence[c] ^ scalar_key));
            }
            input.cryptedSequence = sequence_temp.ToString();    // pwd
            input.kkey            = kkey_accumulator.ToString(); // kkey multi
            // ready
            return(input);
        }        // end xorMultiCrypto_andata
Esempio n. 7
0
    private static void test01()

    //****************************************************************************80
    //
    //  Purpose:
    //
    //    TEST01 uses TRIANGLE_SAMPLE_01 with an increasing number of points.
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    15 August 2009
    //
    //  Author:
    //
    //    John Burkardt
    //
    {
        const int f_num = 3;

        double[] t =
        {
            1.0, 0.0,
            0.0, 1.0,
            0.0, 0.0
        };

        Console.WriteLine("");
        Console.WriteLine("TEST01");
        Console.WriteLine("  Sample using TRIANGLE_UNIT_SAMPLE_01");
        Console.WriteLine("  Integrate TRIANGLE_UNIT_INTEGRAND_03");
        Console.WriteLine("  Integration region is the unit triangle.");
        Console.WriteLine("");
        Console.WriteLine("  Use an increasing number of points P_NUM.");
        Console.WriteLine("  Note that the sample routine is a \"bad\" sampler.");

        int seed = 123456789;

        Console.WriteLine("");
        Console.WriteLine("     P_NUM      X^2             X*Y             Y^2");
        Console.WriteLine("");

        int p_num = 1;

        while (p_num <= 65536)
        {
            double[] result = MonteCarlo.triangle_monte_carlo(t, p_num, f_num, MonteCarlo.triangle_unit_sample_01,
                                                              MonteCarlo.triangle_integrand_03, ref seed);

            Console.WriteLine("  " + p_num.ToString(CultureInfo.InvariantCulture).PadLeft(8)
                              + "  " + result[0].ToString(CultureInfo.InvariantCulture).PadLeft(14)
                              + "  " + result[1].ToString(CultureInfo.InvariantCulture).PadLeft(14)
                              + "  " + result[2].ToString(CultureInfo.InvariantCulture).PadLeft(14) + "");

            p_num = 2 * p_num;
        }
    }
Esempio n. 8
0
        public void Test_ExploringDrawSpace()
        {
            var cards  = gsl("Strike", "Defend");
            var enemy  = new Cultist(hp: 1, hpMax: 1);
            var player = new Player(hp: 1, maxEnergy: 1, drawAmount: 1);
            var deck   = new Deck(cards, gsl(), gsl(), gsl());
            var fs     = new MonteCarlo(deck, enemy, player);
            var root   = fs.SimIncludingDraw();

            //there should be two randomChoice nodes
            Assert.AreEqual(2, root.Choices.Count);
            Assert.AreEqual(0, root.Randoms.Count);

            foreach (var r in root.Choices)
            {
                //var v = r.GetValue();
                //endturn and play your single card.
                Assert.AreEqual(2, r.Choices.Count);
                Assert.AreEqual(0, r.Randoms.Count);

                //player can always win the fight.
                Assert.AreEqual(1, r.GetValue().Value);
            }

            //draw orders:
            // S* -win
            // DS* win
            // DD* lose
            //so Value should be 75 and the tree should be exhausted.

            // S win
            // D
            //  S  win
            //  D  lose
        }
Esempio n. 9
0
        private void buttonStart_Click(object sender, EventArgs e)
        {
            //set parameters
            Parameters parameters = new Parameters();

            parameters.InitialPrice  = Convert.ToDouble(textBoxInitialPrice.Text);
            parameters.ExercisePrice = Convert.ToDouble(textBoxExercisePrice.Text);
            parameters.UpGrowth      = Convert.ToDouble(textBoxUpGrowth.Text);
            parameters.DownGrowth    = Convert.ToDouble(textBoxDownGrowth.Text);
            parameters.InterestRate  = Convert.ToDouble(textBoxInterestRate.Text);
            parameters.Periods       = Convert.ToInt64(textBoxPeriods.Text);
            parameters.Simulations   = Convert.ToInt64(textBoxSimulations.Text);

            //start simulation
            MonteCarlo monteCarlo = new MonteCarlo(parameters);
            Stopwatch  stopwatch  = new Stopwatch();

            stopwatch.Start();
            var simulationResult = monteCarlo.Simulate();

            stopwatch.Stop();

            //collect results
            var elapsedTime = stopwatch.ElapsedMilliseconds;
            var itemCount   = listBoxResults.Items.Count;
            var result      = $"{itemCount + 1} -> {simulationResult:C} ({elapsedTime:##,###} secs)";

            //display results
            listBoxResults.Items.Insert(itemCount, result);
            stopwatch.Reset();
        }
        public static void Solve()
        {
            const int    iterations   = 1000;
            const double youngModulus = 2.1e8;

            var domainMapper = new CantileverStochasticDomainMapper(new[] { 0d, 0d, 0d });
            var evaluator    = new StructuralStochasticEvaluator(youngModulus, domainMapper);
            var m            = new MonteCarlo(iterations, evaluator, evaluator);

            m.Evaluate();
            double[] expectedMeanValueResponse = new double[]
            {
                1.5999674517697445E-08, -2.399309224401548E-08
            };

            for (int i = 0; i < expectedMeanValueResponse.Length; i++)
            {
                Assert.Equal(expectedMeanValueResponse[i], m.MeanValueResponse[i], 10);
            }
            double[] expectedStandardDeviationResponse = new double[]
            {
                4.3180461976960273E-12, 2.6374139668652252E-12
            };

            for (int i = 0; i < expectedStandardDeviationResponse.Length; i++)
            {
                Assert.Equal(expectedStandardDeviationResponse[i], m.StandardDeviationResponse[i], 10);
            }
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            try {
                PrintLogo();
                Console.WriteLine(Directory.GetCurrentDirectory());

                ComandManager commanager = new ComandManager();
                ITemplate     monteCarlo = new MonteCarlo();

                IComand run = new Run();
                (run as Run).Add(monteCarlo);

                IComand cnew = new New();
                (cnew as New).Add(monteCarlo);

                commanager.Add(cnew);
                commanager.Add(run);

                if (args.Length == 0)
                {
                    commanager.Help();
                }
                else
                {
                    commanager.Start(args);
                }
            }
            catch (Exception exc) {
                Console.WriteLine(exc);
                Console.WriteLine("Exception was saved at 'log_exception.txt' file");
                StreamWriter sw = new StreamWriter("log_exception.txt", true, Encoding.Unicode);
                sw.WriteLine(exc);
                sw.Close(); sw.Dispose();
            }
        }
Esempio n. 12
0
        public void Test_Longer_Setup()
        {
            //Correct strategy is to take damage the first round.
            var cis = GetCis("Defend", "Strike", "Defend", "Inflame", /* AFTER */ "Inflame", "Inflame", "Inflame", "Defend");

            var enemyStatuses = GSS(new Feather(), 10);

            enemyStatuses.AddRange(GSS(new Strength(), -10));
            var enemy     = new GenericEnemy(amount: 1, count: 5, hp: 14, hpMax: 14, statuses: enemyStatuses);
            var player    = new Player(drawAmount: 4, hp: 10);
            var firstHand = new List <string>()
            {
                "Inflame", "Inflame", "Inflame", "Defend"
            };
            var deck = new Deck(cis);

            var fs   = new MonteCarlo(deck, enemy, player, firstHand: firstHand);
            var node = fs.SimAfterFirstDraw();

            Assert.AreEqual(1, node.Choices.Count);
            //also assert there is only one good path.
            var best = node.Choices.Max(el => el.GetValue());

            var bests = node.Choices.Where(el => el.GetValue().Value == 5);
            //this is good but there can still be dumb paths that are longer.

            var win     = bests.First();
            var hh      = win.GetTurnHistory();
            var winNode = GetBestLeaf(node);

            Assert.AreEqual(5, hh.Count());

            Assert.AreEqual(5, best.Value);
            Assert.AreEqual(5, node.GetValue().Value);
        }
Esempio n. 13
0
        private void buttonStart_Click(object sender, EventArgs e)
        {
            if (simulationCount == 0)
            {
                toolStripProgressBar.Value = 0;
            }

            //set parameters
            Parameters parameters = new Parameters();

            parameters.InitialPrice  = Convert.ToDouble(textBoxInitialPrice.Text);
            parameters.ExercisePrice = Convert.ToDouble(textBoxExercisePrice.Text);
            parameters.UpGrowth      = Convert.ToDouble(textBoxUpGrowth.Text);
            parameters.DownGrowth    = Convert.ToDouble(textBoxDownGrowth.Text);
            parameters.InterestRate  = Convert.ToDouble(textBoxInterestRate.Text);
            parameters.Periods       = Convert.ToInt64(textBoxPeriods.Text);
            parameters.Simulations   = Convert.ToInt64(textBoxSimulations.Text);

            MonteCarlo monteCarlo = new MonteCarlo(parameters);
            Stopwatch  stopwatch  = new Stopwatch();
            int        itemCount  = 0;

            simulationCount++;
            toolStripStatusLabel.Text = $@"Simulation Count: {simulationCount}";

            //first start simulation and calculate result
            Task <string> simulationTask = Task <string> .Factory.StartNew(
                () =>
            {
                //start simulation
                stopwatch.Start();
                double simulationResult = monteCarlo.Simulate();
                stopwatch.Stop();

                //collect results
                var elapsedTime = stopwatch.ElapsedMilliseconds;
                itemCount       = listBoxResults.Items.Count;
                string result   = $"{itemCount + 1} -> {simulationResult:C} ({elapsedTime:##,###} secs)";
                stopwatch.Reset();

                return(result);
            });

            //then after first task completed, update the UI. Because of it is UI, do this task
            //in UI thread by using TaskScheduler.FromCurrentSynchronizationContext
            simulationTask.ContinueWith(
                (previous) =>
            {
                //display results
                listBoxResults.Items.Insert(itemCount, previous.Result);

                simulationCount--;
                toolStripStatusLabel.Text = $@"Simulation Count: {simulationCount}";

                toolStripProgressBar.Value = 100 - 100 / (listBoxResults.Items.Count + simulationCount) * simulationCount;
            },
                TaskScheduler.FromCurrentSynchronizationContext());
        }
Esempio n. 14
0
    /* Main function */
    public static void Main()
    {
        /* Create object mcarlo */
        MonteCarlo mcarlo = new MonteCarlo(4, 40000000);

        /* Count the time that has elapsed */
        Stopwatch stopWatch = new Stopwatch();

        stopWatch.Start();

        /* Create the threads */
        Thread worker1 = new Thread(new ThreadStart(() => mcarlo.worker(0)));

        worker1.Name = "worker1";

        Thread worker2 = new Thread(new ThreadStart(() => mcarlo.worker(1)));

        worker2.Name = "worker2";

        Thread worker3 = new Thread(new ThreadStart(() => mcarlo.worker(2)));

        worker3.Name = "worker3";

        Thread worker4 = new Thread(new ThreadStart(() => mcarlo.worker(3)));

        worker4.Name = "worker4";

        /* Threads start their work */
        worker1.Start();
        worker2.Start();
        worker3.Start();
        worker4.Start();

        /* Threads finish their work */
        worker1.Join();
        worker2.Join();
        worker3.Join();
        worker4.Join();

        /* Stop the clock */
        stopWatch.Stop();
        /* Get the elapsed time as a TimeSpan value. */
        TimeSpan ts = stopWatch.Elapsed;

        Console.WriteLine();
        Console.WriteLine("Elapsed time:");
        /* Format and display the TimeSpan value. */
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                           ts.Hours, ts.Minutes, ts.Seconds,
                                           ts.Milliseconds / 10);

        Console.WriteLine(elapsedTime, "RunTime");

        /* Print the final pi */
        mcarlo.print_pi();
    }
Esempio n. 15
0
        }        // end commonCore

        // una specifica implementazione di una funzione di questa categoria
        internal static CryptoEngine.theReturnType xorCrypto_andata(
            CryptoEngine.theReturnType input)
        {
            // solo in andata: preparo la chiave di criptazione
            MonteCarlo mc = new MonteCarlo();                 // seme dipendente dall'orario

            input.kkey = mc.next_integer(32, 125).ToString(); // il commonCore lo vuole stringa per compatibilita' col db (quindi col ritorno)
            // end solo in andata
            return(commonCore(input));
        }        // end xorCryptoService
Esempio n. 16
0
        public void UpdateApplication(Carteira carteira, MonteCarlo mc, int countLoops, int totalLoops)
        {
            UpdatesToAdd updt = new UpdatesToAdd();

            updt.carteira   = carteira;
            updt.mc         = mc;
            updt.countLoops = countLoops;
            updt.totalLoops = gpRunner.pool.iterationNumber;
            updatesToAdd.Add(updt);
        }
Esempio n. 17
0
        private static void SolveCantileverWithStochasticMaterial()
        {
            const int    iterations   = 1000;
            const double youngModulus = 2.1e8;

            var domainMapper = new CantileverStochasticDomainMapper(new[] { 0d, 0d, 0d });
            var evaluator    = new StructuralStochasticEvaluator(youngModulus, domainMapper);
            var m            = new MonteCarlo(iterations, evaluator, evaluator);

            m.Evaluate();
        }
Esempio n. 18
0
        public void Solve()
        {
            const int    iterations   = 1000;
            const double youngModulus = 2.1e8;

            var domainMapper = new CantileverStochasticDomainMapper(new[] { 0d, 0d, 0d });
            var realizer     = new GiannisStructuralStochasticRealizer(youngModulus, domainMapper);
            var evaluator    = new StructuralStochasticEvaluator(youngModulus, domainMapper);
            var m            = new MonteCarlo(iterations, realizer, evaluator);

            m.Evaluate();
        }
Esempio n. 19
0
        public Form1()
        {
            InitializeComponent();

            data       = new Data();
            display    = new Display(pictureBox, data);
            execute    = new Execute(display, data);
            neighbor   = new Neighbor(data, execute, display);
            monteCarlo = new MonteCarlo(display, data);

            Set_Limits();
        }
Esempio n. 20
0
        public void Test_Using_Inflame()
        {
            var cards = gsl("Strike", "Defend", "Inflame", "Defend", "Defend");

            var enemy  = new GenericEnemy(4, 4, 8, 8);
            var player = new Player(hp: 1);
            var deck   = new Deck(cards, gsl(), gsl(), gsl());
            var fs     = new MonteCarlo(deck, enemy, player, firstHand: cards);
            var node   = fs.SimAfterFirstDraw();

            Assert.AreEqual(1, node.GetValue().Value);
        }
Esempio n. 21
0
    private static void test01(string[] args)
    {
        //
        //  Get the spatial dimension M.
        //
        int m, n, seed;

        try
        {
            m = Convert.ToInt32(args[0]);
        }
        catch (Exception)
        {
            Console.WriteLine("");
            Console.WriteLine("  Enter the spatial dimension M (1 or greater)");
            m = Convert.ToInt32(Console.Read());
        }

        m = Math.Max(1, m);

        //
        //  Get the number of points N.
        //
        try
        {
            n = Convert.ToInt32(args[1]);
        }
        catch (Exception)
        {
            Console.WriteLine("");
            Console.WriteLine("  Enter the number of points N (1 or greater):");
            n = Convert.ToInt32(Console.Read());
        }

        n = Math.Max(1, n);

        //
        //  Get the seed S.
        //
        try
        {
            seed = Convert.ToInt32(args[2]);
        }
        catch (Exception)
        {
            Console.WriteLine("");
            Console.WriteLine("  Enter the seed S (1 or greater):");
            seed = Convert.ToInt32(Console.Read());
        }
        seed = Math.Max(1, seed);

        MonteCarlo.calc(m, n, seed);
    }
Esempio n. 22
0
        public void Test_Basic()
        {
            //I want to validate that I am properly generating all outcomes.
            var cards = gsl("Strike");

            var enemy   = new Cultist(1);
            var player  = new Player(hp: 1);
            var deck    = new Deck(cards, gsl(), gsl(), gsl());
            var fs      = new MonteCarlo(deck, enemy, player, firstHand: cards);
            var results = fs.SimAfterFirstDraw();

            Assert.AreEqual(1, results.Value.Value);
        }
Esempio n. 23
0
 public OutputModel(InputModel input)
 {
     person = new Person(input);
     if (person.concerns[2])
     {
         expectedReturn = -0.05;
     }
     time         = (person.retirementDate - DateTime.Now.Year);
     carlo        = new MonteCarlo(person.lumpSum, expectedReturn, standardDeviation, time);
     brokerage    = new Brokerage(carlo, person);
     qualified    = new Qualified(brokerage, person);
     nonQualified = new NonQualified(brokerage, person);
     assetIncome  = Math.Round(person.assetIncome, 2);
 }
Esempio n. 24
0
    /* Main function */
    public static void Main()
    {
        /* Create object mcarlo */
        MonteCarlo mcarlo = new MonteCarlo(4, 40000000);

        /* Count the time that has elapsed */
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();

        /* Create the threads */
        Thread worker1 = new Thread(new ThreadStart(()=> mcarlo.worker(0)));
        worker1.Name = "worker1";

        Thread worker2 = new Thread(new ThreadStart(() => mcarlo.worker(1)));
        worker2.Name = "worker2";

        Thread worker3 = new Thread(new ThreadStart(() => mcarlo.worker(2)));
        worker3.Name = "worker3";

        Thread worker4 = new Thread(new ThreadStart(() => mcarlo.worker(3)));
        worker4.Name = "worker4";

        /* Threads start their work */
        worker1.Start();
        worker2.Start();
        worker3.Start();
        worker4.Start();

        /* Threads finish their work */
        worker1.Join();
        worker2.Join();
        worker3.Join();
        worker4.Join();

        /* Stop the clock */
        stopWatch.Stop();
        /* Get the elapsed time as a TimeSpan value. */
        TimeSpan ts = stopWatch.Elapsed;

        Console.WriteLine();
        Console.WriteLine("Elapsed time:");
        /* Format and display the TimeSpan value. */
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
        Console.WriteLine(elapsedTime, "RunTime");

        /* Print the final pi */
        mcarlo.print_pi();
    }
Esempio n. 25
0
        static void Main(string[] args)
        {
            var limits = new List <LimitPair>
            {
                new LimitPair(Za, Zb),
                new LimitPair(Ya, Yb),
                new LimitPair(Xa, Xb)
            };
            var monteCarlo = new MonteCarlo(F, limits);

            Console.WriteLine(monteCarlo.Solve());
            var rec = new RectangularTriple(F, limits);

            Console.WriteLine(rec.Solve());
        }
Esempio n. 26
0
        public void Test_PommelStrike_Randomness()
        {
            var cards = gsl("Defend", "Strike", "Inflame", "PommelStrike+");

            var enemy  = new GenericEnemy(15, 3, 20, 20);
            var player = new Player(drawAmount: 1);
            var deck   = new Deck(cards, gsl(), gsl(), gsl());
            var fs     = new MonteCarlo(deck, enemy, player, firstHand: gsl("PommelStrike+"));
            var node   = fs.SimAfterFirstDraw();

            Assert.AreEqual(1, node.Choices.Count);
            var ps = node.Choices.First().Choices.Single(el => el.FightAction.CardInstance?.Card.Name == nameof(PommelStrike));

            Assert.AreEqual(0, ps.Randoms.Count()); //we only draw the one reality that the deck was shuffled into.
        }
Esempio n. 27
0
        /*   public void printMonteCarlo()
         * {
         *     for (int i = 0; i < monteCarlo.Count; i++)
         *     {
         *         MonteCarlo mC = monteCarlo[i];
         *         mC.printPerformance("MC(" + i + ")");
         *     }
         * }*/

        /*    public void ordernaMonteCarlo(Consts.OrdemEstatistica ordem)
         *  {
         *      for (int i = 0; i < monteCarlo.Count - 1; i++)
         *      {
         *
         *          for (int j = i + 1; j < monteCarlo.Count; j++)
         *          {
         *              MonteCarlo statI = monteCarlo[i];
         *              float vI = 0;
         *              MonteCarlo statJ = monteCarlo[j];
         *              float vJ = 0;
         *              if (ordem == Backtester.backend.Consts.OrdemEstatistica.CAPITAL_FINAL) vI = statI.getCapitalFinal();
         *              if (ordem == Backtester.backend.Consts.OrdemEstatistica.CAPITAL_FINAL) vJ = statJ.getCapitalFinal();
         *              if (vI > vJ)
         *              {
         *                  monteCarlo[j] = statI;
         *                  monteCarlo[i] = statJ;
         *              }
         *          }
         *
         *      }
         *
         *  }*/

        public Carteira runMonteCarlo(ICaller caller, String name)
        {
            MonteCarlo mC = new MonteCarlo(name);

            Utils.println("runMonteCarlo:" + name);
            Estatistica stat = runSingleBackTest(caller, mC).estatistica;

            stat.setDesc(getVarsValues());
            mC.setEstatistica(stat);
            mC.FinishStats(facade.formulaManager, carteira);
            mC.printPerformance("");
            caller.UpdateApplication(carteira, mC, countLoops_, totalLoops_);
            //monteCarlo.Add(mC);
            return(carteira);
        }
Esempio n. 28
0
        public static void Test_WildStrike_FightNode()
        {
            var player = new Player(drawAmount: 1);
            var enemy  = new Cultist(40, 40);
            var cis    = GetCis("Strike", "WildStrike");
            var deck   = new Deck(cis);
            var mc     = new MonteCarlo(deck, enemy, player, firstHand: gsl("WildStrike"));
            //testing: this should create one choice with the first draw (which is force)

            var root = mc.SimAfterFirstDraw(100);
            //this should create root C=> draw => Cwildstrike => [R,various keys with no duplication]
            var a = 43;
            //TODO fix this.
            //structure should be: root => 1 draw => play ws => 2 randoms for where the wound ended up.
        }
Esempio n. 29
0
        public void Test_Defending()
        {
            //It is now a requirement that all fights end before maxTurns
            //since we can't calculate value for incomplete fights.
            var cards = gsl("Defend", "Defend", "Strike");

            var enemy  = new GenericEnemy(amount: 5, count: 1, hp: 8, statuses: GSS(new Feather(), 5));
            var player = new Player(hp: 5); //fullblock first turn. 2nd turn take 5
            var deck   = new Deck(cards, gsl(), gsl(), gsl());
            var fs     = new MonteCarlo(deck, enemy, player, firstHand: cards);
            var node   = fs.SimAfterFirstDraw();
            var best   = GetBestLeaf(node);

            Assert.AreEqual(5, node.GetValue().Value);
        }
Esempio n. 30
0
        public void TestTradeSystem()
        {
            facade = new FacadeBacktester();
            Config      config      = new Config();
            TradeSystem tradeSystem = new TradeSystem(config);
            MonteCarlo  mc          = new MonteCarlo("teste");

            float    valorInicial = 100000;
            Carteira carteira     = new Carteira(facade, valorInicial, config, tradeSystem, mc);

            config.custoOperacao = 20f;

            tradeSystem.condicaoEntradaC = "GREATER(MME(C,9),MME(C,3))";
            tradeSystem.condicaoSaidaC   = "LOWER(MME(C,9),MME(C,3))";
            tradeSystem.condicaoEntradaV = "LOWER(MME(C,9),MME(C,3))";

            Periodo periodo = new Periodo("01-01-2017");
            Ativo   ativo   = new Ativo(facade, "TESTE", 100);
            Candle  candle  = new Candle(periodo, ativo);

            ativo.firstCandle = candle;
            candle.SetValor("MME(C,9)", 10);
            candle.SetValor("MME(C,3)", 5);
            candle.SetValor("SUBTRACT(L,MULTIPLY(STD(C,10),2))", 2);
            candle.SetValor("H", 10);
            candle.SetValor(tradeSystem.stopInicialC, 5);

            Formula formulaGreater = facade.formulaManager.GetFormula(tradeSystem.condicaoEntradaC);
            float   value          = formulaGreater.Calc(candle);

            Assert.IsTrue(value > 0, value + "<=0");

            Formula formulaLower = facade.formulaManager.GetFormula(tradeSystem.condicaoEntradaV);

            value = formulaLower.Calc(candle);
            Assert.IsTrue(value == 0, value + ">0");

            float result = tradeSystem.checaCondicaoEntrada(candle, config);

            Assert.IsTrue(result > 0, "result:" + result);

            candle.SetValor("MME(C,9)", 2);
            candle.SetValor("C", 2);
            candle.RemoveValor(tradeSystem.condicaoEntradaC);

            result = tradeSystem.checaCondicaoEntrada(candle, config);
            Assert.IsTrue(result == 0, "result:" + result);
        }
        public void Solve()
        {
            const int    iterations   = 1000;
            const double youngModulus = 2.1e8;

            var domainMapper = new CantileverStochasticDomainMapper(new [] { 0d, 0d, 0d });
            var realizer     = new StructuralStochasticRealizer(youngModulus, domainMapper);
            var evaluator    = new StructuralStochasticEvaluator(youngModulus, domainMapper);
            var m            = new MonteCarlo(iterations, realizer, evaluator);

            m.Evaluate();
            Assert.Equal(1.5999674517697445E-08, MonteCarloMeanValue[0], 10);
            Assert.Equal(-2.399309224401548E-08, MonteCarloMeanValue[1], 10);
            Assert.Equal(4.3180461976960273E-12, MonteCarloStandardDeviation[0], 10);
            Assert.Equal(2.6374139668652252E-12, MonteCarloStandardDeviation[1], 10);
        }