コード例 #1
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var company = value as Company;

            if (company != null)
            {
                GraphEntity ge = new GraphEntity();

                ge.Name        = company.Name;
                ge.XAxisValues = new List <string>();
                ge.GraphLines  = new List <GraphLineEntity>();

                var sums = new List <double>();

                foreach (var invoiceRow in company.InvoiceRow)
                {
                    ge.XAxisValues.Add(invoiceRow.Invoice.Date.ToString());
                    sums.Add(invoiceRow.Sum);
                }

                ge.GraphLines.Add(new GraphLineEntity(ge.Name, "White", sums));

                return(ge);
            }

            return(null);
        }
コード例 #2
0
ファイル: SubGraphTest.cs プロジェクト: git-thinh/limada
        public void ChangeEdge()
        {
            var source   = new Graph <IGraphEntity, IGraphEdge> ();
            var sink     = new Graph <IGraphEntity, IGraphEdge> ();
            var subGraph = new SubGraph <IGraphEntity, IGraphEdge> (source, sink);

            var one   = new GraphEntity <string> ("1");
            var two   = new GraphEntity <string> ("2");
            var three = new GraphEntity <string> ("3");
            var link  = new GraphEdge(one, two);

            subGraph.Add(one);
            subGraph.Add(two);
            subGraph.Add(three);
            subGraph.Add(link);

            Assert.IsTrue(source.Contains(link), "source has to contain link");
            Assert.IsTrue(sink.Contains(link), "sink has to contain link");

            subGraph.ChangeEdge(link, three, true);

            Assert.IsFalse(sink.Edges(one).Contains(link), "sink.Edges (one) has not to contain link");
            Assert.IsFalse(source.Edges(one).Contains(link), "source.Edges (one) has not to contain link");
            Assert.IsFalse(subGraph.Edges(one).Contains(link), "subGraph.Edges (one) has not to contain link");
        }
コード例 #3
0
ファイル: NodeMapper.cs プロジェクト: m-wilczynski/Graphinder
        public static IEnumerable<NodeEntity> AsEntityModel(this IEnumerable<Node> models, GraphEntity graph)
        {
            if (models == null || graph == null) return new List<NodeEntity>();

            var nodes = models as IList<Node> ?? models.ToList();
            var counter = 0;
            var dict = nodes.FirstOrDefault(n => n != null).Parent.Nodes.Where(m => m != null)
                .Select(m =>
                {
                    var entity = new NodeEntity
                    {
                        Graph = graph,
                        Id = m.Id,
                        Key = m.Key,
                        Position = counter
                    };
                    counter++;
                    return entity;
                })
                .ToDictionary(m => m.Id, m => m);
            foreach (var model in nodes.Where(m => m != null))
            {
                NodeEntity entity = dict[model.Id];
                entity.Neighbours = new List<NodeEntity>();
                foreach (var ngh in model.Neighbours.Where(ngh => ngh != null))
                {
                    entity.Neighbours.Add(dict[ngh.Id]);
                }
            }
            return dict.Values.ToList();
        }
コード例 #4
0
        public void TestGraphPair(ISampleGraphFactory <IGraphEntity, IGraphEdge> source, ThingGraph target)
        {
            source.Count = 10;
            source.Populate();
            this.ReportDetail(source.GetType().FullName + "\t" + source.Count);

            var graphPair =
                new HollowGraphPair <IGraphEntity, IThing, IGraphEdge, ILink> (
                    source.Graph,
                    target,
                    new GraphEntity2ThingTransformer());

            var mapper = graphPair.Mapper;

            mapper.ConvertSinkSource();

            var convertionTesterOne = new MapperTester <IGraphEntity, IThing, IGraphEdge, ILink> ();

            mapper.ConvertSinkSource();
            convertionTesterOne.ProveConversion(graphPair.Sink, graphPair.Source, mapper.Get);

            var newEntity = new GraphEntity <string> ("new");

            graphPair.Add(newEntity);
            convertionTesterOne.ProveConversion(graphPair.Sink, graphPair.Source, mapper.Get);
        }
コード例 #5
0
        public static ProblemEntity AsEntityModelResolved(this IProblem model, GraphEntity graph = null)
        {
            if (model is MinimumVertexCover)
                return ((MinimumVertexCover) model).AsEntityModel(graph);

            throw new MappingNotImplementedException(model as BaseModel);
        }
コード例 #6
0
 protected override void CreateItems()
 {
     One    = new GraphEntity <string> ("One");
     Two    = new GraphEntity <string> ("Two");
     Three  = new GraphEntity <string> ("Three");
     Aside  = new GraphEntity <string> ("Aside");
     Single = new GraphEntity <string> ("Single");
 }
