コード例 #1
0
        public static void GetCyclePaths_GivenEmptyTables_ReturnsEmptyCollection()
        {
            var cycleDetector = new CycleDetector();
            var result        = cycleDetector.GetCyclePaths(Array.Empty <IRelationalDatabaseTable>());

            Assert.That(result, Is.Empty);
        }
コード例 #2
0
        public void DisconnectedGraphCycleIsDetected()
        {
            var graph = new[]
            {
                new GraphVertex <int>
                {
                    Value = 1,
                },
                new GraphVertex <int>
                {
                    Value            = 2,
                    AdjacentVertices = new System.Collections.Generic.List <int> {
                        2
                    }
                },
                new GraphVertex <int>
                {
                    Value            = 2,
                    AdjacentVertices = new System.Collections.Generic.List <int> {
                        1
                    }
                },
            };

            Assert.True(CycleDetector.IsCyclic(graph));
        }
コード例 #3
0
 public void TestFindAnyCycleFromManyCycles()
 {
     using (var env = new TestEnvironment())
     {
         env.CreateRepo("A", new Dictionary <string, DepsContent>
         {
             { "full-build", new DepsContent(null, new List <Dep> {
                     new Dep("B"), new Dep("C")
                 }) }
         });
         env.CreateRepo("B", new Dictionary <string, DepsContent>
         {
             { "full-build", new DepsContent(null, new List <Dep> {
                     new Dep("D")
                 }) }
         });
         env.CreateRepo("C", new Dictionary <string, DepsContent>
         {
             { "full-build", new DepsContent(null, new List <Dep> {
                     new Dep("D")
                 }) }
         });
         env.CreateRepo("D", new Dictionary <string, DepsContent>
         {
             { "full-build", new DepsContent(null, new List <Dep> {
                     new Dep("A")
                 }) }
         });
         Helper.SetWorkspace(env.RemoteWorkspace);
         var cycle = CycleDetector.TryFindCycle("A");
         Assert.IsNotNull(cycle);
     }
 }
コード例 #4
0
        private ILookup <ISourceFile, ISourceFile> ReportFailuresForCycles()
        {
            var sourceFileGraph = this.sourceFilesByUri.Values
                                  .SelectMany(sourceFile => GetModuleDeclarations(sourceFile)
                                              .Where(this.sourceFilesByModuleDeclaration.ContainsKey)
                                              .Select(moduleDeclaration => this.sourceFilesByModuleDeclaration[moduleDeclaration])
                                              .Distinct()
                                              .Select(referencedFile => (sourceFile, referencedFile)))
                                  .ToLookup(x => x.sourceFile, x => x.referencedFile);

            var cycles = CycleDetector <ISourceFile> .FindCycles(sourceFileGraph);

            foreach (var(moduleDeclaration, moduleSourceFile) in sourceFilesByModuleDeclaration)
            {
                if (cycles.TryGetValue(moduleSourceFile, out var cycle))
                {
                    if (cycle.Length == 1)
                    {
                        errorBuildersByModuleDeclaration[moduleDeclaration] = x => x.CyclicModuleSelfReference();
                    }
                    else
                    {
                        errorBuildersByModuleDeclaration[moduleDeclaration] = x => x.CyclicModule(cycle.Select(x => x.FileUri.LocalPath));
                    }
                }
            }

            return(sourceFileGraph);
        }
コード例 #5
0
 public void TestCycleWithTwoWays()
 {
     using (var env = new TestEnvironment())
     {
         env.CreateRepo("A", new Dictionary <string, DepsData>
         {
             { "full-build", new DepsData(null, new List <Dep> {
                     new Dep("B"), new Dep("C")
                 }) }
         });
         env.CreateRepo("C", new Dictionary <string, DepsData>
         {
             { "full-build", new DepsData(null, new List <Dep> {
                     new Dep("D")
                 }) }
         });
         env.CreateRepo("D", new Dictionary <string, DepsData>
         {
             { "full-build", new DepsData(null, new List <Dep> {
                     new Dep("C")
                 }) }
         });
         Helper.SetWorkspace(env.RemoteWorkspace);
         var cycle = CycleDetector.TryFindCycle("A");
         Assert.AreEqual(new[] { "A/full-build", "C/full-build", "D/full-build", "C/full-build" }, cycle.ToArray());
     }
 }
