Inheritance: Descriptor
        /// <summary>
        /// Sprawdza, czy decyzja jest zwycieska
        /// </summary>
        /// <param name="mine"></param>
        /// <param name="opponet"></param>
        /// <returns></returns>
        public static int Score(this Decision mine, Decision opponet)
        {
            if (mine == opponet)
                    return 0;

                switch (mine)
                {
                    case Decision.Rock:
                        if (opponet == Decision.Paper)
                            return -1;
                        else return 1;
                    case Decision.Paper:
                        if (opponet == Decision.Scissor)
                            return -1;
                        else
                            return 1;
                    case Decision.Scissor:
                        if (opponet == Decision.Rock)
                            return -1;
                        else
                            return 1;
                    default:
                        return 0;
                }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            SolverContext context = SolverContext.GetContext();
            Model model = context.CreateModel();

            // ------------
            // Parameters
            Set city = new Set(Domain.IntegerNonnegative, "city");
            Parameter dist = new Parameter(Domain.Real, "dist", city, city);
            var arcs = from p1 in data
                       from p2 in data
                       select new Arc { City1 = p1.Name, City2 = p2.Name, Distance = p1.Distance(p2) };

            dist.SetBinding(arcs, "Distance", "City1", "City2");
            model.AddParameters(dist);

            // ------------
            // Decisions
            Decision assign = new Decision(Domain.IntegerRange(0, 1), "assign", city, city);
            Decision rank = new Decision(Domain.RealNonnegative, "rank", city);
            model.AddDecisions(assign, rank);

            // ------------
            // Goal: minimize the length of the tour.
            Goal goal = model.AddGoal("TourLength", GoalKind.Minimize,
              Model.Sum(Model.ForEach(city, i => Model.ForEachWhere(city, j => dist[i, j] * assign[i, j], j => i != j))));

            // ------------
            // Enter and leave each city only once.
            int N = data.Length;
            model.AddConstraint("assign1",
              Model.ForEach(city, i => Model.Sum(Model.ForEachWhere(city, j => assign[i, j],
                j => i != j)) == 1));
            model.AddConstraint("assign2",
              Model.ForEach(city, j => Model.Sum(Model.ForEachWhere(city, i => assign[i, j], i => i != j)) == 1));

            // Forbid subtours (Miller, Tucker, Zemlin - 1960...)
            model.AddConstraint("no_subtours",
              Model.ForEach(city,
                i => Model.ForEachWhere(city,
                  j => rank[i] + 1 <= rank[j] + N * (1 - assign[i, j]),
                  j => Model.And(i != j, i >= 1, j >= 1)
                )
              )
            );

            Solution solution = context.Solve();

            // Retrieve solution information.
            Console.WriteLine("Cost = {0}", goal.ToDouble());
            Console.WriteLine("Tour:");
            var tour = from p in assign.GetValues() where (double)p[0] > 0.9 select p[2];
            foreach (var i in tour.ToArray())
            {
                Console.Write(i + " -> ");
            }
            Console.WriteLine();
            Console.WriteLine("Press enter to continue...");
            Console.ReadLine();
        }
Beispiel #3
0
 public static double[] d2d(Decision[] d)
 {
     var result = new double[d.Length];
     for (int i = 0; i < d.Length; i++)
         result[i] = d[i].ToDouble();
     return result;
 }
Beispiel #4
0
        static void Main(string[] args)
        {
            //4.1)
            SimpleActivity greaterThan100Activity = new SimpleActivity(()=>Console.WriteLine("Value is greater than 100."));

            //4.2)
            SimpleActivity lessThan100Activity = new SimpleActivity(()=>Console.WriteLine("Value is less than 100."));

            //3.)
            Decision<int> greaterOrLess100Decision = new Decision<int>(multipliedValue => multipliedValue > 100, greaterThan100Activity, lessThan100Activity);

            //2.)
            InputOutputActivity<int,int> mutiplyBy10Activity = new InputOutputActivity<int, int>(inputValue => inputValue * 10, greaterOrLess100Decision);

            //1.)
            OutputActivity<int> getInputValueActivity = new OutputActivity<int>(()=>
                                                                                {
                                                                                    Console.Write("Please type in value:");
                                                                                    var input = Console.ReadLine();
                                                                                    return Convert.ToInt32(input);
                                                                                }, mutiplyBy10Activity);

            WorkflowEngine engine = new WorkflowEngine();
            engine.WorkflowProgressChanged += (arg1, arg2, arg3, arg4) => Console.WriteLine("Step:{0}\r\nContext:{1}\r\nSuccess:{2}\r\nException message:{3}", arg1, arg2, arg3, arg4 != null ? arg4.Message : string.Empty);

            engine.WorkflowCompleted += (arg1, arg2) => Console.WriteLine("Completed:\r\nSucceeded:{0}\r\nException message:{1}", arg1, arg2 != null ? arg2.Message : string.Empty);

            engine.Run(getInputValueActivity);

            Console.ReadLine();

            engine.Dispose();
        }
 public WinByPointsPrediction(Decision by, Boxer winner, PlayerPrediction playerPrediction)
 {
     By = by;
     Winner = winner;
     Type = "WinByPointsPrediction";
     PlayerPrediction = playerPrediction;
 }
        public override Decision Decide(IEntityRecord opponent)
        {
            Decision trick = Decision.Undecided;
            Outcome outcome = Outcome.Unknown;

            int retries = 0;
            int maxRetries = 5;

            while (outcome == Outcome.Unknown || outcome == Outcome.Loss) {
                // pick any hand and use it to see how opponent would react
                // > note that it must have some amount of influence to be considered a real decision
                trick = Decision.Next(1);

                Decision reaction = new Decision();

                foreach (Behavior behavior in opponent.GetComponents().OfType<Behavior>()) {
                    reaction += behavior.React(Record, trick);
                }

                outcome = trick.DetermineOutcome(reaction);

                if (retries++ > maxRetries) {
                    break;
                }
            }

            // > note that we do not use Decision.Counter on the reaction that resulted in a win, because
            // it was actually the trick hand that caused the win
            return Decision.Distribute(
                trick.MostInfluencedHand, Influence);
        }
    /// <summary>
    /// Initializes a new instance of the <see cref="DecisionTree"/> class.
    /// </summary>
    /// <param name="_decisions">_decisions.</param>
    /// <param name="_actions">_actions.</param>
    /// <param name="_callback">_callback.</param>
    public DecisionTree(Decision[] _decisions, TreeAction[] _actions, Action<TreeAction> _callback)
    {
        decisions = _decisions;
        actions = _actions;
        callback = _callback;

        doneEvent = new ManualResetEvent(true);
    }
Beispiel #8
0
        /// <summary>
        /// Gets the decision that has occured later in time.
        /// </summary>
        public static Decision GetNewer(Decision a, Decision b)
        {
            if (a == null)
                return b;

            if (b == null)
                return a;

            return a.time > b.time ? a : b;
        }
Beispiel #9
0
        public bool Transfer(Guid competitionId, Decision decision)
        {
            var competition = this.repository.Get(competitionId);
            if (competition == null) return false;
            if (!this.stateService.CanUpdateResult(competition)) return false;

            competition.RegisterWin(decision.Winner);
            competition.RegisterLoss(decision.Looser);
            return this.repository.Update(competition);
        }
Beispiel #10
0
    //public GameObject gameLogic;

    // Use this for initialization
    void Start () {
        gameState = FindObjectOfType<PersistantState>();
        currentDecision = gameState.Decisions[gameState.Stage];

        textDay.text = string.Format("Day {0}", gameState.Stage + 1);
        textQuery.text = currentDecision.query;
        buttonAlternative1.GetComponentInChildren<Text>().text = currentDecision.alternatives[0];
        buttonAlternative1.onClick.AddListener(delegate { onClick(0); });
        buttonAlternative2.GetComponentInChildren<Text>().text = currentDecision.alternatives[1];
        buttonAlternative2.onClick.AddListener(delegate { onClick(1); });
    }
        public override Decision React(IEntityRecord opponent, Decision decision)
        {
            Decision counter = Decision.Win(decision, Influence);

            Hand choices =
                counter.MostInfluencedHand |
                decision.MostInfluencedHand;

            return Decision.Next(
                choices, Influence * 2);
        }
Beispiel #12
0
        public Decision[,] BuildDecisions()
        {
            for (int i = 0; i < Decisions.GetLength(0); i++)
            {
                for (int j = 0; j < Decisions.GetLength(1); j++)
                {
                    Decisions[i, j] = new Decision(domain, "_" + i + "Decision" + j);
                }
            }

            return Decisions;
        }
        public override Decision React(IEntityRecord opponent, Decision decision)
        {
            Decision reaction = Decision.Undecided;

            History opponentHistory = opponent.GetComponent<History>();

            if (opponentHistory != null) {
                reaction = opponentHistory.PreviousDecision;
            }

            return Decision.Distribute(
                reaction.MostInfluencedHand, Influence);
        }
Beispiel #14
0
        public bool MakeDecision(Guid sessionId, Decision decision)
        {
            var session = Get(sessionId);
            if (session == null) return false;
            if (session.IsClosed) return false;

            var operationChecker = new OperationChecker(this.competitionRepository);
            var gateway = new DecisionGateway(this.competitionRepository, operationChecker);
            session.RegisterDecision(decision, gateway);

            this.unitOfWork.Commit();
            return true;
        }
Beispiel #15
0
        public void RegisterDecision(Decision decision, IDecisionGateway gateway)
        {
            if (this.IsClosed) return;

            var duel = decision.Duel;

            AssertScheduleContainsDuel(duel);
            AssertDecisionIsNotRegisteredYet(duel);

            this.Outcomes.Add(new Outcome(decision));
            this.Schedule.Remove(duel);

            gateway.Transfer(this.CompetitionId, decision);
        }
Beispiel #16
0
 /*
  * Init method allow to pass a title and message that will be displayed to the user,
  * and also a decision delegate
 */
 public void init(string title, string message, Decision dec)
 {
     this.title.text = title;
     this.message.text = message;
     cancel.onClick.AddListener(delegate {
         gameObject.SetActive(false);
         dec(false);
     });
     ok.onClick.AddListener(delegate {
         gameObject.SetActive(false);
         dec(true);
     });
     gameObject.SetActive (true);
 }
        /// <summary>
        /// Aktualizuje wejscia po kolejnej rundzie gry
        /// </summary>
        /// <param name="AIDecision">własna decyzja</param>
        /// <param name="opponentDecision">decyzja przeciwnika</param>
        public void updateInputs(Decision AIDecision, Decision opponentDecision )
        {
            //przesuwamy wejscia w prawo
            double[] oldInputs = new double[inputs.Length];
            inputs.CopyTo(oldInputs, 0);
            for (int j = 3; j < inputs.Length; ++j)
                inputs[j] = oldInputs[j - 3];

            //dopisujemy nowe wejscia
            for (int j = 0; j < 3; ++j)
            {
                inputs[j] = AIDecision.ToNeural()[j];
                inputs[j + inputs.Length / 2] = opponentDecision.ToNeural()[j];
            }
        }
Beispiel #18
0
        /// <summary>
        /// Creates a new Result using the provided information.
        /// </summary>
        /// <param name="resourceId">The resource id for this result.</param>
        /// <param name="decision">The decission of the evaluation.</param>
        /// <param name="status">The status with information about the execution.</param>
        /// <param name="obligations">The list of obligations</param>
        /// <param name="schemaVersion">The version of the schema that was used to validate.</param>
        public ResultElement(string resourceId, Decision decision, StatusElement status, ObligationCollection obligations, XacmlVersion schemaVersion)
            : base(XacmlSchema.Context, schemaVersion)
        {
            _resourceId = resourceId;
            Decision = decision;

            // If the status is null, create an empty status
            Status = status ?? new StatusElement(null, null, null, schemaVersion);

            // If the obligations are null, leave the empty ObligationCollection.
            if (obligations != null)
            {
                _obligations = obligations;
            }
        }
        public void scoreRound(Decision playerDecision)
        {
            var opponentDecision = decisionMaker.getNextDecision();
            int score = playerDecision.Score(opponentDecision);

            if (score == -1)
                opponentScore += 1;
            else if (score == 1)
                playerScore += 1;

            ScoreLabel.Content = playerScore + " : " + opponentScore;

            HistoryTextBox.Text = "Ty: " + playerDecision.toLocalString() + ", przeciwnik: " + opponentDecision.toLocalString();

            decisionMaker.rememberDecision(playerDecision);
        }
    private void sendDecision(Decision decision)
    {
        BroadcastMessage("Decision",  decision);

        if(decision == Decision.left){
            currentHorizontal--;
        }

        if(decision == Decision.right){
            currentHorizontal++;
        }

        if(decision == Decision.up){
            currentVertical++;
        }

        if(decision == Decision.down){
            currentVertical--;
        }
    }
        /// <summary>
        /// Funkcja odpowiedzialna za proces nauki
        /// </summary>
        /// <param name="AIDecision">decyzja podjeta przez siec</param>
        /// <param name="opponentDecision">decyzja przeciwnika</param>
        public void updateWeights(Decision AIDecision, Decision opponentDecision)
        {
            Decision expectedDecision = opponentDecision.GetCounter(); //decyzja, ktora powinnismy podjac

            if (expectedDecision == AIDecision)
                return; //i tak sie wagi nie zmienia, wiec konczymy funkcje od razu

            double[] desiredOutput = expectedDecision.ToNeural();
            double[] currentOutput = AIDecision.ToNeural();

            for (int i = 0; i < outputs.Length; ++i)
            {
                double diff = (desiredOutput[i] - currentOutput[i]) * learningRate; //obliczamy poprawke

                for (int j = 0; j < inputs.Length; ++j)
                    weights[i, j] +=  diff * inputs[j]; //wprowadzamy poprawke do wag sieci
            }

            if (minLearningRate < learningRate - learnigEnstinguishRate)
                learningRate -= learnigEnstinguishRate;
        }