コード例 #7
0
        public static AlgorithmEntity AsEntityModelResolved(this IAlgorithm model, GraphEntity graph = null)
        {
            if (model is Core.Algorithms.GeneticAlgorithm.GeneticAlgorithm)
                return ((Core.Algorithms.GeneticAlgorithm.GeneticAlgorithm) model).AsEntityModel(graph);
            if (model is Core.Algorithms.SimulatedAnnealing.SimulatedAnnealing)
                return ((Core.Algorithms.SimulatedAnnealing.SimulatedAnnealing) model).AsEntityModel(graph);

            throw new MappingNotImplementedException(model as Algorithm);
        }
コード例 #8
0
        public static GraphEntity AsEntityModel(this Graph model)
        {
            var graph = new GraphEntity {
                Id = model.Id
            };

            graph.Nodes = model.Nodes.AsEntityModel(graph).ToList();
            return(graph);
        }
コード例 #9
0
        public static ProblemEntity AsEntityModelResolved(this IProblem model, GraphEntity graph = null)
        {
            if (model is MinimumVertexCover)
            {
                return(((MinimumVertexCover)model).AsEntityModel(graph));
            }

            throw new MappingNotImplementedException(model as BaseModel);
        }
コード例 #10
0
 private static IndividualEntity AsEntityModel(this Individual model, GraphEntity graph, ProblemEntity problem)
 {
     return new IndividualEntity
     {
         Id = model.Id,
         Graph = graph,
         Problem = problem,
         CurrentSolution = model.CurrentSolution.Select(Convert.ToByte).ToArray()
     };
 }
コード例 #11
0
 private static IndividualEntity AsEntityModel(this Individual model, GraphEntity graph, ProblemEntity problem)
 {
     return(new IndividualEntity
     {
         Id = model.Id,
         Graph = graph,
         Problem = problem,
         CurrentSolution = model.CurrentSolution.Select(Convert.ToByte).ToArray()
     });
 }
コード例 #12
0
        private static void BuildRelationshipGraph(DbContext dbContext, GraphEntity graphEntity, IDictionary <object, GraphItem> entityGraphMap, ICollection <GraphItem> result)
        {
            var entryEntity       = graphEntity.Entity;
            var entryEntityType   = entryEntity.GetType();
            var entityType        = dbContext.Model.FindEntityType(entryEntityType);
            var sourceEntryEntity = graphEntity.ParentEntity;

            GraphItem parentGraphItem;
            GraphItem graphItem;

            if (sourceEntryEntity != null)
            {
                parentGraphItem = entityGraphMap[sourceEntryEntity];
                graphItem       = parentGraphItem.Relationships.FirstOrDefault(y => y.EntityClrType == entryEntityType);
            }
            else
            {
                parentGraphItem = null;
                graphItem       = result.FirstOrDefault(y => y.EntityClrType == entryEntityType);
            }

            if (graphItem is null)
            {
                graphItem = new GraphItem
                {
                    EntityClrType = entryEntityType,
                    EntityType    = entityType,
                    Entities      =
                    {
                        graphEntity
                    },
                    Parent           = parentGraphItem,
                    ParentNavigation = graphEntity.InboundNavigation
                };

                if (parentGraphItem != null)
                {
                    parentGraphItem.Relationships.Add(graphItem);
                }
            }
            else
            {
                graphItem.Entities.Add(graphEntity);
            }

            // Always track in case the entryEntity has dependents
            if (entityGraphMap.ContainsKey(entryEntity) == false)
            {
                entityGraphMap.Add(entryEntity, graphItem);
            }

            result.Add(graphItem);
            EnumerateRelationshipValues(dbContext, entryEntity, entityType, entityGraphMap, result);
        }
コード例 #13
0
        public static AlgorithmEntity AsEntityModelResolved(this IAlgorithm model, GraphEntity graph = null)
        {
            if (model is Core.Algorithms.GeneticAlgorithm.GeneticAlgorithm)
            {
                return(((Core.Algorithms.GeneticAlgorithm.GeneticAlgorithm)model).AsEntityModel(graph));
            }
            if (model is Core.Algorithms.SimulatedAnnealing.SimulatedAnnealing)
            {
                return(((Core.Algorithms.SimulatedAnnealing.SimulatedAnnealing)model).AsEntityModel(graph));
            }

            throw new MappingNotImplementedException(model as Algorithm);
        }
