### Complete IMU Motion Recognition Example Source: https://context7.com/general-vision/neuroshield/llms.txt This C++ code demonstrates a full implementation for motion recognition using an MPU6050 IMU and the NeuroMemAI library on an Arduino-compatible platform. It includes setup, data acquisition, feature extraction, learning, and recognition functions. ```cpp #include #include #include MPU6050 mpu(0x68); NeuroMemAI hNN; #define SAMPLE_NBR 20 #define CHANNEL_NBR 6 // ax, ay, az, gx, gy, gz #define VECTOR_LEN (SAMPLE_NBR * CHANNEL_NBR) int vector[VECTOR_LEN]; int16_t ax, ay, az, gx, gy, gz; void setup() { Serial.begin(115200); Wire.begin(); // Initialize neural network if (hNN.begin(2) != 0) { // NeuroShield Serial.println("NeuroMem init failed!"); while(1); } Serial.print("Neurons available: "); Serial.println(hNN.navail); // Initialize IMU mpu.initialize(); if (!mpu.testConnection()) { Serial.println("MPU6050 connection failed!"); while(1); } // Set sensor ranges mpu.setFullScaleGyroRange(MPU6050_GYRO_FS_1000); mpu.setFullScaleAccelRange(MPU6050_ACCEL_FS_8); // Set neural network parameters hNN.forget(1000); // MAXIF = 1000 for motion patterns Serial.println("Ready! Commands: 1-9=learn motion, r=recognize, s=stop"); } int extractFeatureVector() { for (int j = 0; j < SAMPLE_NBR; j++) { mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); // Normalize to 0-255 range vector[(j * CHANNEL_NBR) + 0] = map(ax, -32768, 32767, 0, 255); vector[(j * CHANNEL_NBR) + 1] = map(ay, -32768, 32767, 0, 255); vector[(j * CHANNEL_NBR) + 2] = map(az, -32768, 32767, 0, 255); vector[(j * CHANNEL_NBR) + 3] = map(gx, -32768, 32767, 0, 255); vector[(j * CHANNEL_NBR) + 4] = map(gy, -32768, 32767, 0, 255); vector[(j * CHANNEL_NBR) + 5] = map(gz, -32768, 32767, 0, 255); delay(10); // 100Hz sampling } return VECTOR_LEN; } void learnMotion(int category) { int vlen = extractFeatureVector(); int ncount = hNN.learn(vector, vlen, category); Serial.print("Learned motion "); Serial.print(category); Serial.print(", total neurons: "); Serial.println(ncount); } void recognizeMotion() { int vlen = extractFeatureVector(); int dist, cat, nid; int status = hNN.classify(vector, vlen, &dist, &cat, &nid); if (cat == 0xFFFF) { Serial.println("Unknown motion"); } else { Serial.print("Motion type: "); Serial.print(cat); Serial.print(", confidence distance: "); Serial.println(dist); } } void loop() { if (Serial.available()) { char cmd = Serial.read(); if (cmd >= '1' && cmd <= '9') { learnMotion(cmd - '0'); } else if (cmd == 'r') { recognizeMotion(); } } } ``` -------------------------------- ### Get Best Match Neuron with Python Source: https://context7.com/general-vision/neuroshield/llms.txt Retrieves the single best matching neuron for a given input vector. ```python import ctypes import NeuroMem as nm LENGTH = 4 bytearray = ctypes.c_int * LENGTH vector = bytearray() # Create test pattern for i in range(LENGTH): vector[i] = 12 # Get best match distance, category, nid = nm.BestMatch(vector, LENGTH) if distance == 0xFFFF: print("Pattern not recognized (unknown)") else: print(f"Best match: Neuron {nid}, Category {category}, Distance {distance}") # Output: Best match: Neuron 1, Category 33, Distance 4 ``` -------------------------------- ### BestMatch - Get Top Firing Neuron Source: https://context7.com/general-vision/neuroshield/llms.txt Retrieves the best matching neuron for a given input vector, returning its distance, category, and ID. ```APIDOC ## BestMatch - Get Top Firing Neuron ### Description Returns the distance, category, and neuron ID of the single best matching neuron for a given input vector. ### Method BestMatch ### Endpoint /general-vision/neuroshield ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **vector** (array of int) - The input vector to match. - **LENGTH** (int) - The length of the input vector. ### Request Example ```python import ctypes LENGTH = 4 bytearray = ctypes.c_int * LENGTH vector = bytearray() # Create test pattern for i in range(LENGTH): vector[i] = 12 distance, category, nid = nm.BestMatch(vector, LENGTH) ``` ### Response #### Success Response (200) - **distance** (int) - The distance to the best matching neuron. Returns 0xFFFF if the pattern is not recognized. - **category** (int) - The category of the best matching neuron. - **nid** (int) - The neuron ID of the best matching neuron. #### Response Example ``` Best match: Neuron 1, Category 33, Distance 4 ``` ``` -------------------------------- ### Initialize Network with C/C++ Source: https://context7.com/general-vision/neuroshield/llms.txt Connects to the NeuroMem device and verifies the network state. ```cpp #include "NeuroMem.h" #include int main() { // Initialize network and get neuron count // Returns 0 if connection fails, otherwise returns available neurons int navail = InitializeNetwork(); if (navail == 0) { printf("Failed to connect to NeuroMem device\n"); return 1; } printf("Connected! Available neurons: %d\n", navail); // Output: Connected! Available neurons: 576 // Clear all neuron memory ClearNeurons(); // Verify network is empty int committed = GetCommitted(); printf("Committed neurons: %d\n", committed); // Output: Committed neurons: 0 return 0; } ``` -------------------------------- ### Train and Classify with C/C++ Source: https://context7.com/general-vision/neuroshield/llms.txt Demonstrates learning patterns and performing classification using the C/C++ API. ```cpp #include "NeuroMem.h" #include int main() { InitializeNetwork(); ClearNeurons(); // Training data int pattern1[4] = {11, 11, 11, 11}; int pattern2[4] = {15, 15, 15, 15}; int pattern3[4] = {20, 20, 20, 20}; // Learn patterns with categories int ncount; ncount = Learn(pattern1, 4, 55); // Category 55 printf("After pattern 1: %d neurons\n", ncount); ncount = Learn(pattern2, 4, 33); // Category 33 printf("After pattern 2: %d neurons\n", ncount); ncount = Learn(pattern3, 4, 100); // Category 100 printf("After pattern 3: %d neurons\n", ncount); // Recognition with K-NN int testPattern[4] = {14, 14, 14, 14}; int K = 3; int distances[3], categories[3], neuronIDs[3]; int responseCount = Recognize(testPattern, 4, K, distances, categories, neuronIDs); printf("\nRecognizing pattern [14,14,14,14]:\n"); for (int i = 0; i < responseCount; i++) { printf(" Neuron %d: Category=%d, Distance=%d\n", neuronIDs[i], categories[i], distances[i]); } // Output: // Neuron 2: Category=33, Distance=4 // Neuron 1: Category=55, Distance=12 // Best match recognition int dist, cat, nid; int status = BestMatch(testPattern, 4, &dist, &cat, &nid); printf("\nBest match: Neuron %d, Category %d, Distance %d\n", nid, cat, dist); return 0; } ``` -------------------------------- ### Connect (Python) Source: https://context7.com/general-vision/neuroshield/llms.txt Establishes SPI communication with the NeuroShield board on Raspberry Pi. ```APIDOC ## Connect ### Description Initializes the SPI communication interface between the Raspberry Pi and the NeuroShield board. ### Response - **int** - Returns 0 on success, non-zero on failure. ``` -------------------------------- ### Initialize NeuroShield Board Source: https://context7.com/general-vision/neuroshield/llms.txt Initializes the NeuroMem hardware platform, detects available neurons, and clears the network. Use platform constants to specify the hardware type. ```cpp #include NeuroMemAI hNN; void setup() { Serial.begin(115200); // Platform constants: HW_BRAINCARD=1, HW_NEUROSHIELD=2, HW_NEUROSTAMP=3, HW_NEUROTILE=4 int platform = 2; // NeuroShield if (hNN.begin(platform) == 0) { Serial.print("NeuroMem initialized! Neurons available: "); Serial.println(hNN.navail); // Returns 576 for NM500 chip } else { Serial.println("Connection failed! Check hardware."); while(1); } } ``` -------------------------------- ### Arduino API - NeuroMemAI Class Initialization Source: https://context7.com/general-vision/neuroshield/llms.txt Initializes the NeuroMem hardware platform, detects available neurons, clears the network, and optionally initializes the SD card interface. ```APIDOC ## POST /api/users ### Description Creates a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. ### Request Body ```json { "username": "john_doe", "password": "secure_password" } ``` ### Response #### Success Response (201) - **id** (integer) - The unique identifier for the newly created user. - **message** (string) - A confirmation message. #### Response Example ```json { "id": 123, "message": "User created successfully." } ``` ``` -------------------------------- ### Initialize SPI Communication on Raspberry Pi Source: https://context7.com/general-vision/neuroshield/llms.txt Establishes SPI communication with the NeuroShield board and clears existing neurons. ```python import sys import ctypes import NeuroMem as nm import GVcomm_SPI as comm from GVconstants import * # Initialize SPI connection to NeuroShield # Returns 0 on success, non-zero on failure if comm.Connect() != 0: print("Cannot connect to NeuroShield") sys.exit() print("Connected to NeuroShield successfully") # Clear all neurons to start fresh nm.ClearNeurons() ``` -------------------------------- ### Learn (Python) Source: https://context7.com/general-vision/neuroshield/llms.txt Broadcasts a vector and commits it to the network with a category label. ```APIDOC ## Learn ### Description Trains the network by committing a vector and its associated category label. ### Parameters - **vector** (int array) - Required - The input pattern vector. - **length** (int) - Required - The length of the input vector. - **category** (int) - Required - The category label for the pattern. ### Response - **int** - Returns the total number of committed neurons. ``` -------------------------------- ### InitializeNetwork - Connect and Detect Neurons Source: https://context7.com/general-vision/neuroshield/llms.txt Initializes the connection to the NeuroMem platform and reports the number of available neurons. ```APIDOC ## InitializeNetwork - Connect and Detect Neurons ### Description Initializes communication with the NeuroMem platform and returns the number of available neurons. It also provides functions to clear and check the number of committed neurons. ### Method InitializeNetwork, ClearNeurons, GetCommitted ### Endpoint Windows C/C++ API ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp #include "NeuroMem.h" #include int main() { int navail = InitializeNetwork(); if (navail == 0) { printf("Failed to connect to NeuroMem device\n"); return 1; } printf("Connected! Available neurons: %d\n", navail); ClearNeurons(); int committed = GetCommitted(); printf("Committed neurons: %d\n", committed); return 0; } ``` ### Response #### Success Response (200) - **navail** (int) - The number of available neurons in the network. Returns 0 if connection fails. - **committed** (int) - The number of currently committed neurons in the network. #### Response Example ``` Connected! Available neurons: 576 Committed neurons: 0 ``` ``` -------------------------------- ### Recognize unknown pattern [6,6,6,6] Source: https://context7.com/general-vision/neuroshield/llms.txt This snippet demonstrates how to recognize a specific pattern and handle cases where the pattern is unknown. ```APIDOC ## Recognize unknown pattern [6,6,6,6] ### Description This code snippet shows how to classify a vector and identify if a known pattern is recognized or if it's an unknown pattern based on the number of firing neurons. ### Method Classify (Implicit) ### Endpoint /general-vision/neuroshield ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **vector** (array of int) - The input vector to classify. - **LENGTH** (int) - The length of the input vector. - **K** (int) - The number of nearest neighbors to consider for classification. ### Request Example ```python vector = [6, 6, 6, 6] LENGTH = len(vector) K = 3 # Example value for K respNbr, dists, cats, nids = nm.Classify(vector, LENGTH, K) ``` ### Response #### Success Response (200) - **respNbr** (int) - The number of recognized neurons. - **dists** (array of float) - Distances to the recognized neurons. - **cats** (array of int) - Categories of the recognized neurons. - **nids** (array of int) - Neuron IDs of the recognized neurons. #### Response Example ``` Pattern [6,6,6,6] - Unknown (no firing neurons) ``` OR ``` Neuron 1: Category=10, Distance=5 Neuron 2: Category=20, Distance=8 ``` ``` -------------------------------- ### Train Neurons with Patterns in Python Source: https://context7.com/general-vision/neuroshield/llms.txt Broadcasts a vector and commits it to the network with a category label using the Python API. ```python import ctypes import NeuroMem as nm # Define vector length and create array LENGTH = 4 bytearray = ctypes.c_int * LENGTH vector = bytearray() # Learn pattern [11,11,11,11] as category 33 for i in range(LENGTH): vector[i] = 11 ncount = nm.Learn(vector, LENGTH, 33) print(f"After learning pattern 1, committed neurons: {ncount}") # Learn pattern [15,15,15,15] as category 55 for i in range(LENGTH): vector[i] = 15 ncount = nm.Learn(vector, LENGTH, 55) print(f"After learning pattern 2, committed neurons: {ncount}") # Learn pattern [20,20,20,20] as category 100 for i in range(LENGTH): vector[i] = 20 ncount = nm.Learn(vector, LENGTH, 100) print(f"After learning pattern 3, committed neurons: {ncount}") # Display neuron contents nm.DisplayNeurons(LENGTH) # Output: # Committed neurons= 3 # Neuron 1: [ 11 11 11 11 ] AIF= 4 CAT 33 # Neuron 2: [ 15 15 15 15 ] AIF= 4 CAT 55 # Neuron 3: [ 20 20 20 20 ] AIF= 5 CAT 100 ``` -------------------------------- ### Learn / Recognize - Training and Classification Source: https://context7.com/general-vision/neuroshield/llms.txt Trains the neural network with labeled patterns and classifies new inputs using K-Nearest Neighbors (KNN) and Best Match algorithms. ```APIDOC ## Learn / Recognize - Training and Classification ### Description Trains the neural network with labeled patterns and classifies new inputs. It supports both K-NN based recognition and finding the single best matching neuron. ### Method Learn, Recognize, BestMatch ### Endpoint Windows C/C++ API ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **pattern** (array of int) - The input pattern to learn or recognize. - **length** (int) - The length of the pattern. - **category** (int) - The category label for training. - **K** (int) - The number of nearest neighbors for recognition. - **distances** (array of int) - Output array to store distances for recognized neurons. - **categories** (array of int) - Output array to store categories for recognized neurons. - **neuronIDs** (array of int) - Output array to store neuron IDs for recognized neurons. - **dist** (pointer to int) - Output variable to store the distance for the best match. - **cat** (pointer to int) - Output variable to store the category for the best match. - **nid** (pointer to int) - Output variable to store the neuron ID for the best match. ### Request Example ```cpp #include "NeuroMem.h" #include int main() { InitializeNetwork(); ClearNeurons(); int pattern1[4] = {11, 11, 11, 11}; int pattern2[4] = {15, 15, 15, 15}; int pattern3[4] = {20, 20, 20, 20}; Learn(pattern1, 4, 55); Learn(pattern2, 4, 33); Learn(pattern3, 4, 100); int testPattern[4] = {14, 14, 14, 14}; int K = 3; int distances[3], categories[3], neuronIDs[3]; int responseCount = Recognize(testPattern, 4, K, distances, categories, neuronIDs); printf("\nRecognizing pattern [14,14,14,14]:\n"); for (int i = 0; i < responseCount; i++) { printf(" Neuron %d: Category=%d, Distance=%d\n", neuronIDs[i], categories[i], distances[i]); } int dist, cat, nid; int status = BestMatch(testPattern, 4, &dist, &cat, &nid); printf("\nBest match: Neuron %d, Category %d, Distance %d\n", nid, cat, dist); return 0; } ``` ### Response #### Success Response (200) - **ncount** (int) - The number of neurons after learning. - **responseCount** (int) - The number of neurons recognized by the Recognize function. - **distances** (array of int) - Distances to the recognized neurons. - **categories** (array of int) - Categories of the recognized neurons. - **neuronIDs** (array of int) - Neuron IDs of the recognized neurons. - **dist** (int) - Distance to the best matching neuron. - **cat** (int) - Category of the best matching neuron. - **nid** (int) - Neuron ID of the best matching neuron. #### Response Example ``` After pattern 1: 1 neurons After pattern 2: 2 neurons After pattern 3: 3 neurons Recognizing pattern [14,14,14,14]: Neuron 2: Category=33, Distance=4 Neuron 1: Category=55, Distance=12 Best match: Neuron 2, Category 33, Distance 4 ``` ``` -------------------------------- ### Persist Neural Network State with ReadNeurons/WriteNeurons Source: https://context7.com/general-vision/neuroshield/llms.txt Use ReadNeurons to save the entire network's state to a buffer and WriteNeurons to restore it. This enables model persistence and resuming training. Ensure sufficient memory is allocated for the buffer based on the number of neurons and maxveclength. ```cpp #include "NeuroMem.h" #include #include // maxveclength is typically 256 for NM500 extern int maxveclength; int main() { InitializeNetwork(); // Train initial model int p1[4] = {10, 10, 10, 10}; int p2[4] = {30, 30, 30, 30}; Learn(p1, 4, 1); Learn(p2, 4, 2); int ncount = GetCommitted(); printf("Trained neurons: %d\n", ncount); // Allocate array for neuron data // Format: NCR + maxveclength*COMP + AIF + MINIF + CAT per neuron int recLen = maxveclength + 4; int* savedKnowledge = (int*)malloc(ncount * recLen * sizeof(int)); // Save all neurons int savedCount = ReadNeurons(savedKnowledge); printf("Saved %d neurons to memory\n", savedCount); // Clear the network Forget(); printf("After forget: %d neurons\n", GetCommitted()); // Restore neurons int restoredCount = WriteNeurons(savedKnowledge, ncount); printf("Restored %d neurons\n", restoredCount); // Verify recognition works int dist, cat, nid; BestMatch(p1, 4, &dist, &cat, &nid); printf("Pattern [10,10,10,10] classified as category: %d\n", cat); free(savedKnowledge); return 0; } ``` -------------------------------- ### Classify (Python) Source: https://context7.com/general-vision/neuroshield/llms.txt Broadcasts a vector and returns up to K firing neurons with their distances and categories. ```APIDOC ## Classify ### Description Performs K-Nearest Neighbor recognition on the provided input vector. ### Parameters - **vector** (int array) - Required - The input pattern to classify. - **length** (int) - Required - The length of the input vector. - **K** (int) - Required - The maximum number of firing neurons to return. ### Response - **tuple** - Returns (respNbr, dists, cats, nids) representing the number of responses, distances, categories, and neuron IDs. ``` -------------------------------- ### ReadNeurons / WriteNeurons - Bulk Knowledge Transfer Source: https://context7.com/general-vision/neuroshield/llms.txt Provides functionality to read all neuron contents for backup or analysis, and to write neuron data back to the network. ```APIDOC ## ReadNeurons / WriteNeurons - Bulk Knowledge Transfer ### Description Reads or writes all neuron contents for backup, transfer, or analysis. This allows for bulk operations on the neural network's knowledge base. ### Method ReadNeurons, WriteNeurons, ClearNeurons ### Endpoint /general-vision/neuroshield ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ncount** (int) - The number of neurons to read or write. - **neurons** (byte array) - The byte array containing neuron data for writing. ### Request Example ```python import NeuroMem as nm import GVcomm_SPI as comm from GVconstants import * # Read number of committed neurons ncount = comm.Read(MOD_NM, NCOUNT) # Read all neurons into array neurons = nm.ReadNeurons(ncount) # Clear all neurons nm.ClearNeurons() # Write neurons back nm.WriteNeurons(neurons, ncount) ``` ### Response #### Success Response (200) - **ncount** (int) - The number of neurons read or written. - **neurons** (byte array) - The byte array containing neuron data (when reading). #### Response Example ``` Committed neurons: 576 Neuron 0: NCR=10, AIF=20, MINIF=30, CAT=40 Model (first 10 bytes): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] After clear: 0 neurons After restore: 576 neurons ``` ``` -------------------------------- ### setContext / getContext - Manage Classification Contexts Source: https://context7.com/general-vision/neuroshield/llms.txt Manages classification contexts, allowing for up to 127 parallel classifiers. It enables setting and retrieving the current context, minimum influence field (MINIF), and maximum influence field (MAXIF). ```APIDOC ## setContext / getContext - Manage Classification Contexts ### Description Sets or retrieves the current context (up to 127 parallel classifiers), minimum influence field, and maximum influence field. Contexts enable training multiple independent classifiers on the same hardware. ### Method `getContext(int* context, int* minif, int* maxif)` `setContext(int context, int minif, int maxif)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp #include NeuroMemAI hNN; int context, minif, maxif; // Get current context settings hNN.getContext(&context, &minif, &maxif); // Set context 1 for motion recognition hNN.setContext(1, 2, 1000); // Switch to context 2 for novelty detection hNN.setContext(2, 2, 500); ``` ### Response #### Success Response (200) `getContext` populates the provided integer pointers with the current context, MINIF, and MAXIF values. #### Response Example `getContext` output (via pointers): `context = 1`, `minif = 2`, `maxif = 1000` ``` -------------------------------- ### Persist Knowledge to SD Card Source: https://context7.com/general-vision/neuroshield/llms.txt Saves and loads neural network knowledge to or from an SD card using files compatible with General Vision tools. ```cpp #include NeuroMemAI hNN; void persistToSDCard() { hNN.begin(2); // NeuroShield initializes SD on pin 6 // Train some patterns int pattern[4]; for (int i = 0; i < 4; i++) pattern[i] = 25; hNN.learn(pattern, 4, 1); for (int i = 0; i < 4; i++) pattern[i] = 50; hNN.learn(pattern, 4, 2); // Save knowledge to SD card // Returns: 0=success, 1=SD not detected, 2=file error int result = hNN.saveKnowledge_SDcard("motion.knf"); if (result == 0) { Serial.println("Knowledge saved to motion.knf"); } else { Serial.print("Save error: "); Serial.println(result); } // Clear and reload hNN.forget(); // Load knowledge from SD card // Returns: 0=success, 1=SD not detected, 2=file not found, // 3=file error, 4=format error, 5=neuron size mismatch, 6=exceeds capacity result = hNN.loadKnowledge_SDcard("motion.knf"); if (result == 0) { Serial.print("Knowledge loaded. Neurons: "); Serial.println(hNN.NCOUNT()); } else { Serial.print("Load error: "); Serial.println(result); } } ``` -------------------------------- ### Bulk Neuron Transfer with Python Source: https://context7.com/general-vision/neuroshield/llms.txt Reads or writes all neuron contents for backup and restoration purposes. ```python import NeuroMem as nm import GVcomm_SPI as comm from GVconstants import * # Read number of committed neurons ncount = comm.Read(MOD_NM, NCOUNT) print(f"Committed neurons: {ncount}") # Read all neurons into array # Format: 264 bytes per neuron (2 NCR + 256 COMP + 2 AIF + 2 MINIF + 2 CAT) neurons = nm.ReadNeurons(ncount) # Inspect first neuron ncr = (neurons[0] << 8) + neurons[1] aif = (neurons[258] << 8) + neurons[259] minif = (neurons[260] << 8) + neurons[261] cat = (neurons[262] << 8) + neurons[263] model = neurons[2:258] print(f"Neuron 0: NCR={ncr}, AIF={aif}, MINIF={minif}, CAT={cat}") print(f"Model (first 10 bytes): {model[:10]}") # Clear and restore neurons nm.ClearNeurons() print(f"After clear: {comm.Read(MOD_NM, NCOUNT)} neurons") nm.WriteNeurons(neurons, ncount) print(f"After restore: {comm.Read(MOD_NM, NCOUNT)} neurons") ``` -------------------------------- ### Manage Classification Contexts Source: https://context7.com/general-vision/neuroshield/llms.txt Configures parallel classifiers by setting context IDs, minimum influence fields, and maximum influence fields. ```cpp #include NeuroMemAI hNN; void manageContexts() { int context, minif, maxif; // Get current context settings hNN.getContext(&context, &minif, &maxif); Serial.print("Current context: "); Serial.print(context); Serial.print(", MINIF: "); Serial.print(minif); Serial.print(", MAXIF: "); Serial.println(maxif); // Set context 1 for motion recognition with custom influence fields // Context value format: bit[7]=Norm (0=L1, 1=LSup), bit[6-0]=context value hNN.setContext(1, 2, 1000); // context=1, minif=2, maxif=1000 // Train motion patterns in context 1 int motionPattern[4] = {100, 120, 130, 110}; hNN.learn(motionPattern, 4, 1); // Category 1 = motion type A // Switch to context 2 for novelty detection hNN.setContext(2, 2, 500); // Smaller maxif for tighter pattern matching // Train novelty patterns in context 2 int noveltyPattern[4] = {50, 55, 60, 52}; hNN.learn(noveltyPattern, 4, 100); // Category 100 = novelty timestamp } ``` -------------------------------- ### Manage Parallel Classifiers with setContext/getContext Source: https://context7.com/general-vision/neuroshield/llms.txt Use setContext to switch between independent classification contexts, each with its own trained data. getContext retrieves the current context settings. Useful for managing distinct classification tasks within a single network instance. ```cpp #include "NeuroMem.h" #include int main() { InitializeNetwork(); // Get current context settings int context, minif, maxif; getContext(&context, &minif, &maxif); printf("Default context: %d, MINIF: %d, MAXIF: %d\n", context, minif, maxif); // Context 1: Motion classifier with standard sensitivity setContext(1, 2, 1000); int motionA[4] = {100, 110, 120, 115}; int motionB[4] = {50, 45, 55, 48}; Learn(motionA, 4, 1); // Motion type A Learn(motionB, 4, 2); // Motion type B printf("Context 1 neurons: %d\n", GetCommitted()); // Context 2: Anomaly detector with tight matching setContext(2, 2, 500); int normal[4] = {128, 128, 128, 128}; Learn(normal, 4, 0); // Normal baseline printf("Context 2 neurons: %d\n", GetCommitted()); // Classify in context 1 setContext(1, 2, 1000); int testMotion[4] = {105, 112, 118, 110}; int dist, cat, nid; BestMatch(testMotion, 4, &dist, &cat, &nid); printf("Motion classification: Category %d\n", cat); // Check for anomaly in context 2 setContext(2, 2, 500); int testAnomaly[4] = {200, 50, 128, 90}; BestMatch(testAnomaly, 4, &dist, &cat, &nid); if (dist == 0xFFFF) { printf("Anomaly detected!\n"); } else { printf("Normal pattern, distance: %d\n", dist); } return 0; } ``` -------------------------------- ### Recognize Patterns with NeuroShield Source: https://context7.com/general-vision/neuroshield/llms.txt Broadcasts a feature vector to the network and returns recognition status and firing neuron details. Overloaded versions provide simple status, best match, or K-Nearest Neighbor results. ```cpp #include NeuroMemAI hNN; #define LEN 4 int pattern[LEN]; int dist, cat, nid; #define K 3 // Number of top firing neurons to retrieve int dists[K], cats[K], nids[K]; void recognizePatterns() { // Simple classification - returns status only // Status: 0=unknown, 4=uncertain, 8=identified for (int i = 0; i < LEN; i++) pattern[i] = 14; int status = hNN.classify(pattern, LEN); Serial.print("Recognition status: "); Serial.println(status); // Best match classification - returns top firing neuron details for (int i = 0; i < LEN; i++) pattern[i] = 12; status = hNN.classify(pattern, LEN, &dist, &cat, &nid); Serial.print("Best match - Distance: "); Serial.print(dist); Serial.print(", Category: "); Serial.print(cat); Serial.print(", NeuronID: "); Serial.println(nid); // K-Nearest Neighbor classification - returns up to K firing neurons for (int i = 0; i < LEN; i++) pattern[i] = 13; int responseNbr = hNN.classify(pattern, LEN, K, dists, cats, nids); Serial.print("Firing neurons: "); Serial.println(responseNbr); for (int i = 0; i < responseNbr; i++) { Serial.print(" Neuron "); Serial.print(nids[i]); Serial.print(": Category="); Serial.print(cats[i]); Serial.print(", Distance="); Serial.println(dists[i]); } } ``` -------------------------------- ### Classify Patterns with Python Source: https://context7.com/general-vision/neuroshield/llms.txt Classifies a vector against the neural network and iterates through firing neurons. ```python for i in range(LENGTH): vector[i] = 6 respNbr, dists, cats, nids = nm.Classify(vector, LENGTH, K) if respNbr == 0: print("Pattern [6,6,6,6] - Unknown (no firing neurons)") else: for i in range(respNbr): print(f" Neuron {nids[i]}: Category={cats[i]}, Distance={dists[i]}") ``` -------------------------------- ### saveKnowledge_SDcard / loadKnowledge_SDcard Source: https://context7.com/general-vision/neuroshield/llms.txt Saves and loads the neural network knowledge to/from an SD card in a format compatible with General Vision tools. ```APIDOC ## saveKnowledge_SDcard ### Description Saves the current neural network knowledge to an SD card file. ### Parameters - **filename** (string) - Required - The name of the file to save to. ### Response - **int** - Returns 0 for success, 1 if SD not detected, 2 for file error. ## loadKnowledge_SDcard ### Description Loads neural network knowledge from an SD card file. ### Parameters - **filename** (string) - Required - The name of the file to load from. ### Response - **int** - Returns 0 for success, 1 if SD not detected, 2 if file not found, 3 for file error, 4 for format error, 5 for size mismatch, 6 if capacity exceeded. ``` -------------------------------- ### Perform K-Nearest Neighbor Recognition Source: https://context7.com/general-vision/neuroshield/llms.txt Broadcasts a vector and returns up to K firing neurons with their distances and categories. ```python import ctypes import NeuroMem as nm LENGTH = 4 K = 3 # Maximum number of responses # Create arrays for input and output bytearray = ctypes.c_int * LENGTH vector = bytearray() # Recognize pattern [14,14,14,14] for i in range(LENGTH): vector[i] = 14 respNbr, dists, cats, nids = nm.Classify(vector, LENGTH, K) print(f"Pattern [14,14,14,14] - Firing neurons: {respNbr}") for i in range(respNbr): print(f" Neuron {nids[i]}: Category={cats[i]}, Distance={dists[i]}") # Output: # Neuron 2: Category=55, Distance=4 # Neuron 1: Category=33, Distance=12 ``` -------------------------------- ### Set Classification Mode Source: https://context7.com/general-vision/neuroshield/llms.txt Toggles between Radial Basis Function (RBF) and K-Nearest Neighbor (KNN) classification modes. ```cpp #include NeuroMemAI hNN; void setClassificationMode() { // RBF mode (default): Neurons fire only if input is within their influence field // Best for well-separated categories hNN.setRBF(); Serial.println("Classification mode: RBF"); // KNN mode: All committed neurons fire, sorted by distance // Best for overlapping categories requiring voting hNN.setKNN(); Serial.println("Classification mode: KNN"); // Example: K-NN classification with voting int pattern[4] = {13, 13, 13, 13}; int K = 5; int dists[5], cats[5], nids[5]; int responseNbr = hNN.classify(pattern, 4, K, dists, cats, nids); // Count votes per category int votes[256] = {0}; for (int i = 0; i < responseNbr; i++) { votes[cats[i]]++; } } ``` -------------------------------- ### Retrieve Neuron Contents Source: https://context7.com/general-vision/neuroshield/llms.txt Reads individual or bulk neuron data including memory models, influence fields, and categories for inspection or backup. ```cpp #include NeuroMemAI hNN; void inspectNeurons() { int ncount = hNN.NCOUNT(); Serial.print("Committed neurons: "); Serial.println(ncount); // Read individual neuron with detailed parameters int ncr, minif, aif, cat; int model[256]; // NEURONSIZE = 256 bytes for (int n = 0; n < ncount; n++) { hNN.readNeuron(n, model, &ncr, &minif, &aif, &cat); Serial.print("Neuron "); Serial.print(n); Serial.print(": NCR="); Serial.print(ncr); Serial.print(", AIF="); Serial.print(aif); Serial.print(", MINIF="); Serial.print(minif); Serial.print(", CAT="); Serial.print(cat); Serial.print(", Model=["); for (int i = 0; i < 4; i++) { // Display first 4 bytes Serial.print(model[i]); if (i < 3) Serial.print(","); } Serial.println("...]"); } // Bulk read all neurons into array // Format: NCR, 256*COMP, AIF, MINIF, CAT (260 ints per neuron) int* neurons = new int[ncount * 260]; int count = hNN.readNeurons(neurons); Serial.print("Read "); Serial.print(count); Serial.println(" neurons into array"); delete[] neurons; } ``` -------------------------------- ### Restore Neuron Contents with writeNeurons Source: https://context7.com/general-vision/neuroshield/llms.txt Clears the network and restores neurons from a previously saved array to enable knowledge transfer between sessions. ```cpp #include NeuroMemAI hNN; void saveAndRestoreKnowledge() { // First, train some patterns hNN.forget(); int p1[4] = {10, 10, 10, 10}; int p2[4] = {20, 20, 20, 20}; hNN.learn(p1, 4, 1); hNN.learn(p2, 4, 2); int ncount = hNN.NCOUNT(); Serial.print("Trained neurons: "); Serial.println(ncount); // Save knowledge to array // Each neuron: NCR + 256 COMP + AIF + MINIF + CAT = 260 ints int recLen = 256 + 4; int* savedNeurons = new int[ncount * recLen]; hNN.readNeurons(savedNeurons); // Clear the network hNN.forget(); Serial.print("After forget, neurons: "); Serial.println(hNN.NCOUNT()); // Returns 0 // Restore knowledge from array hNN.writeNeurons(savedNeurons, ncount); Serial.print("After restore, neurons: "); Serial.println(hNN.NCOUNT()); // Returns 2 // Verify recognition still works int dist, cat, nid; hNN.classify(p1, 4, &dist, &cat, &nid); Serial.print("Pattern1 recognized as category: "); Serial.println(cat); // Returns 1 delete[] savedNeurons; } ``` -------------------------------- ### Reset Neural Network with forget Source: https://context7.com/general-vision/neuroshield/llms.txt Uncommits all neurons to prepare for new learning. Optionally accepts a custom Maximum Influence Field (MAXIF) value. ```cpp #include NeuroMemAI hNN; void resetNetwork() { // Reset with default MAXIF (0x4000 = 16384) hNN.forget(); Serial.println("Network reset with default MAXIF"); // Reset with custom MAXIF for finer pattern discrimination int customMaxif = 1000; hNN.forget(customMaxif); Serial.print("Network reset with MAXIF: "); Serial.println(customMaxif); // Verify committed neurons is now 0 int committed = hNN.NCOUNT(); Serial.print("Committed neurons: "); Serial.println(committed); // Returns 0 } ``` -------------------------------- ### writeNeurons Source: https://context7.com/general-vision/neuroshield/llms.txt Clears the network and restores neurons from a previously saved array, enabling knowledge transfer between sessions. ```APIDOC ## writeNeurons ### Description Clears the current network and restores neurons from a provided array, allowing for the transfer of learned knowledge between sessions. ### Parameters - **savedNeurons** (int*) - Required - Pointer to the array containing neuron data. - **ncount** (int) - Required - The number of neurons to restore. ### Response - **void** - Updates the internal state of the NeuroMemAI object. ``` -------------------------------- ### setRBF / setKNN - Set Classification Mode Source: https://context7.com/general-vision/neuroshield/llms.txt Switches the neural network's classification mode between Radial Basis Function (RBF) and K-Nearest Neighbor (KNN). RBF is suitable for well-separated categories, while KNN is better for overlapping categories requiring voting. ```APIDOC ## setRBF / setKNN - Set Classification Mode ### Description Switches the neural network between Radial Basis Function (default) and K-Nearest Neighbor classification modes. ### Method `setRBF()` `setKNN()` ### Parameters None ### Request Example ```cpp #include NeuroMemAI hNN; // Set RBF mode (default) hNN.setRBF(); // Set KNN mode hNN.setKNN(); ``` ### Response None (This function modifies the internal state of the neural network). #### Success Response (200) None #### Response Example None ```