Root/Examples/ehw4/src/genetic.c

1#include "stdio.h"
2#include "termios.h"
3#include "sys/mman.h"
4#include "stdlib.h"
5#include "sys/types.h"
6#include "sys/stat.h"
7#include "fcntl.h"
8#include "time.h"
9#include "math.h"
10#include "pthread.h"
11#include "sys/socket.h"
12#include "netinet/in.h"
13#include "netdb.h"
14#include "errno.h"
15#include "sys/un.h"
16#include "genetic.h"
17#include "jz47xx_gpio.h"
18#include <jz47xx_mmap.h>
19
20#define CS2_PORT JZ_GPIO_PORT_B
21#define CS2_PIN 26
22
23/**************************************************************************************************************************************
24    imprime un cromosoma completo */
25void mostrar_indiv(char *cromo, int pentarboles, int vars)
26{
27char *ap, i, fn[8] = {'!', '&', '^', '|', '_'}; //NOT, AND, XOR, OR, NADA o YES
28char vn[] = {'A', 'B', 'C', 'D', 'E' , 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', '.'};
29char f1,f2,f3;
30char a;
31
32ap = cromo;
33
34for(i = 0; i < ARBOLES_INDIV; i++){
35        if(*(cromo + 7) == 1)
36        {
37            vn[vars] = '.';
38            printf("%0x%c%c%c%c %i ", *(unsigned short int *)ap, vn[(*(ap+2) >> 4) & 0xF], vn[*(ap+2) & 0xF], vn[(*(ap+3) >> 4) & 0xF], vn[*(ap+3) & 0xF], *(ap+6));
39        }
40        else
41        {
42            vn[4] = '.';
43            printf("%0x%c%c%c%c %i", *(unsigned short int *)ap, vn[(*(ap+2) >> 4) & 0xF], vn[*(ap+2) & 0xF], vn[(*(ap+3) >> 4) & 0xF], vn[*(ap+3) & 0xF], *(ap+6));
44        }
45// printf("\t %0x %0x ", *(short int *)(ap+2), *(ap+6) );
46    ap = ap + LONG_ARBOL;
47}
48
49printf(" ");
50for(i = 0; i < LONG_INDIV; i++)
51{ a=*(char *)(cromo+i) & 0xff;
52    printf("%hhu,",a);
53}
54//fflush(stdout);
55}
56
57/**************************************************************************************************************************************
58    imprime un arbol completo */
59mostrar_arbol(char *cromo, int vars)
60{
61    char *ap, i, fn[8] = {'!', '&', '^', '|', '_'}; //NOT, AND, XOR, OR, NADA o YES
62    char vn[] = {'A', 'B', 'C', 'D', 'E' , 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', '.'};
63    ap = cromo;
64
65        if(*(cromo + 7) == 1)
66        {
67            vn[vars] = '.';
68            printf("LUT:%04x VARS:%c%c%c%c %0x", *(unsigned short int *)ap, vn[*(ap+2) >> 4], vn[*(ap+2) & 0xF], vn[*(ap+3) >> 4], vn[*(ap+3) & 0xF], *(ap+6));
69        }
70        else
71        {
72            vn[4] = '.';
73            printf("LUT:%04x VARS:%c%c%c%c %0x", *(unsigned short int *)ap, vn[*(ap+2) >> 4], vn[*(ap+2) & 0xF], vn[*(ap+3) >> 4], vn[*(ap+3) & 0xF], *(ap+6));
74        }
75        printf("\tVARS:%04x \tLUT_index:%0x \t", *(unsigned short int *)(ap+2), *(ap+6) );
76    for(i = 0; i < LONG_ARBOL; i++)
77    {
78        printf("%0x,",*(cromo+i));
79    }
80    printf("\n");
81}
82
83/**************************************************************************************************************************************
84    genera un numero de forma aleatoria hasta max inclusive*/
85char random_var(int max)
86{
87    char variable, mascara;
88    int i;
89    mascara = 1;
90    do
91    {
92        mascara = (mascara << 1) + 1;
93    }while(max > mascara);
94
95    if(HW_ENABLE == 1) variable = (*(int *)(evalfit_ptr1 + EVALFIT_RANDOM)) & mascara;
96    else variable = random() & mascara;
97
98    while(variable > max)
99    {
100        variable = variable - max;
101    }
102    return variable;
103}
104
105/**************************************************************************************************************************************
106    Genera un arbol de forma aleatoria
107        Las funciones y variables son representadas por enteros del 0 al 3 o mas...
108    - el arbol se encuentra compuesto de tres funciones, dos de entrada y una de salida.
109*/
110void gen_arbol(char *ap, int variables)
111{
112    int lut;
113    short int dato_lut;
114    lut = (random_var(FUNCIONES)*25) + (random_var(FUNCIONES) * 5) + random_var(FUNCIONES);//random_var(FUNCOMBS-1);
115    dato_lut = (*(funlut_ap+(lut*2)) << 8) + (*(funlut_ap+(lut*2)+1));
116    *(short int *)ap = ntohs(dato_lut); //Se cambia endianismo para cuando se ejecute en 386, que es distinto a PPC
117    *(ap+2) = *(ap+3) = 0;
118    *(ap+2) = random_var(variables) + (random_var(variables) << 4);
119    *(ap+3) = random_var(variables) + (random_var(variables) << 4);
120    *(ap+6) = lut;
121// mostrar_arbol(ap);
122}
123
124
125/**************************************************************************************************************************************
126    genera un individuo de forma aleatoria */
127void gen_indiv(char *cromo, int pentarboles, int vars)
128{
129char i=0;
130int n1, n2, n3, n4, n5, c1, c2, c3, c4, c5, sig, indice;
131
132n1 = n2 = n3 = n4 = n5 = 0;
133c1 = c2 = c3 = c4 = c5 = 0;
134indice = 0;
135
136sig=1;
137
138
139do
140{
141
142if((sig == 1) && (c1 < nivel1))
143{
144    gen_arbol(cromo + (indice * LONG_ARBOL), vars-1);
145    *(cromo +(indice*LONG_ARBOL) + 7) = 1;
146    n1 ++;
147    c1 ++;
148    indice ++;
149    if(n1 < 4)
150        sig = 1;
151    else
152    {
153        sig = 2;
154        n1 = 0;
155    }//printf("1");
156}
157else
158{
159    if((sig == 2) && (c2 < *(nivel2+pentarboles)))
160    {
161        gen_arbol(cromo + (indice*LONG_ARBOL), 3);
162        *(cromo +(indice*LONG_ARBOL) + 7) = 2;
163        n2++;
164        c2 ++;
165        indice ++;
166        if(c2 == *(nivel2+pentarboles))
167            sig = 3;
168        else
169        {
170            if(n2 < 4)
171                sig = 1;
172            else
173            {
174                sig = 3;
175                n2 = 0;
176            }
177        }//printf("2");
178    }
179    else
180    {
181        if((sig == 3) && (c3 < *(nivel3+pentarboles)))
182        {
183            gen_arbol(cromo + (indice*LONG_ARBOL), 3);
184            *(cromo +(indice*LONG_ARBOL) + 7) = 3;
185            n3++;
186            c3++;
187            indice++;
188            if(c3 == *(nivel3+pentarboles))
189                sig = 4;
190            else
191            {
192                if(n3 < 4)
193                    sig = 1;
194                else
195                {
196                    sig = 4;
197                    n3 = 0;
198                }
199            }//printf("3");
200        }
201        else
202        {
203            if((sig == 4) && (c4 < *(nivel4+pentarboles)))
204            {
205                gen_arbol(cromo + (indice*LONG_ARBOL), 3);
206                *(cromo +(indice*LONG_ARBOL) + 7) = 4;
207                n4++;
208                c4++;
209                indice++;
210                if(c4 == *(nivel4+pentarboles))
211                    sig = 5;
212                else
213                {
214                    if(n4 < 4)
215                        sig = 1;
216                    else
217                    {
218                        sig = 5;
219                        n4 = 0;
220                    }
221                }//printf("4");
222            }
223            else
224            {
225                if((sig == 5) && (c5 < *(nivel5+pentarboles)))
226                {
227                    gen_arbol(cromo + (indice*LONG_ARBOL), 3);
228                    *(cromo +(indice*LONG_ARBOL) + 7) = 5;
229                    c5++;
230                    indice++;
231                    if(c5 == *(nivel5+pentarboles))
232                        sig = 1;
233                    else
234                        sig = 1;
235                }
236            }
237
238        }
239    }
240
241}
242/* mostrar_indiv(cromo, 1,vars); //*/
243}while(indice < ARBOLES_INDIV);
244
245}
246
247
248/**************************************************************************************************************************************
249    genera una poblacion completa */
250void gen_poblacion(char *cromo, int pentarboles, int vars, int indivs)
251{
252    int i;
253    for(i=0; i < indivs; i++)
254    {
255        gen_indiv(cromo + ( i * LONG_INDIV), pentarboles, vars);
256    }
257}
258
259
260/**************************************************************************************************************************************
261    halla la salida de un arbol para una entrada de x de un cromo basado en LUT*/
262int eval_func_lut(char *ap, int x, int vars ) //var apunta al valor de las variables
263{
264char Y;
265char var[vars], i, a, b, c, d;
266int lut;
267
268for(i=0;i <= vars-1;i++)
269{
270    var[i] = (x >> i) & 0x1;
271// printf("-%i",var[i]);
272}
273var[vars] = 0;
274
275a = *(ap + 3) & 0xF;
276b = (*(ap + 3) >> 4) & 0xF;
277c = *(ap + 2) & 0xF;
278d = (*(ap + 2) >> 4) & 0xF;
279i = var[a] + (var[b]*2) + (var[c]*4) + (var[d]*8);
280lut = *(short int *)ap;
281Y = (lut >> i) & 0x1;
282
283return Y;
284}
285
286/**************************************************************************************************************************************
287    retorna las salidas de un cromosoma de 5 arboles*/
288void eval_pentarbol_sw(char *ap, int *salida, int *entrada, int vars)
289{
290    int i, k ;
291    char salidas[ARBOLES][COMBS], aux[COMBS];
292
293    for(i=0; i <= ARBOLES-2; i++){ //se evaluan las salidas de los primeros arboles y se almacenan en salidas
294        for(k=0; k<= (COMBS-1); k++)
295        {
296            salidas[i][k] = eval_func_lut((ap+(i*LONG_ARBOL)), k, vars);
297        }
298    }
299
300    //se calculan los minterminos para el arbol de salida
301    for(k=0; k <= (COMBS-1); k++)
302    {
303        aux[k] = ((salidas[0][k])*1) + ((salidas[1][k])*2) + ((salidas[2][k])*4) + ((salidas[3][k])*8);
304    }
305
306    for(i=0; i <= (COMBS-1); i++)
307    {
308        *(salida + i) = eval_func_lut(ap + ((ARBOLES-1) * LONG_ARBOL), aux[i], vars);
309    }
310}
311
312
313/**************************************************************************************************************************************
314    retorna el numero de errores y las salidas de un cromosoma de 1 o mas pentarboles*/
315int eval_fit_sw(char *ap, int *objetivo, int num_min, int pentarboles, int vars )
316{
317    int *obj_min, *med_min2, *med_min3, *med_min4, *med_min5, *entrada, i, j, errores, puertas;
318    int *salida, n2, n3, n4, n5, x;
319
320    obj_min = malloc(sizeof(obj_min)*COMBS);
321    med_min2 = malloc(sizeof(med_min2)*COMBS);
322    med_min3 = malloc(sizeof(med_min3)*COMBS);
323    med_min4 = malloc(sizeof(med_min4)*COMBS);
324    med_min5 = malloc(sizeof(med_min5)*COMBS);
325    entrada = malloc(sizeof(entrada)*COMBS);
326    salida = malloc(sizeof(salida)*COMBS);
327    errores = 0;
328
329    for(i=0; i < COMBS; i++)
330    {
331        *(obj_min+i) = 0;
332        *(entrada+i) = i;
333        *(med_min2 + i) = 0;
334        *(med_min3 + i) = 0;
335        *(med_min4 + i) = 0;
336        *(med_min5 + i) = 0;
337    }
338
339    for(i = 0; i < num_min; i++)
340    {
341        *(obj_min + (*(objetivo + i))) = 1; //se convierte el objetivo a un arreglo
342    }
343
344    i = 0;
345    n2 = 0;
346    n3 = 0;
347    n4 = 0;
348    n5 = 0;
349
350    do
351    {
352        if(*(ap + (i * LONG_ARBOL) + 7) == 1)
353        {
354            eval_pentarbol_sw(ap + (i * LONG_ARBOL), salida, entrada, vars);
355            for(j = 0; j < COMBS; j++)
356            {
357                *(med_min2 + j) = *(med_min2 + j) + (*(salida + j) << n2);
358            }
359            if(n2 == 3) n2 = 0; else n2++;
360            i = i + 5;
361        }
362         else
363        {
364            if(*(ap + (i * LONG_ARBOL) + 7) == 3)
365            {
366                for(j = 0; j < COMBS; j++)
367                {
368                    *(salida + j) = eval_func_lut(ap + (i * LONG_ARBOL), *(med_min2 + j), vars);
369                }
370                for(j = 0; j < COMBS; j++)
371                {
372                    *(med_min3 + j) = *(med_min3 + j) + (*(salida + j) << n3);
373                }
374                if(n3 == 3) n3 = 0; else n3++;
375                i++;
376            }
377            else
378            {
379
380                if(*(ap + (i * LONG_ARBOL) + 7) == 4)
381                {
382                    for(j = 0; j < COMBS; j++)
383                    {
384                        *(salida + j) = eval_func_lut(ap + (i * LONG_ARBOL), *(med_min3 + j), vars);
385                    }
386                    for(j = 0; j < COMBS; j++)
387                    {
388                        *(med_min4 + j) = *(med_min4 + j) + (*(salida + j) << n4);
389                    }
390                    if(n4 == 3) n4 = 0; else n4++;
391                    i++;
392                }
393            }
394        }
395    }while(i <= (ARBOLES_INDIV-1));
396
397    if(*(ap + ((ARBOLES_INDIV-1) * LONG_ARBOL) + 7) == 2)
398    {
399        for(j = 0; j < COMBS; j++) //se evalua el arbol de salida
400        {
401            errores = errores + abs(*(med_min2 + j) - *(obj_min + j)); //errores
402/* printf("[%i]",*(med_min2 + j));*/
403        }
404    }
405
406    if(*(ap + ((ARBOLES_INDIV-1) * LONG_ARBOL) + 7) == 3)
407    {
408        for(j = 0; j < COMBS; j++) //se evalua el arbol de salida
409        {
410            errores = errores + abs(*(med_min3 + j) - *(obj_min + j)); //errores
411        }
412    }
413
414    if(*(ap + ((ARBOLES_INDIV-1) * LONG_ARBOL) + 7) == 4)
415    {
416        for(j = 0; j < COMBS; j++) //se evalua el arbol de salida
417        {
418            errores = errores + abs(*(med_min4 + j) - *(obj_min + j)); //errores
419        }
420    }
421
422    if(*(ap + ((ARBOLES_INDIV-1) * LONG_ARBOL) + 7) == 5)
423    {
424        for(j = 0; j < COMBS; j++) //se evalua el arbol de salida
425        {
426            errores = errores + abs(*(med_min5 + j) - *(obj_min + j)); //errores
427        }
428    }
429    free(obj_min);
430    free(med_min2);
431    free(med_min3);
432    free(med_min4);
433    free(med_min5);
434    free(entrada);
435    free(salida);
436
437    puertas = 0;
438
439    return ((errores * PESO_SALIDA) + puertas);
440}
441
442/**************************************************************************************************************************************
443    inicia la evaluacion de un cromosoma en un periferico*/
444int evalfit_hw_init(char *cromo, int pentarboles, int nivel_max, void *evalfit_ptr )
445{
446int i;
447
448/** insertar cromosoma en periferico **/
449    for(i = 0; i < ARBOLES_INDIV; i++)
450    {
451        *(int *)(evalfit_ptr + EVALFIT_MEMOFFSET + (LONG_ARBOL*i) + 0) =*(char *)(cromo +(LONG_ARBOL*i)+7);
452        //printf("\n%04hhu: Level:%X ", *(cromo+(i*LONG_ARBOL) + 6), *(int *)(evalfit_ptr + EVALFIT_MEMOFFSET + (LONG_ARBOL*i) + 0));
453        *(int *)(evalfit_ptr + EVALFIT_MEMOFFSET + (LONG_ARBOL*i) + 4) = *(int *)(cromo +(LONG_ARBOL*i));
454        //printf("LUT-VARS: %08x",*(int *)(evalfit_ptr + EVALFIT_MEMOFFSET + (LONG_ARBOL*i) + 4));
455    }
456    *(int *)((evalfit_ptr) + EVALFIT_MEMOFFSET + (LONG_ARBOL*i) + 0) = 0xF; //para terminar
457    i++;
458    *(int *)((evalfit_ptr) + EVALFIT_MEMOFFSET + (LONG_ARBOL*i) + 0) = 0xF; //para terminar
459/** Iniciar **/
460    *(int *)(evalfit_ptr + EVALFIT_CONTROL_OFFSET) = CONTROL_START_MASK;
461}
462
463/**************************************************************************************************************************************
464    espera y retorna el numero de errores y las salidas de un cromosoma de 1 o mas pentarboles*/
465int evalfit_hw_wait(char *cromo, int pentarboles, int nivel_max, void *evalfit_ptr )
466{
467int errores, puertas, i;
468
469   // tiempo1 = get_timestamp();
470    do{
471        //printf("\nSTATUS: %0x",*(short *)(evalfit_ptr + EVALFIT_STATUS));
472        //usleep(100);
473    }while((*(short *)(evalfit_ptr + EVALFIT_STATUS) & DONE_MASK) != 0x8000); //wait for DONE
474    //tiempo2 = get_timestamp();
475    //printf("\n\nErrors calculated HW: %0x",(*(int *)(evalfit_ptr + EVALFIT_ERRORS) & ERRORS_MASK)); //errores
476    errores = (*(int *)(evalfit_ptr + EVALFIT_ERRORS) & ERRORS_MASK); //errores
477    *(int *)(evalfit_ptr + EVALFIT_CONTROL_OFFSET) = 0; //end , disable
478    puertas = 0;
479    for(i = 0; i < ARBOLES_INDIV; i++)
480    {
481        puertas = puertas + *(puertas_ap + *(char *)(cromo +(LONG_ARBOL*i)+6));
482    }
483    return ((errores * PESO_SALIDA) + (PESO_PUERTAS * puertas) + (PESO_NIVELES * nivel_max));
484}
485
486/**************************************************************************************************************************************
487    cruza dos cromosomas y almacena en destino. */
488void cruzar(char *padre1, char *padre2, char *destino1, char *destino2, int pentarboles)
489{
490int a, i;
491
492    a = (random() & 0x1F) + 1; //punto de corte, es un numero de arbol
493
494    while(a > (ARBOLES_INDIV))
495    {
496        a = a - ARBOLES_INDIV;//(pentarboles * ARBOLES);
497    }
498    a = a-1;
499// printf("\n%i",a);
500
501    for(i = 0; i < (a * LONG_ARBOL); i++)
502    {
503        *(destino1 + i) = *(padre1 + i); //padre1
504        *(destino2 + i) = *(padre2 + i); //padre1
505    }
506
507    for(i = (a * LONG_ARBOL); i < LONG_INDIV; i++) // +1 para el arbol de salida
508    {
509        *(destino1 + i) = *(padre2 + i); //padre2
510        *(destino2 + i) = *(padre1 + i); //padre2
511    }
512}
513
514/**************************************************************************************************************************************
515    cruza dos cromosomas y almacena en destino. */
516void cross2point(char *padre1, char *padre2, char *destino1, char *destino2, int pentarboles)
517{
518int a, b, i;
519
520    a = random_var((pentarboles*ARBOLES)-3);
521    b = random_var((pentarboles*ARBOLES)-a-2)+a;
522    a++;
523    b++;
524// printf("\n%i %i %i",a,b,pentarboles*ARBOLES);fflush(stdout);
525    for(i = 0; i < (a*LONG_ARBOL) ; i++)
526    {
527        *(destino1 + i) = *(padre1 + i); //
528        *(destino2 + i) = *(padre2 + i); //
529    }
530    for(i = a; i < (b*LONG_ARBOL) ; i++)
531    {
532        *(destino2 + i) = *(padre1 + i); //
533        *(destino1 + i) = *(padre2 + i); //
534    }
535    for(i = (b*LONG_ARBOL); i < LONG_INDIV; i++) // +1 para el arbol de salida
536    {
537        *(destino1 + i) = *(padre1 + i); //padre2
538        *(destino2 + i) = *(padre2 + i); //padre2
539    }
540}
541
542/**************************************************************************************************************************************
543    muta un cromosoma y almacena en destino. */
544
545void muta_indiv(char *padre, char *destino, int pentarboles, int vars)
546{
547    int a, i;
548
549    gen_indiv(destino, pentarboles, vars);
550
551    a = (random() & 0x1F) + 1; //punto de corte, es un numero de arbol
552
553    while(a > (ARBOLES_INDIV))
554    {
555        a = a - ARBOLES_INDIV;
556    }
557
558    for(i = 0; i < (a * LONG_ARBOL); i++)
559    {
560        *(destino + i) = *(padre + i); //padre1
561    }
562}
563
564/**************************************************************************************************************************************
565        Introducir minterminos **/
566void minterm2peripheral(int *fun_obj, int tamano, void *evalfit_ptr)
567{
568    int i, j, a;
569
570    for(i = 0; i < 512; i++) //rellenar con 0
571    {
572        *(int *)(evalfit_ptr + EVALFIT_OBJOFFSET + (i*4)) = 0;
573    }
574
575    for(i = 0; i < tamano; i++) //insertar 1's en segmento de mem objetivo
576    {
577        j=0;
578        a=fun_obj[i];
579        while(a > 31)
580        {
581            a -= 32;
582            j++;
583        }
584        *(int *)(evalfit_ptr + EVALFIT_OBJOFFSET + (j*4)) += (1 << (31-a));
585    }
586}
587
588
589/**************************************************************************************************************************************
590    map peripheral **/
591int periph_map(off_t offset)
592{
593int basemem, baseperiph;
594    basemem = open("/dev/mem", (O_RDWR | O_SYNC)); //abrir dispositivo memoria para mapear dir del periferico
595    if(basemem == -1)
596    {
597        printf("Error to open /dev/mem \n");
598        return -1;
599    }
600    baseperiph = (int )mmap(NULL, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, basemem, offset);// & ~MAP_MASK);
601    if (baseperiph == -1)
602    {
603        printf ("Cannot mmap.\n");
604        return -1;
605    }
606return baseperiph;
607}
608
609/**************************************************************************************************************************************
610     inicializar periferico **/
611int init_peripheral(int offset_int, int basemem)
612{
613/* Variables para periferico*/
614    int *aux, base_periferico, *ConfigRegsBase_ptr, maxcombs, nivel_max;
615    void *pio, *evalfit_ptr;
616    basemem = open("/dev/mem", (O_RDWR | O_SYNC)); //abrir dispositivo memoria para mapear dir del periferico
617    if(basemem == -1)
618    {
619            printf("Error al abrir /dev/mem \n");
620            return -1;
621    }
622    pio = jz_gpio_map(CS2_PORT);
623    jz_gpio_as_func (pio, CS2_PIN, 0);
624    ConfigRegsBase_ptr = (int *)periph_map(CONFIG_REGS_BASE);// + SACR2_OFFSET/sizeof(int);//SMCR2_OFFSET/sizeof(int);
625    printf("\n%0x ", *(ConfigRegsBase_ptr + SMCR2_OFFSET/sizeof(int)));
626    munmap(ConfigRegsBase_ptr, MAP_SIZE);
627    evalfit_ptr = (int *)periph_map(EVALFIT_PHYSBASE1);
628
629    printf("\r\nevalfit_ptr: %0x", evalfit_ptr);
630    if( evalfit_ptr == (int *)MAP_FAILED)
631    { printf("error mmap!\n");
632            fflush(stdout);
633            return -1;
634    }
635    *(char *)(evalfit_ptr + EVALFIT_CONTROL_OFFSET) = CONTROL_RESET_MASK; //reset
636    //sleep(1);
637    *(char *)(evalfit_ptr + EVALFIT_CONTROL_OFFSET) = 0;
638    printf("\nDate + Status: %0x\n", *(char *)(evalfit_ptr + EVALFIT_STATUS));
639return evalfit_ptr;
640}
641
642/**************************************************************************************************************************************
643     cerrar periferico **/
644int close_peripheral(char *evalfit_ptr)
645{
646    if(munmap(evalfit_ptr, MAP_SIZE)==-1)
647        perror("munmap");
648        printf("Error en unmap() (close_peripheral)\n");
649        exit(-1);
650}
651
652/**************************************************************************************************************************************
653     cambiar endianismo **/
654int big2little(int x)
655{
656int y, i, r;
657y=0;
658r=0;
659    for(i=0 ; i<=3; i++){
660        x = x >> r;
661        y = y << r;
662        y = y | (x & 0xFF);
663        r = 8;
664    }
665return y;
666}
667
668/**************************************************************************************************************************************
669    crea y evoluciona un cromosoma a partir de una funcion objetivo*/
670evolucionar(struct gen_datos_tipo *gen_datos)
671{
672int *generacion, k, a, i, j = 0, tamacromo, vars, aux, *aux_sal, T;
673int conta=0, aux1, aux2, *fitness, *fitness2, *entrada, *objetivo, tamaobj, pentarboles, *fitness_sal, fitness_entrada, nivel_max;
674char o, *ap, *cromo, *ordenpoblacion, *cromo_sal, *cromo_entrada;
675long int tiempo1, tiempo2;
676float tiempof1, tiempof2, tiempof3;
677
678/* Variables para almacenar datos para graficar*/
679    int *datos, x, puntos;
680    char ruta[]="sarsar.dat";
681    FILE *fich;
682/* datos = malloc(sizeof(datos)*maxgeneraciones*2); if(datos==0) printf("Error en malloc");*/
683/* x=0;*/
684
685    objetivo = gen_datos -> objetivo;
686    tamaobj = gen_datos -> tamaobj;
687    pentarboles = gen_datos -> pentarboles;
688    tamacromo = gen_datos -> tamacrom;
689    cromo_sal = gen_datos -> cromo_sal;
690    fitness_sal = gen_datos -> fitness;
691    cromo_entrada = gen_datos -> cromo_entrada;
692    fitness_entrada = gen_datos -> fitness_entrada;
693    nivel_max = gen_datos -> nivel_max;
694    vars = gen_datos -> vars;
695    generacion = gen_datos->generacion;
696    aux = gen_datos->aux;
697    aux_sal = gen_datos->aux_sal;
698
699    cromo = malloc(sizeof(cromo) * (poblacion + 2) * LONG_INDIV); if(cromo==0) printf("Error en malloc");
700    fitness = malloc(sizeof(fitness) * (poblacion+1)); if(fitness==0) printf("Error en malloc");
701    fitness2 = malloc(sizeof(fitness2) * (poblacion+1)); if(fitness2==0) printf("Error en malloc");
702    ordenpoblacion = malloc(sizeof(ordenpoblacion) * (poblacion+1)); if(ordenpoblacion==0) printf("Error en malloc");
703
704    if(gen_datos->en_cromo_entrada == 1)
705    {
706        for(i = 0; i < LONG_INDIV; i++ )
707        {
708            *(char *)(cromo + i) = *(char *)(cromo_entrada + i);
709        }
710    }
711
712    if(gen_datos->en_cromo_entrada == 0)
713        gen_poblacion(cromo, pentarboles, vars, poblacion); //generate chromosome
714    else
715        gen_poblacion(cromo + LONG_INDIV, pentarboles, vars, poblacion-1);
716
717    for(i = 0; i < poblacion; i++)
718    {
719        *(ordenpoblacion + i) = i; //se inicializa el stream para el orden poblacional
720        *(fitness + i) = 100000;
721        *(fitness2 + i) = 100000;
722    }
723
724/** copiar miniterminos a periferico **/
725    if(HW_ENABLE == 1) {
726        minterm2peripheral(objetivo, tamaobj, (int *)(evalfit_ptr1));
727/*
728         minterm2peripheral(objetivo, tamaobj, (int *)(evalfit_ptr2));
729        minterm2peripheral(objetivo, tamaobj, (int *)(evalfit_ptr3));
730        minterm2peripheral(objetivo, tamaobj, (int *)(evalfit_ptr4));
731*/
732    }
733
734/** Insertar maxcombs y nivel_max **/
735    if(HW_ENABLE == 1) {
736        *(int *)(evalfit_ptr1 + EVALFIT_WREG4) = (COMBS-1) + (nivel_max << 16);
737/*
738        *(int *)(evalfit_ptr2 + EVALFIT_WREG4) = (COMBS-1) + (nivel_max << 16);
739        *(int *)(evalfit_ptr3 + EVALFIT_WREG4) = (COMBS-1) + (nivel_max << 16);
740        *(int *)(evalfit_ptr4 + EVALFIT_WREG4) = (COMBS-1) + (nivel_max << 16);
741*/
742    }
743    o=0;
744    *generacion = 0;
745    T = aux >> 16;
746    do{
747
748// cruzar
749        for(i = ((poblacion*T)/8); i < ((poblacion*(T+1))/8); i=i+4) //salvar los primeros 4 y cruzar
750        {
751            cross2point(cromo+INDICE_PADRE1, cromo+INDICE_PADRE2, cromo+(*(ordenpoblacion+i)*LONG_INDIV), cromo+(*(ordenpoblacion+i+1)*LONG_INDIV), pentarboles);
752            cross2point(cromo+INDICE_PADRE1, cromo+INDICE_PADRE2, cromo+(*(ordenpoblacion+i+2)*LONG_INDIV), cromo+(*(ordenpoblacion+i+3)*LONG_INDIV), pentarboles);
753        }//cruzar
754
755// Mutacion
756        for(i = ((poblacion*(T+1))/8); i < ((poblacion*(T+2))/8); i++)
757        {
758            muta_indiv(cromo + INDICE_PADRE1, cromo + ((*(ordenpoblacion + i )) * LONG_INDIV), pentarboles, vars);
759        }
760        for(i = ((poblacion*(T+2))/8); i < ((poblacion*(T+3))/8); i++)
761        {
762            muta_indiv(cromo + INDICE_PADRE2, cromo + ((*(ordenpoblacion + i )) * LONG_INDIV), pentarboles, vars);
763        }
764
765//crear nuevos indiv reemplazar por taras
766        for(i = ((poblacion*(T+3))/8); i < poblacion; i++)
767        {
768            gen_indiv((cromo + ((*(ordenpoblacion + i)) * LONG_INDIV)), pentarboles, vars);
769        }
770
771// evaluar cromosomas de poblacion
772        o=0;
773// tiempo1 = get_timestamp();
774        for(i = 0; i < poblacion; i=i+1)
775        {
776            if(HW_ENABLE == 1)
777            {
778                evalfit_hw_init((cromo + (i * LONG_INDIV)), pentarboles, nivel_max, (int *)evalfit_ptr1);
779/*
780                evalfit_hw_init((cromo + ((i+1) * LONG_INDIV)), pentarboles, nivel_max, (int *)evalfit_ptr2);
781                evalfit_hw_init((cromo + ((i+2) * LONG_INDIV)), pentarboles, nivel_max, (int *)evalfit_ptr3);
782                evalfit_hw_init((cromo + ((i+3) * LONG_INDIV)), pentarboles, nivel_max, (int *)evalfit_ptr4);
783*/
784                *(fitness + i) = evalfit_hw_wait((cromo + (i * LONG_INDIV)), pentarboles, nivel_max, (int *)evalfit_ptr1);
785/*
786                *(fitness + i+1) = evalfit_hw_wait((cromo + ((i+1) * LONG_INDIV)), pentarboles,nivel_max, (int *)evalfit_ptr2);
787                *(fitness + i+2) = evalfit_hw_wait((cromo + ((i+2) * LONG_INDIV)), pentarboles,nivel_max, (int *)evalfit_ptr3);
788                *(fitness + i+3) = evalfit_hw_wait((cromo + ((i+3) * LONG_INDIV)), pentarboles, nivel_max, (int *)evalfit_ptr4);
789*/
790            }else{
791                *(fitness + i) = eval_fit_sw((cromo + (i * LONG_INDIV)), objetivo, tamaobj, pentarboles, vars);
792/*
793                *(fitness + i+1) = eval_fit_sw((cromo + ((i+1) * LONG_INDIV)), objetivo, tamaobj, pentarboles, vars);
794                *(fitness + i+2) = eval_fit_sw((cromo + ((i+2) * LONG_INDIV)), objetivo, tamaobj, pentarboles, vars);
795                *(fitness + i+3) = eval_fit_sw((cromo + ((i+3) * LONG_INDIV)), objetivo, tamaobj, pentarboles, vars);
796*/
797            }
798            *(fitness2 + i) = *(fitness + i);
799/*
800            *(fitness2 + i+1) = *(fitness + i+1);
801            *(fitness2 + i+2) = *(fitness + i+2);
802            *(fitness2 + i+3) = *(fitness + i+3);
803*/
804
805            if(*(fitness + i) < PESO_SALIDA)
806            {
807                o++; //incrementar numero de aciertos
808            }
809        }
810// tiempo2 = get_timestamp();
811        x++;
812
813    //seleccionar cromosomas para mutar y cruzar y para eliminar, se realiza una ordenacion en ordenpoblacion, solo se ordena el indice del cromosoma
814        for(i = 0; i < poblacion; i++)
815        {
816            *(ordenpoblacion + i) = i; //se inicializa el stream para el orden poblacional
817        }
818
819        for(i=0; i < poblacion; i++)
820        {
821            for(j=i+1; j < poblacion; j++)
822            {
823                if(*(fitness2 + j) < *(fitness2 + i))
824                {
825                    aux1 = *(ordenpoblacion + i);
826                    *(ordenpoblacion + i) = *(ordenpoblacion + j);
827                    *(ordenpoblacion + j) = aux1;
828                    aux2 = *(fitness2 + i);
829                    *(fitness2 + i) = *(fitness2 + j);
830                    *(fitness2 + j) = aux2;
831                }
832            }
833        }
834
835
836    //Se mide la evolucion del fitness en las generaciones, se saca la media por generacion
837        aux1 = 0;
838        for(i = 0; i < poblacion; i++)
839        {
840            aux1 = aux1 + *(fitness + i);
841        }
842        *(aux_sal + *generacion) = aux1 / poblacion;
843        *(aux_sal + maxgeneraciones + *generacion) = *fitness2;
844
845        (*generacion)++;
846
847// for(i=0; i < RESULTADOS; i++)
848// {
849// printf("\nfit%i: %i ", i, *(fitness+*(ordenpoblacion+i)), *(generacion+*(ordenpoblacion+i)));
850// mostrar_indiv(cromo + ( *(ordenpoblacion + i) * LONG_INDIV), pentarboles, vars);
851// }
852
853    }while(/* (o < RESULTADOS) && */ (*generacion < maxgeneraciones));
854
855    for(i = 0; i < RESULTADOS; i++)
856    {
857        for(j=0; j< LONG_INDIV;j++)
858        {
859            *(cromo_sal + (i*LONG_INDIV) + j) = *(cromo + (*(ordenpoblacion + i)*LONG_INDIV) + j);
860        }
861        *(fitness_sal + i) = *(fitness + *(ordenpoblacion + i));
862    }
863
864    free(cromo);
865    free(fitness);
866    free(fitness2);
867    free(ordenpoblacion);
868}
869
870

Archive Download this file

Branches:
master



interactive