示例#1
0
// DataIO_Std::Get3Double()
int DataIO_Std::Get3Double(std::string const& key, Vec3& vec, bool& specified)
{
  specified = false;
  if (!key.empty()) {
    ArgList oArg(key, ",");
    if (oArg.Nargs() != 3) {
      mprinterr("Error: Expected 3 comma-separated values for '%s'\n", key.c_str());
      return 1;
    }
    vec[0] = oArg.getNextDouble(vec[0]);
    vec[1] = oArg.getNextDouble(vec[1]);
    vec[2] = oArg.getNextDouble(vec[2]);
    specified = true;
  }
  return 0;
}
示例#2
0
/** Increase size of buffer by delta elements, keeping contents intact. */
size_t BufferedFrame::ResizeBuffer(int delta) {
  if (delta == 0) return frameSize_;
  if (delta < 0) {
    mprinterr("Internal Error: ResizeBuffer: Negative value given.\n");
    return frameSize_;
  }
  size_t newsize = frameSize_ + CalcFrameSize( delta );
  char* newbuffer = new char[ newsize ];
  memcpy(newbuffer, buffer_, frameSize_);
  memset(newbuffer+frameSize_, 0, newsize - frameSize_);
  delete[] buffer_;
  buffer_ = newbuffer;
  bufferPosition_ = buffer_;
  frameSize_ = newsize;
  return frameSize_;
}
示例#3
0
// Analysis_VectorMath::Analyze()
Analysis::RetType Analysis_VectorMath::Analyze() {
  // Ensure vectors have the same # of frames
  if (vinfo1_->Size() != vinfo2_->Size()) {
    mprinterr("Error: # Frames in vec %s (%i) != # Frames in vec %s (%i)\n",
              vinfo1_->legend(), vinfo1_->Size(),
              vinfo2_->legend(), vinfo2_->Size());
    return Analysis::ERR;
  }
  int err = 0;
  if (mode_ == CROSSPRODUCT)
    err = CrossProduct();
  else // DOTPRODUCT || DOTANGLE
    err = DotProduct();
  if (err != 0) return Analysis::ERR;
  return Analysis::OK;
}
示例#4
0
/** Increase size of buffer by delta elements, keeping contents intact. */
size_t BufferedFrame::ResizeBuffer(int delta) {
  if (delta == 0) return frameSize_;
  if (delta < 0) {
    mprinterr("Internal Error: ResizeBuffer: Negative value given.\n");
    return frameSize_;
  }
  size_t newsize = frameSize_ + CalcFrameSize( delta );
  char* newbuffer = new char[ newsize + 1]; // +1 for null
  std::copy(buffer_, buffer_+frameSize_, newbuffer);
  std::fill(newbuffer+frameSize_, newbuffer+newsize, 0);
  delete[] buffer_;
  buffer_ = newbuffer;
  bufferPosition_ = buffer_;
  frameSize_ = newsize;
  return frameSize_;
}
示例#5
0
/** Read REMD indices. Input array must be allocated to be size remd_dimension
  * by prior call to NreplicaDimensions().
  */
int Traj_AmberNetcdf::readIndices(int set, int* remd_indices) {
  if (indicesVID_!=-1) {
    start_[0] = set;
    start_[1] = 0;
    count_[0] = 1;
    count_[1] = remd_dimension_;
    if ( checkNCerr(nc_get_vara_int(ncid_, indicesVID_, start_, count_, remd_indices)) ) {
      mprinterr("Error: Getting replica indices.\n");
      return 1;
    }
    //mprintf("DEBUG:\tReplica indices:");
    //for (int dim=0; dim < remd_dimension_; dim++) mprintf(" %i",remd_indices[dim]);
    //mprintf("\n");
  }
  return 0;
}
示例#6
0
// DataIO_OpenDx::WriteData()
int DataIO_OpenDx::WriteData(FileName const& fname, DataSetList const& setList)
{
  // Open output file
  CpptrajFile outfile;
  if (outfile.OpenWrite(fname)) {
    mprinterr("Error: Could not open OpenDX output file.\n");
    return 1;
  }
  // Warn about writing multiple sets
  if (setList.size() > 1)
    mprintf("Warning: %s: Writing multiple 3D sets in OpenDX format may result in unexpected behavior\n", fname.full());
  int err = 0;
  for (DataSetList::const_iterator set = setList.begin(); set != setList.end(); ++set)
    err += WriteSet3D( *(*set), outfile );
  return err;
}
示例#7
0
/** Generate a temporary file name of format:
  *   TempPrefix_<#>
  * where <#> is based on the current number of temporary file names
  * that have been requested.
  */