Beispiel #22
0
        private void TestService1(Directive directive)
        {
            SolverContext context = SolverContext.GetContext();
            Model model = context.CreateModel();

            Decision x1 = new Decision(Domain.RealRange(0, 2), "x1");
            Decision x2 = new Decision(Domain.RealRange(0, 2), "x2");

            Decision z = new Decision(Domain.IntegerRange(0, 1), "z");

            model.AddDecisions(x1, x2, z);

            model.AddConstraint("Row0", x1 - z <= 1);
            model.AddConstraint("Row1", x2 + z <= 2);

            Goal goal = model.AddGoal("Goal0", GoalKind.Maximize, x1 + x2);

            Solution solution = context.Solve(directive);
            Assert.IsTrue(goal.ToInt32() == 3);
            context.ClearModel();
        }
Beispiel #23
0
        List <Decision> Decide(DecisionTask task)
        {
            try
            {
                List <Decision> decisions  = new List <Decision>();
                var             startEvent = task.Events.FirstOrDefault(x => x.EventType == EventType.WorkflowExecutionStarted);
                if (startEvent != null)
                {
                    var pollId = startEvent.WorkflowExecutionStartedEventAttributes.Input;
                    Logger.LogMessage("Processing decision task for poll id: " + pollId);

                    var poll = PollProcessor.Instance.GetPollAsync(pollId).Result;

                    if (poll != null)
                    {
                        if (poll.State == PollDefinition.POLL_STATE_UNSCHEDULE && DateTime.Now < poll.StartTime)
                        {
                            // Add second to compensate for the rounding
                            var timeDelay = (int)(new TimeSpan(poll.StartTime.Ticks - DateTime.Now.Ticks).TotalSeconds) + 1;
                            var decision  = new Decision
                            {
                                DecisionType = DecisionType.StartTimer,
                                StartTimerDecisionAttributes = new StartTimerDecisionAttributes
                                {
                                    StartToFireTimeout = timeDelay.ToString(),
                                    TimerId            = Guid.NewGuid().ToString()
                                }
                            };
                            decisions.Add(decision);
                            PollProcessor.Instance.UpdatePollStateAsync(pollId, PollDefinition.POLL_STATE_SCHEDULE).Wait();
                            Logger.LogMessage("Scheduled timer for {0} seconds till activating poll.", timeDelay);
                        }
                        else if (poll.State == PollDefinition.POLL_STATE_SCHEDULE)
                        {
                            Decision decision = new Decision()
                            {
                                DecisionType = DecisionType.ScheduleActivityTask,
                                ScheduleActivityTaskDecisionAttributes = new ScheduleActivityTaskDecisionAttributes()
                                {
                                    ActivityType = new ActivityType()
                                    {
                                        Name    = Constants.SWF_ACTIVTY_START_TIMER_EXPIRED,
                                        Version = Constants.SWF_ACTIVTY_START_TIMER_EXPIRED_VERSION
                                    },
                                    TaskList = new TaskList
                                    {
                                        Name = Constants.SWF_ACTIVTY_START_TIMER_EXPIRED_TASKLIST
                                    },
                                    HeartbeatTimeout       = Constants.SWF_TIMEOUT,
                                    ScheduleToCloseTimeout = Constants.SWF_TIMEOUT,
                                    ScheduleToStartTimeout = Constants.SWF_TIMEOUT,
                                    StartToCloseTimeout    = Constants.SWF_TIMEOUT,
                                    ActivityId             = string.Format("{0}:{1}", Constants.SWF_ACTIVTY_START_TIMER_EXPIRED, DateTime.Now.Ticks),
                                    Input = poll.Id
                                }
                            };
                            decisions.Add(decision);
                            Logger.LogMessage("Start timer complete now deciding to run the {0} activity to activate poll.", Constants.SWF_ACTIVTY_START_TIMER_EXPIRED);
                        }
                        else if (poll.State == PollDefinition.POLL_STATE_ACTIVE && DateTime.Now < poll.EndTime)
                        {
                            // Add second to compensate for the rounding
                            var timeDelay = (int)(new TimeSpan(poll.EndTime.Ticks - DateTime.Now.Ticks).TotalSeconds) + 1;
                            var decision  = new Decision
                            {
                                DecisionType = DecisionType.StartTimer,
                                StartTimerDecisionAttributes = new StartTimerDecisionAttributes
                                {
                                    StartToFireTimeout = timeDelay.ToString(),
                                    TimerId            = Guid.NewGuid().ToString()
                                }
                            };
                            decisions.Add(decision);
                            Logger.LogMessage("Scheduled timer for {0} seconds till poll expires.", timeDelay);
                        }
                        else if (poll.State == PollDefinition.POLL_STATE_ACTIVE)
                        {
                            Decision decision = new Decision()
                            {
                                DecisionType = DecisionType.ScheduleActivityTask,
                                ScheduleActivityTaskDecisionAttributes = new ScheduleActivityTaskDecisionAttributes()
                                {
                                    ActivityType = new ActivityType()
                                    {
                                        Name    = Constants.SWF_ACTIVTY_END_TIMER_EXPIRED,
                                        Version = Constants.SWF_ACTIVTY_END_TIMER_EXPIRED_VERSION
                                    },
                                    TaskList = new TaskList
                                    {
                                        Name = Constants.SWF_ACTIVTY_END_TIMER_EXPIRED_TASKLIST
                                    },
                                    HeartbeatTimeout       = Constants.SWF_TIMEOUT,
                                    ScheduleToCloseTimeout = Constants.SWF_TIMEOUT,
                                    ScheduleToStartTimeout = Constants.SWF_TIMEOUT,
                                    StartToCloseTimeout    = Constants.SWF_TIMEOUT,
                                    ActivityId             = string.Format("{0}:{1}", Constants.SWF_ACTIVTY_END_TIMER_EXPIRED, DateTime.Now.Ticks),
                                    Input = poll.Id
                                }
                            };
                            decisions.Add(decision);
                            Logger.LogMessage("End timer complete now deciding to run the {0} activity to expire poll.", Constants.SWF_ACTIVTY_END_TIMER_EXPIRED);
                        }
                    }
                }

                if (decisions.Count == 0)
                {
                    Decision decision = new Decision()
                    {
                        DecisionType = DecisionType.CompleteWorkflowExecution,
                        CompleteWorkflowExecutionDecisionAttributes = new CompleteWorkflowExecutionDecisionAttributes
                        {
                        }
                    };
                    decisions.Add(decision);
                    Logger.LogMessage("Workflow execution complete for {0}", task.WorkflowExecution.WorkflowId);
                }

                return(decisions);
            }
            catch (Exception e)
            {
                string message = string.Format("Error processing work flow execution {0} and is being aborted: {1}\n", task.WorkflowExecution.WorkflowId, e.Message, e.StackTrace);
                Logger.LogMessage(message);
                Decision decision = new Decision()
                {
                    DecisionType = DecisionType.CompleteWorkflowExecution,
                    CompleteWorkflowExecutionDecisionAttributes = new CompleteWorkflowExecutionDecisionAttributes
                    {
                        Result = message
                    }
                };
                return(new List <Decision> {
                    decision
                });
            }
        }
Beispiel #24
0
        public virtual Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
        {
            if (searchCriteria != null && searchCriteria.UserInvokedSearch)
            {
                _logger.Debug("Ignoring delay for user invoked search");
                return(Decision.Accept());
            }

            var profile             = subject.Series.Profile.Value;
            var delayProfile        = _delayProfileService.BestForTags(subject.Series.Tags);
            var delay               = delayProfile.GetProtocolDelay(subject.Release.DownloadProtocol);
            var isPreferredProtocol = subject.Release.DownloadProtocol == delayProfile.PreferredProtocol;

            if (delay == 0)
            {
                _logger.Debug("Profile does not require a waiting period before download for {0}.", subject.Release.DownloadProtocol);
                return(Decision.Accept());
            }

            var comparer = new QualityModelComparer(profile);

            if (isPreferredProtocol)
            {
                foreach (var file in subject.Episodes.Where(c => c.EpisodeFileId != 0).Select(c => c.EpisodeFile.Value))
                {
                    var upgradable = _qualityUpgradableSpecification.IsUpgradable(profile, file.Quality, subject.ParsedEpisodeInfo.Quality);

                    if (upgradable)
                    {
                        var revisionUpgrade = _qualityUpgradableSpecification.IsRevisionUpgrade(file.Quality, subject.ParsedEpisodeInfo.Quality);

                        if (revisionUpgrade)
                        {
                            _logger.Debug("New quality is a better revision for existing quality, skipping delay");
                            return(Decision.Accept());
                        }
                    }
                }
            }

            // If quality meets or exceeds the best allowed quality in the profile accept it immediately
            var bestQualityInProfile = new QualityModel(profile.LastAllowedQuality());
            var isBestInProfile      = comparer.Compare(subject.ParsedEpisodeInfo.Quality, bestQualityInProfile) >= 0;

            if (isBestInProfile && isPreferredProtocol)
            {
                _logger.Debug("Quality is highest in profile for preferred protocol, will not delay");
                return(Decision.Accept());
            }

            // var episodeIds = subject.Episodes.Select(e => e.Id);

            //var oldest = _pendingReleaseService.OldestPendingRelease(subject.Series.Id, episodeIds);

            //if (oldest != null && oldest.Release.AgeMinutes > delay)
            //{
            //    return Decision.Accept();
            //}

            if (subject.Release.AgeMinutes < delay)
            {
                _logger.Debug("Waiting for better quality release, There is a {0} minute delay on {1}", delay, subject.Release.DownloadProtocol);
                return(Decision.Reject("Waiting for better quality release"));
            }

            return(Decision.Accept());
        }
        public void DecisionFunctionTest()
        {
            BusinessRuleTask ruleTask = new BusinessRuleTask();

            ruleTask.BusinessRule = new Definitions();

            var decision = new Decision();

            decision.Id = "decision_kowu89q";
            decision.DecisionTable.HitPolicy   = "COLLECT";
            decision.DecisionTable.Aggregation = "SUM";

            decision.DecisionTable.Inputs.Add(new DecisionTableInput()
            {
                InputExpression = new InputExpression()
                {
                    Text    = "person.age",
                    TypeRef = "number"
                }
            });
            decision.DecisionTable.Inputs.Add(new DecisionTableInput()
            {
                InputExpression = new InputExpression()
                {
                    Text    = "person.name",
                    TypeRef = "string"
                }
            });
            decision.DecisionTable.Inputs.Add(new DecisionTableInput()
            {
                InputExpression = new InputExpression()
                {
                    Text    = "person.dateOfBirth",
                    TypeRef = "date"
                }
            });

            decision.DecisionTable.Outputs.Add(new DecisionTableOutput()
            {
                Name    = "categoryOne",
                TypeRef = "number"
            });
            decision.DecisionTable.Outputs.Add(new DecisionTableOutput()
            {
                Name    = "categoryTwo",
                TypeRef = "number"
            });

            var rule1 = new DecisionTableRule();

            rule1.InputEntries.Add(new InputEntry()
            {
                Text = "18"
            });
            rule1.InputEntries.Add(new InputEntry()
            {
                Text = "\"Paul\""
            });
            rule1.InputEntries.Add(new InputEntry()
            {
                Text = string.Empty
            });
            rule1.OutputEntries.Add(new OutputEntry()
            {
                Text = "5"
            });
            rule1.OutputEntries.Add(new OutputEntry()
            {
                Text = "6"
            });
            decision.DecisionTable.Rules.Add(rule1);

            var rule2 = new DecisionTableRule();

            rule2.InputEntries.Add(new InputEntry()
            {
                Text = "> 18"
            });
            rule2.InputEntries.Add(new InputEntry()
            {
                Text = "\"Peter\""
            });
            rule2.InputEntries.Add(new InputEntry()
            {
                Text = string.Empty
            });
            rule2.OutputEntries.Add(new OutputEntry()
            {
                Text = "3"
            });
            rule2.OutputEntries.Add(new OutputEntry()
            {
                Text = "4"
            });
            decision.DecisionTable.Rules.Add(rule2);

            var rule3 = new DecisionTableRule();

            rule3.InputEntries.Add(new InputEntry()
            {
                Text = string.Empty
            });
            rule3.InputEntries.Add(new InputEntry()
            {
                Text = string.Empty
            });
            rule3.InputEntries.Add(new InputEntry()
            {
                Text = "> date(\"2000 - 01 - 01\")"
            });
            rule3.OutputEntries.Add(new OutputEntry()
            {
                Text = "1"
            });
            rule3.OutputEntries.Add(new OutputEntry()
            {
                Text = "2"
            });
            decision.DecisionTable.Rules.Add(rule3);

            var rule4 = new DecisionTableRule();

            rule4.InputEntries.Add(new InputEntry()
            {
                Text = string.Empty
            });
            rule4.InputEntries.Add(new InputEntry()
            {
                Text = string.Empty
            });
            rule4.InputEntries.Add(new InputEntry()
            {
                Text = string.Empty
            });
            rule4.OutputEntries.Add(new OutputEntry()
            {
                Text = "0"
            });
            rule4.OutputEntries.Add(new OutputEntry()
            {
                Text = "0"
            });
            decision.DecisionTable.Rules.Add(rule4);

            ruleTask.BusinessRule.Decisions.Add(decision);

            BusinessRuleTaskConverter ruleConverter = new BusinessRuleTaskConverter(ruleTask, null);

            foreach (var decisionRC in ruleConverter.BusinessRuleTaskElement.BusinessRule.Decisions)
            {
                var decisionConverter = new DecisionConverter(decisionRC);
                decisionConverter.ConvertElementLogic();
                ruleConverter.DecisionConverters.Add(decisionConverter);
            }
            string given = string.Empty;

            var components = new List <SolidityComponent>();

            foreach (var decisionConverter in ruleConverter.DecisionConverters)
            {
                components.AddRange(decisionConverter.GetGeneratedSolidityComponents());
            }
            foreach (var component in components)
            {
                given += $"{component.ToString()}\n";
            }

            string expected = "struct Decision_kowu89qOutput{\n" +
                              "\tint categoryOne;\n" +
                              "\tint categoryTwo;\n" +
                              "}\n" +
                              "\n" +
                              "function decision_kowu89q() internal view returns(Decision_kowu89qOutput memory){\n" +
                              "\tDecision_kowu89qOutput memory output;\n" +
                              "\tbool matchedRule = false;\n" +
                              "\tif(person.age == 18 && keccak256(abi.encodePacked(person.name)) == keccak256(abi.encodePacked(\"Paul\"))){\n" +
                              "\t\toutput.categoryOne += 5;\n" +
                              "\t\toutput.categoryTwo += 6;\n" +
                              "\t\tmatchedRule = true;\n" +
                              "\t}\n" +
                              "\tif(person.age > 18 && keccak256(abi.encodePacked(person.name)) == keccak256(abi.encodePacked(\"Peter\"))){\n" +
                              "\t\toutput.categoryOne += 3;\n" +
                              "\t\toutput.categoryTwo += 4;\n" +
                              "\t\tmatchedRule = true;\n" +
                              "\t}\n" +
                              "\tif(person.dateOfBirth > 20000101){\n" +
                              "\t\toutput.categoryOne += 1;\n" +
                              "\t\toutput.categoryTwo += 2;\n" +
                              "\t\tmatchedRule = true;\n" +
                              "\t}\n" +
                              "\toutput.categoryOne += 0;\n" +
                              "\toutput.categoryTwo += 0;\n" +
                              "\tmatchedRule = true;\n" +
                              "\tif(!matchedRule){\n" +
                              "\t\trevert('Undefined output');\n" +
                              "\t}\n" +
                              "\treturn output;\n" +
                              "}\n\n";

            Assert.Equal(expected, given);
        }
