Ejemplo n.º 1
0
        protected override void Context()
        {
            _sensitivityAnalysisTask = A.Fake <ISensitivityAnalysisTask>();
            _simulationAnalyzer      = A.Fake <ISimulationAnalyzer>();
            _parameterSelector       = A.Fake <IParameterAnalysableParameterSelector>();
            _containerTask           = A.Fake <IContainerTask>();

            _simulation              = A.Fake <ISimulation>();
            _sensitivityAnalysis     = new SensitivityAnalysis(_simulation);
            _coreSensitivityAnalysis = new Core.Domain.SensitivityAnalyses.SensitivityAnalysis();

            sut = new SensitivityAnalysisToCoreSensitivityAnalysisMapper(_sensitivityAnalysisTask, _simulationAnalyzer, _parameterSelector, _containerTask);

            _constantParameterCache = new PathCacheForSpecs <IParameter>
            {
                { _parameterPath1, DomainHelperForSpecs.ConstantParameterWithValue(10).WithName("P1") },
                { _parameterPath2, DomainHelperForSpecs.ConstantParameterWithValue(10).WithName("P2") },
                { _parameterPath3, DomainHelperForSpecs.ConstantParameterWithValue(10).WithName("P3") }
            };

            A.CallTo(() => _sensitivityAnalysisTask.CreateSensitivityAnalysisFor(_simulation)).Returns(_coreSensitivityAnalysis);
            A.CallTo(_containerTask).WithReturnType <PathCache <IParameter> >().Returns(_constantParameterCache);

            _allSensitivityParametersCreated = new List <ParameterSelection>();
            A.CallTo(() => _sensitivityAnalysisTask.AddParametersTo(_coreSensitivityAnalysis, A <IReadOnlyList <ParameterSelection> > ._))
            .Invokes(x => _allSensitivityParametersCreated.AddRange(x.GetArgument <IReadOnlyList <ParameterSelection> >(1)));
        }
Ejemplo n.º 2
0
        protected override void Context()
        {
            _view                               = A.Fake <IParameterIdentificationSimulationSelectionView>();
            _treeNodeFactory                    = A.Fake <ITreeNodeFactory>();
            _applicationController              = A.Fake <IApplicationController>();
            _lazyLoadTask                       = A.Fake <ILazyLoadTask>();
            _treeNodeContextMenuFactory         = A.Fake <ITreeNodeContextMenuFactory>();
            _multipleTreeNodeContextMenuFactory = A.Fake <IMultipleTreeNodeContextMenuFactory>();
            _dialogCreator                      = A.Fake <IDialogCreator>();
            _parameterIdentificationTask        = A.Fake <IParameterIdentificationTask>();
            sut = new ParameterIdentificationSimulationSelectionPresenter(_view, _treeNodeFactory, _applicationController, _lazyLoadTask, _treeNodeContextMenuFactory,
                                                                          _multipleTreeNodeContextMenuFactory, _dialogCreator, _parameterIdentificationTask);

            _parameterIdentification = new ParameterIdentification();
            _simulation = A.Fake <ISimulation>().WithId("Id").WithName("S");
            _parameterIdentification.AddSimulation(_simulation);
            _outputMapping = new OutputMapping
            {
                OutputSelection = new SimulationQuantitySelection(_simulation, new QuantitySelection("PATH", QuantityType.Drug))
            };
            _parameterIdentification.AddOutputMapping(_outputMapping);

            _simulationNode = A.Fake <ITreeNode>();
            A.CallTo(() => _treeNodeFactory.CreateFor(_simulation)).Returns(_simulationNode);

            _simulationSelectionPresenter = A.Fake <ISelectionSimulationPresenter>();
            A.CallTo(() => _applicationController.Start <ISelectionSimulationPresenter>()).Returns(_simulationSelectionPresenter);

            sut.EditParameterIdentification(_parameterIdentification);
        }
Ejemplo n.º 3
0
 protected override void Context()
 {
     _oldSimulation = A.Fake <ISimulation>();
     sut            = new SensitivityAnalysis {
         Simulation = _oldSimulation
     };
 }
        // Schedule() implementation for ITriggerEventsJob when Havok Physics is available
        public static unsafe JobHandle Schedule <T>(this T jobData, ISimulation simulation, ref PhysicsWorld world, JobHandle inputDeps)
            where T : struct, ITriggerEventsJob
        {
            switch (simulation.Type)
            {
            case SimulationType.UnityPhysics:
                // Call the scheduling method for Unity.Physics
                return(ITriggerEventJobExtensions.ScheduleUnityPhysicsTriggerEventsJob(jobData, simulation, ref world, inputDeps));

            case SimulationType.HavokPhysics:
            {
                var data = new TriggerEventJobData <T>
                {
                    UserJobData = jobData,
                    EventReader = ((Havok.Physics.HavokSimulation)simulation).TriggerEvents
                };

                // Ensure the input dependencies include the end-of-simulation job, so events will have been generated
                inputDeps = JobHandle.CombineDependencies(inputDeps, simulation.FinalSimulationJobHandle);

                var parameters = new JobsUtility.JobScheduleParameters(
                    UnsafeUtility.AddressOf(ref data),
                    TriggerEventJobProcess <T> .Initialize(), inputDeps, ScheduleMode.Batched);
                return(JobsUtility.Schedule(ref parameters));
            }

            default:
                return(inputDeps);
            }
        }
