Code indexing in gitaly is broken and leads to code not being visible to the user. We work on the issue with highest priority.

Skip to content
Snippets Groups Projects
Commit 68bf1198 authored by gsell's avatar gsell
Browse files

standalone nsga2 removed

parent d447b22b
No related branches found
No related tags found
No related merge requests found
add_subdirectory( wfgHypervolume )
add_subdirectory( nsga2 )
add_executable(nsga2 nsga2.c nsga2_functions.c nsga2_io.c)
target_link_libraries( nsga2 "-lm")
alpha 20
mu 10
lambda 10
dim 2
/*========================================================================
PISA (www.tik.ee.ethz.ch/pisa/)
========================================================================
Computer Engineering (TIK)
ETH Zurich
========================================================================
NSGA2
Implementation in C for the selector side.
Implements Petri net.
file: nsga2.c
author: Marco Laumanns, laumanns@tik.ee.ethz.ch
revision by: Stefan Bleuler, bleuler@tik.ee.ethz.ch
last change: $date$
========================================================================
*/
/* CAUTION: <unistd.h> is not standard C
It is used only for sleep() and usleep() in wait().
In Windows use Sleep() in <windows.h> or implement busy waiting.
*/
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include "nsga2.h"
#ifdef PISA_UNIX
#include <unistd.h>
#endif
#ifdef PISA_WIN
#include <windows.h>
#endif
/*------------------------------| main() |-------------------------------*/
int main(int argc, char* argv[])
{
/* command line parameters */
char paramfile[FILE_NAME_LENGTH]; /* file with local parameters */
char filenamebase[FILE_NAME_LENGTH]; /* filename base,
e.g., "dir/test." */
double poll = 1.0; /* polling interval in seconds */
/* other variables */
int state = -1;
char *statefile;
int result;
/* reading command line parameters */
if (argc != 4)
PISA_ERROR("Selector: wrong number of arguments");
sscanf(argv[1], "%s", paramfile);
sscanf(argv[2], "%s", filenamebase);
sscanf(argv[3], "%lf", &poll);
/* generate name of statefile */
asprintf(&statefile, "%ssta", filenamebase);
/* main loop */
while (state != 6) /* stop state for selector */
/* Caution: if reading of the statefile fails
(e.g. no permission) this is an infinite loop */
{
state = read_flag(statefile);
if (state == 1) /* inital selection */
{
initialize(paramfile, filenamebase);
result = read_ini(); /* read ini file */
if (result == 0) /* reading ini file successful */
{
select_initial(); /* do selection */
write_arc(); /* write arc file (all individuals
that could ever be used again) */
write_sel(); /* write sel file */
state = 2;
write_flag(statefile, state);
} /* else don't do anything and wait again */
}
else if (state == 3) /* selection */
{
if(check_arc() == 0 && check_sel() == 0)
{
result = read_var(); /* read var file */
if (result == 0) /*reading var file successful */
{
select_normal(); /* do selection */
write_arc(); /* write arc file (all individuals
that could ever be used again) */
write_sel(); /* write sel file */
state = 2;
write_flag(statefile, state);
} /* else don't do anything and wait again */
else
printf("read_var failed\n");
} /* else don't do anything and wait again */
}
else if (state == 5) /* variator just terminated,
here you can do what you want */
{
state = 6; /* e.g., terminate too */
write_flag(statefile, state);
}
else if (state == 9) /* variator ready for reset,
here you can do what you want */
{
state = 10; /* e.g., get ready for reset too */
write_flag(statefile, state);
}
else if (state == 10) /* reset */
{
free_memory();
state = 11;
write_flag(statefile, state);
}
else /* state == -1 (reading failed) or state concerns variator */
{
nsga_wait(poll);
}
} /* state == 6 (stop) */
free_memory();
state = 7;
write_flag(statefile, state);
return (0);
}
/*--------------------| functions for control flow |---------------------*/
void write_flag(char* filename, int flag)
/* Write the state flag to given file. */
{
FILE *fp;
assert(0 <= flag && flag <= 11);
fp = fopen(filename, "w");
assert(fp != NULL);
fprintf(fp, "%d", flag);
fclose(fp);
}
int read_flag(char* filename)
/* Read state flag from given file. */
{
int result;
int flag = -1;
FILE *fp;
fp = fopen(filename, "r");
if (fp != NULL)
{
result = fscanf(fp, "%d", &flag);
fclose(fp);
if (result == 1) /* excatly one element read */
{
if (flag < 0 || flag > 11)
PISA_ERROR("Selector: Invalid state read from file.");
}
}
return (flag);
}
void nsga_wait(double sec)
/* Makes the calling process sleep. */
/* pre: sec >= 0.01 */
{
#ifdef PISA_UNIX
unsigned int int_sec;
unsigned int usec;
assert(sec > 0);
int_sec = (unsigned int) floor(sec);
usec = (unsigned int) floor((sec - floor(sec)) * 1e6);
/* split it up, usleep can fail if argument greater than 1e6 */
/* two asserts to make sure your file server doesn't break down */
assert(!((int_sec == 0) && (usec == 0))); /* should never be 0 */
assert((int_sec * 1e6) + usec >= 10000); /* you might change this one
if you know what you are
doing */
sleep(int_sec);
usleep(usec);
#endif
#ifdef PISA_WIN
unsigned int msec;
assert(sec > 0);
msec = (unsigned int) floor(sec * 1e3);
assert(msec >= 10); /* making sure we are really sleeping for some time*/
Sleep(msec);
#endif
}
/*========================================================================
PISA (www.tik.ee.ethz.ch/pisa/)
========================================================================
Computer Engineering (TIK)
ETH Zurich
========================================================================
NSGA2
Implementation in C for the selector side.
Header file.
file: nsga2.h
author: Marco Laumanns, laumanns@tik.ee.ethz.ch
revision by: Stefan Bleuler, bleuler@tik.ee.ethz.ch
last change: $date$
========================================================================
*/
#ifndef NSGA2_H
#define NSGA2_H
/*-----------------------| specify Operating System |------------------*/
/* necessary for wait() */
/* #define PISA_WIN */
#define PISA_UNIX
/*----------------------------| macro |----------------------------------*/
#define PISA_ERROR(x) fprintf(stderr, "\nError: " x "\n"), fflush(stderr), exit(EXIT_FAILURE)
/*---------------------------| constants |-------------------------------*/
#define FILE_NAME_LENGTH 128 /* maximal length of filenames */
#define CFG_ENTRY_LENGTH 128 /* maximal length of entries in cfg file */
#define PISA_MAXDOUBLE 1E99 /* Internal maximal value for double */
/*----------------------------| structs |--------------------------------*/
typedef struct ind_st /* an individual */
{
int index;
double *f; /* objective vector */
double fitness;
} ind;
typedef struct pop_st /* a population */
{
int size;
int maxsize;
ind **ind_array;
} pop;
/*-------------| functions for control flow (in nsga2.c) |------------*/
void write_flag(char *filename, int flag);
int read_flag(char *filename);
void nsga_wait(double sec);
/*---------| initialization function (in nsga2_functions.c) |---------*/
void initialize(char *paramfile, char *filenamebase);
/*--------| memory allocation functions (in nsga2_functions.c) |------*/
void* chk_malloc(size_t size);
pop* create_pop(int size, int dim);
ind* create_ind(int dim);
void free_memory(void);
void free_pop(pop *pp);
void complete_free_pop(pop *pp);
void free_ind(ind *p_ind);
/*-----| functions implementing the selection (nsga2_functions.c) |---*/
void selection();
void mergeOffspring();
void calcFitnesses();
void calcDistances();
int getNN(int index, int k);
double getNNd(int index, int k);
void environmentalSelection();
void truncate_nondominated();
void truncate_dominated();
void matingSelection();
void select_initial();
void select_normal();
int dominates(ind *p_ind_a, ind *p_ind_b);
int is_equal(ind *p_ind_a, ind *p_ind_b);
double calcDistance(ind *p_ind_a, ind *p_ind_b);
int irand(int range);
/*--------------------| data exchange functions |------------------------*/
/* in nsga2_functions.c */
int read_ini(void);
int read_var(void);
void write_sel(void);
void write_arc(void);
int check_sel(void);
int check_arc(void);
/* in nsga2_io.c */
int read_pop(char *filename, pop *pp, int size, int dim);
void write_pop(char *filename, pop *pp, int size);
int check_file(char *filename);
#endif /* NSGA2_H */
========================================================================
PISA (www.tik.ee.ethz.ch/pisa/)
========================================================================
Computer Engineering (TIK)
ETH Zurich
========================================================================
NSGA2 - Nondominated Sorting GA II
Implementation in C for the selector side.
Documentation
file: nsga2_documentation.txt
author: Marco Laumanns, laumanns@tik.ee.ethz.ch
last change: $date$
========================================================================
The Optimizer
=============
NSGA2 in an elitist multiobjective evolutionary algorithm and has been
proposed by Prof. Kalyanmoy Deb at the KanGAL. Here, we present a
PISA-implementation of the algorithm based on the description in the
cited paper.
@InProceedings{DAPM2000,
author = {K. Deb and Samir Agrawal and Amrit Pratap and T. Meyarivan},
title = {A Fast Elitist Non-Dominated Sorting Genetic Algorithm for
Multi-Objective Optimization: {NSGA-II}},
booktitle = {Parallel Problem Solving from Nature -- {PPSN VI}},
pages = {849--858},
year = {2000},
editor = {Marc Schoenauer and K. Deb and G.
Rudolph and Xin Yao and Evelyne Lutton and Juan
Julian Merelo and Hans-Paul Schwefel},
address = {Berlin},
publisher = {Springer}
}
The Parameters
==============
NSGA2 uses the following values for the common parameters.
These parameters are specified in 'PISA_cfg'.
alpha (population size)
mu (number of parent individuals)
lambda (number of offspring individuals)
dim (number of objectives)
NSGA2 takes two local parameter which is given in a parameter
file. The name of this parameter file is passed to NSGA2 as command
line argument. (See 'nsga2_param.txt' for an example.)
seed (seed for the random number generator)
tournament (tournament size for mating selection)
Source Files
============
The source code for LOTZ is divided into four files:
'nsga2.h' is the header file.
'nsga2.c' contains the main function and implements the control flow.
'nsga2_io.c' implements the file i/o functions.
'nsga2_functions.c' implements all other functions including the
selection.
Additionally a Makefile, a PISA_configuration file with common
parameters and a PISA_parameter file with local parameters are
contained in the tar file.
Depending on whether you compile on Windows or on Unix (any OS having
<unistd.h>) uncomment the according '#define' in the 'spea2.h' file.
Usage
=====
Start NSGA2 with the following arguments:
nsga2 paramfile filenamebase poll
paramfile: specifies the name of the file containing the local
parameters (e.g. nsga2_param.txt)
filenamebase: specifies the name (and optionally the directory) of the
communication files. The filenames of the communication files and the
configuration file are built by appending 'sta', 'var', 'sel','ini',
'arc' and 'cfg' to the filenamebase. This gives the following names for
the 'PISA_' filenamebase:
PISA_cfg - configuration file
PISA_ini - initial population
PISA_sel - individuals selected for variation (PISA_
PISA_var - variated individuals (offspring)
PISA_arc - individuals in the archive
Caution: the filenamebase must be consistent with the name of
the configuration file and the filenamebase specified for the NSGA2
module.
poll: gives the value for the polling time in seconds (e.g. 0.5). This
polling time must be larger than 0.01 seconds.
Limitations
===========
None limitations are known so far.
Stopping and Resetting
======================
The behaviour in state 5 and 9 is not determined by the interface but
by each variator module specifically. NSGA2 behaves as follows:
state 5 (= variator terminated): set state to 6 (terminate as well).
state 9 (= variator resetted): set state to 10 (reset as well).
/*========================================================================
PISA (www.tik.ee.ethz.ch/pisa/)
========================================================================
Computer Engineering (TIK)
ETH Zurich
========================================================================
NSGA2
Implements most functions.
file: nsga2_functions.c
author: Marco Laumanns, laumanns@tik.ee.ethz.ch
revision by: Stefan Bleuler, bleuler@tik.ee.ethz.ch
last change: $date$
========================================================================
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include "nsga2.h"
/* common parameters */
int alpha; /* number of individuals in initial population */
int mu; /* number of individuals selected as parents */
int lambda; /* number of offspring individuals */
int dim; /* number of objectives */
/* local parameters from paramfile*/
int seed; /* seed for random number generator */
int tournament; /* parameter for tournament selection */
/* other variables */
char cfgfile[FILE_NAME_LENGTH]; /* 'cfg' file (common parameters) */
char inifile[FILE_NAME_LENGTH]; /* 'ini' file (initial population) */
char selfile[FILE_NAME_LENGTH]; /* 'sel' file (parents) */
char arcfile[FILE_NAME_LENGTH]; /* 'arc' file (archive) */
char varfile[FILE_NAME_LENGTH]; /* 'var' file (offspring) */
/* population containers */
pop *pp_all = NULL;
pop *pp_new = NULL;
pop *pp_sel = NULL;
/* NSGA2 internal global variables */
int *copies;
int **front;
double *dist;
/*-----------------------| initialization |------------------------------*/
void initialize(char *paramfile, char *filenamebase)
/* Performs the necessary initialization to start in state 0. */
{
FILE *fp;
int result;
char str[CFG_ENTRY_LENGTH];
#if (NDEBUG)
/*
'result' is used in assert() only. Without below statement
we get a warning if we compile with NDEBUG (assert() disabled)
*/
(void)result;
#endif
/* reading parameter file with parameters for selection */
fp = fopen(paramfile, "r");
assert(fp != NULL);
result = fscanf(fp, "%s", str);
assert(strcmp(str, "seed") == 0);
result = fscanf(fp, "%d", &seed);
result = fscanf(fp, "%s", str);
assert(strcmp(str, "tournament") == 0);
result = fscanf(fp, "%d", &tournament); /* fscanf() returns EOF
if reading fails. */
assert(result != EOF); /* no EOF, parameters correctly read */
fclose(fp);
srand(seed); /* seeding random number generator */
sprintf(varfile, "%svar", filenamebase);
sprintf(selfile, "%ssel", filenamebase);
sprintf(cfgfile, "%scfg", filenamebase);
sprintf(inifile, "%sini", filenamebase);
sprintf(arcfile, "%sarc", filenamebase);
/* reading cfg file with common configurations for both parts */
fp = fopen(cfgfile, "r");
assert(fp != NULL);
result = fscanf(fp, "%s", str);
assert(strcmp(str, "alpha") == 0);
result = fscanf(fp, "%d", &alpha);
assert(alpha > 0);
result = fscanf(fp, "%s", str);
assert(strcmp(str, "mu") == 0);
result = fscanf(fp, "%d", &mu);
assert(mu > 0);
result = fscanf(fp, "%s", str);
assert(strcmp(str, "lambda") == 0);
result = fscanf(fp, "%d", &lambda);
assert(lambda > 0);
result = fscanf(fp, "%s", str);
assert(strcmp(str, "dim") == 0);
result = fscanf(fp, "%d", &dim);
assert(result != EOF); /* no EOF, 'dim' correctly read */
assert(dim > 0);
fclose(fp);
/* create individual and archive pop */
pp_all = create_pop(alpha + lambda, dim);
pp_sel = create_pop(mu, dim);
}
/*-------------------| memory allocation functions |---------------------*/
void* chk_malloc(size_t size)
/* Wrapper function for malloc(). Checks for failed allocations. */
{
void *return_value = malloc(size);
if(return_value == NULL)
PISA_ERROR("Selector: Out of memory.");
return (return_value);
}
pop* create_pop(int maxsize, int dim)
/* Allocates memory for a population. */
{
int i;
pop *pp;
assert(dim >= 0);
assert(maxsize >= 0);
pp = (pop*) chk_malloc(sizeof(pop));
pp->size = 0;
pp->maxsize = maxsize;
pp->ind_array = (ind**) chk_malloc(maxsize * sizeof(ind*));
for (i = 0; i < maxsize; i++)
pp->ind_array[i] = NULL;
return (pp);
}
ind* create_ind(int dim)
/* Allocates memory for one individual. */
{
ind *p_ind;
assert(dim >= 0);
p_ind = (ind*) chk_malloc(sizeof(ind));
p_ind->index = -1;
p_ind->fitness = -1;
p_ind->f = (double*) chk_malloc(dim * sizeof(double));
return (p_ind);
}
void free_memory()
/* Frees all memory. */
{
free_pop(pp_sel);
complete_free_pop(pp_all);
free_pop(pp_new);
pp_sel = NULL;
pp_all = NULL;
pp_new = NULL;
}
void free_pop(pop *pp)
/* Frees memory for given population. */
{
if(pp != NULL)
{
free(pp->ind_array);
free(pp);
}
}
void complete_free_pop(pop *pp)
/* Frees memory for given population and for all individuals in the
population. */
{
int i = 0;
if (pp != NULL)
{
if(pp->ind_array != NULL)
{
for (i = 0; i < pp->size; i++)
{
if (pp->ind_array[i] != NULL)
{
free_ind(pp->ind_array[i]);
pp->ind_array[i] = NULL;
}
}
free(pp->ind_array);
}
free(pp);
}
}
void free_ind(ind *p_ind)
/* Frees memory for given individual. */
{
assert(p_ind != NULL);
free(p_ind->f);
free(p_ind);
}
/*-----------------------| selection functions|--------------------------*/
void selection()
{
int i;
int size;
/* Join offspring individuals from variator to population */
mergeOffspring();
size = pp_all->size;
/* Create internal data structures for selection process */
/* Vectors */
copies = (int*) chk_malloc(size * sizeof(int));
dist = (double*) chk_malloc(size * sizeof(double));
/* Matrices */
front = (int**) chk_malloc(size * sizeof(int*));
for (i = 0; i < size; i++)
{
front[i] = (int*) chk_malloc(size * sizeof(int));
}
/* Calculates NSGA2 fitness values for all individuals */
calcFitnesses();
/* Calculates distance cuboids */
calcDistances();
/* Performs environmental selection
(truncates 'pp_all' to size 'alpha') */
environmentalSelection();
/* Performs mating selection
(fills mating pool / offspring population pp_sel */
matingSelection();
/* Frees memory of internal data structures */
free(copies);
copies = NULL;
free(dist);
dist = NULL;
for (i = 0; i < size; i++)
{
free(front[i]);
}
free(front);
front = NULL;
return;
}
void mergeOffspring()
{
int i;
assert(pp_all->size + pp_new->size <= pp_all->maxsize);
for (i = 0; i < pp_new->size; i++)
{
pp_all->ind_array[pp_all->size + i] = pp_new->ind_array[i];
}
pp_all->size += pp_new->size;
free_pop(pp_new);
pp_new = NULL;
}
void calcFitnesses()
{
int i, j, l;
int size;
int num;
int *d;
int *f;
size = pp_all->size;
d = (int*) chk_malloc(size * sizeof(int));
f = (int*) chk_malloc(size * sizeof(int));
/* initialize fitness and strength values */
for (i = 0; i < size; i++)
{
pp_all->ind_array[i]->fitness = 0;
d[i] = 1;
f[i] = 1;
copies[i] = 0;
}
/* calculate strength values */
num = size;
for (l = 0; l < size; l++)
{
/* find next front */
for (i = 0; i < size; i++)
{
d[i] = 0;
if (f[i] != 0)
{
for (j = 0; j < i && d[i] == 0; j++)
if (f[j] != 0)
if (dominates(pp_all->ind_array[j], pp_all->ind_array[i]))
d[i] = 1;
for(j = i+1; j < size && d[i] == 0; j++)
if (f[j] != 0)
if (dominates(pp_all->ind_array[j], pp_all->ind_array[i]))
d[i] = 1;
}
}
/* extract front */
for (i = 0; i < size; i++)
{
if (f[i] != 0 && d[i] == 0)
{
pp_all->ind_array[i]->fitness = l;
f[i] = 0;
num--;
front[l][copies[l]] = i;
copies[l] += 1;
}
}
if (num == 0)
break;
}
free(d);
d = NULL;
free(f);
f = NULL;
return;
}
void calcDistances()
{
int i, j, l, d;
int size = pp_all->size;
double dmax = PISA_MAXDOUBLE / (dim + 1);
for (i = 0; i < size; i++)
{
dist[i] = 1;
}
for (l = 0; l < size; l++)
{
for (d = 0; d < dim; d++)
{
/* sort accorting to d-th objective */
for (i = 0; i < copies[l]; i++)
{
int min_index = -1;
int min = i;
for (j = i + 1; j < copies[l]; j++)
{
if (pp_all->ind_array[front[l][j]]->f[d] <
pp_all->ind_array[front[l][min]]->f[d])
min = j;
}
min_index = front[l][min];
front[l][min] = front[l][i];
front[l][i] = min_index;
}
/* add distances */
for (i = 0; i < copies[l]; i++)
{
if (i == 0 || i == copies[l] - 1)
dist[front[l][i]] += dmax;
else
{
dist[front[l][i]] +=
pp_all->ind_array[front[l][i+1]]->f[d] -
pp_all->ind_array[front[l][i-1]]->f[d];
}
}
}
}
}
void environmentalSelection()
{
int i, j;
int size = pp_all->size;
for (i = 0; i < size; i++)
{
pp_all->ind_array[i]->fitness += 1.0 / dist[i];
}
for (i = 0; i < alpha; i++)
{
ind *p_min;
int min = i;
for (j = i + 1; j < size; j++)
{
if (pp_all->ind_array[j]->fitness <
pp_all->ind_array[min]->fitness)
min = j;
}
p_min = pp_all->ind_array[min];
pp_all->ind_array[min] = pp_all->ind_array[i];
pp_all->ind_array[i] = p_min;
}
for (i = alpha; i < size; i++)
{
free_ind(pp_all->ind_array[i]);
pp_all->ind_array[i] = NULL;
}
pp_all->size = alpha;
return;
}
void matingSelection()
/* Fills mating pool 'pp_sel' */
{
int i, j;
for (i = 0; i < mu; i++)
{
int winner = irand(pp_all->size);
for (j = 1; j < tournament; j++)
{
int opponent = irand(pp_all->size);
if (pp_all->ind_array[opponent]->fitness
< pp_all->ind_array[winner]->fitness || winner == opponent)
{
winner = opponent;
}
}
pp_sel->ind_array[i] = pp_all->ind_array[winner];
}
pp_sel->size = mu;
}
void select_initial()
/* Performs initial selection. */
{
selection();
}
void select_normal()
/* Performs normal selection.*/
{
selection();
}
int dominates(ind *p_ind_a, ind *p_ind_b)
/* Determines if one individual dominates another.
Minimizing fitness values. */
{
int i;
int a_is_worse = 0;
int equal = 1;
for (i = 0; i < dim && !a_is_worse; i++)
{
a_is_worse = p_ind_a->f[i] > p_ind_b->f[i];
equal = (p_ind_a->f[i] == p_ind_b->f[i]) && equal;
}
return (!equal && !a_is_worse);
}
int is_equal(ind *p_ind_a, ind *p_ind_b)
/* Determines if two individuals are equal in all objective values.*/
{
int i;
int equal = 1;
for (i = 0; i < dim; i++)
equal = (p_ind_a->f[i] == p_ind_b->f[i]) && equal;
return (equal);
}
int irand(int range)
/* Generate a random integer. */
{
int j;
j=(int) ((double)range * (double) rand() / (RAND_MAX+1.0));
return (j);
}
/*--------------------| data exchange functions |------------------------*/
int read_ini()
{
int i;
pp_new = create_pop(alpha, dim);
for (i = 0; i < alpha; i++)
pp_new->ind_array[i] = create_ind(dim);
pp_new->size = alpha;
return (read_pop(inifile, pp_new, alpha, dim));
}
int read_var()
{
int i;
pp_new = create_pop(lambda, dim);
for (i = 0; i < lambda; i++)
pp_new->ind_array[i] = create_ind(dim);
pp_new->size = lambda;
return (read_pop(varfile, pp_new, lambda, dim));
}
void write_sel()
{
write_pop(selfile, pp_sel, mu);
}
void write_arc()
{
write_pop(arcfile, pp_all, pp_all->size);
}
int check_sel()
{
return (check_file(selfile));
}
int check_arc()
{
return (check_file(arcfile));
}
\ No newline at end of file
/*========================================================================
PISA (www.tik.ee.ethz.ch/pisa/)
========================================================================
Computer Engineering (TIK)
ETH Zurich
========================================================================
NSGA2
Implements data exchange trough files.
file: nsga2_io.c
author: Marco Laumanns, laumanns@tik.ee.ethz.ch
revision by: Stefan Bleuler, bleuler@tik.ee.ethz.ch
last change: $date$
========================================================================
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "nsga2.h"
int read_pop(char *filename, pop *pp, int size, int dim)
/* Reads individuals from file into pop */
{
int i, j;
int entries = 0;
char tag[4];
FILE *fp;
int result;
assert(dim >= 0);
assert(pp != NULL);
fp = fopen(filename, "r");
assert(fp != NULL);
result = fscanf(fp, "%d", &entries);
if (entries == 0) /* file has not been written yet */
{
return (1); /* signalling that reading failed */
}
assert(entries == size * (dim + 1));
for (j = 0; j < size; j++)
{
/* reading index of individual */
result = fscanf(fp, "%d", &(pp->ind_array[j]->index));
for (i = 0; i < dim; i++)
{
/* reading objective values of ind */
result = fscanf(fp, "%le", &(pp->ind_array[j]->f[i]));
assert(pp->ind_array[j]->f[i] >= 0);
if (result == EOF) /* file not completely written */
{
fclose(fp);
return (1); /* signalling that reading failed */
}
}
}
/* after all data elements: "END" expected */
result = fscanf(fp, "%s", tag);
if (strcmp(tag, "END") != 0)
{
fclose(fp);
return (1); /* signalling that reading failed */
}
else /* "END" ok */
{
fclose(fp);
/* delete file content if reading successful */
fp = fopen(filename, "w");
assert(fp != NULL);
fprintf(fp, "0");
fclose(fp);
return (0); /* signalling that reading was successful */
}
}
void write_pop(char* filename, pop* pp, int size)
/* Writes a pop or PISA_to a given filename. */
{
int i;
FILE *fp;
assert(0 <= size && size <= pp->size);
fp = fopen(filename, "w");
assert(fp != NULL);
fprintf(fp, "%d\n", size); /* number of elements */
for (i = 0; i < size; i++)
{
fprintf(fp, "%d\n", pp->ind_array[i]->index);
}
fprintf(fp, "END");
fclose(fp);
}
int check_file(char* filename)
{
int control_element = 1;
FILE *fp;
fp = fopen(filename, "r");
assert(fp != NULL);
if (fscanf(fp, "%d", &control_element) != 1) {
fprintf(stderr, "Couldn't read file '%s'.", filename);
}
fclose(fp);
if(0 == control_element)
return (0); /* file is ready for writing */
else
return (1); /* file is not ready for writing */
}
seed 11
tournament 2
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment