// Action_AreaPerMol::Init()
Action::RetType Action_AreaPerMol::Init(ArgList& actionArgs, TopologyList* PFL, DataSetList* DSL, DataFileList* DFL, int debugIn)
{
  // Get keywords
  DataFile* outfile = DFL->AddDataFile( actionArgs.GetStringKey("out"), actionArgs );
  if (actionArgs.hasKey("xy")) areaType_ = XY;
  else if (actionArgs.hasKey("xz")) areaType_ = XZ;
  else if (actionArgs.hasKey("yz")) areaType_ = YZ;
  else areaType_ = XY;

  Nmols_ = (double)actionArgs.getKeyInt("nmols", -1);

  // Get Masks
  if (Nmols_ < 0.0) {
    Nlayers_ = (double)actionArgs.getKeyInt("nlayers", 1);
    if (Nlayers_ < 1.0) {
      mprinterr("Error: Number of layers must be > 0\n");
      return Action::ERR;
    }
    Mask1_.SetMaskString( actionArgs.GetMaskNext() );
  }

  // DataSet
  area_per_mol_ = DSL->AddSet(DataSet::DOUBLE, actionArgs.GetStringNext(),"APM");
  if (area_per_mol_==0) return Action::ERR;
  // Add DataSet to DataFileList
  if (outfile != 0) outfile->AddDataSet( area_per_mol_ );

  mprintf("    AREAPERMOL: Calculating %s area per molecule", APMSTRING[areaType_]);
  if (Mask1_.MaskStringSet())
    mprintf(" using mask '%s', %.0f layers.\n", Mask1_.MaskString(), Nlayers_);
  else
    mprintf(" for %.0f mols\n", Nmols_);

  return Action::OK;
}
示例#2
0
// Cluster_Kmeans::SetupCluster()
int Cluster_Kmeans::SetupCluster(ArgList& analyzeArgs) {
  nclusters_ = analyzeArgs.getKeyInt("clusters", -1);
  if (nclusters_ < 2) {
    mprinterr("Error: Specify number of clusters > 1 for K-means algorithm.\n");
    return 1;
  }
  if (analyzeArgs.hasKey("randompoint"))
    mode_ = RANDOM;
  else
    mode_ = SEQUENTIAL;
  kseed_ = analyzeArgs.getKeyInt("kseed", -1);
  maxIt_ = analyzeArgs.getKeyInt("maxit", 100);
  return 0;
}
示例#3
0
// -----------------------------------------------------------------------------
/// Convert next Xplor-style selection 'resid X name A' resnum/atom name 
static inline int GetAssignSelection(std::string& aName, ArgList& line, int offset)
{
  int resnum = line.getKeyInt("resid",0) + offset;
  if (resnum < 1) return -1;
  aName = line.GetStringKey("name");
  return resnum;
}
示例#4
0
// Exec_DataSetCmd::Make2D()
Exec::RetType Exec_DataSetCmd::Make2D(CpptrajState& State, ArgList& argIn) {
  std::string name = argIn.GetStringKey("name");
  int ncols = argIn.getKeyInt("ncols", 0);
  int nrows = argIn.getKeyInt("nrows", 0);
  if (ncols <= 0 || nrows <= 0) {
    mprinterr("Error: Must specify both ncols and nrows\n");
    return CpptrajState::ERR;
  }
  DataSet* ds1 = State.DSL().GetDataSet( argIn.GetStringNext() );
  if (ds1 == 0) return CpptrajState::ERR;
  if (ds1->Ndim() != 1) {
    mprinterr("Error: make2d only works for 1D data sets.\n");
    return CpptrajState::ERR;
  }
  if (nrows * ncols != (int)ds1->Size()) {
    mprinterr("Error: Size of '%s' (%zu) != nrows X ncols.\n", ds1->legend(), ds1->Size());
    return CpptrajState::ERR;
  }
  if (name.empty())
    name = State.DSL().GenerateDefaultName("make2d");
  MetaData md(name, MetaData::M_MATRIX);
  DataSet* ds3 = State.DSL().AddSet( DataSet::MATRIX_DBL, md );
  
  if (ds3 == 0) return CpptrajState::ERR;
  mprintf("\tConverting values from 1D set '%s' to 2D matrix '%s' with %i cols, %i rows.\n",
          ds1->legend(), ds3->legend(), ncols, nrows);
  DataSet_1D const& data = static_cast<DataSet_1D const&>( *ds1 );
  DataSet_MatrixDbl& matrix = static_cast<DataSet_MatrixDbl&>( *ds3 );
  if (matrix.Allocate2D( ncols, nrows )) return CpptrajState::ERR;
  for (unsigned int idx = 0; idx != data.Size(); idx++)
    matrix.AddElement( data.Dval(idx) );
  return CpptrajState::OK;
}
示例#5
0
// Traj_SQM::processWriteArgs()
int Traj_SQM::processWriteArgs(ArgList& argIn) {
  if (argIn.Contains("charge")) {
    charge_ = argIn.getKeyInt( "charge", 0 );
    chargeIsSet_ = true;
  } else
    chargeIsSet_ = false;
  return 0;
}
// Action_VelocityAutoCorr::Init()
Action::RetType Action_VelocityAutoCorr::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
  if (actionArgs.hasKey("usevelocity")) {
    mprinterr("Error: The 'usevelocity' keyword is deprecated. Velocity information\n"
              "Error:   is now used by default if present. To force cpptraj to use\n"
              "Error:   coordinates to estimate velocities (not recommended) use the\n"
              "Error:   'usecoords' keyword.\n");
    return Action::ERR;
  }
  useVelInfo_ = !actionArgs.hasKey("usecoords");
  if (mask_.SetMaskString( actionArgs.GetMaskNext() )) return Action::ERR;
  DataFile* outfile =  init.DFL().AddDataFile( actionArgs.GetStringKey("out"), actionArgs );
  diffout_ = init.DFL().AddCpptrajFile( actionArgs.GetStringKey("diffout"),
                                        "VAC diffusion constants", DataFileList::TEXT, true );
  maxLag_ = actionArgs.getKeyInt("maxlag", -1);
  tstep_ = actionArgs.getKeyDouble("tstep", 1.0);
  useFFT_ = !actionArgs.hasKey("direct");
  normalize_ = actionArgs.hasKey("norm");
  // Set up output data set
  VAC_ = init.DSL().AddSet(DataSet::DOUBLE, actionArgs.GetStringNext(), "VAC");
  if (VAC_ == 0) return Action::ERR;
  // TODO: This should just be a scalar
  diffConst_ = init.DSL().AddSet(DataSet::DOUBLE,
                                 MetaData(VAC_->Meta().Name(), "D", MetaData::NOT_TS));
  if (diffConst_ == 0) return Action::ERR;
  if (outfile != 0) outfile->AddDataSet( VAC_ );
# ifdef MPI
  trajComm_ = init.TrajComm(); 
  if (trajComm_.Size() > 1 && !useVelInfo_)
    mprintf("\nWarning: When calculating velocities between consecutive frames,\n"
            "\nWarning:   'velocityautocorr' in parallel will not work correctly if\n"
            "\nWarning:   coordinates have been modified by previous actions (e.g. 'rms').\n\n");
  diffConst_->SetNeedsSync( false );
