//добавляем одного агента в общий каталог
 public static void AddOneAgent(IAgent agent)
 {
     lock (agentDictionary)
     {
         agentDictionary.Add(agent.GetId(), agent);
     }
 }
示例#2
0
        static void PerformGameBenchmarking()
        {
            Dictionary<int, int> wins = new Dictionary<int, int>(4);

            for (int i = 0; i < 1000; i++)
            {
                var controller = new GameController();
                var agents = new IAgent[] { new StarterAgent(), new StarterAgent(), new StarterAgent() }; // new HumanAgent()
                int intWinner = controller.StartGame(agents, i, i, false, false);
                //var winner = agents[intWinner];

                if (wins.ContainsKey(intWinner))
                {
                    wins[intWinner] = wins[intWinner] + 1;
                }
                else
                {
                    wins.Add(intWinner, 1);
                }
                Console.WriteLine(i + ": P " + intWinner + " wins.");
            }

            Console.WriteLine();
            wins.OrderBy(w => w.Key).ForEach(kv => Console.WriteLine("Player " + kv.Key + ": " + kv.Value + " wins."));
        }
示例#3
0
        public User(IAgent agent)
        {
            this._Agent = agent;

            this._Updater = new Updater();
            this._User = new Remoting.User(this._Agent);
        }
示例#4
0
 public RunParameters(XmlElement e, Provider<IAgent, string> agentProvider)
 {
     exePath = e.SelectSingleNode("./cmd").InnerText;
     workingDirectory = e.SelectSingleNode("./dir").InnerText;
     parameters = e.SelectSingleNode("./args").InnerText;
     agent = agentProvider(e.SelectSingleNode("./agent").InnerText);
 }
示例#5
0
 static double Evaluate(IAgent model, IAgent benchmark, GridGameParameters _params)
 {
     double score = 0;
     Console.WriteLine("Starting games as player 1..");
     for (int i = 0; i < _params.MatchesPerOpponent; i++)
     {
         var game = _params.GameFunction(model, benchmark);
         game.PlayToEnd();
         if (game.Winner == 1)
             score += _params.WinReward;
         else if (game.Winner == 0)
             score += _params.TieReward;
         else
             score += _params.LossReward;
     }
     Console.WriteLine("Starting games as player 2..");
     for (int i = 0; i < _params.MatchesPerOpponent; i++)
     {
         var game = _params.GameFunction(benchmark, model);
         game.PlayToEnd();
         if (game.Winner == -1)
             score += _params.WinReward;
         else if (game.Winner == 0)
             score += _params.TieReward;
         else
             score += _params.LossReward;
     }
     Console.WriteLine("Done!");
     return score;
 }
示例#6
0
 public RunParameters(string exePath, string workingDirectory, string parameters, IAgent agent)
 {
     this.exePath = exePath;
     this.workingDirectory = workingDirectory;
     this.parameters = parameters;
     this.agent = agent;
 }
示例#7
0
        public override IEnumerable<Term> FindTargetTerms(IAgent agent, Func<Term, bool> predicate)
        {
            Func<Term, bool> whereClause = t => t.Level > 0 && t.Level < 3 && predicate(t);
            var results = agent.SelectTargetTerms(whereClause);

            return results;
        }
示例#8
0
        public void SetAgent(IAgent aAgent)
        {
            // detach existing agent
              if (mAgent != null) {
            if (mAgent is Agent) {
              var agent = mAgent as Agent;
              agent.KeyListChanged -= AgentKeyListChangeHandler;
              agent.Locked -= AgentLockHandler;
            }
              }

              mAgent = aAgent;

              if (mAgent is Agent) {
            var agent = mAgent as Agent;
            mKeyNodeView.Columns[0].Visible = true;
            mKeyNodeView.Columns[1].Visible = true;
            agent.KeyListChanged += AgentKeyListChangeHandler;
            agent.Locked += AgentLockHandler;
            //buttonTableLayoutPanel.Controls.Remove(refreshButton);
            //buttonTableLayoutPanel.ColumnCount = 5;
              } else {
            mKeyNodeView.Columns[0].Visible = false;
            mKeyNodeView.Columns[1].Visible = false;
            //buttonTableLayoutPanel.ColumnCount = 6;
            //buttonTableLayoutPanel.Controls.Add(refreshButton, 5, 0);
              }
              ReloadKeyListView();
        }
        public override IEnumerable<Term> FindTargetTerms(IAgent agent, Func<Term, bool> predicate)
        {
            var results = agent.SelectTargetTerms(
                t => (t is Assignment || t is OvertimeAssignment) && predicate(t));

            return results;
        }
        /// <summary>
        /// Combines wandering and separation
        /// </summary>
        public static void Wander(IAgent agent, IAgent[] otherAgents, ref Steering.SteerParameters steerParams)
        {
            // add up the steering forces
            Vector3 wander = Steering.WanderForce(agent, ref steerParams);
            Vector3 separation = Vector3.Zero;
            Vector3 bounds = Steering.WorldBoundsForce(agent, steerParams);

            int avoiding = 0;
            for (int i = 0; i < otherAgents.Length; i++)
            {
                IAgent otherAgent = otherAgents[i];

                if (agent != otherAgent)
                {
                    float separationDistance = Vector3.Distance(agent.Position, otherAgent.Position);
                    if (separationDistance < steerParams.SeparationRange)
                    {
                        separation += Steering.SeparationForce(agent, otherAgent, steerParams, separationDistance);
                        avoiding++;
                    }
                }
            }

            agent.Direction = Vector3.Normalize(agent.Direction + wander + separation + bounds);
        }
