OptimizeCmd.cpp 16.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include "Optimize/OptimizeCmd.h"
#include "Optimize/DVar.h"
#include "Optimize/Objective.h"
#include "Optimize/Constraint.h"
#include "Optimize/OpalSimulation.h"

#include "Attributes/Attributes.h"
#include "AbstractObjects/OpalData.h"
#include "Utilities/OpalException.h"

//#include "Utility/Inform.h"
#include "Utility/IpplInfo.h"
#include "Utility/IpplTimings.h"
#include "Track/Track.h"

#include "Pilot/Pilot.h"
#include "Util/CmdArguments.h"
#include "Util/OptPilotException.h"
#include "Util/OpalInputFileParser.h"

#include "Optimizer/EA/FixedPisaNsga2.h"
#include "Optimizer/EA/BlendCrossover.h"
#include "Optimizer/EA/IndependentBitMutation.h"

#include "Comm/CommSplitter.h"
#include "Comm/Topology/NoCommTopology.h"
#include "Comm/Splitter/ManyMasterSplit.h"
#include "Comm/MasterGraph/SocialNetworkGraph.h"

#include "Expression/Parser/function.hpp"
#include "Expression/FromFile.h"
#include "Expression/SumErrSq.h"
#include "Expression/SDDSVariable.h"
#include "Expression/RadialPeak.h"
35
#include "Expression/MaxNormRadialPeak.h"
36
#include "Expression/NumberOfPeaks.h"
37 38 39 40 41
#include "Expression/SumErrSqRadialPeak.h"
#include "Expression/ProbeVariable.h"

#include <boost/filesystem.hpp>

42 43 44 45 46
#include <map>
#include <set>
#include <string>
#include <vector>

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
extern Inform *gmsg;

namespace {
    enum {
        INPUT,
        OUTPUT,
        OUTDIR,
        OBJECTIVES,
        DVARS,
        CONSTRAINTS,
        INITIALPOPULATION,
        NUMMASTERS,
        NUMCOWORKERS,
        SELECTOR,
        DUMPDAT,
62
        DUMPFREQ,
63 64 65 66
        NUMINDGEN,
        MAXGENERATIONS,
        EPSILON,
        EXPECTEDHYPERVOL,
67
        HYPERVOLREFERENCE,
68
        CONVHVOLPROG,
69
        ONEPILOTCONVERGE,
70 71 72 73
        SOLSYNCH,
        GENEMUTATIONPROBABILITY,
        MUTATIONPROBABILITY,
        RECOMBINATIONPROBABILITY,
74
        SIMBINCROSSOVERNU,
75 76 77
        SIMTMPDIR,
        TEMPLATEDIR,
        FIELDMAPDIR,
frey_m's avatar
frey_m committed
78
        DISTDIR,
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
        SIZE
    };
}