# endif
  mprintf("    VELOCITYAUTOCORR:\n"
          "\tCalculate velocity auto-correlation function for atoms in mask '%s'\n",
          mask_.MaskString());
  if (useVelInfo_)
    mprintf("\tUsing velocity information present in frames.\n");
  else
    mprintf("\tCalculating velocities between consecutive frames from coordinates.\n");
  if (outfile != 0)
    mprintf("\tOutput velocity autocorrelation function '%s' to '%s'\n", VAC_->legend(), 
            outfile->DataFilename().full());
  mprintf("\tWriting diffusion constants to '%s'\n", diffout_->Filename().full());
  if (maxLag_ < 1)
    mprintf("\tMaximum lag will be half total # of frames");
  else
    mprintf("\tMaximum lag is %i frames", maxLag_);
  mprintf(", time step between frames is %f ps\n", tstep_);
  if (useFFT_)
    mprintf("\tUsing FFT to calculate autocorrelation function.\n");
  else
    mprintf("\tUsing direct method to calculate autocorrelation function.\n");
  if (normalize_)
    mprintf("\tNormalizing autocorrelation function to 1.0\n");
  return Action::OK;
}
// Analysis_Wavelet::Setup
Analysis::RetType Analysis_Wavelet::Setup(ArgList& analyzeArgs, DataSetList* datasetlist,
        TopologyList* PFLin, DataFileList* DFLin, int debugIn)
{
    // Attempt to get COORDS DataSet from DataSetList. If none specified the
    // default COORDS set will be used.
    std::string setname = analyzeArgs.GetStringKey("crdset");
    coords_ = (DataSet_Coords*)datasetlist->FindCoordsSet( setname );
    if (coords_ == 0) {
        mprinterr("Error: Could not locate COORDS set corresponding to %s\n", setname.c_str());
        return Analysis::ERR;
    }
    // Get keywords
    DataFile* outfile = DFLin->AddDataFile( analyzeArgs.GetStringKey("out"), analyzeArgs );
    setname = analyzeArgs.GetStringKey("name");
    // TODO: Check defaults
    nb_ = analyzeArgs.getKeyInt("nb", 0); // FIXME: Should be more descriptive? nscale?
    if (nb_ < 1) {
        mprinterr("Error: Scaling number must be > 0\n");
        return Analysis::ERR;
    }
    S0_ = analyzeArgs.getKeyDouble("s0", 0.2);
    ds_ = analyzeArgs.getKeyDouble("ds", 1.0/3.0);
    correction_ = analyzeArgs.getKeyDouble("correction", 1.01);
    chival_ = analyzeArgs.getKeyDouble("chival", 0.2231);
    // Wavelet type: default to Morlet
    std::string wavelet_name = analyzeArgs.GetStringKey("type");
    if (wavelet_name.empty())
        wavelet_type_ = W_MORLET;
    else {
        wavelet_type_ = W_NONE;
        for (int itoken = 0; itoken != (int)W_NONE; itoken++)
            if (wavelet_name.compare(Tokens_[itoken].key_) == 0) {
                wavelet_type_ = (WaveletType)itoken;
                break;
            }
        if (wavelet_type_ == W_NONE) {
            mprinterr("Error: Unrecognized wavelet type: %s\n", wavelet_name.c_str());
            return Analysis::ERR;
        }
    }
    // Atom mask
    mask_.SetMaskString( analyzeArgs.GetMaskNext() );
    // Set up output data set
    output_ = datasetlist->AddSet( DataSet::MATRIX_FLT, setname, "WAVELET" );
    if (output_ == 0) return Analysis::ERR;
    if (outfile != 0) outfile->AddDataSet( output_ );

    mprintf("    WAVELET: Using COORDS set '%s', wavelet type %s\n",
            coords_->legend(), Tokens_[wavelet_type_].description_);
    mprintf("\tCalculating for atoms in mask '%s'\n", mask_.MaskString());
    mprintf("\tScaling wavelet %i times starting from %g with delta of %g\n",
            nb_, S0_, ds_);
    mprintf("\tCorrection: %g\n", correction_);
    mprintf("\tChiVal:     %g\n", chival_);
    if (outfile != 0) mprintf("\tOutput to '%s'\n", outfile->DataFilename().full());

    return Analysis::OK;
}
示例#8
0
// DataIO_Std::processReadArgs()
int DataIO_Std::processReadArgs(ArgList& argIn) {
  mode_ = READ1D;
  if (argIn.hasKey("read1d")) mode_ = READ1D;
  else if (argIn.hasKey("read2d")) mode_ = READ2D;
  else if (argIn.hasKey("read3d")) mode_ = READ3D;
  else if (argIn.hasKey("vector")) mode_ = READVEC;
  else if (argIn.hasKey("mat3x3")) mode_ = READMAT3X3;
  indexcol_ = argIn.getKeyInt("index", -1);
  // Column user args start from 1.
  if (indexcol_ == 0) {
    mprinterr("Error: Column numbering for standard data files starts from 1.\n");
    return 1;
  }
  if (indexcol_ > 0) --indexcol_;
  std::string ocarg = argIn.GetStringKey("onlycols");
  if (!ocarg.empty()) {
    onlycols_.SetRange( ocarg );
    onlycols_.ShiftBy( -1 );
  }
  // Options for 3d
  if (mode_ == READ3D) {
    if (Get3Double(argIn.GetStringKey("origin"), origin_, originSpecified_)) return 1;
    if (Get3Double(argIn.GetStringKey("delta"),  delta_,  deltaSpecified_ )) return 1;

    std::string dimKey = argIn.GetStringKey("dims");
    if (!dimKey.empty()) {
      ArgList oArg(dimKey, ",");
      if (oArg.Nargs() != 3) {
        mprinterr("Error: Expected 3 comma-separated values for 'dims'.\n");
        return 1;
      }
      dims_[0] = oArg.getNextInteger(dims_[0]);
      dims_[1] = oArg.getNextInteger(dims_[1]);
      dims_[2] = oArg.getNextInteger(dims_[2]);
    }
    // TODO precision for 1d and 2d too
    std::string precKey = argIn.GetStringKey("prec");
    if (!precKey.empty()) {
      if (precKey == "flt") prec_ = FLOAT;
      else if (precKey == "dbl") prec_ = DOUBLE;
      else {
        mprinterr("Error: Expected only 'flt' or 'dbl' for keyword 'prec'\n");
        return 1;
      }
    }
    std::string binKey = argIn.GetStringKey("bin");
    if (!binKey.empty()) {
      if (binKey == "center") binCorners_ = false;
      else if (binKey == "corner") binCorners_ = true;
      else {
        mprinterr("Error: Expected only 'center' or 'corner' for keyword 'bin'\n");
        return 1;
      }
    }
  }
  return 0;
}
Analysis::RetType Analysis_AutoCorr::Setup(ArgList& analyzeArgs, DataSetList* datasetlist,
                            TopologyList* PFLin, DataFileList* DFLin, int debugIn)
{
  const char* calctype;

  std::string setname = analyzeArgs.GetStringKey("name");
  DataFile* outfile = DFLin->AddDataFile( analyzeArgs.GetStringKey("out"), analyzeArgs );
  lagmax_ = analyzeArgs.getKeyInt("lagmax",-1);
  calc_covar_ = !analyzeArgs.hasKey("nocovar");
  usefft_ = !analyzeArgs.hasKey("direct");
  // Select datasets from remaining args
  ArgList dsetArgs = analyzeArgs.RemainingArgs();
  for (ArgList::const_iterator dsa = dsetArgs.begin(); dsa != dsetArgs.end(); ++dsa)
    dsets_ += datasetlist->GetMultipleSets( *dsa );
  if (dsets_.empty()) {
    mprinterr("Error: autocorr: No data sets selected.\n");
    return Analysis::ERR;
  }
  // If setname is empty generate a default name
  if (setname.empty())
    setname = datasetlist->GenerateDefaultName( "autocorr" );
  // Setup output datasets
  int idx = 0;
  MetaData md( setname );
  for (DataSetList::const_iterator DS = dsets_.begin(); DS != dsets_.end(); ++DS) {
    md.SetIdx( idx++ );
    DataSet* dsout = datasetlist->AddSet( DataSet::DOUBLE, md );
    if (dsout==0) return Analysis::ERR;
    dsout->SetLegend( (*DS)->Meta().Legend() );
    outputData_.push_back( dsout );
    // Add set to output file
    if (outfile != 0) outfile->AddDataSet( outputData_.back() );
  }
 
  if (calc_covar_)
    calctype = "covariance";
  else
    calctype = "correlation";
 
  mprintf("    AUTOCORR: Calculating auto-%s for %i data sets:\n", calctype, dsets_.size());
  dsets_.List();
  if (lagmax_!=-1)
    mprintf("\tLag max= %i\n", lagmax_);
  if ( !setname.empty() )
    mprintf("\tSet name: %s\n", setname.c_str() );
  if ( outfile != 0 )
    mprintf("\tOutfile name: %s\n", outfile->DataFilename().base());
  if (usefft_)
    mprintf("\tUsing FFT to calculate %s.\n", calctype);
  else
    mprintf("\tUsing direct method to calculate %s.\n", calctype);

  return Analysis::OK;
}
示例#10
0
// Action_AtomicCorr::Init()
Action::RetType Action_AtomicCorr::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
  debug_ = debugIn;
  outfile_ = init.DFL().AddDataFile( actionArgs.GetStringKey("out"), actionArgs );
  cut_ = actionArgs.getKeyDouble("cut", 0.0);
  if (cut_ < 0.0 || cut_ > 1.0) {
    mprinterr("Error: cut value must be between 0 and 1.\n");
    return Action::ERR;
  }
  min_ = actionArgs.getKeyInt("min",0);
  if (actionArgs.hasKey("byatom"))
    acorr_mode_ = ATOM;
  else if (actionArgs.hasKey("byres"))
    acorr_mode_ = RES;
  mask_.SetMaskString( actionArgs.GetMaskNext() );
  
  // Set up DataSet
  dset_ = init.DSL().AddSet( DataSet::MATRIX_FLT, actionArgs.GetStringNext(), "ACorr" );
  if (dset_ == 0) {
    mprinterr("Error: Could not allocate output data set.\n");
    return Action::ERR;
  }
  // Add DataSet to output file
  if (outfile_ != 0) outfile_->AddDataSet( dset_ );

  mprintf("    ATOMICCORR: Correlation of %s motions will be calculated for\n",
          ModeString[acorr_mode_]);
  mprintf("\tatoms in mask [%s]", mask_.MaskString());
  if (outfile_ != 0) mprintf(", output to file %s", outfile_->DataFilename().full());
  mprintf("\n\tData saved in set '%s'\n", dset_->legend());
  if (cut_ != 0)
    mprintf("\tOnly correlations greater than %.2f or less than -%.2f will be printed.\n",
            cut_,cut_);
  if (min_!=0)
    mprintf("\tOnly correlations for %ss > %i apart will be calculated.\n",
            ModeString[acorr_mode_],min_);
# ifdef MPI
  trajComm_ = init.TrajComm();
  if (trajComm_.Size() > 1)
    mprintf("\nWarning: 'atomiccorr' in parallel will not work correctly if coordinates have\n"
              "Warning:   been modified by previous actions (e.g. 'rms').\n\n");
  // Since matrix calc only happens in Print(), no sync needed.
  dset_->SetNeedsSync( false );
# endif
  return Action::OK;
}
示例#11
0
// Action_VelocityAutoCorr::Init()
Action::RetType Action_VelocityAutoCorr::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
  useVelInfo_ = actionArgs.hasKey("usevelocity");
  mask_.SetMaskString( actionArgs.GetMaskNext() );
  DataFile* outfile =  init.DFL().AddDataFile( actionArgs.GetStringKey("out"), actionArgs );
  maxLag_ = actionArgs.getKeyInt("maxlag", -1);
  tstep_ = actionArgs.getKeyDouble("tstep", 1.0);
  useFFT_ = !actionArgs.hasKey("direct");
  normalize_ = actionArgs.hasKey("norm");
  // Set up output data set
  VAC_ = init.DSL().AddSet(DataSet::DOUBLE, actionArgs.GetStringNext(), "VAC");
  if (VAC_ == 0) return Action::ERR;
  if (outfile != 0) outfile->AddDataSet( VAC_ );
# ifdef MPI
  trajComm_ = init.TrajComm(); 
  if (trajComm_.Size() > 1 && !useVelInfo_)
    mprintf("\nWarning: When calculating velocities between consecutive frames,\n"
            "\nWarning:   'velocityautocorr' in parallel will not work correctly if\n"
            "\nWarning:   coordinates have been modified by previous actions (e.g. 'rms').\n\n");
# endif
  mprintf("    VELOCITYAUTOCORR:\n"
          "\tCalculate velocity auto-correlation function for atoms in mask '%s'\n",
          mask_.MaskString());
  if (useVelInfo_)
    mprintf("\tUsing velocity information present in frames.\n");
  else
    mprintf("\tCalculating velocities between consecutive frames.\n");
  if (outfile != 0)
    mprintf("\tOutput data set '%s' to '%s'\n", VAC_->legend(), 
            outfile->DataFilename().full());
  if (maxLag_ < 1)
    mprintf("\tMaximum lag will be half total # of frames");
  else
    mprintf("\tMaximum lag is %i frames", maxLag_);
  mprintf(", time step is %f ps\n", tstep_);
  if (useFFT_)
    mprintf("\tUsing FFT to calculate autocorrelation function.\n");
  else
    mprintf("\tUsing direct method to calculate autocorrelation function.\n");
  if (normalize_)
    mprintf("\tNormalizing autocorrelation function to 1.0\n");
  return Action::OK;
}
示例#12
0
int Cluster_DPeaks::SetupCluster(ArgList& analyzeArgs) {
  epsilon_ = analyzeArgs.getKeyDouble("epsilon", -1.0);
  if (epsilon_ <= 0.0) {
    mprinterr("Error: DPeaks requires epsilon to be set and > 0.0\n"
              "Error: Use 'epsilon <e>'\n");
    return 1;
  }
  densityCut_ = analyzeArgs.getKeyDouble("densitycut", -1.0);
  distanceCut_ = analyzeArgs.getKeyDouble("distancecut", -1.0);
  calc_noise_ = analyzeArgs.hasKey("noise");
  dvdfile_ = analyzeArgs.GetStringKey("dvdfile");
  rafile_ = analyzeArgs.GetStringKey("runavg");
  radelta_ = analyzeArgs.GetStringKey("deltafile");
  avg_factor_ = analyzeArgs.getKeyInt("avgfactor", -1);
  if (avg_factor_ != -1 && avg_factor_ < 1) {
    mprinterr("Error: avgfactor must be >= 1.\n");
    return 1;
  }
  useGaussianKernel_ = analyzeArgs.hasKey("gauss");
  // Determine how peaks will be chosen. Default is not to choose peaks,
  // just print out density versus distance for manual choice.
  choosePoints_ = PLOT_ONLY;
  std::string choose_keyword = analyzeArgs.GetStringKey("choosepoints");
  if (!choose_keyword.empty()) {
    if      (choose_keyword == "manual") choosePoints_ = MANUAL;
    else if (choose_keyword == "auto"  ) choosePoints_ = AUTOMATIC;
    else {
      mprinterr("Error: Unrecognized choosepoints keyword: %s\n", choose_keyword.c_str());
      return 1;
    }
  }
  if (choosePoints_ == PLOT_ONLY && dvdfile_.empty())
    dvdfile_.assign("DensityVsDistance.dat");
  else if ( choosePoints_ == MANUAL &&
            (distanceCut_ < 0.0 || densityCut_ < 0.0) )
  {
    mprinterr("Error: For choosepoints manual must specify distancecut and densitycut.\n");
    return 1;
  }
  return 0;
}
示例#13
0
// Action_RandomizeIons::Init()
Action::RetType Action_RandomizeIons::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
  debug_ = debugIn;
  // Get first mask
  std::string ionmask = actionArgs.GetMaskNext();
  if (ionmask.empty()) {
    mprinterr("Error: randomizeions: No mask for ions specified.\n");
    return Action::ERR;
  }
  ions_.SetMaskString( ionmask );

  // Get Keywords
  image_.InitImaging( !actionArgs.hasKey("noimage") );
  int seed = actionArgs.getKeyInt("seed", -1);
  overlap_ = actionArgs.getKeyDouble("overlap", 3.5);
  min_ = actionArgs.getKeyDouble("by", 3.5);
  // Pre-square overlap and min
  overlap_ *= overlap_;
  min_ *= min_;
  // If no around mask specified, leave blank
  std::string aroundmask = actionArgs.GetStringKey("around");
  if (!aroundmask.empty())
    around_.SetMaskString( aroundmask );
  
  // INFO
  mprintf("    RANDOMIZEIONS: Swapping postions of ions in mask '%s' with solvent.\n",
          ions_.MaskString());
  mprintf("\tNo ion can get closer than %.2f angstroms to another ion.\n", sqrt( overlap_ ));
  if (around_.MaskStringSet())
    mprintf("\tNo ion can get closer than %.2f angstroms to atoms in mask '%s'\n",
            sqrt( min_ ), around_.MaskString());
  if (!image_.UseImage())
    mprintf("\tImaging of the coordinates will not be performed.\n");
  if (seed > 0)
    mprintf("\tRandom number generator seed is %i\n", seed);
  RN_.rn_set( seed );

  return Action::OK;
}
示例#14
0
// Action_AtomicCorr::Init()
Action::RetType Action_AtomicCorr::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
  debug_ = debugIn;
  outfile_ = init.DFL().AddDataFile( actionArgs.GetStringKey("out"), actionArgs );
  cut_ = actionArgs.getKeyDouble("cut", 0.0);
  if (cut_ < 0.0 || cut_ > 1.0) {
    mprinterr("Error: cut value must be between 0 and 1.\n");
    return Action::ERR;
  }
  min_ = actionArgs.getKeyInt("min",0);
  if (actionArgs.hasKey("byatom"))
    acorr_mode_ = ATOM;
  else if (actionArgs.hasKey("byres"))
    acorr_mode_ = RES;
  mask_.SetMaskString( actionArgs.GetMaskNext() );
  
  // Set up DataSet
  dset_ = init.DSL().AddSet( DataSet::MATRIX_FLT, actionArgs.GetStringNext(), "ACorr" );
  if (dset_ == 0) {
    mprinterr("Error: Could not allocate output data set.\n");
    return Action::ERR;
  }
  // Add DataSet to output file
  if (outfile_ != 0) outfile_->AddDataSet( dset_ );

  mprintf("    ATOMICCORR: Correlation of %s motions will be calculated for\n",
          ModeString[acorr_mode_]);
  mprintf("\tatoms in mask [%s]", mask_.MaskString());
  if (outfile_ != 0) mprintf(", output to file %s", outfile_->DataFilename().full());
  mprintf("\n\tData saved in set '%s'\n", dset_->legend());
  if (cut_ != 0)
    mprintf("\tOnly correlations greater than %.2f or less than -%.2f will be printed.\n",
            cut_,cut_);
  if (min_!=0)
    mprintf("\tOnly correlations for %ss > %i apart will be calculated.\n",
            ModeString[acorr_mode_],min_);

  return Action::OK;
}
示例#15
0
/** Search for a REF_FRAME DataSet. Provided for backwards compatibility
  * with the FrameList::GetFrameFromArgs() routine.
  * The keywords in order of precedence are:
  *   - 'ref <name>'  : Get reference frame by full/base filename or tag.
  *   - 'reference'   : First reference frame in list.
  *   - 'refindex <#>': Reference frame at position.
  */