示例#11
0
 private void _ToGaming(IAgent agent)
 {
     var stage = new LocalGamingStage(agent, WorldPrefab, ControllerPrefab);
     stage.DoneEvent += _ToSetting;
     _DrawWindow = stage.DrawWindow;
     _Machine.Push(stage);
 }
示例#12
0
文件: User.cs 项目: jiowchern/Regulus
 public User(IAgent agent)
 {
     _Agent = agent;
     _ConnectProvider = new TProvider<IConnect>();
     _OnlineProvider = new TProvider<IOnline>();
     _Machine = new StageMachine();
     _Updater = new Updater();
 }
示例#13
0
        public DeaWinService(ILog log, IAgent agent)
        {
            this.log = log;
            this.agent = agent;

            agentTask = new Task(() => agent.Start());
            agentMonitorTimer = new Timer(agentMonitor);
        }
示例#14
0
    public void addAgent(IAgent a, System.String startLocation)
    {
		// Ensure the agent state information is tracked before
		// adding to super, as super will notify the registered
		// EnvironmentViews that is was added.
		state.setAgentLocationAndTravelDistance(a, startLocation, 0.0);
		base.addAgent(a);
	}
        //---------------------------------------------------------------------
        ///<summary>
        ///Calculate the Site Resource Dominance (SRD) for all active sites.
        ///The SRD averages the resources for each species as defined in the
        ///BDA species table.
        ///SRD ranges from 0 - 1.
        ///</summary>
        //---------------------------------------------------------------------
        public static void SiteResourceDominance(IAgent agent, int ROS)
        {
            PlugIn.ModelCore.Log.WriteLine("   Calculating BDA Site Resource Dominance.");

            foreach (ActiveSite site in PlugIn.ModelCore.Landscape) {

                double sumValue = 0.0;
                double maxValue = 0.0;
                int    ageOldestCohort= 0;
                int    numValidSpp = 0;
                double speciesHostValue = 0;

                foreach (ISpecies species in PlugIn.ModelCore.Species)
                {
                    ageOldestCohort = Util.GetMaxAge(SiteVars.Cohorts[site][species]);
                    ISppParameters sppParms = agent.SppParameters[species.Index];
                    if (sppParms == null)
                        continue;

                    bool negList = false;
                    foreach (ISpecies negSpp in agent.NegSppList)
                    {
                        if (species == negSpp)
                            negList = true;
                    }

                    if ((ageOldestCohort > 0) && (! negList))
                    {
                        numValidSpp++;
                        speciesHostValue = 0.0;

                        if (ageOldestCohort >= sppParms.MinorHostAge)
                            //speciesHostValue = 0.33;
                            speciesHostValue = sppParms.MinorHostSRD;

                        if (ageOldestCohort >= sppParms.SecondaryHostAge)
                            //speciesHostValue = 0.66;
                            speciesHostValue = sppParms.SecondaryHostSRD;

                        if (ageOldestCohort >= sppParms.PrimaryHostAge)
                            //speciesHostValue = 1.0;
                            speciesHostValue = sppParms.PrimaryHostSRD;


                        sumValue += speciesHostValue;
                        maxValue = System.Math.Max(maxValue, speciesHostValue);
                    }
                }

                if (agent.SRDmode == SRDmode.mean)
                    SiteVars.SiteResourceDom[site] = sumValue / (double) numValidSpp;

                if (agent.SRDmode == SRDmode.max)
                    SiteVars.SiteResourceDom[site] = maxValue;

            }

        }  //end siteResourceDom