コード例 #6
0
 public void TestNoCycleInDirectedGraph()
 {
     using (var env = new TestEnvironment())
     {
         env.CreateRepo("A", new Dictionary <string, DepsData>
         {
             { "full-build", new DepsData(null, new List <Dep> {
                     new Dep("B"), new Dep("C")
                 }) }
         });
         env.CreateRepo("B", new Dictionary <string, DepsData>
         {
             { "full-build", new DepsData(null, new List <Dep> {
                     new Dep("D")
                 }) }
         });
         env.CreateRepo("C", new Dictionary <string, DepsData>
         {
             { "full-build", new DepsData(null, new List <Dep> {
                     new Dep("D")
                 }) }
         });
         env.CreateRepo("D", new Dictionary <string, DepsData>
         {
             { "full-build", new DepsData(null, new List <Dep>()) }
         });
         Helper.SetWorkspace(env.RemoteWorkspace);
         var cycle = CycleDetector.TryFindCycle("A");
         Assert.IsNull(cycle);
     }
 }
コード例 #7
0
ファイル: CyclicCheckVisitor.cs プロジェクト: rwsanders/bicep
        private ImmutableDictionary <DeclaredSymbol, ImmutableArray <DeclaredSymbol> > FindCycles()
        {
            var symbolGraph = declarationAccessDict
                              .SelectMany(kvp => kvp.Value.Select(x => bindings[x]).OfType <DeclaredSymbol>().Select(x => (kvp.Key, x)))
                              .ToLookup(x => x.Item1, x => x.Item2);

            return(CycleDetector <DeclaredSymbol> .FindCycles(symbolGraph));
        }
コード例 #8
0
        public void ExampleHistoryRepeatItselfTest(string fileName, long expectedSteps)
        {
            var exampleLoader = new AlternateExampleLoader(fileName);

            var cycleDetector = new CycleDetector(exampleLoader.MoonsPositions);

            var cycleSteps = cycleDetector.FindCycleSteps();

            Assert.Equal(expectedSteps, cycleSteps);
        }
コード例 #9
0
ファイル: MainViewModel.cs プロジェクト: Forichok/Graphs
        private void CheckCycle()
        {
            var diGraph = DiGraph <string> .GetDiGraph(Model.NodesSource.Cast <NodeModel>(), Model.LinksSource.Cast <LinkModel>());

            var algorithm = new CycleDetector <string>();

            var HasCycle = algorithm.HasCycle(diGraph);

            MessageBox.Show(HasCycle.ToString());
        }
コード例 #10
0
        public void DoesNotThrowWhenThereAreNoCycles()
        {
            var mockContainer = new Mock <IContainer>();

            mockContainer.Setup(x => x.GetDependencies(typeof(A)))
            .Returns(new[] { typeof(B) });

            mockContainer.Setup(x => x.GetDependencies(typeof(B)))
            .Returns(new[] { typeof(C) });

            CycleDetector.CheckForCycles(typeof(A), mockContainer.Object);
        }
コード例 #11
0
 public GetCommand()
     : base(
         new CommandSettings
 {
     LogPerfix          = "GET",
     LogFileName        = "get",
     MeasureElapsedTime = true,
     Location           = CommandSettings.CommandLocation.WorkspaceDirectory
 })
 {
     cycleDetector = new CycleDetector();
 }
コード例 #12
0
        /// <summary>
        /// Analyses database tables. Reports messages when a set of foreign key relationships forms a cycle.
        /// </summary>
        /// <param name="tables">A set of database tables.</param>
        /// <param name="cancellationToken">A cancellation token used to interrupt analysis.</param>
        /// <returns>A set of linting messages used for reporting. An empty set indicates no issues discovered.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="tables"/> is <c>null</c>.</exception>
        public IAsyncEnumerable <IRuleMessage> AnalyseTables(IEnumerable <IRelationalDatabaseTable> tables, CancellationToken cancellationToken = default)
        {
            if (tables == null)
            {
                throw new ArgumentNullException(nameof(tables));
            }

            var cycleDetector = new CycleDetector();
            var cycles        = cycleDetector.GetCyclePaths(tables.ToList());

            return(cycles.Select(BuildMessage).ToAsyncEnumerable());
        }
