Commit 68bf1198 authored by gsell's avatar gsell
Browse files

standalone nsga2 removed

parent d447b22b
add_subdirectory( wfgHypervolume ) 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