示例#16
0
 static void Main(string[] aArgs)
 {
     //Debugger.Launch();
       CommandLineArgs.Parse(aArgs);
       if (CommandLineArgs.Mode == AgentMode.Server &&
     PageantAgent.CheckPageantRunning()) {
       MessageBox.Show(Strings.errPageantRunning, Util.AssemblyTitle,
     MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
     Environment.Exit(1);
     return;
       }
       if (CommandLineArgs.Mode == AgentMode.Auto) {
     if (PageantAgent.CheckPageantRunning()) {
       CommandLineArgs.Mode = AgentMode.Client;
     } else {
       CommandLineArgs.Mode = AgentMode.Server;
     }
       }
       Application.EnableVisualStyles();
       Application.SetCompatibleTextRenderingDefault(false);
       switch (CommandLineArgs.Mode) {
     case AgentMode.Server:
       try {
     Agent = new PageantAgent();
       } catch (PageantRunningException) {
     Debug.Fail("should not get here unless Pageant started in last few msec.");
     Environment.Exit(1);
     return;
       }
       break;
     case AgentMode.Client:
       Agent = new PageantClient();
       break;
     default:
       Debug.Fail("unknown mode");
       Environment.Exit(1);
       return;
       }
       Agent.AddKeysFromFiles(CommandLineArgs.Files);
       Application.ApplicationExit +=
     delegate(object aSender, EventArgs aEventArgs)
     {
       if (Agent is Agent) {
     ((Agent)Agent).Dispose();
       }
     };
       var keyManagerForm = new KeyManagerForm(Agent);
       if (!(Agent is Agent)) {
     keyManagerForm.Text += " - client mode";
       }
       keyManagerForm.FormClosed +=
     delegate(object aSender, FormClosedEventArgs aEventArgs)
     {
       Environment.Exit(0);
     };
       keyManagerForm.Show();
       Application.Run();
 }
示例#17
0
 public Game(IMapGenerator generator, IEnumerable<IAction> coreActions, IAgent agent)
 {
     _initialiseHooks = new List<IInitialiseHook>();
     _addedActions = new List<IAction>();
     _actionHooks = new Dictionary<string, List<IActionHook>>();
     _coreActions = coreActions;
     _generator = generator;
     Reset(agent);
 }
示例#18
0
 public XenGuestServices(IAgent agent)
 {
     xgsc = agent;
     uuid = xgsc.GetUuid();
     domid = xgsc.GetDomId();
     showSwitcher = xgsc.GetShowSwitcher();
     vmsEventName = xgsc.RegisterVmsEvent();
     alertsEventName = xgsc.RegisterAlertsEvent();
 }
示例#19
0
文件: user.cs 项目: jiowchern/Regulus
        public User(IAgent agent)
        {
            _Agent = agent;
            _Updater = new Updater();
            _User = new Regulus.Remoting.User(_Agent);

            _Version = typeof(IVerify).Assembly.GetName()
                                    .Version.ToString();
        }
示例#20
0
        public void TryDispatch(IAgent agent, Func<Term, bool> filter, Action<Term, TimeBox> action, Action<ITerm, string, bool> callback)
        {
            _dispatchedCallback = callback;
            _customValidation = filter;

            var newSubEvent = Term.New(SearchDate, SelectedEventType, _length);
            //newSubEvent.Tag = comments;
            action(newSubEvent, agent.Schedule);
        }
示例#21
0
        void world_PlantEaten(object sender, IAgent eater, Plant eaten)
        {
            // Only update the observed reward if it was a result of our action
            if (eater != this)
                return;

            // If we receive a reward for taking a step, record it
            reward += eaten.Reward;
        }
        /// <summary>
        /// Desire to randomly adjust current direction
        /// </summary>
        public static Vector3 WanderForce(IAgent agent, ref SteerParameters steerParams)
        {
            Vector3 wanderFocus = agent.Direction * 1.4f;

            // the current angle of the wander should be offset slightly
            steerParams.WanderCurrentAngle += (float)(rand.NextDouble() - 0.5f) * 2 * steerParams.TurningWeight;
            Vector3 offset = new Vector3((float)Math.Cos(steerParams.WanderCurrentAngle), 0, (float)Math.Sin(steerParams.WanderCurrentAngle));

            return Vector3.Normalize(wanderFocus + offset) * steerParams.WanderWeight;
        }
示例#23
0
        protected override void OnStart( string[] args )
        {
            if( _ServiceHost != null )
                    _ServiceHost.Close();

            ServiceHost = new ServiceHost( typeof( AgentService ) );
            ServiceHost.Open();

            _AgentEngine = new AgentEngine( int.Parse( ConfigurationManager.AppSettings["SETTINGS_ID"] ) );
        }
示例#24
0
 public String getAgentLocation(IAgent a)
 {
     Pair<String, Double> locAndTDistance = agentLocationAndTravelDistance
             [a];
     if (null == locAndTDistance)
     {
         return null;
     }
     return locAndTDistance.getFirst();
 }
示例#25
0
 public Double getAgentTravelDistance(IAgent a)
 {
     Pair<String, Double> locAndTDistance = agentLocationAndTravelDistance
             [a];
     if (null == locAndTDistance)
     {
         return Double.MinValue;
     }
     return locAndTDistance.getSecond();
 }
示例#26
0
 public ActionResult DoSpecial(string action, IAgent agent)
 {
     return new ActionResult()
                {
                    Special = false,
                    Message = Strings.NothingHappened,
                    MoveSuccessful = true,
                    GameOver = false
                };
 }
示例#27
0
 public ActionResult DoSpecial(string action, IAgent agent)
 {
     return new ActionResult()
                {
                    Message = string.Empty,
                    MoveSuccessful = true,
                    Special = false,
                    GameOver = true
                };
 }
示例#28
0
    /// <summary>
    /// Initializes a new instance of the BaseMessage class by using the
    /// message sender and recipients.
    /// </summary>
    /// <param name="sender">A string that identifies the message sender.
    /// </param>
    /// <param name="receipts">A string array containing the message
    /// recipients.</param>
    public BaseMessage(IAgent sender, IAgent[] recipients)
      : this(sender) {
      if (recipients == null)
        throw new ArgumentNullException("recipients");

      for (int i = 0, j = recipients.Length; i < j; i++) {
        IAgent recipient = recipients[i];
        recipients_.Add(recipient.Address, recipient);
      }
    }
示例#29
0
 public AgentType(IAgent a, Point3d emittionPt, Vector3d initialVelocity, AbstractEnvironmentType environment)
   : base(a, emittionPt, initialVelocity, environment)
 {
   SteerAcceleration = a.SteerAcceleration;
   MaxSpeed = a.MaxSpeed;
   MaxForce = a.MaxForce;
   VisionRadius = a.VisionRadius;
   VisionAngle = a.VisionAngle;
   Lat = 0;//Util.Random.RandomDouble(0, RS.TWO_PI);
   Lon = 0;//Util.Random.RandomDouble(-RS.HALF_PI, RS.HALF_PI);
 }
示例#30
0
        public void TryDispatch(IAgent agent, Func<Term, bool> filter, Action<Term, TimeBox> action, Action<ITerm, string, bool> callback)
        {
            var newAssignment = Term.NewAssignment(_newAssignmentStart, _newAssignmentEnd, SelectedType);

            agent.Schedule.Create(newAssignment, (terms, success) =>
            {
                if (success)
                    agent.Schedule.ArrangeSubEvent(newAssignment as IAssignment, SelectedType.GetSubEventInsertRules(), (t, result) => { });
                callback(newAssignment, "", success);
            }, false);
        }
示例#31
0
        //---------------------------------------------------------------------
        ///<summary>
        /// Calculate the The Resource Dominance of all active NEIGHBORS
        /// within the User defined NeighborRadius.
        ///
        /// The weight of neighbors is dependent upon distance and a
        /// weighting algorithm:  uniform, linear, or gaussian.
        ///
        /// Subsampling determined by User defined NeighborSpeedUp.
        /// Gaussian equation:  http://www.anc.ed.ac.uk/~mjo/intro/node7.html
        ///</summary>
        //---------------------------------------------------------------------
        public static void NeighborResourceDominance(IAgent agent)
        {
            PlugIn.ModelCore.UI.WriteLine("   Calculating BDA Neighborhood Resource Dominance.");

            double totalNeighborWeight = 0.0;
            double maxNeighborWeight   = 0.0;
            int    neighborCnt         = 0;
            int    speedUpFraction     = (int)agent.NeighborSpeedUp + 1;

            foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
            {
                if (agent.OutbreakZone[site] == Zone.Newzone)
                {
                    //neighborWeight = 0.0;
                    totalNeighborWeight = 0.0;
                    maxNeighborWeight   = 0.0;
                    neighborCnt         = 0;

                    if (SiteVars.SiteResourceDom[site] > 0)
                    {
                        List <RelativeLocationWeighted> neighborhood = new List <RelativeLocationWeighted>();
                        foreach (RelativeLocationWeighted relativeLoc in agent.ResourceNeighbors)
                        {
                            Site neighbor = site.GetNeighbor(relativeLoc.Location);
                            if (neighbor != null &&
                                neighbor.IsActive)
                            {
                                neighborhood.Add(relativeLoc);
                            }
                        }

                        neighborhood = PlugIn.ModelCore.shuffle(neighborhood);
                        foreach (RelativeLocationWeighted neighbor in neighborhood)
                        {
                            //Do NOT subsample if there are too few neighbors
                            //i.e., <= subsample size.
                            if (neighborhood.Count <= speedUpFraction ||
                                neighborCnt % speedUpFraction == 0)
                            {
                                Site activeSite = site.GetNeighbor(neighbor.Location);

                                //Note:  SiteResourceDomMod ranges from 0 - 1.
                                if (SiteVars.SiteResourceDomMod[activeSite] > 0)
                                {
                                    totalNeighborWeight += SiteVars.SiteResourceDomMod[activeSite] * neighbor.Weight;
                                    maxNeighborWeight   += neighbor.Weight;
                                }
                            }
                            neighborCnt++;
                        }

                        if (maxNeighborWeight > 0.0)
                        {
                            SiteVars.NeighborResourceDom[site] = totalNeighborWeight / maxNeighborWeight;
                        }
                        else
                        {
                            SiteVars.NeighborResourceDom[site] = 0.0;
                        }
                    }
                    else
                    {
                        SiteVars.NeighborResourceDom[site] = 0.0;
                    }
                }
            }
        }
示例#32
0
 public AttackEventArgs(IAgent source, IAgent target)
 {
     Source     = source;
     Target     = target;
     StatsDelta = new BaseStatsModel();
 }
示例#33
0
 /// <summary>
 /// Constructs a new instance.
 /// </summary>
 /// <param name="agent">The agent.</param>
 public AgentPlayout(IAgent <SearchContext <D, P, A, S, Sol>, P, A> agent)
 {
     Agent = agent;
 }
示例#34
0
        //---------------------------------------------------------------------
        //Go through all active sites and damage them according to the
        //Site Vulnerability.
        private void DisturbSites(IAgent agent)
        {
            int totalSiteSeverity = 0;
            int siteCohortsKilled = 0;

            int[] cohortsKilled = new int[2];
            //this.advRegenAgeCutoff = agent.AdvRegenAgeCutoff;

            foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
            {
                siteCohortsKilled = 0;
                this.siteSeverity = 0;
                this.random       = 0;

                double myRand = PlugIn.ModelCore.GenerateUniform();

                if (agent.OutbreakZone[site] == Zone.Newzone &&
                    SiteVars.Vulnerability[site] > myRand)
                {
                    //PlugIn.ModelCore.Log.WriteLine("Zone={0}, agent.OutbreakZone={1}", Zone.Newzone.ToString(), agent.OutbreakZone[site]);
                    //PlugIn.ModelCore.Log.WriteLine("Vulnerability={0}, Randnum={1}", SiteVars.Vulnerability[site], PlugIn.ModelCore.GenerateUniform());
                    double vulnerability = SiteVars.Vulnerability[site];

                    if (vulnerability >= 0)
                    {
                        this.siteSeverity = 1;
                    }

                    if (vulnerability >= agent.Class2_SV)
                    {
                        this.siteSeverity = 2;
                    }

                    if (vulnerability >= agent.Class3_SV)
                    {
                        this.siteSeverity = 3;
                    }

                    this.random            = myRand;
                    this.siteVulnerability = SiteVars.Vulnerability[site];

                    if (this.siteSeverity > 0)
                    {
                        cohortsKilled = KillSiteCohorts(site);
                    }

                    siteCohortsKilled = cohortsKilled[0];

                    if (SiteVars.NumberCFSconifersKilled[site].ContainsKey(PlugIn.ModelCore.CurrentTime))
                    {
                        int prevKilled = SiteVars.NumberCFSconifersKilled[site][PlugIn.ModelCore.CurrentTime];
                        SiteVars.NumberCFSconifersKilled[site][PlugIn.ModelCore.CurrentTime] = prevKilled + cohortsKilled[1];
                    }
                    else
                    {
                        SiteVars.NumberCFSconifersKilled[site].Add(PlugIn.ModelCore.CurrentTime, cohortsKilled[1]);
                    }

                    if (siteCohortsKilled > 0)
                    {
                        this.totalCohortsKilled += siteCohortsKilled;
                        this.totalSitesDamaged++;
                        totalSiteSeverity             += this.siteSeverity;
                        SiteVars.Disturbed[site]       = true;
                        SiteVars.TimeOfLastEvent[site] = PlugIn.ModelCore.CurrentTime;
                    }
                    else
                    {
                        this.siteSeverity = 0;
                    }
                }
                agent.Severity[site] = (byte)this.siteSeverity;
            }
            if (this.totalSitesDamaged > 0)
            {
                this.meanSeverity = (double)totalSiteSeverity / (double)this.totalSitesDamaged;
            }
        }
示例#35
0
 public virtual void SetAgent(IAgent agent)
 {
     Assert.IsNotNull(agent);
     AgentBase = agent;
 }
示例#36
0
 public override IPercept getPerceptSeenBy(IAgent anAgent)
 {
     return(new DynamicPercept(DynAttributeNames.PERCEPT_IN, getAgentLocation(anAgent)));
 }
示例#37
0
 public FitnessSimulation(uint simulationIDx, IAgent agent, IFitnessScenario scenario)
     : base(simulationIDx, agent, scenario)
 {
     //controls agent fitness from here
     this.StatisticsCollection.Add(agent.Fitness = this.CreateStatisticalQuantity(SCORE_ID));
 }
 public StochasticScenario(IAgent baseAgent, IEnvironment baseEnvironment, IStochasticTestsConfig testsConfig)
     : base(baseAgent, baseEnvironment, testsConfig)
 {
 }
示例#39
0
        public AfterWrappedMethodDelegate BeforeWrappedMethod(InstrumentedMethodCall instrumentedMethodCall, IAgent agent, ITransaction transaction)
        {
            var typeName   = instrumentedMethodCall.MethodCall.Method.Type.FullName ?? "<unknown>";
            var methodName = instrumentedMethodCall.MethodCall.Method.MethodName;
            var segment    = !string.IsNullOrEmpty(instrumentedMethodCall.RequestedMetricName)
                ? transaction.StartCustomSegment(instrumentedMethodCall.MethodCall, instrumentedMethodCall.RequestedMetricName)
                : transaction.StartMethodSegment(instrumentedMethodCall.MethodCall, typeName, methodName);

            //Only override transaction name if priority set since this is segment-level instrumentation
            if (!string.IsNullOrEmpty(instrumentedMethodCall.RequestedMetricName) && instrumentedMethodCall.RequestedTransactionNamePriority.HasValue)
            {
                transaction.SetCustomTransactionName(instrumentedMethodCall.RequestedMetricName, instrumentedMethodCall.RequestedTransactionNamePriority.Value);
            }

            return(Delegates.GetDelegateFor(segment));
        }
示例#40
0
        public TIView FromPrefab <TIView>(Object prefab, Transform parent, bool instantiateInWorldSpace, IAgent agent) where TIView : class, IViewBase
        {
            Assert.IsNotNull(prefab);
            var view = Object.Instantiate(prefab, parent, instantiateInWorldSpace) as TIView;

            Assert.IsNotNull(view);

            view.SetAgent(agent);
            view.SetModel(agent.BaseModel);

            view = Prepare(Inject(typeof(TIView), view)) as TIView;
            view.AddSubscriptions();
            agent.AddSubscriptions();
            agent.BaseModel.AddSubscriptions();
            return(view);
        }
示例#41
0
 public static AfterWrappedMethodDelegate GetAsyncDelegateFor <T>(IAgent agent, ISegment segment) where T : Task
 {
     return(GetAsyncDelegateFor <T>(agent, segment, TaskContinueWithOption.UseSynchronizationContext));
 }
 public void AgentActed(IAgent agent, IPercept percept, IAction action, IEnvironment source)
 {
     envChanges.Append(action).Append(":");
 }
示例#43
0
        //---------------------------------------------------------------------
        ///<summary>
        ///Calculate the Site Resource Dominance (SRD) for all active sites.
        ///The SRD averages the resources for each species as defined in the
        ///BDA species table.
        ///SRD ranges from 0 - 1.
        ///</summary>
        //---------------------------------------------------------------------
        public static void SiteResourceDominance(IAgent agent, int ROS)
        {
            PlugIn.ModelCore.UI.WriteLine("   Calculating BDA Site Resource Dominance.");

            foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
            {
                double sumValue         = 0.0;
                double maxValue         = 0.0;
                int    ageOldestCohort  = 0;
                int    numValidSpp      = 0;
                double speciesHostValue = 0;

                foreach (ISpecies species in PlugIn.ModelCore.Species)
                {
                    ageOldestCohort = Util.GetMaxAge(SiteVars.Cohorts[site][species]);
                    ISppParameters sppParms = agent.SppParameters[species.Index];
                    if (sppParms == null)
                    {
                        continue;
                    }

                    bool negList = false;
                    foreach (ISpecies negSpp in agent.NegSppList)
                    {
                        if (species == negSpp)
                        {
                            negList = true;
                        }
                    }

                    if ((ageOldestCohort > 0) && (!negList))
                    {
                        numValidSpp++;
                        speciesHostValue = 0.0;

                        if (ageOldestCohort >= sppParms.MinorHostAge)
                        {
                            speciesHostValue = 0.33;
                        }

                        if (ageOldestCohort >= sppParms.SecondaryHostAge)
                        {
                            speciesHostValue = 0.66;
                        }

                        if (ageOldestCohort >= sppParms.PrimaryHostAge)
                        {
                            speciesHostValue = 1.0;
                        }


                        sumValue += speciesHostValue;
                        maxValue  = System.Math.Max(maxValue, speciesHostValue);
                    }
                }

                if (agent.SRDmode == SRDmode.mean)
                {
                    SiteVars.SiteResourceDom[site] = sumValue / (double)numValidSpp;
                }

                if (agent.SRDmode == SRDmode.max)
                {
                    SiteVars.SiteResourceDom[site] = maxValue;
                }
            }
        }  //end siteResourceDom
示例#44
0
 private Trainer GetTrainer(IAgent agent0, IAgent agent1)
 {
     return(new Trainer(agent0, agent1, _mockedStartPlayerDeterminer.Object));
 }
示例#45
0
 public AgentUpdater(IAgent agent)
 {
     _Agent = agent;
 }
示例#46
0
        public AfterWrappedMethodDelegate BeforeWrappedMethod(InstrumentedMethodCall instrumentedMethodCall, IAgent agent, ITransaction transaction)
        {
            var typeName = instrumentedMethodCall.MethodCall.Method.Type.FullName ?? "unknown";
            var segment  = transaction.StartMethodSegment(instrumentedMethodCall.MethodCall, typeName, instrumentedMethodCall.MethodCall.Method.MethodName, isLeaf: true);

            return(Delegates.GetDelegateFor(segment));
        }
示例#47
0
 public IdleAction(IAgent <ActionEnum, GoalEnum> agent) : base(agent)
 {
 }
示例#48
0
 protected override bool InternalCondition(IAgent agent, Blackboard bb)
 {
     return(bb.ContainsValue(BlackboardKey.TargetMovePos));
 }
示例#49
0
 public double getAgentTravelDistance(IAgent a)
 {
     return(state.getAgentTravelDistance(a));
 }
示例#50
0
        }  //end siteResourceDom

        //---------------------------------------------------------------------
        ///<summary>
        ///Calculate the Site Resource Dominance MODIFIER for all active sites.
        ///Site Resource Dominance Modifier takes into account other disturbances and
        ///any ecoregion modifiers defined.
        ///SRDMods range from 0 - 1.
        ///</summary>
        //---------------------------------------------------------------------
        public static void SiteResourceDominanceModifier(IAgent agent)
        {
            PlugIn.ModelCore.UI.WriteLine("   Calculating BDA Modified Site Resource Dominance.");
            foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
            {
                if (SiteVars.SiteResourceDom[site] > 0.0)
                {
                    int    lastDisturb    = 0;
                    int    duration       = 0;
                    double disturbMod     = 0;
                    double sumDisturbMods = 0.0;
                    double SRDM           = 0.0;

                    //---- FIRE -------------------------
                    if (SiteVars.TimeOfLastFire != null &&
                        agent.DistParameters[(int)DisturbanceType.Fire].Duration > 0)
                    {
                        PlugIn.ModelCore.UI.WriteLine("   Calculating effect of Fire.");
                        lastDisturb = SiteVars.TimeOfLastFire[site];
                        duration    = agent.DistParameters[(int)DisturbanceType.Fire].Duration;

                        if (lastDisturb < duration)
                        {
                            disturbMod = agent.DistParameters[(int)DisturbanceType.Fire].DistModifier *
                                         (double)(duration - lastDisturb) / duration;
                            sumDisturbMods += disturbMod;
                        }
                    }

                    //---- WIND -------------------------
                    if (SiteVars.TimeOfLastWind != null &&
                        agent.DistParameters[(int)DisturbanceType.Wind].Duration > 0)
                    {
                        PlugIn.ModelCore.UI.WriteLine("   Calculating effect of Wind.");
                        lastDisturb = SiteVars.TimeOfLastWind[site];
                        duration    = agent.DistParameters[(int)DisturbanceType.Wind].Duration;

                        if (lastDisturb < duration)
                        {
                            disturbMod = agent.DistParameters[(int)DisturbanceType.Wind].DistModifier *
                                         (double)(duration - lastDisturb) / duration;
                            sumDisturbMods += disturbMod;
                        }
                    }

                    //---- HARVEST -------------------------
                    if (SiteVars.TimeOfLastHarvest != null &&
                        agent.DistParameters[(int)DisturbanceType.Harvest].Duration > 0)
                    {
                        PlugIn.ModelCore.UI.WriteLine("   Calculating effect of Harvesting.");
                        lastDisturb = SiteVars.TimeOfLastHarvest[site];
                        duration    = agent.DistParameters[(int)DisturbanceType.Harvest].Duration;

                        if (lastDisturb < duration)
                        {
                            disturbMod = agent.DistParameters[(int)DisturbanceType.Harvest].DistModifier *
                                         (double)(duration - lastDisturb) / duration;
                            sumDisturbMods += disturbMod;
                        }
                    }

                    //PlugIn.ModelCore.UI.WriteLine("   Summation of Disturbance Modifiers = {0}.", sumMods);
                    //---- APPLY ECOREGION MODIFIERS --------
                    IEcoregion ecoregion = PlugIn.ModelCore.Ecoregion[site];


                    SRDM = SiteVars.SiteResourceDom[site] +
                           sumDisturbMods +
                           agent.EcoParameters[ecoregion.Index].EcoModifier;

                    SRDM = System.Math.Max(0.0, SRDM);
                    SRDM = System.Math.Min(1.0, SRDM);

                    SiteVars.SiteResourceDomMod[site] = SRDM;
                }//end of one site

                else
                {
                    SiteVars.SiteResourceDomMod[site] = 0.0;
                }
            } //end Active sites
        }     //end Function