コード例 #13
0
        public void Calculate_cykl()
        {
            var odbiorcy = new List <InputData>()
            {
                new InputData(0, InputType.Odbiorca, 10, 30),
                new InputData(1, InputType.Odbiorca, 28, 25),
                new InputData(2, InputType.Odbiorca, 27, 30),
                new InputData(3, InputType.Odbiorca, 50, null, true)
            };

            var dostawcy = new List <InputData>()
            {
                new InputData(0, InputType.Dostawca, 20, 10),
                new InputData(1, InputType.Dostawca, 30, 12),
                new InputData(2, InputType.Odbiorca, 65, null, true)
            };

            var datagrid = Utility.CreateEmptyCellGrid(dostawcy.Count, odbiorcy.Count);

            datagrid[0][0].KosztyJednostkowe = 8;
            datagrid[0][1].KosztyJednostkowe = 14;
            datagrid[0][2].KosztyJednostkowe = 17;

            datagrid[1][0].KosztyJednostkowe = 12;
            datagrid[1][1].KosztyJednostkowe = 9;
            datagrid[1][2].KosztyJednostkowe = 19;

            datagrid[0][3].IsVirtual = true;
            datagrid[1][3].IsVirtual = true;
            datagrid[2][3].IsVirtual = true;

            datagrid[2][0].IsVirtual = true;
            datagrid[2][1].IsVirtual = true;
            datagrid[2][2].IsVirtual = true;

            var iteracja = new IterationProfit(datagrid, JobType.Profit, 1);

            iteracja.CalculateZysk(dostawcy, odbiorcy);
            iteracja.CalculatePrzydzial(dostawcy, odbiorcy);
            iteracja.CalculateWspolczynnikiAlfaAndBeta();
            iteracja.CalculateDeltyNiebazowe();

            var cycleDetector = new CycleDetector(iteracja.DataGrid, CycleBaseType.Maximizing).Detect();
            var points = cycleDetector.WyznaczonyCykl.ToPointsList();
            var expectedPoints = new string[] { "13", "12", "22", "23" }.ToList();

            Assert.IsTrue(expectedPoints.Contains(points[0].Id));
            Assert.IsTrue(expectedPoints.Contains(points[1].Id));
            Assert.IsTrue(expectedPoints.Contains(points[2].Id));
            Assert.IsTrue(expectedPoints.Contains(points[3].Id));

            Assert.AreEqual(2, cycleDetector.FindPrzydzialDoOptymalizacji());
        }
コード例 #14
0
        public void ThrowsExceptionWhenCycleExists()
        {
            var mockContainer = new Mock <IContainer>();

            mockContainer.Setup(x => x.GetDependencies(typeof(A)))
            .Returns(new[] { typeof(B) });

            mockContainer.Setup(x => x.GetDependencies(typeof(B)))
            .Returns(new[] { typeof(C) });

            mockContainer.Setup(x => x.GetDependencies(typeof(C)))
            .Returns(new[] { typeof(A) });

            CycleDetector.CheckForCycles(typeof(A), mockContainer.Object);
        }
コード例 #15
0
        public async Task RenderAsync(CancellationToken cancellationToken = default)
        {
            if (!ExportDirectory.Exists)
            {
                ExportDirectory.Create();
            }

            var cycleDetector = new CycleDetector();
            var cycles        = cycleDetector.GetCyclePaths(Tables);
            var hasCycles     = cycles.Count > 0;

            // TODO acutlly use the canellation tokens here
            await ExportInsertionOrderAsync(hasCycles, cancellationToken).ConfigureAwait(false);
            await ExportDeletionOrderAsync(hasCycles, cancellationToken).ConfigureAwait(false);
        }
コード例 #16
0
        public void CycleIsNotDetectedForNonCycledGraph()
        {
            var graph = new[]
            {
                new GraphVertex <int>
                {
                    Value            = 1,
                    AdjacentVertices = new System.Collections.Generic.List <int> {
                        1
                    }
                },
                new GraphVertex <int>
                {
                    Value = 2,
                },
            };

            Assert.False(CycleDetector.IsCyclic(graph));
        }
