コード例 #1
0
ファイル: ActionWithVessel.cpp プロジェクト: apoma/plumed2
ActionWithVessel::ActionWithVessel(const ActionOptions&ao):
  Action(ao),
  serial(false),
  lowmem(false),
  contributorsAreUnlocked(false),
  weightHasDerivatives(false)
{
  maxderivatives=309; parse("MAXDERIVATIVES",maxderivatives);
  if( keywords.exists("SERIAL") ) parseFlag("SERIAL",serial);
  else serial=true;
  if(serial)log.printf("  doing calculation in serial\n");
  if( keywords.exists("LOWMEM") ){
     parseFlag("LOWMEM",lowmem);
     if(lowmem)log.printf("  lowering memory requirements\n");
  }
  tolerance=nl_tolerance=epsilon; 
  if( keywords.exists("TOL") ) parse("TOL",tolerance);
  if( tolerance>epsilon){
     if( keywords.exists("NL_TOL") ) parse("NL_TOL",nl_tolerance);
     if( nl_tolerance>tolerance ) error("NL_TOL must be smaller than TOL"); 
     log.printf(" Ignoring contributions less than %lf",tolerance);
     if( nl_tolerance>epsilon ) log.printf(" and ignoring quantities less than %lf inbetween neighbor list update steps\n",nl_tolerance);
     else log.printf("\n");
  }
}
コード例 #2
0
ファイル: ActionIMD.cpp プロジェクト: apoma/plumed2
IMD::IMD(const ActionOptions& ao):
  Action(ao),
  ActionAtomistic(ao),
  ActionPilot(ao),
  host("localhost"),
  port(0),
  wait(false),
  wrap(false),
  sock(NULL),
  clientsock(NULL),
  connected(false),
  transferRate(100),
  fscale(1.0)
{
  natoms=plumed.getAtoms().getNatoms();

  std::vector<AtomNumber> index(natoms);
  for(int i=0;i<natoms;i++) index[i].setIndex(i);
  requestAtoms(index);
  coord.resize(natoms*3,float(0.0));
  forces.resize(natoms*3,0.0);

  parseFlag("WAIT",wait);
  bool nowait=false;
  parseFlag("NOWAIT",nowait);
  if(nowait)wait=false;
  parseFlag("WRAP",wrap);
  parse("PORT",port);
  parse("HOST",host);
  parse("FSCALE",fscale);

  checkRead();

  log.printf("  with host %s\n",host.c_str());
  log.printf("  with port %d\n",port);
  if(wait) log.printf("  waiting for a connection\n");
  else     log.printf("  not waiting for a connection\n");
  if(wrap) log.printf("  wrapping atoms\n");
  else     log.printf("  not wrapping atoms\n");
  log.printf("  WMD forces will be scaled by %f\n",fscale);

  if(comm.Get_rank()==0){
    vmdsock_init();
    sock = vmdsock_create();
    vmdsock_bind(sock, port);
    vmdsock_listen(sock);
  }

  connect();
}
コード例 #3
0
LandmarkSelectionBase::LandmarkSelectionBase( const LandmarkSelectionOptions& lo ):
  style(lo.words[0]),
  input(lo.words),
  action(lo.action)
{
  input.erase( input.begin() );
  if( style=="ALL" ) {
    novoronoi=true;
  } else {
    parse("N",nlandmarks);
    parseFlag("NOVORONOI",novoronoi);
  }
  parseFlag("IGNORE_WEIGHTS",noweights);
}
コード例 #4
0
SecondaryStructureRMSD::SecondaryStructureRMSD(const ActionOptions&ao):
Action(ao),
ActionAtomistic(ao),
ActionWithValue(ao),
ActionWithVessel(ao),
updateFreq(0),
align_strands(false),
s_cutoff(0),
align_atom_1(0),
align_atom_2(0)
{
  parse("TYPE",alignType);
  log.printf("  distances from secondary structure elements are calculated using %s algorithm\n",alignType.c_str() );
  log<<"  Bibliography "<<plumed.cite("Pietrucci and Laio, J. Chem. Theory Comput. 5, 2197 (2009)"); log<<"\n";

  parseFlag("VERBOSE",verbose_output);
  if( keywords.exists("NL_STRIDE") ) parse("NL_STRIDE",updateFreq);
  if(updateFreq>0){ 
     firsttime=true; 
     log.printf("  Updating contributors every %d steps.\n",updateFreq);
  } else {
     firsttime=false; contributorsAreUnlocked=true;   // This will lock during first prepare step methinks
     log.printf("  Updating contributors every step.\n");
  }

  if( keywords.exists("STRANDS_CUTOFF") ){
    parse("STRANDS_CUTOFF",s_cutoff); align_strands=true;
    if( s_cutoff>0) log.printf("  ignoring contributions from strands that are more than %f apart\n",s_cutoff);
  }
}
コード例 #5
0
void ActionWithVessel::readVesselKeywords(){
  // Set maxderivatives if it is too big
  if( maxderivatives>getNumberOfDerivatives() ) maxderivatives=getNumberOfDerivatives();

  // Loop over all keywords find the vessels and create appropriate functions
  for(unsigned i=0;i<keywords.size();++i){
      std::string thiskey,input; thiskey=keywords.getKeyword(i);
      // Check if this is a key for a vessel
      if( vesselRegister().check(thiskey) ){
          plumed_assert( keywords.style(thiskey,"vessel") );
          bool dothis=false; parseFlag(thiskey,dothis);
          if(dothis) addVessel( thiskey, input );

          parse(thiskey,input);
          if(input.size()!=0){ 
                addVessel( thiskey, input );
          } else {
             for(unsigned i=1;;++i){
                if( !parseNumbered(thiskey,i,input) ) break;
                std::string ss; Tools::convert(i,ss);
                addVessel( thiskey, input, i ); 
                input.clear();
             } 
          }
      }
  }

  // Make sure all vessels have had been resized at start
  if( functions.size()>0 ) resizeFunctions();
}
コード例 #6
0
ファイル: ActionWithValue.cpp プロジェクト: JFDama/plumed2
ActionWithValue::ActionWithValue(const ActionOptions&ao):
  Action(ao),
  noderiv(true),
  numericalDerivatives(false)
{
  if( keywords.exists("NUMERICAL_DERIVATIVES") ) parseFlag("NUMERICAL_DERIVATIVES",numericalDerivatives);
  if(numericalDerivatives) log.printf("  using numerical derivatives\n");
}
コード例 #7
0
ファイル: Histogram.cpp プロジェクト: OndrejMarsalek/plumed2
Histogram::Histogram( const VesselOptions& da ):
ShortcutVessel(da)
{
  bool norm; parseFlag("NORM",norm); std::string normstr="";
  if(norm) normstr=" NORM";
  std::vector<std::string> bins; HistogramBead::generateBins( getAllInput(), "", bins );
  for(unsigned i=0;i<bins.size();++i) addVessel("BETWEEN",bins[i] + normstr);
}
コード例 #8
0
ファイル: DRMSD.cpp プロジェクト: amcadmus/plumed2
void DRMSD::read( const PDB& pdb ){
  readAtomsFromPDB( pdb );

  parseFlag("NOPBC",nopbc);  
  parse("LOWER_CUTOFF",lower,true);
  parse("UPPER_CUTOFF",upper,true);
  setBoundsOnDistances( !nopbc, lower, upper );
  setup_targets();
}
コード例 #9
0
ActionWithVessel::ActionWithVessel(const ActionOptions&ao):
  Action(ao),
  serial(false),
  lowmem(false),
  noderiv(true),
  actionIsBridged(false),
  mydata(NULL),
  contributorsAreUnlocked(false),
  weightHasDerivatives(false),
  stopwatch(*new Stopwatch),
  dertime_can_be_off(false),
  dertime(true)
{
  maxderivatives=309; parse("MAXDERIVATIVES",maxderivatives);
  if( keywords.exists("SERIAL") ) parseFlag("SERIAL",serial);
  else serial=true;
  if(serial)log.printf("  doing calculation in serial\n");
  if( keywords.exists("LOWMEM") ){
     plumed_assert( !keywords.exists("HIGHMEM") );
     parseFlag("LOWMEM",lowmem);
     if(lowmem){ 
        log.printf("  lowering memory requirements\n");
        dertime_can_be_off=true;
     }
  } 
  if( keywords.exists("HIGHMEM") ){
     plumed_assert( !keywords.exists("LOWMEM") );
     bool highmem; parseFlag("HIGHMEM",highmem);
     lowmem=!highmem;
     if(!lowmem) log.printf("  increasing the memory requirements\n");
  }
  tolerance=nl_tolerance=epsilon; 
  if( keywords.exists("TOL") ) parse("TOL",tolerance);
  if( tolerance>epsilon){
     if( keywords.exists("NL_TOL") ) parse("NL_TOL",nl_tolerance);
     if( nl_tolerance>tolerance ) error("NL_TOL must be smaller than TOL"); 
     log.printf(" Ignoring contributions less than %f",tolerance);
     if( nl_tolerance>epsilon ) log.printf(" and ignoring quantities less than %f inbetween neighbor list update steps\n",nl_tolerance);
     else log.printf("\n");
  }
  parseFlag("TIMINGS",timers);
  stopwatch.start(); stopwatch.pause();
}
コード例 #10
0
ファイル: PathBase.cpp プロジェクト: OndrejMarsalek/plumed2
PathBase::PathBase(const ActionOptions& ao):
Action(ao),
Mapping(ao)
{
  bool noz; parseFlag("NOZPATH",noz);
  parse("LAMBDA",lambda);

  // Create the list of tasks
  for(unsigned i=0;i<getNumberOfReferencePoints();++i) addTaskToList( i );

  std::string empty="LABEL=zpath";
  if(!noz) addVessel("ZPATH",empty,0);
}
コード例 #11
0
MultiColvarBase::MultiColvarBase(const ActionOptions&ao):
Action(ao),
ActionAtomistic(ao),
ActionWithValue(ao),
ActionWithVessel(ao),
usepbc(false),
linkcells(comm),
usespecies(false)
{
  if( keywords.exists("NOPBC") ){ 
    bool nopbc=!usepbc; parseFlag("NOPBC",nopbc);
    usepbc=!nopbc;
  } 
  if( keywords.exists("SPECIES") ) usespecies=true;
}
コード例 #12
0
SecondaryStructureRMSD::SecondaryStructureRMSD(const ActionOptions&ao):
  Action(ao),
  ActionAtomistic(ao),
  ActionWithValue(ao),
  ActionWithVessel(ao),
  nopbc(false),
  align_strands(false),
  s_cutoff2(0),
  align_atom_1(0),
  align_atom_2(0)
{
  parse("TYPE",alignType); parseFlag("NOPBC",nopbc);
  log.printf("  distances from secondary structure elements are calculated using %s algorithm\n",alignType.c_str() );
  log<<"  Bibliography "<<plumed.cite("Pietrucci and Laio, J. Chem. Theory Comput. 5, 2197 (2009)"); log<<"\n";

  parseFlag("VERBOSE",verbose_output);

  if( keywords.exists("STRANDS_CUTOFF") ) {
    double s_cutoff = 0;
    parse("STRANDS_CUTOFF",s_cutoff); align_strands=true;
    if( s_cutoff>0) log.printf("  ignoring contributions from strands that are more than %f apart\n",s_cutoff);
    s_cutoff2=s_cutoff*s_cutoff;
  }
}
コード例 #13
0
Between::Between( const VesselOptions& da ) :
  FunctionVessel(da)
{
  usetol=true;
  bool isPeriodic=getAction()->isPeriodic();
  double min, max; std::string str_min, str_max;
  if( isPeriodic ) {
    getAction()->retrieveDomain( str_min, str_max );
    Tools::convert(str_min,min); Tools::convert(str_max,max);
  }

  parseFlag("NORM",norm); std::string errormsg;

  hist.set( getAllInput(),errormsg );
  if( !isPeriodic ) hist.isNotPeriodic();
  else hist.isPeriodic( min, max );
  if( errormsg.size()!=0 ) error( errormsg );
}
コード例 #14
0
ActionWithAveraging::ActionWithAveraging( const ActionOptions& ao ):
  Action(ao),
  ActionPilot(ao),
  ActionAtomistic(ao),
  ActionWithArguments(ao),
  ActionWithValue(ao),
  ActionWithVessel(ao),
  myaverage(NULL),
  useRunAllTasks(false),
  clearstride(0),
  lweight(0),cweight(0)
{
  if( keywords.exists("CLEAR") ) {
    parse("CLEAR",clearstride);
    if( clearstride>0 ) {
      if( clearstride%getStride()!=0 ) error("CLEAR parameter must be a multiple of STRIDE");
      log.printf("  clearing grid every %u steps \n",clearstride);
    }
  }
  if( keywords.exists("LOGWEIGHTS") ) {
    std::vector<std::string> wwstr; parseVector("LOGWEIGHTS",wwstr);
    if( wwstr.size()>0 ) log.printf("  reweighting using weights from ");
    std::vector<Value*> arg( getArguments() );
    for(unsigned i=0; i<wwstr.size(); ++i) {
      ActionWithValue* val = plumed.getActionSet().selectWithLabel<ActionWithValue*>(wwstr[i]);
      if( !val ) error("could not find value named");
      weights.push_back( val->copyOutput(val->getLabel()) );
      arg.push_back( val->copyOutput(val->getLabel()) );
      log.printf("%s ",wwstr[i].c_str() );
    }
    if( wwstr.size()>0 ) log.printf("\n");
    else log.printf("  weights are all equal to one\n");
    requestArguments( arg );
  }
  if( keywords.exists("UNORMALIZED") ) parseFlag("UNORMALIZED",unormalised);
}
コード例 #15
0
ファイル: ActionVolume.cpp プロジェクト: epfl-cosmo/plumed2
ActionVolume::ActionVolume(const ActionOptions&ao):
  Action(ao),
  VolumeGradientBase(ao)
{
  // Find number of quantities
  if( getPntrToMultiColvar()->isDensity() ) nquantities=2;                           // Value + weight
  else if( getPntrToMultiColvar()->getNumberOfQuantities()==2 ) nquantities=2;       // Value + weight
  else nquantities = 1 + getPntrToMultiColvar()->getNumberOfQuantities()-2 + 1;      // Norm  + vector + weight

  // Output some nice information
  std::string functype=getPntrToMultiColvar()->getName();
  std::transform( functype.begin(), functype.end(), functype.begin(), tolower );
  log.printf("  calculating %s inside region of insterest\n",functype.c_str() );

  parseFlag("OUTSIDE",not_in); sigma=0.0;
  if( keywords.exists("SIGMA") ) parse("SIGMA",sigma);
  if( keywords.exists("KERNEL") ) parse("KERNEL",kerneltype);

  if( getPntrToMultiColvar()->isDensity() ) {
    std::string input;
    addVessel( "SUM", input, -1 );  // -1 here means that this value will be named getLabel()
  }
  readVesselKeywords();
}
コード例 #16
0
void Moc::parse()
{
    QList<NamespaceDef> namespaceList;
    bool templateClass = false;
    while (hasNext()) {
        Token t = next();
        switch (t) {
            case NAMESPACE: {
                int rewind = index;
                if (test(IDENTIFIER)) {
                    if (test(EQ)) {
                        // namespace Foo = Bar::Baz;
                        until(SEMIC);
                    } else if (!test(SEMIC)) {
                        NamespaceDef def;
                        def.name = lexem();
                        next(LBRACE);
                        def.begin = index - 1;
                        until(RBRACE);
                        def.end = index;
                        index = def.begin + 1;
                        namespaceList += def;
                        index = rewind;
                    }
                }
                break;
            }
            case SEMIC:
            case RBRACE:
                templateClass = false;
                break;
            case TEMPLATE:
                templateClass = true;
                break;
            case MOC_INCLUDE_BEGIN:
                currentFilenames.push(symbol().unquotedLexem());
                break;
            case MOC_INCLUDE_END:
                currentFilenames.pop();
                break;
            case Q_DECLARE_INTERFACE_TOKEN:
                parseDeclareInterface();
                break;
            case Q_DECLARE_METATYPE_TOKEN:
                parseDeclareMetatype();
                break;
            case USING:
                if (test(NAMESPACE)) {
                    while (test(SCOPE) || test(IDENTIFIER))
                        ;
                    next(SEMIC);
                }
                break;
            case CLASS:
            case STRUCT: {
                if (currentFilenames.size() <= 1)
                    break;

                ClassDef def;
                if (!parseClassHead(&def))
                    continue;

                while (inClass(&def) && hasNext()) {
                    if (next() == Q_OBJECT_TOKEN) {
                        def.hasQObject = true;
                        break;
                    }
                }

                if (!def.hasQObject)
                    continue;

                for (int i = namespaceList.size() - 1; i >= 0; --i)
                    if (inNamespace(&namespaceList.at(i)))
                        def.qualified.prepend(namespaceList.at(i).name + "::");

                knownQObjectClasses.insert(def.classname);
                knownQObjectClasses.insert(def.qualified);

                continue; }
            default: break;
        }
        if ((t != CLASS && t != STRUCT)|| currentFilenames.size() > 1)
            continue;
        ClassDef def;
        if (parseClassHead(&def)) {
            FunctionDef::Access access = FunctionDef::Private;
            for (int i = namespaceList.size() - 1; i >= 0; --i)
                if (inNamespace(&namespaceList.at(i)))
                    def.qualified.prepend(namespaceList.at(i).name + "::");
            while (inClass(&def) && hasNext()) {
                switch ((t = next())) {
                case PRIVATE:
                    access = FunctionDef::Private;
                    if (test(Q_SIGNALS_TOKEN))
                        error("Signals cannot have access specifier");
                    break;
                case PROTECTED:
                    access = FunctionDef::Protected;
                    if (test(Q_SIGNALS_TOKEN))
                        error("Signals cannot have access specifier");
                    break;
                case PUBLIC:
                    access = FunctionDef::Public;
                    if (test(Q_SIGNALS_TOKEN))
                        error("Signals cannot have access specifier");
                    break;
                case CLASS: {
                    ClassDef nestedDef;
                    if (parseClassHead(&nestedDef)) {
                        while (inClass(&nestedDef) && inClass(&def)) {
                            t = next();
                            if (t >= Q_META_TOKEN_BEGIN && t < Q_META_TOKEN_END)
                                error("Meta object features not supported for nested classes");
                        }
                    }
                } break;
                case Q_SIGNALS_TOKEN:
                    parseSignals(&def);
                    break;
                case Q_SLOTS_TOKEN:
                    switch (lookup(-1)) {
                    case PUBLIC:
                    case PROTECTED:
                    case PRIVATE:
                        parseSlots(&def, access);
                        break;
                    default:
                        error("Missing access specifier for slots");
                    }
                    break;
                case Q_OBJECT_TOKEN:
                    def.hasQObject = true;
                    if (templateClass)
                        error("Template classes not supported by Q_OBJECT");
                    if (def.classname != "Qt" && def.classname != "QObject" && def.superclassList.isEmpty())
                        error("Class contains Q_OBJECT macro but does not inherit from QObject");
                    break;
                case Q_GADGET_TOKEN:
                    def.hasQGadget = true;
                    if (templateClass)
                        error("Template classes not supported by Q_GADGET");
                    break;
                case Q_PROPERTY_TOKEN:
                    parseProperty(&def);
                    break;
                case Q_ENUMS_TOKEN:
                    parseEnumOrFlag(&def, false);
                    break;
                case Q_FLAGS_TOKEN:
                    parseEnumOrFlag(&def, true);
                    break;
                case Q_DECLARE_FLAGS_TOKEN:
                    parseFlag(&def);
                    break;
                case Q_CLASSINFO_TOKEN:
                    parseClassInfo(&def);
                    break;
                case Q_INTERFACES_TOKEN:
                    parseInterfaces(&def);
                    break;
                case Q_PRIVATE_SLOT_TOKEN:
                    parseSlotInPrivate(&def, access);
                    break;
                case Q_PRIVATE_PROPERTY_TOKEN:
                    parsePrivateProperty(&def);
                    break;
                case ENUM: {
                    EnumDef enumDef;
                    if (parseEnum(&enumDef))
                        def.enumList += enumDef;
                } break;
                default:
                    FunctionDef funcDef;
                    funcDef.access = access;
                    int rewind = index;
                    if (parseMaybeFunction(&def, &funcDef)) {
                        if (funcDef.isConstructor) {
                            if ((access == FunctionDef::Public) && funcDef.isInvokable) {
                                def.constructorList += funcDef;
                                while (funcDef.arguments.size() > 0 && funcDef.arguments.last().isDefault) {
                                    funcDef.wasCloned = true;
                                    funcDef.arguments.removeLast();
                                    def.constructorList += funcDef;
                                }
                            }
                        } else if (funcDef.isDestructor) {
                            // don't care about destructors
                        } else {
                            if (access == FunctionDef::Public)
                                def.publicList += funcDef;
                            if (funcDef.isSlot) {
                                def.slotList += funcDef;
                                while (funcDef.arguments.size() > 0 && funcDef.arguments.last().isDefault) {
                                    funcDef.wasCloned = true;
                                    funcDef.arguments.removeLast();
                                    def.slotList += funcDef;
                                }
                            } else if (funcDef.isSignal) {
                                def.signalList += funcDef;
                                while (funcDef.arguments.size() > 0 && funcDef.arguments.last().isDefault) {
                                    funcDef.wasCloned = true;
                                    funcDef.arguments.removeLast();
                                    def.signalList += funcDef;
                                }
                            } else if (funcDef.isInvokable) {
                                def.methodList += funcDef;
                                while (funcDef.arguments.size() > 0 && funcDef.arguments.last().isDefault) {
                                    funcDef.wasCloned = true;
                                    funcDef.arguments.removeLast();
                                    def.methodList += funcDef;
                                }
                            }
                        }
                    } else {
                        index = rewind;
                    }
                }
            }

            next(RBRACE);

            if (!def.hasQObject && !def.hasQGadget && def.signalList.isEmpty() && def.slotList.isEmpty()
                && def.propertyList.isEmpty() && def.enumDeclarations.isEmpty())
                continue; // no meta object code required


            if (!def.hasQObject && !def.hasQGadget)
                error("Class declarations lacks Q_OBJECT macro.");

            checkSuperClasses(&def);
            checkProperties(&def);

            classList += def;
            knownQObjectClasses.insert(def.classname);
            knownQObjectClasses.insert(def.qualified);
        }
    }
}
コード例 #17
0
ファイル: bbsfmlmain.cpp プロジェクト: qyqx/BerryBots
int main(int argc, char *argv[]) {
  Zipper *zipper = new GuiZipper();
  FileManager *fileManager = new FileManager(zipper);
  CliPackageReporter *packageReporter = new CliPackageReporter();
  fileManager->setListener(packageReporter);

  char *shipsBaseDir = fileManager->getAbsFilePath(SHIPS_SUBDIR);
  char *stagesBaseDir = fileManager->getAbsFilePath(STAGES_SUBDIR);

  if (flagExists(argc, argv, "packstage")) {
    char **stageInfo = parseFlag(argc, argv, "packstage", 2);
    if (stageInfo == 0) {
      printUsage();
    } else {
      // TODO: add a new flag for obfuscating source code
      bool obfuscate = false;
      try {
        char *stageAbsName = fileManager->getAbsFilePath(stageInfo[0]);
        char *stageName =
            fileManager->parseRelativeFilePath(stagesBaseDir, stageAbsName);
        if (stageName == 0) {
          std::cout << "Stage must be located under " << STAGES_SUBDIR
                    << "/ subdirectory: " << stageInfo[0] << std::endl;
        } else {
          fileManager->packageStage(stagesBaseDir, stageName, stageInfo[1],
                                    CACHE_SUBDIR, TMP_SUBDIR, obfuscate, true);
          delete stageName;
        }
        delete stageAbsName;
      } catch (std::exception *e) {
        std::cout << "BerryBots encountered an error:" << std::endl;
        std::cout << "  " << e->what() << std::endl;
        delete e;
      }
      delete stageInfo;
    }
    return 0;
  }

  if (flagExists(argc, argv, "packbot")) {
    char **shipInfo = parseFlag(argc, argv, "packbot", 2);
    if (shipInfo == 0) {
      printUsage();
    } else {
      // TODO: add a new flag for obfuscating source code
      bool obfuscate = false;
      try {
        char *shipAbsName = fileManager->getAbsFilePath(shipInfo[0]);
        char *shipName =
           fileManager->parseRelativeFilePath(shipsBaseDir, shipAbsName);
        if (shipName == 0) {
          std::cout << "Ship must be located under " << SHIPS_SUBDIR
                    << "/ subdirectory: " << shipInfo[0] << std::endl;
        } else {
          fileManager->packageShip(shipsBaseDir, shipName, shipInfo[1],
                                   CACHE_SUBDIR, TMP_SUBDIR, obfuscate, true);
          delete shipName;
        }
        delete shipAbsName;
      } catch (std::exception *e) {
        std::cout << "BerryBots encountered an error:" << std::endl;
        std::cout << "  " << e->what() << std::endl;
        delete e;
      }
      delete shipInfo;
    }
    return 0;
  }
  
  bool nodisplay = flagExists(argc, argv, "nodisplay");
  bool saveReplay = flagExists(argc, argv, "savereplay");
  int optArgsOffset = (nodisplay ? 1 : 0) + (saveReplay ? 1 : 0);
  if (argc < 3 + optArgsOffset) {
    printUsage();
  }

  srand(time(NULL));
  CliPrintHandler *printHandler = new CliPrintHandler();
  BerryBotsEngine *engine =
      new BerryBotsEngine(printHandler, fileManager, resourcePath().c_str());
  Stage *stage = engine->getStage();

  char *stageAbsName = fileManager->getAbsFilePath(argv[1 + optArgsOffset]);
  char *stageName =
      fileManager->parseRelativeFilePath(stagesBaseDir, stageAbsName);
  if (stageName == 0) {
    std::cout << "Stage must be located under " << STAGES_SUBDIR
              << "/ subdirectory: " << argv[1 + optArgsOffset] << std::endl;
    return 0;
  }
  try {
    engine->initStage(stagesBaseDir, stageName, CACHE_SUBDIR);
  } catch (EngineException *e) {
    delete stageAbsName;
    delete stageName;
    std::cout << "BerryBots initialization failed:" << std::endl;
    std::cout << "  " << e->what() << std::endl;
    delete e;
    return 0;
  }
  delete stageAbsName;
  delete stageName;

  int firstTeam = (2 + optArgsOffset);
  int numTeams = argc - firstTeam;
  char **teams = new char*[numTeams];
  for (int x = 0; x < numTeams; x++) {
    char *teamAbsName = fileManager->getAbsFilePath(argv[x + firstTeam]);
    char *teamName =
        fileManager->parseRelativeFilePath(shipsBaseDir, teamAbsName);
    if (teamName == 0) {
      std::cout << "Ship must be located under " << SHIPS_SUBDIR
                << "/ subdirectory: " << argv[x + firstTeam] << std::endl;
      return 0;
    }
    teams[x] = teamName;
    delete teamAbsName;
  }

  printHandler->setNumTeams(numTeams);
  try {
    engine->initShips(shipsBaseDir, teams, numTeams, CACHE_SUBDIR);
  } catch (EngineException *e) {
    std::cout << "BerryBots initialization failed:" << std::endl;
    std::cout << "  " << e->what() << std::endl;
    delete e;
    return 0;
  }
  printHandler->updateTeams(engine->getTeams());

  GfxManager *gfxManager;
  sf::RenderWindow *window = 0;
  GfxEventHandler *gfxHandler = 0;
  unsigned int viewWidth = stage->getWidth() + (STAGE_MARGIN * 2);
  unsigned int viewHeight = stage->getHeight() + (STAGE_MARGIN * 2);
  if (!nodisplay) {
    gfxHandler = new GfxEventHandler();
    stage->addEventHandler((EventHandler*) gfxHandler);

    unsigned int screenWidth = sf::VideoMode::getDesktopMode().width;
    unsigned int screenHeight = sf::VideoMode::getDesktopMode().height;
    double windowScale = std::min(1.0,
        std::min(((double) screenWidth) / viewWidth,
                 ((double) screenHeight) / viewHeight));
    unsigned int targetWidth = round(windowScale * viewWidth);
    unsigned int targetHeight = round(windowScale * viewHeight);

    gfxManager = new GfxManager(false);
    window = new sf::RenderWindow(sf::VideoMode(targetWidth, targetHeight),
        "BerryBots", sf::Style::Default, sf::ContextSettings(0, 0, 16, 2, 0));
    gfxManager->initViews(window, viewWidth, viewHeight);
    gfxManager->initBbGfx(window, viewHeight, stage, engine->getTeams(),
        engine->getNumTeams(), engine->getShips(), engine->getNumShips(),
        resourcePath());
    window->clear();
    gfxManager->drawGame(window, stage, engine->getShips(),
        engine->getNumShips(), engine->getGameTime(), gfxHandler, false, false,
        0);
    window->display();
  }
  
  time_t realTime1;
  time_t realTime2;
  time(&realTime1);
  int realSeconds = 0;
  
  try {
    while ((nodisplay || window->isOpen()) && !engine->isGameOver()) {
      engine->processTick();
  
      if (!nodisplay) {
        sf::Event event;
        bool resized = false;
        while (window->pollEvent(event)) {
          if (event.type == sf::Event::Closed) {
            window->close();
          }
          if (event.type == sf::Event::KeyPressed
              && event.key.code == sf::Keyboard::Escape) {
            window->close();
          }
          if (event.type == sf::Event::Resized && !resized) {
            resized = true;
            gfxManager->onResize(window, viewWidth, viewHeight);
          }
        }
    
        window->clear();
        gfxManager->drawGame(window, stage, engine->getShips(),
            engine->getNumShips(), engine->getGameTime(), gfxHandler, false,
            false, 0);
        window->display();
      }
  
      time(&realTime2);
      if (realTime2 - realTime1 > 0) {
        realSeconds++;
        if (realSeconds % 10 == 0) {
          std::cout << "TPS: "
                    << (((double) engine->getGameTime()) / realSeconds)
                    << std::endl;
        }
      }
      realTime1 = realTime2;
    }
  } catch (EngineException *e) {
    std::cout << "BerryBots encountered an error:" << std::endl;
    std::cout << "  " << e->what() << std::endl;
    delete e;
    return 0;
  }
  
  if (!nodisplay) {
    gfxManager->destroyBbGfx();
    delete window;
  }
  
  const char* winnerName = engine->getWinnerName();
  if (winnerName != 0) {
    std::cout << std::endl<< winnerName << " wins! Congratulations!"
              << std::endl;
  }

  std::cout << std::endl << "Results:" << std::endl;
  Team **rankedTeams = engine->getRankedTeams();
  bool hasScores = false;
  for (int x = 0; x < numTeams; x++) {
    if (rankedTeams[x]->result.score != 0) {
      hasScores = true;
      break;
    }
  }
  TeamResult *firstResult = &(rankedTeams[0]->result);
  int numStats = firstResult->numStats;
  char **statKeys = 0;
  if (numStats > 0) {
    statKeys = new char*[firstResult->numStats];
    for (int x = 0; x < numStats; x++) {
      statKeys[x] = new char[strlen(firstResult->stats[x]->key) + 1];
      strcpy(statKeys[x], firstResult->stats[x]->key);
    }
  }

  for (int x = 0; x < engine->getNumTeams(); x++) {
    TeamResult *result = &(rankedTeams[x]->result);
    if (result->showResult) {
      std::cout << "    " << rankedTeams[x]->name << ":" << std::endl;
      std::cout << "        Rank: ";
      if (result->rank == 0) {
        std::cout << "-";
      } else {
        std::cout << result->rank;
      }
      std::cout << std::endl;
      if (hasScores) {
        std::cout << "        Score: " << round(result->score, 2) << std::endl;
      }

      for (int y = 0; y < numStats; y++) {
        char *key = statKeys[y];
        bool found = false;
        for (int z = 0; z < result->numStats; z++) {
        char *resultKey = result->stats[z]->key;
        if (strcmp(key, resultKey) == 0) {
          std::cout << "        " << key << ": "
              << round(result->stats[z]->value, 2) << std::endl;
          found = true;
          break;
        }
        }
        if (!found) {
        std::cout << "        " << key << ": -" << std::endl;
        }
      }
    }
  }

  std::cout << std::endl << "CPU time used per tick (microseconds):"
            << std::endl;
  for (int x = 0; x < engine->getNumTeams(); x++) {
    Team *team = engine->getTeam(x);
    if (!team->stageShip && !team->disabled) {
      std::cout << "  " << team->name << ": "
                << (team->totalCpuTime / team->totalCpuTicks) << std::endl;
    }
  }

  if (realSeconds > 0) {
    std::cout << std::endl << "TPS: "
              << (((double) engine->getGameTime()) / realSeconds) << std::endl;
  }

  if (saveReplay) {
    ReplayBuilder *replayBuilder = engine->getReplayBuilder();

    // TODO: move this into a function in the engine
    Team **rankedTeams = engine->getRankedTeams();
    replayBuilder->setResults(rankedTeams, engine->getNumTeams());

    char *filename = 0;
    char *absFilename = 0;
    do {
      if (filename != 0) {
        delete filename;
      }
      if (absFilename != 0) {
        delete absFilename;
      }
      filename = replayFilename(stage->getName());
      char *filePath = fileManager->getFilePath(REPLAYS_SUBDIR, filename);
      absFilename = fileManager->getAbsFilePath(filePath);
      delete filePath;
    } while (fileManager->fileExists(absFilename));
    replayBuilder->saveReplay(filename);
    std::cout << std::endl << "Saved replay to: " << REPLAYS_SUBDIR << "/"
              << filename << std::endl;
    delete filename;
    delete absFilename;
  }

  std::cout << std::endl;

  delete engine;
  for (int x = 0; x < numTeams; x++) {
    delete teams[x];
  }
  delete teams;
  delete rankedTeams;
  for (int x = 0; x < numStats; x++) {
    delete statKeys[x];
  }
  delete statKeys;
  delete printHandler;
  if (!nodisplay) {
    delete gfxManager;
  }
  delete packageReporter;
  delete fileManager;
  delete zipper;
  delete shipsBaseDir;
  delete stagesBaseDir;

  return 0;
}
コード例 #18
0
CoordinationBase::CoordinationBase(const ActionOptions&ao):
  PLUMED_COLVAR_INIT(ao),
  pbc(true),
  serial(false),
  invalidateList(true),
  firsttime(true)
{

  parseFlag("SERIAL",serial);

  vector<AtomNumber> ga_lista,gb_lista;
  parseAtomList("GROUPA",ga_lista);
  parseAtomList("GROUPB",gb_lista);

  bool nopbc=!pbc;
  parseFlag("NOPBC",nopbc);
  pbc=!nopbc;

// pair stuff
  bool dopair=false;
  parseFlag("PAIR",dopair);

// neighbor list stuff
  bool doneigh=false;
  double nl_cut=0.0;
  int nl_st=0;
  parseFlag("NLIST",doneigh);
  if(doneigh) {
    parse("NL_CUTOFF",nl_cut);
    if(nl_cut<=0.0) error("NL_CUTOFF should be explicitly specified and positive");
    parse("NL_STRIDE",nl_st);
    if(nl_st<=0) error("NL_STRIDE should be explicitly specified and positive");
  }

  addValueWithDerivatives(); setNotPeriodic();
  if(gb_lista.size()>0) {
    if(doneigh)  nl= new NeighborList(ga_lista,gb_lista,dopair,pbc,getPbc(),nl_cut,nl_st);
    else         nl= new NeighborList(ga_lista,gb_lista,dopair,pbc,getPbc());
  } else {
    if(doneigh)  nl= new NeighborList(ga_lista,pbc,getPbc(),nl_cut,nl_st);
    else         nl= new NeighborList(ga_lista,pbc,getPbc());
  }

  requestAtoms(nl->getFullAtomList());

  log.printf("  between two groups of %u and %u atoms\n",static_cast<unsigned>(ga_lista.size()),static_cast<unsigned>(gb_lista.size()));
  log.printf("  first group:\n");
  for(unsigned int i=0; i<ga_lista.size(); ++i) {
    if ( (i+1) % 25 == 0 ) log.printf("  \n");
    log.printf("  %d", ga_lista[i].serial());
  }
  log.printf("  \n  second group:\n");
  for(unsigned int i=0; i<gb_lista.size(); ++i) {
    if ( (i+1) % 25 == 0 ) log.printf("  \n");
    log.printf("  %d", gb_lista[i].serial());
  }
  log.printf("  \n");
  if(pbc) log.printf("  using periodic boundary conditions\n");
  else    log.printf("  without periodic boundary conditions\n");
  if(dopair) log.printf("  with PAIR option\n");
  if(doneigh) {
    log.printf("  using neighbor lists with\n");
    log.printf("  update every %d steps and cutoff %f\n",nl_st,nl_cut);
  }
}
コード例 #19
0
ファイル: DRMSD.cpp プロジェクト: hockyg/plumed2
void DRMSD::readBounds(){
  parseFlag("NOPBC",nopbc);  
  parse("LOWER_CUTOFF",lower,true);
  parse("UPPER_CUTOFF",upper,true);
  setBoundsOnDistances( !nopbc, lower, upper );
}
コード例 #20
0
ファイル: argumentprocessor.cpp プロジェクト: s1hofmann/PipeR
std::unordered_map<std::string, std::string> ArgumentProcessor::parse(int32_t argc, char *argv[])
{
    std::vector<std::string> args = toStringVector(argc, argv);

    std::unordered_map<std::string, std::string> argumentMap;

    for(size_t idx = 0; idx < argc; ++idx) {
        std::string currentArgument = args[idx];
        if(notIn(currentArgument, mArguments) &&
           notIn(currentArgument, mOptionalArguments) &&
           notIn(currentArgument, mSwitches)) {
            continue;
        } else {
            size_t nextIdx = idx + 1;
            if(nextIdx >= argc) {
                if(notIn(currentArgument, mSwitches)) {
                    continue;
                } else {
                    argumentMap[parseFlag(currentArgument)] = "true";
                }
            } else {
                std::string nextArgument = args[nextIdx];
                if(!notIn(currentArgument, mArguments) && notIn(nextArgument, {mOptionalArguments, mSwitches})) {
                    if(!mAllowedValues[currentArgument].empty()) {
                        if(!notIn(nextArgument, mAllowedValues[currentArgument])) {
                            argumentMap[parseFlag(currentArgument)] = nextArgument;
                        } else {
                            std::stringstream s;
                            s << "Encountered invalid option: " << currentArgument << " " << nextArgument << std::endl;
                            throw CommandLineError(s.str(), currentMethod, currentLine);
                        }
                    } else {
                        argumentMap[parseFlag(currentArgument)] = nextArgument;
                    }
                } else if(!notIn(currentArgument, mOptionalArguments) && notIn(nextArgument, {mArguments, mSwitches})) {
                    if(!mAllowedValues[currentArgument].empty()) {
                        if(!notIn(nextArgument, mAllowedValues[currentArgument])) {
                            argumentMap[parseFlag(currentArgument)] = nextArgument;
                        } else {
                            std::stringstream s;
                            s << "Encountered invalid option: " << currentArgument << " " << nextArgument << std::endl;
                            throw CommandLineError(s.str(), currentMethod, currentLine);
                        }
                    } else {
                        argumentMap[parseFlag(currentArgument)] = nextArgument;
                    }
                } else if(!notIn(currentArgument, mSwitches) && !notIn(nextArgument, {mArguments, mOptionalArguments})) {
                    argumentMap[parseFlag(currentArgument)] = "true";
                }
            }
        }
    }

    if(argumentMap[parseFlag("--help")].empty()) {
        for(std::string arg : mArguments) {
            if(argumentMap[parseFlag(arg)].empty()) {
                std::stringstream s;
                s << "Missing required argument: " << arg << std::endl;
                throw CommandLineError(s.str(), currentMethod, currentLine);
            }
        }
    } else {
        std::stringstream s;
        s << "Let me help you!" << std::endl;
        throw CommandLineError(s.str());
    }

    return argumentMap;
}
コード例 #21
0
ファイル: Mapping.cpp プロジェクト: psolsson/plumed2
Mapping::Mapping(const ActionOptions&ao):
Action(ao),
ActionAtomistic(ao),
ActionWithArguments(ao),
ActionWithValue(ao),
ActionWithVessel(ao)
{
  // Read the input
  std::string mtype; parse("TYPE",mtype);
  bool skipchecks; parseFlag("DISABLE_CHECKS",skipchecks);
  // Setup the object that does the mapping
  mymap = new PointWiseMapping( mtype, skipchecks ); 
 
  // Read the properties we require
  if( keywords.exists("PROPERTY") ){
     std::vector<std::string> property;
     parseVector("PROPERTY",property);
     if(property.size()==0) error("no properties were specified");
     mymap->setPropertyNames( property, false );
  } else {
     std::vector<std::string> property(1); 
     property[0]="sss";
     mymap->setPropertyNames( property, true );
  }

  // Open reference file
  std::string reference; parse("REFERENCE",reference); 
  FILE* fp=fopen(reference.c_str(),"r"); 
  if(!fp) error("could not open reference file " + reference );

  // Read all reference configurations 
  bool do_read=true; std::vector<double> weights; 
  unsigned nfram=0, wnorm=0., ww;
  while (do_read){
     PDB mypdb; 
     // Read the pdb file
     do_read=mypdb.readFromFilepointer(fp,plumed.getAtoms().usingNaturalUnits(),0.1/atoms.getUnits().getLength());
     // Fix argument names
     expandArgKeywordInPDB( mypdb );
     if(do_read){
        mymap->readFrame( mypdb ); ww=mymap->getWeight( nfram ); 
        weights.push_back( ww );
        wnorm+=ww; nfram++;
     } else {
        break;
     }
  }
  fclose(fp); 

  if(nfram==0 ) error("no reference configurations were specified");
  log.printf("  found %d configurations in file %s\n",nfram,reference.c_str() );
  for(unsigned i=0;i<weights.size();++i) weights[i] /= wnorm;
  mymap->setWeights( weights );

  // Finish the setup of the mapping object
  // Get the arguments and atoms that are required
  std::vector<AtomNumber> atoms; std::vector<std::string> args;
  mymap->getAtomAndArgumentRequirements( atoms, args );
  requestAtoms( atoms ); std::vector<Value*> req_args;
  interpretArgumentList( args, req_args ); requestArguments( req_args );
  // Duplicate all frames (duplicates are used by sketch-map)
  mymap->duplicateFrameList(); 
  fframes.resize( 2*nfram, 0.0 ); dfframes.resize( 2*nfram, 0.0 );
  plumed_assert( !mymap->mappingNeedsSetup() );
  // Resize all derivative arrays
  mymap->setNumberOfAtomsAndArguments( atoms.size(), args.size() );
  // Resize forces array
  if( getNumberOfAtoms()>0 ){ 
     forcesToApply.resize( 3*getNumberOfAtoms() + 9 + getNumberOfArguments() );
  } else {
     forcesToApply.resize( getNumberOfArguments() );
  }
}