Beispiel #26
0
        /// <summary>
        /// Called when a acknowledge message is received from the client
        /// </summary>
        internal async Task AcknowledgeDelivered(MqClient from, TmqMessage deliveryMessage)
        {
            MessageDelivery delivery = TimeKeeper.FindAndRemoveDelivery(from, deliveryMessage.MessageId);

            //when server and consumer are in pc,
            //sometimes consumer sends ack before server start to follow ack of the message
            //that happens when ack message is arrived in less than 0.01ms
            //in that situation, server can't find the delivery with FindAndRemoveDelivery, it returns null
            //so we need to check it again after a few milliseconds
            if (delivery == null)
            {
                await Task.Delay(1);

                delivery = TimeKeeper.FindAndRemoveDelivery(from, deliveryMessage.MessageId);

                //try again
                if (delivery == null)
                {
                    await Task.Delay(3);

                    delivery = TimeKeeper.FindAndRemoveDelivery(from, deliveryMessage.MessageId);
                }
            }

            bool success = true;

            if (deliveryMessage.Length > 0 && deliveryMessage.Content != null)
            {
                string msg = deliveryMessage.Content.ToString();
                if (msg.Equals("FAILED", StringComparison.InvariantCultureIgnoreCase) || msg.Equals("TIMEOUT", StringComparison.InvariantCultureIgnoreCase))
                {
                    success = false;
                }
            }

            if (delivery != null)
            {
                delivery.MarkAsAcknowledged(success);
            }

            if (success)
            {
                Info.AddAcknowledge();
            }
            else
            {
                Info.AddUnacknowledge();
            }

            Decision decision = await DeliveryHandler.AcknowledgeReceived(this, deliveryMessage, delivery, success);

            if (delivery != null)
            {
                if (Options.HideClientNames)
                {
                    deliveryMessage.SetSource(null);
                }

                await ApplyDecision(decision, delivery.Message, deliveryMessage);
            }

            ReleaseAcknowledgeLock(true);
        }
Beispiel #27
0
        public async Task <PullResult> Pull(ChannelClient client, TmqMessage request)
        {
            QueueMessage message = null;

            await _queue.RunInListSync(() =>
            {
                //pull from prefential messages
                if (_queue.HighPriorityLinkedList.Count > 0)
                {
                    message = _queue.HighPriorityLinkedList.First.Value;
                    _queue.HighPriorityLinkedList.RemoveFirst();

                    if (message != null)
                    {
                        message.IsInQueue = false;
                    }
                }

                //if there is no prefential message, pull from standard messages
                if (message == null && _queue.RegularLinkedList.Count > 0)
                {
                    message = _queue.RegularLinkedList.First.Value;
                    _queue.RegularLinkedList.RemoveFirst();

                    if (message != null)
                    {
                        message.IsInQueue = false;
                    }
                }
            });

            //there is no pullable message
            if (message == null)
            {
                await client.Client.SendAsync(MessageBuilder.ResponseStatus(request, KnownContentTypes.NotFound));

                return(PullResult.Empty);
            }

            try
            {
                await ProcessPull(client, request, message);
            }
            catch (Exception ex)
            {
                _queue.Info.AddError();
                try
                {
                    Decision decision = await _queue.DeliveryHandler.ExceptionThrown(_queue, message, ex);

                    await _queue.ApplyDecision(decision, message);

                    if (decision.KeepMessage && !message.IsInQueue)
                    {
                        _queue.AddMessage(message, false);
                    }
                }
                catch //if developer does wrong operation, we should not stop
                {
                }
            }

            return(PullResult.Success);
        }
Beispiel #28
0
        /// <summary>
        /// Deletes the decision.
        /// </summary>
        /// <param name="decision">The decision.</param>
        /// <returns></returns>
        public int DeleteDecision(Decision decision)
        {
            var result = _repositoryFactory.GetDecisionRepository.GetDecisionById(decision.Id);

            return(_repositoryFactory.GetDecisionRepository.DeleteDecision(result));
        }
 partial void EditOverride(T4MVC_System_Web_Mvc_ActionResult callInfo, Decision.ViewModel.Role.EditRoleViewModel viewModel);
 public override System.Threading.Tasks.Task<System.Web.Mvc.ActionResult> ListAjax(Decision.ViewModel.Role.RoleSearchRequest request)
 {
     var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.ListAjax);
     ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "request", request);
     ListAjaxOverride(callInfo, request);
     return System.Threading.Tasks.Task.FromResult(callInfo as ActionResult);
 }
 /// <summary>
 /// Reacts on an opponent's decision by always picking a losing hand.
 /// </summary>
 public override Decision React(IEntityRecord opponent, Decision decision)
 {
     return Decision.Loss(
         decision, Influence);
 }
Beispiel #32
0
 // i've decided to make the node data it self viewable
 public Info(Decision choices)
 {
     type = Type.Descision;
     Data = choices;
 }
        protected override PatternResult <Overtrade?> ComputeByIndexImpl(int index)
        {
            var result = _rsiIndicator.ComputeByIndex(index);

            return(new PatternResult <Overtrade?>(Equity[index].DateTime, Decision.IsOvertrade(result.Rsi)));
        }
Beispiel #34
0
 public Decision(Guard guard)
 {
     this.guard     = guard;
     this.trueNode  = null;
     this.falseNode = null;
 }
Beispiel #35
0
        public override Decision Next(Solver solver)
        {
            if (lastDecisionRoute1 == null || lastDecisionRoute2 == null)
            {
                ConstraintProblem.ConstraintModelNode[] startNodes =
                    (from node in csp.ModelNodes
                     where node.Route.Value() != 0 && node.NodeDescription.IsStart
                     select node).ToArray();

                lastDecisionRoute1 = (from node in startNodes where node.Route.Value() == 1 select node).ToArray().First();
                lastDecisionRoute2 = (from node in startNodes where node.Route.Value() == 2 select node).ToArray().First();
            }

            if (lastDecisionRoute1.NodeDescription.IsEnd &&
                lastDecisionRoute2.NodeDescription.IsEnd)
            {
                return(null);
            }

            ConstraintProblem.ConstraintModelNode nextRoute1 = null;
            ConstraintProblem.ConstraintModelNode nextRoute2 = null;
            if (lastDecisionRoute1.Next.Bound())
            {
                nextRoute1 = csp.ModelNodes[lastDecisionRoute1.Next.Value()];
            }
            else
            {
                nextRoute1 = lastDecisionRoute1;
            }
            if (lastDecisionRoute2.Next.Bound())
            {
                nextRoute2 = csp.ModelNodes[lastDecisionRoute2.Next.Value()];
            }
            else
            {
                nextRoute2 = lastDecisionRoute2;
            }

            ConstraintProblem.ConstraintModelNode closestRoute1 = null;
            ConstraintProblem.ConstraintModelNode closestRoute2 = null;

            ConstraintProblem.ConstraintModelNode[] NextsFromNextNodes =
                (from node in csp.ModelNodes
                 where nextRoute1.Next.Contains(node.Id) || nextRoute2.Next.Contains(node.Id)
                 orderby node.Id
                 select node).ToArray();

            ConstraintProblem.ConstraintModelNode[] NextsFromNextNodeRoute1 =
                (from node in NextsFromNextNodes
                 where node.Route.Value() == nextRoute1.Route.Value() && nextRoute1.Next.Contains(node.Id)
                 select node).ToArray();

            ConstraintProblem.ConstraintModelNode[] NextsFromNextNodeRoute2 =
                (from node in NextsFromNextNodes
                 where node.Route.Value() == nextRoute2.Route.Value() && nextRoute2.Next.Contains(node.Id)
                 select node).ToArray();


            closestRoute1 = findClosestNode(nextRoute1, NextsFromNextNodeRoute1);
            closestRoute2 = findClosestNode(nextRoute2, NextsFromNextNodeRoute2);

            if (closestRoute1.NodeDescription.IsEnd)
            {
                lastDecisionRoute1 = closestRoute1;
            }
            else
            {
                lastDecisionRoute1 = nextRoute1;
            }

            if (closestRoute2.NodeDescription.IsEnd)
            {
                lastDecisionRoute2 = closestRoute2;
            }
            else
            {
                lastDecisionRoute2 = nextRoute2;
            }

            lastDecision = solver.MakeAssignVariablesValues(new IntVar[] { nextRoute1.Next, nextRoute2.Next }, new long[] { closestRoute1.Id, closestRoute2.Id });
            return(lastDecision);
        }