FileName GenTempName() {
  // Could also set this to 0, but setting it to size is a better guarantee
  // that the name will be free.
  unsigned int tmpidx = TempFileNames_.size();
  FileName temp( TempPrefix_ + integerToString(tmpidx) );
  while (tmpidx < maxtmpidx_ && Exists(temp)) {
    tmpidx++;
    temp = FileName( TempPrefix_ + integerToString(tmpidx) );
  }
  if (tmpidx >= maxtmpidx_) {
    mprinterr("Internal Error: Too many temporary files. Remove files named '%s*'\n",
              TempPrefix_.c_str());
    return FileName();
  }
  return temp;
}
示例#8
0
/** Add specified analysis to the analysis list with given args and 
  * DataSetList.
  */
int AnalysisList::AddAnalysis(DispatchObject::DispatchAllocatorType Alloc, ArgList& argIn,
                              TopologyList* PFLin, DataSetList* DSLin, DataFileList* DFLin)
{
  Analysis* ana = (Analysis*)Alloc();
  // Attempt to set up analysis
  if (ana->Setup( argIn, DSLin, PFLin, DFLin, debug_) != Analysis::OK) {
    mprinterr("Error: Could not setup analysis [%s]\n", argIn.Command());
    delete ana;
    return 1;
  }
  argIn.CheckForMoreArgs();
  analysisList_.push_back( ana );
  analysisCmd_.push_back( argIn.ArgLine() );
  analysisStatus_.push_back( SETUP );
  return 0;
}
示例#9
0
/** Create Netcdf file specified by filename and set up dimension and
  * variable IDs. 
  */
