public void LoadPak(string fileName) { pak = new Adjutant.Saber3D.Halo1X.PakFile(fileName); rootNode = new TreeItemModel(pak.FileName); tv.ItemsSource = rootNode.Items; TabModel.Header = Utils.GetFileName(pak.FileName); TabModel.ToolTip = $"Pak Viewer - {TabModel.Header}"; foreach (var item in globalMenuButton.MenuItems.OfType <MenuItem>()) { item.Click -= GlobalContextItem_Click; } globalMenuButton.MenuItems.Clear(); var globalHandlers = Substrate.GetContextItems(GetFolderArgs(rootNode)); HasGlobalHandlers = globalHandlers.Any(); if (HasGlobalHandlers) { foreach (var item in globalHandlers) { globalMenuButton.MenuItems.Add(new MenuItem { Header = item.Path, Tag = item }); } foreach (var item in globalMenuButton.MenuItems.OfType <MenuItem>()) { item.Click += GlobalContextItem_Click; } } BuildItemTree(null); }
void Awake() { if (_instance != null) { Debug.LogError("Error: Multiple instances of Substrate. Substrate is a singleton."); Destroy(this.gameObject); return; } _instance = this; _substrates = new GameObject[8]; _substrates[0] = transform.FindChildInHierarchy("Substrate0").gameObject; _substrates[1] = transform.FindChildInHierarchy("Substrate1").gameObject; _substrates[2] = transform.FindChildInHierarchy("Substrate2").gameObject; _substrates[3] = transform.FindChildInHierarchy("Substrate3").gameObject; _substrates[4] = transform.FindChildInHierarchy("Substrate4").gameObject; _substrates[5] = transform.FindChildInHierarchy("Substrate5").gameObject; _substrates[6] = transform.FindChildInHierarchy("Substrate6").gameObject; _substrates[7] = transform.FindChildInHierarchy("Substrate7").gameObject; ResetSubstrate(); }
// Use this for initialization void Start() { substrate = GetComponentInChildren <Substrate>(); }
protected override void OnExit(ExitEventArgs e) { Substrate.Shutdown(); base.OnExit(e); }
/// <summary> /// Creates a genome decoder. We split this code into a separate method so that it can be re-used by the problem domain visualization code /// (it needs to decode genomes to phenomes in order to create a visualization). /// </summary> /// <param name="visualFieldResolution">The visual field's pixel resolution, e.g. 11 means 11x11 pixels.</param> /// <param name="lengthCppnInput">Indicates if the CPPNs being decoded have an extra input for specifying connection length.</param> public IGenomeDecoder <NeatGenome, IBlackBox> CreateGenomeDecoder(int visualFieldResolution, bool lengthCppnInput) { // Create two layer 'sandwich' substrate. int pixelCount = visualFieldResolution * visualFieldResolution; double pixelSize = BoxesVisualDiscriminationEvaluator.VisualFieldEdgeLength / visualFieldResolution; double originPixelXY = -1 + (pixelSize / 2.0); SubstrateNodeSet inputLayer = new SubstrateNodeSet(pixelCount); SubstrateNodeSet outputLayer = new SubstrateNodeSet(pixelCount); // Node IDs start at 1. (bias node is always zero). uint inputId = 1; uint outputId = (uint)(pixelCount + 1); double yReal = originPixelXY; for (int y = 0; y < visualFieldResolution; y++, yReal += pixelSize) { double xReal = originPixelXY; for (int x = 0; x < visualFieldResolution; x++, xReal += pixelSize, inputId++, outputId++) { inputLayer.NodeList.Add(new SubstrateNode(inputId, new double[] { xReal, yReal, -1.0 })); outputLayer.NodeList.Add(new SubstrateNode(outputId, new double[] { xReal, yReal, 1.0 })); } } /* * ////////////////////////////////////////////////////////////////////////////// * // Create two layer substrate. * SubstrateNodeSet inputLayer = new SubstrateNodeSet(Constants.INPUT_SIZE); * SubstrateNodeSet outputLayer = new SubstrateNodeSet(Constants.FULLY_CONNECTED_SIZE); * * // Inputs to Outputs Mapping * // 1 1 2 2 3 3 * // 1 2 3 1 1 2 2 3 3 * // 4 5 6 ---> 4 4 5 5 6 6 * // 7 8 9 4 4 5 5 6 6 * // 7 7 8 8 9 9 * // 7 7 8 8 9 9 * * for (uint width = 0; width < Constants.INPUT_WIDTH; width++) * { * for (uint height = 0; height < Constants.INPUT_HEIGHT; height++) * { * // start + 1 because of bias node * uint inputID = (width * Constants.INPUT_HEIGHT) + height + 1; * inputLayer.NodeList.Add(new SubstrateNode(inputID, new double[] { inputID })); * * } * } * * // we're fully connected so we will have NEXT_LAYER_SIZE * IMAGE_SIZE weights. This is a lot. yes. * for (uint height = 0; height < Constants.OUTPUT_SIZE; height++) * { * for (uint width = 0; width < Constants.INPUT_SIZE; width++) * { * uint outputID = Constants.INPUT_SIZE + (height * Constants.INPUT_SIZE) + width + 1; * * outputLayer.NodeList.Add(new SubstrateNode(outputID, new double[] { outputID })); * } * } * /////////////////////////////////////////////////////////////////////////// */ List <SubstrateNodeSet> nodeSetList = new List <SubstrateNodeSet>(2); nodeSetList.Add(inputLayer); nodeSetList.Add(outputLayer); // Define connection mappings between layers/sets. List <NodeSetMapping> nodeSetMappingList = new List <NodeSetMapping>(1); nodeSetMappingList.Add(NodeSetMapping.Create(0, 1, (double?)null)); // Construct substrate. //Substrate substrate = new Substrate(nodeSetList, DefaultActivationFunctionLibrary.CreateLibraryNeat(SteepenedSigmoid.__DefaultInstance), 0, 0.2, 5, nodeSetMappingList); Substrate substrate = new Substrate(nodeSetList, DefaultActivationFunctionLibrary.CreateLibraryCppn(), 0, 0.2, 5, nodeSetMappingList); // Create genome decoder. Decodes to a neural network packaged with an activation scheme that defines a fixed number of activations per evaluation. IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = new HyperNeatDecoder(substrate, _activationSchemeCppn, _activationScheme, lengthCppnInput); return(genomeDecoder); }
/// <summary> /// Create a genome decoder for the experiment. /// </summary> protected override IGenomeDecoder <NeatGenome, IBlackBox> CreateHyperNeatGenomeDecoder() { // Create HyperNEAT network substrate. uint nodeId = 1; //-- Create input layer nodes. var inputLayer = new SubstrateNodeSet(nbInputs * f2); for (var i = 0; i < nbInputs; i++) { for (var j = 0; j < f; j++) { for (var k = 0; k < f; k++) { if (filter[j, k]) { var x = (double)j / f - 0.5; var y = (double)k / f - 0.5; inputLayer.NodeList.Add(new SubstrateNode(nodeId++, new double[] { x, y, -1 - i })); } } } } //-- Create hidden layer nodes. var hiddenLayers = new SubstrateNodeSet[nbClusters]; for (var i = 0; i < nbClusters; i++) { hiddenLayers[i] = new SubstrateNodeSet(f2); for (var j = 0; j < f; j++) { for (var k = 0; k < f; k++) { if (filter[j, k]) { var x = (double)j / f - 0.5; var y = (double)k / f - 0.5; hiddenLayers[i].NodeList.Add(new SubstrateNode(nodeId++, new double[] { x, y, 0 })); } } } } //-- Create output layer nodes. var outputLayers = new SubstrateNodeSet[nbClusters]; for (var i = 0; i < nbClusters; i++) { outputLayers[i] = new SubstrateNodeSet(f2); for (var j = 0; j < f; j++) { for (var k = 0; k < f; k++) { if (filter[j, k]) { var x = (double)j / f - 0.5; var y = (double)j / f - 0.5; outputLayers[i].NodeList.Add(new SubstrateNode(nodeId++, new double[] { x, y, +1 + i })); } } } } // Connect up layers. List <SubstrateNodeSet> nodeSetList = new List <SubstrateNodeSet>(1 + 2 * nbClusters); nodeSetList.Add(inputLayer); foreach (var layer in hiddenLayers) { nodeSetList.Add(layer); } foreach (var layer in outputLayers) { nodeSetList.Add(layer); } List <NodeSetMapping> nodeSetMappingList = new List <NodeSetMapping>(2 * nbClusters); for (int i = 0; i < nbClusters; i++) { var inputLayerIdx = 0; var hiddenLayerIdx = 1 + i; var outputLayerIdx = 1 + nbClusters + i; nodeSetMappingList.Add(NodeSetMapping.Create(inputLayerIdx, hiddenLayerIdx, (double?)null)); nodeSetMappingList.Add(NodeSetMapping.Create(hiddenLayerIdx, outputLayerIdx, (double?)null)); } // Construct substrate. Substrate substrate = new Substrate(nodeSetList, DefaultActivationFunctionLibrary.CreateLibraryNeat(SteepenedSigmoid.__DefaultInstance), 0, 0.2, 5, nodeSetMappingList); // Create genome decoder. Decodes to a neural network packaged with an activation scheme that defines a fixed number of activations per evaluation. IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = new HyperNeatDecoder(substrate, _activationSchemeCppn, _activationScheme, _lengthCppnInput); return(genomeDecoder); }
/// <summary> /// Create a genome decoder for the experiment. /// </summary> public IGenomeDecoder <NeatGenome, IBlackBox> CreateGenomeDecoder() { // Create HyperNEAT network substrate. //-- Create input layer nodes. SubstrateNodeSet inputLayer = new SubstrateNodeSet(13); //-- Hip joint inputs. // Left hip joint. AddNode(inputLayer, 1, -1.0, +1.0, -1.0); // Angular velocity. AddNode(inputLayer, 2, -0.5, +1.0, -1.0); // Angle. // Right hip joint. AddNode(inputLayer, 3, +0.5, +1.0, -1.0); // Angle. AddNode(inputLayer, 4, +1.0, +1.0, -1.0); // Angular velocity. //-- Knee joint inputs. // Left knee joint. AddNode(inputLayer, 5, -1.0, -1.0, -1.0); // Angular velocity. AddNode(inputLayer, 6, -0.5, -1.0, -1.0); // Angle. // Right knee joint. AddNode(inputLayer, 7, +0.5, -1.0, -1.0); // Angular velocity. AddNode(inputLayer, 8, +1.0, -1.0, -1.0); // Angle. //-- Torso inputs. AddNode(inputLayer, 9, 0.0, +1.0, -1.0); // Torso elevation. AddNode(inputLayer, 10, 0.0, +0.75, -1.0); // Torso angle. AddNode(inputLayer, 11, 0.0, +0.5, -1.0); // Torso angular velocity. AddNode(inputLayer, 12, 0.0, +0.25, -1.0); // Velocity X. AddNode(inputLayer, 13, 0.0, 0.0, -1.0); // Velocity Y. //-- Output layer nodes. SubstrateNodeSet outputLayer = new SubstrateNodeSet(4); AddNode(outputLayer, 14, -1.0, +1.0, +1.0); // Left hip torque. AddNode(outputLayer, 15, +1.0, +1.0, +1.0); // Right hip torque. AddNode(outputLayer, 16, -1.0, -1.0, +1.0); // Left knee torque. AddNode(outputLayer, 17, +1.0, -1.0, +1.0); // Right knee torque. //-- Hidden layer nodes. SubstrateNodeSet h1Layer = new SubstrateNodeSet(4); AddNode(h1Layer, 18, -1.0, +1.0, 0.0); AddNode(h1Layer, 19, +1.0, +1.0, 0.0); AddNode(h1Layer, 20, -1.0, -1.0, 0.0); AddNode(h1Layer, 21, +1.0, -1.0, 0.0); // Connect up layers. List <SubstrateNodeSet> nodeSetList = new List <SubstrateNodeSet>(2); nodeSetList.Add(inputLayer); nodeSetList.Add(outputLayer); nodeSetList.Add(h1Layer); List <NodeSetMapping> nodeSetMappingList = new List <NodeSetMapping>(1); nodeSetMappingList.Add(NodeSetMapping.Create(0, 1, (double?)null)); // Input -> Output. nodeSetMappingList.Add(NodeSetMapping.Create(0, 2, (double?)null)); // Input -> Hidden. nodeSetMappingList.Add(NodeSetMapping.Create(2, 1, (double?)null)); // Hidden -> Output. nodeSetMappingList.Add(NodeSetMapping.Create(1, 2, (double?)null)); // Output -> Hidden // Construct substrate. Substrate substrate = new Substrate(nodeSetList, DefaultActivationFunctionLibrary.CreateLibraryNeat(SteepenedSigmoid.__DefaultInstance), 0, 0.2, 5, nodeSetMappingList); // Create genome decoder. Decodes to a neural network packaged with an activation scheme that defines a fixed number of activations per evaluation. IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = new HyperNeatDecoder(substrate, _activationSchemeCppn, _activationScheme, _lengthCppnInput); return(genomeDecoder); }
private void menuOutput_Click(object sender, RoutedEventArgs e) { Substrate.ShowOutput(); }
private IEnumerator GenerateHeatMap() { paintModeToggle.interactable = false; yield return(null); PositionScaleBarSetColor(); int colCount = simulate.ny2.Length; foreach (int i in simulate.ny2) { if (i > 0) { colCount += 1; } } heatmap.GetComponent <GridLayoutGroup>().constraintCount = colCount; int counter = 0; for (int ei = 0; ei < simulate.ne.Length; ei++) { Enzyme enz = Instantiate(enzPrefab, enzymes).GetComponent <Enzyme>(); enz.SetColor(simulate.enzyme_colors[ei]); enz.SetName(simulate.enzyme_names[ei], Color.clear); if (barMode[0]) { enz.SetBarMode(); } for (int si = 0; si < simulate.ny1.Length; si++) { if (ei == 0) { Substrate sub = Instantiate(subPrefab, substrates).GetComponent <Substrate>(); if (simulate.ny2[si] > 0) { Color[] otherColors = new Color[2]; for (int i = 0; i < otherColors.Length; i++) { otherColors[i] = new Color(simulate.substrate_colors[si, i].r, simulate.substrate_colors[si, i].g, simulate.substrate_colors[si, i].b, .2f); } sub.SetType(true); sub.SetName(simulate.substrate_names[si] + " A", Color.clear); sub.SetColor(simulate.substrate_colors[si, 0], 0); sub.SetColor(otherColors[1], 1); Substrate sub2 = Instantiate(subPrefab, substrates).GetComponent <Substrate>(); sub2.SetType(true); sub2.SetName(simulate.substrate_names[si] + " B", Color.clear); sub2.SetColor(simulate.substrate_colors[si, 1], 1); sub2.SetColor(otherColors[0], 0); if (barMode[1]) { sub2.SetBarMode(1); } } else { sub.SetType(false); sub.SetName(simulate.substrate_names[si], Color.clear); sub.SetColor(simulate.substrate_colors[si, 0], 0); } if (barMode[1]) { sub.SetBarMode(0); } } NewSquare(si, ei, 0); if (simulate.ny2[si] > 0) { NewSquare(si, ei, 1); } counter += 1; if (counter % 10 == 0) { yield return(null); } } } SetScaleBarText(); hmSquares = heatmap.GetComponentsInChildren <HeatmapSquare>(); paintModeToggle.interactable = true; }
/// <summary> /// Create a genome decoder for the experiment. /// </summary> protected override IGenomeDecoder <NeatGenome, IBlackBox> CreateHyperNeatGenomeDecoder() { // Create HyperNEAT network substrate. uint nodeId = 1; //-- Create input layer nodes. var inputLayer = new SubstrateNodeSet(samples.Length); for (int v = 0; v < samples.GetLength(0); v++) // variables { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { var x = 2 * (double)i / n - 1; var y = 2 * (double)j / m - 1; var z = -(double)v / samples.GetLength(0); inputLayer.NodeList.Add(new SubstrateNode(nodeId++, new double[] { x, y, z })); } } } //-- Create output layer nodes. var outputLayers = new SubstrateNodeSet[nbClusters]; for (var c = 0; c < nbClusters; c++) // clusters { outputLayers[c] = new SubstrateNodeSet(n * m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { var x = 2 * (double)i / n - 1; var y = 2 * (double)j / m - 1; var z = c / nbClusters; outputLayers[c].NodeList.Add(new SubstrateNode(nodeId++, new double[] { x, y, z })); } } } // Connect up layers. List <SubstrateNodeSet> nodeSetList = new List <SubstrateNodeSet>(1 + nbClusters); nodeSetList.Add(inputLayer); foreach (var layer in outputLayers) { nodeSetList.Add(layer); } List <NodeSetMapping> nodeSetMappingList = new List <NodeSetMapping>(nbClusters); for (int i = 0; i < nbClusters; i++) { var inputLayerIdx = 0; var outputLayerIdx = 1 + i; nodeSetMappingList.Add(NodeSetMapping.Create(inputLayerIdx, outputLayerIdx, (double?)null)); } // Construct substrate. Substrate substrate = new Substrate(nodeSetList, DefaultActivationFunctionLibrary.CreateLibraryNeat(SteepenedSigmoid.__DefaultInstance), 0, 0.2, 5, nodeSetMappingList); // Create genome decoder. Decodes to a neural network packaged with an activation scheme that defines a fixed number of activations per evaluation. IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = new HyperNeatDecoder(substrate, _activationSchemeCppn, _activationScheme, _lengthCppnInput); return(genomeDecoder); }
/// <summary> /// Creates a new HyperNEAT genome decoder that can be used to convert a genome into a phenome. /// </summary> public IGenomeDecoder <NeatGenome, IBlackBox> CreateGenomeDecoder() { // Create an input and an output layer for the HyperNEAT // substrate. Each layer corresponds to the game board // with 9 squares. SubstrateNodeSet inputLayer = new SubstrateNodeSet(9); SubstrateNodeSet outputLayer = new SubstrateNodeSet(9); // Each node in each layer needs a unique ID. // The input nodes use ID range [1,9] and // the output nodes use [10,18]. uint inputId = 1, outputId = 10; // The game board is represented as a 2-dimensional plane. // Each square is at -1, 0, or 1 in the x and y axis. // Thus, the game board looks like this: // // (-1,1) | (0,1) | (1,1) // (-1,0) | (0,0) | (1,0) // (-1,-1) | (0,-1) | (1,-1) // // Note that the NeatPlayer class orders the board from // left to right, then top to bottom. So we need to create // nodes with the following IDs: // // 1 | 2 | 3 // 4 | 5 | 6 // 7 | 8 | 9 // for (int x = -1; x <= 1; x++) { for (int y = 1; y >= -1; y--, inputId++, outputId++) { inputLayer.NodeList.Add(new SubstrateNode(inputId, new double[] { x, y })); outputLayer.NodeList.Add(new SubstrateNode(outputId, new double[] { x, y })); } } List <SubstrateNodeSet> nodeSetList = new List <SubstrateNodeSet>(2); nodeSetList.Add(inputLayer); nodeSetList.Add(outputLayer); // Define a connection mapping from the input layer to the output layer. List <NodeSetMapping> nodeSetMappingList = new List <NodeSetMapping>(1); nodeSetMappingList.Add(NodeSetMapping.Create(0, 1, (double?)null)); // Construct the substrate using a steepened sigmoid as the phenome's // activation function. All weights under 0.2 will not generate // connections in the final phenome. Substrate substrate = new Substrate(nodeSetList, DefaultActivationFunctionLibrary.CreateLibraryCppn(), 0, 0.2, 5, nodeSetMappingList); // Create genome decoder. Decodes to a neural network packaged with // an activation scheme that defines a fixed number of activations per evaluation. IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = new HyperNeatDecoder(substrate, _activationSchemeCppn, _activationScheme, false); return(genomeDecoder); }
// This is built from these two sources: //http://www.nashcoding.com/2010/10/29/tutorial-%E2%80%93-evolving-neural-networks-with-sharpneat-2-part-3/ //SharpNeat.Domains.BoxesVisualDiscrimination.BoxesVisualDiscriminationExperiment.CreateGenomeDecoder() //TODO: Instead of hardcoding input and output as 2D squares, the constructor should take enums for common shapes { Line, Square, Cube, CirclePerimiter, CircleArea, SphereShell, SphereFilled } public IGenomeDecoder <NeatGenome, IBlackBox> CreateGenomeDecoder(int inputSizeXY, int outputSizeXY) { int numInputs = inputSizeXY * inputSizeXY; int numOutputs = outputSizeXY * outputSizeXY; SubstrateNodeSet inputLayer = new SubstrateNodeSet(numInputs); SubstrateNodeSet outputLayer = new SubstrateNodeSet(numOutputs); // Each node in each layer needs a unique ID // Node IDs start at 1. (bias node is always zero) // The input nodes use ID range { 1, inputSize^2 } and // the output nodes are the next outputSize^2. uint inputId = 1; uint outputId = Convert.ToUInt32(numInputs + 1); var inputCells = Math2D.GetCells_WithinSquare(_inputSizeWorld, inputSizeXY); var outputCells = Math2D.GetCells_WithinSquare(_outputSizeWorld, outputSizeXY); for (int y = 0; y < inputSizeXY; y++) { for (int x = 0; x < inputSizeXY; x++) { inputId++; outputId++; Point inputPoint = inputCells[(y * inputSizeXY) + x].center; Point outputPoint = outputCells[(y * outputSizeXY) + x].center; inputLayer.NodeList.Add(new SubstrateNode(inputId, new double[] { inputPoint.X, inputPoint.Y, -1d })); outputLayer.NodeList.Add(new SubstrateNode(outputId, new double[] { outputPoint.X, outputPoint.Y, 1d })); } } List <SubstrateNodeSet> nodeSetList = new List <SubstrateNodeSet>(); nodeSetList.Add(inputLayer); nodeSetList.Add(outputLayer); //TODO: The two samples that I copied from have the same number of inputs and outputs. This mapping may be too simplistic when the counts are different // Define a connection mapping from the input layer to the output layer. List <NodeSetMapping> nodeSetMappingList = new List <NodeSetMapping>(); nodeSetMappingList.Add(NodeSetMapping.Create(0, 1, (double?)null)); // Construct the substrate using a steepened sigmoid as the phenome's // activation function. All weights under 0.2 will not generate // connections in the final phenome. Substrate substrate = new Substrate(nodeSetList, DefaultActivationFunctionLibrary.CreateLibraryCppn(), 0, 0.2, 5, nodeSetMappingList); // Create genome decoder. Decodes to a neural network packaged with // an activation scheme that defines a fixed number of activations per evaluation. IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = new HyperNeatDecoder(substrate, _activationSchemeCppn, _activationScheme, false); return(genomeDecoder); }
void TestAutomaticAuth(Tpm2 tpm, TestContext testCtx) { TpmHandle hPrim = Substrate.LoadRsaPrimary(tpm); // Make an RSA encryption key. var decScheme = new SchemeOaep(Substrate.Random(TpmCfg.HashAlgs)); var sigScheme = new SchemeRsassa(Substrate.Random(TpmCfg.HashAlgs)); ushort keyLength = Substrate.RandomRsaKeySize(decScheme.hashAlg); var inPub = new TpmPublic(Substrate.Random(TpmCfg.HashAlgs), ObjectAttr.Decrypt | ObjectAttr.Sign | ObjectAttr.FixedParent | ObjectAttr.FixedTPM | ObjectAttr.UserWithAuth | ObjectAttr.SensitiveDataOrigin, null, new RsaParms(new SymDefObject(), null, keyLength, 0), new Tpm2bPublicKeyRsa()); TpmPublic keyPublic; TpmPrivate keyPrivate = Substrate.Create(tpm, hPrim, inPub, out keyPublic); TpmHandle keyHandle = null; tpm._Behavior.Strict = true; try { // No auth session is added automatically when TPM object is in strict mode. tpm._ExpectError(TpmRc.AuthMissing) .Load(hPrim, keyPrivate, keyPublic); // Now explicitly request an auth session of appropriate type keyHandle = tpm[Auth.Default].Load(hPrim, keyPrivate, keyPublic); } finally { tpm._Behavior.Strict = false; } byte[] message = Substrate.RandBytes(1, TpmHelper.MaxOaepMsgSize(keyLength, decScheme.hashAlg)); byte[] encrypted = tpm.RsaEncrypt(keyHandle, message, decScheme, null); // An auth session is added automatically when TPM object is not in strict mode. byte[] decrypted1 = tpm.RsaDecrypt(keyHandle, encrypted, decScheme, null); TpmAlgId auditHashAlg = Substrate.Random(TpmCfg.HashAlgs); byte[] nonceTpm; // AuthSession object can be built from session handle concatenated, if necessary, // with session flags and unencrypted salt value (not used in this example). AuthSession auditSess = tpm.StartAuthSession( TpmRh.Null, // no salt TpmRh.Null, // no bind object Substrate.RandomNonce(auditHashAlg), // nonceCaller null, // no salt TpmSe.Hmac, // session type new SymDef(), // no encryption/decryption auditHashAlg, // authHash out nonceTpm) + (SessionAttr.ContinueSession | SessionAttr.Audit); /* * Alternatively one of the StartAuthSessionEx helpers can be used) * AuthSession auditSess = tpm.StartAuthSessionEx(TpmSe.Hmac, auditHashAlg, null, * SessionAttr.ContinueSession | SessionAttr.Audit); */ // TSS-specific call to verify TPM auditing correctness. tpm._SetCommandAuditAlgorithm(auditHashAlg); // Appropriate auth value is added automatically into the provided session byte[] decrypted2 = tpm[auditSess]._Audit() .RsaDecrypt(keyHandle, encrypted, decScheme, null); ISignatureUnion sig; Attest attest; // A session is added automatically to authorize TpmRh.Endorsement usage. attest = tpm.GetSessionAuditDigest(TpmRh.Endorsement, TpmRh.Null, auditSess, null, new NullSigScheme(), out sig); // But if the corresponding auth value stored in the Tpm2 object is invalid, ... AuthValue endorsementAuth = tpm.EndorsementAuth; tpm.EndorsementAuth = Globs.ByteArray(16, 0xde); // ... the command will fail tpm._ExpectError(TpmRc.BadAuth) .GetSessionAuditDigest(TpmRh.Endorsement, TpmRh.Null, auditSess, null, new NullSigScheme(), out sig); // Restore correct auth value. tpm.EndorsementAuth = endorsementAuth; // Verify that both decryption and auditing worked correctly. SessionAuditInfo info = (SessionAuditInfo)attest.attested; byte[] auditDigest = tpm._GetAuditHash(); testCtx.AssertEqual("AuditSessionDigest", info.sessionDigest, auditDigest); testCtx.AssertEqual("Decryption", decrypted1, decrypted2); // Change auth value of the decryption key. TpmPrivate newKeyPrivate = tpm.ObjectChangeAuth(keyHandle, hPrim, Substrate.RandomAuth(keyPublic.nameAlg)); TpmHandle newKeyHandle = tpm.Load(hPrim, newKeyPrivate, keyPublic); auditSess.Attrs &= ~SessionAttr.AuditExclusive; // Correct auth value (corresponding to newKeyHandle, and different from // the one used for keyHandle) will be added to auditSess. decrypted1 = tpm[auditSess]._Audit().RsaDecrypt(newKeyHandle, encrypted, decScheme, null); // And now two sessions are auto-generated (for TpmRh.Endorsement and keyHandle). attest = tpm.GetSessionAuditDigest(TpmRh.Endorsement, keyHandle, auditSess, null, sigScheme, out sig); bool sigOk = keyPublic.VerifySignatureOverData( Marshaller.GetTpmRepresentation(attest), sig); testCtx.Assert("AuditSessionSignatute.1", sigOk); // Here the first session is generated based on session type indicator // (Auth.Pw), and the second one is added automatically. attest = tpm[Auth.Pw].GetSessionAuditDigest(TpmRh.Endorsement, keyHandle, auditSess, null, sigScheme, out sig); // Verify that auditing worked correctly. sigOk = keyPublic.VerifySignatureOverData( Marshaller.GetTpmRepresentation(attest), sig); testCtx.Assert("AuditSessionSignatute.2", sigOk); tpm.FlushContext(newKeyHandle); tpm.FlushContext(auditSess); if (!TestCfg.HasTRM) { // Deplete TPM's active session storage List <AuthSession> landfill = new List <AuthSession>(); for (;;) { tpm._AllowErrors(); AuthSession s = tpm.StartAuthSessionEx(TpmSe.Hmac, Substrate.Random(TpmCfg.HashAlgs), SessionAttr.ContinueSession); if (!tpm._LastCommandSucceeded()) { break; } landfill.Add(s); } // Check if session type indicators are processed correctly tpm[Auth.Hmac]._ExpectError(TpmRc.SessionMemory) .RsaDecrypt(keyHandle, encrypted, null, null); tpm[Auth.Pw].RsaDecrypt(keyHandle, encrypted, null, null); // Check if default session type defined by the TPM device is processed correctly bool needHmac = tpm._GetUnderlyingDevice().NeedsHMAC; tpm._GetUnderlyingDevice().NeedsHMAC = true; tpm._ExpectError(TpmRc.SessionMemory) .RsaDecrypt(keyHandle, encrypted, null, null); tpm[Auth.Default]._ExpectError(TpmRc.SessionMemory) .RsaDecrypt(keyHandle, encrypted, null, null); tpm._GetUnderlyingDevice().NeedsHMAC = false; tpm.RsaDecrypt(keyHandle, encrypted, null, null); tpm[Auth.Default].RsaDecrypt(keyHandle, encrypted, null, null); tpm._GetUnderlyingDevice().NeedsHMAC = needHmac; landfill.ForEach(s => tpm.FlushContext(s)); } tpm.FlushContext(keyHandle); } // TestAutomaticAuth
void TestCertifyX509Impl(Tpm2 tpm, TestContext testCtx, TpmPublic subjectTemplate, TpmPublic sigKeyTemplate, PolicyTree policy, string testLabel) { var partialCert = X509Helpers.MakePartialCert(subjectTemplate); var partialCertBytes = partialCert.GetDerEncoded(); // If you want to paste in your own hex put it here and s //var partialCertBytes = Globs.ByteArrayFromHex("01020304"); // Certify RSA with RSA TpmPublic certifyingKeyPub, keyToBeCertifiedPub; TpmHandle hSigKey = Substrate.CreatePrimary(tpm, sigKeyTemplate, out certifyingKeyPub); TpmHandle hSubjectKey = Substrate.CreatePrimary(tpm, subjectTemplate, out keyToBeCertifiedPub); AuthSession sess = tpm.StartAuthSessionEx(TpmSe.Policy, TpmAlgId.Sha256); sess.RunPolicy(tpm, policy); ISignatureUnion sig; byte[] tbsHash; byte[] addedTo = tpm[sess].CertifyX509(hSubjectKey, hSigKey, null, new NullSigScheme(), partialCertBytes, out tbsHash, out sig); tpm.FlushContext(sess); tpm.FlushContext(hSubjectKey); var addedToCert = AddedToCertificate.FromDerEncoding(addedTo); X509Certificate returnedCert = X509Helpers.AssembleCertificate(partialCert, addedToCert, sig is SignatureRsa ? ((SignatureRsa)sig).GetTpmRepresentation() : ((SignatureEcc)sig).GetTpmRepresentation()); // Does the expected hash match the returned hash? var tbsBytes = returnedCert.GetTbsCertificate(); var expectedTbsHash = TpmHash.FromData(TpmAlgId.Sha256, tbsBytes); Debug.Assert(Globs.ArraysAreEqual(expectedTbsHash.HashData, tbsHash)); // Is the cert properly signed? if (TpmHelper.GetScheme(sigKeyTemplate).GetUnionSelector() != TpmAlgId.Rsapss) { // Software crypto layer does not support PSS bool sigOk = certifyingKeyPub.VerifySignatureOverHash(tbsHash, sig); if (sigKeyTemplate.type == TpmAlgId.Ecc) { #if !__NETCOREAPP2__ // No ECC in .Net Core testCtx.Assert("Sign" + testLabel, sigOk); #endif } else { testCtx.Assert("Sign" + testLabel, sigOk); } } tpm.VerifySignature(hSigKey, tbsHash, sig); tpm.FlushContext(hSigKey); }
private void btnExportBitmaps_Click(object sender, RoutedEventArgs e) { var export = Substrate.GetSharedFunction <ExportBitmaps>("Reclaimer.Plugins.ModelViewerPlugin.ExportBitmaps"); export?.Invoke(renderGeometry); }
private static IGenomeDecoder <NeatGenome, IBlackBox> CreateGenomeDecoder_Finish(HyperNEAT_Args args, NetworkActivationScheme activationSchemeCppn, NetworkActivationScheme activationSchemeSubstrate) { int numInputs = args.NeuronCount_Input; int numOutputs = args.NeuronCount_Output; SubstrateNodeSet inputLayer = new SubstrateNodeSet(numInputs); SubstrateNodeSet outputLayer = new SubstrateNodeSet(numOutputs); //NOTE: Can't put a neuron at the origin, because the bias node is there - see Substrate.CreateNetworkDefinition() // Each node in each layer needs a unique ID // Node IDs start at 1. (bias node is always zero) // The input nodes use ID range { 1, inputSize^2 } and // the output nodes are the next outputSize^2. uint inputId = 1; uint outputId = Convert.ToUInt32(numInputs + 1); for (int cntr = 0; cntr < args.InputPositions.Length; cntr++) { inputLayer.NodeList.Add(new SubstrateNode(inputId, args.InputPositions[cntr].ToArray())); inputId++; } for (int cntr = 0; cntr < args.OutputPositions.Length; cntr++) { outputLayer.NodeList.Add(new SubstrateNode(outputId, args.OutputPositions[cntr].ToArray())); outputId++; } List <SubstrateNodeSet> nodeSetList = new List <SubstrateNodeSet> { inputLayer, outputLayer }; //TODO: The two samples that I copied from have the same number of inputs and outputs. This mapping may be too simplistic when the counts are different //TODO: Notes on using hidden layers: // The above example is a simple 2-layer CPPN with no hidden layers. If you want to add hidden layers, you simply need to create an additional SubstrateNodeSet // and add it to the nodeSetList. Then you will need two NodeSetMappings, one from the input (0) to the hidden (1) layer, and one from the hidden (1) to the // output (2) layer.3 // Define a connection mapping from the input layer to the output layer. List <NodeSetMapping> nodeSetMappingList = new List <NodeSetMapping>(); nodeSetMappingList.Add(NodeSetMapping.Create ( //NOTE: Substrate is hardcoded to 0 and 1 for input and output. 2 and up is hidden nodes. So passing these as params unnecessary 0, // this is the index into nodeSetList (the item in nodeSetList that is the input layer) 1, // index of nodeSetList that is the output layer (double?)null )); // Construct the substrate using a steepened sigmoid as the phenome's activation function. All weights // under .2 will not generate connections in the final phenome //Substrate substrate = new Substrate(nodeSetList, DefaultActivationFunctionLibrary.CreateLibraryCppn(), 0, .2, 5, nodeSetMappingList); Substrate substrate = new Substrate(nodeSetList, DefaultActivationFunctionLibrary.CreateLibraryNeat(SteepenedSigmoid.__DefaultInstance), 0, .2, 5, nodeSetMappingList); // Create genome decoder. Decodes to a neural network packaged with // an activation scheme that defines a fixed number of activations per evaluation. //IGenomeDecoder<NeatGenome, IBlackBox> genomeDecoder = new HyperNeatDecoder(substrate, _activationSchemeCppn, _activationScheme, false); return(new HyperNeatDecoder(substrate, activationSchemeCppn, activationSchemeSubstrate, true)); }
private void RecentsItem_Click(object sender, RoutedEventArgs e) { var fileName = (sender as MenuItem)?.Tag as string; Substrate.HandlePhysicalFile(fileName); }
private void btnExportBitmaps_Click(object sender, RoutedEventArgs e) { var export = Substrate.GetSharedFunction <ExportBitmaps>(Constants.SharedFuncExportBitmaps); export.Invoke(geometry); }
void Start() { _substrate = Substrate.Instance; }
/// <summary> /// Create a genome decoder for the experiment. /// </summary> protected override IGenomeDecoder <NeatGenome, IBlackBox> CreateHyperNeatGenomeDecoder() { // Create HyperNEAT network substrate. uint nodeId = 1; //-- Create input layer nodes. SubstrateNodeSet inputLayer = new SubstrateNodeSet(_dataset.InputCount); for (var i = 0; i < _dataset.InputCount; i++) { inputLayer.NodeList.Add(new SubstrateNode(nodeId++, SetInputNodePosition(i).Extend(-1))); } //-- Create output layer nodes. var outputLayers = new SubstrateNodeSet[nbClusters]; for (var i = 0; i < nbClusters; i++) { outputLayers[i] = new SubstrateNodeSet(1); outputLayers[i].NodeList.Add(new SubstrateNode(nodeId++, SetOutputNodePosition(i).Extend(+1 + i))); } //-- Create hidden layer nodes. SubstrateNodeSet hiddenLayer = null; if (HiddenNodesCount > 0) { hiddenLayer = new SubstrateNodeSet(HiddenNodesCount); for (var i = 0; i < HiddenNodesCount; i++) { hiddenLayer.NodeList.Add(new SubstrateNode(nodeId++, SetHiddenNodePosition(i).Extend(0))); } } // Connect up layers. List <SubstrateNodeSet> nodeSetList = new List <SubstrateNodeSet>(2 + nbClusters + (HiddenNodesCount > 0 ? 1 : 0)); nodeSetList.Add(inputLayer); for (var i = 0; i < nbClusters; i++) { nodeSetList.Add(outputLayers[i]); } if (HiddenNodesCount > 0) { nodeSetList.Add(hiddenLayer); } List <NodeSetMapping> nodeSetMappingList = new List <NodeSetMapping>(nbClusters * (1 + (HiddenNodesCount > 0 ? 2 : 0))); var inputIdx = 0; var hiddenIdx = nbClusters + 1; for (var i = 0; i < nbClusters; i++) { var outputIdx = i + 1; if (HiddenNodesCount > 0) { nodeSetMappingList.Add(NodeSetMapping.Create(inputIdx, hiddenIdx, (double?)null)); // Input -> Hidden. nodeSetMappingList.Add(NodeSetMapping.Create(hiddenIdx, outputIdx, (double?)null)); // Hidden-> Output. nodeSetMappingList.Add(NodeSetMapping.Create(inputIdx, outputIdx, (double?)null)); // Input -> Output. } else { nodeSetMappingList.Add(NodeSetMapping.Create(inputIdx, outputIdx, (double?)null)); // Input -> Output. } } // Construct substrate. Substrate substrate = new Substrate(nodeSetList, DefaultActivationFunctionLibrary.CreateLibraryNeat(SteepenedSigmoid.__DefaultInstance), 0, 0.2, 5, nodeSetMappingList); // Create genome decoder. Decodes to a neural network packaged with an activation scheme that defines a fixed number of activations per evaluation. IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = new HyperNeatDecoder(substrate, _activationSchemeCppn, _activationScheme, _lengthCppnInput); return(genomeDecoder); }
void ActivateAikSample(Tpm2 tpm, TestContext testCtx) { // Use an RSA primary key in the Endorsement hierarchy (EK) to 'activate' // another primary in the Endorsement hierarchy (AIK). // Note: this procedure can be used to activate a key in the Storage hierarchy, too. // "Activation" means secure passing sensitive data generated by a CA (e.g. // a symmetric key protecting a freshly generated certificate), so that only // a device with the TPM owning the target AIK and EK can access these data. // Create a primary key that we will certify. ////////////////////////////////////////////////////////////////////////////// // Device side code ////////////////////////////////////////////////////////////////////////////// // Name algorithm of the new AIK TpmAlgId nameAlg = TpmAlgId.Sha256; // The key to be certified needs a policy. It can be ANY policy, but here // it is configured to allow AIK usage only with the following commands var policyAIK = new PolicyTree(nameAlg); var policyOR = new TpmPolicyOr(); policyAIK.SetPolicyRoot(policyOR); policyOR.AddPolicyBranch(new TpmPolicyCommand(TpmCc.ActivateCredential, "Activate")); policyOR.AddPolicyBranch(new TpmPolicyCommand(TpmCc.Certify, "Certify")); policyOR.AddPolicyBranch(new TpmPolicyCommand(TpmCc.CertifyCreation, "CertifyCreation")); policyOR.AddPolicyBranch(new TpmPolicyCommand(TpmCc.Quote, "Quote")); var inAIKPub = new TpmPublic(nameAlg, ObjectAttr.Restricted | ObjectAttr.Sign | ObjectAttr.FixedParent | ObjectAttr.FixedTPM | ObjectAttr.AdminWithPolicy | ObjectAttr.SensitiveDataOrigin, policyAIK.GetPolicyDigest(), new RsaParms(new SymDefObject(), new SchemeRsassa(TpmAlgId.Sha256), 2048, 0), new Tpm2bPublicKeyRsa()); TpmPublic AIKpub; var inSens = new SensitiveCreate(Substrate.RandomAuth(nameAlg), null); CreationData creationData; byte[] creationHash; TkCreation creationTk; TpmHandle hAIK = tpm.CreatePrimary(TpmRh.Endorsement, inSens, inAIKPub, null, null, out AIKpub, out creationData, out creationHash, out creationTk); // An alternative using test substrate helper //TpmHandle hAIK = Substrate.CreatePrimary(tpm, inAIKPub, TpmRh.Endorsement); // Normally a device would have a pre-provisioned persistent EK with the above handle TpmHandle hEK = new TpmHandle(0x81010001); // Get its public part TpmPublic EKpub = null; // In a test environment the real EK may be absent. In this case use // a primary key temporarily created in the Endorsement hierarchy. byte[] name, qname; tpm._AllowErrors() .ReadPublic(hEK, out name, out qname); if (!tpm._LastCommandSucceeded()) { var inEKpub = new TpmPublic(TpmAlgId.Sha256, ObjectAttr.Restricted | ObjectAttr.Decrypt | ObjectAttr.FixedParent | ObjectAttr.FixedTPM | ObjectAttr.AdminWithPolicy | ObjectAttr.SensitiveDataOrigin, new byte[] { 0x83, 0x71, 0x97, 0x67, 0x44, 0x84, 0xb3, 0xf8, 0x1a, 0x90, 0xcc, 0x8d, 0x46, 0xa5, 0xd7, 0x24, 0xfd, 0x52, 0xd7, 0x6e, 0x06, 0x52, 0x0b, 0x64, 0xf2, 0xa1, 0xda, 0x1b, 0x33, 0x14, 0x69, 0xaa }, new RsaParms(new SymDefObject(TpmAlgId.Aes, 128, TpmAlgId.Cfb), null, 2048, 0), new Tpm2bPublicKeyRsa()); inSens = new SensitiveCreate(null, null); hEK = tpm.CreatePrimary(TpmRh.Endorsement, inSens, inEKpub, null, null, out EKpub, out creationData, out creationHash, out creationTk); } // Marshal public parts of AIK and EK byte[] AIKpubBytes = AIKpub.GetTpmRepresentation(); byte[] EKpubBytes = EKpub.GetTpmRepresentation(); // Here the device uses network to pass AIKpubBytes and EKpubBytes (as well as // the EK certificate) to CA service. ////////////////////////////////////////////////////////////////////////////// // Service (CA) side code ////////////////////////////////////////////////////////////////////////////// // Unmarshal AIKpub and EKpub (and EK certificate) var m = new Marshaller(AIKpubBytes); AIKpub = m.Get <TpmPublic>(); m = new Marshaller(EKpubBytes); EKpub = m.Get <TpmPublic>(); // Symmetric key to be used by CA to encrypt the new certificate it creates for AIK byte[] secretKey = Substrate.RandomBytes(32); // Here CA does the following (the sample does not show this code): // - Validates EK certificate // - Generates a new certificate for AIK (AIKcert) // - Encrypts AIKcert with secretKey // Create an activation blob // Internal wrapper key encrypted with EKpub to be used by TPM2_ActivateCredential() command. byte[] encSecret; // An encrypted and HMACed object tied to the destination TPM. It contains // 'secret' to be extracted by the successful TPM2_ActivateCredential() command // (that can only succeeed on the TPM that originated both EK and AIK). IdObject certInfo; // Run TSS.Net equivalent of TPM2_MakeCredential() command (convenient for the server side, // as it will likely be faster than the TPM transaction and allows concurrent execution). certInfo = EKpub.CreateActivationCredentials(secretKey, AIKpub.GetName(), out encSecret); // Marshal certInfo // IdObject data type requires customized marshaling m = new Marshaller(); m.Put(certInfo.integrityHMAC.Length, "integrityHMAC.Length"); m.Put(certInfo.integrityHMAC, "integrityHMAC"); m.Put(certInfo.encIdentity.Length, "encIdentity"); m.Put(certInfo.encIdentity, "encIdentity.Length"); byte[] certInfoBytes = m.GetBytes(); // Here the CA passes certInfoBytes and encSecret (as well as the encrypted // AIK certificate) back to the device via network. ////////////////////////////////////////////////////////////////////////////// // Device side code again ////////////////////////////////////////////////////////////////////////////// // Unmarshal certInfo and encSecret (and encrypted AIK certificate) m = new Marshaller(certInfoBytes); int len = m.Get <int>(); certInfo.integrityHMAC = m.GetArray <byte>(len); len = m.Get <int>(); certInfo.encIdentity = m.GetArray <byte>(len); // encSecret is a byte array, so, normally, no special unmarshalling is required // Create policy session to authorize AIK usage AuthSession sessAIK = tpm.StartAuthSessionEx(TpmSe.Policy, nameAlg); sessAIK.RunPolicy(tpm, policyAIK, "Activate"); // Create policy description and corresponding policy session to authorize EK usage var policyEK = new PolicyTree(EKpub.nameAlg); policyEK.SetPolicyRoot(new TpmPolicySecret(TpmRh.Endorsement, false, 0, null, null)); AuthSession sessEK = tpm.StartAuthSessionEx(TpmSe.Policy, EKpub.nameAlg); sessEK.RunPolicy(tpm, policyEK); byte[] recoveredSecretKey = tpm[sessAIK, sessEK].ActivateCredential(hAIK, hEK, certInfo, encSecret); testCtx.AssertEqual("Secret.1", recoveredSecretKey, secretKey); // Here the device can use recoveredSecretKey to decrypt the AIK certificate ////////////////////////////////////////////////////////////////////////////// // End of activation sequence ////////////////////////////////////////////////////////////////////////////// // // Now prepare activation using the TPM built-in command // byte[] encSecret2 = null; IdObject certInfo2 = tpm.MakeCredential(hEK, secretKey, AIKpub.GetName(), out encSecret2); // Reinitialize policy sessions tpm.PolicyRestart(sessAIK); sessAIK.RunPolicy(tpm, policyAIK, "Activate"); tpm.PolicyRestart(sessEK); sessEK.RunPolicy(tpm, policyEK); recoveredSecretKey = tpm[sessAIK, sessEK].ActivateCredential(hAIK, hEK, certInfo2, encSecret2); testCtx.AssertEqual("Secret.2", recoveredSecretKey, secretKey); // Cleanup tpm.FlushContext(sessAIK); tpm.FlushContext(sessEK); tpm.FlushContext(hAIK); if (hEK.handle != 0x81010001) { tpm.FlushContext(hEK); } } // ActivateAikSample
private void TreeItemContextMenuOpening(object sender, ContextMenuEventArgs e) { if ((sender as TreeViewItem)?.DataContext != tv.SelectedItem) { return; //because this event bubbles to the parent node } foreach (var item in ContextItems.OfType <MenuItem>().Concat(OpenFromContextItem.Items.OfType <MenuItem>())) { item.Click -= ContextItem_Click; } var menu = (sender as ContextMenu); var node = tv.SelectedItem as TreeItemModel; ContextItems.Clear(); OpenFromContextItem.Items.Clear(); var moduleItem = node.Tag as ModuleItem; if (moduleItem != null) { ContextItems.Add(OpenContextItem); ContextItems.Add(OpenWithContextItem); var instances = moduleItem.Module.FindAlternateTagInstances(moduleItem.GlobalTagId).ToList(); if (instances.Count > 1) { foreach (var instance in instances) { var item = new MenuItem { Header = Utils.GetFileNameWithoutExtension(instance.Module.FileName), Tag = instance }; OpenFromContextItem.Items.Add(item); } ContextItems.Add(OpenFromContextItem); } ContextItems.Add(CopyPathContextItem); } var customItems = Substrate.GetContextItems(GetSelectedArgs()); if (ContextItems.Any() && customItems.Any()) { ContextItems.Add(ContextSeparator); } foreach (var item in customItems) { ContextItems.Add(new MenuItem { Header = item.Path, Tag = item }); } foreach (var item in ContextItems.OfType <MenuItem>().Concat(OpenFromContextItem.Items.OfType <MenuItem>())) { item.Click += ContextItem_Click; } if (!ContextItems.Any()) { e.Handled = true; } }
public IGenomeDecoder <NeatGenome, IBlackBox> CreateGenomeDecoder() { // Create HyperNEAT network substrate. //-- Create input layer nodes. uint i = 1; SubstrateNodeSet inputLayer = new SubstrateNodeSet(1); AddNode(inputLayer, 1, 0.0, 0.0, -1.0, 0.0); //x velocity object AddNode(inputLayer, 2, 0.0, 0.0, -1.0, 0.0); //x velocity object //for (int x = 0; x < _inputCount / 3; x++) //{ // AddNode(inputLayer, i, x/ (InputCount/3), 0.0, -1.0, -1.0);//x velocity object // i++; // AddNode(inputLayer, i, x / (InputCount / 3), 0.0, -1.0, 0.0);// y velocity object // i++; // AddNode(inputLayer, i, x / (InputCount / 3), 0.0, -1.0, +1.0);// z velocity object // i++; //} SubstrateNodeSet outputLayer = _optimizer.CreateSubstrate(); //SubstrateNodeSet h1Layer = new SubstrateNodeSet(_inputCount); //for (int x = 0; x < _inputCount; x++) //{ // AddNode(h1Layer, i, 0.0, 0.0, -0.25, -1.0);//x velocity object // i++; // AddNode(h1Layer, i, 0.0, 0.0, -0.25, 0.0);// y velocity object // i++; // AddNode(h1Layer, i, 0.0, 0.0, -0.25, +1.0);// z velocity object // i++; //} SubstrateNodeSet h2Layer = _optimizer.CreateSubstrateHidden(); // Connect up layers. List <SubstrateNodeSet> nodeSetList = new List <SubstrateNodeSet>(3); nodeSetList.Add(inputLayer); nodeSetList.Add(outputLayer); // nodeSetList.Add(h1Layer); nodeSetList.Add(h2Layer); List <NodeSetMapping> nodeSetMappingList = new List <NodeSetMapping>(4); nodeSetMappingList.Add(NodeSetMapping.Create(0, 1, (double?)null)); // Input -> Output. nodeSetMappingList.Add(NodeSetMapping.Create(0, 2, (double?)null)); // Input -> Hidden. nodeSetMappingList.Add(NodeSetMapping.Create(2, 1, (double?)null)); // Hidden -> Output. nodeSetMappingList.Add(NodeSetMapping.Create(1, 2, (double?)null)); // Output -> Hidden // nodeSetMappingList.Add(NodeSetMapping.Create(2, 3, (double?)null)); // Hidden -> Hidden2 // nodeSetMappingList.Add(NodeSetMapping.Create(0, 3, (double?)null)); // input -> Hidden2 // nodeSetMappingList.Add(NodeSetMapping.Create(3, 1, (double?)null)); // Hidden2 -> Output // Construct substrate. Substrate substrate = new Substrate(nodeSetList, DefaultActivationFunctionLibrary.CreateLibraryNeat(SteepenedSigmoid.__DefaultInstance), 0, 0.2, 5, nodeSetMappingList);//++ // Create genome decoder. Decodes to a neural network packaged with an activation scheme that defines a fixed number of activations per evaluation. IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = new HyperNeatDecoder(substrate, _activationSchemeCppn, _activationScheme, false);//++ //return new NeatGenomeDecoder(_activationScheme); return(genomeDecoder); }
public void Render() { NEATGenome genome = (NEATGenome)this.pop.BestGenome; Substrate substrate = SubstrateFactory.factorSandwichSubstrate(resolution, resolution); HyperNEATCODEC codec = new HyperNEATCODEC(); NEATNetwork phenotype = (NEATNetwork)codec.Decode(this.pop, substrate, genome); TrialEvaluation trial = new TrialEvaluation(phenotype, this.testCase); IntPair actualPos = trial.Query(resolution); // clear what was there before GridCanvas.Children.Clear(); // double boxWidth = GridCanvas.ActualWidth / resolution; double boxHeight = GridCanvas.ActualHeight / resolution; double delta = 2.0 / resolution; int index = 0; for (int row = 0; row < resolution; row++) { double y = -1 + (row * delta); double boxY = row * boxHeight; for (int col = 0; col < resolution; col++) { double x = -1 + (col * delta); double boxX = col * boxWidth; Rectangle r = new Rectangle(); r.SetValue(Canvas.LeftProperty, boxX); r.SetValue(Canvas.TopProperty, boxY); r.Width = boxWidth; r.Height = boxHeight; if (this.testCase.GetPixel(x, y) > 0) { r.Fill = Brushes.Blue; } else { double d = trial.Output[index]; int c = trial.Normalize(d, 255); SolidColorBrush b = new SolidColorBrush(Color.FromRgb(255, (byte)c, 255)); r.Fill = b; r.Stroke = Brushes.Black; } GridCanvas.Children.Add(r); index++; } } Rectangle target = new Rectangle(); target.SetValue(Canvas.LeftProperty, actualPos.X * boxWidth); target.SetValue(Canvas.TopProperty, actualPos.Y * boxHeight); target.Width = boxWidth; target.Height = boxHeight; target.Fill = Brushes.Red; GridCanvas.Children.Add(target); }