protected override async Task<IConstraintSolverResult> Run(ProjectDataSet dataSet, IConstraints constraints, IDictionary<Guid, TimeFrame> overrideActivityTargetDurations) { if (constraints == null) throw new ArgumentNullException("The constraint object cannot be null."); var bestSolutionResult = new ConstraintSolverResult(constraints); try { var dataManager = new SolverDataManager(dataSet, bestSolutionResult); await dataManager.InitializeDataAsync(); var solver = new Solver(dataManager); await solver.ComputeSolutionAsync(); bestSolutionResult.State = SolverResultState.OptimalSolutionFound; } catch (Exception ex) { bestSolutionResult.Errors.Add(new ConstraintSolverError(null, "Error running GreedySolver solver", ex.LastExceptionMessage())); } return bestSolutionResult; }
public Calculator(IDelimiterParser delimiterParser, IDataParser dataParser, IValidationService validationService, IConstraints constraints) { _delimiterParser = delimiterParser ?? throw new ArgumentNullException(nameof(delimiterParser)); _dataParser = dataParser ?? throw new ArgumentNullException(nameof(dataParser)); _validationService = validationService ?? throw new ArgumentNullException(nameof(validationService)); _constraints = constraints ?? throw new ArgumentNullException(nameof(constraints)); }
public override bool CanSolve(IConstraints constraints) { return (constraints.ConstrainOnLaborPool || constraints.ConstrainOnLaborSchedule || constraints.ConstrainOnTools || constraints.ConstrainOnZones); }
public OniConstraintsBatchImpl(IConstraints constraints, Oni.ConstraintType type) { this.m_Constraints = constraints; this.m_ConstraintType = type; m_OniBatch = Oni.CreateBatch((int)type); }
public override bool CanSolve(IConstraints constraints) { return(constraints.ConstrainOnLaborPool || constraints.ConstrainOnLaborSchedule || constraints.ConstrainOnTools || constraints.ConstrainOnZones); }
public static bool SatisfiesConstraints <M>(this IConstraints <M> constraints, IEnumerable <M> members, M member, out int constraintViolations) where M : IMember { bool isValid = true; // TODO: rewrite this code to be more efficient, using hashsets instead of iterating the lists. constraintViolations = 0; if (constraints.AllowDuplicateFromSource.HasValue && !constraints.AllowDuplicateFromSource.Value) { constraintViolations += members.Any(mem => mem.Source == member.Source) ? 1 : 0; } if (constraints.AllowDuplicateIds.HasValue && !constraints.AllowDuplicateIds.Value) { constraintViolations += members.Any(mem => mem.Id == member.Id) ? 1 : 0; } if (constraints.AllowDuplicateTags.HasValue && !constraints.AllowDuplicateTags.Value) { constraintViolations += members.Where(mem => mem.Tags.Intersect(member.Tags).Count() > 0).Count(); } if (constraints.AllowedMemberTags != null) { constraintViolations += (member.Tags.Intersect(constraints.AllowedMemberTags).Count() <= 0) ? 1 : 0; } if (constraints.BannedMemberIds != null) { constraintViolations += constraints.BannedMemberIds.Contains(member.Id) ? 1 : 0; } if (constraints.BannedMemberTags != null) { constraintViolations += (member.Tags.Intersect(constraints.BannedMemberTags).Count() > 0) ? 1 : 0; } /* // This doesn't work / needs to be re-thought * if (constraints.MinMemberCount.HasValue * && ((members.Count() + 1) < constraints.MinMemberCount.Value)) * { * constraintViolations += 1; * }*/ if (constraints.MaxMemberCount.HasValue && ((members.Count() + 1) > constraints.MaxMemberCount.Value)) { isValid = false; //constraintViolations += 1; } return(isValid); }
public void DestroyConstraintsGroup(IConstraints group) { if (constraints != null && group != null) { var c = constraints[(int)group.constraintType]; if (c != null) { c.Remove((IBurstConstraintsImpl)group); } } }
public void FindOtherConstraintsContainingAllKeysTest2() { IConstraints <int> constraints = new Constraints <int>(); Keys <int> group1 = new Keys <int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; IConstraint <int> constraint1 = new ConstraintMutuallyExclusive <int>("row1", group1); Keys <int> group2 = new Keys <int>() { 1, 10, 19, 28, 37, 46, 55, 64, 73 }; IConstraint <int> constraint2 = new ConstraintMutuallyExclusive <int>("col1", group2); Keys <int> group3 = new Keys <int>() { 1, 2, 3, 10, 11, 12, 19, 20, 21 }; IConstraint <int> constraint3 = new ConstraintMutuallyExclusive <int>("grid1", group3); Keys <int> group4 = new Keys <int>() { 2, 11, 20, 29, 38, 47, 56, 65, 74 }; IConstraint <int> constraint4 = new ConstraintMutuallyExclusive <int>("col2", group4); constraints.Add(constraint1); constraints.Add(constraint2); constraints.Add(constraint3); constraints.Add(constraint4); // Calling Params Keys <int> keys = new Keys <int>() { 1, 2 }; ICollection <ConstraintType> types = new List <ConstraintType>() { ConstraintType.MutuallyExclusive }; IConstraints <int> excluding = new Constraints <int>(); IConstraints <int> expected = new Constraints <int>() { constraint1, constraint3 }; IConstraints <int> actual = constraints.FindOtherConstraintsContainingAllKeys(keys, types, excluding); Assert.AreEqual(expected.Count, actual.Count, "Incorrect count"); Assert.AreEqual(actual.ElementAt(0).Name, constraint1.Name, "First element does not equal col1"); Assert.AreEqual(actual.ElementAt(1).Name, constraint3.Name, "Second element does not equal grid1"); }
public static bool SatisfiesConstraints <M>(IConstraints <M> groupConstraints, IEnumerable <IConstraints <M> > subGroupConstraints, IEnumerable <IEnumerable <M> > members, M member, out int constraintViolations) where M : IMember { constraintViolations = 0; bool valid = true; foreach ((IConstraints <M> constraints, IEnumerable <M> group) in subGroupConstraints.Zip(members)) { valid &= constraints.SatisfiesConstraints(group, member, out int violations); constraintViolations += violations; } valid &= groupConstraints.SatisfiesConstraints(members.SelectMany(grp => grp).ToList(), member, out int violations2); constraintViolations += violations2; return(valid); }
public ConstraintSolverResult ScheduleDataSet(ProjectDataSet dataSet, IConstraints constraints, GreedyActivityStrategy strategy) { var result = new ConstraintSolverResult(constraints); try { var cp = new CriticalPathHelper(); cp.OrderActivitySchedule(dataSet, result); foreach (var a in result.Schedule) { _scheduledJobs.GetOrAdd(a.ScheduledItem.UID, a); } SetupJobsAndResources(dataSet, constraints); var dataManager = new SolverDataManager(dataSet, result); var solver = new Solver(dataManager); //var results = solver.Solve( // _shifts.Values.ToList(), // _workers.Values.ToList(), // _tools.Values.ToList(), // _zones.Values, // _jobs.Values, // strategy, _shiftManager); //foreach (var job in results) //{ // var activity = _activitiesMap[job.Job.ID]; // var scheduledActivity = _scheduledJobs[activity.UID]; // var start = TimeFrame.FromMinutes(job.Start); // var end = TimeFrame.FromMinutes(job.End); // scheduledActivity.ScheduledStart = start; // scheduledActivity.ScheduledFinish = end; // //result.ActivitySchedule.AddOrUpdateItemSchedule(job.Start, scheduledActivity); // //result.State = SolverResultState.OptimalSolutionFound; //} //result.State = SolverResultState.OptimalSolutionFound; } catch (Exception ex) { throw new Exception("Yikes! Error in solver!", ex); } return(result); }
public virtual void TestConstraints() { IQuery q = NewQuery(); q.Constrain(new Db4objects.Db4o.Tests.Common.Soda.Wrapper.Untyped.STStringUTestCase ("aaa")); q.Constrain(new Db4objects.Db4o.Tests.Common.Soda.Wrapper.Untyped.STStringUTestCase ("bbb")); IConstraints cs = q.Constraints(); IConstraint[] csa = cs.ToArray(); if (csa.Length != 2) { Assert.Fail("Constraints not returned"); } }
public virtual void TestConstraints() { IQuery q = NewQuery(); q.Constrain(new Db4objects.Db4o.Tests.Common.Soda.Classes.Simple.STByteTestCase(( byte)1)); q.Constrain(new Db4objects.Db4o.Tests.Common.Soda.Classes.Simple.STByteTestCase(( byte)0)); IConstraints cs = q.Constraints(); IConstraint[] csa = cs.ToArray(); if (csa.Length != 2) { Assert.Fail("Constraints not returned"); } }
protected override List<IDataSetValidationResult> PerformSpecificValidation(ProjectDataSet dataSet, IConstraints constraints) { List<IDataSetValidationResult> validationResults = new List<IDataSetValidationResult>(); if (constraints.ConstrainOnLaborPool) { validationResults.Add(ValidationService.ValidateActivityLaborRequirement(dataSet, ValidationOutcome.Invalid)); //validationResults.Add(ValidationService.ValidateActivityShiftLengthForRequiredLabor(dataSet, ValidationOutcome.Warning)); } if (constraints.ConstrainOnTools) { validationResults.Add(ValidationService.ValidateActivityToolRequirement(dataSet, ValidationOutcome.Invalid)); //validationResults.Add(ValidationService.ValidateActivityShiftLengthForRequiredTools(dataSet, ValidationOutcome.Warning)); } return validationResults; }
private void SetupJobsAndResources(ProjectDataSet dataSet, IConstraints constraints) { //foreach (var shift in dataSet.Shifts) //{ // var cshift = CreateShiftFromShift(shift); // _shiftManager.AddShift(cshift); // _shifts.GetOrAdd(shift.Name, cshift); // if (constraints.ConstrainOnLaborPool) // { // foreach (var laborLink in shift.LaborLinks) // { // foreach (var w in CreateWorkerFromLaborLink(laborLink)) // { // _workers.GetOrAdd(w.ID, w); // _shifts[shift.Name].Workers.Add(w); // } // } // } // if (constraints.ConstrainOnTools) // { // foreach (var toolLink in shift.ToolLinks) // { // foreach (var t in CreateToolFromToolLink(toolLink)) // { // _tools.GetOrAdd(t.ID, t); // _shifts[shift.Name].Tools.Add(t); // } // } // } //} if (constraints.ConstrainOnZones) { foreach (var zone in dataSet.GetZoneResources()) { var z = CreateZoneFromZone(zone); _zones.GetOrAdd(z.ID, z); _zonesMap.GetOrAdd(z.ID, zone); } } }
public void Setup() { _delimiterParser = new DelimiterParser(); _dataParser = new DataParser(); IValidation lengthValidation = new LengthValidation(); var validations = new List <IValidation> { lengthValidation }; IConstraint maxNumberConstraint = new MaxNumberConstraint(); var constraints = new List <IConstraint> { maxNumberConstraint }; _validationService = new ValidationService(validations); _constraints = new Constraints(constraints); _calculator = new Calculator(_delimiterParser, _dataParser, _validationService, _constraints); }
public void AddGrids(int xOffset, int yOffset, int xSize, int ySize, int xWidth, IConstraints <int> constraints) { for (int y2 = 0; y2 < ySize; y2 = y2 + 3) { for (int x2 = 0; x2 < xSize; x2 = x2 + 3) { AddGrid(x2 + xOffset, y2 + yOffset, 3, 3, xWidth, constraints); } } }
public async Task <ConstraintSolverResult> ScheduleDataSetAsync(ProjectDataSet dataSet, IConstraints constraints, GreedyActivityStrategy strategy) { return(await Task.Run(() => ScheduleDataSet(dataSet, constraints, strategy))); }
public void DestroyConstraintsGroup(IConstraints group) { }
public void AddGrid(int xOffset, int yOffset, int xSize, int ySize, int xWidth, IConstraints <int> constraints) { Keys <int> group = new Keys <int>(); for (int y = 0; y < ySize; y++) { for (int x = 0; x < xSize; x++) { group.Add(1 + x + xOffset + ((y + yOffset) * xWidth)); } } int xGrid = xOffset > 0 ? (xOffset / xSize) + 1 : 1; int yGrid = yOffset > 0 ? (yOffset * xWidth) / ySize + 1 : 1; string name = string.Format("Grid {0},{1}: At {2}", xGrid, yGrid, xOffset + 1 + (yOffset * xWidth)); IConstraint <int> constraint = new ConstraintMutuallyExclusive <int>(name, group); constraints.Add(constraint); }
/// <summary> /// Find all constraints that contain all the keys /// E.g. Find me a constraint that contains the set 1,5,6 /// </summary> /// <param name="keys"></param> /// <param name="me"></param> /// <returns></returns> public IConstraints <TKey> FindOtherConstraintsContainingAllKeys(Keys <TKey> keys, ICollection <ConstraintType> types, IConstraints <TKey> excluding) { IConstraints <TKey> constraints = new Constraints <TKey>(); // look through contraints that intesect at each of our combinations foreach (IConstraint <TKey> constraint in this) { if (types.Contains(constraint.Type)) { if (!excluding.Contains(constraint)) { bool allPresent = true; foreach (TKey key in keys) { if (!constraint.Keys.Contains(key)) { allPresent = false; break; } } if (allPresent) { constraints.Add(constraint); } } } } return(constraints); }
public void ProcessModel(ProjectDataSet model, IConstraints constraints) { ProcessShifts(model.Shifts, constraints); }
private void ProcessShifts(IEnumerable <DataSetServices.Data.Modeling.Core.IShift> shifts, IConstraints constraints) { foreach (var shift in shifts) { var cshift = CreateShiftFromShift(shift); _shifts.GetOrAdd(shift.Name, cshift); if (constraints.ConstrainOnLaborPool) { foreach (var laborLink in shift.LaborLinks) { foreach (var w in CreateWorkerFromLaborLink(laborLink)) { _workers.GetOrAdd(w.ID, w); _shifts[shift.Name].Workers.Add(w); } } } if (constraints.ConstrainOnTools) { foreach (var toolLink in shift.ToolLinks) { foreach (var t in CreateToolFromToolLink(toolLink)) { _tools.GetOrAdd(t.ID, t); _shifts[shift.Name].Tools.Add(t); } } } AddShift(cshift); } }
int CreateXWingProcesses(IList <IList <IKeyedRegions <TKey> > > xwings, IPuzzleEngine <TKey> engine) { int added = 0; foreach (IList <IKeyedRegions <TKey> > xwing in xwings) { foreach (Keys <TKey> keys1 in xwing[0].OtherKeys) { foreach (TKey key1 in keys1) { foreach (Keys <TKey> keys2 in xwing[1].OtherKeys) { foreach (TKey key2 in keys2) { Keys <TKey> keysA = new Keys <TKey>() { key1, key2 }; IConstraints <TKey> y = engine.Puzzle.Constraints.FindOtherConstraintsContainingAllKeys( keysA, new HashSet <ConstraintType>() { this.Type }, new Constraints <TKey>() { this }); foreach (IConstraint <TKey> constraint in y) { if (xwing[0].Value.IsSubsetOf(keysA.ReducedSetValues(constraint.Keys, engine.Puzzle.Space))) { Keys <TKey> keys1R = new Keys <TKey>(keys1); keys1R.Remove(key1); if (keys1R.Count > 0) { //SpaceAdapter<int>.ToFile(engine.Puzzle.Space.ToString(), 0); JobFilter <TKey> action1 = new JobFilter <TKey>("XWing", keys1R, xwing[0].Value); engine.Add(action1); added++; } Keys <TKey> keys2R = new Keys <TKey>(keys2); keys2R.Remove(key2); if (keys2R.Count > 0) { //SpaceAdapter<int>.ToFile(engine.Puzzle.Space.ToString(), 2); JobFilter <TKey> action2 = new JobFilter <TKey>("XWing", keys2R, xwing[1].Value); engine.Add(action2); added++; //SpaceAdapter<int>.ToFile(engine.Puzzle.Space.ToString(), 3); } } } } } } } } return(added); }
public void AddColumns(int xOffset, int yOffset, int xSize, int ySize, int xWidth, IConstraints <int> constraints) { for (int x = 0; x < xSize; x++) { Keys <int> group = new Keys <int>(); for (int y = 0; y < ySize; y++) { group.Add(1 + x + xOffset + ((y + yOffset) * xWidth)); } string name = string.Format("Column {0}: At {1}", x + 1, x + 1 + xOffset + (yOffset * xWidth)); IConstraint <int> constraint = new ConstraintMutuallyExclusive <int>(name, group); constraints.Add(constraint); } }
protected override async Task <IConstraintSolverResult> Run(ProjectDataSet dataSet, IConstraints constraints, IDictionary <Guid, TimeFrame> overrideActivityTargetDurations) { if (constraints == null) { throw new ArgumentNullException("The constraint object cannot be null."); } var bestSolutionResult = new ConstraintSolverResult(constraints); try { var dataManager = new SolverDataManager(dataSet, bestSolutionResult); await dataManager.InitializeDataAsync(); var solver = new Solver(dataManager); await solver.ComputeSolutionAsync(); bestSolutionResult.State = SolverResultState.OptimalSolutionFound; } catch (Exception ex) { bestSolutionResult.Errors.Add(new ConstraintSolverError(null, "Error running GreedySolver solver", ex.LastExceptionMessage())); } return(bestSolutionResult); }
public async Task<ConstraintSolverResult> ScheduleDataSetAsync(ProjectDataSet dataSet, IConstraints constraints, GreedyActivityStrategy strategy) { return await Task.Run(() => ScheduleDataSet(dataSet, constraints, strategy)); }
private void SetupConstraints9x9(int xOffset, int yOffset, int xSize, int ySize, int xWidth, IConstraints <int> constraints) { // Row Exclusive Constraints AddRows(xOffset, yOffset, xSize, ySize, xWidth, Constraints); // Column Exclusive Constraints AddColumns(xOffset, yOffset, xSize, ySize, xWidth, Constraints); // Grid Exclusive Constraints AddGrids(xOffset, yOffset, xSize, ySize, xWidth, Constraints); }
public ConstraintSolverResult ScheduleDataSet(ProjectDataSet dataSet, IConstraints constraints, GreedyActivityStrategy strategy) { var result = new ConstraintSolverResult(constraints); try { var cp = new CriticalPathHelper(); cp.OrderActivitySchedule(dataSet, result); foreach (var a in result.Schedule) { _scheduledJobs.GetOrAdd(a.ScheduledItem.UID, a); } SetupJobsAndResources(dataSet, constraints); var dataManager = new SolverDataManager(dataSet, result); var solver = new Solver(dataManager); //var results = solver.Solve( // _shifts.Values.ToList(), // _workers.Values.ToList(), // _tools.Values.ToList(), // _zones.Values, // _jobs.Values, // strategy, _shiftManager); //foreach (var job in results) //{ // var activity = _activitiesMap[job.Job.ID]; // var scheduledActivity = _scheduledJobs[activity.UID]; // var start = TimeFrame.FromMinutes(job.Start); // var end = TimeFrame.FromMinutes(job.End); // scheduledActivity.ScheduledStart = start; // scheduledActivity.ScheduledFinish = end; // //result.ActivitySchedule.AddOrUpdateItemSchedule(job.Start, scheduledActivity); // //result.State = SolverResultState.OptimalSolutionFound; //} //result.State = SolverResultState.OptimalSolutionFound; } catch (Exception ex) { throw new Exception("Yikes! Error in solver!", ex); } return result; }
protected override List <IDataSetValidationResult> PerformSpecificValidation(ProjectDataSet dataSet, IConstraints constraints) { List <IDataSetValidationResult> validationResults = new List <IDataSetValidationResult>(); if (constraints.ConstrainOnLaborPool) { validationResults.Add(ValidationService.ValidateActivityLaborRequirement(dataSet, ValidationOutcome.Invalid)); //validationResults.Add(ValidationService.ValidateActivityShiftLengthForRequiredLabor(dataSet, ValidationOutcome.Warning)); } if (constraints.ConstrainOnTools) { validationResults.Add(ValidationService.ValidateActivityToolRequirement(dataSet, ValidationOutcome.Invalid)); //validationResults.Add(ValidationService.ValidateActivityShiftLengthForRequiredTools(dataSet, ValidationOutcome.Warning)); } return(validationResults); }
private void ProcessShifts(IEnumerable<DataSetServices.Data.Modeling.Core.IShift> shifts, IConstraints constraints) { foreach (var shift in shifts) { var cshift = CreateShiftFromShift(shift); _shifts.GetOrAdd(shift.Name, cshift); if (constraints.ConstrainOnLaborPool) { foreach (var laborLink in shift.LaborLinks) { foreach (var w in CreateWorkerFromLaborLink(laborLink)) { _workers.GetOrAdd(w.ID, w); _shifts[shift.Name].Workers.Add(w); } } } if (constraints.ConstrainOnTools) { foreach (var toolLink in shift.ToolLinks) { foreach (var t in CreateToolFromToolLink(toolLink)) { _tools.GetOrAdd(t.ID, t); _shifts[shift.Name].Tools.Add(t); } } } AddShift(cshift); } }
protected IList <IList <IKeyedRegions <TKey> > > CreateXWing(IRegion <TKey> isolatedSet, IPuzzleEngine <TKey> engine) { List <IList <IKeyedRegions <TKey> > > xwings = new List <IList <IKeyedRegions <TKey> > >(); // Check each of our isolated set values foreach (int value in isolatedSet.Value) { IList <IKeyedRegions <TKey> > xwing = new List <IKeyedRegions <TKey> >(); xwing.Add(new KeyedRegions <TKey>()); xwing.Add(new KeyedRegions <TKey>()); xwing[0].Value = new Possible() { value }; xwing[1].Value = new Possible() { value }; int perpSetId = 0; foreach (TKey key in isolatedSet.Keys) // Two isolated keys only { // Find other constraints passing through "key" IConstraints <TKey> perpConstraints = engine.Puzzle.Constraints.FindOtherConstraintsContainingAllKeys( new Keys <TKey>() { key }, new HashSet <ConstraintType>() { this.Type }, new Constraints <TKey>() { this }); foreach (IConstraint <TKey> perpConstraint in perpConstraints) { // Check each location in other set Keys <TKey> otherKeys = new Keys <TKey>(); foreach (TKey constraintKey in perpConstraint.Keys) { if (!constraintKey.Equals(key)) { // check if the spaces have the same values as our reducedset visitor combination if (engine.Puzzle.Space[constraintKey].Contains(value)) { // TODO need two xwing groups. One for each constraint (linked contraint is different) otherKeys.Add(constraintKey); } } } if (otherKeys.Count() > 0) { xwing[perpSetId].OtherKeys.Add(otherKeys); xwing[perpSetId].Keys.Add(key); } } perpSetId++; } xwings.Add(xwing); } return(xwings); }
public void DestroyConstraintsGroup(IConstraints group) { // no need to implement. }