private string BuildTodayMessage(PlanningResult result, DateTimeOffset date) { var day = date.DayOfWeek; var sb = new StringBuilder($"These are the results for today, {DayReactions[day].MessageFormat}:\n"); sb.AppendLine("Available today:"); foreach (var userName in result.DayUserNames[day]) { sb.AppendLine($"- {userName}"); } sb.AppendLine(""); sb.AppendLine("Most voted items:"); foreach (var item in result.Items.Where(i => i.YesUserNames.Count > 0).OrderByDescending(i => i.YesUserNames.Intersect(result.DayUserNames[day]).Count() + (i.MaybeUserNames.Intersect(result.DayUserNames[day]).Count() * 0.5)).Take(3)) { var userString = $"({string.Join(", ", item.YesUserNames)})"; if (item.MaybeUserNames.Any()) { userString += $" ~ *({string.Join(", ", item.MaybeUserNames)})*"; } sb.AppendLine($"**{item.Message.Content}** {userString}"); } return(sb.ToString()); }
private async Task <PlanningResult> GetPlanningResult() { var messages = await Context.Channel.GetMessagesAsync(250); var ownMessages = messages.Where(m => m.Author.Id == Context.Bot.CurrentUser.Id).ToList(); var planMessages = ownMessages.TakeUntilIncluding(m => !m.Content.StartsWith(planMessagePrefix)); var result = new PlanningResult { Message = planMessages.Single(m => m.Content.StartsWith(planMessagePrefix)) }; foreach (var dayReaction in result.Message.Reactions.Keys.Where(r => DayReactions.ContainsValue(r))) { var dictEntry = DayReactions.Single(e => e.Value.Equals(dayReaction)); var dayReactions = await result.Message.GetReactionsAsync(dayReaction); result.DayUserNames.Add(dictEntry.Key, SelectUserName(dayReactions)); } foreach (var message in planMessages.Where(m => m.Reactions.Keys.Contains(YesReaction)).Reverse()) { var messageResult = await GetPlanningResult(message); result.Items.Add(messageResult); } return(result); }
private void ArcVoteZone(Coordinates goalPoint, List <Obstacle> perimeterObstacles) { List <Polygon> perimeterPolys = new List <Polygon>(); foreach (Obstacle obs in perimeterObstacles) { perimeterPolys.Add(obs.cspacePolygon); } PlanningResult result; ISteeringCommandGenerator steeringCommand = ZoneArcVoting.SparcVote(ref prevCurvature, goalPoint, perimeterPolys); if (steeringCommand == null) { result = OnDynamicallyInfeasible(null, null); } else { result = new PlanningResult(); result.commandLabel = command_label; result.steeringCommandGenerator = steeringCommand; } settings.maxSpeed = recommendedSpeed.Speed; Track(result, command_label); }
private IEnumerable <string> BuildResultMessage(PlanningResult result) { var resultMessages = new List <string>(); var sb = new StringBuilder("These are the results of the last planning:\n"); foreach (var resultItem in result.Items.Where(r => r.YesUserNames.Any() || r.MaybeUserNames.Any()).OrderByDescending(r => r.YesUserNames.Count)) { var itemStringBuilder = new StringBuilder($"**{resultItem.Message.Content}**\n"); if (resultItem.YesUserNames.Any()) { itemStringBuilder.AppendLine($" {YesReaction.MessageFormat} {string.Join(", ", resultItem.YesUserNames)}"); } if (resultItem.MaybeUserNames.Any()) { itemStringBuilder.AppendLine($" {MaybeReaction.MessageFormat} {string.Join(", ", resultItem.MaybeUserNames)}"); } /*if (resultItem.NoUserNames.Any()) * itemStringBuilder.AppendLine($" {NoReaction.MessageFormat} {string.Join(", ", resultItem.NoUserNames)}");*/ if (sb.Length + itemStringBuilder.Length > 2000) { resultMessages.Add(" \n" + sb); sb = itemStringBuilder; } else { sb.Append(itemStringBuilder); } } resultMessages.Add(sb.ToString()); return(resultMessages); }
protected override void OnSmoothSuccess(ref PlanningResult result) { if (!(result.pathBlocked || result.dynamicallyInfeasible)) { // check the path, see if the first segment goes 180 off if (result.smoothedPath != null && result.smoothedPath.Count >= 2 && Math.Abs(result.smoothedPath.GetSegment(0).UnitVector.ArcTan) > 90 * Math.PI / 180) { result = OnDynamicallyInfeasible(null, null, true); Console.WriteLine("turn is 180 deg off, returning infeasible"); return; } } base.OnSmoothSuccess(ref result); }
protected override void OnSmoothSuccess(ref PlanningResult result) { if (sparse) { if (Services.ObstaclePipeline.ExtraSpacing < 1) { Services.ObstaclePipeline.ExtraSpacing = Math.Min(1, Services.ObstaclePipeline.ExtraSpacing + 0.02); } if (smootherSpacingAdjust < 0) { smootherSpacingAdjust = Math.Min(0, smootherSpacingAdjust + 0.01); } } base.OnSmoothSuccess(ref result); }
public void ExecutePlanning(int timeAvailable, IplannerFactory plannerFac) { PlanningData data = ReadPlanningDataFromDB(); PlanningResult result = plannerFac.create(timeAvailable).CreatePlan(data); //if (timeAvailable < 3) //{ // ReallyFastPlannerAdapter rfpAdap = new ReallyFastPlannerAdapter(); // result = rfpAdap.CreatePlan(data); //} //else if (timeAvailable < 12) //{ // PrettyFastPlannerV24 pfp24 = new PrettyFastPlannerV24(); // result = pfp24.CreatePlan(data); //} //else //{ // ExactPlannerV37 ep37 = new ExactPlannerV37(); // result = ep37.CreatePlan(data); //} WritePlanningResultToDB(result); }
public void ExecutePlanning(int timeAvailable) { PlanningData data = ReadPlanningDataFromDB(); PlanningResult result = null; if (timeAvailable < 3) { ReallyFastPlannerV16 rfp16 = new ReallyFastPlannerV16(); result = rfp16.CreatePlanFast(data); } else if (timeAvailable < 12) { PrettyFastPlannerV24 pfp24 = new PrettyFastPlannerV24(); result = pfp24.CalculatePlan(data); } else { ExactPlannerV37 ep37 = new ExactPlannerV37(); result = ep37.FindExactSolution(data); } WritePlanningResultToDB(result); }
public void ExecutePlanning(int timeAvailable, IPlannerFactory plannerFactory) { PlanningData data = ReadPlanningDataFromDB(); PlanningResult result = plannerFactory.Create(timeAvailable).CreatePlan(data); //if (timeAvailable < 3) //{ // ReallyFastPlannerV16 rfp16 = new ReallyFastPlannerV16(); // result = rfp16.CreatePlanFast(data); //} //else if (timeAvailable < 12) //{ // PrettyFastPlannerV24 pfp24 = new PrettyFastPlannerV24(); // result = pfp24.CalculatePlan(data); //} //else //{ // ExactPlannerV37 ep37 = new ExactPlannerV37(); // result = ep37.FindExactSolution(data); //} WritePlanningResultToDB(result); }
async Task PreparePlanning() { // Display waiter SetWaitStatus(true); lbProgress.Text = AppResources.lblProgressPlanning; // Set db again else db is cleared after power down/up, resulting in program crash // try { db = App.dbHandler.db; MobRegService service = new MobRegService(ProgramVars.URL); // 1. Delete all 'planned' plannings and associated data from local database // Common.DeletePlannedPlanningByUserID(App.appSettings.loginVars.userID.ToString()); // 2. Validate rest of local stored planning data against server stored data // var plannings = db.Table <Planning> ().ToList <Planning> ().Where(p => p.UserIDguid == App.appSettings.loginVars.userID); ValidatePlanningInput input = new ValidatePlanningInput() { installationID = App.appSettings.installationID, userIDin = App.appSettings.loginVars.userID.ToString() }; input.plannings = new List <rsPlanningValidation> (plannings.Count() + 1); foreach (Planning p in plannings) { input.plannings.Add(new rsPlanningValidation() { PlanningID = p.IDguid, StatusID = p.StatusID }); } ValidatePlanningResult valResult = await service.ValidatePlanningAsync(input); if (valResult.statusCode != 0) { throw new Exception(valResult.status); } if (valResult.PlanningResults != null) { foreach (rsPlanningValidation plan in valResult.PlanningResults) { if (plan.StatusCode != 0) { Common.DeletePlanningByPlanningID(plan.PlanningID.ToString()); } } } // 3. Get new planning from server // PlanningResult result = await service.GetPlanningAsync(new RegServices.Data.GetPlanningInput() { userID = App.appSettings.loginVars.userID.ToString(), installationID = App.appSettings.installationID, carID = App.appSettings.loginVars.carID }); if (result.statusCode != 0) { throw new Exception(result.status); } foreach (rsPlanning p in result.Plannings) { Planning planning = new Planning() { ID = p.ID.ToString(), OrderID = p.OrderID.ToString(), StatusID = p.StatusID, CarID = p.CarID, StartTime = p.StartDateTime, EndTime = p.EndDateTime, Project = p.Project, Alias = p.Alias, OrderType = p.OrderType, Description = p.Description, Comment = p.Comment, Reference = p.Reference, Customer = p.Customer, ContactName = p.ContactName, Phone = p.Phone, Street = p.Street, HouseNr = p.HouseNr, Zip = p.Zip, City = p.City, Country = p.Country, UserID = p.UserID.ToString(), PauzeTime = p.PauzeTime, ExecStartDateTime = p.ExecStartDateTime, ExecEndDateTime = p.ExecEndDateTime, Email = p.Email, SignatureName = p.SignatureName }; Common.ChangeStatus(planning, planning.StatusID); PlanningHistory his = new PlanningHistory() { PlanningID = planning.ID, StatusID = planning.StatusID, StartTime = DateTime.Now, EndTime = DateTime.Now }; db.Insert(his); db.Insert(planning); foreach (rsResource r in p.Resources) { Resource res = new Resource() { PlanningID = planning.ID.ToString(), UserID = r.UserID.ToString(), FriendlyName = r.FriendlyName, OwnPlanningID = r.OwnPlanningID.ToString(), IsDriver = r.IsDriver, IsSeparate = r.IsSeparate, IsPresent = r.IsPresent, StartDate = r.StartDate, EndDate = r.EndDate }; res.ID = res.PlanningID + res.UserID; //fake clustered PK, need this for deleting records db.Insert(res); } } //end foreach SetWaitStatus(false); } catch (Exception ex) { SetWaitStatus(false); await DisplayAlert(AppResources.Error, ex.Message, AppResources.Cancel); } }
private void WritePlanningResultToDB(PlanningResult result) { throw new NotImplementedException(); }
public void PlanningShouldFindWayToReachTargetValue() { var actionList = new List <IDomainAction> { new BuyAction("Axe"), new SellAction("Wood"), new EatPieAction(), new BuyAction("Pie"), new ChopWoodAction(), new TakeANapAction(), new GoToAction("Shop"), new GoToAction("Tree"), new GoToAction("Home"), new BuyAction("Alcohol"), new DrinkAlcoholAction() }; var actions = new ActionSet(actionList); var start = DomainState.Empty .Set("isHungry", true) .Set("isSober", true) .Set("hasAxe", true); var goal = DomainState.Empty .Set("isHungry", false) .Set("isDrunk", true); var planner = PlannerFactory.CreatePlanner( new PlannerSettings { EarlyExit = false, CreateDebugGraph = true, PlannerType = PlannerType.Regressive }); // WarmUp // for (var i = 0; i < 10; i++) // { // var _ = planner.GetPlan(start, goal, actions); // } PlanningResult result = null; var sw = Stopwatch.StartNew(); for (var i = 0; i < BenchmarkIterations; i++) { result = planner.GetPlan(start, goal, actions); } Assert.NotNull(result); Assert.NotNull(result.Plan); Assert.NotEmpty(result.Plan); Assert.NotNull(result.SearchTree); sw.Stop(); //WritePlanToFile(plan, sw); }
private void DoInitialPlan() { InitializePlanningSettings(); curTimestamp = Services.RelativePose.CurrentTimestamp; vs = Services.StateProvider.GetVehicleState(); LinePath curTargetPath = targetPath.Clone(); LinePath curLeftBound = null; if (leftBound != null) { curLeftBound = leftBound.Clone(); } LinePath curRightBound = null; if (rightBound != null) { curRightBound = rightBound.Clone(); } // get the distance between our current location and the start point double distToStart = Coordinates.Zero.DistanceTo(curTargetPath[0]); // extract off the first 5 m of the target path LinePath.PointOnPath endTarget = curTargetPath.AdvancePoint(curTargetPath.StartPoint, 12); curTargetPath = curTargetPath.SubPath(curTargetPath.StartPoint, endTarget); AddTargetPath(curTargetPath.Clone(), 0.005); // adjust the left bound and right bounds starting distance if (curLeftBound != null) { LinePath.PointOnPath leftBoundStart = curLeftBound.AdvancePoint(curLeftBound.StartPoint, 2); curLeftBound = curLeftBound.SubPath(leftBoundStart, curLeftBound.EndPoint); AddLeftBound(curLeftBound, false); } if (curRightBound != null) { LinePath.PointOnPath rightBoundStart = curRightBound.AdvancePoint(curRightBound.StartPoint, 2); curRightBound = curRightBound.SubPath(rightBoundStart, curRightBound.EndPoint); AddRightBound(curRightBound, false); } // add the intersection pull path LinePath intersectionPullPath = new LinePath(); double pullWeight = 0; AbsoluteTransformer trans = Services.StateProvider.GetAbsoluteTransformer(curTimestamp); GetIntersectionPullPath(pseudoStartLane.Transform(trans), curTargetPath, intersectionPolygon, true, true, intersectionPullPath, ref pullWeight); if (intersectionPullPath.Count > 0) { AddTargetPath(intersectionPullPath, pullWeight); } // set up planning details // add our position to the current target path curTargetPath.Insert(0, new Coordinates(0, 0)); smootherBasePath = curTargetPath; // add the bounds // calculate max speed settings.maxSpeed = GetMaxSpeed(null, LinePath.PointOnPath.Invalid); // fill in auxiliary settings if (curLeftBound != null || curRightBound != null) { settings.endingHeading = curTargetPath.EndSegment.UnitVector.ArcTan; } disablePathAngleCheck = true; settings.Options.w_diff = 4; // do the planning PlanningResult planningResult = Smooth(false); // if the planning was a success, store the result if (!planningResult.dynamicallyInfeasible) { // transform to absolute coordinates AbsoluteTransformer absTransform = Services.StateProvider.GetAbsoluteTransformer(curTimestamp); turnBasePath = planningResult.smoothedPath.Transform(absTransform.Invert()); } }
public override void Process(object param) { // inform the base that we're beginning processing if (!BeginProcess()) { return; } // check if we were given a parameter if (param != null && param is StayInLaneBehavior) { HandleBehavior((StayInLaneBehavior)param); } if (reverseGear) { ProcessReverse(); return; } // figure out the planning distance double planningDistance = GetPlanningDistance(); if (sparse && planningDistance > 10) { planningDistance = 10; } double?boundStartDistMin = null; double?boundEndDistMax = null; if (laneID != null && Services.RoadNetwork != null) { ArbiterLane lane = Services.RoadNetwork.ArbiterSegments[laneID.SegmentId].Lanes[laneID]; AbsolutePose pose = Services.StateProvider.GetAbsolutePose(); ArbiterLanePartition partition = lane.GetClosestPartition(pose.xy); LinePath partitionPath = partition.UserPartitionPath; LinePath.PointOnPath closestPoint = partitionPath.GetClosestPoint(pose.xy); double remainingDist = planningDistance; double totalDist = partitionPath.DistanceBetween(closestPoint, partitionPath.EndPoint); remainingDist -= totalDist; if (sparse) { // walk ahead and determine where sparsity ends bool nonSparseFound = false; while (remainingDist > 0) { // get the next partition partition = partition.Final.NextPartition; if (partition == null) { break; } if (partition.Type != PartitionType.Sparse) { nonSparseFound = true; break; } else { double dist = partition.UserPartitionPath.PathLength; totalDist += dist; remainingDist -= dist; } } if (nonSparseFound) { boundStartDistMin = totalDist; } } else { // determine if there is a sparse segment upcoming bool sparseFound = false; while (remainingDist > 0) { partition = partition.Final.NextPartition; if (partition == null) { break; } if (partition.Type == PartitionType.Sparse) { sparseFound = true; break; } else { double dist = partition.Length; totalDist += dist; remainingDist -= dist; } } if (sparseFound) { boundEndDistMax = totalDist; sparse = true; } } } BehaviorManager.TraceSource.TraceEvent(TraceEventType.Information, 0, "in stay in lane, planning distance {0}", planningDistance); // update the rndf path RelativeTransform relTransfrom = Services.RelativePose.GetTransform(behaviorTimestamp, curTimestamp); LinePath curRndfPath = rndfPath.Transform(relTransfrom); ILaneModel centerLaneModel = Services.RoadModelProvider.GetLaneModel(curRndfPath, rndfPathWidth + extraWidth, curTimestamp, numLanesLeft, numLanesRight); double avoidanceExtra = sparse ? 5 : 7.5; LinePath centerLine, leftBound, rightBound; if (boundEndDistMax != null || boundStartDistMin != null) { LinearizeStayInLane(centerLaneModel, planningDistance + avoidanceExtra, null, boundEndDistMax, boundStartDistMin, null, curTimestamp, out centerLine, out leftBound, out rightBound); } else { LinearizeStayInLane(centerLaneModel, planningDistance + avoidanceExtra, curTimestamp, out centerLine, out leftBound, out rightBound); } BehaviorManager.TraceSource.TraceEvent(TraceEventType.Verbose, 0, "in stay in lane, center line count: {0}, left bound count: {1}, right bound count: {2}", centerLine.Count, leftBound.Count, rightBound.Count); // calculate time to collision of opposing obstacle if it exists LinePath targetLine = centerLine; double targetWeight = default_lane_alpha_w; if (sparse) { targetWeight = 0.00000025; } else if (oncomingVehicleExists) { double shiftDist = -(TahoeParams.T + 1); targetLine = centerLine.ShiftLateral(shiftDist); targetWeight = 0.01; } else if (opposingLaneVehicleExists) { double timeToCollision = opposingLaneVehicleDist / (Math.Abs(vs.speed) + Math.Abs(opposingLaneVehicleSpeed)); Services.Dataset.ItemAs <double>("time to collision").Add(timeToCollision, curTimestamp); if (timeToCollision < 5) { // shift to the right double shiftDist = -TahoeParams.T / 2.0; targetLine = centerLine.ShiftLateral(shiftDist); } } // set up the planning AddTargetPath(targetLine, targetWeight); if (!sparse || boundStartDistMin != null || boundEndDistMax != null) { AddLeftBound(leftBound, true); if (!oncomingVehicleExists) { AddRightBound(rightBound, false); } } double targetDist = Math.Max(centerLine.PathLength - avoidanceExtra, planningDistance); smootherBasePath = centerLine.SubPath(centerLine.StartPoint, targetDist); maxSmootherBasePathAdvancePoint = smootherBasePath.EndPoint; double extraDist = (planningDistance + avoidanceExtra) - centerLine.PathLength; extraDist = Math.Min(extraDist, 5); if (extraDist > 0) { centerLine.Add(centerLine[centerLine.Count - 1] + centerLine.EndSegment.Vector.Normalize(extraDist)); } avoidanceBasePath = centerLine; Services.UIService.PushLineList(centerLine, curTimestamp, "subpath", true); Services.UIService.PushLineList(leftBound, curTimestamp, "left bound", true); Services.UIService.PushLineList(rightBound, curTimestamp, "right bound", true); // get the overall max speed looking forward from our current point settings.maxSpeed = GetMaxSpeed(curRndfPath, curRndfPath.AdvancePoint(curRndfPath.ZeroPoint, vs.speed * TahoeParams.actuation_delay)); // get the max speed at the end point settings.maxEndingSpeed = GetMaxSpeed(curRndfPath, curRndfPath.AdvancePoint(curRndfPath.ZeroPoint, planningDistance)); useAvoidancePath = false; if (sparse) { // limit to 5 mph laneWidthAtPathEnd = 20; pathAngleCheckMax = 50; pathAngleMax = 5 * Math.PI / 180.0; settings.maxSpeed = Math.Min(settings.maxSpeed, 2.2352); maxAvoidanceBasePathAdvancePoint = avoidanceBasePath.AdvancePoint(avoidanceBasePath.EndPoint, -2); //maxSmootherBasePathAdvancePoint = smootherBasePath.AdvancePoint(smootherBasePath.EndPoint, -2); LinePath leftEdge = RoadEdge.GetLeftEdgeLine(); LinePath rightEdge = RoadEdge.GetRightEdgeLine(); if (leftEdge != null) { leftLaneBounds.Add(new Boundary(leftEdge, 0.1, 1, 100, false)); } if (rightEdge != null) { rightLaneBounds.Add(new Boundary(rightEdge, 0.1, 1, 100, false)); } PlanningResult result = new PlanningResult(); ISteeringCommandGenerator commandGenerator = SparseArcVoting.SparcVote(ref prevCurvature, goalPoint); if (commandGenerator == null) { // we have a block, report dynamically infeasible result = OnDynamicallyInfeasible(null, null); } else { result.steeringCommandGenerator = commandGenerator; result.commandLabel = commandLabel; } Track(result, commandLabel); return; } else if (oncomingVehicleExists) { laneWidthAtPathEnd = 10; } BehaviorManager.TraceSource.TraceEvent(TraceEventType.Information, 0, "max speed set to {0}", settings.maxSpeed); disablePathAngleCheck = false; SmoothAndTrack(commandLabel, true); }