int Traj_AmberNetcdf::setupTrajout(FileName const& fname, Topology* trajParm,
                                   CoordinateInfo const& cInfoIn, 
                                   int NframesToWrite, bool append)
{
  readAccess_ = false;
  if (!append) {
    CoordinateInfo cInfo = cInfoIn;
    // Deal with output options
    // For backwards compatibility always write temperature if remdtraj is true.
    if (outputTemp_ && !cInfo.HasTemp()) cInfo.SetTemperature(true);
    // Explicitly write velocity - initial frames may not have velocity info.
    if (outputVel_ && !cInfo.HasVel()) cInfo.SetVelocity(true);
    SetCoordInfo( cInfo );
    filename_ = fname;
    // Set up title
    if (Title().empty())
      SetTitle("Cpptraj Generated trajectory");
    // Create NetCDF file.
    if (NC_create( filename_.Full(), NC_AMBERTRAJ, trajParm->Natom(), CoordInfo(), Title() ))
      return 1;
    if (debug_>1) NetcdfDebug();
    // Close Netcdf file. It will be reopened write.
    NC_close();
    // Allocate memory
    if (Coord_!=0) delete[] Coord_;
    Coord_ = new float[ Ncatom3() ];
  } else { // NOTE: File existence is checked for in Trajout
    // Call setupTrajin to set input parameters. This will also allocate
    // memory for coords.
    if (setupTrajin(fname, trajParm) == TRAJIN_ERR) return 1;
    // Check output options.
    if (outputTemp_ && !CoordInfo().HasTemp())
      mprintf("Warning: Cannot append temperature data to NetCDF file '%s'; no temperature dimension.\n",
              filename_.base());
    if (outputVel_ && !CoordInfo().HasVel())
      mprintf("Warning: Cannot append velocity data to NetCDF file '%s'; no velocity dimension.\n",
              filename_.base());
    if (debug_ > 0)
      mprintf("\tNetCDF: Appending %s starting at frame %i\n", filename_.base(), Ncframe()); 
  }
  // Open file
  if ( NC_openWrite( filename_.Full() ) != 0 ) {
    mprinterr("Error: Opening Netcdf file %s for Write.\n", filename_.base());
    return 1;
  }
  return 0;
}
示例#10
0
int Analysis_Hist::CalcFreeE() {
//  int refbin = -1; // TODO: re-enable
    mprintf("\tHistogram: Calculating free E at %f K.\n",Temp_);
  // TODO: Make Kb a constant
  double KT = (-Constants::GASK_KCAL * Temp_);

  // Find most populated bin for G=0
  std::vector<double>::iterator bin = Bins_.begin();
  double binmax = *bin;
  ++bin;
  for (; bin != Bins_.end(); ++bin)
    if (*bin > binmax)
      binmax = *bin;
  mprintf("\t           Bins max is %.0f\n",binmax);
  if (binmax==0) {
    mprinterr("Histogram: Cannot calc free E, no bins populated!\n");
    return 1;
  }

/*  // If requested, set up reference bin other than max
  if (refbin>-1) {
    if (Bins_[refbin] > 0) {
      binmax = Bins_[refbin];
      mprintf("\t           Calculating free E w.r.t bin %i, population %f\n",refbin,binmax);
    } else
      mprintf("Warning: Reference bin %i has no population. Using %f\n",refbin,binmax);
  }*/

  // Set artificial ceiling for bins with 0 population. Make it equivalent
  // to a bin population of 0.5. 
  double temp = 0.5 / binmax;
  double ceiling = log(temp) * KT;
  //ceiling*=1.10;
  mprintf("\t           Artificial ceiling (bin pop = 0.5) is %f kcal/mol.\n",ceiling);

  // Calculate free E based on populations
  for (bin = Bins_.begin(); bin != Bins_.end(); ++bin) {
    temp = *bin;               // Store Bin population in temp
    if (temp>0) {
      temp /= binmax;          // bin/max
      *bin = log(temp) * KT;   // -R*T*ln(bin/max)
    } else
      *bin = ceiling;          // Artificial ceiling for 0 pop bins.
  }

  return 0;
}
Action::RetType Action_MultiDihedral::Init(ArgList& actionArgs, TopologyList* PFL, FrameList* FL,
                          DataSetList* DSL, DataFileList* DFL, int debugIn)
{
  debug_ = debugIn;
  // Get keywords
  outfile_ = DFL->AddDataFile( actionArgs.GetStringKey("out"), actionArgs);
  range360_ = actionArgs.hasKey("range360");
  std::string resrange_arg = actionArgs.GetStringKey("resrange");
  if (!resrange_arg.empty())
    if (resRange_.SetRange( resrange_arg )) return Action::ERR;
  // Search for known dihedral keywords
  dihSearch_.SearchForArgs(actionArgs);
  // Get custom dihedral arguments: dihtype <name>:<a0>:<a1>:<a2>:<a3>[:<offset>]
  std::string dihtype_arg = actionArgs.GetStringKey("dihtype");
  while (!dihtype_arg.empty()) {
    ArgList dihtype(dihtype_arg, ":");
    if (dihtype.Nargs() < 5) {
      mprinterr("Error: Malformed dihtype arg.\n");
      return Action::ERR;
    }
    int offset = 0;
    if (dihtype.Nargs() == 6) offset = convertToInteger(dihtype[5]);
    dihSearch_.SearchForNewType(offset,dihtype[1],dihtype[2],dihtype[3],dihtype[4], dihtype[0]);
    dihtype_arg = actionArgs.GetStringKey("dihtype");
  }
  // If no dihedral types yet selected, this will select all.
  dihSearch_.SearchForAll();

  // Setup DataSet(s) name
  dsetname_ = actionArgs.GetStringNext();

  mprintf("    MULTIDIHEDRAL: Calculating");
  dihSearch_.PrintTypes();
  if (!resRange_.Empty())
    mprintf(" dihedrals for residues in range %s\n", resRange_.RangeArg());
  else
    mprintf(" dihedrals for all residues.\n");
  if (!dsetname_.empty())
    mprintf("\tDataSet name: %s\n", dsetname_.c_str());
  if (outfile_ != 0) mprintf("\tOutput to %s\n", outfile_->DataFilename().base());
  if (range360_) 
    mprintf("\tRange 0-360 deg.\n");
  else
    mprintf("\tRange -180-180 deg.\n");
  masterDSL_ = DSL;
  return Action::OK;
}
示例#12
0
// Traj_AmberNetcdf::readForce()
int Traj_AmberNetcdf::readForce(int set, Frame& frameIn) {
  start_[0] = set;
  start_[1] = 0;
  start_[2] = 0;
  count_[0] = 1;
  count_[1] = Ncatom();
  count_[2] = 3;
  // Read forces
  if (frcVID_ != -1) {
    if ( NC::CheckErr(nc_get_vara_float(ncid_, frcVID_, start_, count_, Coord_)) ) {
      mprinterr("Error: Getting forces for frame %i\n", set+1);
      return 1;
    }
    FloatToDouble(frameIn.fAddress(), Coord_);
  }
  return 0;
}
示例#13
0
// PairList::GridAtom()
void PairList::GridAtom(int atomIdx, Vec3 const& frac, Vec3 const& cart) {
  int i1 = (int)((frac[0]) * (double)nGridX_);
  int i2 = (int)((frac[1]) * (double)nGridY_);
  int i3 = (int)((frac[2]) * (double)nGridZ_);
  int idx = (i3*nGridX_*nGridY_)+(i2*nGridX_)+i1;
# ifdef DEBUG_PAIRLIST
  mprintf("GRID2 atom assigned to cell %6i%6i%10.5f%10.5f%10.5f\n",
          atomIdx+1, idx+1, frac[0], frac[1], frac[2]);
# endif
  if (idx < 0 || idx >= (int)cells_.size()) { // Sanity check
    mprinterr("Internal Error: Grid %i is out of range (>= %zu || < 0)\n",
              idx, cells_.size());
    return;
  }
  cells_[idx].AddAtom( AtmType(atomIdx, cart) );
  Frac_.push_back( frac );
}
/** Setting up is done for each frame.  */
int Traj_AmberRestartNC::setupTrajout(std::string const& fname, Topology* trajParm,
                                      int NframesToWrite, bool append)
{
  if (append) {
    mprinterr("Error: 'append' not supported by NetCDF restart\n");
    return 1;
  }
  filename_.SetFileName( fname );
  SetNcatom( trajParm->Natom() );
  // If number of frames to write == 1 set singleWrite so we dont append
  // frame # to filename.
  if (NframesToWrite == 1) singleWrite_ = true;
  // Set up title
  if (Title().empty())
    SetTitle("Cpptraj Generated Restart");
  return 0;
}
示例#15
0
/** Add column label from loop section. */
int CIFfile::DataBlock::AddLoopColumn( const char* ptr, BufferedLine& infile ) {
  if (ptr == 0) return 1;
  // Expect header.id
  int Ncols = infile.TokenizeLine(" \t");
  if ( Ncols > 1 ) {
    mprinterr("Error: Data record expected to have ID only.\n"
              "Error: '%s'\n", ptr);
    return 1;
  }
  std::string ID, Header;
  if (ParseData( std::string(infile.NextToken()), Header, ID )) return 1;
  //mprintf("\n"); // DEBUG
  if (AddHeader( Header )) return 1;
  columnHeaders_.push_back( ID );

  return 0;
}  
示例#16
0
// Traj_AmberNetcdf::readVelocity()
int Traj_AmberNetcdf::readVelocity(int set, Frame& frameIn) {
  start_[0] = set;
  start_[1] = 0;
  start_[2] = 0;
  count_[0] = 1;
  count_[1] = Ncatom();
  count_[2] = 3;
  // Read Velocities
  if (velocityVID_ != -1) {
    if ( checkNCerr(nc_get_vara_float(ncid_, velocityVID_, start_, count_, Coord_)) ) {
      mprinterr("Error: Getting velocities for frame %i\n", set+1);
      return 1;
    }
    FloatToDouble(frameIn.vAddress(), Coord_);
  }
  return 0;
}
示例#17
0
// AnalysisList::DoAnalyses()
int AnalysisList::DoAnalyses() {
  if (analysisList_.empty()) return 0;
  int err = 0;
  mprintf("\nANALYSIS: Performing %zu analyses:\n",analysisList_.size());
  for (Aarray::const_iterator ana = analysisList_.begin(); ana != analysisList_.end(); ++ana)
  {
    if ( ana->status_ == SETUP ) {
      mprintf("  %u: [%s]\n", ana - analysisList_.begin(), ana->args_.ArgLine());
      if (ana->ptr_->Analyze()==Analysis::ERR) {
        mprinterr("Error: In Analysis [%s]\n", ana->args_.Command()); // TODO exit? Set INACTIVE?
        ++err;
      }
    }
  }
  mprintf("\n");
  return err;
}
示例#18
0
// Action_Distance::Init()
Action::RetType Action_Distance::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
  AssociatedData_NOE noe;
  // Get Keywords
  image_.InitImaging( !(actionArgs.hasKey("noimage")) );
  useMass_ = !(actionArgs.hasKey("geom"));
  DataFile* outfile = init.DFL().AddDataFile( actionArgs.GetStringKey("out"), actionArgs );
  MetaData::scalarType stype = MetaData::UNDEFINED;
  std::string stypename = actionArgs.GetStringKey("type");
  if ( stypename == "noe" ) {
    stype = MetaData::NOE;
    if (noe.NOE_Args( actionArgs )) return Action::ERR;
  }
  // Get Masks
  std::string mask1 = actionArgs.GetMaskNext();
  std::string mask2 = actionArgs.GetMaskNext();
  if (mask1.empty() || mask2.empty()) {
    mprinterr("Error: distance requires 2 masks\n");
    return Action::ERR;
  }
  Mask1_.SetMaskString(mask1);
  Mask2_.SetMaskString(mask2);

  // Dataset to store distances TODO store masks in data set?
  dist_ = init.DSL().AddSet(DataSet::DOUBLE, MetaData(actionArgs.GetStringNext(),
                                                MetaData::M_DISTANCE, stype), "Dis");
  if (dist_==0) return Action::ERR;
  if ( stype == MetaData::NOE ) {
    dist_->AssociateData( &noe );
    dist_->SetLegend(Mask1_.MaskExpression() + " and " + Mask2_.MaskExpression());
  }
  // Add dataset to data file
  if (outfile != 0) outfile->AddDataSet( dist_ );

  mprintf("    DISTANCE: %s to %s",Mask1_.MaskString(), Mask2_.MaskString());
  if (!image_.UseImage()) 
    mprintf(", non-imaged");
  if (useMass_) 
    mprintf(", center of mass");
  else
    mprintf(", geometric center");
  mprintf(".\n");

  return Action::OK;
}
示例#19
0
// AnalysisList::DoAnalyses()
int AnalysisList::DoAnalyses() {
  if (analysisList_.empty()) return 0;
  int err = 0;
  mprintf("\nANALYSIS: Performing %zu analyses:\n",analysisList_.size());
  unsigned int ananum = 0;
  for (aListType::iterator ana = analysisList_.begin(); ana != analysisList_.end(); ++ana) {
    if ( analysisStatus_[ananum] == SETUP ) {
      mprintf("  %u: [%s]\n", ananum, analysisCmd_[ananum].c_str());
      if ((*ana)->Analyze()==Analysis::ERR) {
        mprinterr("Error: in Analysis # %u\n", ananum);
        ++err;
      }
    }
    ++ananum;
  }
  mprintf("\n");
  return err;
}
示例#20
0
文件: Cpptraj.cpp 项目: jcr13/cpptraj
/** Process a mask from the command line. */
int Cpptraj::ProcessMask( Sarray const& topFiles, Sarray const& refFiles,
                          std::string const& maskexpr,
                          bool verbose, bool residue ) const
{
  SetWorldSilent(true);
  if (topFiles.empty()) {
    mprinterr("Error: No topology file specified.\n");
    return 1;
  }
  ParmFile pfile;
  Topology parm;
  if (pfile.ReadTopology(parm, topFiles[0], State_.Debug())) return 1;
  if (!refFiles.empty()) {
    DataSet_Coords_REF refCoords;
    if (refCoords.LoadRefFromFile( refFiles[0], parm, State_.Debug())) return 1;
    parm.SetDistMaskRef( refCoords.RefFrame() );
  }
  if (!verbose) {
    AtomMask tempMask( maskexpr );
    if (parm.SetupIntegerMask( tempMask )) return 1;
    loudPrintf("Selected=");
    if (residue) {
      int res = -1;
      for (AtomMask::const_iterator atom = tempMask.begin(); 
                                    atom != tempMask.end(); ++atom)
      {
        if (parm[*atom].ResNum() > res) {
          loudPrintf(" %i", parm[*atom].ResNum()+1);
          res = parm[*atom].ResNum();
        }
      }
    } else
      for (AtomMask::const_iterator atom = tempMask.begin();
                                    atom != tempMask.end(); ++atom)
        loudPrintf(" %i", *atom + 1);
    loudPrintf("\n");
  } else {
    if (residue)
      parm.PrintResidueInfo( maskexpr );
    else
      parm.PrintAtomInfo( maskexpr );
  }
  return 0;
}
示例#21
0
// Action_Grid::PrintPDB()
void Action_Grid::PrintPDB(double gridMax)
{
  if (gridMax == 0.0) {
    mprinterr("Error: Grid max is 0. No density for PDB write.\n");
    return;
  }
  double norm = 1.0 / gridMax;
  // Calculate normalization if necessary
//  if (norm < 0.0) {
//    norm = (double)*std::max_element(grid_->begin(), grid_->end());
//  }
  // Write PDB
  PDBfile& pdbout = static_cast<PDBfile&>( *pdbfile_ );
  mprintf("\tWriting PDB of grid points > %.2f%% of grid max.\n", max_*100.0);
  int res = 1;
  for (size_t k = 0; k < grid_->NZ(); ++k) {
    for (size_t j = 0; j < grid_->NY(); ++j) {
      for (size_t i = 0; i < grid_->NX(); ++i) {
        double gridval = grid_->GetElement(i, j, k) * norm;
        if (gridval > max_) {
          Vec3 cxyz = grid_->BinCenter(i,j,k);
          pdbout.WriteATOM(res++, cxyz[0], cxyz[1], cxyz[2], "GRID", gridval);
        }
      }
    }
  }
  // Write grid boundaries
  for (size_t k = 0; k <= grid_->NZ(); k += grid_->NZ())
    for (size_t j = 0; j <= grid_->NY(); j += grid_->NY())
      for (size_t i = 0; i <= grid_->NX(); i += grid_->NX()) {
        Vec3 cxyz = grid_->BinCorner(i,j,k);
        pdbout.WriteHET(res, cxyz[0], cxyz[1], cxyz[2]);
      }
  // DEBUG: Write all grid bin corners
  if (debug_ > 1) {
    ++res;
    for (size_t k = 0; k <= grid_->NZ(); k++)
      for (size_t j = 0; j <= grid_->NY(); j++)
        for (size_t i = 0; i <= grid_->NX(); i++) {
          Vec3 cxyz = grid_->BinCorner(i,j,k);
          pdbout.WriteATOM(res, cxyz[0], cxyz[1], cxyz[2], "BIN", 0.0);
        }
  }
}
示例#22
0
// Action_Principal::Init()
Action::RetType Action_Principal::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
  debug_ = debugIn;
  // Keywords
  std::string dsname = actionArgs.GetStringKey("name");
  doRotation_ = actionArgs.hasKey("dorotation");
  // CPPTRAJ always uses mass no matter what this keyword says.
  useMass_ = actionArgs.hasKey("mass");
  std::string filename = actionArgs.GetStringKey("out");
  if (!doRotation_ && filename.empty() && dsname.empty()) {
    mprinterr("Error: At least one of 'dorotation', 'out <filename>', or 'name <dsname>' must be specified.\n");
    return Action::ERR;
  }
  // Masks
  mask_.SetMaskString( actionArgs.GetMaskNext() );
  // Set up data
  if (!dsname.empty()) {
     vecData_ = (DataSet_Mat3x3*)init.DSL().AddSet(DataSet::MAT3X3, MetaData(dsname, "evec"));
     valData_ = (DataSet_Vector*)init.DSL().AddSet(DataSet::VECTOR, MetaData(dsname, "eval"));
     if (vecData_ == 0 || valData_ == 0) return Action::ERR;
  }

  mprintf("    PRINCIPAL:");
  if (!filename.empty()) {
    outfile_ = init.DFL().AddCpptrajFile(filename, "Eigenvectors/Eigenvalues");
    if (outfile_ == 0) return Action::ERR;
    mprintf(" output eigenvectors/eigenvalues to %s,", outfile_->Filename().full());
  }
  if (doRotation_)
    mprintf(" with rotation by");
  else
    mprintf(" without rotation by");
  if (useMass_)
    mprintf(" center of mass");
  else
    mprintf(" center of geometry");
  mprintf(", atoms selected by [%s]\n", mask_.MaskString());
  if (vecData_ != 0)
    mprintf("\tSaving eigenvectors to '%s' (in rows of 3x3 matrices).\n"
            "\tSaving eigenvalues to '%s'\n", vecData_->legend(), valData_->legend());

  return Action::OK;
}
示例#23
0
/** Set angle up for this parmtop. Get masks etc.
  */