コード例 #17
0
        protected override int Execute()
        {
            string workspace = Directory.GetCurrentDirectory();

            if (!Helper.IsCurrentDirectoryModule(Path.Combine(workspace, module)))
            {
                throw new CementTrackException($"{workspace} is not cement workspace directory.");
            }

            configuration = string.IsNullOrEmpty(configuration) ? "full-build" : configuration;

            Log.Info("Updating packages");
            PackageUpdater.UpdatePackages();

            GetModule();
            CycleDetector.WarnIfCycle(module, configuration, Log);

            Log.Info("SUCCESS get " + module);
            return(0);
        }
コード例 #18
0
 public void TestSimpleCycle()
 {
     using (var env = new TestEnvironment())
     {
         env.CreateRepo("A", new Dictionary <string, DepsContent>
         {
             { "full-build", new DepsContent(null, new List <Dep> {
                     new Dep("B")
                 }) }
         });
         env.CreateRepo("B", new Dictionary <string, DepsContent>
         {
             { "full-build", new DepsContent(null, new List <Dep> {
                     new Dep("A")
                 }) }
         });
         Helper.SetWorkspace(env.RemoteWorkspace);
         var cycle = CycleDetector.TryFindCycle("A");
         Assert.AreEqual(new[] { "A/full-build", "B/full-build", "A/full-build" }, cycle.ToArray());
     }
 }
コード例 #19
0
 public void TestNoCycleIfDifferentConfigs()
 {
     using (var env = new TestEnvironment())
     {
         env.CreateRepo("A", new Dictionary <string, DepsData>
         {
             { "full-build", new DepsData(null, new List <Dep> {
                     new Dep("B")
                 }) },
             { "client", new DepsData(null, new List <Dep>()) }
         });
         env.CreateRepo("B", new Dictionary <string, DepsData>
         {
             { "full-build", new DepsData(null, new List <Dep> {
                     new Dep("A", null, "client")
                 }) }
         });
         Helper.SetWorkspace(env.RemoteWorkspace);
         var cycle = CycleDetector.TryFindCycle("A/full-build");
         Assert.IsNull(cycle);
     }
 }
コード例 #20
0
        private void ReportFailuresForCycles()
        {
            var syntaxTreeGraph = syntaxTrees.Values.OfType <SyntaxTree>()
                                  .SelectMany(tree => GetModuleSyntaxes(tree).Where(moduleLookup.ContainsKey).Select(x => moduleLookup[x]).Distinct().Select(x => (tree, x)))
                                  .ToLookup(x => x.Item1, x => x.Item2);

            var cycles = CycleDetector <SyntaxTree> .FindCycles(syntaxTreeGraph);

            foreach (var kvp in moduleLookup)
            {
                if (cycles.TryGetValue(kvp.Value, out var cycle))
                {
                    if (cycle.Length == 1)
                    {
                        moduleFailureLookup[kvp.Key] = x => x.CyclicModuleSelfReference();
                    }
                    else
                    {
                        moduleFailureLookup[kvp.Key] = x => x.CyclicModule(cycle.Select(x => x.FileUri.LocalPath));
                    }
                }
            }
        }
コード例 #21
0
 public void TestCycleWithDefaultConfig()
 {
     using (var env = new TestEnvironment())
     {
         env.CreateRepo("A", new Dictionary <string, DepsData>
         {
             { "full-build", new DepsData(null, new List <Dep> {
                     new Dep("B")
                 }) },
             { "client *default", new DepsData(null, new List <Dep> {
                     new Dep("B")
                 }) }
         });
         env.CreateRepo("B", new Dictionary <string, DepsData>
         {
             { "full-build", new DepsData(null, new List <Dep> {
                     new Dep("A", null, "full-build")
                 }) }
         });
         Helper.SetWorkspace(env.RemoteWorkspace);
         var cycle = CycleDetector.TryFindCycle("A");
         Assert.AreEqual(new[] { "A/client", "B/full-build", "A/full-build", "B/full-build" }, cycle);
     }
 }