コード例 #14
0
 public static MinimumVertexCoverEntity AsEntityModel(this MinimumVertexCover model, GraphEntity graph = null)
 {
     var outputGraph = graph ?? model.Graph.AsEntityModel();
     return new MinimumVertexCoverEntity
     {
         Id = model.Id,
         Graph = outputGraph,
         CurrentSolution = model.Graph.Nodes.Select(graphNode =>
         {
             return Convert.ToByte(model.CurrentSolution.Any(node => node.Id.Equals(graphNode.Id)));
         }).ToArray()
     };
 }
コード例 #15
0
ファイル: SubGraphTest.cs プロジェクト: git-thinh/limada
        public void EdgeNotInView()
        {
            var source   = new Graph <IGraphEntity, IGraphEdge> ();
            var sink     = new Graph <IGraphEntity, IGraphEdge>();
            var subGraph = new SubGraph <IGraphEntity, IGraphEdge> (source, sink);


            var one   = new GraphEntity <string> ("1");
            var two   = new GraphEntity <string>("2");
            var three = new GraphEntity <string>("3");

            source.Add(one);
            source.Add(two);
            source.Add(three);
            var link     = new GraphEdge(one, two);
            var linklink = new GraphEdge(link, three);

            source.Add(linklink);
            sink.Add(one);
            sink.Add(two);
            sink.Add(link);
            Assert.IsTrue(source.Contains(link), "source has to contain link");
            Assert.IsTrue(source.Contains(linklink), "source has to contain linklink");
            Assert.IsFalse(sink.Contains(linklink), "sink must not contain linklink");
            Assert.IsFalse(subGraph.Contains(linklink), "subGraph must not contain linklink");
            sink.Add(linklink);

            sink.Remove(link);
            Assert.IsFalse(subGraph.Contains(linklink), "subGraph must not contain linklink");

            sink.Add(link);

            foreach (var edge in subGraph.Fork(three))
            {
                Assert.IsFalse(edge.Equals(linklink), "subGraph must not contain linklink");
            }

            bool found = false;

            foreach (var edge in source.Fork(three))
            {
                if (edge == linklink)
                {
                    found = true;
                    break;
                }
            }
            Assert.IsTrue(found, "source.fork has to contain linklink");
        }
コード例 #16
0
 public static SimulatedAnnealingEntity AsEntityModel(this SimulatedAnnealing model, GraphEntity graph = null)
 {
     var usedGraph = graph ?? model.Graph.AsEntityModel();
     var problem = model.Problem.AsEntityModelResolved(graph);
     return new SimulatedAnnealingEntity
     {
         Id = model.Id,
         Graph = graph,
         CoolingRate = model.CoolingSetup.CoolingRate,
         CoolingStrategy = CoolingFactory.ProvideMappingType(model.CoolingSetup.CoolingStrategy),
         CurrentTemperature = model.CurrentTemperature,
         InitialTemperature = model.CoolingSetup.InitialTemperature,
         Problem = problem,
         TotalProcessorTimeCost = model.TotalProcessorTimeCost
     };
 }
コード例 #17
0
 public static GeneticAlgorithmEntity AsEntityModel(this GeneticAlgorithm model, GraphEntity graph = null)
 {
     var usedGraph = graph ?? model.Graph.AsEntityModel();
     var problem = model.Problem.AsEntityModelResolved(graph);
     return new GeneticAlgorithmEntity
     {
         Id = model.Id,
         Graph = graph,
         Problem = problem,
         SelectionStrategy = SelectionFactory.ProvideMappingType(model.GeneticOperators.SelectionStrategy),
         CrossoverStrategy = CrossoverFactory.ProvideMappingType(model.GeneticOperators.CrossoverStrategy),
         MutationStrategy = MutationFactory.ProvideMappingType(model.GeneticOperators.MutationStrategy),
         GenerationsToCome = (int)model.Settings.GenerationsToCome,
         InitialPopulationSize = (int)model.Settings.InitialPopulationSize,
         CrossoverProbability = model.Settings.CrossoverProbability,
         MutationProbability = model.Settings.MutationProbability,
         WithElitistSelection = model.Settings.WithElitistSelection,
         CurrentPopulation = model.CurrentPopulation.AsEntityModel(graph, problem).ToList(),
         CurrentGeneration = (int)model.CurrentGeneration,
         TotalProcessorTimeCost = model.TotalProcessorTimeCost
     };
 }