OptimizeCmd::OptimizeCmd():
    Action(SIZE, "OPTIMIZE",
           "The \"OPTIMIZE\" command initiates optimization.") {
    itsAttr[INPUT] = Attributes::makeString
        ("INPUT", "Path to input file");
    itsAttr[OUTPUT] = Attributes::makeString
        ("OUTPUT", "Name used in output file generation");
    itsAttr[OUTDIR] = Attributes::makeString
        ("OUTDIR", "Name of directory used to store generation output files");
    itsAttr[OBJECTIVES] = Attributes::makeStringArray
        ("OBJECTIVES", "List of objectives to be used");
    itsAttr[DVARS] = Attributes::makeStringArray
        ("DVARS", "List of optimization variables to be used");
    itsAttr[CONSTRAINTS] = Attributes::makeStringArray
        ("CONSTRAINTS", "List of constraints to be used");
98
    itsAttr[INITIALPOPULATION] = Attributes::makeReal
99
        ("INITIALPOPULATION", "Size of the initial population");
100
    itsAttr[NUMMASTERS] = Attributes::makeReal
101
        ("NUM_MASTERS", "Number of master nodes");
102
    itsAttr[NUMCOWORKERS] = Attributes::makeReal
103 104 105
        ("NUM_COWORKERS", "Number processors per worker");
    itsAttr[SELECTOR] = Attributes::makeString
        ("SELECTOR", "Path of the selector (PISA only)");
106
    itsAttr[DUMPDAT] = Attributes::makeReal
107
        ("DUMP_DAT", "Dump old generation data format with frequency (PISA only)");
108 109 110
    itsAttr[DUMPFREQ] = Attributes::makeReal
        ("DUMP_FREQ", "Dump old generation data format with frequency (PISA only)");
    itsAttr[NUMINDGEN] = Attributes::makeReal
111
        ("NUM_IND_GEN", "Number of individuals in a generation (PISA only)");
112
    itsAttr[MAXGENERATIONS] = Attributes::makeReal
113
        ("MAXGENERATIONS", "Number of generations to run");
114
    itsAttr[EPSILON] = Attributes::makeReal
115
        ("EPSILON", "Tolerance of hypervolume criteria, default 0.001");
116
    itsAttr[EXPECTEDHYPERVOL] = Attributes::makeReal
117
        ("EXPECTED_HYPERVOL", "The reference hypervolume, default 0");
118 119
    itsAttr[HYPERVOLREFERENCE] = Attributes::makeRealArray
        ("HYPERVOLREFERENCE", "The reference point (real array) for the hypervolume, default empty (origin)");
120
    itsAttr[CONVHVOLPROG] = Attributes::makeReal
121
        ("CONV_HVOL_PROG", "converge if change in hypervolume is smaller, default 0");
122
    itsAttr[ONEPILOTCONVERGE] = Attributes::makeBool
123
        ("ONE_PILOT_CONVERGE", "default false");
124
    itsAttr[SOLSYNCH] = Attributes::makeReal
125
        ("SOL_SYNCH", "Solution exchange frequency, default 0");
126
    itsAttr[GENEMUTATIONPROBABILITY] = Attributes::makeReal
127
        ("GENE_MUTATION_PROBABILITY", "Mutation probability of individual gene, default: 0.5");
128
    itsAttr[MUTATIONPROBABILITY] = Attributes::makeReal
129
        ("MUTATION_PROBABILITY", "Mutation probability of genome, default: 0.5");
130
    itsAttr[RECOMBINATIONPROBABILITY] = Attributes::makeReal
131 132
        ("RECOMBINATION_PROBABILITY", "Probability for genes to recombine, default: 0.5");
    itsAttr[SIMBINCROSSOVERNU] = Attributes::makeReal
133
        ("SIMBIN_CROSSOVER_NU", "Simulated binary crossover, default: 2.0");
134 135 136 137 138 139
    itsAttr[SIMTMPDIR] = Attributes::makeString
        ("SIMTMPDIR", "Directory where simulations are run");
    itsAttr[TEMPLATEDIR] = Attributes::makeString
        ("TEMPLATEDIR", "Directory where templates are stored");
    itsAttr[FIELDMAPDIR] = Attributes::makeString
        ("FIELDMAPDIR", "Directory where field maps are stored");
frey_m's avatar
frey_m committed
140 141
    itsAttr[DISTDIR] = Attributes::makeString
        ("DISTDIR", "Directory where distributions are stored", "");
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    registerOwnership(AttributeHandler::COMMAND);
}

OptimizeCmd::OptimizeCmd(const std::string &name, OptimizeCmd *parent):
    Action(name, parent)
{ }

OptimizeCmd::~OptimizeCmd()
{ }

OptimizeCmd *OptimizeCmd::clone(const std::string &name) {
    return new OptimizeCmd(name, this);
}