コード例 #22
0
        public void Graph_Cycle_Detection_Tests()
        {
            var graph = new DiGraph <char>();

            graph.AddVertex('A');
            graph.AddVertex('B');
            graph.AddVertex('C');
            graph.AddVertex('D');
            graph.AddVertex('E');
            graph.AddVertex('F');
            graph.AddVertex('G');
            graph.AddVertex('H');


            graph.AddEdge('A', 'B');
            graph.AddEdge('B', 'C');
            graph.AddEdge('C', 'A');

            graph.AddEdge('C', 'D');
            graph.AddEdge('D', 'E');

            graph.AddEdge('E', 'F');
            graph.AddEdge('F', 'G');
            graph.AddEdge('G', 'E');

            graph.AddEdge('F', 'H');

            var algo = new CycleDetector <char>();

            Assert.IsTrue(algo.HasCycle(graph));

            graph.RemoveEdge('C', 'A');
            graph.RemoveEdge('G', 'E');

            Assert.IsFalse(algo.HasCycle(graph));
        }
コード例 #23
0
        public void Graph_Cycle_Detection_AdjancencyListGraph_Tests()
        {
            var graph = new Advanced.Algorithms.DataStructures.Graph.AdjacencyList.DiGraph <char>();

            graph.AddVertex('A');
            graph.AddVertex('B');
            graph.AddVertex('C');
            graph.AddVertex('D');
            graph.AddVertex('E');
            graph.AddVertex('F');
            graph.AddVertex('G');
            graph.AddVertex('H');


            graph.AddEdge('A', 'B');
            graph.AddEdge('B', 'C');
            graph.AddEdge('C', 'A');

            graph.AddEdge('C', 'D');
            graph.AddEdge('D', 'E');

            graph.AddEdge('E', 'F');
            graph.AddEdge('F', 'G');
            graph.AddEdge('G', 'E');

            graph.AddEdge('F', 'H');

            var algorithm = new CycleDetector <char>();

            Assert.IsTrue(algorithm.HasCycle(graph));

            graph.RemoveEdge('C', 'A');
            graph.RemoveEdge('G', 'E');

            Assert.IsFalse(algorithm.HasCycle(graph));
        }
コード例 #24
0
        public static void GetCyclePaths_GivenTablesWithCycle_ReturnsEmptyCollection()
        {
            var cycleDetector = new CycleDetector();

            var mockChildKey = new Mock <IDatabaseKey>();

            mockChildKey.Setup(c => c.KeyType).Returns(DatabaseKeyType.Foreign);
            var childKey = mockChildKey.Object;

            var mockParentKey = new Mock <IDatabaseKey>();

            mockParentKey.Setup(p => p.KeyType).Returns(DatabaseKeyType.Primary);
            var parentKey = mockParentKey.Object;

            // create tables with no cycle where the path is a -> b -> c -> a
            var tableAMock = new Mock <IRelationalDatabaseTable>();

            tableAMock.Setup(t => t.Name).Returns(Identifier.CreateQualifiedIdentifier("a"));
            tableAMock.Setup(t => t.ParentKeys).Returns(new[]
            {
                new DatabaseRelationalKey(
                    Identifier.CreateQualifiedIdentifier("a"),
                    childKey,
                    Identifier.CreateQualifiedIdentifier("b"),
                    parentKey,
                    ReferentialAction.NoAction,
                    ReferentialAction.NoAction
                    )
            });

            var tableBMock = new Mock <IRelationalDatabaseTable>();

            tableBMock.Setup(t => t.Name).Returns(Identifier.CreateQualifiedIdentifier("b"));
            tableBMock.Setup(t => t.ParentKeys).Returns(new[]
            {
                new DatabaseRelationalKey(
                    Identifier.CreateQualifiedIdentifier("b"),
                    childKey,
                    Identifier.CreateQualifiedIdentifier("c"),
                    parentKey,
                    ReferentialAction.NoAction,
                    ReferentialAction.NoAction
                    )
            });

            var tableCMock = new Mock <IRelationalDatabaseTable>();

            tableCMock.Setup(t => t.Name).Returns(Identifier.CreateQualifiedIdentifier("c"));
            tableCMock.Setup(t => t.ParentKeys).Returns(new[]
            {
                new DatabaseRelationalKey(
                    Identifier.CreateQualifiedIdentifier("c"),
                    childKey,
                    Identifier.CreateQualifiedIdentifier("a"),
                    parentKey,
                    ReferentialAction.NoAction,
                    ReferentialAction.NoAction
                    )
            });

            var tables = new[]
            {
                tableAMock.Object,
                tableBMock.Object,
                tableCMock.Object
            };

            var result = cycleDetector.GetCyclePaths(tables);

            var cycleTableNames = result.SelectMany(c => c.Select(t => t.LocalName)).ToList();
            var expectedCycle   = new[] { "a", "b", "c" };

            Assert.Multiple(() =>
            {
                Assert.That(result, Has.Exactly(1).Items);
                Assert.That(cycleTableNames, Has.Exactly(3).Items);
                Assert.That(cycleTableNames, Is.EquivalentTo(expectedCycle));
            });
        }
