/* Perform the memory allocation needed for the strings that will be generated */ void memory_allocation() { unsigned numbytes; int i; /* Allocate memory for old and new populations of individuals */ numbytes = popsize * sizeof(struct individual); if ((oldpop = (struct individual *) malloc(numbytes)) == NULL) nomemory("old population"); if ((newpop = (struct individual *) malloc(numbytes)) == NULL) nomemory("new population"); /* Allocate memory for chromosome strings in populations */ for (i = 0; i < popsize; i++) { if ((oldpop[i].chrom = (unsigned *) malloc(numbytes)) == NULL) nomemory("old population chromosomes"); if ((newpop[i].chrom = (unsigned *) malloc(numbytes)) == NULL) nomemory("new population chromosomes"); if ((bestfit.chrom = (unsigned *) malloc(numbytes)) == NULL) nomemory("bestfit chromosomes"); } memory_for_selection(); }
/* Routine to calculate the matrix of expectation of the * rooted tree from the unrooted*/ void planttree(double **original_matrix,double **new_matrix){ double **matrix; extern int **conv_matrix; int a,b,c,d,is_k=0; extern int branches; extern int nodecount; extern int mode; d=(ISMODE(NODEASROOT))?1:2; /* Have an extra row/column if we want information about kappa*/ if(ISMODE(HKY) && NOTMODE(NOKAPPA)){ d++; is_k=1; } /* Get memory for necessary matrix*/ matrix=calloc(nodecount+d,sizeof(double *)); if(matrix==NULL) nomemory(); for(a=0;a<nodecount+d;a++){ matrix[a]=calloc(branches+is_k,sizeof(double)); if(matrix[a]==NULL) nomemory(); } /* Zero rootedexpect matrix*/ for(a=0;a<nodecount+d;a++) for(b=0;b<nodecount+d;b++) new_matrix[a][b]=0; /* Do first matrix multiplication, conv_matrix*expectation*/ for(a=0;a<nodecount+d;a++) for(b=0;b<branches+is_k;b++) for(c=0;c<branches+is_k;c++) matrix[a][b]+=(double)conv_matrix[a][c]*original_matrix[c][b]; /* Do second matrix multiplication, result*conv_matrix^{t}*/ for(a=0;a<nodecount+d;a++) for(b=0;b<nodecount+d;b++) for(c=0;c<branches+is_k;c++) new_matrix[a][b]+=matrix[a][c]*conv_matrix[b][c]; /* Free memory used, since we don't need the intermediate * matrix any more*/ for(a=0;a<nodecount+d;a++) free(matrix[a]); free(matrix); }
/* Allocate memory for performing tournament selection */ void memory_for_selection() { unsigned numbytes; numbytes = popsize * sizeof(int); if ((tournlist = (int *) malloc(numbytes)) == NULL) nomemory("tournament list"); tournsize = 2; /* Use binary tournament selection */ }
void app2_ordena_piezas_problema_g(void) //Obtiene Arreglo con todas las Piezas del Problema { int i, j, k=0; #define ORDEN_x_NINGUNO 0 #define ORDEN_x_AREA 1 #define ORDEN_x_LADO_HORIZONTAL 2 #define ORDEN_x_LADO_VERTICAL 3 //#define TIPO_ORDEN ORDEN_x_AREA #define TIPO_ORDEN ORDEN_x_NINGUNO //Solicita memoria para piezasdistintas if((piezasproblema = (TNodoAP*) malloc(NumPie*sizeof(TNodoAP))) == NULL) nomemory("piezasproblema en app_ordena_piezas_problema_g"); #ifdef _DEBUG_MALLOC_ printf("Malloc, App_g.c, 237, piezasproblema, %d\n", NumPie*sizeof(TNodoAP)); #endif #if (TIPO_ORDEN == ORDEN_x_NINGUNO) //No hay ordenamiento #elif(TIPO_ORDEN == ORDEN_x_AREA) //Ordenamiento Qsort por Area de cada pieza //Deja primero las piezas con area menor en forma ascendente con respecto al area de c/pieza qsort(piezasdistintas, cantidadtipospiezas + 1, sizeof(TNodoAP), (void *) AreaNodoAPCompara_g); #elif(TIPO_ORDEN == ORDEN_x_LADO_HORIZONTAL) //Ordenamiento Qsort horizontal (considera el ancho de cada pieza) //Deja primero las piezas con ancho menor en forma ascendente con respecto al ancho de c/pieza qsort(piezasdistintas, cantidadtipospiezas + 1, sizeof(TNodoAP), (void *) HorizontalNodoAPCompara_g); #elif(TIPO_ORDEN == ORDEN_x_LADO_VERTICAL) //Ordenamiento Qsort Vertical (considera el alto de cada pieza) //Deja primero las piezas con alto menor en forma ascendente con respecto al alto de c/pieza qsort(piezasdistintas, cantidadtipospiezas + 1, sizeof(TNodoAP), (void *) VerticalNodoAPCompara_g); #endif // Una vez ordenadas las piezas, se leen de mayor a menor. // Como el ordenamiento es de menor a mayor hay que leer las piezas de atras para adelante for(i=cantidadtipospiezas;i>0;i--) { for(j=1;j<=piezasdistintas[i].cantidadpiezas;j++) { piezasproblema[k].ancho = piezasdistintas[i].ancho; piezasproblema[k].alto = piezasdistintas[i].alto; piezasproblema[k].numero = piezasdistintas[i].numero; piezasproblema[k].cantidadpiezas = 1; k++; }//End for }//End for }//End app_ordena_piezas_problema_g
void app2_agregalistap_g(int x, int y, int anc, int alt, char tipo, int t_pieza) // Agrega un elemento al final de la lista de pérdidas, su parámetro // inicial es un puntero apuntando al nodo final de la lista { TListaPE2 *LAux2; if((LAux2 = (TListaPE2*) malloc(sizeof(TListaPE2))) == NULL) nomemory("Laux2 en app2_agregalistap_g"); #ifdef _DEBUG_MALLOC_ printf("Malloc, App2_g.c, 35, LAux2, %d\n", sizeof(TListaPE2)); #endif LAux2->ancho = anc; LAux2->alto = alt; LAux2->xini = x; LAux2->yini = y; LAux2->tipo = tipo; // 'E'= Pérdida Externa,'P'=Pérdida Interna, 'G'=Ganacia LAux2->pieza = t_pieza; // t_pieza = 0 => Identifica pérdida, LAux2->prox = LPer2; // t_pieza > 0 => Id tipo de pieza con orientación normal de la pieza, LPer2 = LAux2; // t_pieza < 0 => Id tipo de pieza orientación invertida de la pieza. TotalPie++; // Incrementa el número de piezas (ganancias + pérdidas) totales. }//End app2_agregalistap
/* Routine to calculate the matrix of expected information * from the first derivatives. Returns pointer to matrix*/ void expectation(unsigned int e,double factor,int factor_flag, struct treenode *tree, struct treenode *tree2){ extern double **expect; extern double **var; extern double **var2; int a,b,d=0; unsigned int c; extern int branches; extern int nodecount; extern int mode; extern int individual; extern int is_kappa; extern int interesting_branches[]; extern int nodecount; double **matrix; double **matrix2; double temp; /* If we are using HKY85, we need a bit more memory for the * derivative WRT kappa*/ if(ISMODE(HKY) && NOTMODE(NOKAPPA)) is_kappa=1; /* Zero the relevant arrays.*/ for(a=0;a<branches+is_kappa;a++) for(b=0;b<branches+is_kappa;b++){ expect[a][b]=0; } if(ISMODE(VARIANCE)){ d=branches+is_kappa; if(ISMODE(ROOTED)) d=nodecount+((ISMODE(NODEASROOT))?1:2)+is_kappa; for(a=0;a<d;a++) for(b=0;b<d;b++) var[a][b]=0; } /* Get array to do all our intermediate calculations in*/ matrix=calloc(branches+1+is_kappa,sizeof(double *)); if(matrix==NULL) nomemory(); for(a=0;a<(branches+1+is_kappa);a++){ matrix[a]=calloc(branches+1+is_kappa,sizeof(double)); if(matrix[a]==NULL) nomemory(); } matrix2=calloc(branches+1+is_kappa,sizeof(double *)); if(matrix2==NULL) nomemory(); for(a=0;a<(branches+1+is_kappa);a++){ matrix2[a]=calloc(branches+1+is_kappa,sizeof(double)); if(matrix2[a]==NULL) nomemory(); } is_kappa=0; /* If we want information about one parameter only and * are not in a rooted tree, only calculate that * information*/ if(ISMODE(INDIVIDUAL) && individual==1 && NOTMODE(ROOTED)){ for(c=0;c<e;c++){ calcllhs(tree,tree2,c,matrix); /* If we are sampling then we have to take into account the * partial second derivatives. * Also must divide by the probability since we are sampling rather than * calculating the expectation*/ temp=evaluate_information(matrix,interesting_branches[0],interesting_branches[0]); expect[interesting_branches[0]][interesting_branches[0]]+=temp; if(ISMODE(VARIANCE)){ temp*=temp/matrix[branches][branches]; if(ISMODE(BOOTSTRAP)) temp*=matrix[branches][branches]; var[interesting_branches[0]][interesting_branches[0]]+=temp; } /* If we are using HKY85 model and wish information about kappa*/ if(ISMODE(HKY) && NOTMODE(NOKAPPA)){ temp=evaluate_information(matrix,branches+1,branches+1); expect[branches][branches]+=temp; if(ISMODE(VARIANCE)){ temp*=temp/matrix[branches][branches]; if(ISMODE(BOOTSTRAP)) temp*=matrix[branches][branches]; var[branches][branches]+=temp; } } } /* If we are sampling for the expected information, then we * must divide by the number of samples*/ if(ISMODE(BOOTSTRAP)){ expect[interesting_branches[0]][interesting_branches[0]]/=e; if(ISMODE(VARIANCE)) var[interesting_branches[0]][interesting_branches[0]]/=e; /* Do same if we are sampling for Kappa*/ if(ISMODE(HKY) && NOTMODE(NOKAPPA)){ expect[branches][branches]/=e; if(ISMODE(VARIANCE)) var[branches][branches]/=e; } } } else{ /* Need to calculate entire expectation matrix*/ for(c=0;c<e;c++){ calcllhs(tree,tree2,c,matrix); for(a=0;a<branches;a++) for(b=0;b<(a+1);b++){ /* Expectation matrix is symmetric */ /* If we are sampling then we have to take into account the * second order partial derivatives. * Also must divide by the probability since we are sampling * rather than calculating the expectation*/ matrix2[a][b]=evaluate_information(matrix,a,b); expect[a][b]+=matrix2[a][b]; matrix2[b][a]=matrix2[a][b]; } if(ISMODE(HKY) && NOTMODE(NOKAPPA)){ matrix2[branches][branches]=evaluate_information(matrix,branches+1,branches+1); expect[branches][branches]+=matrix2[branches][branches]; is_kappa=1; } /* If we want the variance of the expected information to be * calculated*/ if(ISMODE(VARIANCE)){ /* Rooted case, we must convert the information just calculated * the rooted form.*/ if(ISMODE(ROOTED)){ planttree(matrix2,var2); for(a=0;a<nodecount+((ISMODE(NODEASROOT))?1:2)+is_kappa;a++) for(b=0;b<nodecount+((ISMODE(NODEASROOT))?1:2)+is_kappa;b++){ temp=var2[a][b]*var2[a][b]/matrix[branches][branches]; if(ISMODE(BOOTSTRAP)) temp*=matrix[branches][branches]; var[a][b]+=temp; } } /* Or the far easier unrooted form - Look, no matrix * multiplication!*/ else{ for(a=0;a<branches+is_kappa;a++) for(b=0;b<branches+is_kappa;b++){ temp=matrix2[a][b]*matrix2[a][b]/matrix[branches][branches]; if(ISMODE(BOOTSTRAP)) temp*=matrix[branches][branches]; var[a][b]+=temp; } } } is_kappa=0; } if(ISMODE(HKY) && NOTMODE(NOKAPPA)) is_kappa=1; /* If we are sampling for the expected information, then we must * divide by the number of samples*/ if(ISMODE(BOOTSTRAP)){ for(a=0;a<branches+is_kappa;a++) for(b=0;b<(a+1);b++) expect[a][b]/=e; if(ISMODE(VARIANCE)) for(a=0;a<d;a++) for(b=0;b<d;b++) var[a][b]/=e; } } /* Exploit symmetry*/ for(a=0;a<branches+is_kappa;a++) for(b=0;b<(a+1);b++){ expect[b][a]=expect[a][b]; } /* Scale the tree.*/ scale_tree(factor_flag,factor,expect,branches); /* We also need to scaling the variance matrix, * the scaling has twice the effect on the variance matrix * since it is, in effect, an expectation squared*/ if(ISMODE(VARIANCE)){ a=branches; if(ISMODE(ROOTED)) a=nodecount+((ISMODE(NODEASROOT))?1:2); scale_tree(factor_flag,factor,var,a); scale_tree(factor_flag,factor,var,a); } for(a=0;a<(branches+1+is_kappa);a++){ free(matrix[a]); free(matrix2[a]); } free(matrix); free(matrix2); is_kappa=0; }
void initmalloc(void) // Localiza memoria para estructuras de datos globales { unsigned nbytes; int j; // Memoria para nueva y antigua poblacin de individuos nbytes = popsize*sizeof(struct individual); if((oldpop = (struct individual *) malloc(nbytes)) == NULL) nomemory("oldpop"); #ifdef _DEBUG_MALLOC_ printf("Malloc, memory.c, 29, oldpop, %d\n", nbytes); #endif if((newpop = (struct individual *) malloc(nbytes)) == NULL) nomemory("newpop"); #ifdef _DEBUG_MALLOC_ printf("Malloc, memory.c, 31, newpop, %d\n", nbytes); #endif // Memoria para cromosoma string de la población nbytes = chromsize*sizeof(unsigned); for(j = 0; j < popsize; j++) { if((oldpop[j].chrom = (unsigned *) malloc(nbytes)) == NULL) nomemory("oldpop chromosome string"); #ifdef _DEBUG_MALLOC_ printf("Malloc, memory.c, 37, oldpop[j].chrom, %d\n", nbytes); #endif if((newpop[j].chrom = (unsigned *) malloc(nbytes)) == NULL) nomemory("newpop chromosome string"); #ifdef _DEBUG_MALLOC_ printf("Malloc, memory.c, 39, newpop[j].chrom, %d\n", nbytes); #endif }//End for if((bestfit.chrom = (unsigned *) malloc(nbytes)) == NULL) nomemory("bestfit chromosome string"); #ifdef _DEBUG_MALLOC_ printf("Malloc, memory.c, 42, bestfit.chrom, %d\n", nbytes); #endif if((indcross.chrom = (unsigned *) malloc(nbytes)) == NULL) nomemory("indcross chromosome string"); #ifdef _DEBUG_MALLOC_ printf("Malloc, memory.c, 44, indcross.chrom, %d\n", nbytes); #endif // Memoria para cromosoma mutación de la población nbytes = chmutsize*sizeof(unsigned); for(j = 0; j < popsize; j++) { if((oldpop[j].chmut = (unsigned *) malloc(nbytes)) == NULL) nomemory("oldpop chromosome mutation"); #ifdef _DEBUG_MALLOC_ printf("Malloc, memory.c, 50, oldpop[j].chmut, %d\n", nbytes); #endif if((newpop[j].chmut = (unsigned *) malloc(nbytes)) == NULL) nomemory("newpop chromosome mutation"); #ifdef _DEBUG_MALLOC_ printf("Malloc, memory.c, 52,newpop[j].chmut, %d\n", nbytes); #endif }//End for if((bestfit.chmut = (unsigned *) malloc(nbytes)) == NULL) nomemory("bestfit chromosome mutation"); #ifdef _DEBUG_MALLOC_ printf("Malloc, memory.c, 55, bestfit.chmut, %d\n", nbytes); #endif if((indcross.chmut = (unsigned *) malloc(nbytes)) == NULL) nomemory("bestfit chromosome mutation"); #ifdef _DEBUG_MALLOC_ printf("Malloc, memory.c, 57, indcross.chmut, %d\n", nbytes); #endif // Memoria para cromosoma Lista de la población nbytes = chlistasize*sizeof(unsigned short); for(j = 0; j < popsize; j++) { if((oldpop[j].pusListaPiezas = (unsigned short *) malloc(nbytes)) == NULL) nomemory("oldpop chromosome Lista"); #ifdef _DEBUG_MALLOC_ printf("Malloc, memory.c, 91, oldpop[j].pusListaPiezas, %d\n", nbytes); #endif if((newpop[j].pusListaPiezas = (unsigned short *) malloc(nbytes)) == NULL) nomemory("newpop chromosome Lista"); #ifdef _DEBUG_MALLOC_ printf("Malloc, memory.c, 98,newpop[j].pusListaPiezas, %d\n", nbytes); #endif }//End for if((bestfit.pusListaPiezas = (unsigned short *) malloc(nbytes)) == NULL) nomemory("bestfit chromosome Lista"); #ifdef _DEBUG_MALLOC_ printf("Malloc, memory.c, 105, bestfit.pusListaPiezas, %d\n", nbytes); #endif if((indcross.pusListaPiezas = (unsigned short *) malloc(nbytes)) == NULL) nomemory("bestfit chromosome Lista"); #ifdef _DEBUG_MALLOC_ printf("Malloc, memory.c, 110, indcross.pusListaPiezas, %d\n", nbytes); #endif }//End initmalloc
int app2_leearchivo_g(char *nombrearchivo) { FILE *fp; int i,num,alt,anc,lim,id=1, lala, lele; char nombre_archivo[100]; sprintf(nombre_archivo, "%s%s", ruta_instancias, nombrearchivo); if((fp = fopen(nombre_archivo,"r"))== NULL){ fprintf(outfp,"error al leer archivo %s\n",nombrearchivo); return 0; } //Inicialización de variables globales NumPie = 0; cantidadtipospiezas = 0; //Lee Ancho y Largo de la Lámina fscanf(fp,"%d %d %d %d",&AnchoPl,&AltoPl,&lala,&lele); //Lee cantidad de tipos de piezas del problema fscanf(fp,"%d",&num); //Solicita memoria para piezasdistintas if((piezasdistintas = (TNodoAP*) malloc((num+1)*sizeof(TNodoAP))) == NULL){ nomemory("piezasdistintas en app_lecturaarchivo_g"); #ifdef _DEBUG_MALLOC_ printf("Malloc, App_g.c, 238, piezasdistintas, %d\n", (num+1)*sizeof(TNodoAP)); #endif return 0; } for(i=1;i<=num;i++) { // Lee ancho, alto y restricciones para cada tipo de pieza fscanf(fp,"%d %d %d",&anc,&alt,&lim); piezasdistintas[i].ancho = anc; piezasdistintas[i].alto = alt; piezasdistintas[i].numero = id; piezasdistintas[i].cantidadpiezas = lim; //Incremento id++ si quiero que sólo cada tipo pieza tenga id distinto id++; NumPie=NumPie+lim; }//End for fclose(fp); //Cierra archivo del problema //Establece la cantidad máxima de tipos de piezas distintos del problema id--; cantidadtipospiezas=id; if(NumPie == 0) return 0; largo_cromosoma = bit_reservados_g + NumPie; //Define el largo del cromosoma fitness_inicial = (float) (AltoPl * AnchoPl); //Obtiene el fitness_inicial arreglo_ocupado_g = (int *) malloc(NumPie * sizeof(int)); //en este arreglo se guarda si la pieza fue ocupada o no arreglo_orden_g = (int *) malloc(NumPie * sizeof(int)); //arreglo que guarda el numero de la pieza que es ingresada en la posicion i arreglo_rotar_g = (int *) malloc(NumPie * sizeof(int)); //arreglo que indica si la pieza i debe ir rotada o no // Establece valor en variables utilizadas en función evaluación peso_func_obj = 0.85;// Uso en función evaluación - Factor de la pérdida peso_uni = 0.15;// Uso en función evaluación - Factor unificación de pérdidas peso_perdida = 1.0; //0.6; /*Factor de la componente perdida*/ peso_distancia = 0.2; //0.2; /*Factor de la componente distancia*/ peso_digregacion = 1.0; //0.2; /*Factor de la componente digregacion*/ app2_ordena_piezas_problema_g(); return -1; }//End app_leearchivo_g
void app2_objfunc_g(struct individual *critter) // Función Objetivo, transforma el string cromosoma en un arreglo de piezas { unsigned mask = 1, tp, rt, bitpos, dir, salto, go = 1, m, b; int j, k, stop, i, ini, vueltas = 0, pIni = 0, valPos, nAsig = 0; int chrom[NumPie]; TNodoAP *piezaschromo; // variable que apunta a todas las piezas del cromosoma generado if ((piezaschromo = (TNodoAP*) malloc(NumPie * sizeof (TNodoAP))) == NULL) nomemory("piezaschromo en objfunc"); #ifdef _DEBUG_MALLOC_ printf("Malloc, App_g.c, 440, piezaschromo, %d\n", NumPie * sizeof (TNodoAP)); #endif for(i=0; i<NumPie; i++) { arreglo_orden_g[i] = -1; arreglo_ocupado_g[i] = 0; chrom[i] = 0; arreglo_rotar_g[i] = 0; } for (i = 0; i < chromsize; i++) { if (i == (chromsize - 1)) //ultimo bloque stop = lchrom - (i * UINTSIZE); else stop = UINTSIZE; tp = critter->chrom[i]; rt = critter->chmut[i]; for (j = 0; j < stop; j++) { bitpos = j + UINTSIZE*i; if((i==0 && j >=bit_reservados_g) || i>0) { /* * Extrae segmento del cromosoma correspondiente a las piezas */ if (tp & mask) chrom[bitpos - bit_reservados_g] = 1; else chrom[bitpos - bit_reservados_g] = 0; /* printf("%i ", chrom[bitpos - bit_reservados_g]); */ /* * Extrae segmento del cromosoma correspondiente a la orientacion de la pieza */ if (rt & mask) arreglo_rotar_g[bitpos - bit_reservados_g] = 1; //Rotada else arreglo_rotar_g[bitpos - bit_reservados_g] = 0; //No rotada } tp = tp >> 1; rt = rt >> 1; } } /* printf("\n"); */ /* * ini: Valor que se considera primero, 0 o 1, al recorrer el cromosoma */ ini = 1; /* * dir: Direccion inicial en que se recorre el cromosoma * 0: der -> izq * 1: izq -> der */ tp = critter->chrom[0]; dir = (tp & mask)?1:0; //Obtiene el valor del salto para recorrer el cromosoma salto = 1; for(i=0; i<3; i++) { tp = tp >> 1; for(b = 1, m = 2; m > i; m--) { b *= 2;} if(tp & mask) salto = salto + b; } vueltas = 0; while(go) { //mientras queden piezas por ordenar if(dir == 1) {//izq->der pIni = 0; //posicion inicial while(arreglo_ocupado_g[pIni] != 0) { //si ya se ordeno la pieza pasa a la de la derecha pIni++; } for(i=pIni; i<NumPie; i = i+salto) { //desde la posicion inicial hasta el final, con (i + salto) como valor de incremento if(arreglo_ocupado_g[i] == 0) { // si no ha sido agregado valPos = chrom[i]; //obtiene el valor en esa posicion arreglo_ocupado_g[i] = 1; //se marca como leida if(valPos==ini) { //si es igual al valor buscado se agrega al listado de piezas ordenado arreglo_orden_g[nAsig] = i; //se agrega al listado de piezas ordenado if(arreglo_rotar_g[i]==1) { piezaschromo[nAsig].ancho = piezasproblema[i].alto; piezaschromo[nAsig].alto = piezasproblema[i].ancho; } else { piezaschromo[nAsig].alto = piezasproblema[i].alto; piezaschromo[nAsig].ancho = piezasproblema[i].ancho; } } else { piezaschromo[nAsig].ancho = 0; piezaschromo[nAsig].alto = 0; piezaschromo[nAsig].numero = 0; piezaschromo[nAsig].cantidadpiezas = 1; } nAsig++; if(nAsig == NumPie) go = 0; //si se ordenaron todas las piezas termina } } } else {//der->izq pIni = NumPie-1; //se ubica en la ultima posicion del string while(arreglo_ocupado_g[pIni] != 0) { //si ya se ordeno la pieza pasa a la de la izquierda pIni--; } for(i=pIni; i>=0; i = i-salto) { //desde la posicion inicial hasta el inicio del string, con (i + salto) como valor de retroceso if(arreglo_ocupado_g[i] == 0) { // si no ha sido agregado valPos = chrom[i]; //obtiene el valor en esa posicion arreglo_ocupado_g[i] = 1; //se marca como leida if(valPos==ini) { //si es igual al valor buscado se agrega al listado de piezas ordenado arreglo_orden_g[nAsig] = i; //se agrega al listado de piezas ordenado if(arreglo_rotar_g[i]==1) { piezaschromo[nAsig].ancho = piezasproblema[i].alto; piezaschromo[nAsig].alto = piezasproblema[i].ancho; } else { piezaschromo[nAsig].alto = piezasproblema[i].alto; piezaschromo[nAsig].ancho = piezasproblema[i].ancho; } piezaschromo[nAsig].numero = piezasproblema[i].numero; piezaschromo[nAsig].cantidadpiezas = 1; } else { piezaschromo[nAsig].ancho = 0; piezaschromo[nAsig].alto = 0; piezaschromo[nAsig].numero = 0; piezaschromo[nAsig].cantidadpiezas = 1; } nAsig++; if(nAsig == NumPie) go = 0; } } } vueltas++; dir = (dir==0)?1:0; //se cambia la direccion en que se recorre el string /* if(vueltas%2 == 0) ini = (ini==0)?1:0; //si ya se dio una vuelta completa, entonces se invierte el valor a buscar */ } /* for (k = 0; k < chromsize; k++) { if (k == (chromsize - 1)) //ultima stop = lchrom - (k * UINTSIZE); else stop = UINTSIZE; tp = critter->chrom[k]; rt = critter->chmut[k]; for (j = 0; j < stop; j++) { bitpos = j + UINTSIZE*k; // Entra al if si el bit actual es 1 if (tp & mask) { //Asigna pieza desde arreglo piezasproblema if (rt & mask) { // Efecta rotacin de piezas piezaschromo[bitpos].ancho = piezasproblema[bitpos].alto; piezaschromo[bitpos].alto = piezasproblema[bitpos].ancho; } else { // No efectua rotacion de piezas piezaschromo[bitpos].ancho = piezasproblema[bitpos].ancho; piezaschromo[bitpos].alto = piezasproblema[bitpos].alto; }//End else piezaschromo[bitpos].numero = piezasproblema[bitpos].numero; piezaschromo[bitpos].cantidadpiezas = 1; } else { //Asigna solo ceros => pieza no se considera piezaschromo[bitpos].ancho = 0; piezaschromo[bitpos].alto = 0; piezaschromo[bitpos].numero = 0; piezaschromo[bitpos].cantidadpiezas = 1; }//End else tp = tp >> 1; rt = rt >> 1; }//End for }//End for */ /* critter->PEval = app2_funceval_g(piezaschromo, 0); critter->fitness = (float) critter->PEval.perdida; */ free(piezaschromo); #ifdef _DEBUG_MALLOC_ printf("Free, app_g.c, 512, piezaschromo\n"); #endif }//End app2_objfunc_g
/* Code to read data from the open file and fill out all * the information for one node. Calls itself recursively * when it meets the start of another node - creating * the memory space first.*/ void makenode(FILE *fp,struct treenode *node_p,int flag){ char l[16],m[16]; char c; char *string; int a, n; struct treenode *cnode; extern int nodecount; extern int leaves; extern struct treenode *leaf[]; extern struct treenode *branch[]; extern int branches; extern int root; extern int individual; extern int mode; extern int interesting_branches[]; n=flag; c=' '; /* Initialise c, so it is not ')'*/ /* Read branch from file and recurse down it until we reach the * end, creating the tree as we go*/ while(c!=')'){ /* Until this branch ends {file format has ')'}*/ c=getnextc(fp); /* Get memory*/ cnode=malloc(sizeof(struct treenode)); if(cnode==NULL) nomemory(); if(c=='('){ /* Check if new node is attached to current one*/ makenode(fp,cnode,1); /* and call recursively.*/ nodecount++; c='0'; } CHILD(node)=cnode; if(c=='0'){ /* Think of suitable name for internal node*/ string=strcpy(m,"Node-"); string=itotext(nodecount,l); string=strcat(m,l); string=strcpy(CHILD(node)->name,m); c=getnextc(fp); } else{ /* Or read name from the file*/ l[0]=c; a=1; while((c=getnextc(fp))!=':' && c!='(' && c!=')' && c!='*') if(a<15) l[a++]=c; l[a]='\0'; sscanf(l,"%s",CHILD(node)->name); leaf[leaves]=CHILD(node); leaves++; for(a=1;a<DOODAH;a++) CHILD(node)->node[a]=NULL; } a=0; if(c!=':' && c!='*'){ /* Be pedantic about file format*/ printf("Error in file format %c - can't find length\n*Plink*\n",c); exit(2); } /* If we want information about this branch only, set the flag*/ if(c=='*'){ if(NOTMODE(INDIVIDUAL)) mode+=INDIVIDUAL; interesting_branches[individual++]=branches; } /* Read in length of branch to new node*/ while((c=getnextc(fp))!=',' && c!='R' && c!='r' && c!='(' && c!=')') l[a++]=c; l[a]='\0'; sscanf(l,"%le",&CHILD(length)); /* Add parent to node just created * and also save length, since memory has been set aside * and the code becomes less obscure*/ PARENT(length)=CHILD(length); PARENT(node)=node_p; if(c=='R' || c=='r'){ root=branches; mode+=ROOTED; if(c=='r') /* If the root is an actual node, rather than a*/ mode+=NODEASROOT;/* branch then flag*/ c=getnextc(fp); } CHILD(node)->bnum = branches; branch[branches++]=CHILD(node); n++; } /* Blank out the remaining pointers, so they aren't * checked at a later date*/ a=n; for(n=a;n<DOODAH;n++){ CHILD(length)=-1; CHILD(node)=NULL; } }
/* Routine to take the matrix given and calculate the log- * determinant, by calling LU decomposition routine and * then multiplying down diagonals. Returns the * log-determinant calculated.*/ double * determinant(void){ int a,max,c; extern int branches; double *det; extern int mode; extern int nodecount; extern double **expect; extern double **rootedexpect; extern int individual; extern int interesting_branches[]; extern int is_kappa; double **matrix; MAT * matrix2; is_kappa=0; if(ISMODE(HKY) && NOTMODE(NOKAPPA)) is_kappa=1; matrix=expect; max=branches; if(ISMODE(ROOTED)){ /* If want rooted tree then create new*/ planttree(expect,rootedexpect); /* matrix*/ matrix=rootedexpect; max=nodecount+2; if(ISMODE(NODEASROOT)) max=nodecount+1; } if(ISMODE(MATRICES)){ /* If want intermediate matrices dumped*/ dump(matrix,max+is_kappa,"Full matrix"); } if(ISMODE(INDIVIDUAL)){ /* We want information about some, but * not all of the elements*/ if(NOTMODE(DETINDIV)){ det=calloc(individual+is_kappa,sizeof(double)); for(a=0;a<individual;a++) det[a]=matrix[interesting_branches[a]][interesting_branches[a]]; if(is_kappa==1) det[individual]=matrix[max][max]; is_kappa=0; return det; } /* Case - we want the determinate of the sub-matrix formed * by several parameters*/ /* Get memory for new matrix*/ matrix2 = m_get(individual+is_kappa,individual+is_kappa); if(NULL==matrix2){ nomemory(); } m_zero(matrix2); /* Creates the sub-matrix from the original expected information * matrix*/ for(a=0;a<individual;a++) for(c=0;c<individual;c++) matrix2->me[a][c]=matrix[interesting_branches[a]][interesting_branches[c]]; if(is_kappa==1){ matrix2->me[individual][individual]=matrix[max][max]; } max=individual; if(ISMODE(MATRICES)) dump(matrix2->me,max,"Sub-matrix to be calculated"); } else { matrix2 = m_get(max,max); if(NULL==matrix2){ nomemory(); } m_zero(matrix2); for ( a=0 ; a<max ; a++){ for ( c=0 ; c<max ; c++){ matrix2->me[a][c] = matrix[a][c]; } } } /* Perform LU decomposition on whichever matrix we've been handed*/ det=calloc(1+is_kappa,sizeof(double)); matrix2=CHfactor(matrix2); /* The determinant of the matrix is the product of * the diagonal elements of the decomposed form*/ for(a=0;a<max;a++){ det[0] += 2.0 * log(matrix2->me[a][a]); } if(is_kappa==1){ det[1] = 2.0 * log(matrix2->me[max][max]); } M_FREE(matrix2); return det; }