ReferenceFrame DataSetList::GetReferenceFrame(ArgList& argIn) const {
    DataSet* ref = 0;
    // 'ref <name>'
    std::string refname = argIn.GetStringKey("ref");
    if (!refname.empty()) {
        ref = FindSetOfType( refname, DataSet::REF_FRAME );
        if (ref == 0) {
            mprinterr("Error: Reference '%s' not found.\n", refname.c_str());
            return ReferenceFrame(1);
        }
    } else {
        int refindex = argIn.getKeyInt("refindex", -1);
        if (argIn.hasKey("reference")) refindex = 0;
        if (refindex > -1 && refindex < (int)RefList_.size())
            ref = RefList_[refindex];
        if (refindex != -1 && ref == 0) {
            mprinterr("Error: Reference index %i not found.\n", refindex);
            return ReferenceFrame(1);
        }
    }
    return ReferenceFrame((DataSet_Coords_REF*)ref);
}
示例#16
0
int Cluster_DBSCAN::SetupCluster(ArgList& analyzeArgs) {
  kdist_.SetRange(analyzeArgs.GetStringKey("kdist"));
  if (kdist_.Empty()) {
    minPoints_ = analyzeArgs.getKeyInt("minpoints", -1);
    if (minPoints_ < 1) {
      mprinterr("Error: DBSCAN requires minimum # of points to be set and >= 1\n"
                "Error: Use 'minpoints <N>'\n");
      return 1;
    }
    epsilon_ = analyzeArgs.getKeyDouble("epsilon", -1.0);
    if (epsilon_ <= 0.0) {
      mprinterr("Error: DBSCAN requires epsilon to be set and > 0.0\n"
                "Error: Use 'epsilon <e>'\n");
      return 1;
    }
    sieveToCentroid_ = !analyzeArgs.hasKey("sievetoframe");
  } else {
    k_prefix_ = analyzeArgs.GetStringKey("kfile");
    if (!k_prefix_.empty() && k_prefix_.at(k_prefix_.size()-1) != '/')
      k_prefix_ += '/';
  }
  return 0;
}
// Action_Temperature::Init()
Action::RetType Action_Temperature::Init(ArgList& actionArgs, TopologyList* PFL, DataSetList* DSL, DataFileList* DFL, int debugIn)
{
  // Keywords
  if (actionArgs.hasKey("frame")) {
    getTempFromFrame_ = true;
    shakeType_ = OFF;
    degrees_of_freedom_ = 0;
  } else {
    getTempFromFrame_ = false;
    int ntc = actionArgs.getKeyInt("ntc",-1);
    if (ntc != -1) {
      if (ntc < 1 || ntc > 3) {
        mprinterr("Error: temperature: ntc must be 1, 2, or 3\n");
        return Action::ERR;
      }
      shakeType_ = (ShakeType)(ntc - 1);
    } else
      shakeType_ = OFF;
  }
  DataFile* outfile = DFL->AddDataFile( actionArgs.GetStringKey("out"), actionArgs );
  // Masks
  if (!getTempFromFrame_)
    Mask_.SetMaskString( actionArgs.GetMaskNext() );
  // DataSet 
  Tdata_ =  DSL->AddSet(DataSet::DOUBLE, actionArgs.GetStringNext(), "Tdata");
  if (Tdata_ == 0) return Action::ERR;
  if (outfile != 0) outfile->AddDataSet( Tdata_ );
  
  if (getTempFromFrame_) {
    mprintf("    TEMPERATURE: Frame temperatures will be saved in data set %s\n",
             Tdata_->legend());
  } else {
    mprintf("    TEMPERATURE: Calculate temperature for atoms in mask [%s]\n", Mask_.MaskString());
    mprintf("\tUsing SHAKE (ntc) value of [%s]\n", ShakeString[shakeType_]);
  }
  return Action::OK;
}
示例#18
0
// 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;
}
示例#19
0
Analysis::RetType Analysis_Spline::Setup(ArgList& analyzeArgs, DataSetList* datasetlist, DataFileList* DFLin, int debugIn)
{
  std::string setname = analyzeArgs.GetStringKey("name");
  outfile_ = DFLin->AddDataFile(analyzeArgs.GetStringKey("out"), analyzeArgs);
  meshsize_ = analyzeArgs.getKeyInt("meshsize", 0);
  meshfactor_ = -1.0;
  if (meshsize_ < 3) {
    meshfactor_ = analyzeArgs.getKeyDouble("meshfactor", -1.0);
    if (meshfactor_ < Constants::SMALL) {
      mprinterr("Error: Either meshsize must be specified and > 2, or meshfactor must be\n"
                "Error:   specified and > 0.0\n");
      return Analysis::ERR;
    }
  }
  if (analyzeArgs.Contains("meshmin")) {
    meshmin_ = analyzeArgs.getKeyDouble("meshmin", 0.0);
    useDefaultMin_ = true;
  } else
    useDefaultMin_ = false;
  if (analyzeArgs.Contains("meshmax")) {
    meshmax_ = analyzeArgs.getKeyDouble("meshmax", -1.0);
    useDefaultMax_ = true;
  } else
    useDefaultMax_ = false;
  if (useDefaultMin_ && useDefaultMax_ && meshmax_ < meshmin_) {
    mprinterr("Error: meshmax must be > meshmin\n");
    return Analysis::ERR;
  }
  // Select datasets from remaining args
  if (input_dsets_.AddSetsFromArgs( analyzeArgs.RemainingArgs(), *datasetlist )) {
    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;
  }

  // Set up output datasets
  Dimension Xdim( meshmin_, (meshmax_ - meshmin_) / (double)meshsize_ );
  for (Array1D::const_iterator dsIn = input_dsets_.begin();
                               dsIn != input_dsets_.end(); ++dsIn)
  {
    DataSet* ds = datasetlist->AddSet(DataSet::XYMESH, setname, "Spline");
    if (ds == 0) return Analysis::ERR;
    ds->SetLegend( "Spline(" + (*dsIn)->Meta().Legend() + ")" );
    // TODO: Set individually based on input_dsets_
    ds->SetDim(Dimension::X, Xdim);
    if (outfile_ != 0) outfile_->AddDataSet( ds );
    output_dsets_.push_back( (DataSet_Mesh*)ds );
  }

  mprintf("    SPLINE: Applying cubic splining to %u data sets\n", input_dsets_.size());
  if (meshfactor_ < 0)
    mprintf("\tMesh size= %i\n", meshsize_);
  else
    mprintf("\tMesh size will be input set size multiplied by %f\n", meshfactor_);
  if (useDefaultMin_)
    mprintf("\tMesh min= %f,", meshmin_);
  else
    mprintf("\tMesh min will be input set min,");
  if (useDefaultMax_)
    mprintf(" Mesh max= %f\n", meshmax_);
  else
    mprintf(" Mesh max will be input set max.\n");
  if (outfile_ != 0) {
    if (!setname.empty())
      mprintf("\tOutput set name: %s\n", setname.c_str());
    mprintf("\tOutfile name: %s\n", outfile_->DataFilename().base());
  }
  //for (Array1D::const_iterator set = input_dsets_.begin(); set != input_dsets_.end(); ++set)
  //  mprintf("\t%s\n", (*set)->legend());
  return Analysis::OK;
}
示例#20
0
// Analysis_CrdFluct::Setup()
Analysis::RetType Analysis_CrdFluct::Setup(ArgList& analyzeArgs, DataSetList* datasetlist, DataFileList* DFLin, int debugIn)
{
  bfactor_ = analyzeArgs.hasKey("bfactor");
  // Attempt to get coords dataset from datasetlist
  std::string setname = analyzeArgs.GetStringKey("crdset");
  coords_ = (DataSet_Coords*)datasetlist->FindCoordsSet( setname );
  if (coords_ == 0) {
    mprinterr("Error: crdfluct: Could not locate COORDS set corresponding to %s\n",
              setname.c_str());
    return Analysis::ERR;
  }
  DataFile* outfile = DFLin->AddDataFile( analyzeArgs.GetStringKey("out"), analyzeArgs );
  windowSize_ = analyzeArgs.getKeyInt("window", -1);
  // Get mask
  mask_.SetMaskString( analyzeArgs.GetMaskNext() );

  mprintf("    CRDFLUCT: Atomic fluctuations will be calcd for set %s, mask [%s]\n", 
          coords_->legend(), mask_.MaskString());
  if (windowSize_ != -1) mprintf("\tWindow size = %i\n", windowSize_);
  if (outfile != 0) mprintf("\tOutput to %s\n", outfile->DataFilename().base());

  // Set up data sets
  setname = analyzeArgs.GetStringNext();
  if (windowSize_ < 1) {
    // Only one data set for total B-factors
    DataSet* ds = datasetlist->AddSet( DataSet::DOUBLE, setname, "fluct" );
    if (ds == 0) return Analysis::ERR;
    outSets_.push_back( ds );
    if (outfile != 0) outfile->AddDataSet( ds );
  } else {
    if (coords_->Size() == 0) {
      mprinterr("Error: window size > 0 and COORDS data set %s is empty.\n", 
                 coords_->legend());
      mprinterr("Error: Cannot predict how many window data sets will be needed.\n");
      return Analysis::ERR;
    }
    if (setname.empty()) setname = datasetlist->GenerateDefaultName("fluct");
    // Determine how many windows will be needed
    int nwindows = coords_->Size() / windowSize_;
    for (int win = 0; win < nwindows; ++win) {
      int frame = (win + 1) * windowSize_;
      DataSet* ds = datasetlist->AddSet( DataSet::DOUBLE, MetaData(setname, frame) );
      if (ds == 0) return Analysis::ERR;
      ds->SetLegend( "F_" + integerToString( frame ) );
      ds->SetDim( Dimension::X, Dimension(1.0, 1.0, "Atom") );
      outSets_.push_back( ds );
      if (outfile != 0) outfile->AddDataSet( ds );
    }
    if ( (coords_->Size() % windowSize_) != 0 ) {
      DataSet* ds = datasetlist->AddSet( DataSet::DOUBLE, MetaData(setname, coords_->Size()) );
      ds->SetLegend("Final");
      outSets_.push_back( ds );
      if (outfile != 0) outfile->AddDataSet( ds );
    }
    for (SetList::iterator out = outSets_.begin(); out != outSets_.end(); ++out)
      mprintf("\t%s\n", (*out)->legend());
  }
  // Setup output file
/*  if (bfactor_)
    outfile->Dim(Dimension::Y).SetLabel("B-factors");
  outfile->Dim(Dimension::X).SetLabel("Atom");*/

  return Analysis::OK;
}
示例#21
0
// -----------------------------------------------------------------------------
// Action_NMRrst::Init()
Action::RetType Action_NMRrst::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
# ifdef MPI
  if (init.TrajComm().Size() > 1) {
    mprinterr("Error: 'nmrrst' action does not work with > 1 thread (%i threads currently).\n",
              init.TrajComm().Size());
    return Action::ERR;
  }