Beispiel #36
0
        /// <summary>
        /// 仿真机器鱼位姿到位姿镇定算法(位置坐标和方向弧度值) Modified by Zhangbo20111020
        /// 场地坐标系定义为:X向右,Y向下,负X轴顺时针转回负X轴角度范围为(-PI,PI)的坐标系
        /// </summary>
        /// <param name="decision">决策变量 输出参数 会被修改</param>
        /// <param name="fish">目标仿真机器鱼(其PositionMm/PolygonVertices[0]和BodyDirectionRad参数为起始位姿)</param>
        /// <param name="destPtMm">目标位置坐标(目标点)</param>
        /// <param name="destDirRad">目标方向弧度值(目标方向)</param>
        /// <param name="angThreshold">关键调节参数(中间方向与鱼体方向度数差值绝对值)上限,默认30度</param>
        /// <param name="disThreshold">关键调节参数(临时目标点与最终目标点距离)阈值</param>
        /// <param name="msPerCycle">每个仿真周期的毫秒数,默认取100</param>
        public static void PoseToPose(ref Decision decision, RoboFish fish, xna.Vector3 destPtMm, float destDirRad,
                                      float angThreshold, float disThreshold, int msPerCycle, ref int times)
        {
            // 标志量为true则起始点为PositionMm即鱼体绘图中心false则起始点为PolygonVertices[0]即鱼头点(起始点)
            xna.Vector3 srcPtMm = fish.PositionMm;
            // 起始点到目标点的距离(目标距离)
            double disSrcPtMmToDestPtMm = Math.Sqrt(Math.Pow(destPtMm.X - srcPtMm.X, 2.0)
                                                    + Math.Pow(destPtMm.Z - srcPtMm.Z, 2.0));

            // 沿目标方向的反方向偏离目标点阈值距离的临时目标点(临时目标点)
            xna.Vector3 tmpPtMm = new xna.Vector3((float)(destPtMm.X - disThreshold * Math.Cos(destDirRad)),
                                                  0, (float)(destPtMm.Z - disThreshold * Math.Sin(destDirRad)));

            double disSrcPtMmToTmpPtMm = Math.Sqrt(Math.Pow(tmpPtMm.X - srcPtMm.X, 2.0)
                                                   + Math.Pow(tmpPtMm.Z - srcPtMm.Z, 2.0));

            // 镇定阶段标志 1为远距离第一阶段2为近距离第二阶段
            int phrase = 2;

            if (disSrcPtMmToTmpPtMm > 0.2 * disThreshold && times == 0)
            {// 起始点到临时目标点的距离大于阈值的20%,则认为尚未镇定到临时目标点,需要把目标点修正成临时目标点
                destPtMm = tmpPtMm;
                phrase   = 1;
            }

            // 鱼体绘图中心指向目标点向量方向的弧度值(中间方向)
            double dirFishToDestPtRad = xna.MathHelper.ToRadians((float)GetAngleDegree(destPtMm - fish.PositionMm));

            // 中间方向与鱼体方向的差值(目标角度)
            double deltaTheta = dirFishToDestPtRad - fish.BodyDirectionRad;

            // 将目标角度规范化到(-PI,PI]
            // 规范化之后目标角度为正,表示目标方向在鱼体方向右边
            // 规范化之后目标角度为负,表示目标方向在鱼体方向左边
            if (deltaTheta > Math.PI)
            {                              // 中间方向为正鱼体方向为负才可能目标角度大于PI
                deltaTheta -= 2 * Math.PI; // 规范化到(-PI,0)
            }
            else if (deltaTheta < -Math.PI)
            {                              // 中间方向为负鱼体方向为正才可能目标角度小于-PI
                deltaTheta += 2 * Math.PI; // 规范化到(0,PI)
            }

            if (Math.Abs(deltaTheta) > angThreshold * Math.PI / 180.0)
            {// 目标角度绝对值超过某一阈值(默认30度)速度档位置次低进行小半径转弯。防止控制率过大。
             //decision.VCode = 1;
             //decision.TCode = (deltaTheta <= 0) ? 1 : 13;
                decision.VCode = 2;
                decision.TCode = (deltaTheta <= 0) ? 0 : 14;
            }
            else
            {
                if (phrase == 1)
                {// 第一阶段(在阈值区域之外)镇定算法
                    times = 0;

                    //decision.VCode = (disSrcPtMmToTmpPtMm < 0.5 * disThreshold) ? 4 : 10;
                    //decision.VCode = 8;
                    decision.VCode = 10;
                    decision.TCode = 7;
                    float lamdadot = ((destPtMm.X - srcPtMm.X) * (fish.VelocityMmPs * (float)Math.Sin(fish.BodyDirectionRad))
                                      - (-destPtMm.Z + srcPtMm.Z) * (fish.VelocityMmPs * (float)Math.Cos(fish.BodyDirectionRad)))
                                     / ((float)Math.Pow(destPtMm.X - srcPtMm.X, 2.0) + (float)Math.Pow(destPtMm.Z - srcPtMm.Z, 2.0));
                    double targetAngularV = 50 * lamdadot;
                    if (deltaTheta <= 0)
                    {     // 目标角度为负目标方向在鱼体方向左边需要给左转档位(注意左转档位对应的角速度值为负值)
                        while ((decision.TCode > 0) && (DataBasedOnExperiment.TCodeAndAngularVelocityTable[decision.TCode] > targetAngularV))
                        { // 目标(转弯)档位对应的角速度值尚未达到目标角速度则调低目标(转弯)档位
                            decision.TCode--;
                        }
                    }
                    else
                    {     // 目标角度为正目标方向在鱼体方向右边需要给右转档位
                        while ((decision.TCode < 14) && (DataBasedOnExperiment.TCodeAndAngularVelocityTable[decision.TCode] < targetAngularV))
                        { // 目标(转弯)档位对应的角速度值尚未达到目标角速度则调高目标(转弯)档位
                            decision.TCode++;
                        }
                    }
                }
                else
                {// 第二阶段(进入阈值区域)镇定算法
                    times++;
                    float       thetae       = destDirRad - fish.BodyDirectionRad;
                    const float K1           = 0.6f;
                    const float K2           = 12.0f;
                    const float K3           = 18.0f;
                    xna.Vector3 srcPtMmLocal = new xna.Vector3(0, 0, 0);
                    UrwpgSimHelper.CoordinateTransformation(destDirRad, destPtMm, ref srcPtMmLocal, srcPtMm);
                    float  u1             = -K1 * srcPtMmLocal.X * (float)Math.Pow(Math.Sin(times * msPerCycle / 1000.0f), 2.0);
                    float  u2             = u1 * K2 * srcPtMmLocal.Z + u1 * K3 * (float)Math.Tan(thetae);
                    double targetVelocity = u1 / Math.Cos(thetae);
                    double targetAngularV = u2 * Math.Pow(Math.Cos(thetae), 2.0);

                    //if (disSrcPtMmToDestPtMm < 150.0f && Math.Abs(deltaTheta) < 10.0f * Math.PI / 180.0f)
                    if (disSrcPtMmToDestPtMm < 140.0f && Math.Abs(deltaTheta) < 10.0f * Math.PI / 180.0f)
                    {
                        decision.VCode = 0;
                        decision.TCode = 7;
                    }
                    else
                    {
                        decision.VCode = 2;
                        while ((decision.VCode < 14) && (DataBasedOnExperiment.VCodeAndVelocityTable[decision.VCode] < targetVelocity))
                        {// 目标(速度)档位对应的速度值尚未达到目标速度则调高目标(速度)档位
                            decision.VCode++;
                        }
                        decision.TCode = 7;
                        if (deltaTheta <= 0)
                        {     // 目标角度为负目标方向在鱼体方向左边需要给左转档位(注意左转档位对应的角速度值为负值)
                            while ((decision.TCode > 0) && (DataBasedOnExperiment.TCodeAndAngularVelocityTable[decision.TCode] > targetAngularV))
                            { // 目标(转弯)档位对应的角速度值尚未达到目标角速度则调低目标(转弯)档位
                                decision.TCode--;
                            }
                        }
                        else
                        {     // 目标角度为正目标方向在鱼体方向右边需要给右转档位
                            while ((decision.TCode < 14) && (DataBasedOnExperiment.TCodeAndAngularVelocityTable[decision.TCode] < targetAngularV))
                            { // 目标(转弯)档位对应的角速度值尚未达到目标角速度则调高目标(转弯)档位
                                decision.TCode++;
                            }
                        }
                    }
                }
            }
        }
Beispiel #37
0
 /// <summary>
 /// Inserts the or update decision.
 /// </summary>
 /// <param name="decision">The decision.</param>
 /// <returns></returns>
 public int InsertOrUpdateDecision(Decision decision)
 {
     return(_repositoryFactory.GetDecisionRepository.InsertOrUpdateDecision(decision));
 }
Beispiel #38
0
 internal void Proceed(Decision decision, Duel duel)
 {
     if (decision != null)
     {
         duel.ClearAwaitingChoice();
     }
     if (decision == null && duel.AwaitingChoice != null)
     {
         return;
     }
     else if (PendingReplacementEffects.Any())
     {
         PendingReplacementEffect = PendingReplacementEffects.Single(x => x.Id == (decision as GuidDecision).Decision.Single());
         PendingReplacementEffects.Clear();
         Proceed(null, duel);
     }
     else if (PendingReplacementEffect != null)
     {
         PendingReplacementEffect.Replace(duel, decision);
         if (duel.AwaitingChoice == null)
         {
             UsedReplacementEffects.Add(PendingReplacementEffect.Id);
             PendingReplacementEffect = null;
         }
         Proceed(null, duel);
     }
     else if (duel.AwaitingEvents.Any())
     {
         CheckAwaitingEvents(duel);
     }
     else if (State == StepState.TurnBasedAction)
     {
         CheckTurnBasedAction(duel, decision);
     }
     else if (State == StepState.CheckGameOver)
     {
         CheckGameOver(duel);
     }
     else if (State == StepState.ResolveSpell)
     {
         ResolveSpells(duel, decision);
     }
     else if (State == StepState.StateBasedAction)
     {
         CheckStateBasedActions(duel);
     }
     else if (State == StepState.ShieldTrigger)
     {
         CheckShieldTriggers(duel, decision);
     }
     else if (State == StepState.SelectAbility)
     {
         SelectAbility(duel, decision);
     }
     else if (State == StepState.ResolveAbility)
     {
         ResolveAbility(duel, decision);
     }
     else if (State == StepState.PriorityAction)
     {
         CheckPriority(duel, decision);
     }
     else if (State != StepState.Over)
     {
         throw new ArgumentOutOfRangeException(State.ToString());
     }
 }
Beispiel #39
0
        private void FindSolution(IEnumerable <Node> nodes, IEnumerable <Link> links, List <SolverWorker> workers)
        {
            SolverContext context = SolverContext.GetContext();
            Model         model   = context.CreateModel();

            var nodeSet   = new Set(0, nodes.Count(), 1);
            var workerSet = new Set(0, workers.Count(), 1);

            //-------------Parameters--------------
            var weights = new Parameter(Domain.IntegerNonnegative, "weights", nodeSet);

            weights.SetBinding(nodes, "Weight", "ID");
            var dependencies = new Parameter(Domain.IntegerRange(0, 1), "dependencies", nodeSet, nodeSet);

            dependencies.SetBinding(links, "isDependent", "Source", "Parent");

            model.AddParameters(weights, dependencies);

            //-------------Decisions--------------
            var startTimes  = new Decision(Domain.IntegerNonnegative, "starts", nodeSet);
            var finishTimes = new Decision(Domain.IntegerNonnegative, "finishes", nodeSet);
            var makespan    = new Decision(Domain.IntegerNonnegative, "makespan");
            var allocation  = new Decision(Domain.IntegerRange(0, 1), "allocation", nodeSet, workerSet);

            model.AddDecisions(startTimes, finishTimes, makespan, allocation);

            //-------------Constraints--------------
            model.AddConstraint("FinishTime", Model.ForEach(nodeSet, (node) => startTimes[node] + weights[node] == finishTimes[node]));

            //model.AddConstraint("OneAtATime", Model.ForEach(nodeSet, (n) =>
            //    Model.ForEachWhere(nodeSet, (n2) => Model.Or(finishTimes[n] < startTimes[n2], startTimes[n] > finishTimes[n2]), (n2) => n != n2)));

            model.AddConstraint("Allocatee", Model.ForEach(nodeSet, (n) => Model.Sum(Model.ForEach(workerSet, (w) => allocation[n, w])) == 1));
            //model.AddConstraint("Allocatee", Model.ForEach(nodeSet, (n) => Model.ExactlyMofN(1,allocation[n])));

            model.AddConstraint("OneAtATime",
                                Model.ForEach(workerSet, (w) =>
                                              Model.ForEach(nodeSet, (n) =>
                                                            Model.ForEachWhere(nodeSet, (n2) => Model.Implies(Model.And(allocation[n, w] == 1, allocation[n2, w] == 1),
                                                                                                              Model.Or(finishTimes[n] <= startTimes[n2], startTimes[n] >= finishTimes[n2])), (n2) => n != n2))));

            model.AddConstraint("PrecedenceConstraints", Model.ForEach(nodeSet, task =>
                                                                       Model.ForEach(nodeSet, parent =>
                                                                                     Model.Implies(dependencies[task, parent] == 1, startTimes[task] >= finishTimes[parent]))));

            //model.AddConstraint("ProjectFinish",  Model.ForEach(nodeSet, (n) => makespan >= finishTimes[n]));

            model.AddConstraint("ProjectFinish", makespan == Model.Max(Model.ForEach(nodeSet, (n) => finishTimes[n])));
            model.AddGoal("MinMakeSpan", GoalKind.Minimize, makespan);

            context.CheckModel();
            //using (StreamWriter sw = new StreamWriter("Stadium.oml")) {
            //    context.SaveModel(FileFormat.OML, sw); ;
            //}
            Solution solution = context.Solve();
            Report   report   = solution.GetReport();

            Console.WriteLine(@"===== report =====");
            Console.Write("{0}", report);
            Console.ReadLine();
            context.ClearModel();
        }
