public static ConnectionList Build(int leftPerceptrons, int rightPerceptrons, ConnectionProperties connectionProperties) { var connectionList = new ConnectionList(); for (int i = 0; i < leftPerceptrons; i++) { for (int j = 0; j < rightPerceptrons; j++) { connectionList.Add(new Connection(i + 1, j + 1, connectionProperties)); } } return connectionList; }
/// <summary> /// 检查连接是否正常 /// </summary> /// <param name="state"></param> private void OnTick(object state) { if (ErrorList.Count == 0) { return; } for (int i = 0; i < ErrorList.Count; i++) { var connS = ErrorList[i]; try { ErrorList[i].Error++; NpgsqlConnection conn = new NpgsqlConnection(connS.ConnectionString); conn.Open(); conn.Close(); ErrorList.RemoveAt(i); ConnectionList.Add(connS); Console.WriteLine("连接正常,重新放入连接池:[{0}]", connS.ConnectionString); } catch { } } }
/** * リストの設定 * 設定したいポイントがすでにリストにあるかどうか調べて、ない場合は追加する * @param point リストに追加したいポイント */ public void SetConnection(FieldConnectPoint point) { int i0; float tmp_f; Vector3 sub; bool flg; flg = true; for (i0 = 0; i0 < ConnectionList.Count; ++i0) { sub = point.Position - ConnectionList[i0].Position; tmp_f = sub.x * sub.x + sub.z * sub.z; if (tmp_f >= 0.1f) { continue; } flg = false; break; } if (flg != false) { ConnectionList.Add(point); } }
/// <summary> /// Create a network definition by querying the provided IBlackBox (typically a CPPN) with the /// substrate connection endpoints. /// </summary> /// <param name="blackbox">The HyperNEAT CPPN that defines the strength of connections between nodes on the substrate.</param> /// <param name="lengthCppnInput">Optionally we provide a connection length input to the CPPN.</param> public INetworkDefinition CreateNetworkDefinition(IBlackBox blackbox, bool lengthCppnInput) { // Get the sequence of substrate connections. Either a pre-built list or a dynamically // generated sequence. IEnumerable <SubstrateConnection> connectionSequence = _connectionList ?? GetConnectionSequence(); // Iterate over substrate connections. Determine each connection's weight and create a list // of network definition connections. ISignalArray inputSignalArr = blackbox.InputSignalArray; ISignalArray outputSignalArr = blackbox.OutputSignalArray; ConnectionList networkConnList = new ConnectionList(_connectionCountHint); int lengthInputIdx = _dimensionality + _dimensionality; foreach (SubstrateConnection substrateConn in connectionSequence) { // Assign the connection's endpoint position coords to the CPPN/blackbox inputs. Note that position dimensionality is not fixed. for (int i = 0; i < _dimensionality; i++) { inputSignalArr[i] = substrateConn._srcNode._position[i]; inputSignalArr[i + _dimensionality] = substrateConn._tgtNode._position[i]; } // Optional connection length input. if (lengthCppnInput) { inputSignalArr[lengthInputIdx] = CalculateConnectionLength(substrateConn._srcNode._position, substrateConn._tgtNode._position); } // Reset blackbox state and activate it. blackbox.ResetState(); blackbox.Activate(); // Read connection weight from output 0. double weight = outputSignalArr[0]; // Skip connections with a weight magnitude less than _weightThreshold. double weightAbs = Math.Abs(weight); if (weightAbs > _weightThreshold) { // For weights over the threshold we re-scale into the range [-_maxWeight,_maxWeight], // assuming IBlackBox outputs are in the range [-1,1]. weight = (weightAbs - _weightThreshold) * _weightRescalingCoeff * Math.Sign(weight); // Create network definition connection and add to list. networkConnList.Add(new NetworkConnection(substrateConn._srcNode._id, substrateConn._tgtNode._id, weight)); } } // Additionally we create connections from each hidden and output node to a bias node that is not defined at any // position on the substrate. The motivation here is that a each node's input bias is independent of any source // node (and associated source node position on the substrate). That we refer to a bias 'node' is a consequence of how input // biases are handled in NEAT - with a specific bias node that other nodes can be connected to. int setCount = _nodeSetList.Count; for (int i = 1; i < setCount; i++) { SubstrateNodeSet nodeSet = _nodeSetList[i]; foreach (SubstrateNode node in nodeSet.NodeList) { // Assign the node's position coords to the blackbox inputs. The CPPN inputs for source node coords are set to zero when obtaining bias values. for (int j = 0; j < _dimensionality; j++) { inputSignalArr[j] = 0.0; inputSignalArr[j + _dimensionality] = node._position[j]; } // Optional connection length input. if (lengthCppnInput) { inputSignalArr[lengthInputIdx] = CalculateConnectionLength(node._position); } // Reset blackbox state and activate it. blackbox.ResetState(); blackbox.Activate(); // Read bias connection weight from output 1. double weight = outputSignalArr[1]; // Skip connections with a weight magnitude less than _weightThreshold. double weightAbs = Math.Abs(weight); if (weightAbs > _weightThreshold) { // For weights over the threshold we re-scale into the range [-_maxWeight,_maxWeight], // assuming IBlackBox outputs are in the range [-1,1]. weight = (weightAbs - _weightThreshold) * _weightRescalingCoeff * Math.Sign(weight); // Create network definition connection and add to list. Bias node is always ID 0. networkConnList.Add(new NetworkConnection(0, node._id, weight)); } } } // Check for no connections. // If no connections were generated then there is no point in further evaulating the network. // However, null is a valid response when decoding genomes to phenomes, therefore we do that here. if (networkConnList.Count == 0) { return(null); } // Construct and return a network definition. NetworkDefinition networkDef = new NetworkDefinition(_inputNodeCount, _outputNodeCount, _activationFnLibrary, _netNodeList, networkConnList); // Check that the definition is valid and return it. Debug.Assert(networkDef.PerformIntegrityCheck()); return(networkDef); }
/// <summary> /// Reads a network definition from XML. /// An activation function library is required to decode the function ID at each node, typically the /// library is stored alongside the network definition XML and will have already been read elsewhere and /// passed in here. /// </summary> /// <param name="xr">The XmlReader to read from.</param> /// <param name="activationFnLib">The activation function library used to decode node activation function IDs.</param> /// <param name="nodeFnIds">Indicates if node activation function IDs should be read. They are required /// for HyperNEAT genomes but not NEAT</param> public static NetworkDefinition ReadNetworkDefinition(XmlReader xr, IActivationFunctionLibrary activationFnLib, bool nodeFnIds) { // Find <Network>. XmlIoUtils.MoveToElement(xr, false, __ElemNetwork); int initialDepth = xr.Depth; // Find <Nodes>. XmlIoUtils.MoveToElement(xr, true, __ElemNodes); // Create a reader over the <Nodes> sub-tree. int inputNodeCount = 0; int outputNodeCount = 0; NodeList nodeList = new NodeList(); using(XmlReader xrSubtree = xr.ReadSubtree()) { // Re-scan for the root <Nodes> element. XmlIoUtils.MoveToElement(xrSubtree, false); // Move to first node elem. XmlIoUtils.MoveToElement(xrSubtree, true, __ElemNode); // Read node elements. do { NodeType nodeType = ReadAttributeAsNodeType(xrSubtree, __AttrType); uint id = XmlIoUtils.ReadAttributeAsUInt(xrSubtree, __AttrId); int fnId = 0; double[] auxState = null; if(nodeFnIds) { // Read activation fn ID. fnId = XmlIoUtils.ReadAttributeAsInt(xrSubtree, __AttrActivationFunctionId); // Read aux state as comma separated list of real values. auxState = XmlIoUtils.ReadAttributeAsDoubleArray(xrSubtree, __AttrAuxState); } // TODO: Read node aux state data. NetworkNode node = new NetworkNode(id, nodeType, fnId, auxState); nodeList.Add(node); // Track the number of input and output nodes. switch(nodeType) { case NodeType.Input: inputNodeCount++; break; case NodeType.Output: outputNodeCount++; break; } } while(xrSubtree.ReadToNextSibling(__ElemNode)); } // Find <Connections>. XmlIoUtils.MoveToElement(xr, false, __ElemConnections); // Create a reader over the <Connections> sub-tree. ConnectionList connList = new ConnectionList(); using(XmlReader xrSubtree = xr.ReadSubtree()) { // Re-scan for the root <Connections> element. XmlIoUtils.MoveToElement(xrSubtree, false); // Move to first connection elem. string localName = XmlIoUtils.MoveToElement(xrSubtree, true); if(localName == __ElemConnection) { // We have at least one connection. // Read connection elements. do { uint srcId = XmlIoUtils.ReadAttributeAsUInt(xrSubtree, __AttrSourceId); uint tgtId = XmlIoUtils.ReadAttributeAsUInt(xrSubtree, __AttrTargetId); double weight = XmlIoUtils.ReadAttributeAsDouble(xrSubtree, __AttrWeight); NetworkConnection conn = new NetworkConnection(srcId, tgtId, weight); connList.Add(conn); } while(xrSubtree.ReadToNextSibling(__ElemConnection)); } } // Move the reader beyond the closing tags </Connections> and </Network>. do { if (xr.Depth <= initialDepth) { break; } } while(xr.Read()); // Construct and return loaded network definition. return new NetworkDefinition(inputNodeCount, outputNodeCount, activationFnLib, nodeList, connList); }
public override Task OnConnectedAsync(Connection connection) { _connections.Add(connection); return(Task.CompletedTask); }
public bool ReleaseConnection(DatabaseConnection connection) { bool bRet = false; lock (this) { MySqlConnection mConn = (MySqlConnection)connection.DbConnection; bRet = _allocatedConnectionList.Remove(connection); //Log.SysLogText(LogLevel.DEBUG, "Releaseing connection: {0}", mConn.ServerThread); #if DEBUG_CONNECTION_POOL if (m_Credentials.UserName == "rtrsvc") { Log.LogToConsoleAndDebug("CONNDBG: ReleaseConn1 - available to pool {0:x} available: {1} alloced: {2} returned: {3}", connection.GetHashCode(), m_AvailableConnectionStack.Count, m_AllocatedConnectionList.Count, bRet); } #endif if (bRet) { /** add it to the end of the list */ _availableConnectionStack.Add(connection); #if DEBUG_CONNECTION_POOL if (m_Credentials.UserName == "rtrsvc") { Log.LogToConsoleAndDebug("CONNDBG: ReleaseConn2 {0:x} - available: {1} alloced: {2} caller: {3}\n{4}", connection.GetHashCode(), m_AvailableConnectionStack.Count, m_AllocatedConnectionList.Count, GetCallingMethod(), GetRemainingConnectionHashCodes()); } #endif } else { Log.SysLogText(LogLevel.DEBUG, "SqlConnectionPool: Released connection which was never allocated"); } /** clean up and release old connections */ if (DateTime.UtcNow > _lastConnectionCleanupTime + CONNECTION_CLEANUP_INTERVAL) { if (_availableConnectionStack.Count > 0) { /** sort by last use time */ SortedList <TimeSpan, DatabaseConnection> sorter = new SortedList <TimeSpan, DatabaseConnection>(); foreach (DatabaseConnection conn in _availableConnectionStack) { TimeSpan lastUsed = DateTime.UtcNow - conn.LastUse; /** do not allow dups */ while (sorter.ContainsKey(lastUsed)) { lastUsed = lastUsed + TimeSpan.FromMilliseconds(1); } sorter.Add(lastUsed, conn); } List <DatabaseConnection> sortedConnections = new List <DatabaseConnection>(sorter.Values.Reverse()); /** we now have list orderd from stalest to freshest */ while (sortedConnections.Count > _credentials.OptimalPoolSize && DateTime.UtcNow > sortedConnections[0].LastUse + _credentials.StaleConnectionCloseTime) { sortedConnections[0].DbConnection.Close(); _availableConnectionStack.Remove(sortedConnections[0]); MySqlConnection mConn2 = (MySqlConnection)sortedConnections[0].DbConnection; //Log.SysLogText(LogLevel.DEBUG, "Clean up old connection: {0}", mConn2.ServerThread); } } _lastConnectionCleanupTime = DateTime.UtcNow; } } return(bRet); }
public Task OnConnectedAsync(ConnectionContext connection) { connectionList.Add(connection); return(Task.CompletedTask); }
void Listen(int port = 9600, string ip = "127.0.0.1") { Ip = ip; Port = port; _server = new SocketServer(Ip, Port); //处理从客户端收到的消息 _server.HandleRecMsg = new Action <byte[], SocketConnection, SocketServer>((bytes, client, theServer) => { string msg = Encoding.UTF8.GetString(bytes); System.Diagnostics.Debug.WriteLine($"MyServer | {client.RemoteEndPoint.ToString()}=>:{msg}"); }); //处理服务器启动后事件 _server.HandleServerStarted = new Action <SocketServer>(theServer => { System.Diagnostics.Debug.WriteLine("MyServer | 服务已启动"); }); //处理新的客户端连接后的事件 _server.HandleNewClientConnected = new Action <SocketServer, SocketConnection>((theServer, theCon) => { System.Diagnostics.Debug.WriteLine($@"MyServer | 一个新的客户端接入,当前连接数:{theServer.GetConnectionCount()}"); Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.SystemIdle, new Action(() => { //ConnectionList.Add(theCon.RemoteEndPoint.ToString()); ConnectionList.Clear(); foreach (var node in _server.GetRemoteEndPointList()) { ConnectionList.Add(node.ToString()); } })); }); //处理客户端连接关闭后的事件 _server.HandleClientClose = new Action <SocketConnection, SocketServer>((theCon, theServer) => { System.Diagnostics.Debug.WriteLine($@"MyServer | 一个客户端关闭,当前连接数为:{theServer.GetConnectionCount()}"); Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.SystemIdle, new Action(() => { ConnectionList.Clear(); if (_server.GetConnectionCount() < 1) { return; } foreach (var node in _server.GetRemoteEndPointList()) { ConnectionList.Add(node.ToString()); } })); }); //处理异常 _server.HandleException = new Action <Exception>(ex => { System.Diagnostics.Debug.WriteLine(ex.Message); }); //服务器启动 _server.StartServer(); }
/// <summary> /// Create a network definition by querying the provided IBlackBox (typically a CPPN) with the /// substrate connection endpoints. /// </summary> /// <param name="blackbox">The HyperNEAT CPPN that defines the strength of connections between nodes on the substrate.</param> /// <param name="lengthCppnInput">Optionally we provide a connection length input to the CPPN.</param> public INetworkDefinition CreateNetworkDefinition(IBlackBox blackbox, bool lengthCppnInput) { // Get the sequence of substrate connections. Either a pre-built list or a dynamically // generated sequence. IEnumerable<SubstrateConnection> connectionSequence = _connectionList ?? GetConnectionSequence(); // Iterate over substrate connections. Determine each connection's weight and create a list // of network definition connections. ISignalArray inputSignalArr = blackbox.InputSignalArray; ISignalArray outputSignalArr = blackbox.OutputSignalArray; ConnectionList networkConnList = new ConnectionList(_connectionCountHint); int lengthInputIdx = inputSignalArr.Length - 1; foreach(SubstrateConnection substrateConn in connectionSequence) { int layerToLayerAdder = ((int)substrateConn._tgtNode._position[2] * 3); // Assign the connection's endpoint position coords to the CPPN/blackbox inputs. Note that position dimensionality is not fixed. for(int i=0; i<_dimensionality - 1; i++) { inputSignalArr[i] = substrateConn._srcNode._position[i]; inputSignalArr[i + _dimensionality - 1] = substrateConn._tgtNode._position[i]; inputSignalArr[i + 2 * (_dimensionality - 1)] = Math.Abs(substrateConn._srcNode._position[i] - substrateConn._tgtNode._position[i]); } // Optional connection length input. if(lengthCppnInput) { inputSignalArr[lengthInputIdx] = CalculateConnectionLength(substrateConn._srcNode._position, substrateConn._tgtNode._position); } // Reset blackbox state and activate it. blackbox.ResetState(); blackbox.Activate(); // Read connection weight from output 0. double weight = outputSignalArr[0 + layerToLayerAdder]; // Skip connections with a weight magnitude less than _weightThreshold. double weightAbs = Math.Abs(weight); if (outputSignalArr[2 + layerToLayerAdder] >= 0) { // For weights over the threshold we re-scale into the range [-_maxWeight,_maxWeight], // assuming IBlackBox outputs are in the range [-1,1]. weight = (weightAbs) * _weightRescalingCoeff * Math.Sign(weight); // Create network definition connection and add to list. networkConnList.Add(new NetworkConnection(substrateConn._srcNode._id, substrateConn._tgtNode._id, weight)); } } // Additionally we create connections from each hidden and output node to a bias node that is not defined at any // position on the substrate. The motivation here is that a each node's input bias is independent of any source // node (and associated source node position on the substrate). That we refer to a bias 'node' is a consequence of how input // biases are handled in NEAT - with a specific bias node that other nodes can be connected to. int setCount = _nodeSetList.Count; for(int i=1; i<setCount; i++) { SubstrateNodeSet nodeSet = _nodeSetList[i]; foreach(SubstrateNode node in nodeSet.NodeList) { // Assign the node's position coords to the blackbox inputs. The CPPN inputs for source node coords are set to zero when obtaining bias values. for(int j=0; j<_dimensionality - 1; j++) { inputSignalArr[j] = 0.0; inputSignalArr[j + _dimensionality - 1] = node._position[j]; } // Optional connection length input. if(lengthCppnInput) { inputSignalArr[lengthInputIdx] = CalculateConnectionLength(node._position); } // Reset blackbox state and activate it. blackbox.ResetState(); blackbox.Activate(); // Read bias connection weight from output 1. double weight = outputSignalArr[1+ (i- 1) * 3]; // Skip connections with a weight magnitude less than _weightThreshold. double weightAbs = Math.Abs(weight); if(weightAbs > _weightThreshold) { // For weights over the threshold we re-scale into the range [-_maxWeight,_maxWeight], // assuming IBlackBox outputs are in the range [-1,1]. weight = (weightAbs - _weightThreshold) * _weightRescalingCoeff * Math.Sign(weight); // Create network definition connection and add to list. Bias node is always ID 0. networkConnList.Add(new NetworkConnection(0, node._id, weight)); } } } // Check for no connections. // If no connections were generated then there is no point in further evaulating the network. // However, null is a valid response when decoding genomes to phenomes, therefore we do that here. if(networkConnList.Count == 0) { return null; } // Construct and return a network definition. NetworkDefinition networkDef = new NetworkDefinition(_inputNodeCount, _outputNodeCount, _activationFnLibrary, _netNodeList, networkConnList); // Check that the definition is valid and return it. Debug.Assert(networkDef.PerformIntegrityCheck()); return networkDef; }
/// <summary> /// Create a network definition by querying the provided IBlackBox (typically a CPPN) with the /// substrate connection endpoints. /// </summary> /// <param name="blackbox">The HyperNEAT CPPN that defines the strength of connections between nodes on the substrate.</param> /// <param name="lengthCppnInput">Optionally we provide a connection length input to the CPPN.</param> public INetworkDefinition CreateNetworkDefinition(IBlackBox blackbox, bool lengthCppnInput) { // Iterate over substrate connections. Determine each connection's weight and create a list // of network definition connections. ISignalArray inputSignalArr = blackbox.InputSignalArray; ISignalArray outputSignalArr = blackbox.OutputSignalArray; ConnectionList networkConnList = new ConnectionList(_connectionCountHint); int lengthInputIdx = Dimensionality + Dimensionality; for (int i = 0; i < N; i++) { foreach (var substrateConnection in _connectionList[i]) { for (int j = 0; j < Dimensionality; j++) { inputSignalArr[j] = substrateConnection._srcNode._position[j]; inputSignalArr[j + Dimensionality] = substrateConnection._tgtNode._position[j]; } // Optional connection length input. if (lengthCppnInput) { inputSignalArr[lengthInputIdx] = CalculateConnectionLength(substrateConnection._srcNode._position, substrateConnection._tgtNode._position); } blackbox.ResetState(); blackbox.Activate(); double weight = outputSignalArr[i]; //if LEO is toggled query for expression double expressionWeight = -0.1; if (Leo) { expressionWeight = outputSignalArr[i + M + N]; } // Skip connections with a weight magnitude less than _weightThreshold. double weightAbs = Math.Abs(weight); if (!Leo && weightAbs > _weightThreshold || Leo && expressionWeight >= 0.0) { // For weights over the threshold we re-scale into the range [-_maxWeight,_maxWeight], // assuming IBlackBox outputs are in the range [-1,1]. weight = (weightAbs - _weightThreshold) * _weightRescalingCoeff * Math.Sign(weight); // Create network definition connection and add to list. networkConnList.Add(new NetworkConnection(substrateConnection._srcNode._id, substrateConnection._tgtNode._id, weight)); } } } var biasOutputIdx = N; foreach (var nodeSet in _outputLayers.Concat(_hiddenLayers)) { foreach (var node in nodeSet.NodeList) { // Assign the node's position coords to the blackbox inputs. The CPPN inputs for source node coords are set to zero when obtaining bias values. for (int j = 0; j < Dimensionality; j++) { inputSignalArr[j] = 0.0; inputSignalArr[j + Dimensionality] = node._position[j]; } // Optional connection length input. if (lengthCppnInput) { inputSignalArr[lengthInputIdx] = CalculateConnectionLength(node._position); } // Reset blackbox state and activate it. blackbox.ResetState(); blackbox.Activate(); // Read bias connection weight from output 1. double weight = outputSignalArr[biasOutputIdx]; // Skip connections with a weight magnitude less than _weightThreshold. double weightAbs = Math.Abs(weight); if (weightAbs > _weightThreshold) { // For weights over the threshold we re-scale into the range [-_maxWeight,_maxWeight], // assuming IBlackBox outputs are in the range [-1,1]. weight = (weightAbs - _weightThreshold) * _weightRescalingCoeff * Math.Sign(weight); // Create network definition connection and add to list. Bias node is always ID 0. networkConnList.Add(new NetworkConnection(0, node._id, weight)); } } biasOutputIdx++; } // Check for no connections. // If no connections were generated then there is no point in further evaulating the network. // However, null is a valid response when decoding genomes to phenomes, therefore we do that here. if (networkConnList.Count == 0) { return(null); } // Construct and return a network definition. NetworkDefinition networkDef = new NetworkDefinition(_inputLayers.Sum(x => x.NodeList.Count), _outputLayers.Sum(x => x.NodeList.Count), _activationFnLibrary, _netNodeList, networkConnList); // Check that the definition is valid and return it. Debug.Assert(networkDef.PerformIntegrityCheck()); return(networkDef); }