コード例 #18
0
        public static Graph AsDomainModel(this GraphEntity entity)
        {
            List <EdgeMapping> edgesToAdd = new List <EdgeMapping>();

            var graph = new Graph(entity.Id);

            foreach (var node in entity.Nodes.OrderBy(e => e.Position))
            {
                graph.AddNode(node.Key, node.Id);
                edgesToAdd.AddRange(node.Neighbours
                                    .Where(ngh => ngh != null)
                                    .Select(ngh => new EdgeMapping {
                    FromKey = node.Key, ToKey = ngh.Key
                }));
            }
            foreach (var edge in edgesToAdd.Where(edge => !graph.ContainsEdge(edge.FromKey, edge.ToKey)))
            {
                graph.AddEdge(edge.FromKey, edge.ToKey);
            }

            return(graph);
        }
コード例 #19
0
        public static MinimumVertexCoverEntity AsEntityModel(this MinimumVertexCover model, GraphEntity graph = null)
        {
            var outputGraph = graph ?? model.Graph.AsEntityModel();

            return(new MinimumVertexCoverEntity
            {
                Id = model.Id,
                Graph = outputGraph,
                CurrentSolution = model.Graph.Nodes.Select(graphNode =>
                {
                    return Convert.ToByte(model.CurrentSolution.Any(node => node.Id.Equals(graphNode.Id)));
                }).ToArray()
            });
        }
