public void Settings_CanSet()
        {
            var sut = CreateSut().Item1;
            var settigs = new SimulationSettings();
            sut.Settings = settigs;

            Assert.Same(settigs, sut.Settings);
        }
Beispiel #2
0
        public void RunDemo(SimulationSettings settings)
        {
            _chainLinkFactory.SetSettings(settings);
            _timerService.SetSettings(settings);

            var conveyorData          = settings.ConveyorSettingsMpaToAa;
            var checkInDisp           = _chainLinkFactory.CreateCheckInDispatcher();
            var checkIn               = _chainLinkFactory.CreateCheckInDesk();
            var firstCheckInConnector = _chainLinkFactory.CreateConveyorConnector();
            var checkInToPsc          = _chainLinkFactory.CreateManyToOneConveyor(conveyorData[0].Length);
            var psc          = _chainLinkFactory.CreatePsc();
            var pscToMpa     = _chainLinkFactory.CreateOneToOneConveyor(conveyorData[1].Length);
            var mpa          = _chainLinkFactory.CreateMpa();
            var mpaToAA      = _chainLinkFactory.CreateOneToOneConveyor(conveyorData[2].Length);
            var aa           = _chainLinkFactory.CreateAa();
            var bagCollector = _chainLinkFactory.CreateBagCollector();

            checkInDisp.SetCheckIns(new List <ICheckInDesk>()
            {
                checkIn
            });
            checkIn.AddSuccessor(firstCheckInConnector);
            firstCheckInConnector.SetNextNode(checkInToPsc, 0);
            checkInToPsc.SetSuccessor(psc);
            psc.AddSuccessor(pscToMpa);
            pscToMpa.SetSuccessor(mpa);

            aa.AddSuccessor(bagCollector);
            mpaToAA.SetSuccessor(aa);
            mpa.AddSuccessor(mpaToAA);

            checkInToPsc.Start();
            mpaToAA.Start();
            pscToMpa.Start();

            _timerService.RunNewTimer();
            checkInDisp.Start();
        }
