/// <summary> /// Create a directed graph based on the provided connections (between node IDs) and a predefined set of input/output /// node IDs defined as being in a contiguous sequence starting at ID zero. /// </summary> /// <remarks> /// connectionList is required to be sorted by sourceID, TargetID. /// </remarks> public static DirectedGraph Create( IList <DirectedConnection> connectionList, int inputCount, int outputCount) { // Debug assert that the connections are sorted. Debug.Assert(SortUtils.IsSortedAscending(connectionList)); // Determine the full set of hidden node IDs. int inputOutputCount = inputCount + outputCount; var hiddenNodeIdArr = GetHiddenNodeIdArray(connectionList, inputOutputCount); // Compile a mapping from current nodeIDs to new IDs (i.e. removing gaps in the ID space). INodeIdMap nodeIdMap = DirectedGraphBuilderUtils.CompileNodeIdMap( inputOutputCount, hiddenNodeIdArr); // Extract/copy the neat genome connectivity graph into an array of DirectedConnection. // Notes. // The array contents will be manipulated, so copying this avoids modification of the genome's // connection gene list. // The IDs are substituted for node indexes here. ConnectionIdArrays connIdArrays = CopyAndMapIds(connectionList, nodeIdMap); // Construct and return a new DirectedGraph. int totalNodeCount = inputOutputCount + hiddenNodeIdArr.Length; return(new DirectedGraph(inputCount, outputCount, totalNodeCount, connIdArrays)); }
/// <summary> /// Split each IWeightedDirectedConnection in a list into an array of DirectedConnections(s), and an array of weights. /// Map the node IDs to indexes as we go. /// </summary> private static void CopyAndMapIds( IList <WeightedDirectedConnection <T> > connectionList, INodeIdMap nodeIdMap, out ConnectionIdArrays connIdArrays, out T[] weightArr) { int count = connectionList.Count; int[] srcIdArr = new int[count]; int[] tgtIdArr = new int[count]; weightArr = new T[count]; for (int i = 0; i < count; i++) { srcIdArr[i] = nodeIdMap.Map(connectionList[i].SourceId); tgtIdArr[i] = nodeIdMap.Map(connectionList[i].TargetId); weightArr[i] = connectionList[i].Weight; } connIdArrays = new ConnectionIdArrays(srcIdArr, tgtIdArr); }