source: branches/uq/packages/optimizer/src/pgapack/gekco/pgapack/examples/c/maxint.c @ 5679

Last change on this file since 5679 was 5679, checked in by ldelgass, 9 years ago

Full merge 1.3 branch to uq branch to sync. Fixed partial subdirectory merge
by removing mergeinfo from lang/python/Rappture directory.

  • Property svn:eol-style set to native
File size: 2.2 KB
Line 
1/*
2 *  This is a test program for PGAPack.  The objective is to maximize each
3 *  allele.  The evaluation function sums all allele values.
4 */
5#include <pgapack.h>
6
7double evaluate(PGAContext *, int, int);
8int    myMutation(PGAContext *, int, int, double);
9int    GetIntegerParameter(char *query);
10
11
12int main(int argc, char **argv) {
13     PGAContext *ctx;
14     int         len, maxiter;
15
16     MPI_Init(&argc, &argv);
17
18     len     = GetIntegerParameter("String length?\n");
19     maxiter = GetIntegerParameter("How many iterations?\n");
20
21     ctx = PGACreate(&argc, argv, PGA_DATATYPE_INTEGER, len, PGA_MAXIMIZE);
22
23     PGASetRandomSeed(ctx, 1);
24     PGASetUserFunction(ctx, PGA_USERFUNCTION_MUTATION, (void *)myMutation);
25     PGASetIntegerInitPermute(ctx, 1, len);
26
27     PGASetMaxGAIterValue(ctx, maxiter);
28     PGASetNumReplaceValue(ctx, 90);
29     PGASetMutationAndCrossoverFlag(ctx, PGA_TRUE);
30     PGASetPrintOptions(ctx, PGA_REPORT_AVERAGE);
31
32     PGASetUp(ctx);
33
34     PGARun(ctx, evaluate);
35     PGADestroy(ctx);
36
37     MPI_Finalize();
38
39     return(0);
40}
41
42
43int myMutation(PGAContext *ctx, int p, int pop, double mr) {
44    int         stringlen, i, v, count;
45
46    stringlen = PGAGetStringLength(ctx);
47    count     = 0;
48
49    for (i=stringlen-1; i>=0; i--) {
50        if (PGARandomFlip(ctx, mr)) {
51            v = PGARandomInterval(ctx, 1, stringlen);
52            PGASetIntegerAllele(ctx, p, pop, i, v);
53            count++;
54        }
55    }
56    return((double)count);
57}
58
59
60
61double evaluate(PGAContext *ctx, int p, int pop) {
62     int  stringlen, i, sum;
63
64     stringlen = PGAGetStringLength(ctx);
65     sum       = 0;
66     
67     for (i=stringlen-1; i>=0; i--)
68          sum += PGAGetIntegerAllele(ctx, p, pop, i);
69
70     return((double)sum);
71}
72
73
74
75/*  Get an integer parameter from the user.  Since this is
76 *  typically a parallel program, we must only do I/O on the
77 *  "master" process -- process 0.  Once we read the parameter,
78 *  we broadcast it to all the other processes, then every
79 *  process returns the correct value.
80 */
81int GetIntegerParameter(char *query) {
82    int  rank, tmp;
83
84    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
85    if (rank == 0) {
86        printf(query);
87        scanf("%d", &tmp);
88    }
89    MPI_Bcast(&tmp, 1, MPI_INT, 0, MPI_COMM_WORLD);
90    return(tmp);
91}
92
93
94
Note: See TracBrowser for help on using the repository browser.