void OptimizeCmd::execute() {
    namespace fs = boost::filesystem;

    auto opal = OpalData::getInstance();
    fs::path inputfile(Attributes::getString(itsAttr[INPUT]));

162 163
    std::vector<std::string> dvarsstr       = Attributes::getStringArray(itsAttr[DVARS]);
    std::vector<std::string> objectivesstr  = Attributes::getStringArray(itsAttr[OBJECTIVES]);
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    std::vector<std::string> constraintsstr = Attributes::getStringArray(itsAttr[CONSTRAINTS]);
    DVarContainer_t dvars;
    Expressions::Named_t objectives;
    Expressions::Named_t constraints;

    // Setup/Configuration
    //////////////////////////////////////////////////////////////////////////
    typedef OpalInputFileParser Input_t;
    typedef OpalSimulation Sim_t;

    typedef FixedPisaNsga2< BlendCrossover, IndependentBitMutation > Opt_t;

    typedef CommSplitter< ManyMasterSplit< NoCommTopology > > Comm_t;
    typedef SocialNetworkGraph< NoCommTopology > SolPropagationGraph_t;

    typedef Pilot<Input_t, Opt_t, Sim_t, SolPropagationGraph_t, Comm_t> pilot_t;

    // prepare function dictionary and add all available functions in
    // expressions
    functionDictionary_t funcs;
    client::function::type ff;
    ff = FromFile();
    funcs.insert(std::pair<std::string, client::function::type>
                 ("fromFile", ff));

    ff = SumErrSq();
    funcs.insert(std::pair<std::string, client::function::type>
                 ("sumErrSq", ff));

    ff = SDDSVariable();
    funcs.insert(std::pair<std::string, client::function::type>
                 ("sddsVariableAt", ff));

    ff = RadialPeak();
    funcs.insert(std::pair<std::string, client::function::type>
                 ("radialPeak", ff));

201
    ff = MaxNormRadialPeak();
frey_m's avatar
frey_m committed
202
    funcs.insert(std::pair<std::string, client::function::type>
203
                 ("maxNormRadialPeak", ff));
204 205 206 207 208
    
    ff = NumberOfPeaks();
    funcs.insert(std::pair<std::string, client::function::type>
            ("numberOfPeaks", ff));
    
209 210 211 212 213 214 215 216 217 218 219
    ff = SumErrSqRadialPeak();
    funcs.insert(std::pair<std::string, client::function::type>
                 ("sumErrSqRadialPeak", ff));

    ff = ProbeVariable();
    funcs.insert(std::pair<std::string, client::function::type>
                 ("probVariableWithID", ff));

    std::string fname = inputfile.stem().native();
    ff = sameSDDSVariable(fname);
    funcs.insert(std::pair<std::string, client::function::type>
kraus's avatar
kraus committed
220
                 ("statVariableAt", ff));
221 222 223 224 225

    //////////////////////////////////////////////////////////////////////////

    std::vector<std::string> arguments(opal->getArguments());
    std::vector<char*> argv;
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    std::map<unsigned int, std::string> argumentMapper({
            {INPUT, "inputfile"},
            {OUTPUT, "outfile"},
            {OUTDIR, "outdir"},
            {INITIALPOPULATION, "initialPopulation"},
            {NUMMASTERS, "num-masters"},
            {NUMCOWORKERS, "num-coworkers"},
            {SELECTOR, "selector"},
            {DUMPDAT, "dump-dat"},
            {DUMPFREQ, "dump-freq"},
            {NUMINDGEN, "num-ind-gen"},
            {MAXGENERATIONS, "maxGenerations"},
            {EPSILON, "epsilon"},
            {EXPECTEDHYPERVOL, "expected-hypervol"},
            {CONVHVOLPROG, "conv-hvol-prog"},
            {ONEPILOTCONVERGE, "one-pilot-converge"},
            {SOLSYNCH, "sol-synch"},
            {GENEMUTATIONPROBABILITY, "gene-mutation-probability"},
            {MUTATIONPROBABILITY, "mutation-probability"},
            {RECOMBINATIONPROBABILITY, "recombination-probability"},
            {SIMBINCROSSOVERNU, "simbin-crossover-nu"}
        });

    auto it = argumentMapper.end();
    for (unsigned int i = 0; i < SIZE; ++ i) {
        if ((it = argumentMapper.find(i)) != argumentMapper.end()) {
            std::string type = itsAttr[i].getType();
            if (type == "string") {
                if (Attributes::getString(itsAttr[i]) != "") {
                    std::string argument = "--" + (*it).second + "=" + Attributes::getString(itsAttr[i]);
                    arguments.push_back(argument);
                }
            } else if (type == "real") {
                if (itsAttr[i]) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
260 261 262 263 264 265
                    std::string val = std::to_string (Attributes::getReal(itsAttr[i]));
                    size_t last = val.find_last_not_of('0');
                    if (val[last] != '.') ++ last;
                    val.erase (last, std::string::npos );
                    std::string argument = "--" + (*it).second + "=" + val;
                    arguments.push_back(argument);
266 267 268 269 270 271 272 273 274
                }
            } else if (type == "logical") {
                if (itsAttr[i]) {
                    std::string argument = "--" + (*it).second + "=" + std::to_string(Attributes::getBool(itsAttr[i]));
                    arguments.push_back(argument);
                }
            }
        }
    }