コード例 #25
0
        public static void GetCyclePaths_GivenTablesWithNoCycle_ReturnsEmptyCollection()
        {
            var cycleDetector = new CycleDetector();

            var mockChildKey = new Mock <IDatabaseKey>();

            mockChildKey.Setup(c => c.KeyType).Returns(DatabaseKeyType.Foreign);
            var childKey = mockChildKey.Object;

            var mockParentKey = new Mock <IDatabaseKey>();

            mockParentKey.Setup(p => p.KeyType).Returns(DatabaseKeyType.Primary);
            var parentKey = mockParentKey.Object;

            // create tables with no cycle where the path is a -> b -> c
            var tableAMock = new Mock <IRelationalDatabaseTable>();

            tableAMock.Setup(t => t.Name).Returns(Identifier.CreateQualifiedIdentifier("a"));
            tableAMock.Setup(t => t.ParentKeys).Returns(new[]
            {
                new DatabaseRelationalKey(
                    Identifier.CreateQualifiedIdentifier("a"),
                    childKey,
                    Identifier.CreateQualifiedIdentifier("b"),
                    parentKey,
                    ReferentialAction.NoAction,
                    ReferentialAction.NoAction
                    )
            });

            var tableBMock = new Mock <IRelationalDatabaseTable>();

            tableBMock.Setup(t => t.Name).Returns(Identifier.CreateQualifiedIdentifier("b"));
            tableBMock.Setup(t => t.ParentKeys).Returns(new[]
            {
                new DatabaseRelationalKey(
                    Identifier.CreateQualifiedIdentifier("b"),
                    childKey,
                    Identifier.CreateQualifiedIdentifier("c"),
                    parentKey,
                    ReferentialAction.NoAction,
                    ReferentialAction.NoAction
                    )
            });

            var tableCMock = new Mock <IRelationalDatabaseTable>();

            tableCMock.Setup(t => t.Name).Returns(Identifier.CreateQualifiedIdentifier("c"));
            tableCMock.Setup(t => t.ParentKeys).Returns(Array.Empty <IDatabaseRelationalKey>());

            var tables = new[]
            {
                tableAMock.Object,
                tableBMock.Object,
                tableCMock.Object
            };

            var result = cycleDetector.GetCyclePaths(tables);

            Assert.That(result, Is.Empty);
        }
コード例 #26
0
 void OnChipNetworkModified()
 {
     CycleDetector.MarkAllCycles(this);
 }
コード例 #27
0
 public void Init()
 {
     this.storage   = new Mock <IMetaDataStorage>();
     this.underTest = new CycleDetector(this.storage.Object);
 }