Ejemplo n.º 5
0
 // Use this for initialization
 void Start()
 {
     hair = HairFactory.GrowHairOnDefinedPos(50, 1f, new List <Vector3>(ScalpMF.sharedMesh.vertices), 0.01f);
     Visualizer.Init(gameObject.GetComponent <MeshFilter>());
     sim = new FTL(hair);
     sim.AddForce(new Vector3(5, 0, 0));
 }
Ejemplo n.º 6
0
        // Schedule() implementation for IContactsJob when Havok Physics is available
        public static unsafe JobHandle Schedule <T>(this T jobData, ISimulation simulation, ref PhysicsWorld world, JobHandle inputDeps)
            where T : struct, IContactsJobBase
        {
            switch (simulation.Type)
            {
            case SimulationType.UnityPhysics:
                // Call the scheduling method for Unity.Physics
                return(IContactsJobExtensions.ScheduleUnityPhysicsContactsJob(jobData, simulation, ref world, inputDeps));

            case SimulationType.HavokPhysics:
            {
                var data = new ContactsJobData <T>
                {
                    UserJobData        = jobData,
                    ManifoldStream     = ((Havok.Physics.HavokSimulation)simulation).ManifoldStream,
                    PluginIndexToLocal = ((Havok.Physics.HavokSimulation)simulation).PluginIndexToLocal,
                    Bodies             = world.Bodies
                };
                var parameters = new JobsUtility.JobScheduleParameters(
                    UnsafeUtility.AddressOf(ref data),
                    ContactsJobProcess <T> .Initialize(), inputDeps, ScheduleMode.Batched);
                return(JobsUtility.Schedule(ref parameters));
            }

            default:
                return(inputDeps);
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BindingContext"/> class.
 /// </summary>
 /// <param name="entity">The entity creating the behavior.</param>
 /// <param name="simulation">The simulation for which a behavior is created.</param>
 /// <param name="behaviors">The behavior container.</param>
 /// <exception cref="ArgumentNullException">Thrown if <paramref name="entity"/> or <paramref name="simulation"/> is <c>null</c>.</exception>
 public BindingContext(IEntity entity, ISimulation simulation, IBehaviorContainer behaviors)
 {
     Entity     = entity.ThrowIfNull(nameof(entity));
     Simulation = simulation.ThrowIfNull(nameof(simulation));
     Behaviors  = behaviors;
     _cloned    = entity.LinkParameters ? null : new Dictionary <IParameterSet, IParameterSet>();
 }
Ejemplo n.º 8
0
        private void FileOpen(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                openSimulationFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;

                if (openSimulationFileDialog.ShowDialog(this) == DialogResult.OK)
                {
                    fileName = openSimulationFileDialog.FileName;
                }
            }

            if (!string.IsNullOrEmpty(fileName))
            {
                this.ClearSimulation();
                _simulation = new LangtonsAntSimulation(this);

                try
                {
                    this.SetStatus("Loading simulation...");
                    _simulation.Load(fileName);
                    _simulationFileName = fileName;

                    this.InitializeSimulation(_simulation);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("Failed to open simulation. {0}", ex.Message), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                finally
                {
                    this.SetStatus(string.Empty);
                }
            }
        }
Ejemplo n.º 9
0
        private void addPKParametersForOutput(ISimulation simulation, int numberOfIndividuals, SimulationResults runResults, Action <int> performIndividualScalingAction,
                                              QuantitySelection selectedQuantity, PopulationSimulationPKAnalyses popAnalyses, string moleculeName,
                                              PKCalculationOptions pkCalculationOptions, IReadOnlyList <PKCalculationOptionsFactory.ApplicationParameters> allApplicationParameters)
        {
            var availablePKParameters = _pkParameterRepository.All().Where(p => PKParameterCanBeUsed(p, pkCalculationOptions)).ToList();

            //create pk parameter for each quantities
            foreach (var pkParameter in availablePKParameters)
            {
                var quantityPKParameter = new QuantityPKParameter {
                    Name = pkParameter.Name, QuantityPath = selectedQuantity.Path, Dimension = pkParameter.Dimension
                };
                quantityPKParameter.SetNumberOfIndividuals(numberOfIndividuals);
                popAnalyses.AddPKAnalysis(quantityPKParameter);
            }

            //add the values for each individual
            foreach (var individualResult in runResults.AllIndividualResults)
            {
                performIndividualScalingAction(individualResult.IndividualId);
                _pkCalculationOptionsFactory.UpdateAppliedDose(simulation, moleculeName, pkCalculationOptions, allApplicationParameters);

                var values   = individualResult.ValuesFor(selectedQuantity.Path);
                var pkValues = _pkValuesCalculator.CalculatePK(individualResult.Time.Values, values.Values, pkCalculationOptions);

                foreach (var pkParameter in availablePKParameters)
                {
                    var quantityPKParameter = popAnalyses.PKParameterFor(selectedQuantity.Path, pkParameter.Name);
                    quantityPKParameter.SetValue(individualResult.IndividualId, pkValues.ValueOrDefaultFor(pkParameter.Name));
                }
            }
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            ISimulation sim = Simulation.getInstance();

            sim.Display = Display.getInstance();
            sim.Start();
        }
Ejemplo n.º 11
0
        protected override void Context()
        {
            base.Context();
            _simulation = A.Fake <ISimulation>();
            _runResults = A.Fake <SimulationResults>();
            var outputSelections = new OutputSelections();

            outputSelections.AddOutput(new QuantitySelection("Liver|Cell|Drug|Concentration", QuantityType.Drug));

            A.CallTo(() => _simulation.OutputSelections).Returns(outputSelections);
            var pKCalculationOptions = new PKCalculationOptions();

            A.CallTo(_pkCalculationOptionsFactory).WithReturnType <PKCalculationOptions>().Returns(pKCalculationOptions);

            _p1      = new PKParameter().WithName("AUC");
            _p1.Mode = PKParameterMode.Single;
            _p2      = new PKParameter().WithName("AUC" + Constants.PKParameters.NormSuffix);
            _p2.Mode = PKParameterMode.Single;

            A.CallTo(() => _pkParameterRepository.All()).Returns(new[] { _p1, _p2 });
            var individualResults = A.Fake <IndividualResults>();

            A.CallTo(() => _runResults.AllIndividualResults).Returns(new HashSet <IndividualResults>(new [] { individualResults }));
            var pKValues = new PKValues();

            pKValues.AddValue(_p1.Name, 10f);
            pKValues.AddValue(_p2.Name, 20f);
            A.CallTo(_pkValuesCalculator).WithReturnType <PKValues>().Returns(pKValues);
        }
Ejemplo n.º 12
0
        private void addSimulationToView(ISimulation simulation)
        {
            _lazyLoadTask.Load(simulation);
            var simulationNode = _treeNodeFactory.CreateFor(simulation);

            _view.AddNode(simulationNode);
        }
        protected override void Context()
        {
            _cloneManager               = A.Fake <ICloneManagerForModel>();
            _simulationFactory          = A.Fake <ICoreSimulationFactory>();
            _parameterIdentificationRun = A.Fake <IParameterIdentificationRun>();
            _coreUserSettings           = A.Fake <ICoreUserSettings>();
            _descriptionCreator         = A.Fake <ICategorialParameterIdentificationDescriptionCreator>();
            _container = A.Fake <Utility.Container.IContainer>();
            A.CallTo(() => _container.Resolve <ICoreSimulationFactory>()).Returns(_simulationFactory);
            _coreUserSettings.MaximumNumberOfCoresToUse = 1;
            sut = new CategorialParameterIdentificationRunInitializer(_cloneManager, _parameterIdentificationRun, _container, _descriptionCreator, _coreUserSettings);

            _parameterIdentification = new ParameterIdentification();
            _parameterIdentification.Configuration.RunMode = new CategorialParameterIdentificationRunMode();

            _simulation       = A.Fake <ISimulation>();
            _clonedSimulation = A.Fake <ISimulation>();

            A.CallTo(() => _simulationFactory.CreateWithCalculationMethodsFrom(_simulation, A <IEnumerable <CalculationMethodWithCompoundName> > ._)).Returns(_clonedSimulation);
            A.CallTo(() => _cloneManager.Clone(_parameterIdentification)).ReturnsLazily(() =>
            {
                var pi = new ParameterIdentification();
                pi.AddSimulation(_simulation);
                var identificationParameter = new IdentificationParameter();
                identificationParameter.AddLinkedParameter(new ParameterSelection(_simulation, A.Fake <QuantitySelection>()));
                pi.AddIdentificationParameter(identificationParameter);
                pi.AddOutputMapping(new OutputMapping
                {
                    OutputSelection = new SimulationQuantitySelection(_simulation, A.Fake <QuantitySelection>())
                });
                pi.Configuration.RunMode = new CategorialParameterIdentificationRunMode();
                return(pi);
            });
        }
Ejemplo n.º 14
0
        protected override void Context()
        {
            base.Context();
            _simulation = A.Fake <ISimulation>();
            _runResults = A.Fake <SimulationResults>();
            var outputSelections = new OutputSelections();

            outputSelections.AddOutput(new QuantitySelection("Liver|Cell|Drug|Concentration", QuantityType.Drug));

            A.CallTo(() => _simulation.OutputSelections).Returns(outputSelections);
            var pKCalculationOptions = new PKCalculationOptions();

            A.CallTo(_pkCalculationOptionsFactory).WithReturnType <PKCalculationOptions>().Returns(pKCalculationOptions);

            _p1 = new PKParameter {
                Name = "AUC", Mode = PKParameterMode.Single
            };
            _userDefinedParameter1 = new UserDefinedPKParameter {
                Name = "Dynamic1", Mode = PKParameterMode.Single
            };

            A.CallTo(() => _pkParameterRepository.All()).Returns(new[] { _p1, _userDefinedParameter1 });
            var individualResults = A.Fake <IndividualResults>();

            A.CallTo(() => _runResults.AllIndividualResults).Returns(new HashSet <IndividualResults>(new[] { individualResults }));

            var pKValues = new PKValues();

            pKValues.AddValue(_p1.Name, 10f);
            pKValues.AddValue(_userDefinedParameter1.Name, 30f);
            A.CallTo(_pkValuesCalculator).WithReturnType <PKValues>().Returns(pKValues);
        }
 protected override void Context()
 {
     sut               = new OutputMappingToOutputMappingDTOMapper();
     _simulation       = A.Fake <ISimulation>();
     _availableOutputs = new List <SimulationQuantitySelectionDTO>();
     _outputMapping    = new OutputMapping();
 }
Ejemplo n.º 16
0
        /// <inheritdoc/>
        public override void CreateBehaviors(ISimulation simulation)
        {
            var behaviors = new BehaviorContainer(Name);

            if (Parameters.Entities != null || Parameters.Entities.Count > 0)
            {
                // Create our local simulation and binding context to allow behaviors to do stuff
                var localSim = new ParallelSimulation(simulation, this);
                var context  = new ParallelBindingContext(this, localSim, behaviors);
                Entities.DependencyInjection.DI.Resolve(simulation, this, behaviors, context);

                // Run the simulation
                localSim.Run(Parameters.Entities);

                // Allow the behaviors to fetch the behaviors if they want
                foreach (var behavior in behaviors)
                {
                    if (behavior is IParallelBehavior parallelBehavior)
                    {
                        parallelBehavior.FetchBehaviors(context);
                    }
                }
            }
            simulation.EntityBehaviors.Add(behaviors);
        }
Ejemplo n.º 17
0
 /// <summary>Initialize session and base classes.</summary>
 /// <param name="session">The session.</param>
 /// <param name="delays">The delays.</param>
 protected AbstractTssController(TSession session, uint[] delays)
     : base(session)
 {
     Tss         = new TSS(delays);
     _simulation = new TssSimulationWrapper(this);
     TargetSpeed = AdjustedSpeed = 1.0f;
 }
Ejemplo n.º 18
0
        public string[] PotentialVariableParameterPathsFor(ISimulation simulation)
        {
            var sensitivityAnalysis     = new SensitivityAnalysis(simulation);
            var coreSensitivityAnalysis = _sensitivityAnalysisMapper.MapFrom(sensitivityAnalysis);

            return(coreSensitivityAnalysis.AllSensitivityParameterPaths);
        }
Ejemplo n.º 19
0
        private void exportToDirectory(ISimulation simulation, string exportDirectory)
        {
            var fileName            = createFilePathFor(simulation, exportDirectory, Constants.Filter.XML_EXTENSION);
            var modelCoreSimulation = _simulationToModelCoreSimulationMapper.MapFrom(simulation, shouldCloneModel: false);

            _simModelExporter.ExportSimModelXml(modelCoreSimulation, fileName);
        }
Ejemplo n.º 20
0
        private void UpdateSector(ISimulation sim, SessionResult session, EntitySessionResult result, double curPos, double prevPos)
        {
            if (session.State != SessionState.Racing)
            {
                return;
            }

            var track = sim.Session.Track;

            if (track.SelectedSectors.Count <= 0)
            {
                return;
            }

            var i = 0;

            foreach (var location in track.SelectedSectors.OrderBy(s => s.Index).Select(s => s.Location))
            {
                if (curPos <= location || i <= result.CurrentLap.CurrentSector.Index)
                {
                    i++;
                    continue;
                }

                var now    = Updater.CurrentTime - (curPos - location) * (curPos - prevPos);
                var sector = new CompletedSector(result.CurrentLap.CurrentSector, now);
                result.CurrentLap.SectorsInt.Add(sector);

                result.CurrentLap.CurrentSector.BeginTime      = now;
                result.CurrentLap.CurrentSector.Index          = i;
                result.CurrentLap.CurrentSector.ReplayPosition = (int)(sim.Telemetry.SessionTime * 60 + Updater.TimeOffset);

                break;
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CurrentSwitchBindingContext"/> class.
        /// </summary>
        /// <param name="component">The component that creates the behavior.</param>
        /// <param name="simulation">The simulation for which the behavior is created.</param>
        /// <param name="behaviors">The created behaviors.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="component"/>, <paramref name="simulation"/> or <paramref name="behaviors"/> is <c>null</c>.</exception>
        public CurrentSwitchBindingContext(ICurrentControllingComponent component, ISimulation simulation, IBehaviorContainer behaviors)
            : base(component, simulation, behaviors)
        {
            var branch = ControlBehaviors.GetValue <IBranchedBehavior <double> >().Branch;

            ControlValue = () => branch.Value;
        }
Ejemplo n.º 22
0
        /// <inheritdoc/>
        public override void CreateBehaviors(ISimulation simulation)
        {
            var behaviors = new BehaviorContainer(Name);

            if (Parameters.Definition != null && Parameters.Definition.Entities.Count > 0)
            {
                // Create our local simulation and binding context to allow our behaviors to do stuff
                var localSim = new SubcircuitSimulation(Name, simulation, Parameters.Definition, NodeMap);
                var context  = new SubcircuitBindingContext(this, localSim, behaviors);
                Entities.DependencyInjection.DI.Resolve(simulation, this, behaviors, context);

                // Run the simulation
                localSim.Run(Parameters.Definition.Entities);

                // Allow the behaviors to fetch the behaviors if they want
                foreach (var behavior in behaviors)
                {
                    if (behavior is ISubcircuitBehavior subcktBehavior)
                    {
                        subcktBehavior.FetchBehaviors(context);
                    }
                }
            }
            simulation.EntityBehaviors.Add(behaviors);
        }
Ejemplo n.º 23
0
        private string displayPathAsStringFor(ISimulation simulation, DataColumn column, bool addSimulationName, Action <PathElements> pathElementAdjustments = null)
        {
            var pathElements = DisplayPathFor(simulation, column);

            pathElementAdjustments?.Invoke(pathElements);
            return(DisplayPathAsStringFrom(pathElements, DefaultPathElementsToUse(addSimulationName, pathElements)));
        }
Ejemplo n.º 24
0
 protected override void Context()
 {
     base.Context();
     _sensitivityAnalysis = new SensitivityAnalysis();
     _oldSimulation       = A.Fake <ISimulation>();
     _newSimulation       = A.Fake <ISimulation>();
 }
Ejemplo n.º 25
0
        protected override void Context()
        {
            base.Context();
            _simulation = A.Fake <ISimulation>();
            var rootContainer = new Container();

            _simulation.Model.Root = rootContainer;

            _constantParameter           = DomainHelperForSpecs.ConstantParameterWithValue(10).WithName("ConstantParameter");
            _formulaParameter            = new Parameter().WithFormula(new ExplicitFormula("1+2")).WithName("FormulaParameter");
            _formulaFixedParameter       = new Parameter().WithFormula(new ExplicitFormula("1+2")).WithName("FormulaFixedParameter");
            _formulaFixedParameter.Value = 10;

            rootContainer.Add(_constantParameter);
            rootContainer.Add(_formulaParameter);
            rootContainer.Add(_formulaFixedParameter);

            _constantParameterSelection     = new ParameterSelection(_simulation, _constantParameter.Name);
            _formulaParameterSelection      = new ParameterSelection(_simulation, _formulaParameter.Name);
            _formulaFixedParameterSelection = new ParameterSelection(_simulation, _formulaFixedParameter.Name);


            A.CallTo(() => _simulationParametersPresenter.AllParameters).Returns(new [] { _constantParameterSelection, _formulaParameterSelection, _formulaFixedParameterSelection });

            A.CallTo(() => _sensitivityAnalysisParametersPresenter.AddParameters(A <IReadOnlyList <ParameterSelection> > ._))
            .Invokes(x => _addedParameters = x.GetArgument <IReadOnlyList <ParameterSelection> >(0));
        }
Ejemplo n.º 26
0
        private void InitializeSimulation(SimulationStartParameters simulationStartParameters)
        {
            List <IActor> actors;

            _simulationFileName = string.Empty;

            // destroy the old simulation or it will keep running with unintended consque
            this.ClearSimulation();

            _simulation       = new LangtonsAntSimulation(this);
            _simulation.Speed = simulationStartParameters.Delay;

            actors = new List <IActor>();
            for (int i = 0; i < simulationStartParameters.InitialActors; i++)
            {
                actors.Add(new Ant());
            }
            _simulation.Actors = actors.ToArray();

            this.InitializeSimulation(_simulation);

            _simulation.Start();
            if (simulationStartParameters.StartPaused)
            {
                _simulation.Pause();
            }
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ParallelSimulation"/> class.
 /// </summary>
 /// <param name="parent">The parent simulation.</param>
 /// <param name="parameters">The parallel component parameters.</param>
 public ParallelSimulation(ISimulation parent, IParameterSetCollection parameters)
     : base(parent,
            new BehaviorContainerCollection(parent?.EntityBehaviors.Comparer),
            new InheritedTypeSet <ISimulationState>())
 {
     LocalParameters = parameters.ThrowIfNull(nameof(parameters));
 }
Ejemplo n.º 28
0
        protected override void Context()
        {
            base.Context();
            _cache1 = _runMode.CalculationMethodCacheFor("compound1");
            _cache2 = _runMode.CalculationMethodCacheFor("compound2");
            _cache1.AddCalculationMethod(new CalculationMethod {
                Category = "Category1", Name = "method1"
            });
            _cache1.AddCalculationMethod(new CalculationMethod {
                Category = "Category1", Name = "method2"
            });

            _cache2.AddCalculationMethod(new CalculationMethod {
                Category = "Category1", Name = "method1"
            });
            _cache2.AddCalculationMethod(new CalculationMethod {
                Category = "Category1", Name = "method2"
            });

            _cache2.AddCalculationMethod(new CalculationMethod {
                Category = "Category2", Name = "method3"
            });
            _cache2.AddCalculationMethod(new CalculationMethod {
                Category = "Category2", Name = "method4"
            });
            _cache2.AddCalculationMethod(new CalculationMethod {
                Category = "Category2", Name = "method5"
            });
            _simulation = A.Fake <ISimulation>();
            _simulation = A.Fake <ISimulation>();
            A.CallTo(() => _simulation.CompoundNames).Returns(new[] { "compound2" });

            _parameterIdentification.AddSimulation(_simulation);
        }
Ejemplo n.º 29
0
        protected override void Context()
        {
            sut          = new CategorialRunModeToCategorialRunModeDTOMapper();
            _simulation1 = A.Fake <ISimulation>();
            A.CallTo(() => _simulation1.CompoundNames).Returns(new[] { "Drug1", "Drug2" });

            _simulation2 = A.Fake <ISimulation>();
            A.CallTo(() => _simulation2.CompoundNames).Returns(new[] { "Drug2", "Drug3" });

            _allSimulations = new List <ISimulation> {
                _simulation1, _simulation2
            };
            _category1 = new CategoryDTO().WithName("Category1");
            _category2 = new CategoryDTO().WithName("Category2");

            _cm1 = new CalculationMethod {
                Category = _category1.Name
            }.WithName("CM1");
            _cm2 = new CalculationMethod {
                Category = _category1.Name
            }.WithName("CM2");
            _cm3 = new CalculationMethod {
                Category = _category2.Name
            }.WithName("CM3");

            _category1.Methods = new[] { _cm1, _cm2 };
            _category2.Methods = new[] { _cm3 };

            _allCategories = new[] { _category1, _category2 };

            _runMode = new CategorialParameterIdentificationRunMode();
        }
Ejemplo n.º 30
0
        public PKCalculationOptions CreateFor(ISimulation simulation, string moleculeName)
        {
            var options = new PKCalculationOptions();
            var endTime = simulation.EndTime ?? 0;

            var allApplicationParameters = AllApplicationParametersOrderedByStartTimeFor(simulation, moleculeName);

            // all application start times starting before the end of the simulation
            var applicationStartTimes = allApplicationParameters.Select(x => x.StartTime.Value).ToFloatArray();

            options.FirstDosingStartValue = applicationStartTimes.FirstOrDefault();

            // single dosing
            if (applicationStartTimes.Length <= 1)
            {
                options.FirstDosingEndValue = endTime.ToFloat();
                options.InfusionTime        = allApplicationParameters.FirstOrDefault()?.InfusionTime?.Value;
            }
            else
            {
                // 1 because we want the start time of the second application
                options.FirstDosingEndValue          = applicationStartTimes[1];
                options.LastMinusOneDosingStartValue = applicationStartTimes[applicationStartTimes.Length - 2];
                options.LastDosingStartValue         = applicationStartTimes[applicationStartTimes.Length - 1];
                options.LastDosingEndValue           = endTime.ToFloat();
            }

            // Once all dosing are defined, update applied dose
            UpdateAppliedDose(simulation, moleculeName, options, allApplicationParameters);

            return(options);
        }
Ejemplo n.º 31
0
 public Recorder(ISimulation hostsimulator, RecordType recordtype, string recordfile)
 {
     this.hostsimulator = hostsimulator;
     this.recordtype = recordtype;
     this.recordfile = recordfile;
     potentialfile = spikefile = null;
     potentialwriter = spikewriter = null;
 }
        /// <summary>
        ///     Draws the simualation with the specified colors.
        /// </summary>
        /// <param name="g">The graphics context.</param>
        /// <param name="s">The simulation to draw.</param>
        public void Draw(Graphics g, ISimulation s)
        {
            g.SmoothingMode = SmoothingMode.AntiAlias;

            DrawPitch(g, s);
            DrawTeams(g, s);
            DrawBall(g, s);
        }
 private void DrawPitch(Graphics g, ISimulation s)
 {
     var w = s.PitchBounds.Width;
     g.DrawEllipse(_linePen, -w / 10, -w / 10, w / 5, w / 5);
     g.DrawRectangle(_linePen, s.PitchBounds);
     g.DrawRectangle(_linePen, s.Teams[0].GoalBounds);
     g.DrawRectangle(_linePen, s.Teams[1].GoalBounds);
 }
Ejemplo n.º 34
0
 /// <summary>
 /// </summary>
 /// <param name="player"></param>
 /// <param name="team"></param>
 /// <param name="otherTeam"></param>
 /// <param name="simulation"></param>
 /// <param name="passingLaneWidth"></param>
 /// <returns></returns>
 public static IEnumerable<IPointMass> GetOpenPlayers(
     PointMass player,
     ITeam team,
     ITeam otherTeam,
     ISimulation simulation,
     float passingLaneWidth)
     => from p in team.Players
         where p != player && IsPlayerOpenForPass(player, p, otherTeam.Players, passingLaneWidth)
         select p;
Ejemplo n.º 35
0
        /// <summary>
        ///     Executes the team strategy.
        /// </summary>
        /// <param name="simulation">The simulation in which the is taking part.</param>
        /// <returns>The kick.</returns>
        public Kick ExecuteStrategy(ISimulation simulation)
        {
            Contract.Requires<ArgumentNullException>(simulation != null);
            Contract.Requires<ArgumentException>(Contract.Exists(simulation.Teams, t => t == this));

            var kick = _strategy.Execute(simulation, this);
            if (kick.Player == null || IsKickValid(kick.Player, simulation))
                return kick;

            throw new InvalidOperationException("Invalid kick.");
        }
        public ThreadSimulationProxy(ISimulation simulation)
        {
            this.simulation = simulation;

            //currentSimulationStep = new SimulationStep();

            physicsWorker = new PhysicsWorker { Simulation = this, /*SimulationStepQueue = simulationStepQueue, SimulationQueueNotEmpty = simulationQueueNotEmpty */ };
            physicsThread = new Thread(physicsWorker.Run) { IsBackground = true };

            physicsThread.Start();
        }
Ejemplo n.º 37
0
        public SpeciesDetails(WebCrittersForm parent, ISimulation simulation, ISpecies species)
        {
            if (parent == null) throw new ArgumentNullException("parent");
            if (simulation == null) throw new ArgumentNullException("simulation");
            if (species == null) throw new ArgumentNullException("species");

            ParentForm = parent;
            CurrentSpecies = species;
            Simulation = simulation;

            InitializeComponent();
            UpdateSpeciesDetails();
        }
Ejemplo n.º 38
0
        public override Kick Execute(ISimulation simulation)
        {
            var ballChaser = FootballStrategies.ClosestPlayerToPoint(this.Players, simulation.Ball, 0);
            var kick = Kick.None;

            foreach (var player in Players)
            {
                if (player == ballChaser)
                {
                    //messages[player] = "Chaser";

                    var playersExceptSelf = Players.ToList();
                    playersExceptSelf.Remove(player);

                    player.Force = SteeringStrategies.Pursue(player, simulation.Ball, 1);

                    if ((player.Position - simulation.Ball.Position).Length() < player.Radius + simulation.Ball.Radius) {
                        var isLeftTeam = this.GoalBounds.Left > 0 ? true : false;
                        PointMass[] arr = new PointMass[7];
                        playersExceptSelf.CopyTo(arr, 0);
                        arr[4] = new PointMass(1, 1, 1, 1, new Vector2(isLeftTeam ? this.GoalBounds.Left : this.GoalBounds.Right, this.GoalBounds.Top + (0.2f) * this.GoalBounds.Height), Vector2.Zero);
                        arr[5] = new PointMass(1, 1, 1, 1, new Vector2(isLeftTeam ? this.GoalBounds.Left : this.GoalBounds.Right, this.GoalBounds.Top + (0.5f) * this.GoalBounds.Height), Vector2.Zero);
                        arr[6] = new PointMass(1, 1, 1, 1, new Vector2(isLeftTeam ? this.GoalBounds.Left : this.GoalBounds.Right, this.GoalBounds.Top + (0.8f) * this.GoalBounds.Height), Vector2.Zero);
                        arr[4].id = "GT";
                        arr[5].id = "GM";
                        arr[6].id = "GB";
                        ReadOnlyCollection<PointMass> roc = new ReadOnlyCollection<PointMass>(arr);
                        Vector2 middleOfGoal = new Vector2(isLeftTeam ? this.GoalBounds.Left : this.GoalBounds.Right, this.GoalBounds.Top - (0.5f) * this.GoalBounds.Height);
                        IPointMass kickTarget = ClosestPlayerToPoint(roc, player, 1, middleOfGoal);
                        messages[player] = "Chaser T: " + kickTarget.id;
                        k = kick = FootballStrategies.PassToPlayer(player, kickTarget, simulation.Ball);
                    }  else
                        k = kick = Kick.None;
                }
                else
                {
                    messages[player] = isOutsideOfField(player, simulation.PitchBounds) ? "Outside" : "inside";

                    var allPlayers = simulation.Teams[0].Players.Concat(simulation.Teams[1].Players);
                    if (isOutsideOfField(player, simulation.PitchBounds))
                        player.Force = SteeringStrategies.Seek(player, Vector2.Zero, player.MaxSpeed);
                    else
                        FootballStrategies.SpreadOut(player, allPlayers, simulation.PitchBounds, 150, 100);
                }
            }

            return kick;
        }
Ejemplo n.º 39
0
        public Species(ISimulation simulation, IAgent exemplar, params UniqueIdentifier[] derivedFromSpeciesIds)
        {
            if (simulation == null) throw new ArgumentNullException("simulation");
            if (exemplar == null) throw new ArgumentNullException("exemplar");

            this.Simulation = simulation;
            this.firstSeen = simulation.CurrentGeneration;
            this.ResourcesFromResourceNodes = 0;
            this.ResourcesFromAgents = 0;
            this.Population = 0;

            this.id = CreateUniqueIdentifier(exemplar);

            this.derivedFromSpeciesIds.AddRange(derivedFromSpeciesIds);
            this.exemplar = exemplar.DeepCopy();
        }
Ejemplo n.º 40
0
        public GridLocation(int x, int y, ISimulation simulation, List<IResourceNode> resourceAllocation, int upkeep, int capacity)
            : base(simulation)
        {
            if (resourceAllocation == null) throw new ArgumentNullException("resourceAllocation");
            if (x < 0) throw new ArgumentOutOfRangeException("x", x, "x must be zero or greater");
            if (y < 0) throw new ArgumentOutOfRangeException("y", y, "y must be zero or greater");
            if (upkeep < 0) throw new ArgumentOutOfRangeException("upkeep", upkeep, "upkeep must be zero or greater");
            if (capacity < 0) throw new ArgumentOutOfRangeException("capacity", upkeep, "capacity must be zero or greater");

            Connections = new List<ILocation>();
            Agents = new List<IAgent>();
            CurrentResources = new List<IResourceNode>();

            X = x;
            Y = y;
            UpkeepCost = upkeep;
            ResourceCapacity = capacity;

            ResourceAllocation = resourceAllocation;
        }
Ejemplo n.º 41
0
        protected LocationBase(ISimulation simulation)
        {
            if (simulation == null) throw new ArgumentNullException("simulation");

            this.Simulation = simulation;
        }
Ejemplo n.º 42
0
 public void AddSimulation(ISimulation simulation)
 {
     model.AddSimulation(simulation);
 }
Ejemplo n.º 43
0
 /// <summary>
 ///     Draws debugging information.
 /// </summary>
 /// <param name="simulation">The simulation in which the team is taking part.</param>
 /// <param name="g">The drawing surface.</param>
 public virtual void DrawDebugInfo(ISimulation simulation, Graphics g)
 {
 }
Ejemplo n.º 44
0
 public Personnage(ISimulation simulation, string nom)
 {
     Nom = nom;
     simulation.Attach<TickEvent>(Tick);
     this.simulation = simulation;
 }
Ejemplo n.º 45
0
 protected Program(IContainer container, ISimulation simulation)
 {
     _container = container;
     _simulation = simulation;
     _application = new Application();
 }
        private void DrawTeams(Graphics g, ISimulation s)
        {
            var pe = _teamPens.GetEnumerator();
            var be = _teamBrushes.GetEnumerator();

            foreach (var t in s.Teams)
            {
                pe.MoveNext();
                be.MoveNext();
                t.Players.ForEach(p => {
                    DrawPointMass(p, pe.Current, be.Current, g);
                    DrawDebugInfo(p, be.Current, _font, g);
                });

                ((Team)t).DrawDebugInfo(s, g);
            }
        }
Ejemplo n.º 47
0
 public static void EndRunningComposition()
 {
     _runningComposition = null;
 }
Ejemplo n.º 48
0
 public ViewEventArgs(ISimulation simulation)
 {
     this.Simulation = simulation;
 }
Ejemplo n.º 49
0
 /// <summary>
 ///     Executes the team strategy.
 /// </summary>
 /// <param name="simulation">The simulation in which the team is taking part.</param>
 /// <returns>The kick.</returns>
 public abstract Kick Execute(ISimulation simulation);
 private void DrawBall(Graphics g, ISimulation s)
 {
     g.FillCircle(_ballBrush, s.Ball.Position, s.Ball.Radius);
     DrawDebugInfo(s.Ball, _ballBrush, _font, g);
 }
Ejemplo n.º 51
0
        public override void DrawDebugInfo(ISimulation simulation, Graphics g)
        {
            //g.DrawLine(Pens.GhostWhite, simulation.Ball.Position, simulation.Ball.Position + simulation.Ball.Velocity);
            foreach (var p in Players)
            {
                //g.DrawLine(Pens.Orange, p.Position, p.Position + 3*p.Velocity);
                //g.DrawLine(Pens.Purple, p.Position, p.Position + 3*p.Acceleration);
                if (k.Force != Vector2.Zero && messages[p] == "Chaser")
                {
                    //g.DrawLine(Pens.Pink, p.Position, p.Position + 3 * k.Force);
                    var playersExceptSelf = Players.ToList();
                    playersExceptSelf.Remove(p);

                    var target = FootballStrategies.ClosestPlayerToPoint(playersExceptSelf, p, 100);
                    var desired = target.Position - p.Position;
                    //g.DrawLine(Pens.Gold, p.Position, p.Position + 10 * desired);
                    //g.DrawLine(Pens.Fuchsia, simulation.Ball.Position, simulation.Ball.Position + simulation.Ball.Velocity.Projection(desired));
                    //g.DrawLine(Pens.Brown, simulation.Ball.Position, simulation.Ball.Position + 10 * simulation.Ball.Velocity.Rejection(desired));

                }

                string message;
                if (messages.TryGetValue(p, out message))
                    g.DrawString(p.id + ": " + message, SystemFonts.DefaultFont, Brushes.Black, p.Position.X + 10, p.Position.Y + 10);
            }
        }
Ejemplo n.º 52
0
 public override Kick Execute(ISimulation simulation)
 {
     return Kick.None;
 }
Ejemplo n.º 53
0
 private bool IsKickValid(IPointMass player, ISimulation simulation) =>
     Players.Any(p => p == player) &&
     (player.Position - simulation.Ball.Position).Length() < player.Radius + simulation.Ball.Radius;
Ejemplo n.º 54
0
 public void AddSimulation(ISimulation simulation)
 {
     this.simulations.Add(simulation);
     this.Changed.Invoke(this, new ModelEventArgs(simulations));
 }
 public override IFabriquePersonnage CreerFabriquePersonnage(ISimulation simulation)
     => new FabriquePersonnageNatation(simulation);
 public FabriquePersonnageNatation(ISimulation simulation) : base(simulation)
 {
 }
 public virtual IFabriqueAcces CreerFabriqueAcces(ISimulation simulation)
     => new FabriqueConcreteAcces();
 public FabriquePersonnage(ISimulation simulation)
 {
     Simulation = simulation;
 }
 public override IFabriqueZone CreerFabriqueZone(ISimulation simulation)
     => new FabriqueZoneNatation();
 public virtual IFabriquePersonnage CreerFabriquePersonnage(ISimulation simulation)
     => new FabriquePersonnage(simulation);