public void OnTriggerDefinitionUpdated(long jobId, long triggerId) { Logger.Info($"The trigger with id '{triggerId}' has been updated. Reflecting changes to Plan if any."); var trigger = this.repository.GetTriggerById(jobId, triggerId); PlanResult planResult = this.GetPlanResult(trigger as dynamic, false); if (planResult.Action != PlanAction.Possible) { Logger.Debug($"The trigger was not considered to be relevant to the plan, skipping. PlanResult was '{planResult.Action}'"); return; } var dateTime = planResult.ExpectedStartDateUtc; if (!dateTime.HasValue) { Logger.Warn($"Unable to gather an expected start date for trigger, skipping."); return; } // Get the next occurence from database var dependentJobRun = this.repository.GetNextJobRunByTriggerId(jobId, trigger.Id, this.dateTimeProvider.GetUtcNow()); if (dependentJobRun == null) { Logger.Error($"Trigger was updated before job run has been created. Cannot apply update."); return; } this.UpdatePlannedJobRun(dependentJobRun, trigger, dateTime.Value); }
public void TestGetGoalsTiming() { string main_path = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName + @"\PlanningProblems\BoxPushing\B3\"; string filePathProblem = main_path + "p.pddl"; string filePathDomain = main_path + "d.pddl"; Domain d = Parser.ParseDomain(filePathDomain, "agent"); Problem p = Parser.ParseProblem(filePathProblem, d); IterativeMAPlanner ma_planner = new IterativeMAPlanner(d, p, SDRPlanner.Planners.FF); var ma_result = ma_planner.Plan(); Assert.IsNotNull(ma_result); Constant a1 = d.GetAgents()[0]; PlanResult pr = ma_result[a1]; List <Predicate> goals = p.GetGoals(); Dictionary <Predicate, int> timing = new Dictionary <Predicate, int>(); pr.Plan.GetGoalsTiming(goals, null, ref timing); string plan = PlanTreePrinter.Print(pr.Plan); File.WriteAllText(main_path + "plan_" + a1.Name + ".txt", plan); Assert.AreEqual(timing.Count, p.GetGoals().Count - 1); }
public void OnTriggerAdded(long jobId, long triggerId) { Logger.Info($"The trigger with id '{triggerId}' has been added. Reflecting changes to the current plan."); var trigger = this.repository.GetTriggerById(jobId, triggerId); PlanResult planResult = this.GetPlanResult(trigger as dynamic, true); if (planResult.Action != PlanAction.Possible) { Logger.Debug($"The trigger was not considered to be relevant to the plan, skipping. PlanResult was '{planResult.Action}'"); return; } var newItem = this.CreateNew(planResult, trigger); if (newItem == null) { Logger.Error($"Unable to create a new Planned Item with a JobRun."); return; } this.currentPlan.Add(newItem); this.PublishCurrentPlan(); }
private void EvaluateRecurringTriggers() { // Re-evaluate recurring triggers every n seconds var activeTriggers = this.repository.GetActiveTriggers().Where(t => t.GetType() == typeof(RecurringTrigger)); var additonalItems = new List <ScheduledPlanItem>(); foreach (RecurringTrigger trigger in activeTriggers.Cast <RecurringTrigger>()) { PlanResult planResult = this.GetPlanResult(trigger, false); if (planResult.Action == PlanAction.Possible) { // Check if there is already a run planned at this time var nextRunForTrigger = this.repository.GetNextJobRunByTriggerId(trigger.JobId, trigger.Id, this.dateTimeProvider.GetUtcNow()); if (nextRunForTrigger == null || !nextRunForTrigger.PlannedStartDateTimeUtc.Equals(planResult.ExpectedStartDateUtc)) { var scheduledItem = this.CreateNew(planResult, trigger); additonalItems.Add(scheduledItem); } } } if (additonalItems.Any()) { Logger.Info($"The re-evaluation of recuring triggers caused the addition of {additonalItems.Count} scheduled items"); this.currentPlan.AddRange(additonalItems); this.PublishCurrentPlan(); } }
public Task <PlanResult> PushPlan(StripePlan plan, bool commit = true) { var retVal = new PlanResult() { }; Plan stripePlan = null; if (!string.IsNullOrWhiteSpace(plan.StripeId)) { stripePlan = _planService.Get(plan.StripeId); } if (stripePlan != null) { stripePlan = _planService.Update(stripePlan.Id, new PlanUpdateOptions { Active = plan.IsActive, Nickname = plan.Name, TrialPeriodDays = plan.TrialPeriodDays, Metadata = new Dictionary <string, string>() { { "ref_id", plan.Id.ToString() } } }); } else { stripePlan = _planService.Create(new PlanCreateOptions() { Active = plan.IsActive, Amount = Convert.ToInt64(plan.Amount * 100), Currency = "usd", Nickname = plan.Name, Interval = plan.Interval, Product = plan.ProductId, TrialPeriodDays = plan.TrialPeriodDays, Metadata = new Dictionary <string, string>() { { "ref_id", plan.Id.ToString() } } }); } plan.StripeId = stripePlan.Id; plan.StripeBlob = JsonConvert.SerializeObject(stripePlan); plan.ObjectState = ObjectState.Modified; var records = Repository.InsertOrUpdateGraph(plan, commit); _logger.LogDebug(GetLogMessage("{0} records updated"), records); if (records > 0) { retVal.Succeeded = true; retVal.PlanId = plan.StripeId; } return(Task.FromResult(retVal)); }
public void IterativeMAPlanner_TestIndepeneceBetweenRuns() { string filePathProblem = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName + @"\PlanningProblems\BoxPushing\B2\p.pddl"; string filePathDomain = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName + @"\PlanningProblems\BoxPushing\B2\d.pddl"; Domain d = Parser.ParseDomain(filePathDomain, "agent"); Problem p = Parser.ParseProblem(filePathProblem, d); SingleAgentSDRPlanner saSDR = new SingleAgentSDRPlanner(d, p, SDRPlanner.Planners.FF); // Get the first agent Constant agent1 = d.GetAgents()[0]; PlanResult pr1 = saSDR.Plan(agent1, null, null, null); string domainAfter_1 = d.ToString(); PlanResult pr2 = saSDR.Plan(agent1, null, null, null); string domainAfter_2 = d.ToString(); // General domain shoud remain the same after planning once Assert.AreEqual(d.ToString(), domainAfter_1); // General domain shoud remain the same after planning twice Assert.AreEqual(d.ToString(), domainAfter_2); // Both used domains (after one & two running) should remain the same Assert.AreEqual(pr1.m_agentDomain.ToString(), pr2.m_agentDomain.ToString()); Assert.AreNotEqual(pr1.m_agentDomain.ToString(), d.ToString()); Assert.AreNotEqual(pr2.m_agentDomain.ToString(), d.ToString()); }
private void btnRunSingleAgentPlan_Click(object sender, EventArgs e) { // Active agent Constant activeAgent = (Constant)cbActiveAgents.SelectedItem; // Active goals List <Predicate> activeGoals = new List <Predicate>(); for (int i = 0; i < clbActiveGoals.Items.Count; i++) { if (clbActiveGoals.GetItemChecked(i)) { activeGoals.Add((Predicate)clbActiveGoals.Items[i]); } } // Required Actions to be preformed List <Action> reqCollabActions = new List <Action>(); for (int i = 0; i < clbActiveJointActions.Items.Count; i++) { if (clbActiveJointActions.GetItemChecked(i)) { reqCollabActions.Add((Action)clbActiveJointActions.Items[i]); } } // Active Prev achieved goals List <KeyValuePair <Predicate, int> > prevAchievedGoals = new List <KeyValuePair <Predicate, int> >(); for (int i = 0; i < clbPrevGoalTime.Items.Count; i++) { if (clbPrevGoalTime.GetItemChecked(i)) { prevAchievedGoals.Add((KeyValuePair <Predicate, int>)clbPrevGoalTime.Items[i]); } } Domain reducedDomain = Parser.ParseDomain(m_DomainPath, m_AgentCallsign); Problem reducedProblem = Parser.ParseProblem(m_ProblemPath, reducedDomain); string sPath = Directory.GetParent(reducedDomain.Path).FullName + "\\"; SingleAgentSDRPlanner m_saSDRPlanner = new SingleAgentSDRPlanner(reducedDomain, reducedProblem, (SDRPlanner.Planners)cbPlanner.SelectedItem); PlanResult planResult = m_saSDRPlanner.Plan(activeAgent, activeGoals, prevAchievedGoals, reqCollabActions); ConditionalPlanTreeNode root = planResult.Plan; PlanDetails pd = root.ScanDetails(reducedDomain, reducedProblem); pd.PlanningTime = planResult.PlanningTime; pd.Valid = planResult.Valid; pd.ActiveAgent = activeAgent; AddResult(pd); }
public PlanResult Plan(Constant activeAgent, List <Predicate> activeGoals, List <KeyValuePair <Predicate, int> > goalsCompletionTime, List <Action> reqActions) { m_AgentDomain = Parser.ParseDomain(m_GeneralDomain.FilePath, m_GeneralDomain.AgentCallsign); m_AgentProblem = Parser.ParseProblem(m_GeneralProblem.FilePath, m_AgentDomain); m_ActiveAgent = activeAgent; m_ActiveGoals = m_AgentProblem.GetGoals(); m_GoalsCompletionTime = goalsCompletionTime; m_ReqCollabActions = reqActions; DateTime start = DateTime.Now; AddNoopAction(); AddTimeConstraints(); List <Action> extractedActions; AddCollabActionReq(out extractedActions); ConvertToSingleAgentProblem(); AddPrevCompletionOfGoals(); SetGoals(); //Reasoning not working for button pushing domain AddReasoningActions(); //AddCosts(); SDRPlanner sdrPlanner = new SDRPlanner(m_AgentDomain, m_AgentProblem, m_planner); string s1 = m_AgentDomain.ToString(); string s2 = m_AgentProblem.ToString(); ConditionalPlanTreeNode Plan = sdrPlanner.OfflinePlanning(); string s = m_AgentDomain.ToString(); bool Valid = sdrPlanner.Valid; // Return extracted actions to domain foreach (var action in extractedActions) { m_AgentDomain.Actions.Add(action); } TimeSpan PlanningTime = DateTime.Now - start; PlanResult result = new PlanResult(activeAgent, Plan, PlanningTime, Valid, goalsCompletionTime, reqActions, m_AgentDomain, m_AgentProblem, m_GeneralDomain, m_GeneralProblem); // Write plan to file string path = Path.GetDirectoryName(m_AgentDomain.FilePath) + "\\plan_" + m_ActiveAgent.Name + ".txt"; File.WriteAllText(path, PlanTreePrinter.Print(result.Plan)); return(result); }
private static List <Action> GenerateJointActionsListForSingleInitialState(PartiallySpecifiedState initialState, Dictionary <Constant, PlanResult> plans) { foreach (var agentPlan in plans) { Constant agent = agentPlan.Key; PlanResult planResult = agentPlan.Value; ConditionalPlanTreeNode cptn = planResult.Plan; List <Action> actions = new List <Action>(); cptn.GetActionUsed(ref actions); return(actions); } return(null); }
public void SingleAgentSDRPlanner_TestConvertToSingleAgentProblemBoxes() { string filePathProblem = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName + @"\PlanningProblems\BoxPushing\B3\p.pddl"; string filePathDomain = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName + @"\PlanningProblems\BoxPushing\B3\d.pddl"; Domain d = Parser.ParseDomain(filePathDomain, "agent"); Problem p = Parser.ParseProblem(filePathProblem, d); // parameters Constant currentAgent = new Constant("agent", "a1"); SingleAgentSDRPlanner saSDR = new SingleAgentSDRPlanner(d, p, SDRPlanner.Planners.FF); PlanResult result = saSDR.Plan(currentAgent, null, null, null); Assert.IsNotNull(result.Plan); }
public void OnJobRunEnded(long id) { lock (this.evaluateTriggersLock) { Logger.Info($"A JobRun has ended. Reevaluating triggers that did not yet schedule a run"); // Remove from in memory plan to not publish this in future var numbertOfDeletedItems = this.currentPlan.RemoveAll(e => e.Id == id); var additonalItems = new List <ScheduledPlanItem>(); // If a trigger was blocked previously, it might be a candidate to schedule now var activeTriggers = this.repository.GetActiveTriggers().Items; foreach (var trigger in activeTriggers) { if (this.currentPlan.Any(p => p.TriggerId == trigger.Id)) { continue; } PlanResult planResult = this.GetPlanResult(trigger as dynamic, false); if (planResult.Action == PlanAction.Possible) { var scheduledItem = this.CreateNew(planResult, trigger); additonalItems.Add(scheduledItem); } } if (additonalItems.Any() || numbertOfDeletedItems > 0) { Logger.Info($"The completion of a previous job caused the addition of {additonalItems.Count} and removal of {numbertOfDeletedItems} scheduled items"); this.currentPlan.AddRange(additonalItems); this.PublishCurrentPlan(); } else { Logger.Debug($"There was no possibility to scheduled new items after the completion of job with it '{id}'."); } } }
public void OnTriggerStateUpdated(long jobId, long triggerId) { lock (this.evaluateTriggersLock) { Logger.Info($"The trigger with id '{triggerId}' has been changed its state. Reflecting changes to Plan if any."); var trigger = this.repository.GetTriggerById(jobId, triggerId); PlanResult planResult = this.GetPlanResult(trigger as dynamic, false); if (planResult.Action == PlanAction.Obsolete) { // Remove from in memory plan to not publish this in future this.currentPlan.RemoveAll(e => e.TriggerId == triggerId); // Set the JobRun to deleted if any var dependentJobRun = this.repository.GetNextJobRunByTriggerId(jobId, trigger.Id, this.dateTimeProvider.GetUtcNow()); if (dependentJobRun != null) { this.repository.Delete(dependentJobRun); } this.PublishCurrentPlan(); return; } if (planResult.Action == PlanAction.Possible) { var newItem = this.CreateNew(planResult, trigger); if (newItem != null) { this.currentPlan.Add(newItem); this.PublishCurrentPlan(); } } } }
private ScheduledPlanItem CreateNew(PlanResult planResult, JobTriggerBase trigger) { var dateTime = planResult.ExpectedStartDateUtc; if (!dateTime.HasValue) { Logger.Warn($"Unable to gather an expected start date for trigger with id {trigger.Id}, (JobId: {trigger.JobId}), skipping."); return(null); } // Create the next occurence from database var newJobRun = this.CreateNewJobRun(trigger, dateTime.Value); // Add to the initial plan var newItem = new ScheduledPlanItem { TriggerId = trigger.Id, Id = newJobRun.Id, PlannedStartDateTimeUtc = newJobRun.PlannedStartDateTimeUtc }; return(newItem); }
private void CreateInitialPlan() { var activeTriggers = this.repository.GetActiveTriggers(); var newPlan = new List <ScheduledPlanItem>(); foreach (var trigger in activeTriggers) { PlanResult planResult = this.GetPlanResult(trigger as dynamic, false); if (planResult.Action == PlanAction.Obsolete) { Logger.WarnFormat($"Disabling trigger with id '{trigger.Id}', because startdate is in the past. (Type: '{trigger.GetType().Name}', userId: '{trigger.UserId}', userName: '******')"); this.repository.DisableTrigger(trigger.JobId, trigger.Id); continue; } if (planResult.Action == PlanAction.Blocked) { // Cannot schedule jobrun, one reason could be that this job is not allowed to run because another jobrun is active continue; } if (planResult.Action == PlanAction.Possible) { if (planResult.ExpectedStartDateUtc == null) { // Move to ctor of PlanResult throw new ArgumentNullException("ExpectedStartDateUtc"); } var dateTime = planResult.ExpectedStartDateUtc; // Get the next occurence from database var dependentJobRun = this.repository.GetNextJobRunByTriggerId(trigger.JobId, trigger.Id, this.dateTimeProvider.GetUtcNow()); if (dependentJobRun != null) { this.UpdatePlannedJobRun(dependentJobRun, trigger, dateTime.Value); } else { dependentJobRun = this.CreateNewJobRun(trigger, dateTime.Value); } // Add to the initial plan newPlan.Add(new ScheduledPlanItem() { TriggerId = trigger.Id, Id = dependentJobRun.Id, PlannedStartDateTimeUtc = dependentJobRun.PlannedStartDateTimeUtc }); } } // Set current plan this.currentPlan = newPlan; // Publish the initial plan top the Excutor this.PublishCurrentPlan(); }
public Dictionary <Constant, PlanResult> Plan() { // Set iteration number = 0; int iteration = 0; // Initialize SA agent Planner SingleAgentSDRPlanner saSDR = new SingleAgentSDRPlanner(Domain, Problem, m_planner); while (!agentSelector.Finished()) { Constant currAgent = agentSelector.GetNextAgent(); // Inc iteration num iteration += 1; // Get constraints from previous iterations // collab action, sender List <Tuple <Action, Constant> > prevCollabConstraints = agentSelector.GetCollabConstraints(currAgent); // Get goals completion time from previous iterations List <KeyValuePair <Predicate, int> > prevGoalsCompletionTime = agentSelector.GetPrevGoalsCompletionTime(currAgent, Problem); // Plan for current agent var collabReqForCurrentAgent = prevCollabConstraints.Select(x => x.Item1).ToList(); PlanResult pr = saSDR.Plan(currAgent, null, prevGoalsCompletionTime, collabReqForCurrentAgent); if (pr.Valid) { // 1. Align tree using joint actions // 1.1 Extract constraints (Collaborative actions) // Agent , Actions required List <Action> collabUsed = pr.GetConstraintsGeneratedForSelf(); // 1.2 Check if sender of can commit to the collaborative actions PlanResult pr_validation = saSDR.Plan(currAgent, null, prevGoalsCompletionTime, collabUsed); if (pr_validation.Valid) { pr = pr_validation; } else { // TODO postpone joint actions until valid throw new NotImplementedException(); } // Dictionary <Constant, List <Action> > constraints = pr.GetNewConstraintsGeneratedForOtherAgents(prevCollabConstraints); // 4. Save collaborative actions' constraints for other agents // for each target agent // TODO inser this part into one function (maybe AddCollabConstraints?) agentSelector.RemoveConstraintsFromSendBy(currAgent); foreach (var agentConstraints in constraints) { // for each action that other target agent needs to complete. foreach (var a in agentConstraints.Value) { // add this action to his tasks. agentSelector.AddCollabConstraints(agentConstraints.Key, a, currAgent); } } // collect effects from joint actions that has been completed // mark goal achiement time to 0 for goals obtained by joint actions - // for disabling improving joint actions HashSet <Predicate> effects = new HashSet <Predicate>(); foreach (var item in prevCollabConstraints) { foreach (Predicate p in item.Item1.Effects.GetAllPredicates()) { effects.Add(p); } } // 5. Save goal completion time, but ignore achieved predicates forced from other agents - he didnt caused that! var goalTiming = pr.GetGoalsCompletionTime(Problem, prevCollabConstraints.Select(x => x.Item1).ToList()); foreach (var item in goalTiming) { bool jumped = false; int newTime = item.Value; if (item.Key.IsContainedIn(effects.ToList())) { newTime = 1; jumped = true; } Constant backtrackToAgent = null; agentSelector.AddGoalCompletionTime(iteration, currAgent, item.Key, newTime, out backtrackToAgent); // TODO - only backtrack to the earliest agent // set backtrack if needed if (backtrackToAgent != null && !jumped) { agentSelector.SetNextAgent(backtrackToAgent); } } // Save plan details if (!m_AgentsPlans.ContainsKey(currAgent)) { m_AgentsPlans.Add(currAgent, pr); } else { m_AgentsPlans[currAgent] = pr; } } else { // failed to plan (without alignment) Console.WriteLine("Agent " + currAgent.Name + " failed to plan"); } } return(m_AgentsPlans); }