示例#51
0
 public NaturalStateEngine(IAgent agent, IStateEngine <TypeState, TypeState> stateEngine)
 {
     _agent       = agent;
     _stateEngine = stateEngine;
 }
示例#52
0
 public Handle(HostReceiveEndpointHandle[] endpoints, IAgent agent)
 {
     _endpoints = endpoints;
     _agent     = agent;
 }
示例#53
0
 public string getAgentLocation(IAgent a)
 {
     return(state.getAgentLocation(a));
 }
 public abstract void AddConsumeAgent(IAgent agent);
        public AfterWrappedMethodDelegate BeforeWrappedMethod(InstrumentedMethodCall instrumentedMethodCall, IAgent agent, ITransaction transaction)
        {
            var typeName   = instrumentedMethodCall.MethodCall.Method.Type;
            var methodName = instrumentedMethodCall.MethodCall.Method.MethodName;

            var name = $"{typeName}/{methodName}";

            transaction = agent.CreateTransaction(
                isWeb: instrumentedMethodCall.StartWebTransaction,
                category: EnumNameCache <WebTransactionType> .GetName(WebTransactionType.Custom),
                transactionDisplayName: name,
                doNotTrackAsUnitOfWork: false);

            transaction.AttachToAsync();

            var segment = !string.IsNullOrEmpty(instrumentedMethodCall.RequestedMetricName)
                ? transaction.StartCustomSegment(instrumentedMethodCall.MethodCall, instrumentedMethodCall.RequestedMetricName)
                : transaction.StartTransactionSegment(instrumentedMethodCall.MethodCall, name);

            var hasMetricName = !string.IsNullOrEmpty(instrumentedMethodCall.RequestedMetricName);

            if (hasMetricName)
            {
                var priority = instrumentedMethodCall.RequestedTransactionNamePriority ?? TransactionNamePriority.Uri;
                transaction.SetCustomTransactionName(instrumentedMethodCall.RequestedMetricName, priority);
            }

            return(Delegates.GetDelegateFor(
                       onFailure: transaction.NoticeError,
                       onComplete: OnComplete));

            void OnComplete()
            {
                segment.End();
                transaction.End();
            }
        }