コード例 #20
0
        public void CreateAndWriteGraph()
        {
            //Instantiate property set manager necessary to gather alignment names
            PropertySetManager psmPipeline = new PropertySetManager(
                Application.DocumentManager.MdiActiveDocument.Database,
                PSetDefs.DefinedSets.DriPipelineData);

            PSetDefs.DriPipelineData driPipelineData = new PSetDefs.DriPipelineData();

            //Counter to count all disjoined graphs
            int graphCount = 0;
            //Flag to signal the entry point subgraph
            bool isEntryPoint = false;
            //Stringbuilder to collect all disjoined graphs
            StringBuilder sbAll = new StringBuilder();

            sbAll.AppendLine("digraph G {");

            while (GraphEntities.Count > 0)
            {
                //Increment graph counter
                graphCount++;

                //Collection to keep track of visited nodes
                //To prevent looping for ever
                //And to be able to handle disjoined piping networks
                HashSet <Handle> visitedHandles = new HashSet <Handle>();

                //Determine starting entity
                //Criteria: Only one child -> means an end node AND largest DN of all not visited
                //Currently only for one network
                //Disjoined networks are not handled yet

                GraphEntity ge = GraphEntities.Where(x => x.Cons.Length == 1).MaxBy(x => x.LargestDn()).FirstOrDefault();

                //prdDbg(ge.OwnerHandle.ToString());
                if (ge == null)
                {
                    //throw new System.Exception("No entity found!");
                    prdDbg("ERROR: Graph not complete!!!");
                    foreach (var item in GraphEntities)
                    {
                        Entity owner = item.Owner;
                        Line   line  = new Line();
                        line.Layer      = "0";
                        line.StartPoint = new Point3d();
                        switch (owner)
                        {
                        case Polyline pline:
                            line.EndPoint = pline.GetPointAtDist(pline.Length / 2);
                            break;

                        case BlockReference br:
                            line.EndPoint = br.Position;
                            break;

                        default:
                            break;
                        }
                        line.AddEntityToDbModelSpace(Application.DocumentManager.MdiActiveDocument.Database);
                    }
                    break;
                }

                //Flag the entry point subgraph
                isEntryPoint = true;

                //Variable to cache previous handle to avoid backreferences
                Handle previousHandle = default;

                //Collection to collect the edges
                HashSet <Edge> edges = new HashSet <Edge>();

                //Collection to collect the subgraphs
                Dictionary <string, Subgraph> subgraphs = new Dictionary <string, Subgraph>();

                //Using a stack traversing strategy
                Stack <GraphEntity> stack = new Stack <GraphEntity>();
                //Put the first element on to the stack manually
                stack.Push(ge);
                //Iterate the stack until no connected nodes left
                while (stack.Count > 0)
                {
                    //Fetch the topmost entity on stack
                    GraphEntity current = stack.Pop();

                    //Determine the subgraph it is part of
                    string alName = psmPipeline.ReadPropertyString(current.Owner, driPipelineData.BelongsToAlignment);
                    //Fetch or create new subgraph object
                    Subgraph subgraph;
                    if (subgraphs.ContainsKey(alName))
                    {
                        subgraph = subgraphs[alName];
                    }
                    else
                    {
                        subgraph = new Subgraph(dB, ComponentTable, alName);
                        subgraphs.Add(alName, subgraph);
                    }
                    subgraph.Nodes.Add(current.OwnerHandle);

                    if (isEntryPoint)
                    {
                        subgraph.isEntryPoint = isEntryPoint;
                        isEntryPoint          = false;
                    }

                    //Iterate over current node's children
                    foreach (Con con in current.Cons)
                    {
                        //Find the child the con is referencing to
                        GraphEntity child = GraphEntities.Where(x => x.OwnerHandle == con.ConHandle).FirstOrDefault();
                        //if it is the con refering back to the parent -> skip it
                        if (child == default || child.OwnerHandle == current.OwnerHandle)
                        {
                            continue;
                        }
                        //Also skip if child has already been visited
                        //This prevents from making circular graphs I think
                        //Comment next line out to test circular graphs
                        //if (visitedHandles.Contains(child.OwnerHandle)) continue; <-- First solution
                        //Solution with caching of previous handle, it I don't think it works when backtracking to a branch -> there will be a double arrow
                        if (previousHandle != null && previousHandle == child.OwnerHandle)
                        {
                            continue;
                        }
                        //Try to control which cons get written by their type
                        //Build string
                        string ownEnd = con.OwnEndType.ToString();
                        string conEnd = con.ConEndType.ToString();
                        string key    = ownEnd + "-" + conEnd;
                        if (!allowedCombinations[key])
                        {
                            continue;
                        }

                        //Tries to prevent duplicate Main-Main edges by eliminating upstream Main-Main instance
                        //Doesn't work if recursion just returned from a branch, because previous is set the the
                        //Last node on the branch
                        if (key == "Main-Main" && con.ConHandle == previousHandle)
                        {
                            continue;
                        }

                        //Record the edge between nodes
                        edges.Add(new Edge(current.OwnerHandle, child.OwnerHandle));
                        //edges.Add(new Edge(current.OwnerHandle, child.OwnerHandle, key));
                        //If this child node is in visited collection -> skip, so we don't ger circular referencing
                        if (visitedHandles.Contains(child.OwnerHandle))
                        {
                            continue;
                        }
                        //If the node has not been visited yet, then put it on the stack
                        stack.Push(child);
                    }
                    //When current iteration completes, put the current node handle in the visited collection
                    visitedHandles.Add(current.OwnerHandle);
                    //Cache current node handle to avoid backreference
                    previousHandle = current.OwnerHandle;
                }

                //Write collected data
                //Stringbuilder to contain the overall file
                //This must be refactored when working with disjoined networks
                StringBuilder sb = new StringBuilder();
                sb.AppendLine($"subgraph G_{graphCount} {{"); //First line of file stating a graph
                                                              //Set the shape of the nodes for whole graph
                sb.AppendLine("node [shape=record];");

                //Write edges
                foreach (Edge edge in edges)
                {
                    sb.AppendLine(edge.ToString("->"));
                }

                //Write subgraphs
                int i = 0;
                foreach (var sg in subgraphs)
                {
                    i++;
                    sb.Append(sg.Value.WriteSubgraph(i));
                }

                //Add closing curly brace correspoinding to the first line
                sb.AppendLine("}");
                //Append current disjoined graph to all collector
                sbAll.Append(sb.ToString());

                //using (System.IO.StreamWriter file = new System.IO.StreamWriter($"C:\\Temp\\MyGraph_{graphCount}.dot"))
                //{
                //    file.WriteLine(sb.ToString()); // "sb" is the StringBuilder
                //}

                //Modify the GraphEntities to remove visited entities
                GraphEntities = GraphEntities.ExceptWhere(x => visitedHandles.Contains(x.OwnerHandle)).ToHashSet();
            }

            //Closing brace of the main graph
            sbAll.AppendLine("}");

            //Check or create directory
            if (!Directory.Exists(@"C:\Temp\"))
            {
                Directory.CreateDirectory(@"C:\Temp\");
            }

            //Write the collected graphs to one file
            using (System.IO.StreamWriter file = new System.IO.StreamWriter($"C:\\Temp\\MyGraph.dot"))
            {
                file.WriteLine(sbAll.ToString()); // "sb" is the StringBuilder
            }
        }
コード例 #21
0
 public static IEnumerable<IndividualEntity> AsEntityModel(this IEnumerable<Individual> models, GraphEntity graph, ProblemEntity problem)
 {
     if (models == null) return new List<IndividualEntity>();
     return models.Where(m => m != null).Select(m => m.AsEntityModel(graph, problem));
 }
コード例 #22
0
 public static GraphEntity AsEntityModel(this Graph model)
 {
     var graph = new GraphEntity { Id = model.Id };
     graph.Nodes = model.Nodes.AsEntityModel(graph).ToList();
     return graph;
 }
コード例 #23
0
 public static IEnumerable <IndividualEntity> AsEntityModel(this IEnumerable <Individual> models, GraphEntity graph, ProblemEntity problem)
 {
     if (models == null)
     {
         return(new List <IndividualEntity>());
     }
     return(models.Where(m => m != null).Select(m => m.AsEntityModel(graph, problem)));
 }
コード例 #24
0
ファイル: IRAPHME.cs プロジェクト: DnKeith/IRAPDCSProjects
        /// <summary>
        ///    保存日志到MongoDB
        /// </summary>
        /// <param name="CommunityID"></param>
        /// <param name="T133LeafID"></param>
        /// <param name="SysLogID"></param>
        /// <param name="T216LeafID"></param>
        /// <param name="T102LeafID"></param>
        /// <param name="T107LeafID"></param>
        /// <param name="WIP_Code"></param>
        /// <param name="WIP_ID_Type_Code"></param>
        /// <param name="WIP_ID_Code"></param>
        /// <param name="Params"></param>
        /// <returns></returns>

        public string SaveFactMongodbLog(string ExCode, int CommunityID, int T133LeafID, Int64 SysLogID
                                         , int T216LeafID, int T102LeafID, int T107LeafID
                                         , string WIP_Code, string WIP_ID_Type_Code, string WIP_ID_Code
                                         , string Params)
        {
            string sqlconnString = string.Empty;

            dynamic res = new System.Dynamic.ExpandoObject();

            try
            {
                string UserCode = "";
                if (SysLogID.ToString() == null)
                {
                    SysLogID = 1;
                }
                if (T216LeafID.ToString() == null)
                {
                    SysLogID = 0;
                }
                if (T107LeafID.ToString() == null)
                {
                    SysLogID = 0;
                }
                if (WIP_Code == null)
                {
                    WIP_Code = "";
                }
                if (WIP_ID_Type_Code == null)
                {
                    WIP_ID_Type_Code = "";
                }
                if (WIP_ID_Code == null)
                {
                    WIP_ID_Code = "";
                }
                if (Params == null)
                {
                    Params = "";
                }
                string StoreTime     = DateTime.Now.ToString();
                string strconn       = "mongodb://192.168.57.12:27017";
                string SeqServerAddr = "192.168.57.13";
                ReadConfig.Read();
                if (ReadConfig.Parameters.ContainsKey("MongodbConnectStr"))
                {
                    strconn = ReadConfig.Parameters["MongodbConnectStr"].ToString();
                }
                /*  sqlconnString = ReadConfig.Parameters["ConnectionString"].ToString()*/;
                if (ReadConfig.Parameters.ContainsKey("SeqServerAddr"))
                {
                    SeqServerAddr = ReadConfig.Parameters["SeqServerAddr"].ToString();
                }
                //创建数据库链接
                MongoClient client = new MongoClient(strconn);
                //获得数据库cnblogs
                IMongoDatabase db = client.GetDatabase(MongoDBName);
                IMongoCollection <GraphEntity> logTBL
                    = db.GetCollection <GraphEntity>("IRAPDCSLog");
                GraphEntity row = new GraphEntity();
                row.LogID            = IRAPUtil.IRAPSocketClient.GetSequenceNo(SeqServerAddr, "NextSysLogID", 1);
                row.ExCode           = ExCode;
                row.CommunityID      = CommunityID;
                row.UserCode         = UserCode;
                row.SysLogID         = SysLogID;
                row.T133LeafID       = T133LeafID;
                row.T216LeafID       = T216LeafID;
                row.T102LeafID       = T102LeafID;
                row.T107LeafID       = T107LeafID;
                row.WIP_Code         = WIP_Code;
                row.WIP_ID_Type_Code = WIP_ID_Type_Code;
                row.WIP_ID_Code      = WIP_ID_Code;
                row.Params           = Params;
                row.StoreTime        = StoreTime;
                logTBL.InsertOne(row);
                res.ErrCode = 0;
                res.ErrText = "保存成功!";
                return(JsonConvert.SerializeObject(res));
            }
            catch (Exception err)
            {
                res.ErrCode = 9999;
                res.ErrText = "保存数据发生异常:" + err.Message;
                return(JsonConvert.SerializeObject(res));
            }
        }
コード例 #25
0
        public static SimulatedAnnealingEntity AsEntityModel(this SimulatedAnnealing model, GraphEntity graph = null)
        {
            var usedGraph = graph ?? model.Graph.AsEntityModel();
            var problem   = model.Problem.AsEntityModelResolved(graph);

            return(new SimulatedAnnealingEntity
            {
                Id = model.Id,
                Graph = graph,
                CoolingRate = model.CoolingSetup.CoolingRate,
                CoolingStrategy = CoolingFactory.ProvideMappingType(model.CoolingSetup.CoolingStrategy),
                CurrentTemperature = model.CurrentTemperature,
                InitialTemperature = model.CoolingSetup.InitialTemperature,
                Problem = problem,
                TotalProcessorTimeCost = model.TotalProcessorTimeCost
            });
        }
コード例 #26
0
        public static IEnumerable <NodeEntity> AsEntityModel(this IEnumerable <Node> models, GraphEntity graph)
        {
            if (models == null || graph == null)
            {
                return(new List <NodeEntity>());
            }

            var nodes   = models as IList <Node> ?? models.ToList();
            var counter = 0;
            var dict    = nodes.FirstOrDefault(n => n != null).Parent.Nodes.Where(m => m != null)
                          .Select(m =>
            {
                var entity = new NodeEntity
                {
                    Graph    = graph,
                    Id       = m.Id,
                    Key      = m.Key,
                    Position = counter
                };
                counter++;
                return(entity);
            })
                          .ToDictionary(m => m.Id, m => m);

            foreach (var model in nodes.Where(m => m != null))
            {
                NodeEntity entity = dict[model.Id];
                entity.Neighbours = new List <NodeEntity>();
                foreach (var ngh in model.Neighbours.Where(ngh => ngh != null))
                {
                    entity.Neighbours.Add(dict[ngh.Id]);
                }
            }
            return(dict.Values.ToList());
        }
コード例 #27
0
        public IMcCeibMetrics CreateMetrics(List <Module> source)
        {
            IMcCeibMetrics metrics = new Metrics();

            metrics.GraphEntities = new Dictionary <string, List <GraphEntity> >();
            Stack <GraphEntity> innert = new Stack <GraphEntity>();

            foreach (var module in source)
            {
                List <GraphEntity> graphEntities = new List <GraphEntity>();
                int number   = -1;
                var analyzed = _lexicalAnalyzer.AnalyzeSource(Encoding.UTF8.GetString(module.Source)).ToArray();
                for (int i = 0; i < analyzed.Length; i++)
                {
                    var         item       = analyzed[i];
                    GraphEntity lastInline = null;
                    var         ge         = new GraphEntity()
                    {
                        LineNumber = item.LineNumber,
                        Number     = i,
                        Comment    = item.Comment
                    };
                    if (item.IsProcedure == true)
                    {
                        ge.Type = GraphEntityTypesEnum.StartProcedure;
                    }
                    else if (item.IsProcedure == false)
                    {
                        ge.Type = GraphEntityTypesEnum.EndProcedure;
                    }
                    else if (item.BranchType == BranchType.If)
                    {
                        innert.Push(ge);
                        ge.Type = GraphEntityTypesEnum.If;
                        var connects = analyzed
                                       .Where(x => x.ConnectedFrom.Any(y => y == item.LineNumber))?
                                       .OrderBy(x => x.BranchType)
                                       .ToList();
                        if (connects.Count == 2 || connects.Count == 1 && connects[0].ConnectedFrom.Count == 2)
                        {
                            var empty = new GraphEntity()
                            {
                                Type       = GraphEntityTypesEnum.Empty,
                                LineNumber = item.LineNumber + 1,
                                Number     = number
                            };
                            number--;
                            ge.ConnectedTo.Add(connects.Count == 2
                                ? analyzed.IndexOf(connects[1])
                                : analyzed.IndexOf(connects[0]));
                            ge.ConnectedTo.Add(empty.Number);
                            if (analyzed[i + 1].BranchType == BranchType.IfEnd || analyzed[i + 1].BranchType == BranchType.Else)
                            {
                                empty.ConnectedTo.Add(analyzed.IndexOf(connects[0]));
                            }
                            else
                            {
                                empty.ConnectedTo.Add(i + 1);
                                //TODO RETURN
                            }
                            graphEntities.Add(empty);
                        }
                    }
                    else if (item.BranchType == BranchType.Else)
                    {
                        ge.Type = GraphEntityTypesEnum.Else;
                        var empty = new GraphEntity()
                        {
                            Type       = GraphEntityTypesEnum.Empty,
                            LineNumber = item.LineNumber + 1,
                            Number     = number
                        };
                        number--;
                        ge.ConnectedTo.Add(empty.Number);
                        empty.ConnectedTo.AddRange(analyzed
                                                   .Where(x => x.ConnectedFrom.Any(y => y == item.LineNumber))?
                                                   .Select(analyzed.IndexOf));
                        graphEntities.Add(empty);
                    }
                    else if (item.BranchType == BranchType.ForOrWhile)
                    {
                        innert.Push(ge);

                        ge.Type = GraphEntityTypesEnum.Cycle;
                        var empty = new GraphEntity()
                        {
                            Type       = GraphEntityTypesEnum.Empty,
                            LineNumber = item.LineNumber + 1,
                            Number     = number
                        };
                        number--;
                        ge.ConnectedTo.Add(empty.Number);
                        if (analyzed[i + 1].BranchType == BranchType.ForOrWhileEnd)
                        {
                            empty.ConnectedTo.Add(ge.Number);
                        }
                        else
                        {
                            empty.ConnectedTo.Add(i + 1);
                            //TODO: ADD RETURN CONNECTION
                        }
                        ge.ConnectedTo.AddRange(analyzed
                                                .Where(x => x.ConnectedFrom.Any(y => y == item.LineNumber))?
                                                .Select(analyzed.IndexOf));
                        graphEntities.Add(empty);
                    }
                    else if (item.BranchType == BranchType.DoWhile)
                    {
                        innert.Push(ge);
                        ge.Type    = GraphEntityTypesEnum.Cycle;
                        ge.Comment = "do";
                    }
                    else if (item.BranchType == BranchType.IfEnd)
                    {
                        innert.Pop();
                        ge.Type = GraphEntityTypesEnum.Empty;
                    }
                    else if (item.BranchType == BranchType.DoWhileEnd)
                    {
                        innert.Pop();

                        ge.Type = GraphEntityTypesEnum.Empty;
                        ge.ConnectedTo.AddRange(analyzed
                                                .Where(x => x.LineNumber == item.ConnectedFrom[0])
                                                ?.Select(analyzed.IndexOf));
                    }
                    else if (item.BranchType == BranchType.ForOrWhileEnd)
                    {
                        lastInline = innert.Pop();
                        if (graphEntities.Last() != lastInline)
                        {
                            graphEntities.Last().ConnectedTo = new List <int>()
                            {
                                lastInline.Number
                            };
                        }
                        ge.Type = GraphEntityTypesEnum.Empty;
                    }

                    var emptyEnt = new GraphEntity()
                    {
                        Type       = GraphEntityTypesEnum.Empty,
                        LineNumber = item.LineNumber + 1,
                        Number     = number,
                    };
                    if (i + 1 < analyzed.Length)
                    {
                        emptyEnt.ConnectedTo.Add(i + 1);
                    }

                    if (item.BranchType != BranchType.If && item.BranchType != BranchType.Else && item.BranchType != BranchType.ForOrWhile &&
                        item.IsProcedure != false)
                    {
                        number--;
                        ge.ConnectedTo.Add(emptyEnt.Number);
                    }

                    graphEntities.Add(ge);

                    if (item.BranchType != BranchType.If && item.BranchType != BranchType.Else && item.BranchType != BranchType.ForOrWhile &&
                        item.IsProcedure != false)
                    {
                        graphEntities.Add(emptyEnt);
                    }
                }

                metrics.GraphEntities.Add(
                    module.Path, graphEntities
                    );
            }

            metrics.ComplexityNumber = metrics.GraphEntities.Values.SelectMany(x => x).Count(x =>

                                                                                             x.Type == GraphEntityTypesEnum.If ||

                                                                                             x.Type == GraphEntityTypesEnum.Cycle) + 1;
            return(metrics);
        }
コード例 #28
0
        public static GeneticAlgorithmEntity AsEntityModel(this GeneticAlgorithm model, GraphEntity graph = null)
        {
            var usedGraph = graph ?? model.Graph.AsEntityModel();
            var problem   = model.Problem.AsEntityModelResolved(graph);

            return(new GeneticAlgorithmEntity
            {
                Id = model.Id,
                Graph = graph,
                Problem = problem,
                SelectionStrategy = SelectionFactory.ProvideMappingType(model.GeneticOperators.SelectionStrategy),
                CrossoverStrategy = CrossoverFactory.ProvideMappingType(model.GeneticOperators.CrossoverStrategy),
                MutationStrategy = MutationFactory.ProvideMappingType(model.GeneticOperators.MutationStrategy),
                GenerationsToCome = (int)model.Settings.GenerationsToCome,
                InitialPopulationSize = (int)model.Settings.InitialPopulationSize,
                CrossoverProbability = model.Settings.CrossoverProbability,
                MutationProbability = model.Settings.MutationProbability,
                WithElitistSelection = model.Settings.WithElitistSelection,
                CurrentPopulation = model.CurrentPopulation.AsEntityModel(graph, problem).ToList(),
                CurrentGeneration = (int)model.CurrentGeneration,
                TotalProcessorTimeCost = model.TotalProcessorTimeCost
            });
        }