275
    // sanity checks
276
    if (Attributes::getString(itsAttr[INPUT]) == "") {
277 278 279
        throw OpalException("OptimizeCmd::execute",
                            "The argument INPUT has to be provided");
    }
280
    if (Attributes::getReal(itsAttr[INITIALPOPULATION]) <= 0) {
281 282 283
        throw OpalException("OptimizeCmd::execute",
                            "The argument INITIALPOPULATION has to be provided");
    }
284
    if (Attributes::getReal(itsAttr[MAXGENERATIONS]) <= 0) {
285 286 287
        throw OpalException("OptimizeCmd::execute",
                            "The argument MAXGENERATIONS has to be provided");
    }
288 289 290 291 292
    if (Attributes::getRealArray(itsAttr[HYPERVOLREFERENCE]).empty() == false &&
        Attributes::getRealArray(itsAttr[HYPERVOLREFERENCE]).size()  != objectivesstr.size()) {
        throw OpalException("OptimizeCmd::execute",
                            "The hypervolume reference point should have the same dimension as the objectives");
    }
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332

    if (Attributes::getString(itsAttr[SIMTMPDIR]) != "") {
        fs::path dir(Attributes::getString(itsAttr[SIMTMPDIR]));
        if (dir.is_relative()) {
            fs::path path = fs::path(std::string(getenv("PWD")));
            path /= dir;
            dir = path;
        }

        *gmsg << dir.native() << endl;
        if (!fs::exists(dir)) {
            fs::create_directory(dir);
        }
        std::string argument = "--simtmpdir=" + dir.native();
        arguments.push_back(argument);
    }

    if (Attributes::getString(itsAttr[TEMPLATEDIR]) != "") {
        fs::path dir(Attributes::getString(itsAttr[TEMPLATEDIR]));
        if (dir.is_relative()) {
            fs::path path = fs::path(std::string(getenv("PWD")));
            path /= dir;
            dir = path;
        }

        std::string argument = "--templates=" + dir.native();
        arguments.push_back(argument);
    }

    if (Attributes::getString(itsAttr[FIELDMAPDIR]) != "") {
        fs::path dir(Attributes::getString(itsAttr[FIELDMAPDIR]));
        if (dir.is_relative()) {
            fs::path path = fs::path(std::string(getenv("PWD")));
            path /= dir;
            dir = path;
        }

        setenv("FIELDMAPS", dir.c_str(), 1);
    }

frey_m's avatar
frey_m committed
333
    if (Attributes::getString(itsAttr[DISTDIR]) != "") {
frey_m's avatar
frey_m committed
334 335 336
        fs::path dir(Attributes::getString(itsAttr[DISTDIR]));
        if (dir.is_relative()) {
            fs::path path = fs::path(std::string(getenv("PWD")));
frey_m's avatar
frey_m committed
337 338 339 340 341 342 343 344
            path /= dir;
            dir = path;
        }

        setenv("DISTRIBUTIONS", dir.c_str(), 1);
    }