コード例 #28
0
        /// <summary>
        /// Finds and initializes all property dependencies expressed via
        /// <see cref="T:ESRI.ArcLogistics.Data.PropertyDependsOnAttribute"/> attribute.
        /// </summary>
        /// <returns>Dictionary mapping names of source properties to a list
        /// of dependendent property names.</returns>
        private IDictionary<string, List<string>> _InitPropertyDependencies()
        {
            var bindingFlags =
                BindingFlags.Instance |
                BindingFlags.NonPublic |
                BindingFlags.Public;
            var dependentProperties =
                from property in this.GetType().GetProperties(bindingFlags)
                from attribute in property.GetCustomAttributes<PropertyDependsOnAttribute>()
                where !string.IsNullOrEmpty(attribute.PropertyName)
                group property.Name by attribute.PropertyName;

            var dependencies = dependentProperties.ToDictionary(
                group => group.Key,
                group => group.ToList());

            var cycleDetector = new CycleDetector<string>(property =>
            {
                List<string> peers;
                if (dependencies.TryGetValue(property, out peers))
                {
                    return peers;
                }

                return Enumerable.Empty<string>();
            });
            foreach (var property in dependencies.Keys)
            {
                var cycle = cycleDetector.FindCycle(property);
                if (cycle.Any())
                {
                    throw new PropertyDependenciesCycleException(
                        property,
                        cycle);
                }
            }

            return dependencies;
        }
コード例 #29
0
        public override GridCell[][] CalculateNextIteration()
        {
            var cycleDetector = new CycleDetector(DataGrid, CycleBaseType.Maximizing).Detect();

            if (cycleDetector.Error.IsError)
            {
                Error = cycleDetector.Error;
                return(null);
            }

            IsOptimal = cycleDetector.IsOptimal;
            if (cycleDetector.IsOptimal)
            {
                IsCorrect = true;
                return(null);
            }

            var cycle = cycleDetector.WyznaczonyCykl;

            Cycle = cycle;
            var przydzial = cycleDetector.FindPrzydzialDoOptymalizacji();

            var nextIterationGrid = Utility.CreateEmptyCellGrid(DataGrid.Length, DataGrid[0].Length);
            var cyclePoints       = cycle.ToPointsList();

            var poz_el      = cycle.Start.Id;
            var punktyCyklu = cyclePoints.ToList();

            punktyCyklu.Remove(punktyCyklu.Single(e => e.Id == poz_el));
            var p1_negatywny = punktyCyklu.Single(x => x.Y == int.Parse(poz_el[0].ToString()));

            punktyCyklu.Remove(p1_negatywny);
            var p2_negatywny = punktyCyklu.Single(x => x.X == int.Parse(poz_el[1].ToString()));

            punktyCyklu.Remove(p2_negatywny);
            var p2_pozytywny = punktyCyklu.First();

            for (int j = 0; j < DataGrid.Length; j++)
            {
                for (int i = 0; i < DataGrid[j].Length; i++)
                {
                    nextIterationGrid[j][i].KosztyJednostkowe = DataGrid[j][i].KosztyJednostkowe;
                    nextIterationGrid[j][i].Zysk      = DataGrid[j][i].Zysk;
                    nextIterationGrid[j][i].IsVirtual = DataGrid[j][i].IsVirtual;

                    var wsp = cyclePoints.SingleOrDefault(e => e.Id == DataGrid[j][i].Id);
                    if (wsp is null)
                    {
                        nextIterationGrid[j][i].Przydzial = DataGrid[j][i].Przydzial;
                    }
                    else
                    {
                        var isEx = true;
                        if (p1_negatywny.Id == wsp.Id || p2_negatywny.Id == wsp.Id)
                        {
                            if (DataGrid[j][i].Przydzial is null)
                            {
                                DataGrid[j][i].Przydzial = 0;
                                isEx = false;
                            }

                            nextIterationGrid[j][i].Przydzial = DataGrid[j][i].Przydzial - przydzial;
                        }
                        else
                        {
                            if (DataGrid[j][i].Przydzial is null)
                            {
                                DataGrid[j][i].Przydzial = 0;
                                isEx = false;
                            }

                            nextIterationGrid[j][i].Przydzial = DataGrid[j][i].Przydzial + przydzial;
                        }

                        if (nextIterationGrid[j][i].Przydzial == 0 && isEx)
                        {
                            nextIterationGrid[j][i].Przydzial = null;
                        }
                    }
                }
            }
            IsCorrect = true;
            return(nextIterationGrid);
        }
コード例 #30
0
        public static void GetCyclePaths_GivenNullTables_ThrowsArgumentNullException()
        {
            var cycleDetector = new CycleDetector();

            Assert.That(() => cycleDetector.GetCyclePaths(null), Throws.ArgumentNullException);
        }