Beispiel #3
0
        public double GetItemMaximumScore(SimulationSettings simSettings)
        {
            double retVal = double.MinValue;
            //retVal = context.Database.SqlQuery<double>(@"
            //        select
            //         max(m1 + m2 + m3 + m4 + m5)
            //        from (
            //         select
            //          a.ID,
            //          iif(@p0 = 0, 0, sum(c.Metric1) * (@p0 / 100)) m1,
            //          iif(@p1 = 0, 0, sum(c.Metric2) * (@p1 / 100)) m2,
            //          iif(@p2 = 0, 0, sum(c.Metric3) * (@p2 / 100)) m3,
            //          iif(@p3 = 0, 0, sum(c.Metric4) * (@p3 / 100)) m4,
            //          iif(@p4 = 0, 0, sum(c.Metric5) * (@p4 / 100)) m5
            //         from Items a
            //         inner join ItemAttributes b on a.ID = b.Item_ID
            //         inner join Attributes c on b.Attributes_ID = c.ID
            //         group by a.ID
            //        ) a
            //    ", simSettings.Metric1, simSettings.Metric2, simSettings.Metric3, simSettings.Metric4, simSettings.Metric5).FirstOrDefault();

            List <double> metricScores = new List <double>();

            foreach (var item in items)
            {
                double metric1 = simSettings.Metric1 == 0 ? 0 : item.Attributes.Select(a => a.Metric1).Sum() * (simSettings.Metric1 / 100);
                double metric2 = simSettings.Metric2 == 0 ? 0 : item.Attributes.Select(a => a.Metric2).Sum() * (simSettings.Metric2 / 100);
                double metric3 = simSettings.Metric3 == 0 ? 0 : item.Attributes.Select(a => a.Metric3).Sum() * (simSettings.Metric3 / 100);
                double metric4 = simSettings.Metric4 == 0 ? 0 : item.Attributes.Select(a => a.Metric4).Sum() * (simSettings.Metric4 / 100);
                double metric5 = simSettings.Metric5 == 0 ? 0 : item.Attributes.Select(a => a.Metric5).Sum() * (simSettings.Metric5 / 100);

                double metrics = metric1 + metric2 + metric3 + metric4 + metric5;

                metricScores.Add(metrics);
            }

            return(metricScores.Max());
        }
        public void TestBug38180()
        {
            var settings = new SimulationSettings()
            {
                AutoSelect = true,
                CompleteWithSpaceOrPunctuation = true,
                AutoCompleteEmptyMatch         = true,
                CompletionData = new [] { "Test", "test" }
            };

            var listWindow           = CreateListWindow(settings);
            var list                 = listWindow.CompletionDataList;
            var testCompletionWidget = (TestCompletionWidget)listWindow.CompletionWidget;

            SimulateInput(listWindow, "test\t");
            Assert.AreEqual("test", testCompletionWidget.CompletedWord);

            ContinueSimulation(listWindow, list, ref testCompletionWidget, "t\t");
            Assert.AreEqual("test", testCompletionWidget.CompletedWord);

            ContinueSimulation(listWindow, list, ref testCompletionWidget, "T\t");
            Assert.AreEqual("Test", testCompletionWidget.CompletedWord);
        }
        public void TestMruSimpleLastItem()
        {
            var settings = new SimulationSettings()
            {
                AutoSelect = true,
                CompleteWithSpaceOrPunctuation = true,
                AutoCompleteEmptyMatch         = true,
                CompletionData = new[] { "FooBar1", "Bar", "FooFoo2" }
            };

            var listWindow           = CreateListWindow(settings);
            var list                 = listWindow.CompletionDataList;
            var testCompletionWidget = (TestCompletionWidget)listWindow.CompletionWidget;

            SimulateInput(listWindow, "FooBar\t");
            Assert.AreEqual("FooBar1", testCompletionWidget.CompletedWord);

            ContinueSimulation(listWindow, list, ref testCompletionWidget, "FooFoo\t");
            Assert.AreEqual("FooFoo2", testCompletionWidget.CompletedWord);

            ContinueSimulation(listWindow, list, ref testCompletionWidget, "F\t");
            Assert.AreEqual("FooFoo2", testCompletionWidget.CompletedWord);
        }
        private void WaitForStatistics(Simulation simulation, SimulationSettings settings, CancellationToken token)
        {
            // Change status
            simulation.Status = SimulationStatuses.WaitingForStatistics;

            // Get statistics in parallel mode
            var statistics = new ConcurrentBag <Statistic>();

            simulation.ServerNodes.Where(n => n.IsConnected == true).ParallelForEach(node =>
            {
                var response = _httpService.Get($"{node.HttpAddress}/api/statistic", _nodeTimeout, token);
                if (response.IsSuccessStatusCode)
                {
                    var statistic = response.Content.ReadAs <SuccessResponse <Statistic> >();
                    statistics.Add(statistic.Result);
                }
            }, token);

            // Extract statistics and save them
            var scenarioId = simulation.ScenarioId.ToString();

            _statisticService.ExtractAndSaveStatistics(statistics.ToList(), settings, scenarioId);
        }
        private void WaitForNetwork(Simulation simulation, SimulationSettings settings)
        {
            do
            {
                // Change status and wait
                simulation.Status = SimulationStatuses.WaitingForNetwork;
                SpinWait.SpinUntil(() =>
                {
                    var wait = !simulation.ServerNodes.Where(n => n.IsConnected == true).Any(n => n.IsWorking);
                    if (!wait)
                    {
                        wait = HasSimulationTimeElapsed(simulation, settings);
                    }

                    return(wait);
                });

                // Safe wait for network hiccups
                Thread.Sleep(TimeSpan.FromSeconds(10));

                // If its still working than wait
            } while (simulation.ServerNodes.Where(n => n.IsConnected == true).Any(n => n.IsWorking));
        }
        public void SetSimSettings(SimulationSettings simSettings)
        {
            if (simSettings != null)
            {
                this.simSettings        = simSettings;
                SimType                 = simSettings.SimType;
                Sessions                = simSettings.Sessions;
                Hours                   = simSettings.Hours;
                Score                   = simSettings.Score;
                chkSimDisplay.IsChecked = simSettings.EnableSimDisplay;

                calculateMaxScore();
                simScoreSlider.Value      = simSettings.DefaultScorePercentage;
                simScoreSliderLbl.Content = simScoreSlider.Value + "%";

                switch (SimType)
                {
                case SimulationType.Sessions:
                    rdbSessions.IsChecked = true;
                    txtSimInput.Text      = Sessions.ToString();
                    showScoreSlider(false);
                    break;

                case SimulationType.Time:
                    rdbTime.IsChecked = true;
                    txtSimInput.Text  = Hours.ToString();
                    showScoreSlider(false);
                    break;

                default:
                    rdbScore.IsChecked = true;
                    txtSimInput.Text   = Score.ToString();
                    showScoreSlider(true);
                    break;
                }
            }
        }
        public void ExtractAndSaveStatistics(List <Statistic> statistics, SimulationSettings settings, string scenarioId)
        {
            var directoryPath = $@"{_directory}\statistics\{scenarioId}\{DateTime.UtcNow:yyyy-MM-dd-hh-mm-ss}";

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            try
            {
                SaveSettings(directoryPath, settings);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            try
            {
                CreateExcelFile(directoryPath, statistics, settings);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            try
            {
                CreateBlockchainTrees(statistics, directoryPath);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #10
0
        protected override void Context()
        {
            base.Context();
            var outputSchemaFactory   = IoC.Resolve <IOutputSchemaFactory>();
            var solverSettingsFactory = IoC.Resolve <ISolverSettingsFactory>();
            var simSettings1          = new SimulationSettings().WithName("Setting");
            var simSettings2          = new SimulationSettings().WithName("Setting");

            simSettings1.AddChartTemplate(new CurveChartTemplate().WithName("Temp"));
            simSettings1.OutputSchema     = outputSchemaFactory.CreateDefault();
            simSettings1.OutputSelections = new OutputSelections();
            simSettings1.OutputSelections.AddOutput(new QuantitySelection("root|comp1|Drug", QuantityType.Drug));
            simSettings1.Solver      = solverSettingsFactory.CreateCVODE();
            simSettings1.Solver.HMin = 1;

            simSettings2.AddChartTemplate(new CurveChartTemplate().WithName("Temp"));
            simSettings2.OutputSchema     = outputSchemaFactory.CreateDefault();
            simSettings2.OutputSelections = new OutputSelections();
            simSettings2.OutputSelections.AddOutput(new QuantitySelection("root|comp1|Drug", QuantityType.Drug));
            simSettings2.Solver = solverSettingsFactory.CreateCVODE();

            _object1 = simSettings1;
            _object2 = simSettings2;
        }
		public void TestMruEmptyMatch ()
		{
			var settings = new SimulationSettings () {
				AutoSelect = true,
				CompleteWithSpaceOrPunctuation = true,
				AutoCompleteEmptyMatch = true,
				CompletionData = new[] { "Foo", "Bar", "Test"}
			};

			var listWindow = CreateListWindow (settings);
			var list = listWindow.CompletionDataList;
			var testCompletionWidget = (TestCompletionWidget)listWindow.CompletionWidget;
			SimulateInput (listWindow, "Foo\t");
			ContinueSimulation (listWindow, list, ref testCompletionWidget, "F\t");
			Assert.AreEqual ("Foo", testCompletionWidget.CompletedWord);

			ContinueSimulation (listWindow, list, ref testCompletionWidget, "Bar\t");
			Assert.AreEqual ("Bar", testCompletionWidget.CompletedWord);

			ContinueSimulation (listWindow, list, ref testCompletionWidget, "\t");
			Assert.AreEqual ("Bar", testCompletionWidget.CompletedWord);
		}
 public EntityEditorSimulation(SimulationSettings settings, EntityDefinitionDatabase entityDefinitionDatabase) : base(settings, entityDefinitionDatabase)
 {
 }
Beispiel #13
0
 public ServerToServerConnectionViewModel(NodeBaseViewModel from, NodeBaseViewModel to, SimulationSettings worldSettings) :
     base(from, to)
 {
     this.worldSettings = worldSettings;
     StrokeThickness    = 5;
     Stroke             = Brushes.OrangeRed;
     //   DispatcherTimer timer = new DispatcherTimer();
     //  timer.Interval = new TimeSpan(0,0,1);
     //  timer.Tick += timer_Tick;
     //   timer.Start();
     Type = EdgeLineType.Bezier;
 }
https:  //www.c-sharpcorner.com/UploadFile/b942f9/implementing-a-double-ended-queue-or-deque-in-C-Sharp/


        //c'tors:

        public AbstractCellSimulation(SimulationSettings settings)
        {
            Settings = settings;
            stats1   = settings.TrackLifeStats ? new List <decimal>() : null;
        }
        public void Synchronize_SynchronizationNotPossible_Throws(IReadOnlyList<Ticker> tickers, SimulationSettings settings, string assertFailMessage)
        {
            Exception otherException = null;
            bool thrownArgumentException = false;

            try { SyncTickersFactory.Synchronize(tickers, settings); }
            catch (ArgumentException) { thrownArgumentException = true; }
            catch (Exception ex) { otherException = ex; }
            finally
            {
                Assert.True(thrownArgumentException,
                    "Expected ArgumentException after calling SyncTickersFactory.Synchronize. Test case: " + assertFailMessage +
                    (otherException == null ? "" : ". Got different exception: " + otherException.Message.ToString())
                    );
            }
        }
 public void CanSynchronize_SynchronizationPossible_ReturnsTrue(IReadOnlyList<Ticker> tickers, SimulationSettings settings, string testCase)
 {
     string error;
     Assert.True(SyncTickersFactory.CanSynchronize(tickers, settings, out error));
 }
Beispiel #17
0
        //c'tors:

        public BinaryCellSimulation(SimulationSettings settings) : base(settings)
        {
            ring  = new BinaryRingBuffer3D(settings.MemSlots, settings.SizeX, settings.SizeY);
            aring = ring;
        }
Beispiel #18
0
        public RaftDiagramDefinition(RaftSoundPlayer raftEventListener, INetworkModel networkModel, SimulationSettings worldSettings)
        {
            this.raftEventListener  = raftEventListener;
            this.simulationSettings = worldSettings;

            // brokers
            AddModelFor <BrokerViewModel, DiagramNodeBroker>(
                "Broker",
                (p) => new BrokerViewModel(string.Format("Br{0}", brokerNo++))
            {
                Location = p
            },
                (vm) => new DiagramNodeBroker()
            {
                Location = vm.Location, Name = vm.Name
            },
                (m) => new BrokerViewModel(m.Name)
            {
                Location = m.Location
            }
                );

            // clients
            AddModelFor <ClientViewModel, DiagramNodeClient>(
                "NetworkClient",
                (p) =>
            {
                string cliendId       = (clientNo++).ToString();
                RaftClient raftClient = new RaftClient(networkModel, cliendId);
                return(new ClientViewModel(raftClient)
                {
                    Location = p
                });
            },
                (vm) => new DiagramNodeClient()
            {
                Location = vm.Location, Name = vm.Name
            },
                (m) =>
            {
                RaftClient raftClient = new RaftClient(networkModel, m.Name);
                return(new ClientViewModel(raftClient)
                {
                    Location = m.Location
                });
            }
                );

            // servers
            AddModelFor <ServerViewModel, DiagramNodeServer>(
                "Server",
                (p) =>
            {
                serverNo++;
                string raftNodeId       = serverNo.ToString();
                RaftHost serverSoftware = new RaftHost(networkModel, raftEventListener, simulationSettings, raftNodeId);
                //this looks nasty
                return(new ServerViewModel(serverSoftware)
                {
                    Location = p
                });
            },
                (vm) => new DiagramNodeServer()
            {
                Location = vm.Location, Name = vm.Name
            },
                (m) =>
            {
                RaftHost serverSoftware = new RaftHost(networkModel, raftEventListener, simulationSettings, m.Name);
                return(new ServerViewModel(serverSoftware)
                {
                    Location = m.Location
                });
            }
                );
        }
Beispiel #19
0
        public void NodeConnectorService_ShouldAttachEndNodes()
        {
            using (var mock = AutoMock.GetLoose((a) =>
            {
                a.RegisterType <ChainLinkFactory>().AsImplementedInterfaces();
                a.RegisterType <ConveyorConnector>().AsImplementedInterfaces();
            }))
            {
                var factoryMock = new Mock <IChainLinkFactory>();
                factoryMock.Setup(f => f.CreateConveyorConnector()).Returns(new Mock <IConveyorConnector>().Object);
                var connector = new NodeConnectorService(factoryMock.Object);

                var conveyorId = Guid.NewGuid().ToString();
                var aaId       = Guid.NewGuid().ToString();

                var checkInDispatcherMock = new Mock <ICheckInDispatcher>();
                var aaDispatcherMock      = new Mock <IAADispatcher>();
                var bagCollectorMock      = new Mock <IBagCollector>();
                var conveyorMock          = new Mock <IOneToOneConveyor>();
                conveyorMock.Setup(m => m.NodeId).Returns(conveyorId);
                var aaMock = new Mock <IAa>();
                aaMock.Setup(m => m.NodeId).Returns(aaId);
                aaMock.Setup(m => m.AddSuccessor(bagCollectorMock.Object));

                var aa = new NodeCreationData()
                {
                    Id        = aaId,
                    NextNodes = null,
                    Type      = BuildingComponentType.AA
                };
                var conveyor = new NodeCreationData()
                {
                    Id        = conveyorId,
                    NextNodes = new Dictionary <NodeCreationData, int?>()
                    {
                        { aa, 0 }
                    },
                    Type = BuildingComponentType.Conveyor
                };

                var simulationSettings = new SimulationSettings()
                {
                    Nodes = new List <NodeCreationData>()
                    {
                        aa, conveyor
                    }
                };

                var nodes = new List <IChainLink>()
                {
                    bagCollectorMock.Object,
                    aaDispatcherMock.Object,
                    checkInDispatcherMock.Object,
                    conveyorMock.Object,
                    aaMock.Object
                };

                connector.ConnectNodes(nodes, simulationSettings.Nodes);

                aaMock.Verify(m => m.AddSuccessor(bagCollectorMock.Object), Times.Once);
            }
        }
Beispiel #20
0
        private IEnumerator SimulateGeneration()
        {
            var solutions     = new Solution[Settings.PopulationSize];
            var solutionIndex = 0;
            // Prepare batch simulation
            int actualBatchSize      = Settings.SimulateInBatches ? Settings.BatchSize : Settings.PopulationSize;
            int numberOfBatches      = (int)Math.Ceiling((double)this.Settings.PopulationSize / actualBatchSize);
            int firstChromosomeIndex = 0;

            // Cache values that can be changed during the simulation
            this.cachedSettings = this.Settings;

            if (NewGenerationDidBegin != null)
            {
                NewGenerationDidBegin();
            }

            for (int i = 0; i < numberOfBatches; i++)
            {
                this.currentBatchNumber = i + 1;
                int remainingCreatures = Settings.PopulationSize - (i * actualBatchSize);
                int currentBatchSize   = Math.Min(actualBatchSize, remainingCreatures);

                var sceneLoadConfig = new SceneController.SimulationSceneLoadConfig(
                    this.SimulationData.CreatureDesign,
                    currentBatchSize,
                    this.SimulationData.SceneDescription,
                    SceneController.SimulationSceneType.Simulation,
                    GetLegacySimulationOptions()
                    );

                var context      = new SceneController.SimulationSceneLoadContext();
                var sceneContext = new SimulationSceneContext(this.SimulationData);

                yield return(SceneController.LoadSimulationScene(sceneLoadConfig, context, sceneContext));

                this.batchPhysicsScene = context.PhysicsScene;

                var batch = context.Creatures;
                this.currentCreatureBatch = batch;

                var chromosomeCount = Math.Min(this.SimulationData.CurrentChromosomes.Length, batch.Length);
                var chromosomes     = new float[chromosomeCount][];
                for (int c = 0; c < chromosomeCount; c++)
                {
                    chromosomes[c] = this.SimulationData.CurrentChromosomes[c + firstChromosomeIndex];
                }
                firstChromosomeIndex += batch.Length;
                ApplyBrains(batch, chromosomes);

                yield return(SimulateBatch());

                // Evaluate creatures and destroy the scene after extracting all
                // required performance statistics
                for (int j = 0; j < batch.Length; j++)
                {
                    var creature = batch[j];
                    solutions[solutionIndex++] = new Solution()
                    {
                        Encodable = creature.brain.Network,
                        Stats     = creature.GetStatistics(this.cachedSettings.SimulationTime)
                    };
                }

                yield return(SceneManager.UnloadSceneAsync(context.Scene));
            }

            EvaluateSolutions(solutions);
        }
Beispiel #21
0
 public void SetSettings(SimulationSettings settings)
 {
     this._simulationSettings = settings;
 }
 public void CanSynchronize_WrongTestCase_ReturnsFalse(IReadOnlyList<Ticker> tickers, SimulationSettings settings, string assertFailMessage)
 {
     string error;
     Assert.False(SyncTickersFactory.CanSynchronize(tickers, settings, out error));
 }
Beispiel #23
0
        private void fillControls()
        {
            #region Game-Settings

            // Limits
            roundsNumericUpDown.Minimum = SimulatorConfiguration.ROUNDSMIN;
            roundsNumericUpDown.Maximum = SimulatorConfiguration.ROUNDSMAX;
            loopsNumericUpDown.Minimum  = SimulatorConfiguration.LOOPSMIN;
            loopsNumericUpDown.Maximum  = SimulatorConfiguration.LOOPSMAX;

            // Values
            roundsNumericUpDown.Value = setup.SimulatorConfiguration.RoundCount;
            loopsNumericUpDown.Value  = setup.SimulatorConfiguration.LoopCount;

            int initValue = Math.Abs(setup.SimulatorConfiguration.MapInitialValue);
            mapInitCheckBox.Checked = (initValue != 0);
            check_mapInit(null, null);
            mapGeneratorMaskedTextBox.Text = initValue.ToString("000000000");

            #endregion

            #region Debug and Timeouts

            // Limits
            loopTimeoutNumericUpDown.Minimum  = SimulatorConfiguration.LOOPTIMEOUTMIN;
            loopTimeoutNumericUpDown.Maximum  = int.MaxValue;
            roundTimeoutNumericUpDown.Minimum = SimulatorConfiguration.ROUNDTIMEOUTMIN;
            roundTimeoutNumericUpDown.Maximum = int.MaxValue;

            // Values
            debugInfoCheckBox.Checked = setup.SimulatorConfiguration.AllowDebuginformation;
            check_timeouts(null, null);
            ignoreTimeoutsCheckBox.Checked  = setup.SimulatorConfiguration.IgnoreTimeouts;
            loopTimeoutNumericUpDown.Value  = setup.SimulatorConfiguration.LoopTimeout;
            roundTimeoutNumericUpDown.Value = setup.SimulatorConfiguration.RoundTimeout;

            #endregion

            #region Security

            // Values
            allowIoCheckBox.Checked      = setup.SimulatorConfiguration.AllowFileAccess;
            allowDbCheckBox.Checked      = setup.SimulatorConfiguration.AllowDatabaseAccess;
            allowUiCheckBox.Checked      = setup.SimulatorConfiguration.AllowUserinterfaceAccess;
            allowRefCheckBox.Checked     = setup.SimulatorConfiguration.AllowReferences;
            allowNetworkCheckBox.Checked = setup.SimulatorConfiguration.AllowNetworkAccess;

            #endregion

            #region Core-Settings

            // Set Default
            presetComboBox.Items.Add(SimulationSettings.Default);

            // Other Presets
            using (var stream = new MemoryStream(Presets.CaptureTheApple))
                presetComboBox.Items.Add(SimulationSettings.LoadSettings(stream));
            using (var stream = new MemoryStream(Presets.Debugging))
                presetComboBox.Items.Add(SimulationSettings.LoadSettings(stream));
            using (var stream = new MemoryStream(Presets.Heros))
                presetComboBox.Items.Add(SimulationSettings.LoadSettings(stream));
            using (var stream = new MemoryStream(Presets.SugarRun))
                presetComboBox.Items.Add(SimulationSettings.LoadSettings(stream));
            using (var stream = new MemoryStream(Presets.SurvivalOfTheFittest))
                presetComboBox.Items.Add(SimulationSettings.LoadSettings(stream));

            // Enumerate all known settingsfiles and add them to the combobox
            List <string> lostSettingsFiles = new List <string>();
            foreach (string knownSettingFile in setup.KnownSettingFiles)
            {
                try
                {
                    SimulationSettings settings = SimulationSettings.LoadSettings(knownSettingFile);
                    presetComboBox.Items.Add(settings);
                }
                catch (Exception)
                {
                    // TODO: Lokalisieren
                    MessageBox.Show("Fehler beim Laden der Settings-Datei " + knownSettingFile + ". Diese Datei wird aus der Liste der bekannten Settings entfernt.");
                    lostSettingsFiles.Add(knownSettingFile);
                }
            }

            // Remove all lost settingsfiles
            foreach (string lostSettingsFile in lostSettingsFiles)
            {
                setup.KnownSettingFiles.Remove(lostSettingsFile);
            }

            // Preselect current settings
            presetComboBox.SelectedItem = setup.SimulatorConfiguration.Settings;

            #endregion
        }
Beispiel #24
0
    /// <summary>
    /// Initializes a new instance of the <see cref="Simulation"/> class.
    /// </summary>
    public Simulation()
    {
      Settings = new SimulationSettings();

      var collisionDetection = new CollisionDetection
      {
        CollisionFilter = new CollisionFilter(),
        FullContactSetPerFrame = true
      };
      CollisionDomain = new CollisionDomain(collisionDetection);

      ConstraintSolver = new SequentialImpulseBasedSolver(this);

      Constraints = new ConstraintCollection();
      Constraints.CollectionChanged += OnConstraintsChanged;

      ForceEffects = new ForceEffectCollection();
      ForceEffects.CollectionChanged += OnForceEffectsChanged;

      RigidBodies = new RigidBodyCollection();
      RigidBodies.CollectionChanged += OnRigidBodiesChanged;

      ContactConstraintsInternal = new List<ContactConstraint>();

      IslandManager = new SimulationIslandManager(this);

      // Define the "World" as a rigid body.
      //   - World is an imaginary body that is used to define the space of the simulation.
      //   - The user can use World in constraints e.g. to anchor objects in the world.
      //   - No contacts are computed for World.
      World = new RigidBody(new BoxShape(20000, 20000, 20000))
      {
        CollisionResponseEnabled = false,
        CollisionObject = { Type = CollisionObjectType.Trigger },
        MotionType = MotionType.Static,
        Name = "World",
        Simulation = this,
      };

      // Remove "World" from the collision domain. 
      CollisionDomain.CollisionObjects.Remove(World.CollisionObject);


      Diagnostics = new SimulationDiagnostics();


      // Store delegate methods to avoid garbage when multithreading.
      _updateVelocityMethod = i =>
      {
        var body = RigidBodies[i];
        body.UpdateVelocity(_fixedTimeStep);
      };
      _solveIslandMethod = SolveIsland;
      _updatePoseMethod = i =>
      {
        var body = RigidBodies[i];
        body.UpdatePose(_fixedTimeStep);
      };
      _computeTimeOfImpactMethod = ComputeTimeOfImpact_Multithreaded;
      _moveToTimeOfImpactMethod = MoveToTimeOfImpact;
    }
 public void Synchronize_DescriptionsAreCorrect(IReadOnlyList<Ticker> tickers, SimulationSettings settings, SyncTickers expected, string testCase)
 {
     var sut = SyncTickersFactory.Synchronize(tickers, settings);
     Assert.True(expected.Descriptions.SequenceEqual(sut.Descriptions, new TickerDescriptionTests.TickerDescriptionComparer()),
         "Ticker descriptions are not correct.");
 }
Beispiel #26
0
    /// <summary>
    /// Loads the simulation from save file of format version 1.
    /// </summary>
    /// <param name="name">The name of the simualtion save.</param>
    /// <param name="content">The Content of the save file.</param>
    public static SimulationData ParseSimulationData(string name, string content, LegacySimulationLoader.SplitOptions splitOptions)
    {
        var creatureName = name.Split('-')[0].Replace(" ", "");

        if (string.IsNullOrEmpty(creatureName))
        {
            creatureName = "Unnamed";
        }

        var components = content.Split(splitOptions.SPLIT_ARRAY, System.StringSplitOptions.None);

        // extract the save data from the file contents.
        var objectiveType = ObjectiveUtil.ObjectiveForNumber(int.Parse(components[0].Replace(Environment.NewLine, "")));

        var timePerGen = int.Parse(components[1].Replace(Environment.NewLine, ""));

        var creatureData   = components[2];
        var creatureDesign = CreatureSerializer.ParseCreatureDesign(creatureData, creatureName);

        var bestChromosomesData = new List <string>(components[3].Split(splitOptions.NEWLINE_SPLIT, StringSplitOptions.None));
        var bestChromosomes     = new List <ChromosomeData>();

        foreach (var chromosomeData in bestChromosomesData)
        {
            if (chromosomeData != "")
            {
                // Parse the chromosome data
                var parts           = chromosomeData.Split(':');
                var chromosome      = parts[0];
                var fitness         = float.Parse(parts[1]);
                var chromosomeStats = new ChromosomeStats(chromosome, new CreatureStats());
                chromosomeStats.stats.fitness = fitness;
                var data = new StringChromosomeData(chromosome, chromosomeStats.stats);
                bestChromosomes.Add(data.ToChromosomeData());
            }
        }

        var chromosomeComponents = components[4].Split(splitOptions.NEWLINE_SPLIT, StringSplitOptions.None);
        var currentChromosomes   = new List <float[]>();

        foreach (var chromosome in chromosomeComponents)
        {
            if (chromosome != "")
            {
                currentChromosomes.Add(ConversionUtils.BinaryStringToFloatArray(chromosome));
            }
        }

        var currentGeneration = bestChromosomes.Count + 1;

        var settings = new SimulationSettings();

        settings.Objective      = objectiveType;
        settings.SimulationTime = timePerGen;
        settings.PopulationSize = currentChromosomes.Count;

        var networkSettings  = NeuralNetworkSettings.Default;
        var sceneDescription = DefaultSimulationScenes.DefaultSceneForObjective(settings.Objective);

        sceneDescription.PhysicsConfiguration = ScenePhysicsConfiguration.Legacy;

        int lastSimulatedV2Generation = bestChromosomes.Count;

        return(new SimulationData(
                   settings, networkSettings, creatureDesign,
                   sceneDescription, bestChromosomes,
                   currentChromosomes.ToArray(),
                   lastSimulatedV2Generation
                   ));
    }
Beispiel #27
0
        public static void Run()
        {
            try
            {
                int numScreens = Screen.AllScreens.Length;
                if (numScreens != 1 && numScreens != 2)
                {
                    throw new NotImplementedException("Only supports single and dual monitor setup!");
                }

                SimulationSettings simSettings = SimulatorResources.GetSimulationSettings();

                if (simSettings.RenderMode == RenderModes.Stereo && numScreens < 2)
                {
                    Console.WriteLine(@"Could not run stereo mode. Can't find two monitors connected?");
                    simSettings.RenderMode = RenderModes.Normal;
                }

                IntPtr rightEyeWindow = IntPtr.Zero;
                if (simSettings.RenderMode == RenderModes.Stereo)
                {
                    rightEyeWindow = SpawnRightEyeWindow();
                }

                // Start the simulator game entry point
                using (var game = new SimulatorGame(simSettings, rightEyeWindow))
                {
                    // Make sure the XNA game window (left eye) displays as a full screen window
                    // just as the one we just created for the right eye
                    var gameForm = (Form)System.Windows.Forms.Control.FromHandle(game.Window.Handle);
                    gameForm.FormBorderStyle = FormBorderStyle.None;
                    gameForm.LostFocus      += (sender, e) => game.IsCapturingMouse = false;
                    gameForm.GotFocus       += (sender, e) => Game_GotFocus(game);
                    gameForm.MouseClick     += (sender, e) =>
                    {
                        if (e.Button == MouseButtons.Right)
                        {
                            Game_MouseRightClick(game);
                        }
                    };

                    // Name the window according to mode
                    gameForm.Text = (simSettings.RenderMode == RenderModes.Stereo)
                                        ? "A²DS Stereoscopy (left eye)"
                                        : "A²DS";

                    _settingsController = new SettingsController(gameForm);

                    // Hook the settings controller to the simulator by events, so changes in PID settings causes
                    // autopilot to use new PID settings.
                    _settingsController.PIDSettingsChanged +=
                        () => game.SetPIDSetup(_settingsController.CurrentPIDSetup);

                    // Run the game code
                    game.Run();
                }
            }
            catch (Exception e)
            {
                string msg = "Error occured!\n\n" + e;
                Console.WriteLine(e);
                MessageBox.Show(msg);
            }
        }
        public void SimulationSettings_Clone_ClonesRememberedChilds()
        {
            var container = new SimulationSettings();
            var setting = container.Get<CloseAllOnLastBarSetting>();
            setting.Value = !setting.Value;

            var sut = (container.Clone() as SimulationSettings);

            Assert.Equal<bool>(setting.Value, sut.Get<CloseAllOnLastBarSetting>().Value);
        }
Beispiel #29
0
 public void InjectSettings(SimulationSettings s)
 {
     settings = s;
 }
        public void SimulationSettings_Clone_InvokesCloneOnChilds(Type settingType)
        {
            var container = new SimulationSettings();
            MethodInfo getMethod = typeof(SimulationSettings).GetMethod("Get");
            MethodInfo genericGetMethod = getMethod.MakeGenericMethod(settingType);

            object fromGetOnOriginal = genericGetMethod.Invoke(container, null);
            var sut = (container.Clone() as SimulationSettings);
            object fromGetOnClone = genericGetMethod.Invoke(sut, null);

            Assert.NotSame(fromGetOnOriginal, fromGetOnClone);
        }
        public void Synchronize_ObservationsAreCorrect(IReadOnlyList<Ticker> tickers, SimulationSettings settings, SyncTickers expected, string testCase)
        {
            Func<IEnumerable<Observation>, string> printer = x => x.Select((o, iO) => string.Format("[{0}: ({2}) {1}]", iO, o.Date,
                    o.CurrentQuoteCount.Select(i => i.ToString()).Aggregate((s1, s2) => s1 + "," + s2))).Aggregate((s1, s2) => s1 + "," + s2);

            var sut = SyncTickersFactory.Synchronize(tickers, settings);
            Assert.True(expected.SequenceEqual(sut, new ObservationTests.ObservationComparer()),
                "Observation are not correct."+
                " Expected: "+printer(expected)+
                ". Got: "+printer(sut));
        }
Beispiel #32
0
 public void AddChartTemplate(CurveChartTemplate chartTemplate)
 {
     SimulationSettings.AddChartTemplate(chartTemplate);
 }
        //c'tors:

        public GenericCellSimulation(SimulationSettings settings) : base(settings)
        {
            ring  = new GenericRingBuffer3D <C>(settings.MemSlots, settings.SizeX, settings.SizeY);
            aring = ring;
        }
 public void Synchronize_TickersAreCorrect(IReadOnlyList<Ticker> tickers, SimulationSettings settings, SyncTickers expected, string testCase)
 {
     var sut = SyncTickersFactory.Synchronize(tickers, settings);
     Assert.True(expected.SimplifiedTickers.SequenceEqual(sut.SimplifiedTickers, new SimplifiedTickerTests.SimplifiedTickerComparer()),
         "Simplified tickers are not correct.");
 }
 public ClientToServerConnectionViewModel(NodeBaseViewModel from, NodeBaseViewModel to, SimulationSettings worldSettings) :
     base(from, to)
 {
     StrokeThickness    = 2;
     this.worldSettings = worldSettings;
 }
Beispiel #36
0
 protected override void Context()
 {
     sut = new SimulationSettings();
 }
Beispiel #37
0
 public SimulationProject()
 {
     Graph = new Graph.Graph();
     SimulationSettings = SimulationSettings.Default;
 }
Beispiel #38
0
 public CurveChartTemplate ChartTemplateByName(string templateName)
 {
     return(SimulationSettings.ChartTemplateByName(templateName));
 }
 static string RunSimulation(SimulationSettings settings)
 {
     CompletionListWindow listWindow = CreateListWindow (settings);
     SimulateInput (listWindow, settings.SimulatedInput);
     return ((TestCompletionWidget)listWindow.CompletionWidget).CompletedWord;
 }
Beispiel #40
0
 public void RemoveAllChartTemplates()
 {
     SimulationSettings.RemoveAllChartTemplates();
 }
        public void SimulationSettings_Get_CanInitializeAllSettings(Type settingType)
        {
            var sut = new SimulationSettings();
            MethodInfo getMethod = typeof(SimulationSettings).GetMethod("Get");
            MethodInfo genericGetMethod = getMethod.MakeGenericMethod(settingType);

            Assert.NotNull(genericGetMethod.Invoke(sut, null));
        }
 public void CanSynchronize_WrongTestCase_SetsNotEmptyError(IReadOnlyList<Ticker> tickers, SimulationSettings settings, string assertFailMessage)
 {
     string error;
     SyncTickersFactory.CanSynchronize(tickers, settings, out error);
     Assert.False(string.IsNullOrEmpty(error), "Error string is empty but should contain explanation message.");
 }
Beispiel #43
0
 public void RemoveChartTemplate(string chartTemplateName)
 {
     SimulationSettings.RemoveChartTemplate(chartTemplateName);
 }
        public void SimulationSettings_Get_RemembersCreatedObject(Type settingType)
        {
            var sut = new SimulationSettings();
            MethodInfo getMethod = typeof(SimulationSettings).GetMethod("Get");
            MethodInfo genericGetMethod = getMethod.MakeGenericMethod(settingType);

            object fromFirstGet = genericGetMethod.Invoke(sut, null);
            object fromSecondGet = genericGetMethod.Invoke(sut, null);

            Assert.Same(fromFirstGet, fromSecondGet);
        }