示例#56
0
        public AfterWrappedMethodDelegate BeforeWrappedMethod(InstrumentedMethodCall instrumentedMethodCall, IAgent agent, ITransaction transaction)
        {
            var operation = instrumentedMethodCall.MethodCall.Method.MethodName;
            var caller    = instrumentedMethodCall.MethodCall.InvocationTarget;

            var collectionNamespace = MongoDbHelper.GetCollectionNamespacePropertyFromGeneric(caller);
            var model = MongoDbHelper.GetCollectionName(collectionNamespace);

            var collection = MongoDbHelper.GetCollectionFieldFromGeneric(caller);
            var database   = MongoDbHelper.GetDatabaseFromGeneric(collection);

            ConnectionInfo connectionInfo = MongoDbHelper.GetConnectionInfoFromDatabase(database);

            var segment = transaction.StartDatastoreSegment(instrumentedMethodCall.MethodCall,
                                                            new ParsedSqlStatement(DatastoreVendor.MongoDB, model, operation), isLeaf: true, connectionInfo: connectionInfo);

            if (!operation.EndsWith("Async", StringComparison.OrdinalIgnoreCase))
            {
                return(Delegates.GetDelegateFor(segment));
            }

            return(Delegates.GetAsyncDelegateFor <Task>(agent, segment, true));
        }
 public NotificationSource(
     IAgent agent)
 {
     _agent = agent;
 }
 public AfterWrappedMethodDelegate BeforeWrappedMethod(InstrumentedMethodCall instrumentedMethodCall, IAgent agent, ITransaction transaction)
 {
     return(Delegates.NoOp);
 }
 public void AgentAdded(IAgent agent, IEnvironment source)
 {
     // Nothing.
 }
示例#60
0
 public PlayerGoalMgr(IAgent <ActionEnum, GoalEnum> agent) : base(agent)
 {
 }