Beispiel #40
0
        public virtual Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase searchCriteria)
        {
            if (searchCriteria != null && searchCriteria.UserInvokedSearch)
            {
                _logger.Debug("Ignoring delay for user invoked search");
                return(Decision.Accept());
            }

            var profile             = subject.Movie.Profile.Value;
            var delayProfile        = _delayProfileService.BestForTags(subject.Movie.Tags);
            var delay               = delayProfile.GetProtocolDelay(subject.Release.DownloadProtocol);
            var isPreferredProtocol = subject.Release.DownloadProtocol == delayProfile.PreferredProtocol;

            // Preferred word count
            var title          = subject.Release.Title;
            var preferredWords = subject.Movie.Profile.Value.PreferredTags;
            var preferredCount = 0;

            if (preferredWords == null)
            {
                preferredCount = 1;
                _logger.Debug("Preferred words is null, setting preffered count to 1.");
            }
            else
            {
                preferredCount = preferredWords.AsEnumerable().Count(w => title.ToLower().Contains(w.ToLower()));
            }

            if (delay == 0)
            {
                _logger.Debug("Profile does not require a waiting period before download for {0}.", subject.Release.DownloadProtocol);
                return(Decision.Accept());
            }

            var comparer = new QualityModelComparer(profile);

            if (isPreferredProtocol && (subject.Movie.MovieFileId != 0 && subject.Movie.MovieFile != null) && (preferredCount > 0 || preferredWords == null))
            {
                var upgradable = _qualityUpgradableSpecification.IsUpgradable(profile, subject.Movie.MovieFile.Value.Quality, subject.ParsedMovieInfo.Quality);

                if (upgradable)
                {
                    var revisionUpgrade = _qualityUpgradableSpecification.IsRevisionUpgrade(subject.Movie.MovieFile.Value.Quality, subject.ParsedMovieInfo.Quality);

                    if (revisionUpgrade)
                    {
                        _logger.Debug("New quality is a better revision for existing quality and preferred word count is {0}, skipping delay", preferredCount);
                        return(Decision.Accept());
                    }
                }
            }

            // If quality meets or exceeds the best allowed quality in the profile accept it immediately
            var bestQualityInProfile = new QualityModel(profile.LastAllowedQuality());
            var isBestInProfile      = comparer.Compare(subject.ParsedMovieInfo.Quality, bestQualityInProfile) >= 0;

            if (isBestInProfile && isPreferredProtocol && (preferredCount > 0 || preferredWords == null))
            {
                _logger.Debug("Quality is highest in profile for preferred protocol and preferred word count is {0}, will not delay.", preferredCount);
                return(Decision.Accept());
            }


            var oldest = _pendingReleaseService.OldestPendingRelease(subject.Movie.Id);

            if (oldest != null && oldest.Release.AgeMinutes > delay)
            {
                return(Decision.Accept());
            }

            if (subject.Release.AgeMinutes < delay)
            {
                _logger.Debug("Waiting for better quality release, There is a {0} minute delay on {1}", delay, subject.Release.DownloadProtocol);
                return(Decision.Reject("Waiting for better quality release"));
            }

            return(Decision.Accept());
        }
Beispiel #41
0
        /// <summary>
        /// dirbble带球算法 Modified By Zhangbo 2011.10.22
        /// </summary>
        /// <param name="decision">每周期机器鱼执行策略,包含速度档位,转弯档位。</param>
        /// <param name="fish">目标仿真机器鱼参数,包含当前位置、速度信息。</param>
        /// <param name="destPtMm">目标点。</param>
        /// <param name="destDirRad">目标方向。</param>
        /// <param name="angleTheta1">鱼体方向与目标方向角度差的阈值一。
        ///   角度差在此阈值范围内,则赋给机器鱼一个合理的速度档位(见参数disThreshold说明)。</param>
        /// <param name="angleTheta2">鱼体方向与目标方向角度差的阈值二。角度差小于此阈值,则机器鱼直线游动;
        /// 角度差大于此阈值,则机器鱼调整游动方向。</param>
        /// <param name="disThreshold">距离阈值。距离大于此阈值,机器鱼以速度档位VCode1游动;
        /// 距离小于此阈值,机器鱼以速度档位VCode2游动。</param>
        /// /// <param name="VCode1">直游档位1(默认6档)。</param>
        /// /// <param name="VCode2">直游档位2(默认4档)。</param>
        /// <param name="cycles">速度和转弯档位之间切换所需周期数经验值。建议取值范围在5-20之间。此参数作用是防止机器鱼“转过”。</param>
        /// <param name="msPerCycle">每个仿真周期的毫秒数,传递固定参数,不能修改。</param>
        /// <param name="flag">机器鱼坐标选择标准,true为PositionMm,即鱼体绘图中心;false为PolygonVertices[0],即鱼头点。</param>
        public static void Dribble(ref Decision decision, RoboFish fish, xna.Vector3 destPtMm, float destDirRad,
                                   float angleTheta1, float angleTheta2, float disThreshold, int VCode1, int VCode2, int cycles, int msPerCycle, bool flag)
        {
            // 调节所用周期数及每周期毫秒数转换得到秒数
            double seconds1 = 15 * msPerCycle / 1000.0;
            double seconds2 = cycles * msPerCycle / 1000.0;

            // 标志量为true则起始点为PositionMm即鱼体绘图中心false则起始点为PolygonVertices[0]即鱼头点(起始点)
            xna.Vector3 srcPtMm = (flag == true) ? fish.PositionMm : fish.PolygonVertices[0];
            // 起始点到目标点的距离(目标距离)
            double disSrcPtMmToDestPtMm = Math.Sqrt(Math.Pow(destPtMm.X - srcPtMm.X, 2.0)
                                                    + Math.Pow(destPtMm.Z - srcPtMm.Z, 2.0));

            // 鱼体绘图中心指向目标点向量方向的弧度值(中间方向)
            double dirFishToDestPtRad = xna.MathHelper.ToRadians((float)GetAngleDegree(destPtMm - fish.PositionMm));

            if (disSrcPtMmToDestPtMm < 30)
            {// 起始点到目标点距离小于阈值(默认58毫米)将中间方向调为目标方向
                dirFishToDestPtRad = destDirRad;
            }

            // 中间方向与鱼体方向的差值(目标角度)
            double deltaTheta = dirFishToDestPtRad - fish.BodyDirectionRad;

            // 将目标角度规范化到(-PI,PI]
            // 规范化之后目标角度为正表示目标方向在鱼体方向右边
            // 规范化之后目标角度为负表示目标方向在鱼体方向左边
            if (deltaTheta > Math.PI)
            {                              // 中间方向为正鱼体方向为负才可能目标角度大于PI
                deltaTheta -= 2 * Math.PI; // 规范化到(-PI,0)
            }
            else if (deltaTheta < -Math.PI)
            {                              // 中间方向为负鱼体方向为正才可能目标角度小于-PI
                deltaTheta += 2 * Math.PI; // 规范化到(0,PI)
            }

            // 最大角速度取左转和右转最大角速度绝对值的均值
            float maxAngularV = (Math.Abs(DataBasedOnExperiment.TCodeAndAngularVelocityTable[0])
                                 + Math.Abs(DataBasedOnExperiment.TCodeAndAngularVelocityTable[14])) / 2;
            // 以最大角速度转过目标角度所需的预计时间(角度预计时间)
            double estimatedTimeByAngle = Math.Abs((double)(deltaTheta / maxAngularV));
            // 以角度预计时间游过目标距离所需平均速度值(目标速度)
            double targetVelocity = disSrcPtMmToDestPtMm / estimatedTimeByAngle;

            int code = 1;   // 目标(速度)档位初值置1

            while ((code < 10) && (DataBasedOnExperiment.VCodeAndVelocityTable[code] < targetVelocity))
            {// 目标(速度)档位对应的速度值尚未达到目标速度则调高目标(速度)档位
                code++;
            }
            decision.VCode = code;
            if (Math.Abs(deltaTheta) > angleTheta2 * Math.PI / 180.0)
            {// 目标角度绝对值超过某一阈值,速度档位置次低进行小半径转弯
                decision.VCode = 1;
            }
            else if (Math.Abs(deltaTheta) < angleTheta1 * Math.PI / 180.0)
            {// 目标角度绝对值小于某一阈值,若此时距离较远速度档置较高高全速前进,否则置适中档位前进。
                if (disSrcPtMmToDestPtMm > disThreshold)
                {
                    decision.VCode = VCode1;
                }
                else
                {
                    decision.VCode = VCode2;
                }
            }

            // 以最大速度游过目标距离所需的预计时间(距离预计时间)
            double estimatedTimeByDistance = disSrcPtMmToDestPtMm / DataBasedOnExperiment.VCodeAndVelocityTable[14];

            if (estimatedTimeByDistance > seconds1)
            {// 距离预计时间超过一次档位切换所需平均时间则取为该时间(默认为1秒)
                estimatedTimeByDistance = seconds1;
            }
            // 以距离预计时间游过目标角度所需平均角速度(目标角速度)
            double targetAngularV = deltaTheta / estimatedTimeByDistance;

            code = 7;
            if (deltaTheta <= 0)
            {     // 目标角度为负目标方向在鱼体方向左边需要给左转档位(注意左转档位对应的角速度值为负值)
                while ((code > 0) && (DataBasedOnExperiment.TCodeAndAngularVelocityTable[code] > targetAngularV))
                { // 目标(转弯)档位对应的角速度值尚未达到目标角速度则调低目标(转弯)档位
                    code--;
                }
                if ((fish.AngularVelocityRadPs * seconds2) < deltaTheta)
                {// 当前角速度值绝对值过大 一次档位切换所需平均时间内能游过的角度超过目标角度
                    // 则给相反方向次大转弯档位
                    code = 12;
                }
            }
            else
            {     // 目标角度为正目标方向在鱼体方向右边需要给右转档位
                while ((code < 14) && (DataBasedOnExperiment.TCodeAndAngularVelocityTable[code] < targetAngularV))
                { // 目标(转弯)档位对应的角速度值尚未达到目标角速度则调高目标(转弯)档位
                    code++;
                }
                if ((fish.AngularVelocityRadPs * seconds2) > deltaTheta)
                {// 当前角速度值绝对值过大 一次档位切换所需平均时间内能游过的角度超过目标角度
                    // 则给相反方向次大转弯档位
                    code = 2;
                }
            }
            decision.TCode = code;
        }
Beispiel #42
0
        //1ターン = 深さ2
        protected override void Solve()
        {
            for (int i = 0; i < 50; ++i)
            {
                dp1[i].Score = int.MinValue;
                dp2[i].Score = int.MinValue;
            }

            int deepness = StartDepth;
            int maxDepth = (TurnCount - CurrentTurn) * 2 + 2;

            PointEvaluator.Base evaluator = (TurnCount / 3 * 2) < CurrentTurn ? PointEvaluator_Normal : PointEvaluator_Distance;
            SearchState         state     = new SearchState(MyBoard, EnemyBoard, MyAgents, EnemyAgents);
            int score = PointEvaluator_Normal.Calculate(ScoreBoard, state.MeBoard, 0, MyAgents, EnemyAgents) - PointEvaluator_Normal.Calculate(ScoreBoard, state.EnemyBoard, 0, EnemyAgents, MyAgents);

            Log("TurnCount = {0}, CurrentTurn = {1}", TurnCount, CurrentTurn);
            if (!(lastTurnDecided is null))
            {
                StringBuilder sb = new StringBuilder("AgentMoved: {");
                for (int i = 0; i < AgentsCount; ++i)
                {
                    sb.Append(IsAgentsMoved[i]);
                    sb.Append(", ");
                }
                string ismoved = sb.ToString();
                Log("{0}}}, lastTurnDecided = {2}", ismoved.Substring(0, ismoved.Length - 2), lastTurnDecided);
            }

            if (!(lastTurnDecided is null) && IsAgentsMoved.GetEnumerable(AgentsCount).All(b => b == false) && score > 0)    //勝っている状態で競合していたら
            {
                SolverResultList.Add(lastTurnDecided);
                return;
            }

            for (; deepness <= maxDepth; deepness++)
            {
                Decided resultList = new Decided();

                int greedyDepth = Math.Min(greedyMaxDepth, maxDepth - deepness);
                if ((deepness + greedyDepth) % 2 == 1 && greedyDepth > 0)
                {
                    greedyDepth--;
                }

                //普通にNegaMaxをして、最善手を探す
                NegaMax(deepness, state, int.MinValue + 1, int.MaxValue, 0, evaluator, null, greedyDepth);
                Decision best1 = new Decision(Unsafe8Array <VelocityPoint> .Create(dp1[0].Ways.GetEnumerable(AgentsCount).Select(x => x.Direction).ToArray()));
                resultList.Add(best1);

                //競合手.Agent == 最善手.Agent の数が半数以上になった場合、競合手をngMoveとして探索をおこない、最善手を探す
                int UnMoveAgentNum = 0;
                for (int i = 0; i < AgentsCount; ++i)
                {
                    if (IsAgentsMoved[i] == false && lastTurnDecided.Agents[i] == best1.Agents[i])
                    {
                        ++UnMoveAgentNum;
                    }
                }
                if (UnMoveAgentNum > AgentsCount / 2)
                {
                    NegaMax(deepness, state, int.MinValue + 1, int.MaxValue, 0, evaluator, best1, greedyDepth);
                    Decision best2 = new Decision(Unsafe8Array <VelocityPoint> .Create(dp2[0].Ways.GetEnumerable(AgentsCount).Select(x => x.Direction).ToArray()));
                    resultList.Add(best2);
                }

                if (CancellationToken.IsCancellationRequested == false)
                {
                    SolverResultList = resultList;
                    if (SolverResultList.Count == 2 && score <= 0)  //現時点で引き分けか負けていたら競合を避けるのを優先してみる(デバッグ用)
                    {
                        var tmp = SolverResultList[0];
                        SolverResultList[0] = SolverResultList[1];
                        SolverResultList[1] = tmp;
                        Log("[SOLVER] Swaped! {0} {1}", SolverResult.Agents[0], SolverResult.Agents[1]);
                    }
                    Log("[SOLVER] SolverResultList.Count = {0}, score = {1}", SolverResultList.Count, score);
                }
                else
                {
                    return;
                }
                Log("[SOLVER] deepness = {0}", deepness);
            }
        }
