コード例 #1
0
ファイル: Analysis_RemLog.cpp プロジェクト: yuqinc/cpptraj
// Analysis_RemLog::Setup()
Analysis::RetType Analysis_RemLog::Setup(ArgList& analyzeArgs, DataSetList* datasetlist, DataFileList* DFLin, int debugIn)
{
  debug_ = debugIn;
  // Get remlog dataset
  std::string remlogName = analyzeArgs.GetStringNext();
  if (remlogName.empty()) {
    mprinterr("Error: no remlog data set or file name specified.\n");
    return Analysis::ERR;
  }
  // Check if data set exists
  remlog_ = (DataSet_RemLog*)datasetlist->FindSetOfType( remlogName, DataSet::REMLOG );
  if (remlog_ == 0) {
    mprinterr("Error: remlog data with name %s not found.\n", remlogName.c_str());
    return Analysis::ERR;
  }
  if (remlog_->Size() < 1 || remlog_->NumExchange() < 1) {
    mprinterr("Error: remlog data set appears to be empty.\n");
    return Analysis::ERR;
  }
  acceptout_ = DFLin->AddCpptrajFile( analyzeArgs.GetStringKey("acceptout"), "replica acceptance",
                                      DataFileList::TEXT, true );
  if (acceptout_ == 0) return Analysis::ERR;
  lifetimes_ = DFLin->AddCpptrajFile( analyzeArgs.GetStringKey("lifetime"), "remlog lifetimes" );
  calculateLifetimes_ = (lifetimes_ != 0);
  calculateStats_ = analyzeArgs.hasKey("stats");
  if (calculateStats_) {
    statsout_ = DFLin->AddCpptrajFile( analyzeArgs.GetStringKey("statsout"), "remlog stats",
                                       DataFileList::TEXT, true );
    reptime_ = DFLin->AddCpptrajFile( analyzeArgs.GetStringKey("reptime"), "replica times",
                                      DataFileList::TEXT, true );
    if (statsout_ == 0 || reptime_ == 0) return Analysis::ERR;
  }
  calcRepFracSlope_ = analyzeArgs.getKeyInt("reptimeslope", 0);
  std::string rfs_name = analyzeArgs.GetStringKey("reptimeslopeout");
  if (!calculateStats_) {
    calcRepFracSlope_ = 0;
    rfs_name.clear();
  }
  if ( (calcRepFracSlope_ > 0) != (!rfs_name.empty()) ) {
    mprinterr("Error: Both reptimeslope and reptimeslopeout must be specified.\n");
    return Analysis::ERR;
  }
  repFracSlope_ = DFLin->AddCpptrajFile( rfs_name, "replica fraction slope" );
  printIndividualTrips_ = analyzeArgs.hasKey("printtrips");
  // Get mode
  if (analyzeArgs.hasKey("crdidx"))
    mode_ = CRDIDX;
  else if (analyzeArgs.hasKey("repidx"))
    mode_ = REPIDX;
  else
    mode_ = NONE;
  const char* def_name = 0;
  const char* yaxis = 0;
  if (mode_ == CRDIDX) {
    def_name = "repidx";
    yaxis = "ylabel CrdIdx";
  } else if (mode_ == REPIDX) {
    def_name = "crdidx";
    yaxis = "ylabel RepIdx";
  }
  // Set up an output set for each replica
  DataFile* dfout = 0;
  if (mode_ != NONE) {
    // Get output filename
    std::string outname = analyzeArgs.GetStringKey("out");
    if (!outname.empty()) {
      dfout = DFLin->AddDataFile( outname, analyzeArgs );
      if (dfout == 0 ) return Analysis::ERR;
      if (yaxis != 0 ) dfout->ProcessArgs(yaxis);
    }
    std::string dsname = analyzeArgs.GetStringKey("name");
    if (dsname.empty())
      dsname = datasetlist->GenerateDefaultName(def_name);
    MetaData md(dsname);
    for (int i = 0; i < (int)remlog_->Size(); i++) {
      md.SetIdx(i+1);
      DataSet_integer* ds = (DataSet_integer*)datasetlist->AddSet(DataSet::INTEGER, md);
      if (ds == 0) return Analysis::ERR;
      outputDsets_.push_back( (DataSet*)ds );
      if (dfout != 0) dfout->AddDataSet( (DataSet*)ds );
      ds->Resize( remlog_->NumExchange() ); 
    }
  }
  mprintf("   REMLOG: %s, %i replicas, %i exchanges\n", remlog_->legend(),
          remlog_->Size(), remlog_->NumExchange());
  if (mode_ == CRDIDX)
    mprintf("\tGetting coordinate index vs exchange.\n");
  else if (mode_ == REPIDX)
    mprintf("\tGetting replica index vs exchange.\n");
  if (mode_ != NONE && dfout != 0)
    mprintf("\tOutput is to %s\n", dfout->DataFilename().base());
  if (calculateStats_) {
    mprintf("\tGetting replica exchange stats, output to %s\n", statsout_->Filename().full());
    if (printIndividualTrips_)
      mprintf("\tIndividual round trips will be printed.\n");
    mprintf("\tWriting time spent at each replica to %s\n", reptime_->Filename().full());
  }
  if (calculateLifetimes_)
    mprintf("\tThe lifetime of each crd at each replica will be calculated.\n");
  if (acceptout_ != 0)
    mprintf("\tOverall exchange acceptance % will be written to %s\n",
            acceptout_->Filename().full());

  return Analysis::OK;
}
コード例 #2
0
ファイル: Analysis_TI.cpp プロジェクト: Amber-MD/cpptraj
// Analysis_TI::Setup()
Analysis::RetType Analysis_TI::Setup(ArgList& analyzeArgs, AnalysisSetup& setup, int debugIn)
{
  debug_ = debugIn;
  int nq = analyzeArgs.getKeyInt("nq", 0);
  ArgList nskipArg(analyzeArgs.GetStringKey("nskip"), ","); // Comma-separated
  avg_increment_ = analyzeArgs.getKeyInt("avgincrement", -1);
  avg_max_ = analyzeArgs.getKeyInt("avgmax", -1);
  avg_skip_ = analyzeArgs.getKeyInt("avgskip", 0);
  n_bootstrap_pts_ = analyzeArgs.getKeyInt("bs_pts", -1);
  n_bootstrap_samples_ = analyzeArgs.getKeyInt("bs_samples", 0);
  bootstrap_seed_ = analyzeArgs.getKeyInt("bs_seed", -1);
  bootstrap_fac_ = analyzeArgs.getKeyDouble("bs_fac", 0.75);
  if (!nskipArg.empty()) {
    avgType_ = SKIP;
    // Specified numbers of points to skip
    nskip_.clear();
    for (int i = 0; i != nskipArg.Nargs(); i++) {
      nskip_.push_back( nskipArg.getNextInteger(0) );
      if (nskip_.back() < 0) nskip_.back() = 0;
    }
  } else if (avg_increment_ > 0)
    avgType_ = INCREMENT;
  else if (n_bootstrap_samples_ > 0)
    avgType_ = BOOTSTRAP;
  else
    avgType_ = AVG;
  masterDSL_ = setup.DslPtr();
  // Get lambda values
  ArgList xArgs(analyzeArgs.GetStringKey("xvals"), ","); // Also comma-separated
  if (!xArgs.empty()) {
    xval_.clear();
    for (int i = 0; i != xArgs.Nargs(); i++)
      xval_.push_back( xArgs.getNextDouble(0.0) );
  }
  std::string setname = analyzeArgs.GetStringKey("name");
  DataFile* outfile = setup.DFL().AddDataFile(analyzeArgs.GetStringKey("out"), analyzeArgs);
  curveout_ = setup.DFL().AddDataFile(analyzeArgs.GetStringKey("curveout"), analyzeArgs);
  // Select datasets from remaining args
  if (input_dsets_.AddSetsFromArgs( analyzeArgs.RemainingArgs(), setup.DSL() )) {
    mprinterr("Error: Could not add data sets.\n");
    return Analysis::ERR;
  }
  if (input_dsets_.empty()) {
    mprinterr("Error: No input data sets.\n");
    return Analysis::ERR;
  }
  if (SetQuadAndWeights(nq)) return Analysis::ERR;
  // Determine integration mode
  if (nq > 0)
    mode_ = GAUSSIAN_QUAD;
  else
    mode_ = TRAPEZOID;
  // Check that # abscissas matches # data sets
  if (xval_.size() != input_dsets_.size()) {
     mprinterr("Error: Expected %zu data sets for integration, got %zu\n",
               input_dsets_.size(), xval_.size());
    return Analysis::ERR;
  }
  // Set up output data sets
  DataSet::DataType dtype = DataSet::DOUBLE;
  if (avgType_ == SKIP || avgType_ == INCREMENT)
    dtype = DataSet::XYMESH;
  dAout_ = setup.DSL().AddSet(dtype, setname, "TI");
  if (dAout_ == 0) return Analysis::ERR;
  if (outfile != 0) outfile->AddDataSet( dAout_ );
  MetaData md(dAout_->Meta().Name(), "TIcurve");
  if (avgType_ == AVG) {
    // Single curve
    curve_.push_back( setup.DSL().AddSet(DataSet::XYMESH, md) );
    if (curve_.back() == 0) return Analysis::ERR;
    curve_.back()->ModifyDim(Dimension::X).SetLabel("Lambda");
    if (curveout_ != 0) curveout_->AddDataSet( curve_.back() );
    if (outfile != 0) outfile->ProcessArgs("noxcol");
  } else if (avgType_ == SKIP) {
    // As many curves as skip values
    for (Iarray::const_iterator it = nskip_.begin(); it != nskip_.end(); ++it) {
      md.SetIdx( *it );
      DataSet* ds = setup.DSL().AddSet(DataSet::XYMESH, md);
      if (ds == 0) return Analysis::ERR;
      ds->ModifyDim(Dimension::X).SetLabel("Lambda");
      ds->SetLegend( md.Name() + "_Skip" + integerToString(*it) );
      if (curveout_ != 0) curveout_->AddDataSet( ds );
      curve_.push_back( ds );
    }
  } else if (avgType_ == BOOTSTRAP) {
    // As many curves as resamples
    for (int nsample = 0; nsample != n_bootstrap_samples_; nsample++) {
      md.SetIdx(nsample);
      DataSet* ds = setup.DSL().AddSet(DataSet::XYMESH, md);
      if (ds == 0) return Analysis::ERR;
      ds->ModifyDim(Dimension::X).SetLabel("Lambda");
      ds->SetLegend( md.Name() + "_Sample" + integerToString(nsample) );
      if (curveout_ != 0) curveout_->AddDataSet( ds );
      curve_.push_back( ds );
    }
    // Standard devation of avg free energy over samples
    dA_SD_ = setup.DSL().AddSet(DataSet::DOUBLE, MetaData(md.Name(), "SD"));
    if (dA_SD_ == 0) return Analysis::ERR;
    if (outfile != 0) {
      outfile->AddDataSet( dA_SD_ );
      outfile->ProcessArgs("noxcol");
    }
  }
  // NOTE: INCREMENT is set up once data set size is known 

  mprintf("    TI: Calculating TI");
  if (mode_ == GAUSSIAN_QUAD) {
    mprintf(" using Gaussian quadrature with %zu points.\n", xval_.size());
    mprintf("\t%6s %8s %8s %s\n", "Point", "Abscissa", "Weight", "SetName");
    for (unsigned int i = 0; i != xval_.size(); i++)
      mprintf("\t%6i %8.5f %8.5f %s\n", i, xval_[i], wgt_[i], input_dsets_[i]->legend());
  } else {
    mprintf(" using the trapezoid rule.\n");
    mprintf("\t%6s %8s %s\n", "Point", "Abscissa", "SetName");
    for (unsigned int i = 0; i != xval_.size(); i++)
      mprintf("\t%6i %8.5f %s\n", i, xval_[i], input_dsets_[i]->legend());
  }
  mprintf("\tResult(s) of integration(s) saved in set '%s'\n", dAout_->legend());
  if (avgType_ == AVG)
    mprintf("\tUsing all data points in <DV/DL> calc.\n");
  else if (avgType_ == SKIP) {
    mprintf("\tSkipping first");
    for (Iarray::const_iterator it = nskip_.begin(); it != nskip_.end(); ++it)
      mprintf(" %i", *it);
    mprintf(" data points for <DV/DL> calc.\n");
  } else if (avgType_ == INCREMENT) {
    mprintf("\tCalculating <DV/DL> starting from point %i, increment by %i.",
            avg_skip_, avg_increment_);
    if (avg_max_ != -1)
      mprintf(" Max %i points.", avg_max_);
    mprintf("\n");
  } else if (avgType_ == BOOTSTRAP) {
    mprintf("\tStandard devation of result stored in set '%s'\n", dA_SD_->legend());
    mprintf("\tCalculating <DV/DL> from %i bootstrap resamples.\n", n_bootstrap_samples_);
    if (n_bootstrap_pts_ > 0)
      mprintf("\tBootstrap resample size is %i data points.\n", n_bootstrap_pts_);
    else
      mprintf("\tWill use bootstrap resample size of %g%% of total points.\n",
              bootstrap_fac_*100.0);
    if (bootstrap_seed_ != -1)
      mprintf("\tBoostrap base seed is %i\n", bootstrap_seed_);
  }
  mprintf("\tTI curve(s) saved in set(s)");
  if (avgType_ != INCREMENT)
    for (DSarray::const_iterator ds = curve_.begin(); ds != curve_.end(); ++ds)
      mprintf(" '%s'", (*ds)->legend());
  else
    mprintf(" named '%s'", md.PrintName().c_str());
  mprintf("\n");
  if (outfile != 0) mprintf("\tResults written to '%s'\n", outfile->DataFilename().full());
  if (curveout_!= 0) mprintf("\tTI curve(s) written to '%s'\n", curveout_->DataFilename().full());

  return Analysis::OK;
}
コード例 #3
0
Analysis::RetType Analysis_Lifetime::Setup(ArgList& analyzeArgs, DataSetList* datasetlist,
                            TopologyList* PFLin, DataFileList* DFLin, int debugIn)
{
  // Get Keywords
  DataFile* outfile = DFLin->AddDataFile(analyzeArgs.GetStringKey("out"), analyzeArgs);
  if (outfile != 0) outfile->ProcessArgs("noemptyframes");
  DataFile* maxfile = 0;
  DataFile* avgfile = 0;
  std::string setname = analyzeArgs.GetStringKey("name");
  windowSize_ = analyzeArgs.getKeyInt("window", -1);
  averageonly_ = analyzeArgs.hasKey("averageonly");
  if (!averageonly_ && outfile != 0) {
    maxfile = DFLin->AddDataFile("max." + outfile->DataFilename().Full(), analyzeArgs);
    maxfile->ProcessArgs("noemptyframes");
    avgfile = DFLin->AddDataFile("avg." + outfile->DataFilename().Full(), analyzeArgs);
    avgfile->ProcessArgs("noemptyframes");
  }
  cumulative_ = analyzeArgs.hasKey("cumulative");
  deltaAvg_ = analyzeArgs.hasKey("delta");
  cut_ = analyzeArgs.getKeyDouble("cut", 0.5);
  // Select datasets from remaining args
  ArgList dsetArgs = analyzeArgs.RemainingArgs();
  for (ArgList::const_iterator dsa = dsetArgs.begin(); dsa != dsetArgs.end(); ++dsa)
    inputDsets_ += datasetlist->GetMultipleSets( *dsa );
  if (inputDsets_.empty()) {
    mprinterr("Error: lifetime: No data sets selected.\n");
    return Analysis::ERR;
  }
  // Sort input datasets
  inputDsets_.sort();

  // Create output datasets
  if ( windowSize_ != -1) {
    if (setname.empty()) 
      setname = datasetlist->GenerateDefaultName( "lifetime" );
    int didx = 0;
    for (DataSetList::const_iterator set = inputDsets_.begin(); set != inputDsets_.end(); ++set)
    {
      DataSet* outSet = datasetlist->AddSetIdx( DataSet::FLOAT, setname, didx );
      if (outSet==0) {
        mprinterr("Error: lifetime: Could not allocate output set for %s\n", 
                  (*set)->Legend().c_str());
        return Analysis::ERR;
      }
      outSet->SetLegend( (*set)->Legend() );
      outputDsets_.push_back( outSet );
      if (outfile != 0) outfile->AddSet( outSet );
      if (!averageonly_) {
        // MAX
        // FIXME: CHeck for nullS
        outSet = datasetlist->AddSetIdxAspect( DataSet::INT, setname, didx, "max" );
        outSet->SetLegend( (*set)->Legend() );
        maxDsets_.push_back( outSet );
        if (maxfile != 0) maxfile->AddSet( outSet );
        // AVG
        outSet = datasetlist->AddSetIdxAspect( DataSet::FLOAT, setname, didx, "avg" );
        outSet->SetLegend( (*set)->Legend() );
        avgDsets_.push_back( outSet );
        if (avgfile != 0) avgfile->AddSet( outSet );
      }
      ++didx;
    }
  } else if (outfile != 0) {
    mprinterr("Error: Output file name specified but no window size given ('window <N>')\n");
    return Analysis::ERR;
  }

  if (!averageonly_)
    mprintf("    LIFETIME: Calculating average lifetime using a cutoff of %f", cut_);
  else
    mprintf("    LIFETIME: Calculating only averages");
  mprintf(" of data in %i sets\n", inputDsets_.size());
  if (debugIn > 0)
    inputDsets_.List();
  if (windowSize_ != -1) {
    mprintf("\tAverage of data over windows will be saved to sets named %s\n",
            setname.c_str());
    mprintf("\tWindow size for averaging: %i\n", windowSize_);
    if (cumulative_)
      mprintf("\tCumulative averages will be saved.\n");
    if (deltaAvg_)
      mprintf("\tChange of average from previous average will be saved.\n");
    if (outfile != 0) {
      mprintf("\tOutfile: %s", outfile->DataFilename().base());
      if (!averageonly_)
        mprintf(", %s, %s", maxfile->DataFilename().base(), avgfile->DataFilename().base());
      mprintf("\n");
    }
  }

  return Analysis::OK;
}
コード例 #4
0
// Analysis_Lifetime::Setup()
Analysis::RetType Analysis_Lifetime::Setup(ArgList& analyzeArgs, DataSetList* datasetlist,
                            TopologyList* PFLin, DataFileList* DFLin, int debugIn)
{
  // Get Keywords
  FileName outfileName( analyzeArgs.GetStringKey("out") );
  std::string setname = analyzeArgs.GetStringKey("name");
  bool sortSets = (!analyzeArgs.hasKey("nosort"));
  windowSize_ = analyzeArgs.getKeyInt("window", -1);
  averageonly_ = analyzeArgs.hasKey("averageonly");
  cumulative_ = analyzeArgs.hasKey("cumulative");
  deltaAvg_ = analyzeArgs.hasKey("delta");
  cut_ = analyzeArgs.getKeyDouble("cut", 0.5);
  fuzzCut_ = analyzeArgs.getKeyInt("fuzz", -1);
  if (fuzzCut_ < 1) fuzzCut_ = -1;
  normalizeCurves_ = !analyzeArgs.hasKey("rawcurve");
  if (analyzeArgs.hasKey("greater"))
    Compare_ = Compare_GreaterThan;
  else if (analyzeArgs.hasKey("less"))
    Compare_ = Compare_LessThan;
  else
    Compare_ = Compare_GreaterThan;
  // Select datasets from remaining args
  if (inputDsets_.AddSetsFromArgs( analyzeArgs.RemainingArgs(), *datasetlist )) {
    mprinterr("Error: lifetime: Could not add data sets.\n");
    return Analysis::ERR;
  }
  // Sort data sets
  if (sortSets) inputDsets_.SortArray1D(); 

  // Create output datasets
  DataFile* outfile = 0;
  DataFile* maxfile = 0;
  DataFile* avgfile = 0;
  if (setname.empty())
    setname = datasetlist->GenerateDefaultName( "lifetime" );
  if ( windowSize_ != -1) {
    outfile = DFLin->AddDataFile(outfileName, analyzeArgs);
    if (!averageonly_ && outfile != 0) {
      maxfile = DFLin->AddDataFile(outfileName.DirPrefix() + "max." + 
                                   outfileName.Base(), analyzeArgs);
      avgfile = DFLin->AddDataFile(outfileName.DirPrefix() + "avg." + 
                                   outfileName.Base(), analyzeArgs);
    }
    int didx = 0;
    for (Array1D::const_iterator set = inputDsets_.begin(); set != inputDsets_.end(); ++set)
    {
      MetaData md(setname, didx);
      md.SetLegend( (*set)->Meta().Legend() );
      DataSet_1D* outSet = (DataSet_1D*)datasetlist->AddSet( DataSet::FLOAT, md );
      if (CheckDsetError(outSet, "output", (*set)->legend())) 
        return Analysis::ERR;
      outputDsets_.push_back( outSet );
      if (outfile != 0) outfile->AddDataSet( outSet );
      if (!averageonly_) {
        // MAX
        md.SetAspect("max");
        outSet = (DataSet_1D*)datasetlist->AddSet(DataSet::INTEGER, md);
        if (CheckDsetError(outSet, "lifetime max", (*set)->legend()))
          return Analysis::ERR;
        maxDsets_.push_back( outSet );
        if (maxfile != 0) maxfile->AddDataSet( outSet );
        // AVG
        md.SetAspect("avg");
        outSet = (DataSet_1D*)datasetlist->AddSet(DataSet::FLOAT, md);
        if (CheckDsetError(outSet, "lifetime avg", (*set)->legend()))
          return Analysis::ERR;
        avgDsets_.push_back( outSet );
        if (avgfile != 0) avgfile->AddDataSet( outSet );
      }
      ++didx;
    }
    // Set step to window size.
    std::string fileArgs = "xstep " + integerToString( windowSize_ ); 
    if (outfile != 0) outfile->ProcessArgs( fileArgs );
    if (maxfile != 0) maxfile->ProcessArgs( fileArgs );
    if (avgfile != 0) avgfile->ProcessArgs( fileArgs );
  }
  // Lifetime curves
  DataFile* crvfile = 0;
  if (!averageonly_) {
    if (!outfileName.empty()) {
      crvfile = DFLin->AddDataFile(outfileName.DirPrefix() + "crv." + 
                                   outfileName.Base(), analyzeArgs);
    }
    MetaData md(setname, "curve");
    for (int didx = 0; didx != (int)inputDsets_.size(); didx++)
    {
      md.SetIdx(didx);
      DataSet_1D* outSet = (DataSet_1D*)datasetlist->AddSet(DataSet::DOUBLE, md);
      if (CheckDsetError(outSet, "lifetime curve", inputDsets_[didx]->legend()))
        return Analysis::ERR;
      curveSets_.push_back( outSet );
      if (crvfile != 0) crvfile->AddDataSet( outSet );
    }
  }
  // Non-window output file
  if (!averageonly_ && windowSize_ == -1) {
    standalone_ = DFLin->AddCpptrajFile( outfileName, "Lifetimes", DataFileList::TEXT, true );
    if (standalone_ == 0) return Analysis::ERR;
  } else
    standalone_ = 0; 

  if (!averageonly_)
    mprintf("    LIFETIME: Calculating average lifetime using a cutoff of %f", cut_);
  else
    mprintf("    LIFETIME: Calculating only averages");
  mprintf(" of data in %i sets\n", inputDsets_.size());
  if (!sortSets) mprintf("\tInput data sets will not be sorted.\n");
  if (debugIn > 0)
    for (Array1D::const_iterator set = inputDsets_.begin(); set != inputDsets_.end(); ++set)
      mprintf("\t%s\n", (*set)->legend());
  if (Compare_ == Compare_GreaterThan) 
    mprintf("\tValues greater than %f are considered present.\n", cut_);
  else
    mprintf("\tValues less than %f are considered present.\n", cut_);
  if (windowSize_ != -1) {
    mprintf("\tAverage of data over windows will be saved to sets named %s\n",
            setname.c_str());
    mprintf("\tWindow size for averaging: %i\n", windowSize_);
    if (cumulative_)
      mprintf("\tCumulative averages will be saved.\n");
    if (deltaAvg_)
      mprintf("\tChange of average from previous average will be saved.\n");
  }
  if (outfile != 0) {
    mprintf("\tOutfile: %s", outfile->DataFilename().full());
    if (!averageonly_ && outfile != 0)
      mprintf(", %s, %s", maxfile->DataFilename().base(), avgfile->DataFilename().base());
    mprintf("\n");
  }
  if (!averageonly_) {
    if (crvfile != 0)
      mprintf("\tLifetime curves output: %s\n", crvfile->DataFilename().base());
    if (normalizeCurves_)
      mprintf("\tLifetime curves will be normalized.\n");
    else
      mprintf("\tLifetime curves will not be normalized.\n");
  }
  if (fuzzCut_ != -1)
    mprintf("\tFuzz value of %i frames will be used.\n", fuzzCut_);
  return Analysis::OK;
}
コード例 #5
0
ファイル: Analysis_Modes.cpp プロジェクト: swails/cpptraj
// Analysis_Modes::Setup()
Analysis::RetType Analysis_Modes::Setup(ArgList& analyzeArgs, AnalysisSetup& setup, int debugIn)
{
  debug_ = debugIn;
  // Analysis type
  if (analyzeArgs.hasKey("fluct"))
    type_ = FLUCT;
  else if (analyzeArgs.hasKey("displ"))
    type_ = DISPLACE;
  else if (analyzeArgs.hasKey("corr"))
    type_ = CORR;
  else if (analyzeArgs.Contains("trajout"))
    type_ = TRAJ;
  else if (analyzeArgs.hasKey("eigenval"))
    type_ = EIGENVAL;
  else if (analyzeArgs.hasKey("rmsip"))
    type_ = RMSIP;
  else {
    mprinterr("Error: No analysis type specified.\n");
    return Analysis::ERR;
  }

  // Get modes name
  std::string modesfile = analyzeArgs.GetStringKey("name");
  if (modesfile.empty()) {
    // Check for deprecated args
    CheckDeprecated(analyzeArgs, modesfile, "file");
    CheckDeprecated(analyzeArgs, modesfile, "stack");
    if (modesfile.empty()) {
      mprinterr("Error: No 'name <modes data set name>' argument given.\n");
      return Analysis::ERR;
    }
  }
  // Get second modes name for RMSIP
  std::string modesfile2 = analyzeArgs.GetStringKey("name2");
  if (type_ == RMSIP) {
    if (modesfile2.empty()) {
      mprinterr("Error: 'rmsip' requires second modes data 'name2 <modes>'\n");
      return Analysis::ERR;
    }
  } else
    modesfile2.clear();
  // Get topology for TRAJ/CORR
  Topology* analyzeParm = setup.DSL().GetTopology( analyzeArgs ); 

  if (type_ == TRAJ ) {
    // Get trajectory format args for projected traj
    beg_ = analyzeArgs.getKeyInt("beg",1) - 1; // Args start at 1
    std::string tOutName = analyzeArgs.GetStringKey("trajout");
    if (tOutName.empty()) {
      mprinterr("Error: Require output trajectory filename, 'trajout <name>'\n");
      return Analysis::ERR;
    }
    TrajectoryFile::TrajFormatType tOutFmt = TrajectoryFile::UNKNOWN_TRAJ;
    if ( analyzeArgs.Contains("trajoutfmt") )
      tOutFmt = TrajectoryFile::GetFormatFromString( analyzeArgs.GetStringKey("trajoutfmt") );
    if (analyzeParm == 0) {
      mprinterr("Error: Could not get topology for output trajectory.\n");
      return Analysis::ERR;
    }
    AtomMask tOutMask( analyzeArgs.GetStringKey("trajoutmask") );
    if ( analyzeParm->SetupIntegerMask( tOutMask ) || tOutMask.None() ) {
      mprinterr("Error: Could not setup output trajectory mask.\n");
      return Analysis::ERR;
    }
    tOutMask.MaskInfo();
    // Strip topology to match mask.
    if (tOutParm_ != 0) delete tOutParm_;
    tOutParm_ = analyzeParm->modifyStateByMask( tOutMask );
    if (tOutParm_ == 0) {
      mprinterr("Error: Could not create topology to match mask.\n");
      return Analysis::ERR;
    }
    // Setup output traj
    if (trajout_.InitTrajWrite( tOutName, ArgList(), tOutFmt ) != 0) {
      mprinterr("Error: Could not init output trajectory.\n");
      return Analysis::ERR;
    }
    // Get min and max for PC
    pcmin_ = analyzeArgs.getKeyDouble("pcmin", -10.0);
    pcmax_ = analyzeArgs.getKeyDouble("pcmax",  10.0);
    if (pcmax_ < pcmin_ || pcmax_ - pcmin_ < Constants::SMALL) {
      mprinterr("Error: pcmin must be less than pcmax\n");
      return Analysis::ERR;
    }
    tMode_ = analyzeArgs.getKeyInt("tmode", 1);
  } else {
    // Args for everything else
    beg_ = analyzeArgs.getKeyInt("beg",7) - 1; // Args start at 1
    bose_ = analyzeArgs.hasKey("bose");
    calcAll_ = analyzeArgs.hasKey("calcall");
  }
  end_ = analyzeArgs.getKeyInt("end", 50);
  factor_ = analyzeArgs.getKeyDouble("factor",1.0);
  std::string setname = analyzeArgs.GetStringKey("setname");

  // Check if modes name exists on the stack
  modinfo_ = (DataSet_Modes*)setup.DSL().FindSetOfType( modesfile, DataSet::MODES );
  if (modinfo_ == 0) {
    mprinterr("Error: '%s' not found: %s\n", modesfile.c_str(), DataSet_Modes::DeprecateFileMsg);
    return Analysis::ERR;
  }
  if (!modesfile2.empty()) {
    modinfo2_ = (DataSet_Modes*)setup.DSL().FindSetOfType( modesfile2, DataSet::MODES );
    if (modinfo2_ == 0) {
      mprinterr("Error: Set %s not found.\n", modesfile2.c_str());
      return Analysis::ERR;
    }
  }

  // Check modes type for specified analysis
  if (type_ == FLUCT || type_ == DISPLACE || type_ == CORR || type_ == TRAJ) {
    if (modinfo_->Meta().ScalarType() != MetaData::COVAR && 
        modinfo_->Meta().ScalarType() != MetaData::MWCOVAR)
    {
      mprinterr("Error: Modes must be of type COVAR or MWCOVAR for %s.\n",
                analysisTypeString[type_]);
      return Analysis::ERR;
    }
  }

  // Get output filename for types that use DataSets
  std::string outfilename = analyzeArgs.GetStringKey("out"); // TODO all datafile?
  DataFile* dataout = 0;
  if (type_ == FLUCT || type_ == DISPLACE || type_ == EIGENVAL || type_ == RMSIP)
    dataout = setup.DFL().AddDataFile( outfilename, analyzeArgs );
  else if (type_ == CORR) {
    // CORR-specific setup
    outfile_ = setup.DFL().AddCpptrajFile( outfilename, "Modes analysis",
                                           DataFileList::TEXT, true );
    if (outfile_ == 0) return Analysis::ERR;
    // Get list of atom pairs
    if (analyzeParm == 0) {
      mprinterr("Error: 'corr' requires topology.\n");
      return Analysis::ERR;
    }
    std::string maskexp = analyzeArgs.GetStringKey("mask1");
    if (maskexp.empty()) {
      while (analyzeArgs.hasKey("maskp")) {
        // Next two arguments should be one-atom masks
        std::string a1mask = analyzeArgs.GetMaskNext();
        std::string a2mask = analyzeArgs.GetMaskNext();
        if (a1mask.empty() || a2mask.empty()) {
          mprinterr("Error: For 'corr' two 1-atom masks are expected.\n");
          return Analysis::ERR;
        }
        // Check that each mask is just 1 atom
        AtomMask m1( a1mask );
        AtomMask m2( a2mask );
        analyzeParm->SetupIntegerMask( m1 ); 
        analyzeParm->SetupIntegerMask( m2 );
        if ( m1.Nselected()==1 && m2.Nselected()==1 )
          // Store atom pair
          atompairStack_.push_back( std::pair<int,int>( m1[0], m2[0] ) );
        else {
          mprinterr("Error: For 'corr', masks should specify only one atom.\n"
                    "\tM1[%s]=%i atoms, M2[%s]=%i atoms.\n", m1.MaskString(), m1.Nselected(),
                    m2.MaskString(), m2.Nselected());
          return Analysis::ERR;
        }
      }
    } else {
      AtomMask mask1( maskexp );
      maskexp = analyzeArgs.GetStringKey("mask2");
      if (maskexp.empty()) {
        mprinterr("Error: 'mask2' must be specified if 'mask1' is.\n");
        return Analysis::ERR;
      }
      AtomMask mask2( maskexp );
      if ( analyzeParm->SetupIntegerMask( mask1 ) ) return Analysis::ERR;
      if ( analyzeParm->SetupIntegerMask( mask2 ) ) return Analysis::ERR;
      mask1.MaskInfo();
      mask2.MaskInfo();
      if (mask1.None() || mask2.None()) {
        mprinterr("Error: One or both masks are empty.\n");
        return Analysis::ERR;
      }
      if (mask1.Nselected() != mask2.Nselected()) {
        mprinterr("Error: # atoms in mask 1 not equal to # atoms in mask 2.\n");
        return Analysis::ERR;
      }
      for (int idx = 0; idx != mask1.Nselected(); idx++)
        atompairStack_.push_back( std::pair<int,int>( mask1[idx], mask2[idx] ) );
    }
    if ( atompairStack_.empty() ) {
      mprinterr("Error: No atom pairs found (use 'maskp' or 'mask1'/'mask2' keywords.)\n");
      return Analysis::ERR;
    }
  }

  // Set up data sets
  Dimension Xdim;
  if (type_ == FLUCT) {
    if (setname.empty()) setname = setup.DSL().GenerateDefaultName("FLUCT");
    MetaData md(setname, "rmsX");
    OutSets_.resize( 4, 0 );
    OutSets_[RMSX] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    md.SetAspect("rmsY");
    OutSets_[RMSY] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    md.SetAspect("rmsZ");
    OutSets_[RMSZ] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    md.SetAspect("rms");
    OutSets_[RMS]  = setup.DSL().AddSet( DataSet::DOUBLE, md );
    Xdim = Dimension(1, 1, "Atom_no.");
  } else if (type_ == DISPLACE) {
    if (setname.empty()) setname = setup.DSL().GenerateDefaultName("DISPL");
    MetaData md(setname, "displX");
    OutSets_.resize( 3, 0 );
    OutSets_[RMSX] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    md.SetAspect("displY");
    OutSets_[RMSY] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    md.SetAspect("displZ");
    OutSets_[RMSZ] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    Xdim = Dimension(1, 1, "Atom_no.");
  } else if (type_ == EIGENVAL) {
    if (setname.empty()) setname = setup.DSL().GenerateDefaultName("XEVAL");
    MetaData md(setname, "Frac");
    OutSets_.resize( 3, 0 );
    OutSets_[0] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    md.SetAspect("Cumulative");
    OutSets_[1] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    md.SetAspect("Eigenval");
    OutSets_[2] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    Xdim = Dimension( 1, 1, "Mode" );
  } else if (type_ == RMSIP) {
    if (setname.empty()) setname = setup.DSL().GenerateDefaultName("RMSIP");
    OutSets_.push_back( setup.DSL().AddSet( DataSet::DOUBLE, setname ) );
    if (dataout != 0) dataout->ProcessArgs("noxcol");
    OutSets_[0]->SetupFormat() = TextFormat(TextFormat::GDOUBLE);
    OutSets_[0]->SetLegend( modinfo_->Meta().Legend() + "_X_" + modinfo2_->Meta().Legend() );
  }
  for (std::vector<DataSet*>::const_iterator set = OutSets_.begin(); set != OutSets_.end(); ++set)
  {
    if (*set == 0) return Analysis::ERR;
    if (dataout != 0) dataout->AddDataSet( *set );
    (*set)->SetDim(Dimension::X, Xdim);
  }

  // Status
  mprintf("    ANALYZE MODES: Calculating %s using modes from %s", 
          analysisTypeString[type_], modinfo_->legend());
  if ( type_ != TRAJ ) {
    if (type_ != EIGENVAL)
      mprintf(", modes %i to %i", beg_+1, end_);
    if (outfile_ != 0)
      mprintf("\n\tResults are written to %s\n", outfile_->Filename().full());
    else if (dataout != 0)
      mprintf("\n\tResults are written to '%s'\n", dataout->DataFilename().full());
    if (type_ != EIGENVAL && type_ != RMSIP) {
      if (bose_)
        mprintf("\tBose statistics used.\n");
      else
        mprintf("\tBoltzmann statistics used.\n");
      if (calcAll_)
        mprintf("\tEigenvectors associated with zero or negative eigenvalues will be used.\n");
      else
        mprintf("\tEigenvectors associated with zero or negative eigenvalues will be skipped.\n");
    }
    if (type_ == DISPLACE)
      mprintf("\tFactor for displacement: %f\n", factor_);
    if (type_ == CORR) {
      mprintf("\tUsing the following atom pairs:");
      for (modestack_it apair = atompairStack_.begin();
                        apair != atompairStack_.end(); ++apair)
        mprintf(" (%i,%i)", apair->first+1, apair->second+1 );
      mprintf("\n");
    }
    if (type_ == RMSIP)
      mprintf("\tRMSIP calculated to modes in %s\n", modinfo2_->legend());
  } else {
    mprintf("\n\tCreating trajectory for mode %i\n"
              "\tWriting to trajectory %s\n"
              "\tPC range: %f to %f\n"
              "\tScaling factor: %f\n", tMode_, 
            trajout_.Traj().Filename().full(), pcmin_, pcmax_, factor_);
  }

  return Analysis::OK;
}