345 346 347 348 349 350 351
    *gmsg << endl;
    for (size_t i = 0; i < arguments.size(); ++ i) {
        argv.push_back(const_cast<char*>(arguments[i].c_str()));
        *gmsg << arguments[i] << " ";
    }
    *gmsg << endl;

352
    std::set<std::string> vars; // check if all unique vars
353 354
    for (const std::string &name: dvarsstr) {
        Object *obj = opal->find(name);
355 356 357 358 359 360
        DVar* dvar = dynamic_cast<DVar*>(obj);
        if (dvar == nullptr) {
            throw OpalException("OptimizeCmd::execute",
                                "The design variable " + name + " is not known");

        }
361 362 363 364 365 366
        std::string var = dvar->getVariable();
        double lowerbound = dvar->getLowerBound();
        double upperbound = dvar->getUpperBound();

        DVar_t tmp = boost::make_tuple(var, lowerbound, upperbound);
        dvars.insert(namedDVar_t(name, tmp));
367 368 369 370 371
        auto ret = vars.insert(var);
        if (ret.second == false) {
            throw OpalException("OptimizeCmd::execute",
                                "There is already a design variable with the variable " + var + " defined");
        }
372
    }
373
    std::set<std::string> objExpressions; // check if all unique objective expressions
374 375
    for (const std::string &name: objectivesstr) {
        Object *obj = opal->find(name);
376 377 378 379 380 381
        Objective* objective = dynamic_cast<Objective*>(obj);
        if (objective == nullptr) {
            throw OpalException("OptimizeCmd::execute",
                                "The objective " + name + " is not known");

        }
382 383 384
        std::string expr = objective->getExpression();
        objectives.insert(Expressions::SingleNamed_t(
                   name, new Expressions::Expr_t(expr, funcs)));
385 386 387 388 389
        auto ret = objExpressions.insert(expr);
        if (ret.second == false) {
            throw OpalException("OptimizeCmd::execute",
                                "There is already a objective with the expression " + expr + " defined");
        }
390
    }
391
    std::set<std::string> constraintExpressions; // check if all unique constraint expressions
392 393
    for (const std::string &name: constraintsstr) {
        Object *obj = opal->find(name);
394 395 396 397 398 399
        Constraint* constraint = dynamic_cast<Constraint*>(obj);
        if (constraint == nullptr) {
            throw OpalException("OptimizeCmd::execute",
                                "The constraint " + name + " is not known");

        }
400 401 402
        std::string expr = constraint->getExpression();
        constraints.insert(Expressions::SingleNamed_t(
                    name, new Expressions::Expr_t(expr, funcs)));
403 404 405 406 407
        auto ret = constraintExpressions.insert(expr);
        if (ret.second == false) {
            throw OpalException("OptimizeCmd::execute",
                                "There is already a constraint with the expression " + expr + " defined");
        }
408 409 410 411 412 413 414 415 416
    }

    Inform *origGmsg = gmsg;
    gmsg = 0;
    stashEnvironment();
    try {
        CmdArguments_t args(new CmdArguments(argv.size(), &argv[0]));

        boost::shared_ptr<Comm_t>  comm(new Comm_t(args, MPI_COMM_WORLD));
417
        boost::scoped_ptr<pilot_t> pi(new pilot_t(args, comm, funcs, dvars, objectives, constraints, Attributes::getRealArray(itsAttr[HYPERVOLREFERENCE])));
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438

    } catch (OptPilotException &e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
        MPI_Abort(MPI_COMM_WORLD, -100);
    }
    popEnvironment();
    gmsg = origGmsg;
}

void OptimizeCmd::stashEnvironment() {
    Ippl::stash();
    IpplTimings::stash();
    Track::stash();
    OpalData::stashInstance();
}

void OptimizeCmd::popEnvironment() {
    Ippl::pop();
    IpplTimings::pop();
    OpalData::popInstance();
    Track::pop();
frey_m's avatar
frey_m committed
439
}