Beispiel #43
0
        /// <summary>
        /// Pushes a message into the queue.
        /// </summary>
        internal async Task <PushResult> Push(QueueMessage message, MqClient sender)
        {
            if (Status == QueueStatus.Stopped)
            {
                return(PushResult.StatusNotSupported);
            }

            if (Options.MessageLimit > 0 && HighPriorityLinkedList.Count + RegularLinkedList.Count >= Options.MessageLimit)
            {
                return(PushResult.LimitExceeded);
            }

            if (Options.MessageSizeLimit > 0 && message.Message.Length > Options.MessageSizeLimit)
            {
                return(PushResult.LimitExceeded);
            }

            //prepare properties
            message.Message.FirstAcquirer       = true;
            message.Message.AcknowledgeRequired = Options.RequestAcknowledge;

            //if message doesn't have message id and "UseMessageId" option is enabled, create new message id for the message
            if (Options.UseMessageId && string.IsNullOrEmpty(message.Message.MessageId))
            {
                message.Message.SetMessageId(Channel.Server.MessageIdGenerator.Create());
            }

            //if we have an option maximum wait duration for message, set it after message joined to the queue.
            //time keeper will check this value and if message time is up, it will remove message from the queue.
            if (Options.MessageTimeout > TimeSpan.Zero)
            {
                message.Deadline = DateTime.UtcNow.Add(Options.MessageTimeout);
            }

            if (Options.HideClientNames)
            {
                message.Message.SetSource(null);
            }

            try
            {
                //fire message receive event
                Info.AddMessageReceive();
                Decision decision = await DeliveryHandler.ReceivedFromProducer(this, message, sender);

                message.Decision = decision;

                bool allow = await ApplyDecision(decision, message);

                if (!allow)
                {
                    return(PushResult.Success);
                }

                if (State.CanEnqueue(message))
                {
                    await RunInListSync(() => AddMessage(message));

                    if (State.TriggerSupported && !_triggering)
                    {
                        _ = Trigger();
                    }
                }
                else
                {
                    _ = State.Push(message);
                }

                return(PushResult.Success);
            }
            catch (Exception ex)
            {
                Info.AddError();
                try
                {
                    Decision decision = await DeliveryHandler.ExceptionThrown(this, State.ProcessingMessage, ex);

                    if (State.ProcessingMessage != null)
                    {
                        await ApplyDecision(decision, State.ProcessingMessage);

                        if (decision.KeepMessage && !State.ProcessingMessage.IsInQueue)
                        {
                            AddMessage(State.ProcessingMessage, false);
                        }
                    }
                }
                catch //if developer does wrong operation, we should not stop
                {
                }
            }

            return(PushResult.Success);
        }
Beispiel #44
0
        private async Task <PushResult> ProcessMessage(QueueMessage message, MqClient sender)
        {
            //if we need acknowledge from receiver, it has a deadline.
            DateTime?ackDeadline = null;

            if (_queue.Options.RequestAcknowledge)
            {
                ackDeadline = DateTime.UtcNow.Add(_queue.Options.AcknowledgeTimeout);
            }

            //if there are not receivers, complete send operation
            List <ChannelClient> clients = _queue.Channel.ClientsClone;

            if (clients.Count == 0)
            {
                _queue.Info.AddMessageRemove();
                _ = _queue.DeliveryHandler.MessageRemoved(_queue, message);

                return(PushResult.NoConsumers);
            }

            //if to process next message is requires previous message acknowledge, wait here
            if (_queue.Options.RequestAcknowledge && _queue.Options.WaitForAcknowledge)
            {
                await _queue.WaitForAcknowledge(message);
            }

            message.Decision = await _queue.DeliveryHandler.BeginSend(_queue, message);

            if (!await _queue.ApplyDecision(message.Decision, message))
            {
                return(PushResult.Success);
            }

            //create prepared message data
            byte[] messageData = await _writer.Create(message.Message);

            Decision final         = new Decision(false, false, false, DeliveryAcknowledgeDecision.None);
            bool     messageIsSent = false;

            //to all receivers
            foreach (ChannelClient client in clients)
            {
                //to only online receivers
                if (!client.Client.IsConnected)
                {
                    continue;
                }

                //somehow if code comes here (it should not cuz of last "break" in this foreach, break
                if (!message.Message.FirstAcquirer && _queue.Options.SendOnlyFirstAcquirer)
                {
                    break;
                }

                //call before send and check decision
                Decision ccrd = await _queue.DeliveryHandler.CanConsumerReceive(_queue, message, client.Client);

                final = ChannelQueue.CreateFinalDecision(final, ccrd);

                if (!ccrd.Allow)
                {
                    continue;
                }

                //create delivery object
                MessageDelivery delivery = new MessageDelivery(message, client, ackDeadline);
                delivery.FirstAcquirer = message.Message.FirstAcquirer;

                //send the message
                bool sent = client.Client.Send(messageData);

                if (sent)
                {
                    messageIsSent = true;

                    //adds the delivery to time keeper to check timing up
                    _queue.TimeKeeper.AddAcknowledgeCheck(delivery);

                    //set as sent, if message is sent to it's first acquirer,
                    //set message first acquirer false and re-create byte array data of the message
                    bool firstAcquirer = message.Message.FirstAcquirer;

                    //mark message is sent
                    delivery.MarkAsSent();

                    //do after send operations for per message
                    _queue.Info.AddDelivery();
                    Decision d = await _queue.DeliveryHandler.ConsumerReceived(_queue, delivery, client.Client);

                    final = ChannelQueue.CreateFinalDecision(final, d);

                    //if we are sending to only first acquirer, break
                    if (_queue.Options.SendOnlyFirstAcquirer && firstAcquirer)
                    {
                        break;
                    }

                    if (firstAcquirer && clients.Count > 1)
                    {
                        messageData = await _writer.Create(message.Message);
                    }
                }
                else
                {
                    Decision d = await _queue.DeliveryHandler.ConsumerReceiveFailed(_queue, delivery, client.Client);

                    final = ChannelQueue.CreateFinalDecision(final, d);
                }
            }

            message.Decision = final;
            if (!await _queue.ApplyDecision(final, message))
            {
                return(PushResult.Success);
            }

            //after all sending operations completed, calls implementation send completed method and complete the operation
            if (messageIsSent)
            {
                _queue.Info.AddMessageSend();
            }

            message.Decision = await _queue.DeliveryHandler.EndSend(_queue, message);

            await _queue.ApplyDecision(message.Decision, message);

            if (message.Decision.Allow && !message.Decision.KeepMessage)
            {
                _queue.Info.AddMessageRemove();
                _ = _queue.DeliveryHandler.MessageRemoved(_queue, message);
            }

            return(PushResult.Success);
        }
Beispiel #45
0
        public virtual Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
        {
            if (searchCriteria != null)
            {
                _logger.Debug("Skipping history check during search");
                return(Decision.Accept());
            }

            var cdhEnabled = _configService.EnableCompletedDownloadHandling;

            _logger.Debug("Performing history status check on report");
            foreach (var episode in subject.Episodes)
            {
                _logger.Debug("Checking current status of episode [{0}] in history", episode.Id);
                var mostRecent = _historyService.MostRecentForEpisode(episode.Id);

                if (mostRecent != null && mostRecent.EventType == EpisodeHistoryEventType.Grabbed)
                {
                    var recent = mostRecent.Date.After(DateTime.UtcNow.AddHours(-12));

                    if (!recent && cdhEnabled)
                    {
                        continue;
                    }

                    // The series will be the same as the one in history since it's the same episode.
                    // Instead of fetching the series from the DB reuse the known series.
                    var preferredWordScore = _preferredWordServiceCalculator.Calculate(subject.Series, mostRecent.SourceTitle, subject.Release?.IndexerId ?? 0);

                    var cutoffUnmet = _upgradableSpecification.CutoffNotMet(
                        subject.Series.QualityProfile,
                        subject.Series.LanguageProfile,
                        mostRecent.Quality,
                        mostRecent.Language,
                        preferredWordScore,
                        subject.ParsedEpisodeInfo.Quality,
                        subject.PreferredWordScore);

                    var upgradeable = _upgradableSpecification.IsUpgradable(
                        subject.Series.QualityProfile,
                        subject.Series.LanguageProfile,
                        mostRecent.Quality,
                        mostRecent.Language,
                        preferredWordScore,
                        subject.ParsedEpisodeInfo.Quality,
                        subject.ParsedEpisodeInfo.Language,
                        subject.PreferredWordScore);

                    if (!cutoffUnmet)
                    {
                        if (recent)
                        {
                            return(Decision.Reject("Recent grab event in history already meets cutoff: {0}", mostRecent.Quality));
                        }

                        return(Decision.Reject("CDH is disabled and grab event in history already meets cutoff: {0}", mostRecent.Quality));
                    }

                    if (!upgradeable)
                    {
                        if (recent)
                        {
                            return(Decision.Reject("Recent grab event in history is of equal or higher quality: {0}", mostRecent.Quality));
                        }

                        return(Decision.Reject("CDH is disabled and grab event in history is of equal or higher quality: {0}", mostRecent.Quality));
                    }
                }
            }

            return(Decision.Accept());
        }
Beispiel #46
0
            public static Tuple <double, double> GetValue(State s, CorrelatedQTable q)
            {
                var contxt = SolverContext.GetContext();

                contxt.ClearModel();
                var model = contxt.CreateModel();

                var actDecisions = new Dictionary <Tuple <Action, Action>, Decision>();

                foreach (Action currentAction in Enum.GetValues(typeof(Action)))
                {
                    foreach (Action player2Action in Enum.GetValues(typeof(Action)))
                    {
                        var decision = new Decision(Domain.RealNonnegative, currentAction.ToString() + player2Action.ToString());
                        model.AddDecisions(decision);
                        actDecisions.Add(new Tuple <Action, Action>(currentAction, player2Action), decision);
                    }
                }

                var actDecisionSum = new SumTermBuilder(25);

                foreach (var decision in actDecisions.Values)
                {
                    actDecisionSum.Add(decision);
                }

                model.AddConstraint("probSumConst", actDecisionSum.ToTerm() == 1.0);

                rationalconsts(s, q.getCurrPQvalue, actDecisions, model, "A");
                rationalityConstrPlayer2(s, q.getPlayer2Qval, actDecisions, model, "B");

                var objectSum = new SumTermBuilder(10);

                //Add my terms from my Q table to objective function
                ObjFunctermAdd(s, q, actDecisions, objectSum);

                model.AddGoal("MaximizeV", GoalKind.Maximize, objectSum.ToTerm());

                var sol = contxt.Solve(new SimplexDirective());



                if (sol.Quality != SolverQuality.Optimal)
                {
                    contxt.ClearModel();
                    return(new Tuple <double, double>(1.0, 1.0));
                }

                double Player1nextVal = 0.0;
                double Player2nextVal = 0.0;

                foreach (Action currentAction in Enum.GetValues(typeof(Action)))
                {
                    foreach (Action player2Action in Enum.GetValues(typeof(Action)))
                    {
                        var policy = getActDecision(currentAction, player2Action, actDecisions);
                        var qValue = q.getCurrPQvalue(s, currentAction, player2Action);
                        Player1nextVal += policy.ToDouble() * qValue;
                        var player2Qv = q.getPlayer2Qval(s, currentAction, player2Action);
                        Player2nextVal += policy.ToDouble() * player2Qv;
                    }
                }

                return(new Tuple <double, double>(Player1nextVal, Player2nextVal));
            }
        public Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
        {
            var cdhEnabled = _configService.EnableCompletedDownloadHandling;

            if (!cdhEnabled)
            {
                _logger.Debug("Skipping already imported check because CDH is disabled");
                return(Decision.Accept());
            }

            _logger.Debug("Performing already imported check on report");
            foreach (var episode in subject.Episodes)
            {
                if (!episode.HasFile)
                {
                    _logger.Debug("Skipping already imported check for episode without file");
                    continue;
                }

                var historyForEpisode = _historyService.FindByEpisodeId(episode.Id);
                var lastGrabbed       = historyForEpisode.FirstOrDefault(h => h.EventType == EpisodeHistoryEventType.Grabbed);

                if (lastGrabbed == null)
                {
                    continue;
                }

                var imported = historyForEpisode.FirstOrDefault(h =>
                                                                h.EventType == EpisodeHistoryEventType.DownloadFolderImported &&
                                                                h.DownloadId == lastGrabbed.DownloadId);

                if (imported == null)
                {
                    continue;
                }

                // This is really only a guard against redownloading the same release over
                // and over when the grabbed and imported qualities do not match, if they do
                // match skip this check.
                if (lastGrabbed.Quality.Equals(imported.Quality))
                {
                    continue;
                }

                var release = subject.Release;

                if (release.DownloadProtocol == DownloadProtocol.Torrent)
                {
                    var torrentInfo = release as TorrentInfo;

                    if (torrentInfo?.InfoHash != null && torrentInfo.InfoHash.ToUpper() == lastGrabbed.DownloadId)
                    {
                        _logger.Debug("Has same torrent hash as a grabbed and imported release");
                        return(Decision.Reject("Has same torrent hash as a grabbed and imported release"));
                    }
                }

                // Only based on title because a release with the same title on another indexer/released at
                // a different time very likely has the exact same content and we don't need to also try it.

                if (release.Title.Equals(lastGrabbed.SourceTitle, StringComparison.InvariantCultureIgnoreCase))
                {
                    _logger.Debug("Has same release name as a grabbed and imported release");
                    return(Decision.Reject("Has same release name as a grabbed and imported release"));
                }
            }

            return(Decision.Accept());
        }