# endif
  debug_ = debugIn;
  // Get Keywords
  Image_.InitImaging( !(actionArgs.hasKey("noimage")) );
  useMass_ = !(actionArgs.hasKey("geom"));
  findNOEs_ = actionArgs.hasKey("findnoes");
  findOutput_ = init.DFL().AddCpptrajFile(actionArgs.GetStringKey("findout"), "Found NOEs",
                                    DataFileList::TEXT, true);
  specOutput_ = init.DFL().AddCpptrajFile(actionArgs.GetStringKey("specout"), "Specified NOEs",
                                    DataFileList::TEXT, true);
  if (findOutput_ == 0 || specOutput_ == 0) return Action::ERR;
  resOffset_ = actionArgs.getKeyInt("resoffset", 0);
  DataFile* outfile = init.DFL().AddDataFile( actionArgs.GetStringKey("out"), actionArgs );
  max_cut_ = actionArgs.getKeyDouble("cut", 6.0);
  strong_cut_ = actionArgs.getKeyDouble("strongcut", 2.9);
  medium_cut_ = actionArgs.getKeyDouble("mediumcut", 3.5);
  weak_cut_ = actionArgs.getKeyDouble("weakcut", 5.0);
  series_ = actionArgs.hasKey("series");
  std::string rstfilename = actionArgs.GetStringKey("file");
  viewrst_ = actionArgs.GetStringKey("viewrst");
  setname_ = actionArgs.GetStringKey("name");
  if (setname_.empty())
    setname_ = init.DSL().GenerateDefaultName("NMR");
  nframes_ = 0;

  // Atom Mask
  Mask_.SetMaskString( actionArgs.GetMaskNext() );

  // Pairs specified on command line.
  std::string pair1 = actionArgs.GetStringKey("pair");
  while (!pair1.empty()) {
    std::string pair2 = actionArgs.GetStringNext();
    if (pair2.empty()) {
      mprinterr("Error: Only one mask specified for pair (%s)\n", pair1.c_str());
      return Action::ERR;
    }
    Pairs_.push_back( MaskPairType(AtomMask(pair1), AtomMask(pair2)) );
    pair1 = actionArgs.GetStringKey("pair");
  }

  // Check that something will be done
  if (!findNOEs_ && rstfilename.empty() && Pairs_.empty()) {
    mprinterr("Error: Must specify restraint file, 'pair', and/or 'findnoes'.\n");
    return Action::ERR;
  }

  // Read in NMR restraints.
  if (!rstfilename.empty()) {
    if (ReadNmrRestraints( rstfilename )) return Action::ERR;
  }

  // Set up distances.
  int num_noe = 1;
  for (noeDataArray::iterator noe = NOEs_.begin(); noe != NOEs_.end(); ++noe, ++num_noe) {
    // Translate any ambiguous atom names
    TranslateAmbiguous( noe->aName1_ ); 
    TranslateAmbiguous( noe->aName2_ );
    // Create mask expressions from resnum/atom name
    noe->dMask1_.SetMaskString( MaskExpression( noe->resNum1_, noe->aName1_ ) ); 
    noe->dMask2_.SetMaskString( MaskExpression( noe->resNum2_, noe->aName2_ ) ); 
    // Dataset to store distances
    AssociatedData_NOE noeData(noe->bound_, noe->boundh_, noe->rexp_);
    MetaData md(setname_, "NOE", num_noe);
    md.SetLegend( noe->dMask1_.MaskExpression() + " and " + noe->dMask2_.MaskExpression());
    md.SetScalarMode( MetaData::M_DISTANCE );
    md.SetScalarType( MetaData::NOE );
    noe->dist_ = init.DSL().AddSet(DataSet::DOUBLE, md);
    if (noe->dist_==0) return Action::ERR;
    noe->dist_->AssociateData( &noeData );
    // Add dataset to data file
    if (outfile != 0) outfile->AddDataSet( noe->dist_ );
  }

  masterDSL_ = init.DslPtr();
 
  mprintf("Warning: *** THIS ACTION IS EXPERIMENTAL. ***\n");
  mprintf("    NMRRST: %zu NOEs from NMR restraint file.\n", NOEs_.size());
  mprintf("\tShifting residue numbers in restraint file by %i\n", resOffset_);
  // DEBUG - print NOEs
  for (noeDataArray::const_iterator noe = NOEs_.begin(); noe != NOEs_.end(); ++noe)
    mprintf("\t'%s'  %f < %f < %f\n", noe->dist_->legend(),
            noe->bound_, noe->rexp_, noe->boundh_);
  if (findNOEs_) {
    mprintf("\tSearching for potential NOEs. Max cutoff is %g Ang.\n", max_cut_);
    mprintf("\tNOE distance criteria (Ang.): S= %g, M= %g, W= %g\n",
            strong_cut_, medium_cut_, weak_cut_);
    if (series_)
      mprintf("\tDistance data for NOEs less than cutoff will be saved as '%s[foundNOE]'.\n",
              setname_.c_str());
    mprintf("\tFound NOEs will be written to '%s'\n", findOutput_->Filename().full());
  }
  if (!Pairs_.empty()) {
    mprintf("\tSpecified NOE pairs:\n");
    for (MaskPairArray::const_iterator mp = Pairs_.begin(); mp != Pairs_.end(); ++mp)
      mprintf("\t\t[%s] to [%s]\n", mp->first.MaskString(), mp->second.MaskString());
    mprintf("\tSpecified NOE data will be written to '%s'\n", specOutput_->Filename().full());
  }
  if (!Image_.UseImage()) 
    mprintf("\tNon-imaged");
  else
    mprintf("\tImaged");
  if (useMass_) 
    mprintf(", center of mass.\n");
  else
    mprintf(", geometric center.\n");
  if (!viewrst_.empty())
    mprintf("\tTopologies corresponding to found NOEs will be written to '%s'\n", viewrst_.c_str());

  return Action::OK;
}
示例#22
0
// Analysis_KDE::Setup()
Analysis::RetType Analysis_KDE::Setup(ArgList& analyzeArgs, AnalysisSetup& setup, int debugIn)
{
  if (analyzeArgs.Contains("min")) {
    default_min_ = analyzeArgs.getKeyDouble("min", 0.0);
    minArgSet_ = true;
  }
  if (analyzeArgs.Contains("max")) {
    default_max_ = analyzeArgs.getKeyDouble("max", 0.0);
    maxArgSet_ = true;
  }
  default_step_ = analyzeArgs.getKeyDouble("step", 0.0);
  default_bins_ = analyzeArgs.getKeyInt("bins", -1);
  if (default_step_ == 0.0 && default_bins_ < 1) {
    mprinterr("Error: Must set either bins or step.\n");
    return Analysis::ERR;
  }
  Temp_ = analyzeArgs.getKeyDouble("free",-1.0);
  if (Temp_!=-1.0) 
    calcFreeE_ = true;
  else
    calcFreeE_ = false;
  std::string setname = analyzeArgs.GetStringKey("name");
  bandwidth_ = analyzeArgs.getKeyDouble("bandwidth", -1.0);
  DataFile* outfile = setup.DFL().AddDataFile( analyzeArgs.GetStringKey("out"), analyzeArgs );
  DataFile* klOutfile = 0;
  // Get second data set for KL divergence calc.
  std::string q_dsname = analyzeArgs.GetStringKey("kldiv");
  if (!q_dsname.empty()) {
    q_data_ = setup.DSL().GetDataSet( q_dsname );
    if (q_data_ == 0) {
      mprinterr("Error: Data set %s not found.\n", q_dsname.c_str());
      return Analysis::ERR;
    }
    if (q_data_->Ndim() != 1) {
      mprinterr("Error: Only 1D data sets supported.\n");
      return Analysis::ERR;
    }
    klOutfile = setup.DFL().AddDataFile( analyzeArgs.GetStringKey("klout"), analyzeArgs );
  } else {
    q_data_ = 0;
    kldiv_ = 0;
  }
  // Get AMD boost data set
  std::string amdname = analyzeArgs.GetStringKey("amd");
  if (!amdname.empty()) {
    amddata_ = setup.DSL().GetDataSet( amdname );
    if (amddata_ == 0) {
      mprinterr("Error: AMD data set %s not found.\n", amdname.c_str());
      return Analysis::ERR;
    }
    if (amddata_->Ndim() != 1) {
      mprinterr("Error: AMD data set must be 1D.\n");
      return Analysis::ERR;
    }
  } else
    amddata_ = 0;

  // Get data set
  data_ = setup.DSL().GetDataSet( analyzeArgs.GetStringNext() );
  if (data_ == 0) {
    mprinterr("Error: No data set or invalid data set name specified\n");
    return Analysis::ERR;
  }
  if (data_->Ndim() != 1) {
    mprinterr("Error: Only 1D data sets supported.\n");
    return Analysis::ERR;
  }
  
  // Output data set
  output_ = setup.DSL().AddSet(DataSet::DOUBLE, setname, "kde");
  if (output_ == 0) return Analysis::ERR;
  if (outfile != 0) outfile->AddDataSet( output_ );
  // Output for KL divergence calc.
  if ( q_data_ != 0 ) {
    kldiv_ = setup.DSL().AddSet(DataSet::DOUBLE, MetaData(output_->Meta().Name(), "kld"));
    if (klOutfile != 0) klOutfile->AddDataSet( kldiv_ );
  }

  mprintf("    KDE: Using gaussian KDE to histogram set \"%s\"\n", data_->legend());
  if (amddata_!=0)
    mprintf("\tPopulating bins using AMD boost from data set %s\n",
            amddata_->legend());
  if (q_data_ != 0) {
    mprintf("\tCalculating Kullback-Leibler divergence with set \"%s\"\n", 
            q_data_->legend());
  }
  if (bandwidth_ < 0.0)
    mprintf("\tBandwidth will be estimated.\n");
  else
    mprintf("\tBandwidth= %f\n", bandwidth_);
  if (calcFreeE_)
    mprintf("\tFree energy in kcal/mol will be calculated from bin populations at %f K.\n",Temp_);
  return Analysis::OK;
}
示例#23
0
int SequenceAlign(CpptrajState& State, ArgList& argIn) {
  std::string blastfile = argIn.GetStringKey("blastfile");
  if (blastfile.empty()) {
    mprinterr("Error: 'blastfile' must be specified.\n");
    return 1;
  }
  ReferenceFrame qref = State.DSL()->GetReferenceFrame(argIn);
  if (qref.error() || qref.empty()) {
    mprinterr("Error: Must specify reference structure for query.\n");
    return 1;
  }
  std::string outfilename = argIn.GetStringKey("out");
  if (outfilename.empty()) {
    mprinterr("Error: Must specify output file.\n");
    return 1;
  }
  TrajectoryFile::TrajFormatType fmt = TrajectoryFile::GetFormatFromArg(argIn);
  if (fmt != TrajectoryFile::PDBFILE && fmt != TrajectoryFile::MOL2FILE)
    fmt = TrajectoryFile::PDBFILE; // Default to PDB
  int smaskoffset = argIn.getKeyInt("smaskoffset", 0) + 1;
  int qmaskoffset = argIn.getKeyInt("qmaskoffset", 0) + 1;

  // Load blast file
  mprintf("\tReading BLAST alignment from '%s'\n", blastfile.c_str());
  BufferedLine infile;
  if (infile.OpenFileRead( blastfile )) return 1;
  // Seek down to first Query line.
  const char* ptr = infile.Line();
  bool atFirstQuery = false;
  while (ptr != 0) {
    if (*ptr == 'Q') {
      if ( strncmp(ptr, "Query", 5) == 0 ) {
        atFirstQuery = true;
        break;
      }
    }
    ptr = infile.Line();
  }
  if (!atFirstQuery) {
    mprinterr("Error: 'Query' not found.\n");
    return 1;
  }

  // Read alignment. Replacing query with subject.
  typedef std::vector<char> Carray;
  typedef std::vector<int> Iarray;
  Carray Query; // Query residues
  Carray Sbjct; // Sbjct residues
  Iarray Smap;  // Smap[Sbjct index] = Query index
  while (ptr != 0) {
    const char* qline = ptr;           // query line
    const char* aline = infile.Line(); // alignment line
    const char* sline = infile.Line(); // subject line
    if (aline == 0 || sline == 0) {
      mprinterr("Error: Missing alignment line or subject line after Query:\n");
      mprinterr("Error:  %s", qline);
      return 1;
    }
    for (int idx = 12; qline[idx] != ' '; idx++) {
      if (qline[idx] == '-') {
        // Sbjct does not have corresponding res in Query
        Smap.push_back(-1);
        Sbjct.push_back( sline[idx] );
      } else if (sline[idx] == '-') {
        // Query does not have a corresponding res in Sbjct
        Query.push_back( qline[idx] );
      } else {
        // Direct Query to Sbjct map
        Smap.push_back( Query.size() );
        Sbjct.push_back( sline[idx] );
        Query.push_back( qline[idx] );
      }
    }
    // Scan to next Query 
    ptr = infile.Line();
    while (ptr != 0) {
      if (*ptr == 'Q') {
        if ( strncmp(ptr, "Query", 5) == 0 ) break;
      }
      ptr = infile.Line();
    }
  }
  // DEBUG
  std::string SmaskExp, QmaskExp;
  if (State.Debug() > 0) mprintf("  Map of Sbjct to Query:\n");
  for (int sres = 0; sres != (int)Sbjct.size(); sres++) {
    if (State.Debug() > 0)
      mprintf("%-i %3s %i", sres+smaskoffset, Residue::ConvertResName(Sbjct[sres]),
              Smap[sres]+qmaskoffset);
    const char* qres = "";
    if (Smap[sres] != -1) {
      qres = Residue::ConvertResName(Query[Smap[sres]]);
      if (SmaskExp.empty())
        SmaskExp.assign( integerToString(sres+smaskoffset) );
      else
        SmaskExp.append( "," + integerToString(sres+smaskoffset) );
      if (QmaskExp.empty())
        QmaskExp.assign( integerToString(Smap[sres]+qmaskoffset) );
      else
        QmaskExp.append( "," + integerToString(Smap[sres]+qmaskoffset) );

    }
    if (State.Debug() > 0) mprintf(" %3s\n", qres);
  }
  mprintf("Smask: %s\n", SmaskExp.c_str());
  mprintf("Qmask: %s\n", QmaskExp.c_str());
  // Check that query residues match reference.
  for (unsigned int sres = 0; sres != Sbjct.size(); sres++) {
    int qres = Smap[sres];
    if (qres != -1) {
      if (Query[qres] != qref.Parm().Res(qres).SingleCharName()) {
        mprintf("Warning: Potential residue mismatch: Query %s reference %s\n",
                Residue::ConvertResName(Query[qres]), qref.Parm().Res(qres).c_str());
      }
    }
  }
  // Build subject using coordinate from reference.
  //AtomMask sMask; // Contain atoms that should be in sTop
  Topology sTop;
  Frame sFrame;
  Iarray placeHolder; // Atom indices of placeholder residues.
  for (unsigned int sres = 0; sres != Sbjct.size(); sres++) {
    int qres = Smap[sres];
    NameType SresName( Residue::ConvertResName(Sbjct[sres]) );
    if (qres != -1) {
      Residue const& QR = qref.Parm().Res(qres);
      Residue SR(SresName, sres+1, ' ', QR.ChainID());
      if (Query[qres] == Sbjct[sres]) { // Exact match. All non-H atoms.
        for (int qat = QR.FirstAtom(); qat != QR.LastAtom(); qat++)
        {
          if (qref.Parm()[qat].Element() != Atom::HYDROGEN)
            sTop.AddTopAtom( qref.Parm()[qat], SR );
            sFrame.AddXYZ( qref.Coord().XYZ(qat) );
            //sMask.AddAtom(qat);
        }
      } else { // Partial match. Copy only backbone and CB.
        for (int qat = QR.FirstAtom(); qat != QR.LastAtom(); qat++)
        {
          if ( qref.Parm()[qat].Name().Match("N" ) ||
               qref.Parm()[qat].Name().Match("CA") ||
               qref.Parm()[qat].Name().Match("CB") ||
               qref.Parm()[qat].Name().Match("C" ) ||
               qref.Parm()[qat].Name().Match("O" ) )
          {
            sTop.AddTopAtom( qref.Parm()[qat], SR );
            sFrame.AddXYZ( qref.Coord().XYZ(qat) );
          }
        }
      }
    } else {
      // Residue in query does not exist for subject. Just put placeholder CA for now.
      Vec3 Zero(0.0);
      placeHolder.push_back( sTop.Natom() );
      sTop.AddTopAtom( Atom("CA", "C "), Residue(SresName, sres+1, ' ', ' ') );
      sFrame.AddXYZ( Zero.Dptr() );
    }
  }
  //sTop.PrintAtomInfo("*");
  mprintf("\tPlaceholder residue indices:");
  for (Iarray::const_iterator p = placeHolder.begin(); p != placeHolder.end(); ++p)
    mprintf(" %i", *p + 1);
  mprintf("\n");
  // Try to give placeholders more reasonable coordinates.
  if (!placeHolder.empty()) {
    Iarray current_indices;
    unsigned int pidx = 0;
    while (pidx < placeHolder.size()) {
      if (current_indices.empty()) {
        current_indices.push_back( placeHolder[pidx++] );
        // Search for the end of this segment
        for (; pidx != placeHolder.size(); pidx++) {
          if (placeHolder[pidx] - current_indices.back() > 1) break;
          current_indices.push_back( placeHolder[pidx] );
        }
        // DEBUG
        mprintf("\tSegment:");
        for (Iarray::const_iterator it = current_indices.begin();
                                    it != current_indices.end(); ++it)
          mprintf(" %i", *it + 1);
        // Get coordinates of residues bordering segment.
        int prev_res = sTop[current_indices.front()].ResNum() - 1;
        int next_res = sTop[current_indices.back() ].ResNum() + 1;
        mprintf(" (prev_res=%i, next_res=%i)\n", prev_res+1, next_res+1);
        Vec3 prev_crd(sFrame.XYZ(current_indices.front() - 1));
        Vec3 next_crd(sFrame.XYZ(current_indices.back()  + 1));
        prev_crd.Print("prev_crd");
        next_crd.Print("next_crd");
        Vec3 crd_step = (next_crd - prev_crd) / (double)(current_indices.size()+1);
        crd_step.Print("crd_step");
        double* xyz = sFrame.xAddress() + (current_indices.front() * 3);
        for (unsigned int i = 0; i != current_indices.size(); i++, xyz += 3) {
          prev_crd += crd_step;
          xyz[0] = prev_crd[0];
          xyz[1] = prev_crd[1];
          xyz[2] = prev_crd[2];
        }
        current_indices.clear();
      }
    }
  }
  //Topology* sTop = qref.Parm().partialModifyStateByMask( sMask );
  //if (sTop == 0) return 1;
  //Frame sFrame(qref.Coord(), sMask);
  // Write output traj
  Trajout_Single trajout;
  if (trajout.PrepareTrajWrite(outfilename, argIn, &sTop, CoordinateInfo(), 1, fmt)) return 1;
  if (trajout.WriteSingle(0, sFrame)) return 1;
  trajout.EndTraj();
  return 0;
}
示例#24
0
// Exec_PermuteDihedrals::Execute()
Exec::RetType Exec_PermuteDihedrals::Execute(CpptrajState& State, ArgList& argIn) {
  debug_ = State.Debug();
  mode_ = INTERVAL;
  // Get Keywords - first determine mode
  if (argIn.hasKey("random"))
    mode_ = RANDOM;
  else if (argIn.hasKey("interval"))
    mode_ = INTERVAL;
  // Get input COORDS set
  std::string setname = argIn.GetStringKey("crdset");
  if (setname.empty()) {
    mprinterr("Error: Specify COORDS dataset name with 'crdset'.\n");
    return CpptrajState::ERR;
  }
  DataSet_Coords* CRD = (DataSet_Coords*)State.DSL().FindCoordsSet( setname );
  if (CRD == 0) {
    mprinterr("Error: Could not find COORDS set '%s'\n", setname.c_str());
    return CpptrajState::ERR;
  }
  mprintf("    PERMUTEDIHEDRALS: Using COORDS '%s'\n", CRD->legend());

  // Get residue range
  Range resRange;
  resRange.SetRange(argIn.GetStringKey("resrange"));
  if (!resRange.Empty())
    resRange.ShiftBy(-1); // User res args start from 1
  mprintf("\tPermutating dihedrals in");
  if (resRange.Empty())
    mprintf(" all solute residues.\n");
  else
    mprintf(" residue range [%s]\n", resRange.RangeArg());

  // Determine which angles to search for
  DihedralSearch dihSearch;
  dihSearch.SearchForArgs(argIn);
  // If nothing is enabled, enable all 
  dihSearch.SearchForAll();
  mprintf("\tSearching for types:");
  dihSearch.PrintTypes();
  mprintf("\n");

  // Setup output trajectory
  outframe_ = 0; 
  std::string outfilename = argIn.GetStringKey("outtraj");
  if (!outfilename.empty()) {
    mprintf("\tCoordinates output to '%s'\n", outfilename.c_str());
    Topology* outtop = State.DSL().GetTopology( argIn );
    if (outtop == 0) {
      mprinterr("Error: No topology for output traj.\n");
      return CpptrajState::ERR;
    }
    // Setup output trajectory FIXME: Correct frames for # of rotations
    if (outtraj_.PrepareTrajWrite(outfilename, argIn, CRD->TopPtr(), CRD->CoordsInfo(),
                                  CRD->Size(), TrajectoryFile::UNKNOWN_TRAJ))
      return CpptrajState::ERR;
  }

  // Setup output coords
  outfilename = argIn.GetStringKey("crdout");
  if (!outfilename.empty()) {
    mprintf("\tCoordinates saved to set '%s'\n", outfilename.c_str());
    crdout_ = (DataSet_Coords_CRD*)State.DSL().AddSet(DataSet::COORDS, outfilename);
    if (crdout_ == 0) return CpptrajState::ERR;
    crdout_->CoordsSetup( CRD->Top(), CRD->CoordsInfo() );
  }

  // Get specific mode options.
  double interval_in_deg = 60.0;
  if ( mode_ == INTERVAL ) {
    interval_in_deg = argIn.getNextDouble(60.0);
    mprintf("\tDihedrals will be rotated at intervals of %.2f degrees.\n", interval_in_deg);
  } else if (mode_ == RANDOM) {
    check_for_clashes_ = argIn.hasKey("check");
    checkAllResidues_ = argIn.hasKey("checkallresidues");
    cutoff_ = argIn.getKeyDouble("cutoff",0.8);
    rescutoff_ = argIn.getKeyDouble("rescutoff",10.0);
    backtrack_ = argIn.getKeyInt("backtrack",4);
    increment_ = argIn.getKeyInt("increment",1);
    max_factor_ = argIn.getKeyInt("maxfactor",2);
    int iseed = argIn.getKeyInt("rseed",-1);
    // Output file for # of problems
    DataFile* problemFile = State.DFL().AddDataFile(argIn.GetStringKey("out"), argIn);
    // Dataset to store number of problems
    number_of_problems_ = State.DSL().AddSet(DataSet::INTEGER, argIn.GetStringNext(),"Nprob");
    if (number_of_problems_==0) return CpptrajState::ERR;
   // Add dataset to data file list
    if (problemFile != 0) problemFile->AddDataSet(number_of_problems_);
    // Check validity of args
    if (cutoff_ < Constants::SMALL) {
      mprinterr("Error: cutoff too small.\n");
      return CpptrajState::ERR;
    }
    if (rescutoff_ < Constants::SMALL) {
      mprinterr("Error: rescutoff too small.\n");
      return CpptrajState::ERR;
    }
    if (backtrack_ < 0) {
      mprinterr("Error: backtrack value must be >= 0\n");
      return CpptrajState::ERR;
    }
    if ( increment_<1 || (360 % increment_)!=0 ) {
      mprinterr("Error: increment must be a factor of 360.\n");
      return CpptrajState::ERR;
    }
    // Calculate max increment
    max_increment_ = 360 / increment_;
    // Seed random number gen
    RN_.rn_set( iseed );
    // Print info
    mprintf("\tDihedrals will be rotated to random values.\n");
    if (iseed==-1)
      mprintf("\tRandom number generator will be seeded using time.\n");
    else
      mprintf("\tRandom number generator will be seeded using %i\n",iseed);
    if (check_for_clashes_) {
      mprintf("\tWill attempt to recover from bad steric clashes.\n");
      if (checkAllResidues_)
        mprintf("\tAll residues will be checked.\n");
      else
        mprintf("\tResidues up to the currenly rotating dihedral will be checked.\n");
      mprintf("\tAtom cutoff %.2f, residue cutoff %.2f, backtrack = %i\n",
              cutoff_, rescutoff_, backtrack_);
      mprintf("\tWhen clashes occur dihedral will be incremented by %i\n",increment_);
      mprintf("\tMax # attempted rotations = %i times number dihedrals.\n",
              max_factor_);
    }
    // Square cutoffs to compare to dist^2 instead of dist
    cutoff_ *= cutoff_;
    rescutoff_ *= rescutoff_;
    // Increment backtrack by 1 since we need to skip over current res
    ++backtrack_;
    // Initialize CheckStructure
    if (checkStructure_.SetOptions( false, false, false, State.Debug(), "*", "", 0.8, 1.15, 4.0 )) {
      mprinterr("Error: Could not set up structure check.\n");
      return CpptrajState::ERR;
    }
    // Set up CheckStructure for this parm (false = nobondcheck)
    if (checkStructure_.Setup(CRD->Top(), CRD->CoordsInfo().TrajBox()))
      return CpptrajState::ERR;
  }

  // Determine from selected mask atoms which dihedrals will be rotated.
  PermuteDihedralsType dst;
  // If range is empty (i.e. no resrange arg given) look through all 
  // solute residues.
  Range actualRange;
  if (resRange.Empty())
    actualRange = CRD->Top().SoluteResidues();
  else 
    actualRange = resRange;
  // Search for dihedrals
  if (dihSearch.FindDihedrals(CRD->Top(), actualRange))
    return CpptrajState::ERR;
  // For each found dihedral, set up mask of atoms that will move upon 
  // rotation. Also set up mask of atoms in this residue that will not
  // move, including atom2.
  if (debug_>0)
    mprintf("DEBUG: Dihedrals:\n");
  for (DihedralSearch::mask_it dih = dihSearch.begin();
                               dih != dihSearch.end(); ++dih)
  {
    dst.checkAtoms.clear();
    // Set mask of atoms that will move during dihedral rotation.
    dst.Rmask = DihedralSearch::MovingAtoms(CRD->Top(), dih->A1(), dih->A2());
    // If randomly rotating angles, check for atoms that are in the same
    // residue as A1 but will not move. They need to be checked for clashes
    // since further rotations will not help them.
    if (mode_ == RANDOM && check_for_clashes_) {
      CharMask cMask( dst.Rmask.ConvertToCharMask(), dst.Rmask.Nselected() );
      int a1res = CRD->Top()[dih->A1()].ResNum();
      for (int maskatom = CRD->Top().Res(a1res).FirstAtom();
               maskatom < CRD->Top().Res(a1res).LastAtom(); ++maskatom)
        if (!cMask.AtomInCharMask(maskatom))
          dst.checkAtoms.push_back( maskatom );
      dst.checkAtoms.push_back(dih->A1()); // TODO: Does this need to be added first?
      // Since only the second atom and atoms it is bonded to move during 
      // rotation, base the check on the residue of the second atom.
      dst.resnum = a1res;
    }
    dst.atom0 = dih->A0(); // FIXME: This duplicates info
    dst.atom1 = dih->A1();
    dst.atom2 = dih->A2();
    dst.atom3 = dih->A3();
    BB_dihedrals_.push_back(dst);
    // DEBUG: List dihedral info.
    if (debug_ > 0) {
      mprintf("\t%s-%s-%s-%s\n", 
              CRD->Top().TruncResAtomName(dih->A0()).c_str(),
              CRD->Top().TruncResAtomName(dih->A1()).c_str(),
              CRD->Top().TruncResAtomName(dih->A2()).c_str(),
              CRD->Top().TruncResAtomName(dih->A3()).c_str() );
      if (debug_ > 1 && mode_ == RANDOM && check_for_clashes_) {
        mprintf("\t\tCheckAtoms=");
        for (std::vector<int>::const_iterator ca = dst.checkAtoms.begin();
                                              ca != dst.checkAtoms.end(); ++ca)
          mprintf(" %i", *ca + 1);
        mprintf("\n");
      }
      if (debug_ > 2) {
        mprintf("\t\t");
        dst.Rmask.PrintMaskAtoms("Rmask:");
      }
    }
  }

  // Set up simple structure check. First step is coarse; check distances 
  // between a certain atom in each residue (first, COM, CA, some other atom?)
  // to see if residues are in each others neighborhood. Second step is to 
  // check the atoms in each close residue.
  if (check_for_clashes_) {
    ResidueCheckType rct;
    int res = 0;
    for (Topology::res_iterator residue = CRD->Top().ResStart();
                                residue != CRD->Top().ResEnd(); ++residue)
    {
      rct.resnum = res++;
      rct.start = residue->FirstAtom();
      rct.stop = residue->LastAtom();
      rct.checkatom = rct.start;
      ResCheck_.push_back(rct);
    }
  }

  // Perform dihedral permute
  Frame currentFrame = CRD->AllocateFrame();
  for (unsigned int set = 0; set != CRD->Size(); set++)
  {
    CRD->GetFrame(set, currentFrame);
    int n_problems = 0;
    switch (mode_) {
      case RANDOM:
        RandomizeAngles(currentFrame, CRD->Top());
        // Check the resulting structure
        n_problems = checkStructure_.CheckOverlaps( currentFrame );
        //mprintf("%i\tResulting structure has %i problems.\n",frameNum,n_problems);
        number_of_problems_->Add(set, &n_problems);
        if (outtraj_.IsInitialized()) outtraj_.WriteSingle(outframe_++, currentFrame);
        if (crdout_ != 0) crdout_->AddFrame( currentFrame );
        break;
      case INTERVAL: IntervalAngles(currentFrame, CRD->Top(), interval_in_deg); break;
    }
  }
  if (outtraj_.IsInitialized()) outtraj_.EndTraj();
  return CpptrajState::OK;
}
示例#25
0
Analysis::RetType Analysis_AutoCorr::Setup(ArgList& analyzeArgs, AnalysisSetup& setup, int debugIn)
{
  const char* calctype;

  std::string setname = analyzeArgs.GetStringKey("name");
  DataFile* outfile = setup.DFL().AddDataFile( analyzeArgs.GetStringKey("out"), analyzeArgs );
  lagmax_ = analyzeArgs.getKeyInt("lagmax",-1);
  calc_covar_ = !analyzeArgs.hasKey("nocovar");
  usefft_ = !analyzeArgs.hasKey("direct");
  // Select datasets from remaining args
  dsets_.clear();
  ArgList dsetArgs = analyzeArgs.RemainingArgs();
  for (ArgList::const_iterator dsa = dsetArgs.begin(); dsa != dsetArgs.end(); ++dsa) {
    DataSetList setsIn = setup.DSL().GetMultipleSets( *dsa );
    for (DataSetList::const_iterator ds = setsIn.begin(); ds != setsIn.end(); ++ds) {
      if ( (*ds)->Group() != DataSet::SCALAR_1D && (*ds)->Type() != DataSet::VECTOR )
        mprintf("Warning: Set '%s' type not supported in AUTOCORR - skipping.\n",
                (*ds)->legend());
      else
        dsets_.push_back( *ds );
    }
  }
  if (dsets_.empty()) {
    mprinterr("Error: No data sets selected.\n");
    return Analysis::ERR;
  }
  // If setname is empty generate a default name
  if (setname.empty())
    setname = setup.DSL().GenerateDefaultName( "autocorr" );
  // Setup output datasets
  MetaData md( setname );
  for (unsigned int idx = 0; idx != dsets_.size(); idx++) {
    md.SetIdx( idx );
    DataSet* dsout = setup.DSL().AddSet( DataSet::DOUBLE, md );
    if (dsout==0) return Analysis::ERR;
    dsout->SetLegend( dsets_[idx]->Meta().Legend() );
    outputData_.push_back( dsout );
    // Add set to output file
    if (outfile != 0) outfile->AddDataSet( outputData_.back() );
  }
 
  if (calc_covar_)
    calctype = "covariance";
  else
    calctype = "correlation";
 
  mprintf("    AUTOCORR: Calculating auto-%s for %i data sets:\n\t", calctype, dsets_.size());
  for (unsigned int idx = 0; idx != dsets_.size(); ++idx)
    mprintf(" %s", dsets_[idx]->legend());
  mprintf("\n");
  if (lagmax_!=-1)
    mprintf("\tLag max= %i\n", lagmax_);
  if ( !setname.empty() )
    mprintf("\tSet name: %s\n", setname.c_str() );
  if ( outfile != 0 )
    mprintf("\tOutfile name: %s\n", outfile->DataFilename().base());
  if (usefft_)
    mprintf("\tUsing FFT to calculate %s.\n", calctype);
  else
    mprintf("\tUsing direct method to calculate %s.\n", calctype);

  return Analysis::OK;
}
示例#26
0
// Exec_RotateDihedral::Execute()
Exec::RetType Exec_RotateDihedral::Execute(CpptrajState& State, ArgList& argIn) {
  // Get input COORDS set
  std::string setname = argIn.GetStringKey("crdset");
  if (setname.empty()) {
    mprinterr("Error: Specify COORDS dataset name with 'crdset'.\n");
    return CpptrajState::ERR;
  }
  DataSet_Coords* CRD = (DataSet_Coords*)State.DSL().FindCoordsSet( setname );
  if (CRD == 0) {
    mprinterr("Error: Could not find COORDS set '%s'\n", setname.c_str());
    return CpptrajState::ERR;
  }
  if (CRD->Size() < 1) {
    mprinterr("Error: COORDS set is empty.\n");
    return CpptrajState::ERR;
  }
  int frame = argIn.getKeyInt("frame", 0);
  if (frame < 0 || frame >= (int)CRD->Size()) {
    mprinterr("Error: Specified frame %i is out of range.\n", frame+1);
    return CpptrajState::ERR;
  }
  mprintf("    ROTATEDIHEDRAL: Using COORDS '%s', frame %i\n", CRD->legend(), frame+1);
  // Get target frame
  Frame FRM = CRD->AllocateFrame();
  CRD->GetFrame(frame, FRM);
  // Save as reference
  Frame refFrame = FRM;

  // Create output COORDS set if necessary
  DataSet_Coords* OUT = 0;
  int outframe = 0;
  std::string outname = argIn.GetStringKey("name");
  if (outname.empty()) {
    // This will not work for TRAJ data sets
    if (CRD->Type() == DataSet::TRAJ) {
      mprinterr("Error: Using TRAJ as input set requires use of 'name' keyword for output.\n");
      return CpptrajState::ERR;
    }
    OUT = CRD;
    outframe = frame;
  } else {
    // Create new output set with 1 empty frame.
    OUT = (DataSet_Coords*)State.DSL().AddSet( DataSet::COORDS, outname );
    if (OUT == 0) return CpptrajState::ERR;
    OUT->Allocate( DataSet::SizeArray(1, 1) );
    OUT->CoordsSetup( CRD->Top(), CRD->CoordsInfo() );
    OUT->AddFrame( CRD->AllocateFrame() );
    mprintf("\tOutput to set '%s'\n", OUT->legend());
  }

  // Determine whether we are setting or incrementing.
  enum ModeType { SET = 0, INCREMENT };
  ModeType mode = SET;
  if (argIn.Contains("value"))
    mode = SET;
  else if (argIn.Contains("increment"))
    mode = INCREMENT;
  else {
    mprinterr("Error: Specify 'value <value>' or 'increment <increment>'\n");
    return CpptrajState::ERR;
  }
  double value = argIn.getKeyDouble(ModeStr[mode], 0.0);
  switch (mode) {
    case SET: mprintf("\tDihedral will be set to %g degrees.\n", value); break;
    case INCREMENT: mprintf("\tDihedral will be incremented by %g degrees.\n", value); break;
  }
  // Convert to radians
  value *= Constants::DEGRAD;

  // Select dihedral atoms
  int A1, A2, A3, A4;
  if (argIn.Contains("type")) {
    // By type
    ArgList typeArg = argIn.GetStringKey("type");
    if (typeArg.empty()) {
      mprinterr("Error: No dihedral type specified after 'type'\n");
      return CpptrajState::ERR;
    }
    DihedralSearch dihSearch;
    dihSearch.SearchForArgs( typeArg );
    if (dihSearch.NoDihedralTokens()) {
      mprinterr("Error: Specified dihedral type not recognized.\n");
      return CpptrajState::ERR;
    }
    // Get residue
    int res = argIn.getKeyInt("res", -1);
    if (res <= 0) {
      mprinterr("Error: If 'type' specified 'res' must be specified and > 0.\n");
      return CpptrajState::ERR;
    }
    // Search for dihedrals. User residue #s start from 1.
    if (dihSearch.FindDihedrals(CRD->Top(), Range(res-1)))
      return CpptrajState::ERR;
    DihedralSearch::mask_it dih = dihSearch.begin();
    A1 = dih->A0();
    A2 = dih->A1();
    A3 = dih->A2();
    A4 = dih->A3();
  } else {
    // By masks
    AtomMask m1( argIn.GetMaskNext() );
    AtomMask m2( argIn.GetMaskNext() );
    AtomMask m3( argIn.GetMaskNext() );
    AtomMask m4( argIn.GetMaskNext() );
    if (CRD->Top().SetupIntegerMask( m1 )) return CpptrajState::ERR;
    if (CRD->Top().SetupIntegerMask( m2 )) return CpptrajState::ERR;
    if (CRD->Top().SetupIntegerMask( m3 )) return CpptrajState::ERR;
    if (CRD->Top().SetupIntegerMask( m4 )) return CpptrajState::ERR;
    if (m1.Nselected() != 1) return MaskError( m1 );
    if (m2.Nselected() != 1) return MaskError( m2 );
    if (m3.Nselected() != 1) return MaskError( m3 );
    if (m4.Nselected() != 1) return MaskError( m4 );
    A1 = m1[0];
    A2 = m2[0];
    A3 = m3[0];
    A4 = m4[0];
  }
  mprintf("\tRotating dihedral defined by atoms '%s'-'%s'-'%s'-'%s'\n",
          CRD->Top().AtomMaskName(A1).c_str(),
          CRD->Top().AtomMaskName(A2).c_str(),
          CRD->Top().AtomMaskName(A3).c_str(),
          CRD->Top().AtomMaskName(A4).c_str());
  // Set mask of atoms that will move during dihedral rotation
  AtomMask Rmask = DihedralSearch::MovingAtoms(CRD->Top(), A2, A3);
  // Calculate current value of dihedral
  double torsion = Torsion( FRM.XYZ(A1), FRM.XYZ(A2), FRM.XYZ(A3), FRM.XYZ(A4) );
  // Calculate delta needed to get to target value.
  double delta;
  switch (mode) {
    case SET:       delta = value - torsion; break;
    case INCREMENT: delta = value; break;
  }
  mprintf("\tOriginal torsion is %g, rotating by %g degrees.\n",
          torsion*Constants::RADDEG, delta*Constants::RADDEG);
  // Set axis of rotation
  Vec3 axisOfRotation = FRM.SetAxisOfRotation( A2, A3 );
  // Calculate rotation matrix for delta.
  Matrix_3x3 rotationMatrix;
  rotationMatrix.CalcRotationMatrix(axisOfRotation, delta);
  // Rotate around axis
  FRM.Rotate(rotationMatrix, Rmask);
  // RMS-fit the non-moving part of the coords back on original
  AtomMask refMask = Rmask;
  refMask.InvertMask();
  FRM.Align( refFrame, refMask );
  // Update coords
  OUT->SetCRD( outframe, FRM );

  return CpptrajState::OK;
}
// Analysis_Timecorr::Setup()
Analysis::RetType Analysis_Timecorr::Setup(ArgList& analyzeArgs, DataSetList* DSLin,
                            TopologyList* PFLin, DataFileList* DFLin, int debugIn)
{
  // Get Vectors
  std::string vec1name = analyzeArgs.GetStringKey("vec1");
  if (vec1name.empty()) {
    mprinterr("Error: no vec1 given, ignoring command\n");
    return Analysis::ERR;
  }
  vinfo1_ = (DataSet_Vector*)DSLin->FindSetOfType( vec1name, DataSet::VECTOR );
  if (vinfo1_==0) {
    mprinterr("Error: vec1: no vector with name %s found.\n", 
              vec1name.c_str());
    return Analysis::ERR;
  }
  std::string vec2name = analyzeArgs.GetStringKey("vec2");
  if (!vec2name.empty()) {
    vinfo2_ = (DataSet_Vector*)DSLin->FindSetOfType( vec2name, DataSet::VECTOR );
    if (vinfo2_==0) {
      mprinterr("Error: vec2: no vector with name %s found.\n", 
                vec2name.c_str());
      return Analysis::ERR;
    }
  } else
    vinfo2_ = 0;
  // Get output DataSet name
  std::string setname = analyzeArgs.GetStringKey("name");
  if (setname.empty())
    setname = DSLin->GenerateDefaultName("TC");
  // Determine auto or cross correlation 
  if (vinfo2_ == 0)
    mode_ = AUTOCORR;
  else
    mode_ = CROSSCORR;
  // Get dplr, norm, drct
  dplr_ = analyzeArgs.hasKey("dplr");
  norm_ = analyzeArgs.hasKey("norm");
  drct_ = analyzeArgs.hasKey("drct");
  std::string dplrname = analyzeArgs.GetStringKey("dplrout");
  // Get order for Legendre polynomial, tstep, and tcorr
  order_ = analyzeArgs.getKeyInt("order",2);
  if (order_ < 0 || order_ > 2) {
    mprintf("Warning: vector order out of bounds (should be 0, 1, or 2), resetting to 2.\n");
    order_ = 2;
  }
  tstep_ = analyzeArgs.getKeyDouble("tstep", 1.0);
  tcorr_ = analyzeArgs.getKeyDouble("tcorr", 10000.0);
  // File output. For ptrajformat, time correlation functions and dipolar
  // are output to file specified by 'out'. Otherwise time correlation
  // functions are written to file specified by 'out' using DataFile 
  // framework and dipolar output to 'dplrname'.
  ptrajformat_ = analyzeArgs.hasKey("ptrajformat");
  std::string filename = analyzeArgs.GetStringKey("out");
  if (ptrajformat_ && filename.empty()) {
    mprinterr("Error: No output file name given ('out <filename>'). Required for 'ptrajformat'.\n");
    return Analysis::ERR;
  }
  DataFile* dataout = 0;
  if (!ptrajformat_) {
    dataout = DFLin->AddDataFile( filename, analyzeArgs );
    if (dplr_) {
      if (!dplrname.empty() && dplrname == filename) {
        mprinterr("Error: 'dplrname' cannot be the same file as 'out' when 'ptrajformat' not specified.\n");
        return Analysis::ERR;
      }
      outfile_ = DFLin->AddCpptrajFile( dplrname, "Timecorr dipolar", DataFileList::TEXT, true );
      if (outfile_ == 0) return Analysis::ERR;
    }
  } else {
    outfile_ = DFLin->AddCpptrajFile( filename, "Timecorr output" );
    if (outfile_ == 0) return Analysis::ERR;
  }
  // Set up output DataSets
  tc_p_ = DSLin->AddSet( DataSet::DOUBLE, MetaData(setname, "P"));
  if (tc_p_ == 0) return Analysis::ERR;
  tc_p_->SetLegend( Plegend_[order_] );
  if (dataout != 0) dataout->AddDataSet( tc_p_ );
  if (dplr_) {
    tc_c_ = DSLin->AddSet( DataSet::DOUBLE, MetaData(setname, "C"));
    tc_r3r3_ = DSLin->AddSet( DataSet::DOUBLE, MetaData(setname, "R3R3"));
    if (tc_c_ == 0 || tc_r3r3_ == 0) return Analysis::ERR;
    tc_c_->SetLegend("<C>");
    tc_r3r3_->SetLegend( "<1/(r^3*r^3)>" );
    if (dataout != 0) {
      dataout->AddDataSet( tc_c_ );
      dataout->AddDataSet( tc_r3r3_ );
    }
  }

  // Print Status
  mprintf("    TIMECORR: Calculating %s", ModeString[mode_]);
  if (mode_ == AUTOCORR)
    mprintf(" of vector %s\n", vinfo1_->legend());
  else // CROSSCORR
    mprintf(" of vectors %s and %s\n", vinfo1_->legend(),
            vinfo2_->legend());
  mprintf("\tCorrelation time %f, time step %f, order %i\n", tcorr_, tstep_, order_);
  mprintf("\tCorr. func. are");
  if (dplr_)
    mprintf(" for dipolar interactions and");
  if (norm_)
    mprintf(" normalized.\n");
  else
    mprintf(" not normalized.\n");
  mprintf("\tCorr. func. are calculated using the");
  if (drct_)
    mprintf(" direct approach.\n");
  else
    mprintf(" FFT approach.\n");
  if (ptrajformat_)
    mprintf("\tResults are written to %s\n", outfile_->Filename().full());
  else {
    if (dataout != 0) mprintf("\tTime correlation functions written to %s\n", dataout->DataFilename().full());
    if (outfile_ != 0) mprintf("\tDipolar results written to %s\n", outfile_->Filename().full()); 
  }
  return Analysis::OK;
}
Analysis::RetType Analysis_CurveFit::Internal_setup(std::string const& suffixIn, ArgList& analyzeArgs, DataSetList* datasetlist, DataFileList* DFLin, int debugIn)
{
  if (dset_->Ndim() != 1) {
    mprinterr("Error: Curve fitting can only be done with 1D data sets.\n");
    return Analysis::ERR;
  }
  std::string dsoutName;
  n_expected_params_ = 0;
  // Determine if special equation is being used.
  nexp_ = analyzeArgs.getKeyInt("nexp", -1);
  bool useGauss = analyzeArgs.hasKey("gauss");
  if ( useGauss || nexp_ > 0 ) {
    // Multi-exponential/Gaussian specialized equation form.
    dsoutName = analyzeArgs.GetStringKey("name");
    if (dsoutName.empty()) {
      mprinterr("Error: 'name <OutputSetName>' must be used with 'nexp <n>' or 'gauss'\n");
      return Analysis::ERR;
    }
    equation_ = dsoutName + " = ";
    if (nexp_ > 0) {
      // Determine form
      eqForm_ = MEXP;
      std::string formStr = analyzeArgs.GetStringKey("form");
      if (!formStr.empty()) {
        if (formStr == "mexp") eqForm_ = MEXP;
        else if (formStr == "mexpk") eqForm_ = MEXP_K;
        else if (formStr == "mexpk_penalty") eqForm_ = MEXP_K_PENALTY;
        else {
          mprinterr("Error: Multi-exponential form '%s' not recognized.\n", formStr.c_str());
          return Analysis::ERR;
        }
      }
      // Set up equation
      int nparam = 0;
      if (eqForm_ != MEXP) {
        equation_.append("A0 +");
        nparam = 1;
      }
      for (int ie = 0; ie != nexp_; ie++, nparam += 2) {
        if (ie > 0)
          equation_.append(" + ");
        equation_.append("(A" + integerToString(nparam) + " * exp(X * A" + 
                               integerToString(nparam+1) + "))");
      }
      n_expected_params_ = nparam;
    } else {
      eqForm_ = GAUSS;
      n_expected_params_ = 3;
      equation_.append("A0 * exp( -((X - A1)^2) / (2 * A2^2) )");
    }
  } else {
    // Any equation form, solve with RPNcalc.
    eqForm_ = GENERAL;
    // Second argument should be the equation to fit DataSet to.
    equation_ = analyzeArgs.GetStringNext();
    if (equation_.empty()) {
      mprinterr("Error: Must specify an equation if 'nexp <n>' not specified.\n");
      return Analysis::ERR;
    }
    Calc_.SetDebug(debugIn);
    if (Calc_.ProcessExpression( equation_ )) return Analysis::ERR;
    // Equation must have an assignment.
    if ( Calc_.AssignStatus() != RPNcalc::YES_ASSIGN ) {
      mprinterr("Error: No assignment '=' in equation '%s'.\n", equation_.c_str());
      return Analysis::ERR;
    }
    dsoutName = Calc_.FirstTokenName();
    if (dsoutName.empty()) {
      mprinterr("Error: Invalid assignment in equation '%s'.\n", equation_.c_str());
      return Analysis::ERR;
    } 
    n_expected_params_ = Calc_.Nparams();
  }
  // Get keywords
  Results_ = DFLin->AddCpptrajFile( analyzeArgs.GetStringKey("resultsout"), "Curve Fit Results",
                                    DataFileList::TEXT, true );
  DataFile* outfile = DFLin->AddDataFile( analyzeArgs.GetStringKey("out"), analyzeArgs );
  tolerance_ = analyzeArgs.getKeyDouble("tol", 0.0001);
  if (tolerance_ < 0.0) {
    mprinterr("Error: Tolerance must be greater than or equal to 0.0\n");
    return Analysis::ERR;
  }
  maxIt_ = analyzeArgs.getKeyInt("maxit", 50);
  if (maxIt_ < 1) {
    mprinterr("Error: Max iterations must be greater than or equal to 1.\n");
    return Analysis::ERR;
  }
  outXbins_ = analyzeArgs.getKeyInt("outxbins", -1);
  outXmin_ = analyzeArgs.getKeyDouble("outxmin", 0.0);
  outXmax_ = analyzeArgs.getKeyDouble("outxmax", 0.0);
  if (outXbins_ > 0) {
    mprintf("%g %g\n", outXmin_, outXmax_);
    if (outXmin_ >= outXmax_) {
      mprinterr("Error: outxmin must be less than outxmax.\n");
      return Analysis::ERR;
    }
  }
  // Now get all parameters
  if (n_expected_params_ < 0) return Analysis::ERR;
  Params_.resize( n_expected_params_, 0.0 );
  n_specified_params_ = 0;
  for (int p = 0; p != n_expected_params_; p++, n_specified_params_++) {
    std::string parameterArg = analyzeArgs.GetStringNext();
    if (parameterArg.empty())
      break;
    ArgList parameter(parameterArg, " =");
    if (parameter.Nargs() != 2) {
      mprinterr("Error: Invalid parameter argument. Expected 'A<n>=<value>'\n");
      return Analysis::ERR;
    }
    std::string parameterName = parameter.GetStringNext();
    if (parameterName[0] != 'A') {
      mprinterr("Error: Invalid parameter name (expected A<n>): %s\n", parameterName.c_str());
      return Analysis::ERR;
    }
    int pnum = convertToInteger(parameterName.substr(1));
    Params_[pnum] = parameter.getNextDouble(0.0);
  }
  // Check if all params specified.
  if (n_specified_params_ != n_expected_params_)
    mprintf("Warning: # specified params (%i) less than # expected params (%i)\n",
            n_specified_params_, n_expected_params_);
  // Set up output data set.
  if (!suffixIn.empty()) dsoutName.append(suffixIn);
  finalY_ = datasetlist->AddSet(DataSet::XYMESH, dsoutName, "FIT");
  if (finalY_ == 0) return Analysis::ERR;
  if (outfile != 0) outfile->AddDataSet( finalY_ );

  mprintf("    CURVEFIT: Fitting set '%s' to equation '%s'\n",
          dset_->legend(), equation_.c_str());
  if (nexp_ > 0) {
    mprintf("\tMulti-exponential form with %i exponentials.\n", nexp_);
    if (eqForm_ == MEXP_K_PENALTY)
      mprintf("\tMulti-exponential equation constraints: sum of prefactors = 1.0,"
              " exponent parameters < 0.0\n");
  } else if (eqForm_ == GAUSS)
    mprintf("\tGaussian form.\n");
  mprintf("\tFinal Y values will be saved in set '%s'\n", finalY_->legend());
  if (outXbins_ > 0)
    mprintf("\tFinal X range: %g to %g, %i points.\n", outXmin_, outXmax_, outXbins_);
  mprintf("\tTolerance= %g, maximum iterations= %i\n", tolerance_, maxIt_);
  mprintf("\tFinal parameters and statistics for fit will be writtent to %s\n",
          Results_->Filename().full());
  if (n_specified_params_ > 0) {
    mprintf("\tInitial parameters:\n");
    for (Darray::const_iterator ip = Params_.begin(); ip != Params_.end(); ++ip)
      mprintf("\t  A%u = %g\n", ip - Params_.begin(), *ip);
  }

  return Analysis::OK;
}
示例#29
0
/** Set up histogram with specified data sets. */
Analysis::RetType Analysis_Hist::Setup(ArgList& analyzeArgs, AnalysisSetup& setup, int debugIn)
{
  debug_ = debugIn;
  // Keywords
  std::string histname = analyzeArgs.GetStringKey("name");
  outfilename_ = analyzeArgs.GetStringKey("out");
  if (outfilename_.empty()) {
    mprinterr("Error: Hist: No output filename specified.\n");
    return Analysis::ERR;
  }
  traj3dName_ = analyzeArgs.GetStringKey("traj3d");
  traj3dFmt_ = TrajectoryFile::WriteFormatFromString( analyzeArgs.GetStringKey("trajfmt"),
                                                      TrajectoryFile::AMBERTRAJ );
  parmoutName_ = analyzeArgs.GetStringKey("parmout");
  // Create a DataFile here so any DataFile arguments can be processed. If it
  // turns out later that native output is needed the DataFile will be removed.
  outfile_ = setup.DFL().AddDataFile(outfilename_, analyzeArgs);
  if (outfile_==0) return Analysis::ERR;
  Temp_ = analyzeArgs.getKeyDouble("free",-1.0);
  if (Temp_!=-1.0) 
    calcFreeE_ = true;
  else
    calcFreeE_ = false;
  gnuplot_ = analyzeArgs.hasKey("gnu");
  if (analyzeArgs.hasKey("norm"))
    normalize_ = NORM_SUM;
  else if (analyzeArgs.hasKey("normint"))
    normalize_ = NORM_INT;
  else
    normalize_ = NO_NORM;
  circular_ = analyzeArgs.hasKey("circular");
  nativeOut_ = analyzeArgs.hasKey("nativeout");
  if ( analyzeArgs.Contains("min") ) {
    default_min_ = analyzeArgs.getKeyDouble("min", 0.0);
    minArgSet_ = true;
  }
  if ( analyzeArgs.Contains("max") ) {
    default_max_ = analyzeArgs.getKeyDouble("max", 0.0);
    maxArgSet_ = true;
  }
  default_step_ = analyzeArgs.getKeyDouble("step", 0.0) ;
  default_bins_ = analyzeArgs.getKeyInt("bins", -1);
  calcAMD_ = false;
  std::string amdname = analyzeArgs.GetStringKey("amd");
  if (!amdname.empty()) {
    DataSet* ds = setup.DSL().GetDataSet( amdname );
    if (ds == 0) {
      mprinterr("Error: AMD data set %s not found.\n", amdname.c_str());
      return Analysis::ERR;
    }
    if (ds->Ndim() != 1) {
      mprinterr("Error: AMD data set must be 1D.\n");
      return Analysis::ERR;
    }
    amddata_ = (DataSet_1D*)ds;
    calcAMD_ = true;
  }

  // Treat all remaining arguments as dataset names. Do not set up dimensions
  // yet since the data sets may not be fully populated.
  ArgList dsetNames = analyzeArgs.RemainingArgs();
  for ( ArgList::const_iterator setname = dsetNames.begin(); 
                                setname != dsetNames.end(); ++setname)
  { 
    if (CheckDimension( *setname, setup.DSL() )) return Analysis::ERR;
  }
  // histdata contains the DataSets to be histogrammed
  if (histdata_.empty()) {
    mprinterr("Error: Hist: No datasets specified.\n");
    return Analysis::ERR;
  }
  // Total # of dimensions for the histogram is the number of sets to be binned.
  N_dimensions_ = histdata_.size();
  if (!nativeOut_) {
    switch ( N_dimensions_ ) {
      case 1: hist_ = setup.DSL().AddSet( DataSet::DOUBLE,     histname, "Hist"); break;
      case 2: hist_ = setup.DSL().AddSet( DataSet::MATRIX_DBL, histname, "Hist"); break;
      // TODO: GRID_DBL
      case 3: hist_ = setup.DSL().AddSet( DataSet::GRID_FLT,   histname, "Hist"); break;
      default: // FIXME: GET N DIMENSION CASE!
        mprintf("Warning: Histogram dimension > 3. DataSet/DataFile output not supported.\n");
        nativeOut_ = true;
    }
  }
  // traj3d only supported with 3D histograms
  if (!traj3dName_.empty() && N_dimensions_ != 3) {
    mprintf("Warning: 'traj3d' only supported with 3D histograms.\n");
    traj3dName_.clear();
    parmoutName_.clear();
  }
  if (!nativeOut_) {
    // DataFile output. Add DataSet to DataFile.
    if (hist_ == 0) {
      mprinterr("Error: Could not set up histogram data set.\n");
      return Analysis::ERR;
    }
    outfile_->AddDataSet( hist_ );
  } else {
    // Native output. Remove DataFile from DataFileList
    outfile_ = setup.DFL().RemoveDataFile( outfile_ );
    native_ = setup.DFL().AddCpptrajFile( outfilename_, "Histogram output" );
    if (native_ == 0) return Analysis::ERR; 
  }

  mprintf("\tHist: %s: Set up for %zu dimensions using the following datasets:\n", 
          outfilename_.c_str(), N_dimensions_);
  mprintf("\t[ ");
  for (std::vector<DataSet_1D*>::iterator ds=histdata_.begin(); ds!=histdata_.end(); ++ds)
    mprintf("%s ",(*ds)->legend());
  mprintf("]\n");
  if (calcAMD_)
    mprintf("\tPopulating bins using AMD boost from data set %s\n", 
            amddata_->legend());
  if (calcFreeE_)
    mprintf("\tFree energy in kcal/mol will be calculated from bin populations at %f K.\n",Temp_);
  if (nativeOut_)
    mprintf("\tUsing internal routine for output. Data will not be stored on the data set list.\n");
  //if (circular_ || gnuplot_) {
  //  mprintf("\tWarning: gnuplot and/or circular specified; advanced grace/gnuplot\n");
  //  mprintf("\t         formatting disabled.\n");*/
    if (circular_)
      mprintf("\tcircular: Output coordinates will be wrapped.\n");
    if (gnuplot_ && outfile_ == 0)
      mprintf("\tgnuplot: Output will be in gnuplot-readable format.\n");
  //}
  if (normalize_ == NORM_SUM)
    mprintf("\tnorm: Sum over bins will be normalized to 1.0.\n");
  else if (normalize_ == NORM_INT)
    mprintf("\tnormint: Integral over bins will be normalized to 1.0.\n");
  if (!traj3dName_.empty()) {
    mprintf("\tPseudo-trajectory will be written to '%s' with format %s\n",
            traj3dName_.c_str(), TrajectoryFile::FormatString(traj3dFmt_));
    if (!parmoutName_.empty())
      mprintf("\tCorresponding pseudo-topology will be written to '%s'\n",
              parmoutName_.c_str());
  }

  return Analysis::OK;
}
示例#30
0
// 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;
}