Action::RetType Action_Energy::Setup(ActionSetup& setup) {
  if (setup.Top().SetupCharMask(Mask1_)) return Action::ERR;
  if (Mask1_.None()) {
    mprintf("Warning: Mask '%s' selects no atoms.\n", Mask1_.MaskString());
    return Action::SKIP;
  }
  Mask1_.MaskInfo();
  Imask_ = AtomMask(Mask1_.ConvertToIntMask(), Mask1_.Natom());
  // Check for LJ terms
  for (calc_it calc = Ecalcs_.begin(); calc != Ecalcs_.end(); ++calc)
    if ((*calc == N14 || *calc == NBD) && !setup.Top().Nonbond().HasNonbond())
    {
      mprinterr("Error: Nonbonded energy calc requested but topology '%s'\n"
                "Error:   does not have non-bonded parameters.\n", setup.Top().c_str());
      return Action::ERR;
    }
  currentParm_ = setup.TopAddress();
  return Action::OK;
}
示例#24
0
/** \author Portable Random number generator by George Marsaglia
  * \author Amber 3.0 Rev A implementation by George Seibel
  *
  * This random number generator originally appeared in 'Toward a Universal
  * Random Number Generator' by George Marsaglia and Arif Zaman.  Florida
  * State University Report: FSU-SCRI-87-50 (1987)
  *
  * It was later modified by F. James and published in 'A Review of Pseudo-
  * random Number Generators'
  *
  * This is claimed to be the best known random number generator available.
  * It passes ALL of the tests for random number generators and has a
  * period of 2^144, is completely portable (gives bit identical results on
  * all machines with at least 24-bit mantissas in the floating point
  * representation).
  *
  * The algorithm is a combination of a Fibonacci sequence (with lags of 97
  * and 33, and operation "subtraction plus one, modulo one") and an
  * "arithmetic sequence" (using subtraction).
  *
  * \return A random number between 0.0 and 1.0
  * \return -1.0 if the random number generator is not initialized.
  */
