示例#1
0
        static void Main(string[] args)
        {
            string stratName   = args.Length < 1 ? "" : args[0];
            int    gamesToPlay = args.Length < 2 ? 100 : int.Parse(args[1]);

            Strategy strat;

            switch (stratName)
            {
            case "-random":
                strat = new RandomStrategy();
                break;

            case "-smart":
                strat = new SmartStrategy();
                break;

            case "-tracking":
                strat = new TrackingStrategy();
                break;

            default:
                strat = new RandomStrategy();
                break;
            }

            PlayGames(strat, gamesToPlay);
        }
示例#2
0
        public static IGameSettings Load(string board)
        {
            var allRows      = board.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            var rows         = allRows.Where(line => !line.StartsWith("{")).ToArray();
            var instructions = allRows.Where(line => line.StartsWith("{")).ToArray();

            var height = rows.Length;
            var width  = 0;

            var ghostSetup = FindHomeLocations(instructions);

            var ghosts = ghostSetup.Select(data =>
            {
                var scatterTarget = new CellLocation(data.ScatterTarget.X, data.ScatterTarget.Y);

                var frightenedStrategy = new RandomStrategy(new RandomDirectionPicker());

                return(new Ghost(data.Name,
                                 new CellLocation(data.StartingLocation.X, data.StartingLocation.Y),
                                 Direction.Left,
                                 data.Name switch
                {
                    GhostNames.Blinky => new DirectToStrategy(new DirectToPacManLocation()),
                    GhostNames.Clyde => new DirectToStrategy(new StaysCloseToPacManLocation(GhostNames.Clyde, scatterTarget)),
                    GhostNames.Inky => new DirectToStrategy(new InterceptPacManLocation(GhostNames.Blinky)),
                    GhostNames.Pinky => new DirectToStrategy(new DirectToExpectedPacManLocation()),
                    _ => new DirectToStrategy(new DirectToPacManLocation())
                },
                                 new DirectToStrategy(new DirectToGhostScatterTarget(scatterTarget)),
                                 frightenedStrategy,
                                 data.PillsToLeave));
            }).ToList();
示例#3
0
        public void TestStrategy()
        {
            IStrategy s       = new RoundRobinStrategy(3);
            int       matched = 0;

            // try 100 times
            for (int i = 1; i <= 100; i++)
            {
                if (s.NextPartition() == i % 3)
                {
                    matched++;
                }
            }
            Assert.Equal(100, matched);

            s       = new RandomStrategy(3);
            matched = 0;
            // try 100 times
            for (int i = 1; i <= 100; i++)
            {
                if (s.NextPartition() == i % 3)
                {
                    matched++;
                }
            }
            Assert.NotEqual(100, matched);
        }
示例#4
0
        public async Task <LiveChartModel> Visualize(DateTime date)
        {
            var ticksToShow = new ChartValues <decimal>();

            seriesCollection = new SeriesCollection
            {
                new LineSeries
                {
                    Values            = ticksToShow,
                    PointGeometrySize = 1,
                    PointForeground   = Brushes.Black,
                    Foreground        = Brushes.Black,
                },
            };

            var historyProvider = new FinamQuotesHistoryProvider(
                new FinamTicksParser(),
                new FinamCandlesParser(),
                new FinamQuotesHistoryClient(
                    new HistoryConfiguration()));

            Log("Load ticks");
            ticks = (await historyProvider.GetTicksHistory(
                         "GAZP",
                         date.Date,
                         date.Date.AddDays(1),
                         CancellationToken.None)).Ticks.ToList();
            Log($"{ticks.Count} ticks loaded");

            textBlock.Dispatcher.InvokeAsync(async() =>
            {
                using var strategy = new RandomStrategy(10);
                strategy.Subscribe(this);
                for (var i = 0; i < ticks.Count; i++)
                {
                    Log($"Tick {i} of {ticks.Count}");
                    var tick = ticks[i];
                    strategy.OnTick(tick);
                    ticksToShow.Add(tick.Value);
                    await Task.Delay(20);
                }

                var report = new Report(strategy);
                Log(report.ToString());
            });

            var ticksDates = ticks.Select(x => x.DateTime.ToString("HH:mm:ss")).ToList();

            return(new LiveChartModel
            {
                SeriesCollection = seriesCollection,
                Labels = ticksDates,
                MinY = ticks.Min(x => x.Value),
                MaxY = ticks.Max(x => x.Value),
            });
        }
示例#5
0
        public RandomStrategyTest()
        {
            var strategyMock = new Mock <IStrategy>();

            _p1  = new Player(strategyMock.Object, "p1");
            _p2  = new Player(strategyMock.Object, "p2");
            _p3  = new Player(strategyMock.Object, "p3");
            _p4  = new Player(strategyMock.Object, "p4");
            _sut = new RandomStrategy();
        }
        public void TestGenerateSmallBlueBubble()
        {
            RandomStrategy generateBubble = new RandomStrategy();
            Field          field          = new Field(10, 10);

            Cell bubble = generateBubble.GenerateBubble(field, BubbleSize.Small, BubbleColor.Blue);

            Assert.IsNotNull(bubble);
            Assert.AreEqual(BubbleSize.Small, bubble.Contain);
            Assert.AreEqual(BubbleColor.Blue, bubble.Color);
            Assert.IsTrue(bubble.Row >= 0);
            Assert.IsTrue(bubble.Row <= field.Height - 1);
            Assert.IsTrue(bubble.Column >= 0);
            Assert.IsTrue(bubble.Column <= field.Width - 1);
        }
        public void TestGenerationFailed()
        {
            RandomStrategy generateBubble = new RandomStrategy();
            Field          field          = new Field(10, 10);

            for (int i = 0; i < field.Height; i++)
            {
                for (int j = 0; j < field.Width; j++)
                {
                    field.Cells[i, j].Contain = BubbleSize.Big;
                    field.Cells[i, j].Color   = BubbleColor.Red;
                    field.EmptyCells--;
                }
            }


            Cell bubble = generateBubble.GenerateBubble(field, BubbleSize.Small, BubbleColor.Blue);
        }
        public void Return_Random_Position_Given_GameBoard()
        {
            var board = new int?[3][];

            board[0] = new int?[3] {
                1, 2, 1
            };
            board[1] = new int?[3] {
                2, null, 1
            };
            board[2] = new int?[3] {
                null, 1, 1
            };
            var strategy = new RandomStrategy();
            var position = strategy.CalculateNextMove(board);

            Assert.IsTrue((position.X == 1 && position.Y == 1) || (position.X == 2 && position.Y == 0));
        }
示例#9
0
        public void RandomStrategy_ReturnsProviderAccordingToRandomNumberGenerated()
        {
            // Arrange
            var mockRandom = new Mock <IRandomNumberGenerator>();

            mockRandom.SetupSequence(r => r.Next(It.IsAny <int>(), It.IsAny <int>())).Returns(1).Returns(0).Returns(2);
            var strategy = new RandomStrategy(mockRandom.Object);

            var providers = new List <IProvider>();

            providers.Add(new Provider("0"));
            providers.Add(new Provider("1"));
            providers.Add(new Provider("2"));

            // Act & Assert
            Assert.AreEqual("1", strategy.SelectProvider(providers).Get());
            Assert.AreEqual("0", strategy.SelectProvider(providers).Get());
            Assert.AreEqual("2", strategy.SelectProvider(providers).Get());
        }
示例#10
0
        public void TestGenerateThreeSmallBubbles()
        {
            RandomStrategy generateBubble = new RandomStrategy();
            Field          field          = new Field(10, 10);

            Cell[] bubbles = generateBubble.GenerateSmallBubbles(field, 3);

            Assert.IsNotNull(bubbles);
            Assert.AreEqual(BubbleSize.Small, bubbles[0].Contain);
            Assert.AreEqual(BubbleSize.Small, bubbles[1].Contain);
            Assert.AreEqual(BubbleSize.Small, bubbles[2].Contain);
            Assert.IsNotNull(bubbles[0].Color);
            Assert.IsNotNull(bubbles[1].Color);
            Assert.IsNotNull(bubbles[2].Color);
            Assert.IsTrue(bubbles[0].Row >= 0 && bubbles[0].Row <= field.Height - 1);
            Assert.IsTrue(bubbles[1].Row >= 0 && bubbles[1].Row <= field.Height - 1);
            Assert.IsTrue(bubbles[1].Row >= 0 && bubbles[1].Row <= field.Height - 1);
            Assert.IsTrue(bubbles[0].Column >= 0 && bubbles[0].Column <= field.Width - 1);
            Assert.IsTrue(bubbles[1].Column >= 0 && bubbles[1].Column <= field.Width - 1);
            Assert.IsTrue(bubbles[2].Column >= 0 && bubbles[2].Column <= field.Width - 1);
        }
示例#11
0
        public void Test1()
        {
            var frames = new List <IFrame>()
            {
                Mock.Of <IFrame>(m => m.Id == Guid.NewGuid()),
                Mock.Of <IFrame>(m => m.Id == Guid.NewGuid()),
                Mock.Of <IFrame>(m => m.Id == Guid.NewGuid()),
            };
            var physicalMemory = Mock.Of <IPhysicalMemory>();

            Mock.Get(physicalMemory).Setup(m => m.GetEnumerator()).Returns(frames.GetEnumerator());
            var strategy = new RandomStrategy(physicalMemory);

            for (var i = 0; i < 10; i++)
            {
                var pageId = Guid.NewGuid();

                var visitor = strategy.CreateReplacingVisitor(Mock.Of <IPageReference>(m => m.PageId == pageId));
                Assert.Contains(visitor.FrameId, frames.Select(f => f.Id));
                Assert.Equal(pageId, visitor.PageId);
            }
            Assert.Equal(10, strategy.PagesErrors);
        }
示例#12
0
        public void TestGenerateSmallBubbles_UniqueResult()
        {
            RandomStrategy generateBubble = new RandomStrategy();
            Field          field          = new Field(5, 5);

            for (int i = 0; i < field.Height; i++)
            {
                for (int j = 0; j < field.Width - 1; j++)
                {
                    field.Cells[i, j].Contain = BubbleSize.Big;
                    field.Cells[i, j].Color   = BubbleColor.Red;
                }
            }
            field.EmptyCells = 5;

            Cell[] bubbles = generateBubble.GenerateSmallBubbles(field, 5);

            Assert.IsTrue(bubbles.Any(x => x.Row == 2 && x.Column == 4));
            Assert.IsTrue(bubbles.Any(x => x.Row == 3 && x.Column == 4));
            Assert.IsTrue(bubbles.Any(x => x.Row == 4 && x.Column == 4));
            Assert.IsTrue(bubbles.Any(x => x.Row == 1 && x.Column == 4));
            Assert.IsTrue(bubbles.Any(x => x.Row == 2 && x.Column == 4));
        }
示例#13
0
        internal Ghost SetToEdible(IDirectionPicker directionPicker)
        {
            var strategy = new RandomStrategy(directionPicker);

            return(WithNewEdibleAndDirectionAndStrategy(GhostStatus.Edible, Direction.Opposite(), strategy));
        }
 public static void UseUnityRandom()
 {
     random = new RandomStrategyUnity();
 }
示例#15
0
        private void buttonStartFuzzing_Click(object sender, EventArgs e)
        {
            try
            {
                tabControl.SelectedTab          = tabPageOutput;
                buttonStartFuzzing.Enabled      = false;
                buttonSaveConfiguration.Enabled = false;
                buttonStopFuzzing.Enabled       = true;

                IterationCount             = 1;
                FaultCount                 = 0;
                textBoxIterationCount.Text = IterationCount.ToString();
                textBoxFaultCount.Text     = FaultCount.ToString();
                textBoxOutput.Text         = "";

                Dom       dom       = new Dom();
                DataModel dataModel = null;

                // Data Set
                Data fileData = new Data();
                if (Directory.Exists(textBoxTemplateFiles.Text))
                {
                    List <string> files = new List <string>();
                    foreach (string fileName in Directory.GetFiles(textBoxTemplateFiles.Text))
                    {
                        files.Add(fileName);
                    }

                    fileData.DataType = DataType.Files;
                    fileData.Files    = files;
                }
                else if (File.Exists(textBoxTemplateFiles.Text))
                {
                    fileData.DataType = DataType.File;
                    fileData.FileName = textBoxTemplateFiles.Text;
                }
                else
                {
                    MessageBox.Show("Error, Unable to locate file/folder called \"" + textBoxTemplateFiles.Text + "\".");
                    return;
                }

                // DataModel
                if (userSelectedDataModel != null)
                {
                    dataModel     = userSelectedDataModel.Clone("TheDataModel") as DataModel;
                    dataModel.dom = dom;

                    dom.dataModels.Add(dataModel.name, dataModel);
                }
                else
                {
                    dataModel = new DataModel("TheDataModel");
                    dataModel.Add(new Blob());
                    dom.dataModels.Add(dataModel.name, dataModel);
                }

                // Publisher
                Dictionary <string, Variant> args = new Dictionary <string, Variant>();
                args["FileName"] = new Variant(textBoxFuzzedFile.Text);
                Peach.Core.Publishers.FilePublisher file = new Peach.Core.Publishers.FilePublisher(args);

                // StateModel
                StateModel stateModel = new StateModel();
                stateModel.name = "TheStateModel";

                State state = new State();
                state.name   = "TheState";
                state.parent = stateModel;

                Peach.Core.Dom.Action actionOutput = new Peach.Core.Dom.Action();
                actionOutput.type      = ActionType.Output;
                actionOutput.dataModel = dataModel;
                actionOutput.dataSet   = new Peach.Core.Dom.DataSet();
                actionOutput.dataSet.Datas.Add(fileData);
                actionOutput.parent = state;

                Peach.Core.Dom.Action actionClose = new Peach.Core.Dom.Action();
                actionClose.type   = ActionType.Close;
                actionClose.parent = state;

                Peach.Core.Dom.Action actionCall = new Peach.Core.Dom.Action();
                actionCall.type      = ActionType.Call;
                actionCall.publisher = "Peach.Agent";
                actionCall.method    = "ScoobySnacks";
                actionCall.parent    = state;

                state.actions.Add(actionOutput);
                state.actions.Add(actionClose);
                state.actions.Add(actionCall);

                stateModel.states.Add(state.name, state);
                stateModel.initialState = state;

                dom.stateModels.Add(stateModel.name, stateModel);

                // Agent
                Peach.Core.Dom.Agent agent = new Peach.Core.Dom.Agent();
                agent.name = "TheAgent";
                agent.url  = "local://";

                Peach.Core.Dom.Monitor monitor = new Peach.Core.Dom.Monitor();

                switch (Platform.GetOS())
                {
                case Platform.OS.OSX:
                    if (radioButtonOSXCrashReporter.Checked)
                    {
                        monitor.cls = "CrashReporter";
                        agent.monitors.Add(monitor);

                        monitor     = new Peach.Core.Dom.Monitor();
                        monitor.cls = "Process";
                        monitor.parameters["StartOnCall"] = new Variant("ScoobySnacks");

                        if (this.checkBoxOSXCpuKill.Checked)
                        {
                            monitor.parameters["NoCpuKill"] = new Variant("false");
                        }
                        else
                        {
                            monitor.parameters["NoCpuKill"] = new Variant("true");
                        }

                        monitor.parameters["Executable"] = new Variant(this.textBoxOSXExecutable.Text);
                        monitor.parameters["Arguments"]  = new Variant(this.textBoxOSXArguments.Text);
                    }
                    else                             // Crash Wrangler
                    {
                        monitor.cls = "CrashWrangler";
                        monitor.parameters["StartOnCall"] = new Variant("ScoobySnacks");

                        if (this.checkBoxOSXCpuKill.Checked)
                        {
                            monitor.parameters["NoCpuKill"] = new Variant("false");
                        }
                        else
                        {
                            monitor.parameters["NoCpuKill"] = new Variant("true");
                        }

                        monitor.parameters["Command"]       = new Variant(this.textBoxOSXExecutable.Text);
                        monitor.parameters["Arguments"]     = new Variant(this.textBoxOSXArguments.Text);
                        monitor.parameters["CrashWrangler"] = new Variant(this.textBoxOSXCrashWrangler.Text);
                    }
                    break;

                case Platform.OS.Linux:                         // Linux
                    monitor.cls = "Process";
                    monitor.parameters["StartOnCall"] = new Variant("ScoobySnacks");
                    monitor.parameters["Executable"]  = new Variant(textBoxLinuxExecutable.Text);
                    monitor.parameters["Arguments"]   = new Variant(textBoxLinuxArguments.Text);
                    monitor.parameters["NoCpuKill"]   = new Variant("false");
                    break;

                case Platform.OS.Windows:
                    monitor.cls = "WindowsDebugger";
                    monitor.parameters["StartOnCall"] = new Variant("ScoobySnacks");
                    monitor.parameters["WinDbgPath"]  = new Variant(textBoxDebuggerPath.Text);

                    if (!checkBoxCpuKill.Checked)
                    {
                        monitor.parameters["NoCpuKill"] = new Variant("true");
                    }

                    if (radioButtonDebuggerStartProcess.Checked)
                    {
                        monitor.parameters["CommandLine"] = new Variant(textBoxDebuggerCommandLine.Text);
                    }
                    else if (radioButtonDebuggerAttachToProcess.Checked)
                    {
                        if (radioButtonAttachToProcessPID.Checked)
                        {
                            monitor.parameters["ProcessName"] = new Variant(textBoxAttachToProcessPID.Text);
                        }
                        else if (radioButtonAttachToProcessProcessName.Checked)
                        {
                            monitor.parameters["ProcessName"] = new Variant(textBoxAttachToProcessProcessName.Text);
                        }
                    }
                    else if (radioButtonDebuggerAttachToService.Checked)
                    {
                        monitor.parameters["Service"] = new Variant(comboBoxAttachToServiceServices.Text);
                    }
                    else if (radioButtonDebuggerKernelDebugger.Checked)
                    {
                        monitor.parameters["KernelConnectionString"] = new Variant(textBoxKernelConnectionString.Text);
                    }
                    break;
                }

                agent.monitors.Add(monitor);
                dom.agents.Add(agent.name, agent);

                // Send WM_CLOSE messages?
                if (checkBoxEnableWmClose.Checked)
                {
                    string windowNames = "";
                    if (!string.IsNullOrWhiteSpace(textBoxWindowTitle1.Text))
                    {
                        if (windowNames.Length > 0)
                        {
                            windowNames += ";";
                        }
                        windowNames += textBoxWindowTitle1.Text;
                    }
                    if (!string.IsNullOrWhiteSpace(textBoxWindowTitle2.Text))
                    {
                        if (windowNames.Length > 0)
                        {
                            windowNames += ";";
                        }
                        windowNames += textBoxWindowTitle2.Text;
                    }
                    if (!string.IsNullOrWhiteSpace(textBoxWindowTitle3.Text))
                    {
                        if (windowNames.Length > 0)
                        {
                            windowNames += ";";
                        }
                        windowNames += textBoxWindowTitle3.Text;
                    }
                    if (!string.IsNullOrWhiteSpace(textBoxWindowTitle4.Text))
                    {
                        if (windowNames.Length > 0)
                        {
                            windowNames += ";";
                        }
                        windowNames += textBoxWindowTitle4.Text;
                    }

                    monitor     = new Peach.Core.Dom.Monitor();
                    monitor.cls = "PopupWatcher";
                    monitor.parameters["WindowNames"] = new Variant(windowNames);

                    agent.monitors.Add(monitor);
                }

                // Mutation Strategy
                MutationStrategy strat = new RandomStrategy(new Dictionary <string, Variant>());
                if (comboBoxFuzzingStrategy.Text.ToLower().IndexOf("Squencial") > -1)
                {
                    strat = new Sequential(new Dictionary <string, Variant>());
                }

                // Test
                Test test = new Test();
                test.name       = "Default";
                test.stateModel = stateModel;
                test.agents.Add(agent.name, agent);
                test.publishers.Add("FileWriter", file);
                test.strategy     = strat;
                stateModel.parent = test;

                dom.tests.Add(test.name, test);

                if (logger == null)
                {
                    Dictionary <string, Variant> loggerArgs = new Dictionary <string, Variant>();
                    loggerArgs["Path"] = new Variant(textBoxLogPath.Text);
                    logger             = new Peach.Core.Loggers.FileLogger(loggerArgs);
                }

                test.loggers.Add(logger);

                // START FUZZING!!!!!
                thread = new Thread(new ParameterizedThreadStart(Run));
                thread.Start(dom);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                throw;
            }
        }
示例#16
0
        /// <summary>
        /// Initialized the testing engine.
        /// </summary>
        /// <param name="configuration">Configuration</param>
        private void Initialize(Configuration configuration)
        {
            this.Configuration = configuration;
            this.Logger        = new ConsoleLogger();
            this.ErrorReporter = new ErrorReporter(this.Configuration, this.Logger);
            this.Profiler      = new Profiler();

            this.PerIterationCallbacks = new HashSet <Action <int> >();

            // Initializes scheduling strategy specific components.
            this.SchedulingStrategyLogger = new SchedulingStrategyLogger(this.Configuration);
            this.SetRandomNumberGenerator();

            this.TestReport = new TestReport(this.Configuration);
            this.CancellationTokenSource = new CancellationTokenSource();
            this.PrintGuard = 1;

            if (this.Configuration.SchedulingStrategy == SchedulingStrategy.Interactive)
            {
                this.Strategy = new InteractiveStrategy(this.Configuration, this.Logger);
                this.Configuration.SchedulingIterations   = 1;
                this.Configuration.PerformFullExploration = false;
                this.Configuration.Verbose = 2;
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.Replay)
            {
                var           scheduleDump = this.GetScheduleForReplay(out bool isFair);
                ScheduleTrace schedule     = new ScheduleTrace(scheduleDump);
                this.Strategy = new ReplayStrategy(this.Configuration, schedule, isFair);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.Random)
            {
                this.Strategy = new RandomStrategy(this.Configuration.MaxFairSchedulingSteps, this.RandomNumberGenerator);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.ProbabilisticRandom)
            {
                this.Strategy = new ProbabilisticRandomStrategy(this.Configuration.MaxFairSchedulingSteps,
                                                                this.Configuration.CoinFlipBound, this.RandomNumberGenerator);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.PCT)
            {
                this.Strategy = new PCTStrategy(this.Configuration.MaxUnfairSchedulingSteps, this.Configuration.PrioritySwitchBound,
                                                this.SchedulingStrategyLogger, this.RandomNumberGenerator);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.FairPCT)
            {
                var prefixLength = this.Configuration.SafetyPrefixBound == 0 ?
                                   this.Configuration.MaxUnfairSchedulingSteps : this.Configuration.SafetyPrefixBound;
                var prefixStrategy = new PCTStrategy(prefixLength, this.Configuration.PrioritySwitchBound,
                                                     this.SchedulingStrategyLogger, this.RandomNumberGenerator);
                var suffixStrategy = new RandomStrategy(this.Configuration.MaxFairSchedulingSteps, this.RandomNumberGenerator);
                this.Strategy = new ComboStrategy(prefixStrategy, suffixStrategy);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.DFS)
            {
                this.Strategy = new DFSStrategy(this.Configuration.MaxUnfairSchedulingSteps, this.SchedulingStrategyLogger);
                this.Configuration.PerformFullExploration = false;
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.IDDFS)
            {
                this.Strategy = new IterativeDeepeningDFSStrategy(this.Configuration.MaxUnfairSchedulingSteps,
                                                                  this.SchedulingStrategyLogger);
                this.Configuration.PerformFullExploration = false;
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.DPOR)
            {
                this.Strategy = new DPORStrategy(
                    new ContractAsserter(),
                    null,
                    -1,
                    this.Configuration.MaxUnfairSchedulingSteps);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.RDPOR)
            {
                this.Strategy = new DPORStrategy(
                    new ContractAsserter(),
                    this.RandomNumberGenerator,
                    -1,
                    this.Configuration.MaxFairSchedulingSteps);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.DelayBounding)
            {
                this.Strategy = new ExhaustiveDelayBoundingStrategy(this.Configuration.MaxUnfairSchedulingSteps,
                                                                    this.Configuration.DelayBound, this.SchedulingStrategyLogger, this.RandomNumberGenerator);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.RandomDelayBounding)
            {
                this.Strategy = new RandomDelayBoundingStrategy(this.Configuration.MaxUnfairSchedulingSteps,
                                                                this.Configuration.DelayBound, this.SchedulingStrategyLogger, this.RandomNumberGenerator);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.Portfolio)
            {
                Error.ReportAndExit("Portfolio testing strategy is only " +
                                    "available in parallel testing.");
            }

            if (this.Configuration.SchedulingStrategy != SchedulingStrategy.Replay &&
                this.Configuration.ScheduleFile.Length > 0)
            {
                var           scheduleDump = this.GetScheduleForReplay(out bool isFair);
                ScheduleTrace schedule     = new ScheduleTrace(scheduleDump);
                this.Strategy = new ReplayStrategy(this.Configuration, schedule, isFair, this.Strategy);
            }
        }
示例#17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TestingEngine"/> class.
        /// </summary>
        private TestingEngine(Configuration configuration, TestMethodInfo testMethodInfo)
        {
            this.Configuration  = configuration;
            this.TestMethodInfo = testMethodInfo;

            this.Logger        = new ConsoleLogger();
            this.ErrorReporter = new ErrorReporter(configuration, this.Logger);
            this.Profiler      = new Profiler();

            this.PerIterationCallbacks = new HashSet <Action <int> >();

            // Initializes scheduling strategy specific components.
            this.RandomValueGenerator = new RandomValueGenerator(configuration);

            this.TestReport        = new TestReport(configuration);
            this.ReadableTrace     = string.Empty;
            this.ReproducableTrace = string.Empty;

            this.CancellationTokenSource = new CancellationTokenSource();
            this.PrintGuard = 1;

            if (!configuration.UserExplicitlySetLivenessTemperatureThreshold &&
                configuration.MaxFairSchedulingSteps > 0)
            {
                configuration.LivenessTemperatureThreshold = configuration.MaxFairSchedulingSteps / 2;
            }

            if (configuration.SchedulingStrategy is "replay")
            {
                var           scheduleDump = this.GetScheduleForReplay(out bool isFair);
                ScheduleTrace schedule     = new ScheduleTrace(scheduleDump);
                this.Strategy = new ReplayStrategy(configuration, schedule, isFair);
            }
            else if (configuration.SchedulingStrategy is "interactive")
            {
                configuration.TestingIterations      = 1;
                configuration.PerformFullExploration = false;
                configuration.IsVerbose = true;
                this.Strategy           = new InteractiveStrategy(configuration, this.Logger);
            }
            else if (configuration.SchedulingStrategy is "random")
            {
                this.Strategy = new RandomStrategy(configuration.MaxFairSchedulingSteps, this.RandomValueGenerator);
            }
            else if (configuration.SchedulingStrategy is "pct")
            {
                this.Strategy = new PCTStrategy(configuration.MaxUnfairSchedulingSteps, configuration.StrategyBound,
                                                this.RandomValueGenerator);
            }
            else if (configuration.SchedulingStrategy is "fairpct")
            {
                var prefixLength = configuration.SafetyPrefixBound == 0 ?
                                   configuration.MaxUnfairSchedulingSteps : configuration.SafetyPrefixBound;
                var prefixStrategy = new PCTStrategy(prefixLength, configuration.StrategyBound, this.RandomValueGenerator);
                var suffixStrategy = new RandomStrategy(configuration.MaxFairSchedulingSteps, this.RandomValueGenerator);
                this.Strategy = new ComboStrategy(prefixStrategy, suffixStrategy);
            }
            else if (configuration.SchedulingStrategy is "probabilistic")
            {
                this.Strategy = new ProbabilisticRandomStrategy(configuration.MaxFairSchedulingSteps,
                                                                configuration.StrategyBound, this.RandomValueGenerator);
            }
            else if (configuration.SchedulingStrategy is "dfs")
            {
                this.Strategy = new DFSStrategy(configuration.MaxUnfairSchedulingSteps);
            }
            else if (configuration.SchedulingStrategy is "portfolio")
            {
                Error.ReportAndExit("Portfolio testing strategy is only " +
                                    "available in parallel testing.");
            }

            if (configuration.SchedulingStrategy != "replay" &&
                configuration.ScheduleFile.Length > 0)
            {
                var           scheduleDump = this.GetScheduleForReplay(out bool isFair);
                ScheduleTrace schedule     = new ScheduleTrace(scheduleDump);
                this.Strategy = new ReplayStrategy(configuration, schedule, isFair, this.Strategy);
            }
        }
示例#18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TestingEngine"/> class.
        /// </summary>
        private TestingEngine(Configuration configuration, TestMethodInfo testMethodInfo)
        {
            this.Configuration  = configuration;
            this.TestMethodInfo = testMethodInfo;

            this.DefaultLogger = new ConsoleLogger()
            {
                LogLevel = configuration.LogLevel
            };
            this.Logger   = this.DefaultLogger;
            this.Profiler = new Profiler();

            this.PerIterationCallbacks = new HashSet <Action <uint> >();

            // Initializes scheduling strategy specific components.
            this.RandomValueGenerator = new RandomValueGenerator(configuration);

            this.TestReport        = new TestReport(configuration);
            this.ReadableTrace     = string.Empty;
            this.ReproducibleTrace = string.Empty;

            this.CancellationTokenSource = new CancellationTokenSource();
            this.PrintGuard = 1;

            if (configuration.IsDebugVerbosityEnabled)
            {
                IO.Debug.IsEnabled = true;
            }

            if (!configuration.UserExplicitlySetLivenessTemperatureThreshold &&
                configuration.MaxFairSchedulingSteps > 0)
            {
                configuration.LivenessTemperatureThreshold = configuration.MaxFairSchedulingSteps / 2;
            }

            if (configuration.SchedulingStrategy is "replay")
            {
                var           scheduleDump = this.GetScheduleForReplay(out bool isFair);
                ScheduleTrace schedule     = new ScheduleTrace(scheduleDump);
                this.Strategy = new ReplayStrategy(configuration, schedule, isFair);
            }
            else if (configuration.SchedulingStrategy is "interactive")
            {
                configuration.TestingIterations      = 1;
                configuration.PerformFullExploration = false;
                configuration.IsVerbose = true;
                this.Strategy           = new InteractiveStrategy(configuration, this.Logger);
            }
            else if (configuration.SchedulingStrategy is "random")
            {
                this.Strategy = new RandomStrategy(configuration.MaxFairSchedulingSteps, this.RandomValueGenerator);
            }
            else if (configuration.SchedulingStrategy is "pct")
            {
                this.Strategy = new PCTStrategy(configuration.MaxUnfairSchedulingSteps, configuration.StrategyBound,
                                                this.RandomValueGenerator);
            }
            else if (configuration.SchedulingStrategy is "fairpct")
            {
                var prefixLength = configuration.SafetyPrefixBound is 0 ?
                                   configuration.MaxUnfairSchedulingSteps : configuration.SafetyPrefixBound;
                var prefixStrategy = new PCTStrategy(prefixLength, configuration.StrategyBound, this.RandomValueGenerator);
                var suffixStrategy = new RandomStrategy(configuration.MaxFairSchedulingSteps, this.RandomValueGenerator);
                this.Strategy = new ComboStrategy(prefixStrategy, suffixStrategy);
            }
            else if (configuration.SchedulingStrategy is "probabilistic")
            {
                this.Strategy = new ProbabilisticRandomStrategy(configuration.MaxFairSchedulingSteps,
                                                                configuration.StrategyBound, this.RandomValueGenerator);
            }
            else if (configuration.SchedulingStrategy is "dfs")
            {
                this.Strategy = new DFSStrategy(configuration.MaxUnfairSchedulingSteps);
            }
            else if (configuration.SchedulingStrategy is "rl")
            {
                this.Strategy = new QLearningStrategy(configuration.AbstractionLevel, configuration.MaxUnfairSchedulingSteps, this.RandomValueGenerator);
            }
            else if (configuration.SchedulingStrategy is "portfolio")
            {
                var msg = "Portfolio testing strategy is only " +
                          "available in parallel testing.";
                if (configuration.DisableEnvironmentExit)
                {
                    throw new Exception(msg);
                }
                else
                {
                    Error.ReportAndExit(msg);
                }
            }

            if (configuration.SchedulingStrategy != "replay" &&
                configuration.ScheduleFile.Length > 0)
            {
                var           scheduleDump = this.GetScheduleForReplay(out bool isFair);
                ScheduleTrace schedule     = new ScheduleTrace(scheduleDump);
                this.Strategy = new ReplayStrategy(configuration, schedule, isFair, this.Strategy);
            }

            if (TelemetryClient is null)
            {
                TelemetryClient = new CoyoteTelemetryClient(this.Configuration);
            }
        }
示例#19
0
        /// <summary>
        /// Initialized the testing engine.
        /// </summary>
        private void Initialize()
        {
            this.Logger        = new ConsoleLogger();
            this.ErrorReporter = new ErrorReporter(this.Configuration, this.Logger);
            this.Profiler      = new Profiler();

            this.CancellationTokenSource = new CancellationTokenSource();

            this.TestReport = new TestReport(this.Configuration);

            this.PrintGuard = 1;

            if (this.Configuration.SchedulingStrategy == SchedulingStrategy.Interactive)
            {
                this.Strategy = new InteractiveStrategy(this.Configuration, this.Logger);
                this.Configuration.SchedulingIterations   = 1;
                this.Configuration.PerformFullExploration = false;
                this.Configuration.Verbose = 2;
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.Replay)
            {
                string[] scheduleDump;
                if (this.Configuration.ScheduleTrace.Length > 0)
                {
                    scheduleDump = this.Configuration.ScheduleTrace.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                }
                else
                {
                    scheduleDump = File.ReadAllLines(this.Configuration.ScheduleFile);
                }

                bool isFair = false;

                foreach (var line in scheduleDump)
                {
                    if (!line.StartsWith("--"))
                    {
                        break;
                    }

                    if (line.Equals("--fair-scheduling"))
                    {
                        isFair = true;
                    }
                    else if (line.Equals("--state-caching"))
                    {
                        this.Configuration.CacheProgramState = true;
                    }
                    else if (line.StartsWith("--liveness-temperature-threshold:"))
                    {
                        this.Configuration.LivenessTemperatureThreshold =
                            Int32.Parse(line.Substring("--liveness-temperature-threshold:".Length));
                    }
                    else if (line.StartsWith("--test-method:"))
                    {
                        this.Configuration.TestMethodName =
                            line.Substring("--test-method:".Length);
                    }
                }

                ScheduleTrace schedule = new ScheduleTrace(scheduleDump);
                this.Strategy = new ReplayStrategy(this.Configuration, schedule, isFair);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.Random)
            {
                this.Strategy = new RandomStrategy(this.Configuration);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.ProbabilisticRandom)
            {
                this.Strategy = new ProbabilisticRandomStrategy(this.Configuration,
                                                                this.Configuration.CoinFlipBound);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.DFS)
            {
                this.Strategy = new DFSStrategy(this.Configuration);
                this.Configuration.PerformFullExploration = false;
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.IDDFS)
            {
                this.Strategy = new IterativeDeepeningDFSStrategy(this.Configuration);
                this.Configuration.PerformFullExploration = false;
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.DelayBounding)
            {
                this.Strategy = new ExhaustiveDelayBoundingStrategy(this.Configuration,
                                                                    this.Configuration.DelayBound);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.RandomDelayBounding)
            {
                this.Strategy = new RandomDelayBoundingStrategy(this.Configuration,
                                                                this.Configuration.DelayBound);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.PCT)
            {
                this.Strategy = new PCTStrategy(this.Configuration, this.Configuration.PrioritySwitchBound);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.FairPCT)
            {
                var strategy1 = new PCTStrategy(this.Configuration, this.Configuration.PrioritySwitchBound);
                var strategy2 = new RandomStrategy(this.Configuration);
                this.Strategy = new ComboStrategy(this.Configuration, strategy1, strategy2);
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.MaceMC)
            {
                this.Strategy = new MaceMCStrategy(this.Configuration);
                this.Configuration.PerformFullExploration = false;
                this.Configuration.CacheProgramState      = false;
            }
            else if (this.Configuration.SchedulingStrategy == SchedulingStrategy.Portfolio)
            {
                Error.ReportAndExit("Portfolio testing strategy in only " +
                                    "available in parallel testing.");
            }
        }
示例#20
0
        public static analysis.analysisResult Strategy(analysis.workData data, string strategyCode)
        {
            GenericStrategy strategy;

            curStrategyCode = strategyCode;

            switch (strategyCode)
            {
            //Screening
            case "SCRPRICE":
            {
                Parameters p = null;
                strategy = new PriceScreening(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "SCRMACD01":
            {
                Parameters p = new Parameters(12, 26, 9);
                strategy = new BasicMACD(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Screening());
            }

            case "SCRMACD02":
            {
                Parameters p = new Parameters(12, 26, 9);
                strategy = new MACD_HistogramChanged(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Screening());
            }

            case "SCRDMI":
            {
                Parameters p = new Parameters(14, 14);
                strategy = new BasicDMI(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Screening());
            }

            case "SCRSupport":
            {
                Parameters p = new Parameters(30, 0.01);
                strategy = new SupportScreening(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Screening());
            }

            case "SCRResist":
            {
                Parameters p = new Parameters(30, 0.01);
                strategy = new ResistanceScreening(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Screening());
            }

            case "BUYANDHOLD":
            {
                strategy = new BuyAndHoldStrategy(data, strategyCode, fExportData, curStrategyCode);
                return(strategy.Execute());
            }

                #region SMA Strategy
            case "SMAONLY":
            {
                Parameters p = new Parameters(5, 10);
                strategy = new TwoSMA(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "EMAONLY":
            {
                Parameters p = new Parameters(5, 10);
                strategy = new TwoEMA(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "WMAONLY":
            {
                strategy = new BasicWMA_5_10(data, strategyCode, fExportData, curStrategyCode);
                return(strategy.Execute());
            }

            case "SMAPRICE":
            {
                //strategy = new Price_SMA_5_10(data, strategyCode, fExportData, curStrategyCode);
                //return strategy.Execute();
                Parameters p = new Parameters(50, 100);
                strategy = new PriceTwoSMA(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "SMAVFIL":
            {
                Parameters p = new Parameters(5, 10, 50000);
                strategy = new TwoSMA_VolumeFilter(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "3SMAPRICE":
            {
                Parameters p = new Parameters(5, 10, 20);
                strategy = new BasicPrice_3SMA(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "3SMANEW":
            {
                Parameters p = new Parameters(10, 20, 30);
                strategy = new BasicPrice_3SMA(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "SMARIRW":
            {
                Parameters p = new Parameters(5, 10, 20);
                strategy = new Price_3SMA_Risk_Reward(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "SMAMID":
            {
                Parameters p = new Parameters(20, 50);
                strategy = new PriceTwoSMA(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
                //strategy = new Price_SMA_20_50(data, strategyCode, fExportData, curStrategyCode);
                //return strategy.Execute();
            }

            case "SMAM50_100":
            {
                Parameters p = new Parameters(50, 100);
                strategy = new PriceTwoSMA(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }
                #endregion

            //Statistic
            case "AVERAGE":
            {
                Parameters p = new Parameters(30, -15, 10);
                strategy = new AverageStrategy(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            //Statistic
            case "AVERAGE1":
            {
                Parameters p = new Parameters(30, -15, 15);
                strategy = new AverageStrategy(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "RAND":
            {
                Parameters p = null;
                strategy = new RandomStrategy(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            //Statistic
            case "MARKOV":
            {
                Parameters p = null;
                strategy = new SimpleMarkov(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }
                #region MACD strategy
            //MACD strategy

            case "MACDBAS":
            {
                Parameters p = new Parameters(12, 26, 9);
                strategy = new BasicMACD(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "MACD1":
            {
                strategy = new MACD_Line_Cut(data, strategyCode, fExportData, curStrategyCode);
                return(strategy.Execute());
            }

            case "MACD2":
            {
                Parameters p = new Parameters(12, 26, 9);
                strategy = new MACD_HistogramChanged(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "MACD_CL":
            {
                strategy = new MACD_HistogramChanged_CutLoss(data, strategyCode, fExportData, curStrategyCode);
                return(strategy.Execute());
            }

                #endregion
            //Strategy with DMI indicator
            case "DMI":
            {
                Parameters p = new Parameters(14, 14);
                strategy = new BasicDMI(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "DMI_CL":
            {
                Parameters p = new Parameters(14, 14, -5);
                strategy = new BasicDMI(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute_CutLoss());
            }

            //Strategy with Stochastic
            case "STOCHFAST":
            {
                Parameters p = new Parameters(14, 3);
                strategy = new StochasticFast(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            //Strategy with Stochastic
            case "STOCHSLOW":
            {
                Parameters p = new Parameters(15, 5, 3);
                strategy = new StochasticSlow(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            //Strategy with pattern
            case "PATERN32":
            {
                const int  CONSECUTIVE_UP   = 4;
                const int  CONSECUTIVE_DOWN = 3;
                Parameters p = new Parameters(CONSECUTIVE_DOWN, CONSECUTIVE_UP);
                strategy = new Pattern_Consecutive_UpAndDown(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

                #region Hybrid strategy
            ////Hybrid strategy

            case "RSI":
            {
                int        RSI_LOWER_LEVEL = 30;
                int        RSI_UPPER_LEVEL = 70;
                double[]   d = { 14, 26, 12, 9, RSI_LOWER_LEVEL, RSI_UPPER_LEVEL };
                Parameters p = new Parameters(d);
                strategy = new RSI_MACD_Histogram(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "SMASTOCH":
            {
                double[]   d = { 5, 10, 15, 5, 3 };
                Parameters p = new Parameters(d);;
                strategy = new SMA_Stochastic(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "MACDSTOC":
            {
                double[]   d = { 20, 12, 26, 9, 15, 5, 3 };
                Parameters p = new Parameters(d);
                strategy = new MACD_Stochastic(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "MS_BOTTOM":
            {
                Parameters p = null;
                strategy = new MACD_Stochastic_Bottom(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "MS_BOTv1":
            {
                Parameters p = null;
                strategy = new MACD_Stochastic_Bottom_v1(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }

            case "TEST":
            {
                Parameters p = new Parameters(5, 10, 1.5);
                strategy = new TestStrategy(data, strategyCode, fExportData, curStrategyCode, p);
                return(strategy.Execute());
            }
                #endregion

            default:
                return(null);
            }
        }
示例#21
0
        static void Main(string[] args)
        {
            if (args.Contains("-h"))
            {
                HandleHelp();
            }


            var file    = args[0];
            var timeout = int.Parse(args[1]);
            var runs    = int.Parse(args[2]);
            var output  = args.Count() == 4
                ? args[3]
                : string.Empty;

            System.Console.WriteLine($"Input params:");
            System.Console.WriteLine($"File: {file}");
            System.Console.WriteLine($"Timeout: {timeout}[s]");
            System.Console.WriteLine($"Runs: {runs}");
            System.Console.WriteLine($"Output: {output}");


            System.Console.WriteLine($"Reading data from input file");
            var data = ReadData(file);

            System.Console.WriteLine("OK");

            var randomResults   = new List <QapResult <int> >();
            var steepestResults = new List <QapResult <int> >();
            var greedyResults   = new List <QapResult <int> >();


            for (var currentRun = 1; currentRun <= runs; currentRun++)
            {
                System.Console.WriteLine();
                System.Console.WriteLine($"### Run: {currentRun} ###");

                var initialPermutation = QapMath.Permutate(QapMath.Range(1, data.MatricesSize));
                System.Console.WriteLine($"Initial permutation: {string.Join(",",initialPermutation)}");

                var cancelationToken = new CancelationToken();

                var randomStrategy   = new RandomStrategy();
                var steepestStrategy = new SteepestStrategy();
                var greedyStrategy   = new GreedyStrategy();

                Func <IEnumerable <int>, float> scoringFunction = (x) => Score(data, x);

                var timer = new Timer(timeout * millisecondsInSeconds);
                timer.Elapsed += (sender, eargs) => cancelationToken.Cancel();

                System.Console.WriteLine("Starting tasks");
                var randomStartegyTask   = Task.Run(() => randomStrategy.SearchBest(scoringFunction, initialPermutation, cancelationToken));
                var steepestStrategyTask = Task.Run(() => randomStrategy.SearchBest(scoringFunction, initialPermutation, cancelationToken));
                var greedyStrategyTask   = Task.Run(() => greedyStrategy.SearchBest(scoringFunction, initialPermutation, cancelationToken));

                System.Console.WriteLine("OK");

                System.Console.WriteLine("Starting timer");
                timer.Start();
                System.Console.WriteLine("OK");

                System.Console.WriteLine("Awaiting tasks to finish");
                Task.WaitAll(new [] { randomStartegyTask, steepestStrategyTask, greedyStrategyTask });
                System.Console.WriteLine("OK");

                System.Console.WriteLine("Collecting results");
                QapResult <int> randomResult   = randomStartegyTask.Result as QapResult <int> ?? null;
                QapResult <int> steepestResult = steepestStrategyTask.Result as QapResult <int> ?? null;
                QapResult <int> greedyResult   = greedyStrategyTask.Result as QapResult <int> ?? null;

                randomResults.Add(randomResult);
                steepestResults.Add(steepestResult);
                greedyResults.Add(greedyResult);

                System.Console.WriteLine("OK");

                System.Console.WriteLine();
                System.Console.WriteLine($"# Results for run: {currentRun}");
                System.Console.WriteLine("Results in format <foundIntime>:<solution>/<ofTotalSeen>:<steps>:<score>:<Permutation>");
                System.Console.WriteLine($"Best random: {randomResult.FoundIn.TotalMilliseconds}:{randomResult.SeenAsSolutionNumber}/{randomResult.TotalSolutionsSeen}:{randomResult.Steps}:{randomResult.Score}:[{String.Join(",",randomResult.Solution)}]");
                System.Console.WriteLine($"Best steepest: {steepestResult.FoundIn.TotalMilliseconds}:{steepestResult.SeenAsSolutionNumber}/{steepestResult.TotalSolutionsSeen}:{steepestResult.Steps}:{steepestResult.Score}:[{String.Join(",",steepestResult.Solution)}]");
                System.Console.WriteLine($"Best greedy: {greedyResult.FoundIn.TotalMilliseconds}:{greedyResult.SeenAsSolutionNumber}/{greedyResult.TotalSolutionsSeen}:{greedyResult.Steps}:{greedyResult.Score}:[{String.Join(",",greedyResult.Solution)}]");
            }

            if (!string.IsNullOrEmpty(output))
            {
                using (var writer = new StreamWriter(File.OpenWrite(output)))
                {
                    writer.WriteLine("algorithm,time,solutionNr,totalSolutions,steps,score,solution");

                    foreach (var solution in randomResults)
                    {
                        writer.WriteLine($"random,{solution.ToCsvLine()}");
                    }
                    foreach (var solution in steepestResults)
                    {
                        writer.WriteLine($"steepest,{solution.ToCsvLine()}");
                    }
                    foreach (var solution in greedyResults)
                    {
                        writer.WriteLine($"greedy,{solution.ToCsvLine()}");
                    }
                }
            }
        }
示例#22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SchedulingContext"/> class.
        /// </summary>
        private SchedulingContext(Configuration configuration, ILogger logger)
        {
            this.Configuration  = configuration;
            this.ValueGenerator = new RandomValueGenerator(configuration);

            if (!configuration.UserExplicitlySetLivenessTemperatureThreshold &&
                configuration.MaxFairSchedulingSteps > 0)
            {
                configuration.LivenessTemperatureThreshold = configuration.MaxFairSchedulingSteps / 2;
            }

            SchedulingStrategy strategy = null;

            if (configuration.SchedulingStrategy is "replay")
            {
                this.ReplayStrategy      = new ReplayStrategy(configuration);
                strategy                 = this.ReplayStrategy;
                this.IsReplayingSchedule = true;
            }
            else if (configuration.SchedulingStrategy is "interactive")
            {
                configuration.TestingIterations      = 1;
                configuration.PerformFullExploration = false;
                configuration.IsVerbose = true;
                strategy = new InteractiveStrategy(configuration, logger);
            }
            else if (configuration.SchedulingStrategy is "random")
            {
                strategy = new RandomStrategy(configuration.MaxFairSchedulingSteps, this.ValueGenerator);
            }
            else if (configuration.SchedulingStrategy is "pct")
            {
                strategy = new PCTStrategy(configuration.MaxUnfairSchedulingSteps, configuration.StrategyBound,
                                           this.ValueGenerator);
            }
            else if (configuration.SchedulingStrategy is "fairpct")
            {
                var prefixLength = configuration.SafetyPrefixBound is 0 ?
                                   configuration.MaxUnfairSchedulingSteps : configuration.SafetyPrefixBound;
                var prefixStrategy = new PCTStrategy(prefixLength, configuration.StrategyBound, this.ValueGenerator);
                var suffixStrategy = new RandomStrategy(configuration.MaxFairSchedulingSteps, this.ValueGenerator);
                strategy = new ComboStrategy(prefixStrategy, suffixStrategy);
            }
            else if (configuration.SchedulingStrategy is "probabilistic")
            {
                strategy = new ProbabilisticRandomStrategy(configuration.MaxFairSchedulingSteps,
                                                           configuration.StrategyBound, this.ValueGenerator);
            }
            else if (configuration.SchedulingStrategy is "dfs")
            {
                strategy = new DFSStrategy(configuration.MaxUnfairSchedulingSteps);
            }
            else if (configuration.SchedulingStrategy is "rl")
            {
                this.Strategy = new QLearningStrategy(configuration.AbstractionLevel, configuration.MaxUnfairSchedulingSteps, this.ValueGenerator);
            }

            if (configuration.SchedulingStrategy != "replay" &&
                configuration.ScheduleFile.Length > 0)
            {
                this.ReplayStrategy      = new ReplayStrategy(configuration, strategy);
                strategy                 = this.ReplayStrategy;
                this.IsReplayingSchedule = true;
            }

            this.Strategy = strategy;
        }
示例#23
0
        private IEnumerable <GuessGrid> RunStrategies(StrategyBoard board)
        {
            var progress = 1 - (float)board.RawCount / (board.Size.Width * board.Size.Height);

            if (progress >= .1)
            {
                var countStrategy = new CountStrategy(board);
                Console.WriteLine("Run count strategy");

                var countGuesses = countStrategy.Guess().ToArray();
                if (countGuesses.Any())
                {
                    return(countGuesses);
                }
            }

            if (progress >= .4)
            {
                var bruteForceStrategy = new BruteForceStrategy(board, progress < .7 ? 5 : 8);
                Console.WriteLine("Run brute-force strategy");

                var bruteForceGuesses = bruteForceStrategy.Guess().ToArray();
                if (bruteForceGuesses.Any())
                {
                    var confirmedBruteForceGuesses = bruteForceGuesses.Where(t => t.Confidence >= 1).ToArray();
                    if (confirmedBruteForceGuesses.Any())
                    {
                        return(confirmedBruteForceGuesses);
                    }

                    var probableBruteForceGuesses = bruteForceGuesses.OrderByDescending(t => t.Confidence).First();
                    return(new[] { probableBruteForceGuesses });
                }
            }

            if (progress <= .1)
            {
                var startCount = (int)((float)board.RawCount / board.BombCount * 3);

                var startStrategy = new RandomStrategy(board);
                Console.WriteLine("Run start strategy");

                var startGuesses = startStrategy.Guess().Take(startCount).ToArray();
                if (startGuesses.Any())
                {
                    return(startGuesses);
                }
            }

            var randomStrategy = new RandomStrategy(board);

            Console.WriteLine("Run random strategy");

            var randomGuesses = randomStrategy.Guess();

            if (randomGuesses.Any())
            {
                var probableRandomGuesses = randomGuesses.OrderByDescending(t => t.Confidence).First();
                return(new[] { probableRandomGuesses });
            }

            return(new GuessGrid[0]);
        }
示例#24
0
        private static List<double> simpleRandomStrategy(int numOfHands)
        {
            var ret = new List<double>();
            int totalHandsPlayed;
            double winLoss = 0.0; //-1 for loss, +1 for win. +1.5 for blackjack. 0 for draw
            var policy = new RandomStrategy();
            int numBlackJacks = 0;
            int numWins = 0;
            int numDraws = 0;
            int numLosses = 0;
            //do each hand
            for (totalHandsPlayed = 0; totalHandsPlayed < numOfHands; totalHandsPlayed++)
            {
                Deck deck = new Deck(6);
                deck.shuffleCards();
                Hand playerHand = new Hand();
                Hand dealerHand = new Hand();
                //deal initial cards
                playerHand.addCards(deck.getCard());
                dealerHand.addCards(deck.getCard());
                playerHand.addCards(deck.getCard());
                dealerHand.addCards(deck.getCard());

                if (playerHand.getValue() == 21 && dealerHand.getValue() != 21)
                {
                    //BLACK JACK
                    numBlackJacks++;
                    winLoss += 1.5;
                }
                else if (dealerHand.getValue() == 21)
                {
                    //Dealer BJ
                    numLosses++;
                    winLoss -= 1.0;
                }
                else
                {
                    //player decisions
                    var action = policy.choosePlayerAction(playerHand, dealerHand);
                    while (action == 1)
                    {
                        playerHand.addCards(deck.getCard());
                        action = policy.choosePlayerAction(playerHand, dealerHand);
                    }

                    //see if we busted
                    if (playerHand.getValue() > 21)
                    {
                        numLosses++;
                        winLoss -= 1.0;
                    }
                    else
                    {
                        //play dealer
                        var dealerAction = policy.chooseDealerAction(dealerHand);
                        while (dealerAction == 1)
                        {
                            dealerHand.addCards(deck.getCard());
                            dealerAction = policy.chooseDealerAction(dealerHand);
                        }

                        if (dealerHand.getValue() > 21) //dealer busts
                        {
                            numWins++;
                            winLoss += 1.0;
                        }
                        else if (dealerHand.getValue() < playerHand.getValue())
                        {
                            numWins++;
                            winLoss += 1.0f;
                        }
                        else if (dealerHand.getValue() == playerHand.getValue())
                        {
                            numDraws++;
                        }
                        else
                        {
                            numLosses++;
                            winLoss -= 1.0;
                        }

                    }
                }

                if(totalHandsPlayed % 1000 == 0)
                {
                    var x = winLoss / (1000.0);
                    ret.Add(x);
                    numWins = 0;
                    numLosses = 0;
                    numDraws = 0;
                    numBlackJacks = 0;
                    winLoss = 0.0;
                }

            }
            Console.WriteLine("Wins: " + numWins);
            Console.WriteLine("Losses: " + numLosses);
            Console.WriteLine("Draws: " + numDraws);
            Console.WriteLine("BJ: " + numBlackJacks);
            Console.WriteLine("WinLoss: " + winLoss);

            return ret;
        }
示例#25
0
        public void Throw_NULLReferenceException_When_GameBoard_Is_Null()
        {
            var strategy = new RandomStrategy();

            strategy.CalculateNextMove(null);
        }
示例#26
0
        public static analysis.analysisResult Strategy(analysis.workData data, string strategyCode)
        {
            GenericStrategy strategy;
            curStrategyCode = strategyCode;

            switch (strategyCode)
            {
                //Screening
                case "SCRPRICE":
                    {
                        Parameters p = null;
                        strategy = new PriceScreening(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();
                    }
                case "SCRMACD01":
                    {
                        Parameters p = new Parameters(12, 26, 9);
                        strategy = new BasicMACD(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Screening();
                    }
                case "SCRMACD02":
                    {
                        Parameters p = new Parameters(12, 26, 9);
                        strategy = new MACD_HistogramChanged(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Screening();
                    }
                case "SCRDMI":
                    {
                        Parameters p = new Parameters(14, 14);
                        strategy = new BasicDMI(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Screening();
                    }
                case "SCRSupport":
                    {
                        Parameters p = new Parameters(30, 0.01);
                        strategy = new SupportScreening(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Screening();
                    }
                case "SCRResist":
                    {
                        Parameters p = new Parameters(30, 0.01);
                        strategy = new ResistanceScreening(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Screening();
                    }

                case "BUYANDHOLD":
                    {
                        strategy = new BuyAndHoldStrategy(data, strategyCode, fExportData, curStrategyCode);
                        return strategy.Execute();
                    }

                #region SMA Strategy
                case "SMAONLY":
                    {
                        Parameters p = new Parameters(5, 10);
                        strategy = new TwoSMA(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();
                    }
                case "EMAONLY":
                    {
                        Parameters p = new Parameters(5, 10);
                        strategy = new TwoEMA(data, strategyCode, fExportData, curStrategyCode,p);
                        return strategy.Execute();
                    }
                case "WMAONLY":
                    {
                        strategy = new BasicWMA_5_10(data, strategyCode, fExportData, curStrategyCode);
                        return strategy.Execute();
                    }

                case "SMAPRICE":
                    {
                        //strategy = new Price_SMA_5_10(data, strategyCode, fExportData, curStrategyCode);
                        //return strategy.Execute();
                        Parameters p = new Parameters(50, 100);
                        strategy = new PriceTwoSMA(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();
                    }

                case "SMAVFIL":
                    {
                        Parameters p = new Parameters(5, 10, 50000);
                        strategy = new TwoSMA_VolumeFilter(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();
                    }

                case "3SMAPRICE":
                    {
                        Parameters p = new Parameters(5, 10, 20);
                        strategy = new BasicPrice_3SMA(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();
                    }
                case "3SMANEW":
                    {
                        Parameters p = new Parameters(10, 20, 30);
                        strategy = new BasicPrice_3SMA(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();
                    }
                case "SMARIRW":
                    {
                        Parameters p = new Parameters(5, 10, 20);
                        strategy = new Price_3SMA_Risk_Reward(data, strategyCode, fExportData, curStrategyCode,p);
                        return strategy.Execute();
                    }
                case "SMAMID":
                    {
                        Parameters p = new Parameters(20, 50);
                        strategy = new PriceTwoSMA(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();
                        //strategy = new Price_SMA_20_50(data, strategyCode, fExportData, curStrategyCode);
                        //return strategy.Execute();
                    }
                case "SMAM50_100":
                    {
                        Parameters p = new Parameters(50, 100);
                        strategy = new PriceTwoSMA(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();
                    }
                #endregion

                //Statistic
                case "AVERAGE":
                    {
                        Parameters p = new Parameters(30, -15, 10);
                        strategy = new AverageStrategy(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();
                    }

                //Statistic
                case "AVERAGE1":
                    {
                        Parameters p = new Parameters(30, -15, 15);
                        strategy = new AverageStrategy(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();
                    }
                case "RAND":
                    {
                        Parameters p = null;
                        strategy = new RandomStrategy(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();
                    }
                //Statistic
                case "MARKOV":
                    {
                        Parameters p = null;
                        strategy = new SimpleMarkov(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();
                    }
                #region MACD strategy
                //MACD strategy

                case "MACDBAS":
                    {
                        Parameters p = new Parameters(12, 26, 9);
                        strategy = new BasicMACD(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();
                    }
                case "MACD1":
                    {
                        strategy = new MACD_Line_Cut(data, strategyCode, fExportData, curStrategyCode);
                        return strategy.Execute();
                    }
                case "MACD2":
                    {
                        Parameters p = new Parameters(12, 26, 9);
                        strategy = new MACD_HistogramChanged(data, strategyCode, fExportData, curStrategyCode,p);
                        return strategy.Execute();
                    }

                case "MACD_CL":
                    {
                        strategy = new MACD_HistogramChanged_CutLoss(data, strategyCode, fExportData, curStrategyCode);
                        return strategy.Execute();
                    }
                #endregion
                //Strategy with DMI indicator
                case "DMI":
                    {
                        Parameters p = new Parameters(14, 14);
                        strategy = new BasicDMI(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();

                    }

                case "DMI_CL":
                    {
                        Parameters p = new Parameters(14, 14, -5);
                        strategy = new BasicDMI(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute_CutLoss();
                    }

                //Strategy with Stochastic
                case "STOCHFAST":
                    {
                        Parameters p = new Parameters(14, 3);
                        strategy = new StochasticFast(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();

                    }

                //Strategy with Stochastic
                case "STOCHSLOW":
                    {
                        Parameters p = new Parameters(15, 5, 3);
                        strategy = new StochasticSlow(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();

                    }

                //Strategy with pattern
                case "PATERN32":
                    {
                        const int CONSECUTIVE_UP = 4;
                        const int CONSECUTIVE_DOWN = 3;
                        Parameters p = new Parameters(CONSECUTIVE_DOWN, CONSECUTIVE_UP);
                        strategy = new Pattern_Consecutive_UpAndDown(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();

                    }

                #region Hybrid strategy
                ////Hybrid strategy

                case "RSI":
                    {
                        int RSI_LOWER_LEVEL = 30;
                        int RSI_UPPER_LEVEL = 70;
                        double[] d = { 14, 26, 12, 9, RSI_LOWER_LEVEL, RSI_UPPER_LEVEL };
                        Parameters p = new Parameters(d);
                        strategy = new RSI_MACD_Histogram(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();
                    }

                case "SMASTOCH":
                    {
                        double[] d = { 5, 10, 15, 5, 3 };
                        Parameters p = new Parameters(d); ;
                        strategy = new SMA_Stochastic(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();

                    }

                case "MACDSTOC":
                    {
                        double[] d = { 20, 12, 26, 9, 15, 5, 3 };
                        Parameters p = new Parameters(d);
                        strategy = new MACD_Stochastic(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();

                    }

                case "MS_BOTTOM":
                    {
                        Parameters p = null;
                        strategy = new MACD_Stochastic_Bottom(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();

                    }

                case "MS_BOTv1":
                    {
                        Parameters p = null;
                        strategy = new MACD_Stochastic_Bottom_v1(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();

                    }
                case "TEST":
                    {
                        Parameters p = new Parameters(5, 10, 1.5);
                        strategy = new TestStrategy(data, strategyCode, fExportData, curStrategyCode, p);
                        return strategy.Execute();

                    }
                #endregion

                default:
                    return null;
            }
        }