Beispiel #48
0
        /// <summary>
        /// Evaluates the policy.
        /// </summary>
        /// <param name="context">The evaluation context instance.</param>
        /// <returns>The decission result for this policy.</returns>
        public Decision Evaluate(EvaluationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            context.Trace("Evaluating policy: {0}", _policy.Description);
            context.AddIndent();
            context.CurrentPolicy = this;
            try
            {
                // Evaluate the variables
                if (this._policy.SchemaVersion == XacmlVersion.Version20)
                {
                    if (_variables == null)
                    {
                        context.Trace("Evaluating variables...");
                        _variables = new Hashtable();

                        foreach (pol.VariableDefinitionElement variableDef in _policy.VariableDefinitions.Values)
                        {
                            VariableDefinition variable = new VariableDefinition(variableDef);
                            _variables.Add(variableDef.Id, variable);
                        }
                    }
                }

                // Matches the target.
                TargetEvaluationValue targetEvaluationValue = Match(context);

                // If the target matches.
                if (targetEvaluationValue == TargetEvaluationValue.Match)
                {
                    context.Trace("Rule combination algorithm: {0}", _policy.RuleCombiningAlgorithm);

                    // Evaluate all rules and apply rule combination
                    inf.IRuleCombiningAlgorithm rca = EvaluationEngine.CreateRuleCombiningAlgorithm(_policy.RuleCombiningAlgorithm);
                    _evaluationValue = rca.Evaluate(context, _rules);
                }
                else if (targetEvaluationValue == TargetEvaluationValue.NoMatch)
                {
                    _evaluationValue = Decision.NotApplicable;
                }
                else if (targetEvaluationValue == TargetEvaluationValue.Indeterminate)
                {
                    _evaluationValue = Decision.Indeterminate;
                }

                context.Trace("Policy: {0}", _evaluationValue);

                // Copy all the obligations.
                _obligations = new pol.ObligationCollection();
                if (_evaluationValue != Decision.Indeterminate &&
                    _evaluationValue != Decision.NotApplicable &&
                    _policy.Obligations != null && _policy.Obligations.Count != 0)
                {
                    foreach (pol.ObligationElement obl in _policy.Obligations)
                    {
                        if ((obl.FulfillOn == pol.Effect.Deny && _evaluationValue == Decision.Deny) ||
                            (obl.FulfillOn == pol.Effect.Permit && _evaluationValue == Decision.Permit))
                        {
                            context.Trace("Adding obligation: {0} ", obl.ObligationId);
                            _obligations.Add(obl);
                        }
                    }
                }

                return(_evaluationValue);
            }
            finally
            {
                context.RemoveIndent();
                context.CurrentPolicy = null;
            }
        }
Beispiel #49
0
        public Add_Increase()
        {
            InitializeComponent();

            db = new PersonelDBContext();



            if (Login.currentUser.Rule == "تدريسي")
            {
                emp = (from p in db.SelfCards
                       where (p.Status != "بحكم المستقيل" && p.Status != "كف اليد" && p.Status != "مصروف من الخدمة" && p.FileClass == "تدريسي")
                       select p.FirstName + " " + p.FatherName + " " + p.LastName).ToList <string>();


                list.ItemsSource = emp;
            }
            else if (Login.currentUser.Rule == "فني")
            {
                emp = (from p in db.SelfCards
                       where (p.Status != "بحكم المستقيل" && p.Status != "كف اليد" && p.Status != "مصروف من الخدمة" && p.FileClass == "فني")
                       select p.FirstName + " " + p.FatherName + " " + p.LastName).ToList <string>();


                list.ItemsSource = emp;
            }
            else if (Login.currentUser.Rule == "معيد")
            {
                emp = (from p in db.SelfCards
                       where (p.Status != "بحكم المستقيل" && p.Status != "كف اليد" && p.Status != "مصروف من الخدمة" && p.FileClass == "معيد")
                       select p.FirstName + " " + p.FatherName + " " + p.LastName).ToList <string>();


                list.ItemsSource = emp;
            }

            else if (Login.currentUser.Rule == "الأولى")
            {
                emp = (from p in db.SelfCards
                       where (p.Status != "بحكم المستقيل" && p.Status != "كف اليد" && p.Status != "مصروف من الخدمة" && p.Category == "الأولى")
                       select p.FirstName + " " + p.FatherName + " " + p.LastName).ToList <string>();


                list.ItemsSource = emp;
            }
            else if (Login.currentUser.Rule == "الثانية")
            {
                emp = (from p in db.SelfCards
                       where (p.Status != "بحكم المستقيل" && p.Status != "كف اليد" && p.Status != "مصروف من الخدمة" && (p.Category == "الثانية/مخبريين" || p.Category == "الثانية/اداريين"))
                       select p.FirstName + " " + p.FatherName + " " + p.LastName).ToList <string>();


                list.ItemsSource = emp;
            }
            else if (Login.currentUser.Rule == "الثالثة")
            {
                emp = (from p in db.SelfCards
                       where (p.Status != "بحكم المستقيل" && p.Status != "كف اليد" && p.Status != "مصروف من الخدمة" && (p.Category == "الثالثة" || p.Category == "الرابعة"))
                       select p.FirstName + " " + p.FatherName + " " + p.LastName).ToList <string>();


                list.ItemsSource = emp;
            }
            else if (Login.currentUser.Rule == "الخامسة")
            {
                emp = (from p in db.SelfCards
                       where (p.Status != "بحكم المستقيل" && p.Status != "كف اليد" && p.Status != "مصروف من الخدمة" && p.Category == "الخامسة")
                       select p.FirstName + " " + p.FatherName + " " + p.LastName).ToList <string>();


                list.ItemsSource = emp;
            }
            else if (Login.currentUser.Rule == "عقود")
            {
                emp = (from p in db.SelfCards
                       where (p.Status != "بحكم المستقيل" && p.Status != "كف اليد" && p.Status != "مصروف من الخدمة" && p.FileClass == "عقد")
                       select p.FirstName + " " + p.FatherName + " " + p.LastName).ToList <string>();


                list.ItemsSource = emp;
            }
            else if (Login.currentUser.Rule == "admin")
            {
                emp = (from p in db.SelfCards
                       where (p.Status != "بحكم المستقيل" && p.Status != "كف اليد" && p.Status != "مصروف من الخدمة")
                       select p.FirstName + " " + p.FatherName + " " + p.LastName).ToList <string>();


                list.ItemsSource = emp;
            }
            /////////////////////////////////////////////////////


            Decision d = (Decision)DataContext;
        }
 public abstract void PerformTurnBasedAction(Duel duel, Decision decision);
        public static Tuple<ICollection<SubCalendarEvent>, double> Run(ICollection<SubCalendarEvent> ListOfElements, int BeginningAndEnd=0)
        {
#if EnableHive            
            if (ListOfElements.Count < 3)
            {
                return new Tuple<ICollection<SubCalendarEvent>, double>(ListOfElements, 0);
            }
            
            CitiesData citiesData = new CitiesData(ListOfElements.ToList());
            int totalNumberBees = 100;
            int numberInactive = 20;
            int numberActive = 50;
            int numberScout = 30;

            int maxNumberVisits = 50;
            int maxNumberCycles = 20;

            Hive hive = new Hive(totalNumberBees, numberInactive, numberActive, numberScout, maxNumberVisits, maxNumberCycles, citiesData, BeginningAndEnd);


            bool doProgressBar = false;
            hive.Solve(doProgressBar);
            return hive.getBestPath();
#endif
            



#if LinearTSP
            Coordinate[] data = new Coordinate[ListOfElements.Count];
            Dictionary<int, SubCalendarEvent> DictOFData = new Dictionary<int,SubCalendarEvent>();
            int NameIndex = 0;
            foreach (SubCalendarEvent eachSubCalendarEvent in ListOfElements)
            {
                data[NameIndex] = new Coordinate(NameIndex, eachSubCalendarEvent);
                DictOFData.Add(NameIndex++, eachSubCalendarEvent);
            }

            SolverContext context = SolverContext.GetContext();
            Model model = context.CreateModel();

            // ------------
            // Parameters
            Set city = new Set(Domain.IntegerNonnegative, "city");
            Parameter dist = new Parameter(Domain.Real, "dist", city, city);
            var arcs = from p1 in data
                       from p2 in data
                       select new Arc { City1 = p1.Name, City2 = p2.Name, Distance = p1.Distance(p2, data.Length) };
            dist.SetBinding(arcs, "Distance", "City1", "City2");
            model.AddParameters(dist);

            // ------------
            // Decisions
            Decision assign = new Decision(Domain.IntegerRange(0, 1), "assign", city, city);
            Decision rank = new Decision(Domain.RealNonnegative, "rank", city);
            model.AddDecisions(assign, rank);

            // ------------
            // Goal: minimize the length of the tour.
            Goal goal = model.AddGoal("TourLength", GoalKind.Minimize,
              Model.Sum(Model.ForEach(city, i => Model.ForEachWhere(city, j => dist[i, j] * assign[i, j], j => i != j))));

            // ------------
            // Enter and leave each city only once.
            int N = data.Length;
            model.AddConstraint("assign_1",
              Model.ForEach(city, i => Model.Sum(Model.ForEachWhere(city, j => assign[i, j],
                j => i != j)) == 1));
            model.AddConstraint("assign_2",
              Model.ForEach(city, j => Model.Sum(Model.ForEachWhere(city, i => assign[i, j], i => i != j)) == 1));

            // Forbid subtours (Miller, Tucker, Zemlin - 1960...)
            model.AddConstraint("no_subtours",
              Model.ForEach(city,
                i => Model.ForEachWhere(city,
                  j => rank[i] + 1 <= rank[j] + N * (1 - assign[i, j]),
                  j => Model.And(i != j, i >= 1, j >= 1)
                )
              )
            );

            Solution solution = context.Solve();
            double Cost = goal.ToDouble();
            List<SubCalendarEvent> OptimizedSubCalEvents = new List<SubCalendarEvent>();

            var tour = from p in assign.GetValues() where (double)p[0] > 0.9 select p;

            foreach (var i in tour.ToArray())
            {
                int MyIndex =Convert.ToInt32(i[2]);
                OptimizedSubCalEvents.Add(DictOFData[MyIndex]);
                //Console.WriteLine(i[1] + " -> " + );
            }

            context.ClearModel();

            return new Tuple<ICollection<SubCalendarEvent>, double>(OptimizedSubCalEvents, Cost);
#endif


        }