double Random_Number::rn_gen() {
  if (!IsSet()) { 
    mprinterr("Error: random number generator not initialized.");
    return -1.0;
  }
  
  double uni = RN_generator.u[RN_generator.i97] - RN_generator.u[RN_generator.j97];
  if (uni < 0.0) uni += 1.0;
  RN_generator.u[RN_generator.i97] = uni;
  RN_generator.i97--;
  if (RN_generator.i97 == -1) RN_generator.i97 = 96;
  RN_generator.j97--;
  if (RN_generator.j97 == -1) RN_generator.j97 = 96;
  RN_generator.c -= RN_generator.cd;
  if (RN_generator.c < 0.0) RN_generator.c += RN_generator.cm;
  uni -= RN_generator.c;
  if (uni < 0.0) uni += 1.0; 
  return uni;
}
示例#25
0
int DataSet_Coords_TRJ::CoordsSetup(Topology const& topIn, CoordinateInfo const& cInfoIn ) {
  if (trajinList_.empty()) {
    top_ = topIn;
    cInfo_ = cInfoIn;
  } else {
    if ( topIn.Natom() != top_.Natom() ) {
      mprinterr("Error: For TRAJ data set currently all trajectories must have same number\n"
                "Error:  of atoms: %i != %i. Recommended course of action is to\n"
                "Error:  create a trajectory where all frames have been stripped to the same\n"
                "Error:  number of atoms first.\n", topIn.Natom(), top_.Natom());
      return 1;
    }
    // Since velocity/force info is not always allocated in Frame, if one traj
    // has velocity/force info ensure that all do.
    if (cInfoIn.HasVel()) cInfo_.SetVelocity( true );
    if (cInfoIn.HasForce()) cInfo_.SetForce( true );
  }
  return 0;
}
示例#26
0
// Ewald::Recip_ParticleMesh()
double Ewald_ParticleMesh::Recip_ParticleMesh(Box const& boxIn)
{
  t_recip_.Start();
  // This essentially makes coordsD and chargesD point to arrays.
  Mat coordsD(&coordsD_[0], Charge_.size(), 3);
  Mat chargesD(&Charge_[0], Charge_.size(), 1);
  int nfft1 = nfft_[0];
  int nfft2 = nfft_[1];
  int nfft3 = nfft_[2];
  if ( DetermineNfft(nfft1, nfft2, nfft3, boxIn) ) {
    mprinterr("Error: Could not determine grid spacing.\n");
    return 0.0;
  }
  // Instantiate double precision PME object
  // Args: 1 = Exponent of the distance kernel: 1 for Coulomb
  //       2 = Kappa
  //       3 = Spline order
  //       4 = nfft1
  //       5 = nfft2
  //       6 = nfft3
  //       7 = scale factor to be applied to all computed energies and derivatives thereof
  //       8 = max # threads to use for each MPI instance; 0 = all available threads used.
  // NOTE: Scale factor for Charmm is 332.0716
  // NOTE: The electrostatic constant has been baked into the Charge_ array already.
  //auto pme_object = std::unique_ptr<PMEInstanceD>(new PMEInstanceD());
  pme_object_.setup(1, ew_coeff_, order_, nfft1, nfft2, nfft3, 1.0, 0);
  // Sets the unit cell lattice vectors, with units consistent with those used to specify coordinates.
  // Args: 1 = the A lattice parameter in units consistent with the coordinates.
  //       2 = the B lattice parameter in units consistent with the coordinates.
  //       3 = the C lattice parameter in units consistent with the coordinates.
  //       4 = the alpha lattice parameter in degrees.
  //       5 = the beta lattice parameter in degrees.
  //       6 = the gamma lattice parameter in degrees.
  //       7 = lattice type
  pme_object_.setLatticeVectors(boxIn.BoxX(), boxIn.BoxY(), boxIn.BoxZ(),
                                boxIn.Alpha(), boxIn.Beta(), boxIn.Gamma(),
                                PMEInstanceD::LatticeType::XAligned);
  double erecip = pme_object_.computeERec(0, chargesD, coordsD);

  t_recip_.Stop();
  return erecip;
}
示例#27
0
// Trajin_Multi::ReadTrajFrame()
int Trajin_Multi::ReadTrajFrame( int currentFrame, Frame& frameIn ) {
    bool replicaFound = false;

    if ( targetType_ == ReplicaInfo::TEMP ) {
        // Find target temperature, exit loop when found.
        for (TrajIOarray::const_iterator rep = REMDtraj_.begin(); rep != REMDtraj_.end(); ++rep)
        {
            // Locate the target temp/indices out of all the replicas
            if ( (*rep)->readFrame(currentFrame, frameIn)) return 1;
            if ( frameIn.Temperature() == remdtrajtemp_ ) {
                replicaFound = true;
                break;
            }
        }
    } else { // Indices
        // Find target indices.
        for (TrajIOarray::const_iterator rep = REMDtraj_.begin(); rep != REMDtraj_.end(); ++rep)
        {
            replicaFound = true;
            if ( (*rep)->readFrame(currentFrame, frameIn)) return 1;
            Frame::RemdIdxType::const_iterator tgtIdx = frameIn.RemdIndices().begin();
            for (RemdIdxType::const_iterator idx = remdtrajidx_.begin();
                    idx != remdtrajidx_.end();
                    ++idx, ++tgtIdx)
            {
                if ( *tgtIdx != *idx ) {
                    replicaFound = false;
                    break;
                }
            }
            if (replicaFound) break;
        }
    }

    if (!replicaFound) {
        mprinterr("Error: Target replica not found. Check that all replica trajectories\n"
                  "Error:   were found and that the target temperature or indices are valid\n"
                  "Error:   for this ensemble.\n");
        return 1;
    }
    return 0;
}
示例#28
0
int Cluster_ReadInfo::Cluster() {
  BufferedLine infile;
  if (infile.OpenFileRead( filename_ )) return Err(0);
  const char* ptr = infile.Line();
  if (ptr == 0) return Err(1);
  ArgList infoLine( ptr, " " );
  int nclusters = infoLine.getKeyInt("#Clustering:", -1);
  if (nclusters == -1) return Err(2);
  int nframes = infoLine.getKeyInt("clusters", -1);
  if (nframes == -1) return Err(3);
  if (nframes != (int)FrameDistances_.Nframes()) {
    mprinterr("Error: # frames in cluster info file (%i) does not match"
              " current # frames (%zu)\n", nframes, FrameDistances_.Nframes());
    return 1;
  }
  // Scan down to clusters
  while (ptr[0] == '#') {
    ptr = infile.Line();
    if (ptr == 0) return Err(1);
    // Save previous clustering info. Includes newline.
    if (ptr[1] == 'A' && ptr[2] == 'l' && ptr[3] == 'g')
      algorithm_.assign( ptr + 12 ); // Right past '#Algorithm: '
  }
  // Read clusters
  ClusterDist::Cframes frames;
  for (int cnum = 0; cnum != nclusters; cnum++) {
    if (ptr == 0) return Err(1);
    frames.clear();
    // TODO: Check for busted lines?
    for (int fidx = 0; fidx != nframes; fidx++) {
      if (ptr[fidx] == 'X')
        frames.push_back( fidx );
    }
    AddCluster( frames );
    mprintf("\tRead cluster %i, %zu frames.\n", cnum, frames.size());
    ptr = infile.Line();
  }
  infile.CloseFile();
  mprintf("\tCalculating the distances between each cluster based on centroids.\n");
  CalcClusterDistances();
  return 0;
}
示例#29
0
int EnsembleOutList::SetupEnsembleOut(Topology* CurrentParm, CoordinateInfo const& cInfo,
                                      int Nframes)
{
  active_.clear();
  for (unsigned int i = 0; i != ensout_.size(); i++) {
    // Check that input parm matches setup parm - if not, skip
    if (CurrentParm->Pindex() == ensTops_[i]->Pindex()) {
      if (!open_[i]) {
        if ( ensout_[i]->SetupEnsembleWrite( CurrentParm, cInfo, Nframes ) )
        {
          mprinterr("Error: Setting up output ensemble %s\n", ensout_[i]->Traj().Filename().full());
          return 1;
        }
        open_[i] = true;
      }
      active_.push_back( ensout_[i] );
    }
  }
  return 0;
}
示例#30
0
/** Given a box, determine number of FFT grid points in each dimension. */
int Ewald_ParticleMesh::DetermineNfft(int& nfft1, int& nfft2, int& nfft3, Box const& boxIn) const
{
   if (nfft1 < 1) {
    // Need even dimension for X direction
    nfft1 = ComputeNFFT( (boxIn.BoxX() + 1.0) * 0.5 );
    nfft1 *= 2;
  }
  if (nfft2 < 1)
    nfft2 = ComputeNFFT( boxIn.BoxY() );
  if (nfft3 < 1)
    nfft3 = ComputeNFFT( boxIn.BoxZ() );

  if (nfft1 < 1 || nfft2 < 1 || nfft3 < 1) {
    mprinterr("Error: Bad NFFT values: %i %i %i\n", nfft1, nfft2, nfft3);
    return 1;
  }
  if (debug_ > 0) mprintf("DEBUG: NFFTs: %i %i %i\n", nfft1, nfft2, nfft3);

  return 0;
}