public void SetUp() { this._parser = new NeuralNetworkFileParser(); this._network = this._parser.CreateNetwork("Configuration_AND.txt", "sigmoid", InputsCount); this._network_AND_00 = this._parser.CreateNetwork("Configuration_AND.txt", "linear", Inputs_AND_Count); this._network_AND_01 = this._parser.CreateNetwork("Configuration_AND.txt", "linear", Inputs_AND_Count); this._network_AND_10 = this._parser.CreateNetwork("Configuration_AND.txt", "linear", Inputs_AND_Count); this._network_AND_11 = this._parser.CreateNetwork("Configuration_AND.txt", "linear", Inputs_AND_Count); this._network_Threshold_AND_11 = this._parser.CreateNetwork("Configuration_AND_threshold.txt","threshold",Inputs_AND_Count - 1); this._network_Threshold_AND_10 = this._parser.CreateNetwork("Configuration_AND_threshold.txt","threshold",Inputs_AND_Count - 1); this._network_Threshold_AND_08 = this._parser.CreateNetwork("Configuration_AND_threshold.txt", "threshold", Inputs_AND_Count - 1); this._network_Threshold_AND_01 = this._parser.CreateNetwork("Configuration_AND_threshold.txt","threshold",Inputs_AND_Count - 1); this._network_Threshold_AND_00 = this._parser.CreateNetwork("Configuration_AND_threshold.txt","threshold",Inputs_AND_Count - 1); this._networkXOR00 = this._parser.CreateNetwork("Configuration_XOR_threshold.txt","threshold",2); this._networkXOR01 = this._parser.CreateNetwork("Configuration_XOR_threshold.txt","threshold",2); this._networkXOR10 = this._parser.CreateNetwork("Configuration_XOR_threshold.txt","threshold",2); this._networkXOR11 = this._parser.CreateNetwork("Configuration_XOR_threshold.txt","threshold",2); this._networkKohonen = this._parser.CreateNetwork("Configuration_Kohonen.txt", "linear",4); this._networkKohonen2 = this._parser.CreateNetwork("Configuration_Kohonen2.txt", "linear",9); this._networkKohonen3 = this._parser.CreateNetwork("Configuration_Kohonen3.txt", "linear",9); this._networkKohonen_parz = this._parser.CreateNetwork("Configuration_Kohonen_parz.txt", "linear",3); this._network_parz_BP = this._parser.CreateNetwork("Configuration_Kohonen_parz_BP.txt", "sigmoid",3); this._network_XOR_BP = this._parser.CreateNetwork("Configuration_Kohonen_XOR_BP.txt", "sigmoid",2); this._network_ikonki_BP = this._parser.CreateNetwork("Configuration_ikonki_BP.txt", "sigmoid",9); }
private void RemoveUnusedNodes(INetwork network) { if (allowRemoveUnusedNodes) { NetworkHelper.RemoveUnusedNodes(network); } }
public NetworkDispatcher(ConcurrentQueue<Request> queue, INetwork network, ICache cache, IResponseDelivery delivery) { this.mQueue = queue; this.mNetwork = network; this.mCache = cache; this.mDelivery = delivery; }
public World(INetwork network) : base(0, 0, 1000, 1000) { color = System.Drawing.Brushes.White; bigBrain = (FloatFastConcurrentNetwork)network; size = height; }
public CellNet(INetwork network, ModelVisual3D mophology, Dictionary<Guid, ICell> cells, Dictionary<Guid, ICellNet> childcellnet) { this.network = network; this.mophology = mophology; this.cells = cells; this.childcellnet = childcellnet; IsPushing = true; var transforms = new Transform3DGroup(); Rotate = new RotateTransform3D(new QuaternionRotation3D()); Translate = new TranslateTransform3D(network.Position.X, network.Position.Y, network.Position.Z); Scale = new ScaleTransform3D(); transforms.Children.Add(Rotate); transforms.Children.Add(Translate); transforms.Children.Add(Scale); Mophology.Transform = transforms; var binding = new Binding() { Source = network, Path = new PropertyPath("Position"), Mode = BindingMode.OneWay }; BindingOperations.SetBinding(this, CellNet.PositionProperty, binding); }
public string GetProperties(INetwork network) { var sb = new StringBuilder(); if (network == null) { sb.AppendLine("network is null"); } else { ListPropertiesOfNetworkBase(network, sb); if (network is IAdjList) { ListPropertiesOfAdjList((IAdjList)network, sb); } else { var isMatrix = network.GetType().GetInterfaces() .Where(t => t.IsGenericType) .Select(t => t.GetGenericTypeDefinition()) .Any(t => t.Equals(typeof(IMatrix<>))); if (isMatrix) ListPropertiesOfMatrix(network, sb); } } return sb.ToString(); }
/// <summary> /// Creates an instance of ICopyNetwork appropriate to the underlying /// Type of <paramref name="network"/>. /// The returned object can be used to create a copy of the input network. /// </summary> /// <param name="network">The network to be copied.</param> /// <returns>An ICopyNetwork instance</returns> public ICopyNetwork CreateCopier(INetwork network) { ICopyNetwork tool = null; if (network != null) { if (network is BlueSpider.Blob.Regular.Network.AdjList.SimpleAdjList) { tool = new BlueSpider.Blob.Regular.Network.AdjList.SimpleAdjListCopier(); } else if (network is AdjList) { tool = new AdjacentList.Y.AdjListCopier(); } else if (network is Matrix.CSpace.DirectedNetworkMatrix) { tool = new Matrix.CSpace.MatrixCopier(); } else if (network is Matrix.CSpace.UnDirectedNetworkMatrix) { tool = new Matrix.CSpace.MatrixCopier(); } else if (network is BlueSpider.Blob.Regular.Network.Matrix.SimpleFullMatrix) { throw new NotImplementedException(); } else if (network is BlueSpider.Blob.Regular.Network.Matrix.SimpleSymmetricMatrix) { throw new NotImplementedException(); } } return tool; }
public void ModifyIsDirectedProperty(INetwork network, bool isDirected) { if (network != null && network is BasicAdjList) { ModifyIsDirectedProperty(network as BasicAdjList, isDirected); } }
public int numBrains; // Schrum: Total number public AgentBrain(bool homogenous, int numAgents, SubstrateDescription substrateDescription, INetwork genome, bool normalizeANNWeights, bool adaptableANN, bool modulatoryANN, bool multi, int brains, bool evolveSubstrate, bool preferenceNeurons, bool forcedSituationalPolicyGeometry) { this.evolveSubstrate = evolveSubstrate; this.normalizeANNWeights = normalizeANNWeights; this.adaptableANN = adaptableANN; this.modulatoryANN = modulatoryANN; this.genome = genome; this.substrateDescription = substrateDescription; this.numRobots = numAgents; this.homogenous = homogenous; this.multipleBrains = multi; this.forcedSituationalPolicyGeometry = forcedSituationalPolicyGeometry; // Schrum: When preference neurons are used, the number of modules in the network is the // more reliable source of information. Especially if Module Mutation will allow more modules // to be created, each creating a new brain. this.numBrains = genome != null && preferenceNeurons ? genome.NumOutputModules : brains; this.preferenceNeurons = preferenceNeurons; //inputCounter = 0; teamInput = new float[numAgents * substrateDescription.InputCount]; activated = new bool[numAgents]; createBrains(); robotListeners = new List<Robot>(); }
private NetworkEvent(INetwork network, IEventType type, IEventSource source) { Network = network; Type = type; TimeStamp = DateTime.UtcNow; Source = source; }
public static void SetOrderForBranch(INetwork network, IBranch branch) { // node is new if it is exclusive to branch var connectionsFromNodeCount = branch.Source.IncomingBranches.Count + branch.Source.OutgoingBranches.Count; var connectionsToNodeCount = branch.Target.IncomingBranches.Count + branch.Target.OutgoingBranches.Count; if (connectionsFromNodeCount == 1 && connectionsToNodeCount == 1) { // new branch, not connected (do not assign -1 since user might have assigned it when constructing object) return; } if(connectionsFromNodeCount > 2 || connectionsToNodeCount > 2) { branch.OrderNumber = -1; return; } if (connectionsFromNodeCount == 1 && connectionsToNodeCount == 2) { branch.OrderNumber = ComputeMaximumOrderForNode(network, branch.Target); return; } if (connectionsFromNodeCount == 2 && connectionsToNodeCount == 1) { branch.OrderNumber = ComputeMaximumOrderForNode(network, branch.Source); return; } }
public DataTable ToDataTable(INetwork network) { if (network == null) throw new ArgumentNullException("network", "The input network must not be null."); if (!(network is IEdgeAttributes)) throw new ArgumentException(string.Format("The input network must implement {0}.", typeof(IEdgeAttributes).Name), "network"); IEdgeAttributes src = network as IEdgeAttributes; DataTable table = new DataTable("Edge data"); AttributeListMgr mgr = src.EdgeAttributeMgr as AttributeListMgr; if (mgr == null) throw new ArgumentException("The EdgeAttributeMgr of the input network must not be null.", "network"); string[] colNames = EnsureUniqueColNames(mgr); int ctr = 0; foreach (IAttributeList list in mgr.Lists) { table.Columns.Add(new DataColumn(colNames[ctr++], list.DataType)); } if (table.Columns.Count>0) for (int i = 0; i < mgr.Depth; i++) { table.Rows.Add(mgr.GetRow(i)); } table.AcceptChanges(); return table; }
/// <summary> /// Initializes a new instance of the DummyInputNetworkPort class, This class maintains the dataObj /// as a member, does NOT use the backingStore of the pipe. /// </summary> /// <param name="parent"></param> /// <param name="inPipe"></param> /// <param name="dataObj"></param> /// <param name="isValid"></param> public DummyInputNetworkPort(IElement parent, INetworkPipe inPipe, INetwork dataObj, bool isValid) { _parent = parent; _inPipe = inPipe; _netObj = dataObj; _IsValid = isValid; }
public INetwork CopyNetwork(INetwork source) { if (source == null) throw new ArgumentNullException("source", "The network to be copied is null."); if (!(source is IBasicAdjList)) throw new ArgumentException( string.Format("The network to be copied must implement {0}.", typeof (IBasicAdjList).Name), "source"); if (NewNetworkId == Guid.Empty) NewNetworkId = Guid.NewGuid(); IBasicAdjList copy = null; IBasicAdjList src = source as IBasicAdjList; // copy the network; *Note this copies the network structure (nodes & edges) but // does not structure or populate the attributes using (var fac = new BasicAdjListFactory()) { fac.IsDirected = src.IsDirected; fac.EnableNodeDataAttributes = (CopyNodeData ); fac.EnableEdgeDataAttributes = (CopyEdgeData ); copy = fac.CreateNetwork(NewNetworkId, src.NodeCount) as IBasicAdjList; copy.Name = src.Name != null ? string.Copy(src.Name) : null; } INode copySrcNode = null; INode copyDestNode = null; int srcNodeIndex = -1; int destNodeIndex = -1; IEdge copiedEdge = null; for (int i = 0; i < src.Edges.Count; i++) { srcNodeIndex = src.Edges[i].SourceNode.Index; destNodeIndex = src.Edges[i].DestinationNode.Index; copySrcNode = copy.Nodes[srcNodeIndex]; copyDestNode = copy.Nodes[destNodeIndex]; copiedEdge = copy.CreateEdge(copySrcNode, copyDestNode); } using (var fac = new DataAttributeCopierProvider()) { if (CopyNodeData && src.NodeData != null) { using (var copier = fac.GetCopier(src.NodeData)) { copier.Copy(src.NodeData, copy.NodeData); } } if (CopyEdgeData && src.EdgeData != null) { using (var copier = fac.GetCopier(src.EdgeData)) { copier.Copy(src.EdgeData, copy.EdgeData); } } } return copy; }
public void TearDown() { networkCoverageBindingList.Dispose(); networkCoverage.Clear(); network = null; networkCoverage.Network = null; }
/// <summary> /// Creates and returns a writer. /// </summary> /// <param name="fileType">A <see cref="NetworkFileTypes"/> value specifying the intended output format.</param> /// <param name="network">The source INetwork to be written.</param> /// <returns>INetworkFileWriter</returns> public static INetworkFileWriter CreateWriter(NetworkFileTypes fileType, INetwork network) { INetworkFileWriter writer = null; if (network!=null) { switch (fileType) { case NetworkFileTypes.Pajek_Net: if (network is IBasicAdjList) writer = new PajekBasicAdjListWriter(); break; case NetworkFileTypes.GraphML: if (network is IBasicAdjList) writer = new GraphMlBasicAdjListWriter(); break; case NetworkFileTypes.NetDraw_VNA: if (network is IBasicAdjList) writer = new VNABasicAdjListWriter(); break; default: writer = null; break; } } return writer; }
public RequestQueue(ICache cache, INetwork network, int threadPoolSize, IResponseDelivery delivery) { this.mCache = cache; this.mNetwork = network; this.mDispatchers = new NetworkDispatcher[threadPoolSize]; this.mDelivery = delivery; }
public BranchReorderAction(INetwork network, int oldIndex, int newIndex) : base("Reorder branch position") { Network = network; OldIndex = oldIndex; NewIndex = newIndex; Branch = Network.Branches[oldIndex]; }
public Message(INetwork network, ILogSource source, IUser user, string message, bool highlight) : base(network, source, user) { this.User = user; this.NicknameContinuity = user.Nickname; this.MessageBody = message; this.Highlight = highlight; }
/// <summary> /// Constructs a new AgentBrain object from the specified parameters. This brain is designed to be used as a multiagent hivemind, but can also be used to control a single agent by setting numAgents equal to 1. /// </summary> /// <param name="homogeneous">Is the team homogeneous? Agents in a homogeneous team all have identical copies of the same brain, while those in a heterogeneous team do not, instead each contributing to one central, distributed hive brain.</param> /// <param name="numAgents">Set to 1 for an individual agent, or >1 for a multiagent team.</param> /// <param name="substrateDescription">HyperNEAT substrate</param> /// <param name="genome">If using NEAT, this should be the already-decoded neural network. Otherwise, if using HyperNEAT, this should be the CPPN that encodes the neural network.</param> /// <param name="normalizeANNWeights"></param> /// <param name="adaptableANN"></param> /// <param name="modulatoryANN"></param> /// <param name="multi">Multiple brains with situational policies?</param> /// <param name="evolveSubstrate">Set to true to enable ES-HyperNEAT.</param> /// <param name="useNeatBrain">If false, the system will use HyperNEAT as the EA.</param> /// <param name="useCTRNNs">Set to true to use continuous time recurrent neural networks.</param> public AgentBrain(bool homogeneous, int numAgents, SubstrateDescription substrateDescription, INetwork genome, bool normalizeANNWeights, bool adaptableANN, bool modulatoryANN, bool multi, bool evolveSubstrate, bool useNeatBrain, bool useCTRNNs = false) { // Set instance variables EvolveSubstrate = evolveSubstrate; NormalizeANNWeights = normalizeANNWeights; AdaptableANN = adaptableANN; ModulatoryANN = modulatoryANN; Genome = genome; SubstrateDescription = substrateDescription; NumRobots = numAgents; Homogeneous = homogeneous; MultipleBrains = multi; NeatBrain = useNeatBrain; UseCTRNNs = useCTRNNs; // Initialiaze team arrays TeamInput = new float[numAgents * substrateDescription.InputCount]; TeamInputOld = new float[numAgents * substrateDescription.InputCount]; TeamOutput = new float[numAgents * substrateDescription.OutputCount]; TeamOutputOld = new float[numAgents * substrateDescription.OutputCount]; TeamHidden = new float[numAgents * 5]; TeamHiddenOld = new float[numAgents * 5]; RobotInput = new float[substrateDescription.InputCount]; RobotInputOld = new float[substrateDescription.InputCount]; Activated = new bool[numAgents]; // Initialize the agents' brains createBrains(); // Register listeners for the robots' neural network outputs RobotListeners = new List<Robot>(); if (OutputComms) { // If the robots' input and output streams have already been initialized, reset them if (OutputsInitialized) { for (int j = 0; j < numAgents; j++) { OutStreams[j].Close(); InStreams[j].Close(); OutStreams[j] = null; InStreams[j] = null; } } // Initialize the robots' input and output streams OutStreams = new List<StreamWriter>(numAgents); InStreams = new List<StreamWriter>(numAgents); for (int j = 0; j < numAgents; j++) { OutStreams.Add(new StreamWriter("agentO" + j + ".txt")); InStreams.Add(new StreamWriter("agentI" + j + ".txt")); } OutputsInitialized = true; } }
// find the branch that has the highest order for all branches connected to this node, and return its order number. private static int ComputeMaximumOrderForNode(INetwork network, INode node) { if (node == null) { return -1; } return network.Branches.Where(c => c.Source == node || c.Target == node).Max(d => d.OrderNumber); }
public Predator(float x, float y, float w, float h,INetwork network) : base(x, y, w, h, network) { radius = 200; sensors = new float[5]; angledelta = (float)Math.PI / sensors.Length; halfangledelta = angledelta / 2.0f; brain = (FloatFastConcurrentNetwork)network; }
public bool Equals(INetwork other) { if(ReferenceEquals(other, null)) return false; return EqualityComparer<String>.Default.Equals(this.Name, other.Name) && EqualityComparer<IClientConnection>.Default.Equals(this.Connection, other.Connection) ; }
public void ListPropertiesOfNetworkBase(INetwork network, StringBuilder sb) { sb.AppendLine(string.Format("Id: {0}", network.Id)); sb.AppendLine(string.Format("Name: \"{0}\"", network.Name)); sb.AppendLine(string.Format("Node count: {0}", network.NodeCount)); sb.AppendLine(string.Format("Edge count: {0}", network.EdgeCount)); sb.AppendLine(string.Format("Directed: {0}", network.IsDirected)); sb.AppendLine(string.Format("Structure: {0}", network.Structure)); sb.AppendLine(string.Format("Implementation: {0}", network.GetType().Name)); }
public void SetUp() { network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(100, 0), new Point(100, 100)); networkCoverage = new NetworkCoverage { Network = network }; networkCoverage.Locations.NextValueGenerator = new NetworkLocationNextValueGenerator(networkCoverage); networkCoverageBindingList = new NetworkCoverageBindingList(networkCoverage); }
public int CompareTo(INetwork other) { if(ReferenceEquals(other, null)) return 1; int result = 0; result = this.Name.Value.CompareTo(other.Name); if(result == 0) result = this.Connection.CompareTo(other.Connection); return result; }
public BackPropagation(INetwork network, ITrainingSetProvider trainingSet, ISolver solver = null) { Network = network; TrainingSetProvider = trainingSet; CurrentEpoch = 0; MinError = 1e-6; MaxEpoch = 1e6; BatchSize = trainingSet.TrainInputs.Length; Solver = solver ?? new GD(network); }
public CongresistaDetailViewModel() { m_picaFlorService = new PicaFlorService(); m_network = Cirrious.CrossCore.Mvx.GetSingleton<INetwork>(); m_assetsManager = Cirrious.CrossCore.Mvx.GetSingleton<IAssetsManager>(); this.ApplicationBar = new ApplicationBarViewModel(Cirrious.CrossCore.Mvx.GetSingleton<IMarketServices>()); LastVotation(); }
public SesionesViewModel(IPicaFlorService picaflorService , INetwork network, IAssetsManager assetsManager) { m_picaFlorService = new PicaFlorService(); m_network = network; m_assetsManager = assetsManager; this.ApplicationBar = new ApplicationBarViewModel(Cirrious.CrossCore.Mvx.GetSingleton<IMarketServices>()); LoadData(); }
private SesionesViewModel() { m_picaFlorService = new PicaFlorService(); m_network = Cirrious.CrossCore.Mvx.GetSingleton<INetwork>(); m_assetsManager = Cirrious.CrossCore.Mvx.GetSingleton<IAssetsManager>(); this.ApplicationBar = new ApplicationBarViewModel(Cirrious.CrossCore.Mvx.GetSingleton<IMarketServices>()); LoadData(); }
public static DataStreamWriter CreateWriter <TRPC, T>(T data, INetwork network) where TRPC : RPC <T>, new() { var rpc = new TRPC(); return(rpc.CreateWriter(data, network)); }
public void Predict() { if (!Config.Reload && File.Exists(Config.RnnPredictedXFile) && File.Exists(Config.RnnPredictedYFile)) { return; } Random rng = new Random(Config.Random.Next()); CustomDataSet data = new CustomDataSet(Config); RnnConfig rnnConfig = (RnnConfig)Serializer.Deserialize(Config.RnnConfigFile); int inputDimension = data.Training[0].Steps[0].Input.Rows; int hiddenDimension = 30; int outputDimension = data.Training[0].Steps[0].TargetOutput.Rows; int hiddenLayers = 1; double learningRate = 0.01; double initParamsStdDev = 0.08; double dropout = 0.5; double inDropout = 0.8; INetwork nn = NetworkBuilder.MakeLstm(inputDimension, hiddenDimension, hiddenLayers, outputDimension, new LinearUnit(), initParamsStdDev, rng, dropout, inDropout, Config); //nn = NetworkBuilder.MakeFeedForward(inputDimension, // hiddenDimension, // hiddenLayers, // outputDimension, // new SigmoidUnit(), // new LinearUnit(), // initParamsStdDev, rng, dropout, inDropout, Config); int reportEveryNthEpoch = 10; int trainingEpochs = 100; Trainer.train <NeuralNetwork>(trainingEpochs, learningRate, nn, data, reportEveryNthEpoch, rng); StreamWriter predictedXFile = new StreamWriter(Config.RnnPredictedXFile); StreamWriter predictedYFile = new StreamWriter(Config.RnnPredictedYFile); for (int i = 0; i < data.Testing.First().Steps.Count; ++i) { DataStep ds = data.Testing.First().Steps[i]; Graph g = new Graph(false); // Generate in dropout bool[] dropped = new bool[ds.Input.W.Length]; for (int col = 0; col < dropped.Length; ++col) { dropped[col] = Math.Abs(rnnConfig.GetTransformed(0, i, col, ds.Input.W[col])) < 0.0000001; } Matrix input = new Matrix(ds.Input.W); Matrix output = nn.Activate(input, g, dropped); // Write into file string line1 = ""; string line2 = ""; foreach (double d in output.W) { line1 += d + ";"; } foreach (double d in ds.TargetOutput.W) { line2 += d + ";"; } predictedXFile.WriteLine(line1.Substring(0, line1.Length - 1)); predictedYFile.WriteLine(line2.Substring(0, line2.Length - 1)); } predictedXFile.Close(); predictedYFile.Close(); }
public SupremeAuthority(INetwork network, ILoggerFactory loggerFactory) { _network = network; _loggerFactory = loggerFactory; }
public LidgrenConnection(INetwork network, NetConnection connection, byte[] aesKey) : this( network, Guid.NewGuid(), connection, aesKey ) { }
public INetwork generateNetwork(INetwork CPPN) { return(generateGenome(CPPN).Decode(null)); }
/// <summary> /// Specifies an existing private subnet to receive network traffic from. /// If this load balancer already has a frontend referencing this subnet, that is the frontend that will be used. /// Else, an automatically named new private frontend will be created implicitly on the load balancer. /// </summary> /// <param name="network">An existing network.</param> /// <param name="subnetName">The name of an existing subnet within the specified network.</param> /// <return>The next stage of the definition.</return> LoadBalancerInboundNatPool.UpdateDefinition.IWithAttach <LoadBalancer.Update.IUpdate> HasFrontend.UpdateDefinition.IWithFrontendBeta <LoadBalancerInboundNatPool.UpdateDefinition.IWithAttach <LoadBalancer.Update.IUpdate> > .FromExistingSubnet(INetwork network, string subnetName) { return(this.FromExistingSubnet(network, subnetName) as LoadBalancerInboundNatPool.UpdateDefinition.IWithAttach <LoadBalancer.Update.IUpdate>); }
public WallhavenClient(INetwork network, IAuthentication auth, Random rng) { _network = network; _auth = auth; _rng = rng; }
public virtual void Init(INetwork parameter) { _network = parameter; }
public SessionFactory(INetwork network, IEnumerable <ICompiledRule> compiledRules) { _network = network; _compiledRules = new List <ICompiledRule>(compiledRules); DependencyResolver = new DependencyResolver(); }
public static ILoadBalancer CreateInternalLoadBalancer( IAzure azure, IResourceGroup resourceGroup, INetwork network, string id, Region location) { string loadBalancerName = TestUtilities.GenerateName("InternalLb" + id); string privateFrontEndName = loadBalancerName + "-FE1"; string backendPoolName1 = loadBalancerName + "-BAP1"; string backendPoolName2 = loadBalancerName + "-BAP2"; string natPoolName1 = loadBalancerName + "-INP1"; string natPoolName2 = loadBalancerName + "-INP2"; string subnetName = "subnet1"; ILoadBalancer loadBalancer = azure.LoadBalancers.Define(loadBalancerName) .WithRegion(location) .WithExistingResourceGroup(resourceGroup) // Add two rules that uses above backend and probe .DefineLoadBalancingRule("httpRule") .WithProtocol(TransportProtocol.Tcp) .FromFrontend(privateFrontEndName) .FromFrontendPort(1000) .ToBackend(backendPoolName1) .WithProbe("httpProbe") .Attach() .DefineLoadBalancingRule("httpsRule") .WithProtocol(TransportProtocol.Tcp) .FromFrontend(privateFrontEndName) .FromFrontendPort(1001) .ToBackend(backendPoolName2) .WithProbe("httpsProbe") .Attach() // Add two nat pools to enable direct VM connectivity to port 44 and 45 .DefineInboundNatPool(natPoolName1) .WithProtocol(TransportProtocol.Tcp) .FromFrontend(privateFrontEndName) .FromFrontendPortRange(8000, 8099) .ToBackendPort(44) .Attach() .DefineInboundNatPool(natPoolName2) .WithProtocol(TransportProtocol.Tcp) .FromFrontend(privateFrontEndName) .FromFrontendPortRange(9000, 9099) .ToBackendPort(45) .Attach() // Explicitly define the frontend .DefinePrivateFrontend(privateFrontEndName) .WithExistingSubnet(network, subnetName) .Attach() // Add two probes one per rule .DefineHttpProbe("httpProbe") .WithRequestPath("/") .Attach() .DefineHttpProbe("httpsProbe") .WithRequestPath("/") .Attach() .Create(); loadBalancer = azure.LoadBalancers.GetByResourceGroup(resourceGroup.Name, loadBalancerName); Assert.Empty(loadBalancer.PublicIPAddressIds); Assert.Equal(2, loadBalancer.Backends.Count()); ILoadBalancerBackend backend1 = null; Assert.True(loadBalancer.Backends.TryGetValue(backendPoolName1, out backend1)); ILoadBalancerBackend backend2 = null; Assert.True(loadBalancer.Backends.TryGetValue(backendPoolName2, out backend2)); ILoadBalancerHttpProbe httpProbe = null; Assert.True(loadBalancer.HttpProbes.TryGetValue("httpProbe", out httpProbe)); Assert.Single(httpProbe.LoadBalancingRules); ILoadBalancerHttpProbe httpsProbe = null; Assert.True(loadBalancer.HttpProbes.TryGetValue("httpsProbe", out httpsProbe)); Assert.Single(httpProbe.LoadBalancingRules); Assert.Equal(2, loadBalancer.InboundNatPools.Count()); return(loadBalancer); }
// Schrum: Had to remove the internal from this too so that I could override it in AdversarialRoomClearingExperiment public override double evaluateNetwork(INetwork network, out SharpNeatLib.BehaviorType behavior, System.Threading.Semaphore sem) { double fitness = 0;//SharpNeatLib.Utilities.random.NextDouble(); //NeatGenome tempGenome; //INetwork controller; behavior = new SharpNeatLib.BehaviorType(); // Schrum: Why is there a magic number 6 here? double[] accumObjectives = new double[6]; for (int i = 0; i < 6; i++) { accumObjectives[i] = 0.0; } IFitnessFunction fit_copy; IBehaviorCharacterization bc_copy; //CollisionManager cm; instance_pack inst = new instance_pack(); inst.timestep = timestep; foreach (Environment env2 in environmentList) { fit_copy = fitnessFunction.copy(); if (behaviorCharacterization != null) { bc_copy = behaviorCharacterization.copy(); inst.bc = bc_copy; } inst.ff = fit_copy; double tempFit = 0; double[] fitnesses = new double[timesToRunEnvironments]; SharpNeatLib.Maths.FastRandom evalRand = new SharpNeatLib.Maths.FastRandom(100); for (int evals = 0; evals < timesToRunEnvironments; evals++) { int agent_trials = timesToRunEnvironments; inst.num_rbts = this.numberRobots; Environment env = env2.copy(); double evalTime = evaluationTime; inst.eval = evals; env.seed = evals; env.rng = new SharpNeatLib.Maths.FastRandom(env.seed + 1); int noise_lev = (int)this.sensorNoise + 1; float new_sn = evalRand.NextUInt() % noise_lev; float new_ef = evalRand.NextUInt() % noise_lev; inst.agentBrain = new AgentBrain(homogeneousTeam, inst.num_rbts, substrateDescription, network, normalizeWeights, adaptableANN, modulatoryANN, multibrain, numBrains, evolveSubstrate, preferenceNeurons, forcedSituationalPolicyGeometry); initializeRobots(agentBrain, env, headingNoise, new_sn, new_ef, inst); inst.elapsed = 0; inst.timestep = this.timestep; //Console.WriteLine(this.timestep); inst.timeSteps = 0; inst.collisionManager = collisionManager.copy(); inst.collisionManager.Initialize(env, this, inst.robots); try { while (inst.elapsed < evalTime) { // Schrum2: Only called for non-visual evaluations //Console.WriteLine("MAE:" + inst.elapsed + "/" + evalTime); runEnvironment(env, inst, sem); } } catch (Exception e) { for (int x = 0; x < inst.robots.Count; x++) { for (int y = 0; y < inst.robots[x].history.Count; y++) { Console.WriteLine(x + " " + y + " " + inst.robots[x].history[y].x + " " + inst.robots[x].history[y].y); } } behavior = new SharpNeatLib.BehaviorType(); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); throw (e); return(0.0001); } double thisFit = inst.ff.calculate(this, env, inst, out behavior.objectives); fitnesses[evals] = thisFit; tempFit += thisFit; if (behavior != null && behavior.objectives != null && inst.bc != null) { for (int i = 0; i < behavior.objectives.Length; i++) { accumObjectives[i] += behavior.objectives[i]; } if (behavior.behaviorList == null) { behavior.behaviorList = new List <double>(); } behavior.behaviorList.AddRange(inst.bc.calculate(this, inst)); inst.bc.reset(); } inst.ff.reset(); } fitness += tempFit / timesToRunEnvironments; } behavior.objectives = accumObjectives; return(fitness / environmentList.Count); }
///GENMHASH:5647899224D30C7B5E1FDCD2D9AAB1DB:F08EFDCC8A8286B3C9226D19B2EA7889 public VirtualNetworkGatewayIPConfigurationImpl WithExistingSubnet(INetwork network, string subnetName) { return(this.WithExistingSubnet(network.Id, subnetName)); }
public virtual NeatGenome.NeatGenome generateGenome(INetwork network) { var coordinates = new double[4]; float output; uint connectionCounter = 0; int iterations = 2 * (network.TotalNeuronCount - (network.InputNeuronCount + network.OutputNeuronCount)) + 1; ConnectionGeneList connections = new ConnectionGeneList(); if (hiddenCount > 0) { coordinates[0] = -1 + inputDelta / 2.0f; coordinates[1] = -1; coordinates[2] = -1 + hiddenDelta / 2.0f; coordinates[3] = 0; for (uint input = 0; input < inputCount; input++, coordinates[0] += inputDelta) { coordinates[2] = -1 + hiddenDelta / 2.0f; for (uint hidden = 0; hidden < hiddenCount; hidden++, coordinates[2] += hiddenDelta) { network.ClearSignals(); network.SetInputSignals(coordinates); network.MultipleSteps(iterations); output = network.GetOutputSignal(0); if (Math.Abs(output) > threshold) { float weight = (float)(((Math.Abs(output) - (threshold)) / (1 - threshold)) * weightRange * Math.Sign(output)); connections.Add(new ConnectionGene(connectionCounter++, input, hidden + inputCount + outputCount, weight)); } } } coordinates[0] = -1 + hiddenDelta / 2.0f; coordinates[1] = 0; coordinates[2] = -1 + outputDelta / 2.0f; coordinates[3] = 1; for (uint hidden = 0; hidden < hiddenCount; hidden++, coordinates[0] += hiddenDelta) { coordinates[2] = -1 + outputDelta / 2.0f; for (uint outputs = 0; outputs < outputCount; outputs++, coordinates[2] += outputDelta) { network.ClearSignals(); network.SetInputSignals(coordinates); network.MultipleSteps(iterations); output = network.GetOutputSignal(0); if (Math.Abs(output) > threshold) { float weight = (float)(((Math.Abs(output) - (threshold)) / (1 - threshold)) * weightRange * Math.Sign(output)); connections.Add(new ConnectionGene(connectionCounter++, hidden + inputCount + outputCount, outputs + inputCount, weight)); } } } } else { coordinates[0] = -1 + inputDelta / 2.0f; coordinates[1] = -1; coordinates[2] = -1 + outputDelta / 2.0f; coordinates[3] = 1; for (uint input = 0; input < inputCount; input++, coordinates[0] += inputDelta) { coordinates[2] = -1 + outputDelta / 2.0f; for (uint outputs = 0; outputs < outputCount; outputs++, coordinates[2] += outputDelta) { network.ClearSignals(); network.SetInputSignals(coordinates); network.MultipleSteps(iterations); output = network.GetOutputSignal(0); if (Math.Abs(output) > threshold) { float weight = (float)(((Math.Abs(output) - (threshold)) / (1 - threshold)) * weightRange * Math.Sign(output)); connections.Add(new ConnectionGene(connectionCounter++, input, outputs + inputCount, weight)); } } } } return(new SharpNeatLib.NeatGenome.NeatGenome(0, neurons, connections, (int)inputCount, (int)outputCount)); }
/// <summary>Initializes a new instance of the <see cref="NetworkProfile"/> class using the GUID of the network profile.</summary> /// <param name="guid">The GUID of the network profile.</param> public NetworkProfile(Guid guid) { inet = NetworkListManager.Manager.GetNetwork(guid); }
private double DoSimulation() { float timetaken = 0; double fitness = 0; int startEnemy = 0; World w = null; INetwork network = null; switch (m_currentShape) { case Shapes.Triangle: w = pointWorldVar(network, (float)Math.PI / 8.0f); startEnemy = w.Enemy.Count; timetaken = w.go(1000); fitness += 10000 * (startEnemy - w.Enemy.Count) + timetaken; w = pointWorldVar(network, 3 * (float)Math.PI / 8.0f); startEnemy = w.Enemy.Count; timetaken = w.go(1000); fitness += 10000 * (startEnemy - w.Enemy.Count) + timetaken; break; case Shapes.Diamond: w = diamondWorldVar(network, 75); startEnemy = w.Enemy.Count; timetaken = w.go(1000); fitness += 10000 * (startEnemy - w.Enemy.Count) + timetaken; w = diamondWorldVar(network, 125); startEnemy = w.Enemy.Count; timetaken = w.go(1000); fitness += 10000 * (startEnemy - w.Enemy.Count) + timetaken; break; case Shapes.Square: w = squareWorldVar(network, 75); startEnemy = w.Enemy.Count; timetaken = w.go(1000); fitness += 10000 * (startEnemy - w.Enemy.Count) + timetaken; w = squareWorldVar(network, 125); startEnemy = w.Enemy.Count; timetaken = w.go(1000); fitness += 10000 * (startEnemy - w.Enemy.Count) + timetaken; break; case Shapes.L: w = lWorldVar(network, 75); startEnemy = w.Enemy.Count; timetaken = w.go(500); fitness += 10000 * (startEnemy - w.Enemy.Count) + timetaken; w = lWorldVar(network, 125); startEnemy = w.Enemy.Count; timetaken = w.go(500); fitness += 10000 * (startEnemy - w.Enemy.Count) + timetaken; break; } return(fitness); }
public Client(Settings settings, IDispatcher dispatcher, IStorage storage) { void ProfileChanged(object sender, PropertyChangedEventArgs e) { var profile = this.profile; Debug.Assert(sender == profile); if (e.PropertyName == nameof(NotifyClientProfile.Name)) { settings.ClientName = profile.Name; } else if (e.PropertyName == nameof(NotifyClientProfile.Text)) { settings.ClientText = profile.Text; } else if (e.PropertyName == nameof(NotifyClientProfile.ImageHash)) { settings.ClientImageHash = profile.ImageHash; } } NotifyClientProfile InitializeProfile() { var imageHash = settings.ClientImageHash; var imagePath = default(FileInfo); var exists = !string.IsNullOrEmpty(imageHash) && this.cache.TryGetCache(imageHash, out imagePath); var profile = new NotifyClientProfile(settings.ClientId) { Name = settings.ClientName, Text = settings.ClientText, UdpPort = settings.UdpEndPoint.Port, TcpPort = settings.TcpEndPoint.Port, ImageHash = exists ? imageHash : string.Empty, }; profile.SetImagePath(exists ? imagePath.FullName : string.Empty); profile.SetIPAddress(IPAddress.Loopback); return(profile); } if (settings is null) { throw new ArgumentNullException(nameof(settings)); } if (dispatcher is null) { throw new ArgumentNullException(nameof(dispatcher)); } if (storage is null) { throw new ArgumentNullException(nameof(storage)); } this.cancellationToken = this.cancellation.Token; this.dispatcher = dispatcher; this.storage = storage; this.settings = settings; this.context = new Context(settings, this.generator, dispatcher, this, this.cancellation.Token); this.network = new Network(this.context); this.cache = new Cache(this.context, this.network); this.profile = InitializeProfile(); this.profile.PropertyChanged += ProfileChanged; this.network.RegisterHandler("link.message.text", this.HandleTextAsync); this.network.RegisterHandler("link.message.image-hash", this.HandleImageAsync); this.network.RegisterHandler("link.sharing.file", this.HandleFileAsync); this.network.RegisterHandler("link.sharing.directory", this.HandleDirectoryAsync); this.network.RegisterHandler("link.broadcast", this.HandleBroadcastAsync); }
/// <summary> /// Specifies an existing private subnet to receive network traffic from. /// If this load balancer already has a frontend referencing this subnet, that is the frontend that will be used. /// Else, an automatically named new private frontend will be created implicitly on the load balancer. /// </summary> /// <param name="network">An existing network.</param> /// <param name="subnetName">The name of an existing subnet within the specified network.</param> /// <return>The next stage of the definition.</return> LoadBalancerInboundNatPool.Definition.IWithFrontendPortRange <LoadBalancer.Definition.IWithCreateAndInboundNatPool> HasFrontend.Definition.IWithFrontendBeta <LoadBalancerInboundNatPool.Definition.IWithFrontendPortRange <LoadBalancer.Definition.IWithCreateAndInboundNatPool> > .FromExistingSubnet(INetwork network, string subnetName) { return(this.FromExistingSubnet(network, subnetName) as LoadBalancerInboundNatPool.Definition.IWithFrontendPortRange <LoadBalancer.Definition.IWithCreateAndInboundNatPool>); }
internal NetworkInfo(INetwork network) { _network = network; }
public ESBodyInformation genomeIntoBodyObject(IGenome genome, out bool isEmpty) { INetwork net = GenomeDecoder.DecodeToModularNetwork((NeatGenome)genome); isEmpty = false; //we want the genome, so we can acknowledge the genomeID! //now convert a network to a set of hidden neurons and connections //we'll make body specific function calls later var allBodyOutputs = new List <List <float> >(); var allBodyInputs = new List <PointPair>(); var indexToConnectionMap = new Dictionary <int, int>(); List <PointF> inputs, outputs, hiddenNeurons; inputs = new List <PointF>(); outputs = new List <PointF>(); hiddenNeurons = new List <PointF>(); //inputs.Add(new PointF(0,0)); //int initialDepth, ESIterations; //uint inputCount, outputCount; //float varianceThreshold, bandThreshold; ConnectionGeneList connections = new ConnectionGeneList(); //loop through a grid, defined by some resolution, and test every connection against another using leo int resolution = 9; //int resolutionHalf = resolution / 2; List <PointF> queryPoints = gridQueryPoints(resolution); float xDistanceThree = dXDistance(resolution, 3.0f); float yDistanceThree = dYDistance(resolution, 3.0f); bool useLeo = true; int counter = 0; Dictionary <long, PointF> conSourcePoints = new Dictionary <long, PointF>(); Dictionary <long, PointF> conTargetPoints = new Dictionary <long, PointF>(); //Dictionary<string, List<PointF>> pointsChecked = new Dictionary<string, List<PointF>>(); //List<PointF> pList; int src, tgt; //for each points we have for (int p1 = 0; p1 < queryPoints.Count; p1++) { PointF xyPoint = queryPoints[p1]; //query against all other points (possibly limiting certain connection lengths for (int p2 = p1; p2 < queryPoints.Count; p2++) { PointF otherPoint = queryPoints[p2]; if (p1 != p2 && (Math.Abs(xyPoint.X - otherPoint.X) < xDistanceThree && Math.Abs(xyPoint.Y - otherPoint.Y) < yDistanceThree)) { //if(!pointsChecked.TryGetValue(xyPoint.ToString(), out pList)) //{ // pList = new List<PointF>(); // pointsChecked.Add(xyPoint.ToString(), pList); //} //pList.Add(otherPoint); //if (!pointsChecked.TryGetValue(otherPoint.ToString(), out pList)) //{ // pList = new List<PointF>(); // pointsChecked.Add(otherPoint.ToString(), pList); //} //pList.Add(xyPoint); //Console.WriteLine("Checking: ({0}, {1}) => ({2}, {3}) ", xyPoint.X, xyPoint.Y, otherPoint.X, otherPoint.Y); float[] outs = queryCPPNOutputs((ModularNetwork)net, xyPoint.X, xyPoint.Y, otherPoint.X, otherPoint.Y, maxXDistanceCenter(xyPoint, otherPoint), minYDistanceGround(xyPoint, otherPoint)); float weight = outs[0]; allBodyInputs.Add(new PointPair(xyPoint, otherPoint)); allBodyOutputs.Add(new List <float>(outs)); if (useLeo) { if (outs[1] > 0) { //Console.WriteLine("XY: " + xyPoint + " Other: " + otherPoint + " LEO : " + outs[1]) ; //Console.WriteLine(" XDist: " + sqrt(xDistanceSq(xyPoint, otherPoint)) // + " yDist : " + sqrt(yDistanceSq(xyPoint, otherPoint)) // + " MaxDist: " + maxXDistanceCenter(xyPoint, otherPoint)) //+ " MinY: " + minYDistanceGround(xyPoint, otherPoint)); //Console.WriteLine(); //add to hidden neurons if (!hiddenNeurons.Contains(xyPoint)) { hiddenNeurons.Add(xyPoint); } src = hiddenNeurons.IndexOf(xyPoint); if (!hiddenNeurons.Contains(otherPoint)) { hiddenNeurons.Add(otherPoint); } tgt = hiddenNeurons.IndexOf(otherPoint); conSourcePoints.Add(counter, xyPoint); conTargetPoints.Add(counter, otherPoint); indexToConnectionMap.Add(allBodyOutputs.Count - 1, counter); connections.Add(new ConnectionGene(counter++, (src), (tgt), weight * HyperNEATParameters.weightRange, new float[] { xyPoint.X, xyPoint.Y, otherPoint.X, otherPoint.Y }, outs)); } } else { //add to hidden neurons if (!hiddenNeurons.Contains(xyPoint)) { hiddenNeurons.Add(xyPoint); } src = hiddenNeurons.IndexOf(xyPoint); if (!hiddenNeurons.Contains(otherPoint)) { hiddenNeurons.Add(otherPoint); } tgt = hiddenNeurons.IndexOf(otherPoint); conSourcePoints.Add(counter, xyPoint); conTargetPoints.Add(counter, otherPoint); indexToConnectionMap.Add(allBodyOutputs.Count - 1, counter); connections.Add(new ConnectionGene(counter++, (src), (tgt), weight * HyperNEATParameters.weightRange, new float[] { xyPoint.X, xyPoint.Y, otherPoint.X, otherPoint.Y }, outs)); } //PointF newp = new PointF(p.x2, p.y2); //targetIndex = hiddenNeurons.IndexOf(newp); //if (targetIndex == -1) //{ // targetIndex = hiddenNeurons.Count; // hiddenNeurons.Add(newp); //} //connections.Add(new ConnectionGene(counter++, (sourceIndex), (targetIndex + inputCount + outputCount), p.weight * HyperNEATParameters.weightRange, new float[] { p.x1, p.y1, p.x2, p.y2 }, p.Outputs)); } } } //esSubstrate.generateSubstrate(inputs, outputs, net, // HyperNEATParameters.initialDepth, // (float)HyperNEATParameters.varianceThreshold, // (float)HyperNEATParameters.bandingThreshold, // HyperNEATParameters.ESIterations, // (float)HyperNEATParameters.divisionThreshold, // HyperNEATParameters.maximumDepth, // (uint)inputs.Count, (uint)outputs.Count, // ref connections, ref hiddenNeurons, true); //generateSubstrate(List<System.Drawing.PointF> inputNeuronPositions, List<PointF> outputNeuronPositions, //INetwork genome, int initialDepth, float varianceThreshold, float bandThreshold, int ESIterations, // float divsionThreshold, int maxDepth, // uint inputCount, uint outputCount, // ref ConnectionGeneList connections, ref List<PointF> hiddenNeurons) //blow out the object, we don't care about testing it //foreach (var pPair in pointsChecked) //{ // Console.WriteLine("Checking: " + pPair.Key + " processed: "); // foreach (var xyPoint in pPair.Value) // { // Console.WriteLine("({0}, {1}) ", xyPoint.X, xyPoint.Y); // } //} var beforeConn = connections.Count; var beforeNeuron = hiddenNeurons.Count; //var hiddenCopy = new List<PointF>(hiddenNeurons); ensureSingleConnectedStructure(connections, hiddenNeurons, conSourcePoints, conTargetPoints); if (hiddenNeurons.Count > 20 || connections.Count > 100) { hiddenNeurons = new List <PointF>(); connections = new ConnectionGeneList(); } if (hiddenNeurons.Count == 0 || connections.Count == 0) { isEmpty = true; } NeatGenome ng = (NeatGenome)genome; bool behaviorExists = (ng.Behavior != null); ESBodyInformation esbody = new ESBodyInformation() { AllBodyOutputs = allBodyOutputs, AllBodyInputs = allBodyInputs, indexToConnection = indexToConnectionMap, //PreHiddenLocations = hiddenCopy, BeforeNeuron = beforeNeuron, BeforeConnection = beforeConn, GenomeID = genome.GenomeId, Connections = connections, HiddenLocations = hiddenNeurons, InputLocations = inputs, Objectives = ng.objectives, Fitness = ng.Fitness, Locality = ng.locality, useLEO = useLeo }; Console.WriteLine(" Nodes: " + hiddenNeurons.Count + " Connections: " + connections.Count); return(esbody); }
public override void DisplayReport(INetwork network, Random rng) { // TODO Auto-generated method stub }
public LidgrenConnection(INetwork network, NetConnection connection, byte[] aesKey, RSAParameters rsaParameters) : this(network, Guid.NewGuid(), connection, aesKey) { CreateRsa(rsaParameters); }
public void SetBrain(INetwork network, bool useSUPG = false, NeatGenome genome = null, INetwork cppn = null, int[] triggerMap = null) { if (useSUPG) { supgOutputs = new float[network.TotalNeuronCount /*- (network.InputNeuronCount + network.OutputNeuronCount)*/, wavelength]; // need at least as many rows as the number of hidden neurons // set all supgOutputs to min value to signal they have not been cached yet for (int i = 0; i < network.TotalNeuronCount /*- (network.InputNeuronCount + network.OutputNeuronCount)*/; i++) { for (int j = 0; j < wavelength; j++) { supgOutputs[i, j] = float.MinValue; } } } this.network = network; this.useSUPG = useSUPG; this.genome = genome; this.cppn = cppn; this.triggerMap = triggerMap; bool[] useSUPGArray = new bool[genome.NeuronGeneList.Count]; useSUPGArray[7] = true; useSUPGArray[8] = true; if (useSUPG) { ((FloatFastConcurrentNetwork)network).UseSUPG = false; ((FloatFastConcurrentNetwork)network).useSUPGArray = useSUPGArray; } brain = network; }
/** * Azure Network sample for managing virtual networks. * - Create a virtual network with Subnets * - Update a virtual network * - Create virtual machines in the virtual network subnets * - Create another virtual network * - List virtual networks */ public async static Task RunSampleAsync(IAzure azure) { string vnetName1 = SdkContext.RandomResourceName("vnet1", 20); string vnetName2 = SdkContext.RandomResourceName("vnet2", 20); string frontEndVmName = SdkContext.RandomResourceName("fevm", 24); string backEndVmName = SdkContext.RandomResourceName("bevm", 24); string publicIpAddressLeafDnsForFrontEndVm = SdkContext.RandomResourceName("pip1", 24); try { //============================================================ // Create a virtual network with specific address-space and two subnet // Creates a network security group for backend subnet Utilities.Log("Creating a network security group for virtual network backend subnet..."); Utilities.Log("Creating a network security group for virtual network frontend subnet..."); var backEndSubnetNsg = await azure.NetworkSecurityGroups .Define(VNet1BackEndSubnetNsgName) .WithRegion(Region.USEast) .WithNewResourceGroup(ResourceGroupName) .DefineRule("DenyInternetInComing") .DenyInbound() .FromAddress("INTERNET") .FromAnyPort() .ToAnyAddress() .ToAnyPort() .WithAnyProtocol() .Attach() .DefineRule("DenyInternetOutGoing") .DenyOutbound() .FromAnyAddress() .FromAnyPort() .ToAddress("INTERNET") .ToAnyPort() .WithAnyProtocol() .Attach() .CreateAsync(); Utilities.Log("Created network security group"); // Print the network security group Utilities.PrintNetworkSecurityGroup(backEndSubnetNsg); var frontEndSubnetNsg = await azure.NetworkSecurityGroups.Define(VNet1FrontEndSubnetNsgName) .WithRegion(Region.USEast) .WithExistingResourceGroup(ResourceGroupName) .DefineRule("AllowHttpInComing") .AllowInbound() .FromAddress("INTERNET") .FromAnyPort() .ToAnyAddress() .ToPort(80) .WithProtocol(SecurityRuleProtocol.Tcp) .Attach() .DefineRule("DenyInternetOutGoing") .DenyOutbound() .FromAnyAddress() .FromAnyPort() .ToAddress("INTERNET") .ToAnyPort() .WithAnyProtocol() .Attach() .CreateAsync(); Utilities.Log("Created network security group"); // Print the network security group Utilities.PrintNetworkSecurityGroup(frontEndSubnetNsg); Utilities.Log("Creating virtual network #1..."); INetwork virtualNetwork1 = await azure.Networks.Define(vnetName1) .WithRegion(Region.USEast) .WithExistingResourceGroup(ResourceGroupName) .WithAddressSpace("192.168.0.0/16") .WithSubnet(VNet1FrontEndSubnetName, "192.168.1.0/24") .DefineSubnet(VNet1BackEndSubnetName) .WithAddressPrefix("192.168.2.0/24") .WithExistingNetworkSecurityGroup(backEndSubnetNsg) .Attach() .CreateAsync(); Utilities.Log("Created a virtual network"); // Print the virtual network details Utilities.PrintVirtualNetwork(virtualNetwork1); //============================================================ // Update a virtual network // Update the virtual network frontend subnet by associating it with network security group Utilities.Log("Associating network security group rule to frontend subnet"); await virtualNetwork1.Update() .UpdateSubnet(VNet1FrontEndSubnetName) .WithExistingNetworkSecurityGroup(frontEndSubnetNsg) .Parent() .ApplyAsync(); Utilities.Log("Network security group rule associated with the frontend subnet"); // Print the virtual network details Utilities.PrintVirtualNetwork(virtualNetwork1); //============================================================ // Create a virtual machine in each subnet // Creates the first virtual machine in frontend subnet Utilities.Log("Creating a Linux virtual machine in the frontend subnet"); // Creates the second virtual machine in the backend subnet Utilities.Log("Creating a Linux virtual machine in the backend subnet"); // Create a virtual network with default address-space and one default subnet Utilities.Log("Creating virtual network #2..."); var t1 = DateTime.UtcNow; var frontEndVM = await azure.VirtualMachines.Define(frontEndVmName) .WithRegion(Region.USEast) .WithExistingResourceGroup(ResourceGroupName) .WithExistingPrimaryNetwork(virtualNetwork1) .WithSubnet(VNet1FrontEndSubnetName) .WithPrimaryPrivateIPAddressDynamic() .WithNewPrimaryPublicIPAddress(publicIpAddressLeafDnsForFrontEndVm) .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername(UserName) .WithSsh(SshKey) .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4")) .CreateAsync(); var t2 = DateTime.UtcNow; Utilities.Log("Created Linux VM: (took " + (t2 - t1).TotalSeconds + " seconds) " + frontEndVM); // Print virtual machine details Utilities.PrintVirtualMachine(frontEndVM); t1 = DateTime.UtcNow; var backEndVM = await azure.VirtualMachines.Define(backEndVmName) .WithRegion(Region.USEast) .WithExistingResourceGroup(ResourceGroupName) .WithExistingPrimaryNetwork(virtualNetwork1) .WithSubnet(VNet1BackEndSubnetName) .WithPrimaryPrivateIPAddressDynamic() .WithoutPrimaryPublicIPAddress() .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername(UserName) .WithSsh(SshKey) .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4")) .CreateAsync(); var t3 = DateTime.UtcNow; Utilities.Log("Created Linux VM: (took " + (t3 - t1).TotalSeconds + " seconds) " + backEndVM.Id); // Print virtual machine details Utilities.PrintVirtualMachine(backEndVM); var virtualNetwork2 = await azure.Networks.Define(vnetName2) .WithRegion(Region.USEast) .WithNewResourceGroup(ResourceGroupName) .CreateAsync(); Utilities.Log("Created a virtual network"); // Print the virtual network details Utilities.PrintVirtualNetwork(virtualNetwork2); //============================================================ // List virtual networks foreach (var virtualNetwork in await azure.Networks.ListByResourceGroupAsync(ResourceGroupName)) { Utilities.PrintVirtualNetwork(virtualNetwork); } //============================================================ // Delete a virtual network Utilities.Log("Deleting the virtual network"); await azure.Networks.DeleteByIdAsync(virtualNetwork2.Id); Utilities.Log("Deleted the virtual network"); } finally { try { Utilities.Log("Deleting Resource Group: " + ResourceGroupName); await azure.ResourceGroups.DeleteByNameAsync(ResourceGroupName); Utilities.Log("Deleted Resource Group: " + ResourceGroupName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception ex) { Utilities.Log(ex); } } }
/** * Azure Network sample for managing express route circuits. * - Create Express Route circuit * - Create Express Route circuit peering. Please note: express route circuit should be provisioned by connectivity provider before this step. * - Adding authorization to express route circuit * - Create virtual network to be associated with virtual network gateway * - Create virtual network gateway * - Create virtual network gateway connection */ public static void RunSample(IAzure azure) { string rgName = SdkContext.RandomResourceName("rg", 20); string ercName = SdkContext.RandomResourceName("erc", 20); string vnetName = SdkContext.RandomResourceName("vnet", 20); string gatewayName = SdkContext.RandomResourceName("gtw", 20); string connectionName = SdkContext.RandomResourceName("con", 20); try { //============================================================ // create Express Route Circuit Utilities.Log("Creating express route circuit..."); IExpressRouteCircuit erc = azure.ExpressRouteCircuits.Define(ercName) .WithRegion(region) .WithNewResourceGroup(rgName) .WithServiceProvider("Equinix") .WithPeeringLocation("Silicon Valley") .WithBandwidthInMbps(50) .WithSku(ExpressRouteCircuitSkuType.PremiumMeteredData) .Create(); Utilities.Log("Created express route circuit"); //============================================================ // Create Express Route circuit peering. Please note: express route circuit should be provisioned by connectivity provider before this step. Utilities.Log("Creating express route circuit peering..."); erc.Peerings.DefineAzurePrivatePeering() .WithPrimaryPeerAddressPrefix("123.0.0.0/30") .WithSecondaryPeerAddressPrefix("123.0.0.4/30") .WithVlanId(200) .WithPeerAsn(100) .Create(); Utilities.Log("Created express route circuit peering"); //============================================================ // Adding authorization to express route circuit erc.Update() .WithAuthorization("myAuthorization") .Apply(); //============================================================ // Create virtual network to be associated with virtual network gateway Utilities.Log("Creating virtual network..."); INetwork network = azure.Networks.Define(vnetName) .WithRegion(region) .WithExistingResourceGroup(rgName) .WithAddressSpace("192.168.0.0/16") .WithSubnet("GatewaySubnet", "192.168.200.0/26") .WithSubnet("FrontEnd", "192.168.1.0/24") .Create(); //============================================================ // Create virtual network gateway Utilities.Log("Creating virtual network gateway..."); IVirtualNetworkGateway vngw1 = azure.VirtualNetworkGateways.Define(gatewayName) .WithRegion(region) .WithNewResourceGroup(rgName) .WithExistingNetwork(network) .WithExpressRoute() .WithSku(VirtualNetworkGatewaySkuName.Standard) .Create(); Utilities.Log("Created virtual network gateway"); //============================================================ // Create virtual network gateway connection Utilities.Log("Creating virtual network gateway connection..."); vngw1.Connections.Define(connectionName) .WithExpressRoute(erc) // Note: authorization key is required only in case express route circuit and virtual network gateway are in different subscriptions // .WithAuthorization(erc.Inner.Authorizations.First().AuthorizationKey) .Create(); Utilities.Log("Created virtual network gateway connection"); } finally { try { Utilities.Log("Deleting Resource Group: " + rgName); azure.ResourceGroups.BeginDeleteByName(rgName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception ex) { Utilities.Log(ex); } } }
internal Network(INetwork network) { this.network = network; }
private static ITraceFlowSolver CreateTraceFlowSolver() { int num; INetFlag netFlag; ITraceFlowSolver solver = (ITraceFlowSolver) new TraceFlowSolverClass(); INetSolver solver2 = (INetSolver)solver; INetwork network = m_pAnalystGN.Network; solver2.SourceNetwork = network; INetElements elements = (INetElements)network; if (m_JunFlags.Count > 0) { IJunctionFlag[] junctionOrigins = new IJunctionFlag[m_JunFlags.Count]; for (num = 0; num < m_JunFlags.Count; num++) { netFlag = (m_JunFlags[num] as NetFlagWrap).NetFlag; junctionOrigins[num] = (IJunctionFlag)netFlag; } (solver as ITraceFlowSolverGEN).PutJunctionOrigins(ref junctionOrigins); } if (m_EdgeFlags.Count > 0) { IEdgeFlag[] edgeOrigins = new IEdgeFlag[m_EdgeFlags.Count]; for (num = 0; num < m_EdgeFlags.Count; num++) { netFlag = (m_EdgeFlags[num] as NetFlagWrap).NetFlag; edgeOrigins[num] = (IEdgeFlag)netFlag; } (solver as ITraceFlowSolverGEN).PutEdgeOrigins(ref edgeOrigins); } INetSolverWeightsGEN sgen = (INetSolverWeightsGEN)solver; if (JunctionWeight != null) { sgen.JunctionWeight = JunctionWeight; } if (FromToEdgeWeight != null) { sgen.JunctionWeight = FromToEdgeWeight; } if (ToFromEdgeWeight != null) { sgen.JunctionWeight = ToFromEdgeWeight; } if (JunctionFilterWeight != null) { sgen.JunctionFilterWeight = JunctionFilterWeight; } if (FromToEdgeFilterWeight != null) { sgen.FromToEdgeFilterWeight = FromToEdgeFilterWeight; } if (ToFromEdgeFilterWeight != null) { sgen.ToFromEdgeFilterWeight = ToFromEdgeFilterWeight; } if (JuncfromValues != null) { sgen.SetFilterRanges(esriElementType.esriETJunction, ref JuncfromValues, ref JunctoValues); sgen.SetFilterType(esriElementType.esriETJunction, esriWeightFilterType.esriWFRange, ApplyJuncFilterWeight); } else { sgen.SetFilterType(esriElementType.esriETJunction, esriWeightFilterType.esriWFNone, ApplyJuncFilterWeight); } if (EdgefromValues != null) { sgen.SetFilterRanges(esriElementType.esriETEdge, ref EdgefromValues, ref EdgetoValues); sgen.SetFilterType(esriElementType.esriETEdge, esriWeightFilterType.esriWFRange, ApplyJuncFilterWeight); } else { sgen.SetFilterType(esriElementType.esriETEdge, esriWeightFilterType.esriWFNone, ApplyEdgeFilterWeight); } INetElementBarriers netElementBarriers = GetNetElementBarriers(esriElementType.esriETJunction); if (netElementBarriers != null) { (solver as INetSolver).set_ElementBarriers(esriElementType.esriETJunction, netElementBarriers); } netElementBarriers = GetNetElementBarriers(esriElementType.esriETEdge); if (netElementBarriers != null) { (solver as INetSolver).set_ElementBarriers(esriElementType.esriETEdge, netElementBarriers); } return(solver); }
public LidgrenInterface(INetwork network, Type peerType, RSAParameters rsaParameters) { if (peerType == null) { throw new ArgumentNullException(nameof(peerType)); } mNetwork = network ?? throw new ArgumentNullException(nameof(network)); var configuration = mNetwork.Configuration; if (configuration == null) { throw new ArgumentNullException(nameof(mNetwork.Configuration)); } mRng = new RNGCryptoServiceProvider(); mRsa = new RSACryptoServiceProvider(); mRsa.ImportParameters(rsaParameters); mPeerConfiguration = new NetPeerConfiguration( $"{VersionHelper.ExecutableVersion} {VersionHelper.LibraryVersion} {SharedConstants.VersionName}" ) { AcceptIncomingConnections = configuration.IsServer }; mPeerConfiguration.DisableMessageType(NetIncomingMessageType.Receipt); mPeerConfiguration.EnableMessageType(NetIncomingMessageType.UnconnectedData); if (configuration.IsServer) { mPeerConfiguration.EnableMessageType(NetIncomingMessageType.DiscoveryRequest); mPeerConfiguration.EnableMessageType(NetIncomingMessageType.ConnectionApproval); mPeerConfiguration.AcceptIncomingConnections = true; mPeerConfiguration.MaximumConnections = configuration.MaximumConnections; //mPeerConfiguration.LocalAddress = DnsUtils.Resolve(config.Host); //mPeerConfiguration.EnableUPnP = true; mPeerConfiguration.Port = configuration.Port; } if (Debugger.IsAttached) { mPeerConfiguration.EnableMessageType(NetIncomingMessageType.DebugMessage); mPeerConfiguration.EnableMessageType(NetIncomingMessageType.ErrorMessage); mPeerConfiguration.EnableMessageType(NetIncomingMessageType.Error); } else { mPeerConfiguration.DisableMessageType(NetIncomingMessageType.DebugMessage); mPeerConfiguration.DisableMessageType(NetIncomingMessageType.ErrorMessage); mPeerConfiguration.DisableMessageType(NetIncomingMessageType.Error); } if (Debugger.IsAttached) { mPeerConfiguration.ConnectionTimeout = 60; mPeerConfiguration.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage); } else { mPeerConfiguration.ConnectionTimeout = 15; mPeerConfiguration.DisableMessageType(NetIncomingMessageType.VerboseDebugMessage); } mPeerConfiguration.PingInterval = 2.5f; mPeerConfiguration.UseMessageRecycling = true; var constructorInfo = peerType.GetConstructor(new[] { typeof(NetPeerConfiguration) }); if (constructorInfo == null) { throw new ArgumentNullException(nameof(constructorInfo)); } var constructedPeer = constructorInfo.Invoke(new object[] { mPeerConfiguration }) as NetPeer; mPeer = constructedPeer ?? throw new ArgumentNullException(nameof(constructedPeer)); mGuidLookup = new Dictionary <long, Guid>(); SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); mPeer?.RegisterReceivedCallback( peer => { lock (mPeer) { if (OnPacketAvailable == null) { Log.Debug("Unhandled inbound Lidgren message."); Log.Diagnostic($"Unhandled message: {TryHandleInboundMessage()}"); return; } OnPacketAvailable(this); } } ); }
public double EvaluateNetwork(INetwork cppn) { lock (locker) { m_evalCount++; SharpNeatLib.NeatGenome.NeatGenome tempGenomeBallOwner = m_substrateBallOwner.GenerateGenome(cppn); INetwork tempNetBallOwner = tempGenomeBallOwner.Decode(HyperNEATParameters.substrateActivationFunction); SharpNeatLib.NeatGenome.NeatGenome tempGenomeNotBallOwner = m_substrateNotBallOwner.GenerateGenome(cppn); INetwork tempNetNotBallOwner = tempGenomeNotBallOwner.Decode(HyperNEATParameters.substrateActivationFunction); m_neatQTable.NetworkToEvaluateBallOwner = tempNetBallOwner; m_neatQTable.NetworkToEvaluateNotBallOwner = tempNetNotBallOwner; m_neatQTable.m_eventNewNetReady.Set(); m_neatQTable.m_eventNetFitnessReady.WaitOne(); double reward = m_neatQTable.PerformanceNetworkToEvaluate.Reward; double maxTime = NeatExpParams.EpisodesPerGenome * 3 * (m_neatQTable.Rows + m_neatQTable.Cols); double globalFitness = (m_neatQTable.PerformanceNetworkToEvaluate.GoalsScoredByTeam * NeatExpParams.GoalScoreEffect); double localFitness = (m_neatQTable.PerformanceNetworkToEvaluate.GoalsScoredByMe * NeatExpParams.GoalScoreEffect); double fitness = globalFitness; switch (NeatExpParams.CreditAssignment) { case CreditAssignments.Global: fitness = globalFitness; break; case CreditAssignments.Local: fitness = localFitness; break; case CreditAssignments.Mid: fitness = (localFitness + globalFitness) * 0.5; break; default: break; } if (m_neatQTable.PerformanceNetworkToEvaluate.GoalsScoredByTeam > 0) { fitness += (maxTime - m_neatQTable.PerformanceNetworkToEvaluate.PerformanceTime); } //- m_neatQTable.PerformanceNetworkToEvaluate.GoalsReceived * NeatExpParams.GoalRecvEffect if (fitness < 0) { fitness = 0; } Console.WriteLine("G: {0,-3} - Rew: {1,-10:F3} - Fitness: {2,-15:F3}", m_neatQTable.GenerationNo, reward, fitness); return(fitness); } }
/// <summary>Initializes a new instance of the <see cref="NetworkProfile"/> class.</summary> /// <param name="inetwork">The INetwork instance.</param> internal NetworkProfile(INetwork inetwork) { inet = inetwork ?? throw new ArgumentNullException(nameof(inetwork)); }
public ICrossValidationStrategy CreateCrossValidationStrategy(CrossValidationType crossValidationType, INetwork network, INetworkEvaluator evaluator) { switch (crossValidationType) { case CrossValidationType.KFold: return(new KFold(network, evaluator)); case CrossValidationType.HoldOut: return(new HoldOut()); default: return(new HoldOut()); } }