/** Create new DataFile, or return existing DataFile. */ DataFile* DataFileList::AddDataFile(FileName const& nameIn, ArgList& argIn, DataFile::DataFormatType typeIn) { // If no filename, no output desired if (nameIn.empty()) return 0; FileName fname( nameIn ); // Append ensemble number if set. //rprintf("DEBUG: Setting up data file '%s' with ensembleNum %i\n", nameIn.base(), ensembleNum_); if (ensembleNum_ != -1) fname.Append( "." + integerToString(ensembleNum_) ); // Check if filename in use by CpptrajFile. CpptrajFile* cf = GetCpptrajFile(fname); if (cf != 0) { mprinterr("Error: Data file name '%s' already in use by text output file '%s'.\n", fname.full(), cf->Filename().full()); return 0; } // Check if this filename already in use DataFile* Current = GetDataFile(fname); // If no DataFile associated with name, create new DataFile if (Current==0) { Current = new DataFile(); if (Current->SetupDatafile(fname, argIn, typeIn, debug_)) { mprinterr("Error: Setting up data file %s\n", fname.full()); delete Current; return 0; } fileList_.push_back(Current); } else { // Set debug level Current->SetDebug(debug_); // If a type was specified, make sure it matches. if (typeIn != DataFile::UNKNOWN_DATA && typeIn != Current->Type()) { mprinterr("Error: '%s' is type %s but has been requested as type %s.\n", Current->DataFilename().full(), Current->FormatString(), DataFile::FormatString( typeIn )); return 0; } // Check for keywords that do not match file type DataFile::DataFormatType kType = DataFile::GetFormatFromArg( argIn ); if (kType != DataFile::UNKNOWN_DATA && kType != Current->Type()) mprintf("Warning: %s is type %s but type %s keyword specified; ignoring keyword.\n", Current->DataFilename().full(), Current->FormatString(), DataFile::FormatString( kType )); // Process Arguments if (!argIn.empty()) Current->ProcessArgs( argIn ); } return Current; }
Exec::RetType Exec_Precision::Execute(CpptrajState& State, ArgList& argIn) { // Next string is DataSet(s)/DataFile that command pertains to. std::string name1 = argIn.GetStringNext(); if (name1.empty()) { mprinterr("Error: No filename/setname given.\n"); return CpptrajState::ERR; } // This will break if dataset name starts with a digit... int width = argIn.getNextInteger(12); if (width < 1) { mprintf("Error: Cannot set width < 1 (%i).\n", width); return CpptrajState::ERR; } int precision = argIn.getNextInteger(4); if (precision < 0) precision = 0; DataFile* df = State.DFL().GetDataFile(name1); if (df != 0) { mprintf("\tSetting precision for all sets in %s to %i.%i\n", df->DataFilename().base(), width, precision); df->SetDataFilePrecision(width, precision); } else { State.DSL().SetPrecisionOfDataSets( name1, width, precision ); } return CpptrajState::OK; }
// Action_FilterByData::Init() Action::RetType Action_FilterByData::Init(ArgList& actionArgs, ActionInit& init, int debugIn) { maxmin_ = init.DSL().AddSet( DataSet::INTEGER, actionArgs.GetStringKey("name"), "Filter" ); if (maxmin_ == 0) return Action::ERR; DataFile* maxminfile = init.DFL().AddDataFile( actionArgs.GetStringKey("out"), actionArgs ); if (maxminfile != 0) maxminfile->AddDataSet( maxmin_ ); // Get min and max args. while (actionArgs.Contains("min")) Min_.push_back( actionArgs.getKeyDouble("min", 0.0) ); while (actionArgs.Contains("max")) Max_.push_back( actionArgs.getKeyDouble("max", 0.0) ); if (Min_.empty()) { mprinterr("Error: At least one 'min' arg must be specified.\n"); return Action::ERR; } if (Max_.empty()) { mprinterr("Error: At least one 'max' arg must be specified.\n"); return Action::ERR; } if (Min_.size() != Max_.size()) { mprinterr("Error: # of 'min' args (%zu) != # of 'max' args (%zu)\n", Min_.size(), Max_.size()); return Action::ERR; } // Get DataSets from remaining arguments Dsets_.AddSetsFromArgs( actionArgs.RemainingArgs(), init.DSL() ); if (Dsets_.empty()) { mprinterr("Error: No data sets specified.\n"); return Action::ERR; } if ( Dsets_.size() < Min_.size() ) { mprinterr("Error: More 'min'/'max' args (%zu) than data sets (%zu).\n", Min_.size(), Dsets_.size()); return Action::ERR; } if ( Dsets_.size() > Min_.size() ) { unsigned int Nremaining = Dsets_.size() - Min_.size(); double useMin = Min_.back(); double useMax = Max_.back(); mprintf("Warning: More data sets than 'min'/'max' args.\n" "Warning: Using min=%f and max=%f for last %zu data sets.\n", useMin, useMax, Nremaining); for (unsigned int ds = 0; ds < Nremaining; ++ds) { Min_.push_back( useMin ); Max_.push_back( useMax ); } } mprintf(" FILTER: Filtering out frames using %zu data sets.\n", Dsets_.size()); for (unsigned int ds = 0; ds < Dsets_.size(); ds++) mprintf("\t%.4f < '%s' < %.4f\n", Min_[ds], Dsets_[ds]->legend(), Max_[ds]); if (maxminfile != 0) mprintf("\tFilter frame info will be written to %s\n", maxminfile->DataFilename().full()); return Action::OK; }
// Action_Grid::Init() Action::RetType Action_Grid::Init(ArgList& actionArgs, ActionInit& init, int debugIn) { debug_ = debugIn; nframes_ = 0; // Get output filename std::string filename = actionArgs.GetStringKey("out"); // Get grid options grid_ = GridInit( "GRID", actionArgs, init.DSL() ); if (grid_ == 0) return Action::ERR; # ifdef MPI if (ParallelGridInit(init.TrajComm(), grid_)) return Action::ERR; # endif // Get extra options max_ = actionArgs.getKeyDouble("max", 0.80); madura_ = actionArgs.getKeyDouble("madura", 0); smooth_ = actionArgs.getKeyDouble("smoothdensity", 0); invert_ = actionArgs.hasKey("invert"); pdbfile_ = init.DFL().AddCpptrajFile(actionArgs.GetStringKey("pdb"),"Grid PDB",DataFileList::PDB,true); density_ = actionArgs.getKeyDouble("density",0.033456); if (actionArgs.hasKey("normframe")) normalize_ = TO_FRAME; else if (actionArgs.hasKey("normdensity")) normalize_ = TO_DENSITY; else normalize_ = NONE; if (normalize_ != NONE && (smooth_ > 0.0 || madura_ > 0.0)) { mprinterr("Error: Normalize options are not compatible with smoothdensity/madura options.\n"); init.DSL().RemoveSet( grid_ ); return Action::ERR; } // Get mask std::string maskexpr = actionArgs.GetMaskNext(); if (maskexpr.empty()) { mprinterr("Error: GRID: No mask specified.\n"); init.DSL().RemoveSet( grid_ ); return Action::ERR; } mask_.SetMaskString(maskexpr); // Setup output file // For backwards compat., if no 'out' assume next string is filename if (filename.empty() && actionArgs.Nargs() > 1 && !actionArgs.Marked(1)) filename = actionArgs.GetStringNext(); DataFile* outfile = init.DFL().AddDataFile(filename, actionArgs); if (outfile != 0) outfile->AddDataSet((DataSet*)grid_); // Info mprintf(" GRID:\n"); GridInfo( *grid_ ); if (outfile != 0) mprintf("\tGrid will be printed to file %s\n", outfile->DataFilename().full()); mprintf("\tGrid data set: '%s'\n", grid_->legend()); mprintf("\tMask expression: [%s]\n",mask_.MaskString()); if (pdbfile_ != 0) mprintf("\tPseudo-PDB will be printed to %s\n", pdbfile_->Filename().full()); if (normalize_ == TO_FRAME) mprintf("\tGrid will be normalized by number of frames.\n"); else if (normalize_ == TO_DENSITY) mprintf("\tGrid will be normalized to a density of %g molecules/Ang^3.\n", density_); // TODO: print extra options return Action::OK; }
// 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; }
// Action_AtomicFluct::Init() Action::RetType Action_AtomicFluct::Init(ArgList& actionArgs, TopologyList* PFL, DataSetList* DSL, DataFileList* DFL, int debugIn) { // Get frame # keywords if (InitFrameCounter(actionArgs)) return Action::ERR; // Get other keywords bfactor_ = actionArgs.hasKey("bfactor"); calc_adp_ = actionArgs.hasKey("calcadp"); adpoutfile_ = DFL->AddCpptrajFile(actionArgs.GetStringKey("adpout"), "PDB w/ADP", DataFileList::PDB);; if (adpoutfile_!=0) calc_adp_ = true; // adpout implies calcadp if (calc_adp_ && !bfactor_) bfactor_ = true; DataFile* outfile = DFL->AddDataFile( actionArgs.GetStringKey("out"), actionArgs ); if (actionArgs.hasKey("byres")) outtype_ = BYRES; else if (actionArgs.hasKey("bymask")) outtype_ = BYMASK; else if (actionArgs.hasKey("byatom") || actionArgs.hasKey("byatm")) outtype_ = BYATOM; // Get Mask Mask_.SetMaskString( actionArgs.GetMaskNext() ); // Get DataSet name std::string setname = actionArgs.GetStringNext(); // Add output dataset MetaData md( setname ); md.SetTimeSeries( MetaData::NOT_TS ); if (bfactor_) md.SetLegend("B-factors"); else md.SetLegend("AtomicFlx"); dataout_ = DSL->AddSet( DataSet::XYMESH, md, "Fluct" ); if (dataout_ == 0) { mprinterr("Error: AtomicFluct: Could not allocate dataset for output.\n"); return Action::ERR; } if (outfile != 0) outfile->AddDataSet( dataout_ ); mprintf(" ATOMICFLUCT: calculating"); if (bfactor_) mprintf(" B factors"); else mprintf(" atomic positional fluctuations"); if (outfile != 0) mprintf(", output to file %s", outfile->DataFilename().full()); mprintf("\n Atom mask: [%s]\n",Mask_.MaskString()); FrameCounterInfo(); if (calc_adp_) { mprintf("\tCalculating anisotropic displacement parameters.\n"); if (adpoutfile_!=0) mprintf("\tWriting PDB with ADP to '%s'\n", adpoutfile_->Filename().full()); } if (!setname.empty()) mprintf("\tData will be saved to set named %s\n", setname.c_str()); return Action::OK; }
// TODO: Accept const ArgList so arguments are not reset? CpptrajFile* DataFileList::AddCpptrajFile(FileName const& nameIn, std::string const& descrip, CFtype typeIn, bool allowStdout) { // If no filename and stdout not allowed, no output desired. if (nameIn.empty() && !allowStdout) return 0; FileName name; CpptrajFile* Current = 0; int currentIdx = -1; if (!nameIn.empty()) { name = nameIn; // Append ensemble number if set. if (ensembleNum_ != -1) name.Append( "." + integerToString(ensembleNum_) ); // Check if filename in use by DataFile. DataFile* df = GetDataFile(name); if (df != 0) { mprinterr("Error: Text output file name '%s' already in use by data file '%s'.\n", nameIn.full(), df->DataFilename().full()); return 0; } // Check if this filename already in use currentIdx = GetCpptrajFileIdx( name ); if (currentIdx != -1) Current = cfList_[currentIdx]; } // If no CpptrajFile associated with name, create new CpptrajFile if (Current==0) { switch (typeIn) { case TEXT: Current = new CpptrajFile(); break; case PDB: Current = (CpptrajFile*)(new PDBfile()); break; } Current->SetDebug(debug_); // Set up file for writing. //if (Current->SetupWrite( name, debug_ )) if (Current->OpenWrite( name )) { mprinterr("Error: Setting up text output file %s\n", name.full()); delete Current; return 0; } cfList_.push_back( Current ); cfData_.push_back( CFstruct(descrip, typeIn) ); } else { // If Current type does not match typeIn do not allow. if (typeIn != cfData_[currentIdx].Type()) { mprinterr("Error: Cannot change type of text output for '%s'.\n", Current->Filename().full()); return 0; } Current->SetDebug(debug_); // Update description if (!descrip.empty()) cfData_[currentIdx].UpdateDescrip( descrip ); } return Current; }
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; }
// Analysis_VectorMath::Setup() Analysis::RetType Analysis_VectorMath::Setup(ArgList& analyzeArgs, DataSetList* DSLin, DataFileList* DFLin, int debugIn) { // Get Vectors vinfo1_ = (DataSet_Vector*)DSLin->FindSetOfType( analyzeArgs.GetStringKey("vec1"), DataSet::VECTOR ); vinfo2_ = (DataSet_Vector*)DSLin->FindSetOfType( analyzeArgs.GetStringKey("vec2"), DataSet::VECTOR ); if (vinfo1_ == 0 ) { mprinterr("Error: 'vec1' not found.\n"); return Analysis::ERR; } if (vinfo2_ == 0) { mprinterr("Error: 'vec2' not found.\n"); return Analysis::ERR; } std::string setname = analyzeArgs.GetStringKey("name"); norm_ = analyzeArgs.hasKey("norm"); // Check for dotproduct/crossproduct keywords DataOut_ = 0; if (analyzeArgs.hasKey("dotproduct")) { mode_ = DOTPRODUCT; if ((DataOut_ = DSLin->AddSet(DataSet::DOUBLE, setname, "Dot")) == 0) return Analysis::ERR; } else if (analyzeArgs.hasKey("dotangle")) { mode_ = DOTANGLE; norm_ = true; // Vecs must be normalized for angle calc to work if ((DataOut_ = DSLin->AddSet(DataSet::DOUBLE, setname, "Angle")) == 0) return Analysis::ERR; } else if (analyzeArgs.hasKey("crossproduct")) { mode_ = CROSSPRODUCT; if ((DataOut_ = DSLin->AddSet(DataSet::VECTOR, setname, "Cross")) == 0) return Analysis::ERR; } else mode_ = DOTPRODUCT; // Set up output file in DataFileList if necessary DataFile* outfile = DFLin->AddDataFile( analyzeArgs.GetStringKey("out"), analyzeArgs ); if (outfile != 0) outfile->AddDataSet( DataOut_ ); // Print Status mprintf(" VECTORMATH: Calculating %s of vectors %s and %s\n", ModeString[mode_], vinfo1_->legend(), vinfo2_->legend()); if (norm_) mprintf("\tVectors will be normalized.\n"); if (outfile != 0) mprintf("\tResults are written to %s\n", outfile->DataFilename().full()); return Analysis::OK; }
// 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; }
// Action_GridFreeEnergy::init() Action::RetType Action_GridFreeEnergy::Init(ArgList& actionArgs, ActionInit& init, int debugIn) { // Get output filename DataFile* outfile = init.DFL().AddDataFile(actionArgs.GetStringNext(), actionArgs); if (outfile == 0) { mprinterr("Error: GridFreeEnergy: no output filename specified.\n"); return Action::ERR; } // Get grid options (<nx> <dx> <ny> <dy> <nz> <dz> [box|origin] [negative]) grid_ = GridInit( "GridFreeEnergy", actionArgs, init.DSL() ); if (grid_ == 0) return Action::ERR; # ifdef MPI if (ParallelGridInit(init.TrajComm(), grid_)) return Action::ERR; # endif //grid_.PrintXplor( filename_, "", "REMARKS Change in Free energy from bulk solvent with bin normalisation of " + integerToString(currentLargestVoxelOccupancyCount) ); // Get mask std::string maskexpr = actionArgs.GetMaskNext(); if (maskexpr.empty()) { mprinterr("Error: GridFreeEnergy: No mask specified.\n"); init.DSL().RemoveSet( grid_ ); return Action::ERR; } mask_.SetMaskString(maskexpr); // Get extra args tempInKevin_ = actionArgs.getKeyDouble("temp", 293.0); outfile->AddDataSet( grid_ ); // Info mprintf("Warning: DNAIONTRACKER is experimental code!\n"); mprintf(" GridFreeEnergy\n"); GridInfo( *grid_ ); mprintf("\tGrid will be printed to file %s\n",outfile->DataFilename().full()); mprintf("\tMask expression: [%s]\n",mask_.MaskString()); mprintf("\tTemp is : %f K\n",tempInKevin_); // Allocate grid //if (GridAllocate()) return 1; return Action::OK; }
// Analysis_FFT::Setup() Analysis::RetType Analysis_FFT::Setup(ArgList& analyzeArgs, DataSetList* datasetlist, DataFileList* DFLin, int debugIn) { std::string setname = analyzeArgs.GetStringKey("name"); DataFile* outfile = DFLin->AddDataFile(analyzeArgs.GetStringKey("out"), analyzeArgs); dt_ = analyzeArgs.getKeyDouble("dt",1.0); // 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; } // If setname is empty generate a default name if (setname.empty()) setname = datasetlist->GenerateDefaultName( "FFT" ); // Setup output datasets. int idx = 0; if ( input_dsets_.size() == 1 ) idx = -1; // Only one input set, no need to refer to it by index for ( Array1D::const_iterator DS = input_dsets_.begin(); DS != input_dsets_.end(); ++DS) { DataSet* dsout = datasetlist->AddSet( DataSet::DOUBLE, MetaData(setname, idx++) ); if (dsout==0) return Analysis::ERR; dsout->SetLegend( (*DS)->Meta().Legend() ); output_dsets_.push_back( (DataSet_1D*)dsout ); if (outfile != 0) outfile->AddDataSet( dsout ); } mprintf(" FFT: Calculating FFT for %u data sets.\n", input_dsets_.size()); mprintf("\tTime step: %f\n", dt_); if ( !setname.empty() ) mprintf("\tSet name: %s\n", setname.c_str() ); if ( outfile != 0 ) mprintf("\tOutfile name: %s\n", outfile->DataFilename().base()); return Analysis::OK; }
// Action_Density::Init() Action::RetType Action_Density::Init(ArgList& actionArgs, ActionInit& init, int debugIn) { # ifdef MPI trajComm_ = init.TrajComm(); # endif DataFile* outfile = init.DFL().AddDataFile(actionArgs.GetStringKey("out"), actionArgs); std::string dsname = actionArgs.GetStringKey("name"); if (actionArgs.hasKey("x") ) { axis_ = DX; area_coord_[0] = DY; area_coord_[1] = DZ; } else if (actionArgs.hasKey("y") ) { axis_ = DY; area_coord_[0] = DX; area_coord_[1] = DZ; } else if (actionArgs.hasKey("z") ) { axis_ = DZ; area_coord_[0] = DX; area_coord_[1] = DY; } property_ = NUMBER; if (actionArgs.hasKey("number") ) property_ = NUMBER; else if (actionArgs.hasKey("mass") ) property_ = MASS; else if (actionArgs.hasKey("charge") ) property_ = CHARGE; else if (actionArgs.hasKey("electron") ) property_ = ELECTRON; binType_ = CENTER; if (actionArgs.hasKey("bincenter")) binType_ = CENTER; else if (actionArgs.hasKey("binedge") ) binType_ = EDGE; delta_ = actionArgs.getKeyDouble("delta", 0.01); if (delta_ <= 0) { mprinterr("Error: Delta must be > 0.0\n"); return Action::ERR; } // for compatibility with ptraj, ignored because we rely on the atom code to // do the right thing, see Atom.{h,cpp} if (actionArgs.hasKey("efile")) mprintf("Warning: The 'efile' keyword is deprecated.\n"); // read the rest of the command line as a series of masks std::string maskstr; unsigned int idx = 1; while ( (maskstr = actionArgs.GetMaskNext() ) != emptystring) { masks_.push_back( AtomMask(maskstr) ); if (dsname.empty()) dsname = init.DSL().GenerateDefaultName("DENSITY"); MetaData MD(dsname, "avg", idx); MD.SetTimeSeries( MetaData::NOT_TS ); // Hold average density DataSet* ads = init.DSL().AddSet( DataSet::DOUBLE, MD ); if (ads == 0) return Action::ERR; ads->SetLegend( NoWhitespace(masks_.back().MaskExpression()) ); AvSets_.push_back( ads ); if (outfile != 0) outfile->AddDataSet( ads ); // Hold SD density MD.SetAspect("sd"); DataSet* sds = init.DSL().AddSet( DataSet::DOUBLE, MD ); if (sds == 0) return Action::ERR; sds->SetLegend( NoWhitespace("sd(" + masks_.back().MaskExpression() + ")") ); SdSets_.push_back( sds ); if (outfile != 0) outfile->AddDataSet( sds ); # ifdef MPI ads->SetNeedsSync( false ); // Populated in Print() sds->SetNeedsSync( false ); # endif idx++; } if (masks_.empty()) { // If no masks assume we want total system density. if (dsname.empty()) dsname = actionArgs.GetStringNext(); density_ = init.DSL().AddSet(DataSet::DOUBLE, dsname, "DENSITY"); if (density_ == 0) return Action::ERR; if (outfile != 0) outfile->AddDataSet( density_ ); image_.InitImaging( true ); // Hijack delta for storing sum of masses delta_ = 0.0; } else { // Density selected by mask(s) along an axis density_ = 0; histograms_.resize(masks_.size() ); } mprintf(" DENSITY:"); if (density_ == 0) { const char* binStr[] = {"center", "edge"}; mprintf(" Determining %s density for %zu masks.\n", PropertyStr_[property_], masks_.size()); mprintf("\troutine version: %s\n", ROUTINE_VERSION_STRING); mprintf("\tDelta is %f\n", delta_); mprintf("\tAxis is %s\n", AxisStr_[axis_]); mprintf("\tData set name is '%s'\n", dsname.c_str()); mprintf("\tData set aspect [avg] holds the mean, aspect [sd] holds standard deviation.\n"); mprintf("\tBin coordinates will be to bin %s.\n", binStr[binType_]); } else { mprintf(" No masks specified, calculating total system density in g/cm^3.\n"); mprintf("\tData set name is '%s'\n", density_->legend()); } if (outfile != 0) mprintf("\tOutput to '%s'\n", outfile->DataFilename().full()); return Action::OK; }
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; }
// 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_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; }
/** Syntax: dataset invert <set arg0> ... name <new name> */ Exec::RetType Exec_DataSetCmd::InvertSets(CpptrajState& State, ArgList& argIn) { DataSetList& DSL = State.DSL(); // Get keywords DataSet* inputNames = 0; std::string dsname = argIn.GetStringKey("legendset"); if (!dsname.empty()) { inputNames = DSL.GetDataSet( dsname ); if (inputNames == 0) { mprinterr("Error: Name set '%s' not found.\n", dsname.c_str()); return CpptrajState::ERR; } if (inputNames->Type() != DataSet::STRING) { mprinterr("Error: Set '%s' does not contain strings.\n", inputNames->legend()); return CpptrajState::ERR; } mprintf("\tUsing names from set '%s' as legends for inverted sets.\n", inputNames->legend()); } dsname = argIn.GetStringKey("name"); if (dsname.empty()) { mprinterr("Error: 'invert' requires that 'name <new set name>' be specified.\n"); return CpptrajState::ERR; } mprintf("\tNew sets will be named '%s'\n", dsname.c_str()); DataFile* outfile = State.DFL().AddDataFile( argIn.GetStringKey("out"), argIn ); if (outfile != 0) mprintf("\tNew sets will be output to '%s'\n", outfile->DataFilename().full()); // TODO determine type some other way DataSet::DataType outtype = DataSet::DOUBLE; // Get input DataSets std::vector<DataSet_1D*> input_sets; std::string dsarg = argIn.GetStringNext(); while (!dsarg.empty()) { DataSetList sets = DSL.GetMultipleSets( dsarg ); for (DataSetList::const_iterator ds = sets.begin(); ds != sets.end(); ++ds) { if ( (*ds)->Group() != DataSet::SCALAR_1D ) { mprintf("Warning: '%s': Inversion only supported for 1D scalar data sets.\n", (*ds)->legend()); } else { if (!input_sets.empty()) { if ( (*ds)->Size() != input_sets.back()->Size() ) { mprinterr("Error: Set '%s' has different size (%zu) than previous set (%zu)\n", (*ds)->legend(), (*ds)->Size(), input_sets.back()->Size()); return CpptrajState::ERR; } } input_sets.push_back( (DataSet_1D*)*ds ); } } dsarg = argIn.GetStringNext(); } if (input_sets.empty()) { mprinterr("Error: No sets selected.\n"); return CpptrajState::ERR; } if (inputNames != 0 && inputNames->Size() != input_sets.front()->Size()) { mprinterr("Error: Name set '%s' size (%zu) differs from # data points (%zu).\n", inputNames->legend(), inputNames->Size(), input_sets.front()->Size()); return CpptrajState::ERR; } mprintf("\t%zu input sets; creating %zu output sets.\n", input_sets.size(), input_sets.front()->Size()); // Need an output data set for each point in input sets std::vector<DataSet*> output_sets; int column = 1; for (int idx = 0; idx != (int)input_sets[0]->Size(); idx++, column++) { DataSet* ds = 0; ds = DSL.AddSet(outtype, MetaData(dsname, column)); if (ds == 0) return CpptrajState::ERR; if (inputNames != 0) ds->SetLegend( (*((DataSet_string*)inputNames))[idx] ); output_sets.push_back( ds ); if (outfile != 0) outfile->AddDataSet( ds ); } // Create a data set containing names of each input data set DataSet* nameset = DSL.AddSet(DataSet::STRING, MetaData(dsname, column)); if (nameset == 0) return CpptrajState::ERR; if (inputNames != 0) nameset->SetLegend("Names"); if (outfile != 0) outfile->AddDataSet( nameset ); // Populate output data sets for (int jdx = 0; jdx != (int)input_sets.size(); jdx++) { DataSet_1D const& INP = static_cast<DataSet_1D const&>( *(input_sets[jdx]) ); nameset->Add( jdx, INP.legend() ); for (unsigned int idx = 0; idx != INP.Size(); idx++) { double dval = INP.Dval( idx ); output_sets[idx]->Add( jdx, &dval ); } } return CpptrajState::OK; }
// Action_Watershell::Init() Action::RetType Action_Watershell::Init(ArgList& actionArgs, ActionInit& init, int debugIn) { image_.InitImaging( !actionArgs.hasKey("noimage") ); // Get keywords std::string filename = actionArgs.GetStringKey("out"); lowerCutoff_ = actionArgs.getKeyDouble("lower", 3.4); upperCutoff_ = actionArgs.getKeyDouble("upper", 5.0); // Get solute mask std::string maskexpr = actionArgs.GetMaskNext(); if (maskexpr.empty()) { mprinterr("Error: Solute mask must be specified.\n"); return Action::ERR; } soluteMask_.SetMaskString( maskexpr ); // Check for solvent mask std::string solventmaskexpr = actionArgs.GetMaskNext(); if (!solventmaskexpr.empty()) solventMask_.SetMaskString( solventmaskexpr ); // For backwards compat., if no 'out' assume next string is file name if (filename.empty() && actionArgs.Nargs() > 2 && !actionArgs.Marked(2)) filename = actionArgs.GetStringNext(); DataFile* outfile = init.DFL().AddDataFile( filename, actionArgs ); // Set up datasets std::string dsname = actionArgs.GetStringNext(); if (dsname.empty()) dsname = init.DSL().GenerateDefaultName("WS"); lower_ = init.DSL().AddSet(DataSet::INTEGER, MetaData(dsname, "lower")); upper_ = init.DSL().AddSet(DataSet::INTEGER, MetaData(dsname, "upper")); if (lower_ == 0 || upper_ == 0) return Action::ERR; if (outfile != 0) { outfile->AddDataSet(lower_); outfile->AddDataSet(upper_); } # ifndef CUDA # ifdef _OPENMP // Determine number of parallel threads int numthreads = 0; #pragma omp parallel { if (omp_get_thread_num()==0) numthreads = omp_get_num_threads(); } shellStatus_thread_.resize( numthreads ); # endif # endif mprintf(" WATERSHELL:"); if (outfile != 0) mprintf(" Output to %s", outfile->DataFilename().full()); mprintf("\n"); if (!image_.UseImage()) mprintf("\tImaging is disabled.\n"); mprintf("\tThe first shell will contain solvent < %.3f angstroms from\n", lowerCutoff_); mprintf("\t the solute; the second shell < %.3f angstroms...\n", upperCutoff_); mprintf("\tSolute atoms will be specified by [%s]\n",soluteMask_.MaskString()); if (solventMask_.MaskStringSet()) mprintf("\tSolvent atoms will be specified by [%s]\n", solventMask_.MaskString()); #ifdef CUDA mprintf("\tDistance calculations will be GPU-accelerated with CUDA.\n"); #else # ifdef _OPENMP if (shellStatus_thread_.size() > 1) mprintf("\tParallelizing calculation with %zu threads.\n", shellStatus_thread_.size()); # endif #endif mprintf("\t# solvent molecules in 'lower' shell stored in set '%s'\n", lower_->legend()); mprintf("\t# solvent molecules in 'upper' shell stored in set '%s'\n", upper_->legend()); // Pre-square upper and lower cutoffs lowerCutoff_ *= lowerCutoff_; upperCutoff_ *= upperCutoff_; return Action::OK; }
// Action_NativeContacts::Init() Action::RetType Action_NativeContacts::Init(ArgList& actionArgs, ActionInit& init, int debugIn) { # ifdef MPI trajComm_ = init.TrajComm(); # endif masterDSL_ = init.DslPtr(); debug_ = debugIn; // Get Keywords image_.InitImaging( !(actionArgs.hasKey("noimage")) ); double dist = actionArgs.getKeyDouble("distance", 7.0); byResidue_ = actionArgs.hasKey("byresidue"); resoffset_ = actionArgs.getKeyInt("resoffset", 0) + 1; if (resoffset_ < 1) { mprinterr("Error: Residue offset must be >= 0\n"); return Action::ERR; } includeSolvent_ = actionArgs.hasKey("includesolvent"); series_ = actionArgs.hasKey("series"); saveNonNative_ = actionArgs.hasKey("savenonnative"); if (actionArgs.hasKey("skipnative")) determineNativeContacts_ = false; if (!determineNativeContacts_ && !saveNonNative_) { mprintf("Warning: 'skipnative' specified; implies 'savenonnative'.\n"); saveNonNative_ = true; } # ifdef MPI if (saveNonNative_) { mprinterr("Error: Saving non-native contact data not yet supported for MPI\n"); return Action::ERR; } # endif distance_ = dist * dist; // Square the cutoff first_ = actionArgs.hasKey("first"); DataFile* outfile = init.DFL().AddDataFile( actionArgs.GetStringKey("out"), actionArgs ); Rseries_ = NO_RESSERIES; if (series_) { seriesout_ = init.DFL().AddDataFile(actionArgs.GetStringKey("seriesout"), actionArgs); init.DSL().SetDataSetsPending( true ); if (saveNonNative_) seriesNNout_ = init.DFL().AddDataFile(actionArgs.GetStringKey("seriesnnout"), actionArgs); std::string rs_arg = actionArgs.GetStringKey("resseries"); if (!rs_arg.empty()) { if (rs_arg == "present") Rseries_ = RES_PRESENT; else if (rs_arg == "sum") Rseries_ = RES_SUM; else { mprinterr("Error: '%s' is not a valid 'resseries' keyword.\n", rs_arg.c_str()); return Action::ERR; } seriesRout_ = init.DFL().AddDataFile(actionArgs.GetStringKey("resseriesout"), actionArgs); } } else { if (KeywordError(actionArgs,"seriesout")) return Action::ERR; if (KeywordError(actionArgs,"seriesnnout")) return Action::ERR; if (KeywordError(actionArgs,"resseries")) return Action::ERR; if (KeywordError(actionArgs,"resseriesout")) return Action::ERR; } cfile_ = init.DFL().AddCpptrajFile(actionArgs.GetStringKey("writecontacts"), "Native Contacts", DataFileList::TEXT, true); pfile_ = init.DFL().AddCpptrajFile(actionArgs.GetStringKey("contactpdb"), "Contact PDB", DataFileList::PDB); if (saveNonNative_) nfile_ = init.DFL().AddCpptrajFile(actionArgs.GetStringKey("nncontactpdb"), "Non-native Contact PDB", DataFileList::PDB); rfile_ = init.DFL().AddCpptrajFile(actionArgs.GetStringKey("resout"), "Contact Res Pairs", DataFileList::TEXT, true); if (cfile_ == 0 || rfile_ == 0) return Action::ERR; pdbcut_ = (float)actionArgs.getKeyDouble("pdbcut", -1.0); usepdbcut_ = (pdbcut_ > -1.0); // Get reference for native contacts. Do this even if we wont be // determining native contacts in order to set up contact lists. ReferenceFrame REF = init.DSL().GetReferenceFrame( actionArgs ); if (!first_) { if (REF.error()) return Action::ERR; if (REF.empty()) { mprintf("Warning: No reference structure specified. Defaulting to first.\n"); first_ = true; } } else { if (!REF.empty()) { mprinterr("Error: Must only specify 'first' or a reference structure, not both.\n"); return Action::ERR; } } // Create data sets std::string name = actionArgs.GetStringKey("name"); if (name.empty()) name = init.DSL().GenerateDefaultName("Contacts"); numnative_ = init.DSL().AddSet(DataSet::INTEGER, MetaData(name, "native")); nonnative_ = init.DSL().AddSet(DataSet::INTEGER, MetaData(name, "nonnative")); if (outfile != 0) { outfile->AddDataSet(numnative_); outfile->AddDataSet(nonnative_); } if (numnative_ == 0 || nonnative_ == 0) return Action::ERR; if (actionArgs.hasKey("mindist")) { mindist_ = init.DSL().AddSet(DataSet::DOUBLE, MetaData(name, "mindist")); if (mindist_ == 0) return Action::ERR; if (outfile != 0) outfile->AddDataSet(mindist_); } if (actionArgs.hasKey("maxdist")) { maxdist_ = init.DSL().AddSet(DataSet::DOUBLE, MetaData(name, "maxdist")); if (maxdist_ == 0) return Action::ERR; if (outfile != 0) outfile->AddDataSet(maxdist_); } DataFile *natmapfile = 0, *nonmapfile = 0; if (actionArgs.hasKey("map")) { nativeMap_ = (DataSet_MatrixDbl*)init.DSL().AddSet(DataSet::MATRIX_DBL, MetaData(name, "nativemap")); if (nativeMap_ == 0) return Action::ERR; nonnatMap_ = (DataSet_MatrixDbl*)init.DSL().AddSet(DataSet::MATRIX_DBL, MetaData(name, "nonnatmap")); if (nonnatMap_ == 0) return Action::ERR; FileName mapFilename; mapFilename.SetFileName( actionArgs.GetStringKey("mapout") ); if (!mapFilename.empty()) { natmapfile = init.DFL().AddDataFile(mapFilename.PrependFileName("native.")); if (natmapfile != 0) natmapfile->AddDataSet(nativeMap_); nonmapfile = init.DFL().AddDataFile(mapFilename.PrependFileName("nonnative.")); if (nonmapfile != 0) nonmapfile->AddDataSet(nonnatMap_); } } // Get Masks if (Mask1_.SetMaskString( actionArgs.GetMaskNext() )) return Action::ERR; std::string mask2 = actionArgs.GetMaskNext(); if (!mask2.empty()) { if (Mask2_.SetMaskString( mask2 )) return Action::ERR; } mprintf(" NATIVECONTACTS: Mask1='%s'", Mask1_.MaskString()); if (Mask2_.MaskStringSet()) mprintf(" Mask2='%s'", Mask2_.MaskString()); if (determineNativeContacts_) { mprintf(", native contacts set up based on"); if (first_) mprintf(" first frame.\n"); else mprintf("'%s'.\n", REF.refName()); } else { mprintf(", skipping native contacts set up.\n"); } if (byResidue_) { mprintf("\tContacts will be ignored for residues spaced < %i apart.\n", resoffset_); if (nativeMap_ != 0) mprintf("\tMap will be printed by residue.\n"); } if (saveNonNative_) mprintf("\tSaving non-native contacts as well (may use a lot of memory).\n"); mprintf("\tDistance cutoff is %g Angstroms,", sqrt(distance_)); if (!image_.UseImage()) mprintf(" imaging is off.\n"); else mprintf(" imaging is on.\n"); if (includeSolvent_) mprintf("\tMask selection will including solvent.\n"); else mprintf("\tMask selection will not include solvent.\n"); mprintf("\tData set name: %s\n", name.c_str()); if (maxdist_ != 0) mprintf("\tSaving maximum observed distances in set '%s'\n", maxdist_->legend()); if (mindist_ != 0) mprintf("\tSaving minimum observed distances in set '%s'\n", mindist_->legend()); if (outfile != 0) mprintf("\tOutput to '%s'\n", outfile->DataFilename().full()); mprintf("\tContact stats will be written to '%s'\n", cfile_->Filename().full()); mprintf("\tContact res pairs will be written to '%s'\n", rfile_->Filename().full()); if (pfile_ != 0) { mprintf("\tContact PDB will be written to '%s'\n", pfile_->Filename().full()); if (usepdbcut_) mprintf("\tOnly atoms with values > %g will be written to PDB.\n", pdbcut_); } if (nfile_ != 0) { mprintf("\tNon-native contact PDB will be written to '%s'\n", nfile_->Filename().full()); if (usepdbcut_) mprintf("\tOnly atoms with values > %g will be written to PDB.\n", pdbcut_); } if (nativeMap_ != 0) { mprintf("\tNative contacts map will be saved as set '%s'\n" "\tNon-native contacts map will be saved as set '%s'\n", nativeMap_->legend(), nonnatMap_->legend()); if (natmapfile!=0) mprintf("\tNative map output to '%s'\n",natmapfile->DataFilename().full()); if (nonmapfile!=0) mprintf("\tNative map output to '%s'\n",nonmapfile->DataFilename().full()); } if (series_) { mprintf("\tSaving native contact time series %s[NC].\n", name.c_str()); if (seriesout_ != 0) mprintf("\tWriting native contact time series to %s\n", seriesout_->DataFilename().full()); if (saveNonNative_) { mprintf("\tSaving non-native contact time series %s[NN]\n", name.c_str()); if (seriesNNout_ != 0) mprintf("\tWriting non-native contact time series to %s\n", seriesNNout_->DataFilename().full()); } if (Rseries_ != NO_RESSERIES) { if (Rseries_ == RES_PRESENT) mprintf("\tResidue contact time series will reflect presence of individual contacts.\n"); else if (Rseries_ == RES_SUM) mprintf("\tResidue contact time series will reflect sum of individual contacts.\n"); if (seriesRout_ != 0) mprintf("\tWriting residue contact time series to %s\n", seriesRout_->DataFilename().full()); } } // Set up reference if necessary. if (!first_) { // Set up imaging info for ref parm image_.SetupImaging( REF.CoordsInfo().TrajBox().Type() ); if (image_.ImageType() == NONORTHO) REF.Coord().BoxCrd().ToRecip(ucell_, recip_); if (DetermineNativeContacts( REF.Parm(), REF.Coord() )) return Action::ERR; } return Action::OK; }
// 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; }
Analysis::RetType Analysis_State::Setup(ArgList& analyzeArgs, DataSetList* datasetlist, DataFileList* DFLin, int debugIn) { debug_ = debugIn; masterDSL_ = datasetlist; DataFile* outfile = DFLin->AddDataFile( analyzeArgs.GetStringKey("out"), analyzeArgs ); curveOut_ = DFLin->AddDataFile( analyzeArgs.GetStringKey("curveout"), analyzeArgs ); stateOut_ = DFLin->AddCpptrajFile( analyzeArgs.GetStringKey("stateout"), "State Output", DataFileList::TEXT, true); transOut_ = DFLin->AddCpptrajFile( analyzeArgs.GetStringKey("transout"), "Transitions Output", DataFileList::TEXT, true); normalize_ = analyzeArgs.hasKey("norm"); // Get definitions of states if present. // Define states as 'state <#>,<dataset>,<min>,<max>' std::string state_arg = analyzeArgs.GetStringKey("state"); if (!state_arg.empty()) { while (!state_arg.empty()) { // Expect form <#>,<dataset> ArgList argtmp(state_arg, ","); if (argtmp.Nargs() != 4) { mprinterr("Error: Malformed state argument '%s': expect <ID>,<dataset>,<min>,<max>\n", state_arg.c_str()); return Analysis::ERR; } std::string state_id = argtmp.GetStringNext(); // TODO: Check duplicate names if (state_id.empty()) { mprinterr("Error: In state argument, could not get ID.\n"); return Analysis::ERR; } DataSet* ds = datasetlist->GetDataSet( argtmp.GetStringNext() ); if (ds == 0) return Analysis::ERR; if (ds->Ndim() != 1) { mprinterr("Error: Only 1D data sets allowed.\n"); return Analysis::ERR; } double min = argtmp.getNextDouble(0.0); double max = argtmp.getNextDouble(0.0); if (max < min) { mprinterr("Error: max value cannot be less than min.\n"); return Analysis::ERR; } States_.push_back( StateType(state_id, (DataSet_1D*)ds, min, max) ); state_arg = analyzeArgs.GetStringKey("state"); } } if (States_.empty()) { mprinterr("Error: No states defined.\n"); return Analysis::ERR; } state_data_ = datasetlist->AddSet(DataSet::INTEGER, analyzeArgs.GetStringKey("name"), "State"); if (state_data_ == 0) return Analysis::ERR; if (outfile != 0) outfile->AddDataSet( state_data_ ); mprintf(" STATE: The following states have been set up:\n"); for (StateArray::const_iterator state = States_.begin(); state != States_.end(); ++state) mprintf("\t%u: %20s %12.4f <= %-20s < %12.4f\n", state - States_.begin(), state->DS().legend(), state->Min(), state->id(), state->Max()); mprintf("\tState data set: %s\n", state_data_->legend()); if (outfile != 0) mprintf("\tStates vs time output to file '%s'\n", outfile->DataFilename().full()); if (curveOut_ != 0) mprintf("\tCurves output to file '%s'\n", curveOut_->DataFilename().full()); mprintf("\tState output to file '%s'\n", stateOut_->Filename().full()); mprintf("\tTransitions output to file '%s'\n", transOut_->Filename().full()); if (normalize_) mprintf("\tCurves will be normalized to 1.0\n"); return Analysis::OK; }
// Analysis_Matrix::Setup() Analysis::RetType Analysis_Matrix::Setup(ArgList& analyzeArgs, AnalysisSetup& setup, int debugIn) { #ifdef NO_MATHLIB mprinterr("Error: Compiled without LAPACK routines.\n"); return Analysis::ERR; #else // Get matrix name std::string mname = analyzeArgs.GetStringNext(); if (mname.empty()) { mprinterr("Error: Missing matrix name (first argument).\n"); return Analysis::ERR; } // Find matrix in DataSetList. matrix_ = (DataSet_2D*)setup.DSL().FindSetOfType( mname, DataSet::MATRIX_DBL ); if (matrix_ == 0) matrix_ = (DataSet_2D*)setup.DSL().FindSetOfType( mname, DataSet::MATRIX_FLT ); if (matrix_ == 0) { mprinterr("Error: Could not find matrix named %s\n",mname.c_str()); return Analysis::ERR; } // Check that matrix is symmetric (half-matrix incl. diagonal). if (matrix_->MatrixKind() != DataSet_2D::HALF) { mprinterr("Error: Only works for symmetric matrices (i.e. no mask2)\n"); return Analysis::ERR; } // nmwiz flag nmwizopt_ = analyzeArgs.hasKey("nmwiz"); if (nmwizopt_) { nmwizvecs_ = analyzeArgs.getKeyInt("nmwizvecs", 20); if (nmwizvecs_ < 1) { mprinterr("Error: nmwizvecs must be >= 1\n"); return Analysis::ERR; } nmwizfile_ = setup.DFL().AddCpptrajFile(analyzeArgs.GetStringKey("nmwizfile"), "NMwiz output", DataFileList::TEXT, true); Topology* parmIn = setup.DSL().GetTopology( analyzeArgs); // TODO: Include with matrix if (parmIn == 0) { mprinterr("Error: nmwiz: No topology specified.\n"); return Analysis::ERR; } AtomMask nmwizMask( analyzeArgs.GetStringKey("nmwizmask") ); if (parmIn->SetupIntegerMask( nmwizMask )) return Analysis::ERR; nmwizMask.MaskInfo(); Topology* nparm = parmIn->partialModifyStateByMask( nmwizMask ); if (nparm == 0) return Analysis::ERR; nmwizParm_ = *nparm; delete nparm; nmwizParm_.Brief("nmwiz topology"); } // Filenames DataFile* outfile = setup.DFL().AddDataFile( analyzeArgs.GetStringKey("out"), analyzeArgs); // Thermo flag thermopt_ = analyzeArgs.hasKey("thermo"); if (thermopt_) { outthermo_ = setup.DFL().AddCpptrajFile(analyzeArgs.GetStringKey("outthermo"), "'thermo' output", DataFileList::TEXT, true); if (outthermo_ == 0) return Analysis::ERR; } thermo_temp_ = analyzeArgs.getKeyDouble("temp", 298.15); if (thermopt_ && matrix_->Meta().ScalarType() != MetaData::MWCOVAR) { mprinterr("Error: Parameter 'thermo' only works for mass-weighted covariance matrix ('mwcovar').\n"); return Analysis::ERR; } // Number of eigenvectors; allow "0" only in case of 'thermo'. -1 means 'All' nevec_ = analyzeArgs.getKeyInt("vecs",-1); if (nevec_ == 0 && !thermopt_) { mprintf("Warning: # of eigenvectors specified is 0 and 'thermo' not specified.\n"); mprintf("Warning: Specify # eigenvectors with 'vecs <#>'. Setting to All.\n"); nevec_ = -1; } // Reduce flag reduce_ = analyzeArgs.hasKey("reduce"); // Set up DataSet_Modes. Set Modes DataSet type to be same as input matrix. MetaData md( analyzeArgs.GetStringKey("name") ); md.SetScalarType( matrix_->Meta().ScalarType() ); modes_ = (DataSet_Modes*)setup.DSL().AddSet( DataSet::MODES, md, "Modes" ); if (modes_==0) return Analysis::ERR; if (outfile != 0) outfile->AddDataSet( modes_ ); // Print Status mprintf(" DIAGMATRIX: Diagonalizing matrix %s",matrix_->legend()); if (outfile != 0) mprintf(" and writing modes to %s", outfile->DataFilename().full()); if (nevec_ > 0) mprintf("\n\tCalculating %i eigenvectors.\n", nevec_); else if (nevec_ == 0) mprintf("\n\tNot calculating eigenvectors.\n"); else mprintf("\n\tCalculating all eigenvectors.\n"); if (thermopt_) mprintf("\tCalculating thermodynamic data at %.2f K, output to %s\n", thermo_temp_, outthermo_->Filename().full()); if (nmwizopt_) mprintf("\tWriting %i modes to NMWiz file %s", nmwizvecs_, nmwizfile_->Filename().full()); if (nevec_>0 && reduce_) mprintf("\tEigenvectors will be reduced\n"); mprintf("\tStoring modes with name: %s\n", modes_->Meta().Name().c_str()); return Analysis::OK; #endif }
Action::RetType Action_DNAionTracker::Init(ArgList& actionArgs, TopologyList* PFL, DataSetList* DSL, DataFileList* DFL, int debugIn) { // Get keywords DataFile* outfile = DFL->AddDataFile(actionArgs.GetStringKey("out"), actionArgs); poffset_ = actionArgs.getKeyDouble("poffset", 5.0); InitImaging( !actionArgs.hasKey("noimage") ); if (actionArgs.hasKey("shortest")) bintype_ = SHORTEST; else if (actionArgs.hasKey("counttopcone")) bintype_ = TOPCONE; else if (actionArgs.hasKey("countbottomcone")) bintype_ = BOTTOMCONE; else if (actionArgs.hasKey("count")) bintype_ = COUNT; // Get masks - 4 must be specified std::string m1 = actionArgs.GetMaskNext(); std::string m2 = actionArgs.GetMaskNext(); std::string m3 = actionArgs.GetMaskNext(); std::string m4 = actionArgs.GetMaskNext(); if (m1.empty() || m2.empty() || m3.empty() || m4.empty()) { mprinterr("Error: dnaiontracker requires 4 masks.\n"); return Action::ERR; } p1_.SetMaskString(m1); p2_.SetMaskString(m2); base_.SetMaskString(m3); ions_.SetMaskString(m4); // Add dataset to dataset list (and datafile list if filename specified) distance_ = DSL->AddSet(DataSet::DOUBLE, MetaData(actionArgs.GetStringNext(), MetaData::M_DISTANCE), "DNAion"); if (distance_==0) return Action::ERR; if (outfile != 0) outfile->AddDataSet( distance_ ); // INFO mprintf(" DNAIONTRACKER: Data representing the "); switch (bintype_) { case COUNT : mprintf("count within the cone will be\n"); break; case SHORTEST: mprintf("shortest distance to a phosphate or base centroid will be\n"); break; case TOPCONE: mprintf("count in the top half of the cone (and sort-of bound) will be\n"); break; case BOTTOMCONE: mprintf("count in the bottom half of the cone will be\n"); break; } mprintf(" saved to array named %s\n", distance_->legend()); mprintf(" Perpendicular offset for cone is %5.2f angstroms\n", poffset_); if (!UseImage()) mprintf(" Imaging has been disabled\n"); mprintf("\tPhosphate1 Mask [%s]\n", p1_.MaskString()); mprintf("\tPhosphate2 Mask [%s]\n", p2_.MaskString()); mprintf("\tBase Mask [%s]\n", base_.MaskString()); mprintf("\tIons Mask [%s]\n", ions_.MaskString()); if (outfile != 0) mprintf("\tData will be printed to a file named %s\n", outfile->DataFilename().full()); return Action::OK; }
Analysis::RetType Analysis_Lifetime::Setup(ArgList& analyzeArgs, DataSetList* datasetlist, TopologyList* PFLin, DataFileList* DFLin, int debugIn) { // Get Keywords DataFile* outfile = DFLin->AddDataFile(analyzeArgs.GetStringKey("out"), analyzeArgs); if (outfile != 0) outfile->ProcessArgs("noemptyframes"); DataFile* maxfile = 0; DataFile* avgfile = 0; std::string setname = analyzeArgs.GetStringKey("name"); windowSize_ = analyzeArgs.getKeyInt("window", -1); averageonly_ = analyzeArgs.hasKey("averageonly"); if (!averageonly_ && outfile != 0) { maxfile = DFLin->AddDataFile("max." + outfile->DataFilename().Full(), analyzeArgs); maxfile->ProcessArgs("noemptyframes"); avgfile = DFLin->AddDataFile("avg." + outfile->DataFilename().Full(), analyzeArgs); avgfile->ProcessArgs("noemptyframes"); } cumulative_ = analyzeArgs.hasKey("cumulative"); deltaAvg_ = analyzeArgs.hasKey("delta"); cut_ = analyzeArgs.getKeyDouble("cut", 0.5); // Select datasets from remaining args ArgList dsetArgs = analyzeArgs.RemainingArgs(); for (ArgList::const_iterator dsa = dsetArgs.begin(); dsa != dsetArgs.end(); ++dsa) inputDsets_ += datasetlist->GetMultipleSets( *dsa ); if (inputDsets_.empty()) { mprinterr("Error: lifetime: No data sets selected.\n"); return Analysis::ERR; } // Sort input datasets inputDsets_.sort(); // Create output datasets if ( windowSize_ != -1) { if (setname.empty()) setname = datasetlist->GenerateDefaultName( "lifetime" ); int didx = 0; for (DataSetList::const_iterator set = inputDsets_.begin(); set != inputDsets_.end(); ++set) { DataSet* outSet = datasetlist->AddSetIdx( DataSet::FLOAT, setname, didx ); if (outSet==0) { mprinterr("Error: lifetime: Could not allocate output set for %s\n", (*set)->Legend().c_str()); return Analysis::ERR; } outSet->SetLegend( (*set)->Legend() ); outputDsets_.push_back( outSet ); if (outfile != 0) outfile->AddSet( outSet ); if (!averageonly_) { // MAX // FIXME: CHeck for nullS outSet = datasetlist->AddSetIdxAspect( DataSet::INT, setname, didx, "max" ); outSet->SetLegend( (*set)->Legend() ); maxDsets_.push_back( outSet ); if (maxfile != 0) maxfile->AddSet( outSet ); // AVG outSet = datasetlist->AddSetIdxAspect( DataSet::FLOAT, setname, didx, "avg" ); outSet->SetLegend( (*set)->Legend() ); avgDsets_.push_back( outSet ); if (avgfile != 0) avgfile->AddSet( outSet ); } ++didx; } } else if (outfile != 0) { mprinterr("Error: Output file name specified but no window size given ('window <N>')\n"); return Analysis::ERR; } if (!averageonly_) mprintf(" LIFETIME: Calculating average lifetime using a cutoff of %f", cut_); else mprintf(" LIFETIME: Calculating only averages"); mprintf(" of data in %i sets\n", inputDsets_.size()); if (debugIn > 0) inputDsets_.List(); if (windowSize_ != -1) { mprintf("\tAverage of data over windows will be saved to sets named %s\n", setname.c_str()); mprintf("\tWindow size for averaging: %i\n", windowSize_); if (cumulative_) mprintf("\tCumulative averages will be saved.\n"); if (deltaAvg_) mprintf("\tChange of average from previous average will be saved.\n"); if (outfile != 0) { mprintf("\tOutfile: %s", outfile->DataFilename().base()); if (!averageonly_) mprintf(", %s, %s", maxfile->DataFilename().base(), avgfile->DataFilename().base()); mprintf("\n"); } } return Analysis::OK; }
// Analysis_Modes::Setup() Analysis::RetType Analysis_Modes::Setup(ArgList& analyzeArgs, AnalysisSetup& setup, int debugIn) { debug_ = debugIn; // Analysis type if (analyzeArgs.hasKey("fluct")) type_ = FLUCT; else if (analyzeArgs.hasKey("displ")) type_ = DISPLACE; else if (analyzeArgs.hasKey("corr")) type_ = CORR; else if (analyzeArgs.Contains("trajout")) type_ = TRAJ; else if (analyzeArgs.hasKey("eigenval")) type_ = EIGENVAL; else if (analyzeArgs.hasKey("rmsip")) type_ = RMSIP; else { mprinterr("Error: No analysis type specified.\n"); return Analysis::ERR; } // Get modes name std::string modesfile = analyzeArgs.GetStringKey("name"); if (modesfile.empty()) { // Check for deprecated args CheckDeprecated(analyzeArgs, modesfile, "file"); CheckDeprecated(analyzeArgs, modesfile, "stack"); if (modesfile.empty()) { mprinterr("Error: No 'name <modes data set name>' argument given.\n"); return Analysis::ERR; } } // Get second modes name for RMSIP std::string modesfile2 = analyzeArgs.GetStringKey("name2"); if (type_ == RMSIP) { if (modesfile2.empty()) { mprinterr("Error: 'rmsip' requires second modes data 'name2 <modes>'\n"); return Analysis::ERR; } } else modesfile2.clear(); // Get topology for TRAJ/CORR Topology* analyzeParm = setup.DSL().GetTopology( analyzeArgs ); if (type_ == TRAJ ) { // Get trajectory format args for projected traj beg_ = analyzeArgs.getKeyInt("beg",1) - 1; // Args start at 1 std::string tOutName = analyzeArgs.GetStringKey("trajout"); if (tOutName.empty()) { mprinterr("Error: Require output trajectory filename, 'trajout <name>'\n"); return Analysis::ERR; } TrajectoryFile::TrajFormatType tOutFmt = TrajectoryFile::UNKNOWN_TRAJ; if ( analyzeArgs.Contains("trajoutfmt") ) tOutFmt = TrajectoryFile::GetFormatFromString( analyzeArgs.GetStringKey("trajoutfmt") ); if (analyzeParm == 0) { mprinterr("Error: Could not get topology for output trajectory.\n"); return Analysis::ERR; } AtomMask tOutMask( analyzeArgs.GetStringKey("trajoutmask") ); if ( analyzeParm->SetupIntegerMask( tOutMask ) || tOutMask.None() ) { mprinterr("Error: Could not setup output trajectory mask.\n"); return Analysis::ERR; } tOutMask.MaskInfo(); // Strip topology to match mask. if (tOutParm_ != 0) delete tOutParm_; tOutParm_ = analyzeParm->modifyStateByMask( tOutMask ); if (tOutParm_ == 0) { mprinterr("Error: Could not create topology to match mask.\n"); return Analysis::ERR; } // Setup output traj if (trajout_.InitTrajWrite( tOutName, ArgList(), tOutFmt ) != 0) { mprinterr("Error: Could not init output trajectory.\n"); return Analysis::ERR; } // Get min and max for PC pcmin_ = analyzeArgs.getKeyDouble("pcmin", -10.0); pcmax_ = analyzeArgs.getKeyDouble("pcmax", 10.0); if (pcmax_ < pcmin_ || pcmax_ - pcmin_ < Constants::SMALL) { mprinterr("Error: pcmin must be less than pcmax\n"); return Analysis::ERR; } tMode_ = analyzeArgs.getKeyInt("tmode", 1); } else { // Args for everything else beg_ = analyzeArgs.getKeyInt("beg",7) - 1; // Args start at 1 bose_ = analyzeArgs.hasKey("bose"); calcAll_ = analyzeArgs.hasKey("calcall"); } end_ = analyzeArgs.getKeyInt("end", 50); factor_ = analyzeArgs.getKeyDouble("factor",1.0); std::string setname = analyzeArgs.GetStringKey("setname"); // Check if modes name exists on the stack modinfo_ = (DataSet_Modes*)setup.DSL().FindSetOfType( modesfile, DataSet::MODES ); if (modinfo_ == 0) { mprinterr("Error: '%s' not found: %s\n", modesfile.c_str(), DataSet_Modes::DeprecateFileMsg); return Analysis::ERR; } if (!modesfile2.empty()) { modinfo2_ = (DataSet_Modes*)setup.DSL().FindSetOfType( modesfile2, DataSet::MODES ); if (modinfo2_ == 0) { mprinterr("Error: Set %s not found.\n", modesfile2.c_str()); return Analysis::ERR; } } // Check modes type for specified analysis if (type_ == FLUCT || type_ == DISPLACE || type_ == CORR || type_ == TRAJ) { if (modinfo_->Meta().ScalarType() != MetaData::COVAR && modinfo_->Meta().ScalarType() != MetaData::MWCOVAR) { mprinterr("Error: Modes must be of type COVAR or MWCOVAR for %s.\n", analysisTypeString[type_]); return Analysis::ERR; } } // Get output filename for types that use DataSets std::string outfilename = analyzeArgs.GetStringKey("out"); // TODO all datafile? DataFile* dataout = 0; if (type_ == FLUCT || type_ == DISPLACE || type_ == EIGENVAL || type_ == RMSIP) dataout = setup.DFL().AddDataFile( outfilename, analyzeArgs ); else if (type_ == CORR) { // CORR-specific setup outfile_ = setup.DFL().AddCpptrajFile( outfilename, "Modes analysis", DataFileList::TEXT, true ); if (outfile_ == 0) return Analysis::ERR; // Get list of atom pairs if (analyzeParm == 0) { mprinterr("Error: 'corr' requires topology.\n"); return Analysis::ERR; } std::string maskexp = analyzeArgs.GetStringKey("mask1"); if (maskexp.empty()) { while (analyzeArgs.hasKey("maskp")) { // Next two arguments should be one-atom masks std::string a1mask = analyzeArgs.GetMaskNext(); std::string a2mask = analyzeArgs.GetMaskNext(); if (a1mask.empty() || a2mask.empty()) { mprinterr("Error: For 'corr' two 1-atom masks are expected.\n"); return Analysis::ERR; } // Check that each mask is just 1 atom AtomMask m1( a1mask ); AtomMask m2( a2mask ); analyzeParm->SetupIntegerMask( m1 ); analyzeParm->SetupIntegerMask( m2 ); if ( m1.Nselected()==1 && m2.Nselected()==1 ) // Store atom pair atompairStack_.push_back( std::pair<int,int>( m1[0], m2[0] ) ); else { mprinterr("Error: For 'corr', masks should specify only one atom.\n" "\tM1[%s]=%i atoms, M2[%s]=%i atoms.\n", m1.MaskString(), m1.Nselected(), m2.MaskString(), m2.Nselected()); return Analysis::ERR; } } } else { AtomMask mask1( maskexp ); maskexp = analyzeArgs.GetStringKey("mask2"); if (maskexp.empty()) { mprinterr("Error: 'mask2' must be specified if 'mask1' is.\n"); return Analysis::ERR; } AtomMask mask2( maskexp ); if ( analyzeParm->SetupIntegerMask( mask1 ) ) return Analysis::ERR; if ( analyzeParm->SetupIntegerMask( mask2 ) ) return Analysis::ERR; mask1.MaskInfo(); mask2.MaskInfo(); if (mask1.None() || mask2.None()) { mprinterr("Error: One or both masks are empty.\n"); return Analysis::ERR; } if (mask1.Nselected() != mask2.Nselected()) { mprinterr("Error: # atoms in mask 1 not equal to # atoms in mask 2.\n"); return Analysis::ERR; } for (int idx = 0; idx != mask1.Nselected(); idx++) atompairStack_.push_back( std::pair<int,int>( mask1[idx], mask2[idx] ) ); } if ( atompairStack_.empty() ) { mprinterr("Error: No atom pairs found (use 'maskp' or 'mask1'/'mask2' keywords.)\n"); return Analysis::ERR; } } // Set up data sets Dimension Xdim; if (type_ == FLUCT) { if (setname.empty()) setname = setup.DSL().GenerateDefaultName("FLUCT"); MetaData md(setname, "rmsX"); OutSets_.resize( 4, 0 ); OutSets_[RMSX] = setup.DSL().AddSet( DataSet::DOUBLE, md ); md.SetAspect("rmsY"); OutSets_[RMSY] = setup.DSL().AddSet( DataSet::DOUBLE, md ); md.SetAspect("rmsZ"); OutSets_[RMSZ] = setup.DSL().AddSet( DataSet::DOUBLE, md ); md.SetAspect("rms"); OutSets_[RMS] = setup.DSL().AddSet( DataSet::DOUBLE, md ); Xdim = Dimension(1, 1, "Atom_no."); } else if (type_ == DISPLACE) { if (setname.empty()) setname = setup.DSL().GenerateDefaultName("DISPL"); MetaData md(setname, "displX"); OutSets_.resize( 3, 0 ); OutSets_[RMSX] = setup.DSL().AddSet( DataSet::DOUBLE, md ); md.SetAspect("displY"); OutSets_[RMSY] = setup.DSL().AddSet( DataSet::DOUBLE, md ); md.SetAspect("displZ"); OutSets_[RMSZ] = setup.DSL().AddSet( DataSet::DOUBLE, md ); Xdim = Dimension(1, 1, "Atom_no."); } else if (type_ == EIGENVAL) { if (setname.empty()) setname = setup.DSL().GenerateDefaultName("XEVAL"); MetaData md(setname, "Frac"); OutSets_.resize( 3, 0 ); OutSets_[0] = setup.DSL().AddSet( DataSet::DOUBLE, md ); md.SetAspect("Cumulative"); OutSets_[1] = setup.DSL().AddSet( DataSet::DOUBLE, md ); md.SetAspect("Eigenval"); OutSets_[2] = setup.DSL().AddSet( DataSet::DOUBLE, md ); Xdim = Dimension( 1, 1, "Mode" ); } else if (type_ == RMSIP) { if (setname.empty()) setname = setup.DSL().GenerateDefaultName("RMSIP"); OutSets_.push_back( setup.DSL().AddSet( DataSet::DOUBLE, setname ) ); if (dataout != 0) dataout->ProcessArgs("noxcol"); OutSets_[0]->SetupFormat() = TextFormat(TextFormat::GDOUBLE); OutSets_[0]->SetLegend( modinfo_->Meta().Legend() + "_X_" + modinfo2_->Meta().Legend() ); } for (std::vector<DataSet*>::const_iterator set = OutSets_.begin(); set != OutSets_.end(); ++set) { if (*set == 0) return Analysis::ERR; if (dataout != 0) dataout->AddDataSet( *set ); (*set)->SetDim(Dimension::X, Xdim); } // Status mprintf(" ANALYZE MODES: Calculating %s using modes from %s", analysisTypeString[type_], modinfo_->legend()); if ( type_ != TRAJ ) { if (type_ != EIGENVAL) mprintf(", modes %i to %i", beg_+1, end_); if (outfile_ != 0) mprintf("\n\tResults are written to %s\n", outfile_->Filename().full()); else if (dataout != 0) mprintf("\n\tResults are written to '%s'\n", dataout->DataFilename().full()); if (type_ != EIGENVAL && type_ != RMSIP) { if (bose_) mprintf("\tBose statistics used.\n"); else mprintf("\tBoltzmann statistics used.\n"); if (calcAll_) mprintf("\tEigenvectors associated with zero or negative eigenvalues will be used.\n"); else mprintf("\tEigenvectors associated with zero or negative eigenvalues will be skipped.\n"); } if (type_ == DISPLACE) mprintf("\tFactor for displacement: %f\n", factor_); if (type_ == CORR) { mprintf("\tUsing the following atom pairs:"); for (modestack_it apair = atompairStack_.begin(); apair != atompairStack_.end(); ++apair) mprintf(" (%i,%i)", apair->first+1, apair->second+1 ); mprintf("\n"); } if (type_ == RMSIP) mprintf("\tRMSIP calculated to modes in %s\n", modinfo2_->legend()); } else { mprintf("\n\tCreating trajectory for mode %i\n" "\tWriting to trajectory %s\n" "\tPC range: %f to %f\n" "\tScaling factor: %f\n", tMode_, trajout_.Traj().Filename().full(), pcmin_, pcmax_, factor_); } return Analysis::OK; }
// 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; }
// Analysis_HausdorffDistance::Setup() Analysis::RetType Analysis_HausdorffDistance::Setup(ArgList& analyzeArgs, AnalysisSetup& setup, int debugIn) { // Keywords int nrows = -1; int ncols = -1; std::string outtypearg = analyzeArgs.GetStringKey("outtype"); if (!outtypearg.empty()) { if (outtypearg == "basic") outType_ = BASIC; else if (outtypearg == "trimatrix") { outType_ = UPPER_TRI_MATRIX; nrows = analyzeArgs.getKeyInt("nrows", -1); if (nrows < 1) { mprinterr("Error: 'nrows' must be specified and > 0 for 'trimatrix'\n"); return Analysis::ERR; } } else if (outtypearg == "fullmatrix") { outType_ = FULL_MATRIX; nrows = analyzeArgs.getKeyInt("nrows", -1); if (nrows < 1) { mprinterr("Error: 'nrows' must be specified and > 0 for 'fullmatrix'\n"); return Analysis::ERR; } ncols = analyzeArgs.getKeyInt("ncols", nrows); if (ncols < 1) { mprinterr("Error: 'ncols' must be > 0 for 'fullmatrix'\n"); return Analysis::ERR; } } else { mprinterr("Error: Unrecognized keyword for 'outtype': %s\n", outtypearg.c_str()); return Analysis::ERR; } } else outType_ = BASIC; std::string dsname = analyzeArgs.GetStringKey("name"); DataFile* df = setup.DFL().AddDataFile( analyzeArgs.GetStringKey("out"), analyzeArgs ); DataFile* dfab = setup.DFL().AddDataFile( analyzeArgs.GetStringKey("outab"), analyzeArgs ); DataFile* dfba = setup.DFL().AddDataFile( analyzeArgs.GetStringKey("outba"), analyzeArgs ); // Get input data sets std::string dsarg = analyzeArgs.GetStringNext(); while (!dsarg.empty()) { DataSetList selected = setup.DSL().GetMultipleSets( dsarg ); for (DataSetList::const_iterator set = selected.begin(); set != selected.end(); ++set) { if ((*set)->Group() == DataSet::MATRIX_2D) inputSets_.AddCopyOfSet( *set ); else mprintf("Warning: Currently only 2D matrices supported; skipping set '%s'\n", (*set)->legend()); } //inputSets_ += setup.DSL().GetMultipleSets( dsarg ); dsarg = analyzeArgs.GetStringNext(); } if (inputSets_.empty()) { mprinterr("Error: No data sets specified.\n"); return Analysis::ERR; } // Output data set out_ = 0; if (outType_ == BASIC) { out_ = setup.DSL().AddSet(DataSet::FLOAT, dsname, "HAUSDORFF"); if (out_ == 0) return Analysis::ERR; // Directed sets ab_out_ = setup.DSL().AddSet(DataSet::FLOAT, MetaData(out_->Meta().Name(),"AB")); if (ab_out_ == 0) return Analysis::ERR; ba_out_ = setup.DSL().AddSet(DataSet::FLOAT, MetaData(out_->Meta().Name(),"BA")); if (ba_out_ == 0) return Analysis::ERR; } else if (outType_ == UPPER_TRI_MATRIX || outType_ == FULL_MATRIX) { out_ = setup.DSL().AddSet(DataSet::MATRIX_FLT, dsname, "HAUSDORFF"); ab_out_ = setup.DSL().AddSet(DataSet::MATRIX_FLT, MetaData(out_->Meta().Name(),"AB")); ba_out_ = setup.DSL().AddSet(DataSet::MATRIX_FLT, MetaData(out_->Meta().Name(),"BA")); if (out_ == 0 || ab_out_ == 0 || ba_out_ == 0) return Analysis::ERR; if (outType_ == UPPER_TRI_MATRIX) { if (((DataSet_2D*)out_)->AllocateTriangle( nrows )) return Analysis::ERR; if (((DataSet_2D*)ab_out_)->AllocateTriangle( nrows )) return Analysis::ERR; if (((DataSet_2D*)ba_out_)->AllocateTriangle( nrows )) return Analysis::ERR; } else if (outType_ == FULL_MATRIX) { if (((DataSet_2D*)out_)->Allocate2D( nrows,ncols )) return Analysis::ERR; if (((DataSet_2D*)ab_out_)->Allocate2D( nrows,ncols )) return Analysis::ERR; if (((DataSet_2D*)ba_out_)->Allocate2D( nrows,ncols )) return Analysis::ERR; } if (out_->Size() != inputSets_.size()) { mprinterr("Warning: Number of input data sets (%zu) != number of expected" " sets in matrix (%zu)\n", inputSets_.size(), out_->Size()); return Analysis::ERR; } // Directed sets } if (df != 0) df->AddDataSet( out_ ); if (dfab != 0) df->AddDataSet( ab_out_ ); if (dfba != 0) df->AddDataSet( ba_out_ ); mprintf(" HAUSDORFF:\n"); mprintf("\tCalculating Hausdorff distances from the following 2D distance matrices:\n\t "); for (DataSetList::const_iterator it = inputSets_.begin(); it != inputSets_.end(); ++it) mprintf(" %s", (*it)->legend()); mprintf("\n"); if (outType_ == BASIC) mprintf("\tOutput will be stored in 1D array set '%s'\n", out_->legend()); else if (outType_ == UPPER_TRI_MATRIX) mprintf("\tOutput will be stored in upper-triangular matrix set '%s' with %i rows.\n", out_->legend(), nrows); else if (outType_ == FULL_MATRIX) mprintf("\tOutput will be stored in matrix set '%s' with %i rows, %i columns.\n", out_->legend(), nrows, ncols); mprintf("\tDirected A->B distance output set: %s\n", ab_out_->legend()); mprintf("\tDirected B->A distance output set: %s\n", ba_out_->legend()); if (df != 0) mprintf("\tOutput set written to '%s'\n", df->DataFilename().full()); if (dfab != 0) mprintf("\tA->B output set written to '%s'\n", dfab->DataFilename().full()); if (dfba != 0) mprintf("\tB->A output set written to '%s'\n", dfba->DataFilename().full()); return Analysis::OK; }
// Action_Radial::Init() Action::RetType Action_Radial::Init(ArgList& actionArgs, ActionInit& init, int debugIn) { debug_ = debugIn; // Get Keywords image_.InitImaging( !(actionArgs.hasKey("noimage")) ); std::string outfilename = actionArgs.GetStringKey("out"); // Default particle density (mols/Ang^3) for water based on 1.0 g/mL density_ = actionArgs.getKeyDouble("density",0.033456); if (actionArgs.hasKey("center1")) rmode_ = CENTER1; else if (actionArgs.hasKey("center2")) rmode_ = CENTER2; else if (actionArgs.hasKey("nointramol")) rmode_ = NO_INTRAMOL; else rmode_ = NORMAL; useVolume_ = actionArgs.hasKey("volume"); DataFile* intrdfFile = init.DFL().AddDataFile(actionArgs.GetStringKey("intrdf")); DataFile* rawrdfFile = init.DFL().AddDataFile(actionArgs.GetStringKey("rawrdf")); spacing_ = actionArgs.getNextDouble(-1.0); if (spacing_ < 0) { mprinterr("Error: Radial: No spacing argument or arg < 0.\n"); Help(); return Action::ERR; } double maximum = actionArgs.getNextDouble(-1.0); if (maximum < 0) { mprinterr("Error: Radial: No maximum argument or arg < 0.\n"); Help(); return Action::ERR; } // Store max^2, distances^2 greater than max^2 do not need to be // binned and therefore do not need a sqrt calc. maximum2_ = maximum * maximum; // Get First Mask std::string mask1 = actionArgs.GetMaskNext(); if (mask1.empty()) { mprinterr("Error: Radial: No mask given.\n"); return Action::ERR; } Mask1_.SetMaskString(mask1); // Check for second mask - if none specified use first mask std::string mask2 = actionArgs.GetMaskNext(); if (!mask2.empty()) Mask2_.SetMaskString(mask2); else Mask2_.SetMaskString(mask1); // If filename not yet specified check for backwards compat. if (outfilename.empty() && actionArgs.Nargs() > 1 && !actionArgs.Marked(1)) outfilename = actionArgs.GetStringNext(); // Set up output dataset. Dset_ = init.DSL().AddSet( DataSet::DOUBLE, actionArgs.GetStringNext(), "g(r)"); if (Dset_ == 0) return RDF_ERR("Could not allocate RDF data set."); DataFile* outfile = init.DFL().AddDataFile(outfilename, actionArgs); if (outfile != 0) outfile->AddDataSet( Dset_ ); // Make default precision a little higher than normal Dset_->SetupFormat().SetFormatWidthPrecision(12,6); // Set DataSet legend from mask strings. Dset_->SetLegend(Mask1_.MaskExpression() + " => " + Mask2_.MaskExpression()); // TODO: Set Yaxis label in DataFile // Calculate number of bins one_over_spacing_ = 1 / spacing_; double temp_numbins = maximum * one_over_spacing_; temp_numbins = ceil(temp_numbins); numBins_ = (int) temp_numbins; // Setup output datafile. Align on bin centers instead of left. // TODO: Use Rdim for binning? Dimension Rdim( spacing_ / 2.0, spacing_, "Distance (Ang)" ); Dset_->SetDim(Dimension::X, Rdim); // Set up output for integral of mask2 if specified. if (intrdfFile != 0) { intrdf_ = init.DSL().AddSet( DataSet::DOUBLE, MetaData(Dset_->Meta().Name(), "int" )); if (intrdf_ == 0) return RDF_ERR("Could not allocate RDF integral data set."); intrdf_->SetupFormat().SetFormatWidthPrecision(12,6); intrdf_->SetLegend("Int[" + Mask2_.MaskExpression() + "]"); intrdf_->SetDim(Dimension::X, Rdim); intrdfFile->AddDataSet( intrdf_ ); } else intrdf_ = 0; // Set up output for raw rdf if (rawrdfFile != 0) { rawrdf_ = init.DSL().AddSet( DataSet::DOUBLE, MetaData(Dset_->Meta().Name(), "raw" )); if (rawrdf_ == 0) return RDF_ERR("Could not allocate raw RDF data set."); rawrdf_->SetupFormat().SetFormatWidthPrecision(12,6); rawrdf_->SetLegend("Raw[" + Dset_->Meta().Legend() + "]"); rawrdf_->SetDim(Dimension::X, Rdim); rawrdfFile->AddDataSet( rawrdf_ ); } else rawrdf_ = 0; // Set up histogram RDF_ = new int[ numBins_ ]; std::fill(RDF_, RDF_ + numBins_, 0); # ifdef _OPENMP // Since RDF is shared by all threads and we cant guarantee that a given // bin in RDF wont be accessed at the same time by the same thread, // each thread needs its own bin space. #pragma omp parallel { if (omp_get_thread_num()==0) numthreads_ = omp_get_num_threads(); } rdf_thread_ = new int*[ numthreads_ ]; for (int i=0; i < numthreads_; i++) { rdf_thread_[i] = new int[ numBins_ ]; std::fill(rdf_thread_[i], rdf_thread_[i] + numBins_, 0); } # endif mprintf(" RADIAL: Calculating RDF for atoms in mask [%s]",Mask1_.MaskString()); if (!mask2.empty()) mprintf(" to atoms in mask [%s]",Mask2_.MaskString()); mprintf("\n"); if (outfile != 0) mprintf(" Output to %s.\n", outfile->DataFilename().full()); if (intrdf_ != 0) mprintf(" Integral of mask2 atoms will be output to %s\n", intrdfFile->DataFilename().full()); if (rawrdf_ != 0) mprintf(" Raw RDF bin values will be output to %s\n", rawrdfFile->DataFilename().full()); if (rmode_==CENTER1) mprintf(" Using center of atoms in mask1.\n"); else if (rmode_==CENTER2) mprintf(" Using center of atoms in mask2.\n"); mprintf(" Histogram max %f, spacing %f, bins %i.\n",maximum, spacing_,numBins_); if (useVolume_) mprintf(" Normalizing based on cell volume.\n"); else mprintf(" Normalizing using particle density of %f molecules/Ang^3.\n",density_); if (!image_.UseImage()) mprintf(" Imaging disabled.\n"); if (numthreads_ > 1) mprintf(" Parallelizing RDF calculation with %i threads.\n",numthreads_); return Action::OK; }
// Analysis_Lifetime::Setup() Analysis::RetType Analysis_Lifetime::Setup(ArgList& analyzeArgs, DataSetList* datasetlist, TopologyList* PFLin, DataFileList* DFLin, int debugIn) { // Get Keywords FileName outfileName( analyzeArgs.GetStringKey("out") ); std::string setname = analyzeArgs.GetStringKey("name"); bool sortSets = (!analyzeArgs.hasKey("nosort")); windowSize_ = analyzeArgs.getKeyInt("window", -1); averageonly_ = analyzeArgs.hasKey("averageonly"); cumulative_ = analyzeArgs.hasKey("cumulative"); deltaAvg_ = analyzeArgs.hasKey("delta"); cut_ = analyzeArgs.getKeyDouble("cut", 0.5); fuzzCut_ = analyzeArgs.getKeyInt("fuzz", -1); if (fuzzCut_ < 1) fuzzCut_ = -1; normalizeCurves_ = !analyzeArgs.hasKey("rawcurve"); if (analyzeArgs.hasKey("greater")) Compare_ = Compare_GreaterThan; else if (analyzeArgs.hasKey("less")) Compare_ = Compare_LessThan; else Compare_ = Compare_GreaterThan; // Select datasets from remaining args if (inputDsets_.AddSetsFromArgs( analyzeArgs.RemainingArgs(), *datasetlist )) { mprinterr("Error: lifetime: Could not add data sets.\n"); return Analysis::ERR; } // Sort data sets if (sortSets) inputDsets_.SortArray1D(); // Create output datasets DataFile* outfile = 0; DataFile* maxfile = 0; DataFile* avgfile = 0; if (setname.empty()) setname = datasetlist->GenerateDefaultName( "lifetime" ); if ( windowSize_ != -1) { outfile = DFLin->AddDataFile(outfileName, analyzeArgs); if (!averageonly_ && outfile != 0) { maxfile = DFLin->AddDataFile(outfileName.DirPrefix() + "max." + outfileName.Base(), analyzeArgs); avgfile = DFLin->AddDataFile(outfileName.DirPrefix() + "avg." + outfileName.Base(), analyzeArgs); } int didx = 0; for (Array1D::const_iterator set = inputDsets_.begin(); set != inputDsets_.end(); ++set) { MetaData md(setname, didx); md.SetLegend( (*set)->Meta().Legend() ); DataSet_1D* outSet = (DataSet_1D*)datasetlist->AddSet( DataSet::FLOAT, md ); if (CheckDsetError(outSet, "output", (*set)->legend())) return Analysis::ERR; outputDsets_.push_back( outSet ); if (outfile != 0) outfile->AddDataSet( outSet ); if (!averageonly_) { // MAX md.SetAspect("max"); outSet = (DataSet_1D*)datasetlist->AddSet(DataSet::INTEGER, md); if (CheckDsetError(outSet, "lifetime max", (*set)->legend())) return Analysis::ERR; maxDsets_.push_back( outSet ); if (maxfile != 0) maxfile->AddDataSet( outSet ); // AVG md.SetAspect("avg"); outSet = (DataSet_1D*)datasetlist->AddSet(DataSet::FLOAT, md); if (CheckDsetError(outSet, "lifetime avg", (*set)->legend())) return Analysis::ERR; avgDsets_.push_back( outSet ); if (avgfile != 0) avgfile->AddDataSet( outSet ); } ++didx; } // Set step to window size. std::string fileArgs = "xstep " + integerToString( windowSize_ ); if (outfile != 0) outfile->ProcessArgs( fileArgs ); if (maxfile != 0) maxfile->ProcessArgs( fileArgs ); if (avgfile != 0) avgfile->ProcessArgs( fileArgs ); } // Lifetime curves DataFile* crvfile = 0; if (!averageonly_) { if (!outfileName.empty()) { crvfile = DFLin->AddDataFile(outfileName.DirPrefix() + "crv." + outfileName.Base(), analyzeArgs); } MetaData md(setname, "curve"); for (int didx = 0; didx != (int)inputDsets_.size(); didx++) { md.SetIdx(didx); DataSet_1D* outSet = (DataSet_1D*)datasetlist->AddSet(DataSet::DOUBLE, md); if (CheckDsetError(outSet, "lifetime curve", inputDsets_[didx]->legend())) return Analysis::ERR; curveSets_.push_back( outSet ); if (crvfile != 0) crvfile->AddDataSet( outSet ); } } // Non-window output file if (!averageonly_ && windowSize_ == -1) { standalone_ = DFLin->AddCpptrajFile( outfileName, "Lifetimes", DataFileList::TEXT, true ); if (standalone_ == 0) return Analysis::ERR; } else standalone_ = 0; if (!averageonly_) mprintf(" LIFETIME: Calculating average lifetime using a cutoff of %f", cut_); else mprintf(" LIFETIME: Calculating only averages"); mprintf(" of data in %i sets\n", inputDsets_.size()); if (!sortSets) mprintf("\tInput data sets will not be sorted.\n"); if (debugIn > 0) for (Array1D::const_iterator set = inputDsets_.begin(); set != inputDsets_.end(); ++set) mprintf("\t%s\n", (*set)->legend()); if (Compare_ == Compare_GreaterThan) mprintf("\tValues greater than %f are considered present.\n", cut_); else mprintf("\tValues less than %f are considered present.\n", cut_); if (windowSize_ != -1) { mprintf("\tAverage of data over windows will be saved to sets named %s\n", setname.c_str()); mprintf("\tWindow size for averaging: %i\n", windowSize_); if (cumulative_) mprintf("\tCumulative averages will be saved.\n"); if (deltaAvg_) mprintf("\tChange of average from previous average will be saved.\n"); } if (outfile != 0) { mprintf("\tOutfile: %s", outfile->DataFilename().full()); if (!averageonly_ && outfile != 0) mprintf(", %s, %s", maxfile->DataFilename().base(), avgfile->DataFilename().base()); mprintf("\n"); } if (!averageonly_) { if (crvfile != 0) mprintf("\tLifetime curves output: %s\n", crvfile->DataFilename().base()); if (normalizeCurves_) mprintf("\tLifetime curves will be normalized.\n"); else mprintf("\tLifetime curves will not be normalized.\n"); } if (fuzzCut_ != -1) mprintf("\tFuzz value of %i frames will be used.\n", fuzzCut_); return Analysis::OK; }