Beispiel #52
0
        private void Raschot_Click(object sender, EventArgs e)
        {
            if (
                #region ---
                (_predel_B1.Text == "") ||
                (_predel_B2.Text == "") ||
                (_predel_B3.Text == "") ||
                (kol_A1_B1.Text == "") ||
                (kol_A1_B2.Text == "") ||
                (kol_A1_B3.Text == "") ||
                (kol_A2_B1.Text == "") ||
                (kol_A2_B2.Text == "") ||
                (kol_A2_B3.Text == "") ||
                (kol_A3_B1.Text == "") ||
                (kol_A3_B2.Text == "") ||
                (kol_A3_B3.Text == "") ||
                (sto_A1.Text == "") ||
                (sto_A2.Text == "") ||
                (sto_A3.Text == ""))
            #endregion ---
            {
                Grafick.Parent = null;
                MessageBox.Show("Не все поля заполнены!", "Ошибка");
                return;
            }
            else
            {
                Grafick.Parent = tabControl1;

                chart1.Series[0].Points.Clear();
                chart1.Series[1].Points.Clear();
                chart1.Series[2].Points.Clear();

                H._predel_B1 = Double.Parse(_predel_B1.Text);
                H._predel_B2 = Double.Parse(_predel_B2.Text);
                H._predel_B3 = Double.Parse(_predel_B3.Text);
                H.kol_A1_B1  = Double.Parse(kol_A1_B1.Text);
                H.kol_A1_B2  = Double.Parse(kol_A1_B2.Text);
                H.kol_A1_B3  = Double.Parse(kol_A1_B3.Text);
                H.kol_A2_B1  = Double.Parse(kol_A2_B1.Text);
                H.kol_A2_B2  = Double.Parse(kol_A2_B2.Text);
                H.kol_A2_B3  = Double.Parse(kol_A2_B3.Text);
                H.kol_A3_B1  = Double.Parse(kol_A3_B1.Text);
                H.kol_A3_B2  = Double.Parse(kol_A3_B2.Text);
                H.kol_A3_B3  = Double.Parse(kol_A3_B3.Text);
                H.sto_A1     = Double.Parse(sto_A1.Text);
                H.sto_A2     = Double.Parse(sto_A2.Text);
                H.sto_A3     = Double.Parse(sto_A3.Text);

                List <SolverRow> solverList = new List <SolverRow>();
                solverList.Add(new SolverRow {
                    xId = 1, Koef = H.X1
                });
                solverList.Add(new SolverRow {
                    xId = 2, Koef = H.X2
                });
                solverList.Add(new SolverRow {
                    xId = 3, Koef = H.X3
                });

                SolverContext context = SolverContext.GetContext();
                Model         model   = context.CreateModel();
                Set           users   = new Set(Domain.Any, "users");

                Parameter Koef = new Parameter(Domain.Real, "Koef", users);
                Koef.SetBinding(solverList, "Koef", "xId");
                model.AddParameter(Koef);

                Decision choose = new Decision(Domain.RealNonnegative, "choose", users);
                model.AddDecisions(choose);
                model.AddGoal("goal", GoalKind.Minimize, Model.Sum(Model.ForEach(users, xId => choose[xId] * Koef[xId])));

                model.AddConstraint("OgranT1", Model.Sum(Model.ForEach(users, xId => H.kol_A1_B1 * H.X1 + H.kol_A2_B1 * H.X2 + H.kol_A3_B1 * H.X3)) <= H._predel_B1);
                model.AddConstraint("OgranT2", Model.Sum(Model.ForEach(users, xId => H.kol_A1_B2 * H.X1 + H.kol_A2_B2 * H.X2 + H.kol_A3_B2 * H.X3)) <= H._predel_B2);
                model.AddConstraint("OgranT3", Model.Sum(Model.ForEach(users, xId => H.kol_A1_B3 * H.X1 + H.kol_A2_B3 * H.X2 + H.kol_A3_B3 * H.X3)) <= H._predel_B3);

                try
                {
                    Solution solution = context.Solve();
                    Report   report   = solution.GetReport();

                    String reportStr = "";

                    for (int i = 0; i < solverList.Count; i++)
                    {
                        reportStr += "Значение X" + (i + 1).ToString() + ": " + choose.GetDouble(solverList[i].xId) + "\n";
                    }
                    reportStr += "\n" + report.ToString();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("При решении задачи оптимизации возникла исключительная ситуация.");
                }

                double X1 = Math.Round(choose.GetDouble(solverList[0].xId), 3);
                double X2 = Math.Round(choose.GetDouble(solverList[1].xId), 3);
                double X3 = Math.Round(choose.GetDouble(solverList[2].xId), 3);

                this.chart1.Series[0].Points.AddXY("", H.X1);
                this.chart1.Series[1].Points.AddXY("", H.X2);
                this.chart1.Series[2].Points.AddXY("", H.X3);

                dataGridView1.Rows.Add(H.X1, H.X2, H.X3);
            }
        }
 partial void ListAjaxOverride(T4MVC_System_Web_Mvc_ActionResult callInfo, Decision.ViewModel.Role.RoleSearchRequest request);
Beispiel #54
0
        public Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
        {
            var queue           = _queueService.GetQueue();
            var matchingEpisode = queue.Where(q => q.RemoteEpisode?.Series != null &&
                                              q.RemoteEpisode.Series.Id == subject.Series.Id &&
                                              q.RemoteEpisode.Episodes.Select(e => e.Id).Intersect(subject.Episodes.Select(e => e.Id)).Any())
                                  .ToList();

            foreach (var queueItem in matchingEpisode)
            {
                var remoteEpisode   = queueItem.RemoteEpisode;
                var qualityProfile  = subject.Series.QualityProfile.Value;
                var languageProfile = subject.Series.LanguageProfile.Value;

                // To avoid a race make sure it's not FailedPending (failed awaiting removal/search).
                // Failed items (already searching for a replacement) won't be part of the queue since
                // it's a copy, of the tracked download, not a reference.

                if (queueItem.TrackedDownloadState == TrackedDownloadState.FailedPending)
                {
                    continue;
                }

                _logger.Debug("Checking if existing release in queue meets cutoff. Queued: {0} - {1}", remoteEpisode.ParsedEpisodeInfo.Quality, remoteEpisode.ParsedEpisodeInfo.Language);
                var queuedItemPreferredWordScore = _preferredWordServiceCalculator.Calculate(subject.Series, queueItem.Title);

                if (!_upgradableSpecification.CutoffNotMet(qualityProfile,
                                                           languageProfile,
                                                           remoteEpisode.ParsedEpisodeInfo.Quality,
                                                           remoteEpisode.ParsedEpisodeInfo.Language,
                                                           queuedItemPreferredWordScore,
                                                           subject.ParsedEpisodeInfo.Quality,
                                                           subject.PreferredWordScore))
                {
                    return(Decision.Reject("Release in queue already meets cutoff: {0} - {1}", remoteEpisode.ParsedEpisodeInfo.Quality, remoteEpisode.ParsedEpisodeInfo.Language));
                }

                _logger.Debug("Checking if release is higher quality than queued release. Queued: {0} - {1}", remoteEpisode.ParsedEpisodeInfo.Quality, remoteEpisode.ParsedEpisodeInfo.Language);

                if (!_upgradableSpecification.IsUpgradable(qualityProfile,
                                                           languageProfile,
                                                           remoteEpisode.ParsedEpisodeInfo.Quality,
                                                           remoteEpisode.ParsedEpisodeInfo.Language,
                                                           queuedItemPreferredWordScore,
                                                           subject.ParsedEpisodeInfo.Quality,
                                                           subject.ParsedEpisodeInfo.Language,
                                                           subject.PreferredWordScore))
                {
                    return(Decision.Reject("Release in queue is of equal or higher preference: {0} - {1}", remoteEpisode.ParsedEpisodeInfo.Quality, remoteEpisode.ParsedEpisodeInfo.Language));
                }

                _logger.Debug("Checking if profiles allow upgrading. Queued: {0} - {1}", remoteEpisode.ParsedEpisodeInfo.Quality, remoteEpisode.ParsedEpisodeInfo.Language);

                if (!_upgradableSpecification.IsUpgradeAllowed(subject.Series.QualityProfile,
                                                               subject.Series.LanguageProfile,
                                                               remoteEpisode.ParsedEpisodeInfo.Quality,
                                                               remoteEpisode.ParsedEpisodeInfo.Language,
                                                               subject.ParsedEpisodeInfo.Quality,
                                                               subject.ParsedEpisodeInfo.Language))
                {
                    return(Decision.Reject("Another release is queued and the Quality or Language profile does not allow upgrades"));
                }
            }

            return(Decision.Accept());
        }
 partial void CreateOverride(T4MVC_System_Web_Mvc_ActionResult callInfo, Decision.ViewModel.Role.AddRoleViewModel viewModel);
Beispiel #56
0
 protected override void EndSolve(object sender, EventArgs e)
 {
     base.EndSolve(sender, e);
     lastTurnDecided = SolverResultList[0];  //0番目の手を指したとする。(次善手を人間が選んで競合した~ということがなければOK)
 }
 public override System.Threading.Tasks.Task<System.Web.Mvc.ActionResult> Edit(Decision.ViewModel.Role.EditRoleViewModel viewModel)
 {
     var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Edit);
     ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "viewModel", viewModel);
     EditOverride(callInfo, viewModel);
     return System.Threading.Tasks.Task.FromResult(callInfo as ActionResult);
 }
Beispiel #58
0
        //Meが動くとする。「Meのスコア - Enemyのスコア」の最大値を返す。
        private int NegaMax(int deepness, SearchState state, int alpha, int beta, int count, PointEvaluator.Base evaluator, Decision ngMove, int greedyDepth)
        {
            if (deepness == 0)
            {
                for (int j = 0; j < greedyDepth; j++)
                {
                    Way move = state.MakeGreedyMove(ScoreBoard, WayEnumerator);
                    state.Move(move.Agent1Way, move.Agent2Way);
                    //Ways moves = state.MakeMoves(WayEnumerator);
                    //SortMoves(ScoreBoard, state, moves, 49, null);
                    //state.Move(moves[0].Agent1Way, moves[1].Agent2Way);
                }
                int score = evaluator.Calculate(ScoreBoard, state.MeBoard, 0, state.Me, state.Enemy) - evaluator.Calculate(ScoreBoard, state.EnemyBoard, 0, state.Enemy, state.Me);
                if (greedyDepth % 2 == 1)
                {
                    return(-score);
                }
                return(score);
            }

            Ways ways = state.MakeMoves(WayEnumerator);

            SortMoves(ScoreBoard, state, ways, count, ngMove);

            for (int i = 0; i < ways.Count; i++)
            {
                if (CancellationToken.IsCancellationRequested == true)
                {
                    return(alpha);
                }                                                                           //何を返しても良いのでとにかく返す
                //if (count == 0 && !(ngMove is null) && new Decided(ways[i].Agent1Way, ways[i].Agent2Way).Equals(ngMove)) { continue; }	//競合手を避ける場合
                if (count == 0 && !(ngMove is null) && (ways[i].Agent1Way.Equals(ngMove.Agents[0]) || ways[i].Agent2Way.Equals(ngMove.Agents[1])))
                {
                    continue;
                }                                                                                                                                                   //2人とも競合手とは違う手を指す

                SearchState nextState = state;
                nextState.Move(ways[i].Agent1Way, ways[i].Agent2Way);
                int res = -NegaMax(deepness - 1, nextState, -beta, -alpha, count + 1, evaluator, ngMove, greedyDepth);
                if (alpha < res)
                {
                    alpha = res;
                    if (ngMove is null)
                    {
                        dp1[count].UpdateScore(alpha, ways[i].Agent1Way, ways[i].Agent2Way);
                    }
                    else
                    {
                        dp2[count].UpdateScore(alpha, ways[i].Agent1Way, ways[i].Agent2Way);
                    }
                    if (alpha >= beta)
                    {
                        return(beta);               //βcut
                    }
                }
            }
            ways.Erase();
            WaysPool.Return(ways);
            return(alpha);
        }
    private void walk(Decision stateOne, Decision stateTwo)
    {
        Decision decision = Decision.none;

        if(currentHorizontal < 0 && currentHorizontal <= -MaxHorizontal){
            decision = Decision.right;
        }

        if(currentVertical < 0 && currentVertical <= -MaxVertical){
            decision = Decision.up;
        }

        if(currentHorizontal > 0 && currentHorizontal >= MaxHorizontal){
            decision = Decision.left;
        }

        if(currentVertical > 0 && currentVertical >= MaxVertical){
            decision = Decision.down;
        }

        if(decision == Decision.none){
            if((Random.Range(1,100) % 2) == 0){
             	decision = stateTwo;
            }else{
             	decision = stateOne;
            }
        }

        sendDecision(decision);
    }
Beispiel #60
0
        //遷移順を決める.  「この関数においては」MeBoard…手番プレイヤのボード, Me…手番プレイヤ、とします。
        //引数: stateは手番プレイヤが手を打つ前の探索状態、(way1[i], way2[i])はi番目の合法手(移動量)です。
        //以下のルールで優先順を決めます.
        //ルール1. Killer手(優先したい手)があれば、それを優先する
        //ルール2. 次のmoveで得られる「タイルポイント」の合計値が大きい移動(の組み合わせ)を優先する。
        //ルール2では, タイル除去によっても「タイルポイント」が得られるとして計算する。
        private void SortMoves(sbyte[,] ScoreBoard, SearchState state, Ways way, int deep, Decision ngMove)
        {
            Unsafe8Array <Point> Killer;

            DP[] dp = ngMove is null ? dp1 : dp2;
            if (dp[deep].Score == int.MinValue)
            {
                Killer = Unsafe8Array <Point> .Create(new Point(114, 191), new Point(114, 191), new Point(114, 191), new Point(114, 191), new Point(114, 191), new Point(114, 191), new Point(114, 191), new Point(114, 191));
            }
            else
            {
                Killer = new Unsafe8Array <Point>();
                for (int i = 0; i < AgentsCount; ++i)
                {
                    Killer[i] = state.Me[i] + dp[deep].AgentsWay[i];
                }
            }

            for (int i = 0; i < way.Count; i++)
            {
                int score = 0;
                Unsafe8Array <Point> nexts = new Unsafe8Array <Point>();
                for (int n = 0; n < AgentsCount; ++i)
                {
                    nexts[n] = state.Me[n] + way[i].AgentWays[n];
                }

                if (Killer.Agent1 == next1 && Killer.Agent2 == next2)
                {
                    score = 100;
                }

                if (state.EnemyBoard[next1])
                {
                    score += ScoreBoard[next1.X, next1.Y];
                }                                                                           //タイル除去によって有利になる
                else if (!state.MeBoard[next1])
                {
                    score += ScoreBoard[next1.X, next1.Y];
                }                                                                           //移動でMeの陣地が増えて有利になる
                if (state.EnemyBoard[next2])
                {
                    score += ScoreBoard[next2.X, next2.Y];
                }
                else if (!state.MeBoard[next2])
                {
                    score += ScoreBoard[next2.X, next2.Y];
                }
                way[i].Point = score;
            }
            way.Sort();
        }