/* cmacdemo.c */ /* This test program exercises some of the CMAC calls It trains in a simple nonlinear function: z = sin(x + y) The program sits in a loop, testing at 100 random points and training at 100 random points, until any key is hit. After each testing cycle (100 random points) the approximation error and memory usage is displayed. */ #include #include #include #include /* Commented out by Patrick van der Smagt 20/08/96 PvdS */ /*#include */ /* Commented out by Patrick van der Smagt 20/08/96 PvdS */ /*#include */ #include #include #include "unh_cmac.h" static int state[2], quant[2] = {10,10}, response[2]; static int cmac_id; static int num_state = 2, num_resp = 1, num_cell = 16; static int mem_size; static int beta = 2; void test(void); void train(void); main() { static int i,j,k; static int index; static float x,y,z; static float pi = 3.14159; static float error_r, mag; /* allocate the CMAC */ /* 2 inputs, 1 output, generalization = 16 */ cmac_id = 0; while(!cmac_id) { printf("\nInput CMAC memory size (e.g. 3000): "); scanf("%d",&mem_size); cmac_id = allocate_cmac(num_state, quant, num_resp, num_cell, mem_size, LINEAR, 0); if (!cmac_id) { printf("CMAC allocation failure!\n"); } } clear_cmac_weights(cmac_id); test(); /* test CMAC */ i=0; while(++i < 200) { train(); /* train CMAC */ test(); /* test CMAC */ } /* save CMAC weights in file */ printf("\nSaving CMAC weights in file\n"); save_cmac(cmac_id, "weights.dat"); /* now clear the weights and retest (showing forget) */ printf("\nClear CMAC weights and test\n"); clear_cmac_weights(cmac_id); test(); /* unsave CMAC weights from file and test again */ printf("\nRestore CMAC weights and test\n"); deallocate_cmac(cmac_id); cmac_id = restore_cmac("weights.dat"); test(); /* de-allocate the CMAC and exit */ deallocate_cmac(cmac_id); remove("weights.dat"); } void test(void) { static int i,j,k; static float x,y,z; static float pi = 3.14159; static float error_r, mag; /* test at 100 random x,y points */ error_r = 0.0; mag = 0.0; for (k=0; k<100; ++k) { x = pi * (float)rand() / 32768.; y = pi * (float)rand() / 16384.; z = 1000.0 * sin(x + y); state[0] = (int)(200.0 * x); state[1] = (int)(200.0 * y); cmac_response(cmac_id, state, response); error_r += fabs( z - (float)response[0] ); mag += fabs( z ); } printf("Percent Error = %5.1f,", (100.0 * error_r/mag)); printf(" Memory Used = %6d\n", cmac_memory_usage(cmac_id)); } void train(void) { static int i,j,k; static float x,y,z; static float pi = 3.14159; /* train at 100 random x,y points */ for (k=0; k<100; ++k) { x = pi * (float)rand() / 32768.; y = pi * (float)rand() / 16384.; z = 1000.0 * sin(x + y); state[0] = (int)(200.0 * x); state[1] = (int)(200.0 * y); response[0] = (int)z; train_cmac(cmac_id, state, response, beta, 40); } }