void Datagram::deserializeToDatagram(unsigned char *datagramChars, int datagramLength) { seqNumber = convertToInteger(datagramChars, 0); ackNumber = convertToInteger(datagramChars, 4); ackFlag = convertToBoolean(datagramChars, 8); finFlag = convertToBoolean(datagramChars, 9); length = convertToShort(datagramChars, 10); data = getPayload(datagramChars, length); }
/** Expect lowest replica file name to be passed in. 'remdtraj' should have * already been parsed out of input arguments. */ int Trajin_Multi::SetupTrajRead(FileName const& tnameIn, ArgList& argIn, Topology *tparmIn) { // Set file name and topology pointer. if (SetTraj().SetNameAndParm(tnameIn, tparmIn)) return 1; REMDtraj_.ClearIOarray(); // Check for deprecated args if (argIn.hasKey("remdout")) { mprinterr("%s", TrajIOarray::DEPRECATED_remdout); return 1; } // Process REMD-specific arguments if (argIn.Contains("remdtrajidx")) { // Looking for specific indices ArgList indicesArg(argIn.GetStringKey("remdtrajidx"), ","); if (indicesArg.empty()) { mprinterr("Error: remdtrajidx expects comma-separated list of target indices in each\n" "Error: dimension, '<dim1 idx>,<dim2 idx>,...,<dimN idx>'. Indices start\n" "Error: from 1.\n"); return 1; } for (ArgList::const_iterator arg = indicesArg.begin(); // TODO: validInteger? arg != indicesArg.end(); ++arg) remdtrajidx_.push_back( convertToInteger( *arg ) ); targetType_ = ReplicaInfo::INDICES; } else if (argIn.Contains("remdtrajtemp")) { // Looking for target temperature remdtrajtemp_ = argIn.getKeyDouble("remdtrajtemp",0.0); targetType_ = ReplicaInfo::TEMP; } // Set up replica file names. if (REMDtraj_.SetupReplicaFilenames( tnameIn, argIn )) return 1; // Set up TrajectoryIO classes for all file names. if (REMDtraj_.SetupIOarray(argIn, SetTraj().Counter(), cInfo_, Traj().Parm())) return 1; // Check that replica dimension valid for desired indices. if (targetType_ == ReplicaInfo::INDICES && cInfo_.ReplicaDimensions().Ndims() != (int)remdtrajidx_.size()) { mprinterr("Error: Replica # of dim (%i) not equal to target # dim (%zu)\n", cInfo_.ReplicaDimensions().Ndims(), remdtrajidx_.size()); return 1; } // If target type is temperature make sure there is temperature info. if (targetType_ == ReplicaInfo::TEMP && !cInfo_.HasTemp()) { mprinterr("Error: Some or all replicas are missing temperature info.\n"); return 1; } return 0; }
// ============================================================================= // ----- RepName Class --------------------------------------------------------- // RepName CONSTRUCTOR File::RepName::RepName(FileName const& fname, int debugIn) : extChar_('.') { if (debugIn > 1) mprintf("\tREMDTRAJ: FileName=[%s]\n", fname.full()); if ( fname.Ext().empty() ) { mprinterr("Error: Traj %s has no numerical extension, required for automatic\n" "Error: detection of replica trajectories. Expected filename format is\n" "Error: <Prefix>.<#> (with optional compression extension), examples:\n" "Error: Rep.traj.nc.000, remd.x.01.gz etc.\n", fname.base()); return; } // Split off everything before replica extension size_t found = fname.Full().rfind( fname.Ext() ); Prefix_.assign( fname.Full().substr(0, found) ); ReplicaExt_.assign( fname.Ext() ); // This should be the numeric extension // Remove leading '.' if (ReplicaExt_[0] == '.') ReplicaExt_.erase(0,1); CompressExt_.assign( fname.Compress() ); if (debugIn > 1) { mprintf("\tREMDTRAJ: Prefix=[%s], #Ext=[%s], CompressExt=[%s]\n", Prefix_.c_str(), ReplicaExt_.c_str(), CompressExt_.c_str()); } // CHARMM replica numbers are format <name>_<num> if ( !validInteger(ReplicaExt_) ) { size_t uscore = fname.Full().rfind('_'); if (uscore != std::string::npos) { Prefix_.assign( fname.Full().substr(0, uscore) ); ReplicaExt_.assign( fname.Full().substr(uscore+1) ); extChar_ = '_'; if (debugIn > 0) mprintf("\tREMDTRAJ: CHARMM style replica names detected, prefix='%s' ext='%s'\n", Prefix_.c_str(), ReplicaExt_.c_str()); } } // Check that the numerical extension is valid. if ( !validInteger(ReplicaExt_) ) { mprinterr("Error: Replica extension [%s] is not an integer.\n", ReplicaExt_.c_str()); Prefix_.clear(); // Empty Prefix_ indicates error. return; } ExtWidth_ = (int)ReplicaExt_.size(); if (debugIn > 1) mprintf("\tREMDTRAJ: Numerical Extension width=%i\n", ExtWidth_); // Store lowest replica number lowestRepnum_ = convertToInteger( ReplicaExt_ ); // TODO: Do not allow negative replica numbers? if (debugIn > 1) mprintf("\tREMDTRAJ: index of first replica = %i\n", lowestRepnum_); }
Action::RetType Action_MultiDihedral::Init(ArgList& actionArgs, TopologyList* PFL, FrameList* FL, DataSetList* DSL, DataFileList* DFL, int debugIn) { debug_ = debugIn; // Get keywords outfile_ = DFL->AddDataFile( actionArgs.GetStringKey("out"), actionArgs); range360_ = actionArgs.hasKey("range360"); std::string resrange_arg = actionArgs.GetStringKey("resrange"); if (!resrange_arg.empty()) if (resRange_.SetRange( resrange_arg )) return Action::ERR; // Search for known dihedral keywords dihSearch_.SearchForArgs(actionArgs); // Get custom dihedral arguments: dihtype <name>:<a0>:<a1>:<a2>:<a3>[:<offset>] std::string dihtype_arg = actionArgs.GetStringKey("dihtype"); while (!dihtype_arg.empty()) { ArgList dihtype(dihtype_arg, ":"); if (dihtype.Nargs() < 5) { mprinterr("Error: Malformed dihtype arg.\n"); return Action::ERR; } int offset = 0; if (dihtype.Nargs() == 6) offset = convertToInteger(dihtype[5]); dihSearch_.SearchForNewType(offset,dihtype[1],dihtype[2],dihtype[3],dihtype[4], dihtype[0]); dihtype_arg = actionArgs.GetStringKey("dihtype"); } // If no dihedral types yet selected, this will select all. dihSearch_.SearchForAll(); // Setup DataSet(s) name dsetname_ = actionArgs.GetStringNext(); mprintf(" MULTIDIHEDRAL: Calculating"); dihSearch_.PrintTypes(); if (!resRange_.Empty()) mprintf(" dihedrals for residues in range %s\n", resRange_.RangeArg()); else mprintf(" dihedrals for all residues.\n"); if (!dsetname_.empty()) mprintf("\tDataSet name: %s\n", dsetname_.c_str()); if (outfile_ != 0) mprintf("\tOutput to %s\n", outfile_->DataFilename().base()); if (range360_) mprintf("\tRange 0-360 deg.\n"); else mprintf("\tRange -180-180 deg.\n"); masterDSL_ = DSL; return Action::OK; }
void TickFct_Display7Seg(void){ static unsigned char init=1; if(init){ //initialization behavior OUTPUT=0x3F; //displays "0" to 7-Segment Display display_value=1; //increment init=0; }else if(keypad_counter){ //display Keypad Input int temp=display_value; display_value=convertToInteger(buffer&0x0F); if(display_value==10) display_value=temp; keypad_counter=0; }else{ display(); increment(); } }
static inline bool IsAtomLine(ArgList& lineIn) { for (int i = 0; i < lineIn.Nargs(); i++) { std::string item = lineIn.GetStringNext(); if (i == 0 || i >= 5) { try { convertToInteger( item ); } catch (std::runtime_error e) { return false; } } else if (i >= 2 && i < 5) { try { convertToDouble( item ); } catch (std::runtime_error e) { return false; } } } return true; }
// Parm_CIF::ReadParm() int Parm_CIF::ReadParm(FileName const& fname, Topology &TopIn) { CIFfile infile; CIFfile::DataBlock::data_it line; if (infile.Read( fname, debug_ )) return 1; CIFfile::DataBlock const& block = infile.GetDataBlock("_atom_site"); if (block.empty()) { mprinterr("Error: CIF data block '_atom_site' not found.\n"); return 1; } // Does this CIF contain multiple models? int Nmodels = 0; int model_col = block.ColumnIndex("pdbx_PDB_model_num"); if (model_col != -1) { line = block.end(); --line; Nmodels = convertToInteger( (*line)[model_col] ); if (Nmodels > 1) mprintf("Warning: CIF '%s' contains %i models. Using first model for topology.\n", fname.full(), Nmodels); } // Get essential columns int COL[NENTRY]; for (int i = 0; i < (int)NENTRY; i++) { COL[i] = block.ColumnIndex(Entries[i]); if (COL[i] == -1) { mprinterr("Error: In CIF file '%s' could not find entry '%s' in block '%s'\n", fname.full(), Entries[i], block.Header().c_str()); return 1; } if (debug_>0) mprintf("DEBUG: '%s' column = %i\n", Entries[i], COL[i]); } // Get optional columns int occ_col = block.ColumnIndex("occupancy"); int bfac_col = block.ColumnIndex("B_iso_or_equiv"); int icode_col = block.ColumnIndex("pdbx_PDB_ins_code"); int altloc_col = block.ColumnIndex("label_alt_id"); std::vector<AtomExtra> extra; // Loop over all atom sites int current_res = 0; double XYZ[3]; double occupancy = 1.0; double bfactor = 0.0; char altloc = ' '; char icode; icode = ' '; Frame Coords; for (line = block.begin(); line != block.end(); ++line) { // If more than 1 model check if we are done. if (Nmodels > 1) { if ( convertToInteger( (*line)[model_col] ) > 1 ) break; } if (occ_col != -1) occupancy = convertToDouble( (*line)[ occ_col ] ); if (bfac_col != -1) bfactor = convertToDouble( (*line)[ bfac_col ] ); if (altloc_col != -1) altloc = (*line)[ altloc_col ][0]; // '.' altloc means blank? if (altloc == '.') altloc = ' '; extra.push_back( AtomExtra(occupancy, bfactor, altloc) ); if (icode_col != -1) { icode = (*line)[ icode_col ][0]; // '?' icode means blank if (icode == '?') icode = ' '; } XYZ[0] = convertToDouble( (*line)[ COL[X] ] ); XYZ[1] = convertToDouble( (*line)[ COL[Y] ] ); XYZ[2] = convertToDouble( (*line)[ COL[Z] ] ); NameType currentResName( (*line)[ COL[RNAME] ] ); // It seems that in some CIF files, there doesnt have to be a residue // number. Check if residue name has changed. if ( (*line)[ COL[RNUM] ][0] == '.' ) { Topology::res_iterator lastResidue = TopIn.ResEnd(); --lastResidue; if ( currentResName != (*lastResidue).Name() ) current_res = TopIn.Nres() + 1; } else current_res = convertToInteger( (*line)[ COL[RNUM] ] ); TopIn.AddTopAtom( Atom((*line)[ COL[ANAME] ], " "), Residue(currentResName, current_res, icode, (*line)[ COL[CHAINID] ][0]) ); Coords.AddXYZ( XYZ ); } if (TopIn.SetExtraAtomInfo( 0, extra )) return 1; // Search for bonds // FIXME nobondsearch? BondSearch( TopIn, Coords, Offset_, debug_ ); // Get title. CIFfile::DataBlock const& entryblock = infile.GetDataBlock("_entry"); std::string ciftitle; if (!entryblock.empty()) ciftitle = entryblock.Data("id"); TopIn.SetParmName( ciftitle, infile.CIFname() ); // Get unit cell parameters if present. CIFfile::DataBlock const& cellblock = infile.GetDataBlock("_cell"); if (!cellblock.empty()) { double cif_box[6]; cif_box[0] = convertToDouble( cellblock.Data("length_a") ); cif_box[1] = convertToDouble( cellblock.Data("length_b") ); cif_box[2] = convertToDouble( cellblock.Data("length_c") ); cif_box[3] = convertToDouble( cellblock.Data("angle_alpha") ); cif_box[4] = convertToDouble( cellblock.Data("angle_beta" ) ); cif_box[5] = convertToDouble( cellblock.Data("angle_gamma") ); mprintf("\tRead cell info from CIF: a=%g b=%g c=%g alpha=%g beta=%g gamma=%g\n", cif_box[0], cif_box[1], cif_box[2], cif_box[3], cif_box[4], cif_box[5]); TopIn.SetParmBox( Box(cif_box) ); } return 0; }
int TransportRegistry::load_transport_configuration(const OPENDDS_STRING& file_name, ACE_Configuration_Heap& cf) { const ACE_Configuration_Section_Key &root = cf.root_section(); // Create a vector to hold configuration information so we can populate // them after the transports instances are created. typedef std::pair<TransportConfig_rch, OPENDDS_VECTOR(OPENDDS_STRING) > ConfigInfo; OPENDDS_VECTOR(ConfigInfo) configInfoVec; // Record the transport instances created, so we can place them // in the implicit transport configuration for this file. OPENDDS_LIST(TransportInst_rch) instances; ACE_TString sect_name; for (int index = 0; cf.enumerate_sections(root, index, sect_name) == 0; ++index) { if (ACE_OS::strcmp(sect_name.c_str(), TRANSPORT_SECTION_NAME) == 0) { // found the [transport/*] section, now iterate through subsections... ACE_Configuration_Section_Key sect; if (cf.open_section(root, sect_name.c_str(), 0, sect) != 0) { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("failed to open section %s\n"), sect_name.c_str()), -1); } else { // Ensure there are no properties in this section ValueMap vm; if (pullValues(cf, sect, vm) > 0) { // There are values inside [transport] ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("transport sections must have a section name\n"), sect_name.c_str()), -1); } // Process the subsections of this section (the individual transport // impls). KeyList keys; if (processSections( cf, sect, keys ) != 0) { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("too many nesting layers in [%s] section.\n"), sect_name.c_str()), -1); } for (KeyList::const_iterator it=keys.begin(); it != keys.end(); ++it) { OPENDDS_STRING transport_id = (*it).first; ACE_Configuration_Section_Key inst_sect = (*it).second; ValueMap values; if (pullValues( cf, (*it).second, values ) != 0) { // Get the factory_id for the transport. OPENDDS_STRING transport_type; ValueMap::const_iterator vm_it = values.find("transport_type"); if (vm_it != values.end()) { transport_type = (*vm_it).second; } else { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("missing transport_type in [transport/%C] section.\n"), transport_id.c_str()), -1); } // Create the TransportInst object and load the transport // configuration in ACE_Configuration_Heap to the TransportInst // object. TransportInst_rch inst = this->create_inst(transport_id, transport_type); if (inst == 0) { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("Unable to create transport instance in [transport/%C] section.\n"), transport_id.c_str()), -1); } instances.push_back(inst); inst->load(cf, inst_sect); } else { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("missing transport_type in [transport/%C] section.\n"), transport_id.c_str()), -1); } } } } else if (ACE_OS::strcmp(sect_name.c_str(), CONFIG_SECTION_NAME) == 0) { // found the [config/*] section, now iterate through subsections... ACE_Configuration_Section_Key sect; if (cf.open_section(root, sect_name.c_str(), 0, sect) != 0) { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("failed to open section [%s]\n"), sect_name.c_str()), -1); } else { // Ensure there are no properties in this section ValueMap vm; if (pullValues(cf, sect, vm) > 0) { // There are values inside [config] ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("config sections must have a section name\n"), sect_name.c_str()), -1); } // Process the subsections of this section (the individual config // impls). KeyList keys; if (processSections( cf, sect, keys ) != 0) { // Don't allow multiple layers of nesting ([config/x/y]). ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("too many nesting layers in [%s] section.\n"), sect_name.c_str()), -1); } for (KeyList::const_iterator it=keys.begin(); it != keys.end(); ++it) { OPENDDS_STRING config_id = (*it).first; // Create a TransportConfig object. TransportConfig_rch config = this->create_config(config_id); if (config == 0) { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("Unable to create transport config in [config/%C] section.\n"), config_id.c_str()), -1); } ValueMap values; pullValues( cf, (*it).second, values ); ConfigInfo configInfo; configInfo.first = config; for (ValueMap::const_iterator it=values.begin(); it != values.end(); ++it) { OPENDDS_STRING name = (*it).first; if (name == "transports") { OPENDDS_STRING value = (*it).second; char delim = ','; size_t pos = 0; OPENDDS_STRING token; while ((pos = value.find(delim)) != OPENDDS_STRING::npos) { token = value.substr(0, pos); configInfo.second.push_back(token); value.erase(0, pos + 1); } configInfo.second.push_back(value); configInfoVec.push_back(configInfo); } else if (name == "swap_bytes") { OPENDDS_STRING value = (*it).second; if ((value == "1") || (value == "true")) { config->swap_bytes_ = true; } else if ((value != "0") && (value != "false")) { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("Illegal value for swap_bytes (%C) in [config/%C] section.\n"), value.c_str(), config_id.c_str()), -1); } } else if (name == "passive_connect_duration") { OPENDDS_STRING value = (*it).second; if (!convertToInteger(value, config->passive_connect_duration_)) { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("Illegal integer value for passive_connect_duration (%s) in [config/%C] section.\n"), value.c_str(), config_id.c_str()), -1); } } else { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("Unexpected entry (%C) in [config/%C] section.\n"), name.c_str(), config_id.c_str()), -1); } } if (configInfo.second.size() == 0) { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("No transport instances listed in [config/%C] section.\n"), config_id.c_str()), -1); } } } } else if (ACE_OS::strncmp(sect_name.c_str(), OLD_TRANSPORT_PREFIX.c_str(), OLD_TRANSPORT_PREFIX.length()) == 0) { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) ERROR: ") ACE_TEXT("Obsolete transport configuration found (%s).\n"), sect_name.c_str()), -1); } } // Populate the configurations with instances for (unsigned int i = 0; i < configInfoVec.size(); ++i) { TransportConfig_rch config = configInfoVec[i].first; OPENDDS_VECTOR(OPENDDS_STRING)& insts = configInfoVec[i].second; for (unsigned int j = 0; j < insts.size(); ++j) { TransportInst_rch inst = this->get_inst(insts[j]); if (inst == 0) { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("The inst (%C) in [config/%C] section is undefined.\n"), insts[j].c_str(), config->name().c_str()), -1); } config->instances_.push_back(inst); } } // Create and populate the default configuration for this // file with all the instances from this file. if (!instances.empty()) { TransportConfig_rch config = this->create_config(file_name); if (config == 0) { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ") ACE_TEXT("Unable to create default transport config.\n"), file_name.c_str()), -1); } instances.sort(predicate); for (OPENDDS_LIST(TransportInst_rch)::const_iterator it = instances.begin(); it != instances.end(); ++it) { config->instances_.push_back(*it); } } return 0; }
int InfoRepoDiscovery::Config::discovery_config(ACE_Configuration_Heap& cf) { const ACE_Configuration_Section_Key& root = cf.root_section(); ACE_Configuration_Section_Key repo_sect; if (cf.open_section(root, REPO_SECTION_NAME, 0, repo_sect) != 0) { if (DCPS_debug_level > 0) { // This is not an error if the configuration file does not have // any repository (sub)section. The code default configuration will be used. ACE_DEBUG((LM_NOTICE, ACE_TEXT("(%P|%t) NOTICE: InfoRepoDiscovery::Config::discovery_config ") ACE_TEXT("failed to open [%s] section.\n"), REPO_SECTION_NAME)); } return 0; } else { // Ensure there are no properties in this section ValueMap vm; if (pullValues(cf, repo_sect, vm) > 0) { // There are values inside [repo] ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) InfoRepoDiscovery::Config::discovery_config ") ACE_TEXT("repo sections must have a subsection name\n")), -1); } // Process the subsections of this section (the individual repos) KeyList keys; if (processSections( cf, repo_sect, keys ) != 0) { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) InfoRepoDiscovery::Config::discovery_config ") ACE_TEXT("too many nesting layers in the [repo] section.\n")), -1); } // Loop through the [repo/*] sections for (KeyList::const_iterator it=keys.begin(); it != keys.end(); ++it) { std::string repo_name = (*it).first; ValueMap values; pullValues( cf, (*it).second, values ); Discovery::RepoKey repoKey = Discovery::DEFAULT_REPO; bool repoKeySpecified = false, bitIpSpecified = false, bitPortSpecified = false; std::string repoIor; int bitPort = 0; std::string bitIp; for (ValueMap::const_iterator it=values.begin(); it != values.end(); ++it) { std::string name = (*it).first; if (name == "RepositoryKey") { repoKey = (*it).second; repoKeySpecified = true; if (DCPS_debug_level > 0) { ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%P|%t) [repository/%C]: RepositoryKey == %C\n"), repo_name.c_str(), repoKey.c_str())); } } else if (name == "RepositoryIor") { repoIor = (*it).second; if (DCPS_debug_level > 0) { ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%P|%t) [repository/%C]: RepositoryIor == %C\n"), repo_name.c_str(), repoIor.c_str())); } } else if (name == "DCPSBitTransportIPAddress") { bitIp = (*it).second; bitIpSpecified = true; if (DCPS_debug_level > 0) { ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%P|%t) [repository/%C]: DCPSBitTransportIPAddress == %C\n"), repo_name.c_str(), bitIp.c_str())); } } else if (name == "DCPSBitTransportPort") { std::string value = (*it).second; bitPort = ACE_OS::atoi(value.c_str()); bitPortSpecified = true; if (convertToInteger(value, bitPort)) { } else { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) InfoRepoDiscovery::Config::discovery_config ") ACE_TEXT("Illegal integer value for DCPSBitTransportPort (%C) in [repository/%C] section.\n"), value.c_str(), repo_name.c_str()), -1); } if (DCPS_debug_level > 0) { ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%P|%t) [repository/%C]: DCPSBitTransportPort == %d\n"), repo_name.c_str(), bitPort)); } } else { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) InfoRepoDiscovery::Config::discovery_config ") ACE_TEXT("Unexpected entry (%C) in [repository/%C] section.\n"), name.c_str(), repo_name.c_str()), -1); } } if (values.find("RepositoryIor") == values.end()) { ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("(%P|%t) InfoRepoDiscovery::Config::discovery_config ") ACE_TEXT("Repository section [repository/%C] section is missing RepositoryIor value.\n"), repo_name.c_str()), -1); } if (!repoKeySpecified) { // If the RepositoryKey option was not specified, use the section // name as the repo key repoKey = repo_name; } InfoRepoDiscovery_rch discovery = new InfoRepoDiscovery(repoKey, repoIor.c_str()); if (bitPortSpecified) discovery->bit_transport_port(bitPort); if (bitIpSpecified) discovery->bit_transport_ip(bitIp); TheServiceParticipant->add_discovery( DCPS::static_rchandle_cast<Discovery>(discovery)); } } return 0; }
Analysis::RetType Analysis_CurveFit::Internal_setup(std::string const& suffixIn, ArgList& analyzeArgs, DataSetList* datasetlist, DataFileList* DFLin, int debugIn) { if (dset_->Ndim() != 1) { mprinterr("Error: Curve fitting can only be done with 1D data sets.\n"); return Analysis::ERR; } std::string dsoutName; n_expected_params_ = 0; // Determine if special equation is being used. nexp_ = analyzeArgs.getKeyInt("nexp", -1); bool useGauss = analyzeArgs.hasKey("gauss"); if ( useGauss || nexp_ > 0 ) { // Multi-exponential/Gaussian specialized equation form. dsoutName = analyzeArgs.GetStringKey("name"); if (dsoutName.empty()) { mprinterr("Error: 'name <OutputSetName>' must be used with 'nexp <n>' or 'gauss'\n"); return Analysis::ERR; } equation_ = dsoutName + " = "; if (nexp_ > 0) { // Determine form eqForm_ = MEXP; std::string formStr = analyzeArgs.GetStringKey("form"); if (!formStr.empty()) { if (formStr == "mexp") eqForm_ = MEXP; else if (formStr == "mexpk") eqForm_ = MEXP_K; else if (formStr == "mexpk_penalty") eqForm_ = MEXP_K_PENALTY; else { mprinterr("Error: Multi-exponential form '%s' not recognized.\n", formStr.c_str()); return Analysis::ERR; } } // Set up equation int nparam = 0; if (eqForm_ != MEXP) { equation_.append("A0 +"); nparam = 1; } for (int ie = 0; ie != nexp_; ie++, nparam += 2) { if (ie > 0) equation_.append(" + "); equation_.append("(A" + integerToString(nparam) + " * exp(X * A" + integerToString(nparam+1) + "))"); } n_expected_params_ = nparam; } else { eqForm_ = GAUSS; n_expected_params_ = 3; equation_.append("A0 * exp( -((X - A1)^2) / (2 * A2^2) )"); } } else { // Any equation form, solve with RPNcalc. eqForm_ = GENERAL; // Second argument should be the equation to fit DataSet to. equation_ = analyzeArgs.GetStringNext(); if (equation_.empty()) { mprinterr("Error: Must specify an equation if 'nexp <n>' not specified.\n"); return Analysis::ERR; } Calc_.SetDebug(debugIn); if (Calc_.ProcessExpression( equation_ )) return Analysis::ERR; // Equation must have an assignment. if ( Calc_.AssignStatus() != RPNcalc::YES_ASSIGN ) { mprinterr("Error: No assignment '=' in equation '%s'.\n", equation_.c_str()); return Analysis::ERR; } dsoutName = Calc_.FirstTokenName(); if (dsoutName.empty()) { mprinterr("Error: Invalid assignment in equation '%s'.\n", equation_.c_str()); return Analysis::ERR; } n_expected_params_ = Calc_.Nparams(); } // Get keywords Results_ = DFLin->AddCpptrajFile( analyzeArgs.GetStringKey("resultsout"), "Curve Fit Results", DataFileList::TEXT, true ); DataFile* outfile = DFLin->AddDataFile( analyzeArgs.GetStringKey("out"), analyzeArgs ); tolerance_ = analyzeArgs.getKeyDouble("tol", 0.0001); if (tolerance_ < 0.0) { mprinterr("Error: Tolerance must be greater than or equal to 0.0\n"); return Analysis::ERR; } maxIt_ = analyzeArgs.getKeyInt("maxit", 50); if (maxIt_ < 1) { mprinterr("Error: Max iterations must be greater than or equal to 1.\n"); return Analysis::ERR; } outXbins_ = analyzeArgs.getKeyInt("outxbins", -1); outXmin_ = analyzeArgs.getKeyDouble("outxmin", 0.0); outXmax_ = analyzeArgs.getKeyDouble("outxmax", 0.0); if (outXbins_ > 0) { mprintf("%g %g\n", outXmin_, outXmax_); if (outXmin_ >= outXmax_) { mprinterr("Error: outxmin must be less than outxmax.\n"); return Analysis::ERR; } } // Now get all parameters if (n_expected_params_ < 0) return Analysis::ERR; Params_.resize( n_expected_params_, 0.0 ); n_specified_params_ = 0; for (int p = 0; p != n_expected_params_; p++, n_specified_params_++) { std::string parameterArg = analyzeArgs.GetStringNext(); if (parameterArg.empty()) break; ArgList parameter(parameterArg, " ="); if (parameter.Nargs() != 2) { mprinterr("Error: Invalid parameter argument. Expected 'A<n>=<value>'\n"); return Analysis::ERR; } std::string parameterName = parameter.GetStringNext(); if (parameterName[0] != 'A') { mprinterr("Error: Invalid parameter name (expected A<n>): %s\n", parameterName.c_str()); return Analysis::ERR; } int pnum = convertToInteger(parameterName.substr(1)); Params_[pnum] = parameter.getNextDouble(0.0); } // Check if all params specified. if (n_specified_params_ != n_expected_params_) mprintf("Warning: # specified params (%i) less than # expected params (%i)\n", n_specified_params_, n_expected_params_); // Set up output data set. if (!suffixIn.empty()) dsoutName.append(suffixIn); finalY_ = datasetlist->AddSet(DataSet::XYMESH, dsoutName, "FIT"); if (finalY_ == 0) return Analysis::ERR; if (outfile != 0) outfile->AddDataSet( finalY_ ); mprintf(" CURVEFIT: Fitting set '%s' to equation '%s'\n", dset_->legend(), equation_.c_str()); if (nexp_ > 0) { mprintf("\tMulti-exponential form with %i exponentials.\n", nexp_); if (eqForm_ == MEXP_K_PENALTY) mprintf("\tMulti-exponential equation constraints: sum of prefactors = 1.0," " exponent parameters < 0.0\n"); } else if (eqForm_ == GAUSS) mprintf("\tGaussian form.\n"); mprintf("\tFinal Y values will be saved in set '%s'\n", finalY_->legend()); if (outXbins_ > 0) mprintf("\tFinal X range: %g to %g, %i points.\n", outXmin_, outXmax_, outXbins_); mprintf("\tTolerance= %g, maximum iterations= %i\n", tolerance_, maxIt_); mprintf("\tFinal parameters and statistics for fit will be writtent to %s\n", Results_->Filename().full()); if (n_specified_params_ > 0) { mprintf("\tInitial parameters:\n"); for (Darray::const_iterator ip = Params_.begin(); ip != Params_.end(); ++ip) mprintf("\t A%u = %g\n", ip - Params_.begin(), *ip); } return Analysis::OK; }
int moProperty::asInteger() { return convertToInteger(this->type, this->val); }
int Parm_CharmmPsf::WriteParm(FileName const& fname, Topology const& parm) { // TODO: CMAP etc info CpptrajFile outfile; if (outfile.OpenWrite(fname)) return 1; // Write PSF outfile.Printf("PSF\n\n"); // Write title std::string titleOut = parm.ParmName(); titleOut.resize(78); outfile.Printf("%8i !NTITLE\n* %-78s\n\n", 1, titleOut.c_str()); // Write NATOM section outfile.Printf("%8i !NATOM\n", parm.Natom()); unsigned int idx = 1; // Make fake segment ids for now. char segid[2]; segid[0] = 'A'; segid[1] = '\0'; mprintf("Warning: Assigning single letter segment IDs.\n"); int currentMol = 0; bool inSolvent = false; for (Topology::atom_iterator atom = parm.begin(); atom != parm.end(); ++atom, ++idx) { int resnum = atom->ResNum(); if (atom->MolNum() != currentMol) { if (!inSolvent) { inSolvent = parm.Mol(atom->MolNum()).IsSolvent(); currentMol = atom->MolNum(); segid[0]++; } else inSolvent = parm.Mol(atom->MolNum()).IsSolvent(); } // TODO: Print type name for xplor-like PSF int typeindex = atom->TypeIndex() + 1; // If type begins with digit, assume charmm numbers were read as // type. Currently Amber types all begin with letters. if (isdigit(atom->Type()[0])) typeindex = convertToInteger( *(atom->Type()) ); // ATOM# SEGID RES# RES ATNAME ATTYPE CHRG MASS (REST OF COLUMNS ARE LIKELY FOR CMAP AND CHEQ) outfile.Printf("%8i %-4s %-4i %-4s %-4s %4i %14.6G %9g %10i\n", idx, segid, parm.Res(resnum).OriginalResNum(), parm.Res(resnum).c_str(), atom->c_str(), typeindex, atom->Charge(), atom->Mass(), 0); } outfile.Printf("\n"); // Write NBOND section outfile.Printf("%8u !NBOND: bonds\n", parm.Bonds().size() + parm.BondsH().size()); idx = 1; for (BondArray::const_iterator bond = parm.BondsH().begin(); bond != parm.BondsH().end(); ++bond, ++idx) { outfile.Printf("%8i%8i", bond->A1()+1, bond->A2()+1); if ((idx % 4)==0) outfile.Printf("\n"); } for (BondArray::const_iterator bond = parm.Bonds().begin(); bond != parm.Bonds().end(); ++bond, ++idx) { outfile.Printf("%8i%8i", bond->A1()+1, bond->A2()+1); if ((idx % 4)==0) outfile.Printf("\n"); } if ((idx % 4)!=0) outfile.Printf("\n"); outfile.Printf("\n"); // Write NTHETA section outfile.Printf("%8u !NTHETA: angles\n", parm.Angles().size() + parm.AnglesH().size()); idx = 1; for (AngleArray::const_iterator ang = parm.AnglesH().begin(); ang != parm.AnglesH().end(); ++ang, ++idx) { outfile.Printf("%8i%8i%8i", ang->A1()+1, ang->A2()+1, ang->A3()+1); if ((idx % 3)==0) outfile.Printf("\n"); } for (AngleArray::const_iterator ang = parm.Angles().begin(); ang != parm.Angles().end(); ++ang, ++idx) { outfile.Printf("%8i%8i%8i", ang->A1()+1, ang->A2()+1, ang->A3()+1); if ((idx % 3)==0) outfile.Printf("\n"); } if ((idx % 3)==0) outfile.Printf("\n"); outfile.Printf("\n"); // Write out NPHI section outfile.Printf("%8u !NPHI: dihedrals\n", parm.Dihedrals().size() + parm.DihedralsH().size()); idx = 1; for (DihedralArray::const_iterator dih = parm.DihedralsH().begin(); dih != parm.DihedralsH().end(); ++dih, ++idx) { outfile.Printf("%8i%8i%8i%8i", dih->A1()+1, dih->A2()+1, dih->A3()+1, dih->A4()+1); if ((idx % 2)==0) outfile.Printf("\n"); } for (DihedralArray::const_iterator dih = parm.Dihedrals().begin(); dih != parm.Dihedrals().end(); ++dih, ++idx) { outfile.Printf("%8i%8i%8i%8i", dih->A1()+1, dih->A2()+1, dih->A3()+1, dih->A4()+1); if ((idx % 2)==0) outfile.Printf("\n"); } if ((idx % 2)==0) outfile.Printf("\n"); outfile.Printf("\n"); outfile.CloseFile(); return 0; }
/** Set up each mask/integer loop. */ int ControlBlock_For::SetupBlock(CpptrajState& State, ArgList& argIn) { mprintf(" Setting up 'for' loop.\n"); Vars_.clear(); Topology* currentTop = 0; static const char* TypeStr[] = { "ATOMS ", "RESIDUES ", "MOLECULES ", "MOL_FIRST_RES ", "MOL_LAST_RES " }; static const char* OpStr[] = {"+=", "-=", "<", ">"}; description_.assign("for ("); int MaxIterations = -1; int iarg = 0; while (iarg < argIn.Nargs()) { // Advance to next unmarked argument. while (iarg < argIn.Nargs() && argIn.Marked(iarg)) iarg++; if (iarg == argIn.Nargs()) break; // Determine 'for' type ForType ftype = UNKNOWN; bool isMaskFor = true; int argToMark = iarg; if ( argIn[iarg] == "atoms" ) ftype = ATOMS; else if ( argIn[iarg] == "residues" ) ftype = RESIDUES; else if ( argIn[iarg] == "molecules" ) ftype = MOLECULES; else if ( argIn[iarg] == "molfirstres" ) ftype = MOLFIRSTRES; else if ( argIn[iarg] == "mollastres" ) ftype = MOLLASTRES; else if ( argIn[iarg].find(";") != std::string::npos ) { isMaskFor = false; ftype = INTEGER; } // If type is still unknown, check for list. if (ftype == UNKNOWN) { if (iarg+1 < argIn.Nargs() && argIn[iarg+1] == "in") { ftype = LIST; isMaskFor = false; argToMark = iarg+1; } } // Exit if type could not be determined. if (ftype == UNKNOWN) { mprinterr("Error: for loop type not specfied.\n"); return 1; } argIn.MarkArg(argToMark); Vars_.push_back( LoopVar() ); LoopVar& MH = Vars_.back(); int Niterations = -1; // Set up for specific type if (description_ != "for (") description_.append(", "); // ------------------------------------------- if (isMaskFor) { // {atoms|residues|molecules} <var> inmask <mask> [TOP KEYWORDS] if (argIn[iarg+2] != "inmask") { mprinterr("Error: Expected 'inmask', got %s\n", argIn[iarg+2].c_str()); return 1; } AtomMask currentMask; if (currentMask.SetMaskString( argIn.GetStringKey("inmask") )) return 1; MH.varType_ = ftype; Topology* top = State.DSL().GetTopByIndex( argIn ); if (top != 0) currentTop = top; if (currentTop == 0) return 1; MH.varname_ = argIn.GetStringNext(); if (MH.varname_.empty()) { mprinterr("Error: 'for inmask': missing variable name.\n"); return 1; } MH.varname_ = "$" + MH.varname_; // Set up mask if (currentTop->SetupIntegerMask( currentMask )) return 1; currentMask.MaskInfo(); if (currentMask.None()) return 1; // Set up indices if (MH.varType_ == ATOMS) MH.Idxs_ = currentMask.Selected(); else if (MH.varType_ == RESIDUES) { int curRes = -1; for (AtomMask::const_iterator at = currentMask.begin(); at != currentMask.end(); ++at) { int res = (*currentTop)[*at].ResNum(); if (res != curRes) { MH.Idxs_.push_back( res ); curRes = res; } } } else if (MH.varType_ == MOLECULES || MH.varType_ == MOLFIRSTRES || MH.varType_ == MOLLASTRES) { int curMol = -1; for (AtomMask::const_iterator at = currentMask.begin(); at != currentMask.end(); ++at) { int mol = (*currentTop)[*at].MolNum(); if (mol != curMol) { if (MH.varType_ == MOLECULES) MH.Idxs_.push_back( mol ); else { int res; if (MH.varType_ == MOLFIRSTRES) res = (*currentTop)[ currentTop->Mol( mol ).BeginAtom() ].ResNum(); else // MOLLASTRES res = (*currentTop)[ currentTop->Mol( mol ).EndAtom()-1 ].ResNum(); MH.Idxs_.push_back( res ); } curMol = mol; } } } Niterations = (int)MH.Idxs_.size(); description_.append(std::string(TypeStr[MH.varType_]) + MH.varname_ + " inmask " + currentMask.MaskExpression()); // ------------------------------------------- } else if (ftype == INTEGER) { // [<var>=<start>;[<var><OP><end>;]<var><OP>[<value>]] MH.varType_ = ftype; ArgList varArg( argIn[iarg], ";" ); if (varArg.Nargs() < 2 || varArg.Nargs() > 3) { mprinterr("Error: Malformed 'for' loop variable.\n" "Error: Expected '[<var>=<start>;[<var><OP><end>;]<var><OP>[<value>]]'\n" "Error: Got '%s'\n", argIn[iarg].c_str()); return 1; } // First argument: <var>=<start> ArgList startArg( varArg[0], "=" ); if (startArg.Nargs() != 2) { mprinterr("Error: Malformed 'start' argument.\n" "Error: Expected <var>=<start>, got '%s'\n", varArg[0].c_str()); return 1; } MH.varname_ = startArg[0]; if (!validInteger(startArg[1])) { // TODO allow variables mprinterr("Error: Start argument must be an integer.\n"); return 1; } else MH.start_ = convertToInteger(startArg[1]); // Second argument: <var><OP><end> size_t pos0 = MH.varname_.size(); size_t pos1 = pos0 + 1; MH.endOp_ = NO_OP; int iargIdx = 1; if (varArg.Nargs() == 3) { iargIdx = 2; if ( varArg[1][pos0] == '<' ) MH.endOp_ = LESS_THAN; else if (varArg[1][pos0] == '>') MH.endOp_ = GREATER_THAN; if (MH.endOp_ == NO_OP) { mprinterr("Error: Unrecognized end op: '%s'\n", varArg[1].substr(pos0, pos1-pos0).c_str()); return 1; } std::string endStr = varArg[1].substr(pos1); if (!validInteger(endStr)) { // TODO allow variables mprinterr("Error: End argument must be an integer.\n"); return 1; } else MH.end_ = convertToInteger(endStr); } // Third argument: <var><OP>[<value>] pos1 = pos0 + 2; MH.incOp_ = NO_OP; bool needValue = false; if ( varArg[iargIdx][pos0] == '+' ) { if (varArg[iargIdx][pos0+1] == '+') { MH.incOp_ = INCREMENT; MH.inc_ = 1; } else if (varArg[iargIdx][pos0+1] == '=') { MH.incOp_ = INCREMENT; needValue = true; } } else if ( varArg[iargIdx][pos0] == '-' ) { if (varArg[iargIdx][pos0+1] == '-' ) { MH.incOp_ = DECREMENT; MH.inc_ = 1; } else if (varArg[iargIdx][pos0+1] == '=') { MH.incOp_ = DECREMENT; needValue = true; } } if (MH.incOp_ == NO_OP) { mprinterr("Error: Unrecognized increment op: '%s'\n", varArg[iargIdx].substr(pos0, pos1-pos0).c_str()); return 1; } if (needValue) { std::string incStr = varArg[iargIdx].substr(pos1); if (!validInteger(incStr)) { mprinterr("Error: increment value is not a valid integer.\n"); return 1; } MH.inc_ = convertToInteger(incStr); if (MH.inc_ < 1) { mprinterr("Error: Extra '-' detected in increment.\n"); return 1; } } // Description MH.varname_ = "$" + MH.varname_; std::string sval = integerToString(MH.start_); description_.append("(" + MH.varname_ + "=" + sval + "; "); std::string eval; if (iargIdx == 2) { // End argument present eval = integerToString(MH.end_); description_.append(MH.varname_ + std::string(OpStr[MH.endOp_]) + eval + "; "); // Check end > start for increment, start > end for decrement int maxval, minval; if (MH.incOp_ == INCREMENT) { if (MH.start_ >= MH.end_) { mprinterr("Error: start must be less than end for increment.\n"); return 1; } minval = MH.start_; maxval = MH.end_; } else { if (MH.end_ >= MH.start_) { mprinterr("Error: end must be less than start for decrement.\n"); return 1; } minval = MH.end_; maxval = MH.start_; } // Figure out number of iterations Niterations = (maxval - minval) / MH.inc_; if (((maxval-minval) % MH.inc_) > 0) Niterations++; } description_.append( MH.varname_ + std::string(OpStr[MH.incOp_]) + integerToString(MH.inc_) + ")" ); // If decrementing just negate value if (MH.incOp_ == DECREMENT) MH.inc_ = -MH.inc_; // DEBUG //mprintf("DEBUG: start=%i endOp=%i end=%i incOp=%i val=%i startArg=%s endArg=%s\n", // MH.start_, (int)MH.endOp_, MH.end_, (int)MH.incOp_, MH.inc_, // MH.startArg_.c_str(), MH.endArg_.c_str()); // ------------------------------------------- } else if (ftype == LIST) { // <var> in <string0>[,<string1>...] MH.varType_ = ftype; // Variable name MH.varname_ = argIn.GetStringNext(); if (MH.varname_.empty()) { mprinterr("Error: 'for in': missing variable name.\n"); return 1; } MH.varname_ = "$" + MH.varname_; // Comma-separated list of strings std::string listArg = argIn.GetStringNext(); if (listArg.empty()) { mprinterr("Error: 'for in': missing comma-separated list of strings.\n"); return 1; } ArgList list(listArg, ","); if (list.Nargs() < 1) { mprinterr("Error: Could not parse '%s' for 'for in'\n", listArg.c_str()); return 1; } for (int il = 0; il != list.Nargs(); il++) { // Check if file name expansion should occur if (list[il].find_first_of("*?") != std::string::npos) { File::NameArray files = File::ExpandToFilenames( list[il] ); for (File::NameArray::const_iterator fn = files.begin(); fn != files.end(); ++fn) MH.List_.push_back( fn->Full() ); } else MH.List_.push_back( list[il] ); } Niterations = (int)MH.List_.size(); // Description description_.append( MH.varname_ + " in " + listArg ); } // Check number of values if (MaxIterations == -1) MaxIterations = Niterations; else if (Niterations != -1 && Niterations != MaxIterations) { mprintf("Warning: # iterations %i != previous # iterations %i\n", Niterations, MaxIterations); MaxIterations = std::min(Niterations, MaxIterations); } } mprintf("\tLoop will execute for %i iterations.\n", MaxIterations); if (MaxIterations < 1) { mprinterr("Error: Loop has less than 1 iteration.\n"); return 1; } description_.append(") do"); return 0; }
// ----- M A I N --------------------------------------------------------------- int main(int argc, char** argv) { SetWorldSilent(true); // No STDOUT output from cpptraj routines. std::string topname, crdname, title, bres, pqr, sybyltype, writeconect; std::string aatm(" pdbatom"), ter_opt(" terbyres"), box(" sg \"P 1\""); TrajectoryFile::TrajFormatType fmt = TrajectoryFile::PDBFILE; bool ctr_origin = false; bool useExtendedInfo = false; int res_offset = 0; int debug = 0; int numSoloArgs = 0; for (int i = 1; i < argc; ++i) { std::string arg( argv[i] ); if (arg == "-p" && i+1 != argc && topname.empty()) // Topology topname = std::string( argv[++i] ); else if (arg == "-c" && i+1 != argc && crdname.empty()) // Coords crdname = std::string( argv[++i] ); else if (arg == "-tit" && i+1 != argc && title.empty()) // Title title = " title " + std::string( argv[++i] ); else if (arg == "-offset" && i+1 != argc) // Residue # offset res_offset = convertToInteger( argv[++i] ); else if ((arg == "-d" || arg == "--debug") && i+1 != argc) // Debug level debug = convertToInteger( argv[++i] ); else if (arg == "-h" || arg == "--help") { // Help Help(argv[0], true); return 0; } else if (arg == "-v" || arg == "--version") { // Version info WriteVersion(); return 0; } else if (arg == "-aatm") // Amber atom names, include extra pts aatm.assign(" include_ep"); else if (arg == "-sybyl") // Amber atom types to SYBYL sybyltype.assign(" sybyltype"); else if (arg == "-conect") // Write CONECT records from bond info writeconect.assign(" conect"); else if (arg == "-ep") // PDB atom names, include extra pts aatm.append(" include_ep"); else if (arg == "-bres") // PDB residue names bres.assign(" pdbres"); else if (arg == "-ext") // Use extended PDB info from Topology useExtendedInfo = true; else if (arg == "-ctr") // Center on origin ctr_origin = true; else if (arg == "-noter") // No TER cards ter_opt.assign(" noter"); else if (arg == "-nobox") // No CRYST1 record box.assign(" nobox"); else if (arg == "-pqr") { // Charge/Radii in occ/bfactor cols pqr.assign(" dumpq"); ++numSoloArgs; } else if (arg == "-mol2") { // output as mol2 fmt = TrajectoryFile::MOL2FILE; ++numSoloArgs; } else if (Unsupported(arg)) { mprinterr("Error: Option '%s' is not yet supported.\n\n", arg.c_str()); return 1; } else { mprinterr("Error: Unrecognized option '%s'\n", arg.c_str()); Help(argv[0], false); return 1; } } if (debug > 0) WriteVersion(); // Check command line for errors. if (topname.empty()) topname.assign("prmtop"); if (debug > 0 && crdname.empty()) mprinterr("| Reading Amber restart from STDIN\n"); if (numSoloArgs > 1) { mprinterr("Error: Only one alternate output format option may be specified (found %i)\n", numSoloArgs); Help(argv[0], true); return 1; } if (!sybyltype.empty() && fmt != TrajectoryFile::MOL2FILE) { mprinterr("Warning: -sybyl is only valid for MOL2 file output.\n"); sybyltype.clear(); } if (debug > 0) { mprinterr("Warning: debug is %i; debug info will be written to STDOUT.\n", debug); SetWorldSilent(false); } // Topology ParmFile pfile; Topology parm; if (pfile.ReadTopology(parm, topname, debug)) { if (topname == "prmtop") Help(argv[0], false); return 1; } if (!useExtendedInfo) parm.ResetPDBinfo(); if (res_offset != 0) for (int r = 0; r < parm.Nres(); r++) parm.SetRes(r).SetOriginalNum( parm.Res(r).OriginalResNum() + res_offset ); ArgList trajArgs; // Input coords Frame TrajFrame; CoordinateInfo cInfo; if (!crdname.empty()) { Trajin_Single trajin; if (trajin.SetupTrajRead(crdname, trajArgs, &parm)) return 1; cInfo = trajin.TrajCoordInfo(); TrajFrame.SetupFrameV(parm.Atoms(), cInfo); trajin.BeginTraj(); if (trajin.ReadTrajFrame(0, TrajFrame)) return 1; trajin.EndTraj(); } else { // Assume Amber restart from STDIN // Check that input is from a redirect. if ( isatty(fileno(stdin)) ) { mprinterr("Error: No coordinates specified with '-c' and no STDIN '<'.\n"); return 1; } Traj_AmberRestart restartIn; restartIn.SetDebug( debug ); //restartIn.processReadArgs( trajArgs ); int total_frames = restartIn.setupTrajin("", &parm); if (total_frames < 1) return 1; cInfo = restartIn.CoordInfo(); TrajFrame.SetupFrameV(parm.Atoms(), cInfo); if (restartIn.openTrajin()) return 1; if (restartIn.readFrame(0, TrajFrame)) return 1; restartIn.closeTraj(); } if (ctr_origin) TrajFrame.CenterOnOrigin(false); // Output coords Trajout_Single trajout; trajArgs.SetList( aatm + bres + pqr + title + ter_opt + box + sybyltype + writeconect, " " ); if ( trajout.PrepareStdoutTrajWrite(trajArgs, &parm, cInfo, 1, fmt) ) return 1; trajout.WriteSingle(0, TrajFrame); trajout.EndTraj(); return 0; }
// Exec_DataSetCmd::Remove() Exec::RetType Exec_DataSetCmd::Remove(CpptrajState& State, ArgList& argIn) { std::string status; // Get criterion type CriterionType criterion = UNKNOWN_C; for (int i = 1; i < (int)N_C; i++) if (argIn.hasKey( CriterionKeys[i] )) { criterion = (CriterionType)i; status.assign( CriterionKeys[i] ); break; } if (criterion == UNKNOWN_C) { mprinterr("Error: No criterion specified for 'remove'.\n"); return CpptrajState::ERR; } // Get select type SelectType select = UNKNOWN_S; std::string val1, val2; for (const SelectPairType* ptr = SelectKeys; ptr->key_ != 0; ptr++) if (argIn.Contains( ptr->key_ )) { select = ptr->type_; val1 = argIn.GetStringKey( ptr->key_ ); status.append( " " + std::string(ptr->key_) + " " + val1 ); // Get 'and' value for between/outside. TODO put nargs in SelectPairType? if (select == BETWEEN || select == OUTSIDE) { val2 = argIn.GetStringKey("and"); if (val2.empty()) { mprinterr("Error: Missing 'and' value for selection '%s'\n", ptr->key_); return CpptrajState::ERR; } status.append(" and " + val2); } break; } if (select == UNKNOWN_S || val1.empty()) { mprinterr("Error: No selection specified for 'remove'.\n"); return CpptrajState::ERR; } if ( (criterion == SMODE || criterion == STYPE) && (select != EQUAL && select != NOT_EQUAL) ) { mprinterr("Error: Specified select not valid for criterion '%s'\n", CriterionKeys[criterion]); return CpptrajState::ERR; } mprintf("\tRemoving data sets"); std::string setSelectArg = argIn.GetStringNext(); if (setSelectArg.empty()) setSelectArg.assign("*"); else mprintf(" within selection '%s'", setSelectArg.c_str()); mprintf(" %s\n", status.c_str()); DataSetList tempDSL = State.DSL().GetMultipleSets( setSelectArg ); if (tempDSL.empty()) { mprinterr("Error: No data sets selected.\n"); return CpptrajState::ERR; } // Remove sets unsigned int Nremoved = 0; if ( criterion == AVERAGE ) { if (!validDouble( val1 )) { mprinterr("Error: '%s' is not a valid number\n", val1.c_str()); return CpptrajState::ERR; } double d_val1 = convertToDouble( val1 ); double d_val2 = d_val1; if (!val2.empty()) { if (!validDouble( val2 )) { mprinterr("Error: '%s' is not a valid number\n", val2.c_str()); return CpptrajState::ERR; } d_val2 = convertToDouble( val2 ); } for (DataSetList::const_iterator ds = tempDSL.begin(); ds != tempDSL.end(); ++ds) { if ( (*ds)->Group() != DataSet::SCALAR_1D ) mprintf("Warning: '%s' is not a valid data set for 'average' criterion.\n", (*ds)->legend()); else { DataSet_1D const& ds1 = static_cast<DataSet_1D const&>( *(*ds) ); double avg = ds1.Avg(); bool remove = false; switch (select) { case EQUAL : remove = (avg == d_val1); break; case NOT_EQUAL : remove = (avg != d_val1); break; case LESS_THAN : remove = (avg < d_val1); break; case GREATER_THAN : remove = (avg > d_val1); break; case BETWEEN : remove = (avg > d_val1 && avg < d_val2); break; case OUTSIDE : remove = (avg < d_val1 || avg > d_val2); break; case UNKNOWN_S: case N_S : return CpptrajState::ERR; // Sanity check } if (remove) { mprintf("\t Removing set '%s' (avg is %g)\n", (*ds)->legend(), avg); State.RemoveDataSet( *ds ); ++Nremoved; } } } } else if ( criterion == SIZE ) { if (!validInteger( val1 )) { mprinterr("Error: '%s' is not a valid number\n", val1.c_str()); return CpptrajState::ERR; } unsigned int i_val1 = (unsigned int)convertToInteger( val1 ); unsigned int i_val2 = i_val1; if (!val2.empty()) { if (!validInteger( val2 )) { mprinterr("Error: '%s' is not a valid number\n", val2.c_str()); return CpptrajState::ERR; } i_val2 = convertToInteger( val2 ); } for (DataSetList::const_iterator ds = tempDSL.begin(); ds != tempDSL.end(); ++ds) { unsigned int size = (*ds)->Size(); bool remove = false; switch ( select ) { case EQUAL : remove = (size == i_val1); break; case NOT_EQUAL : remove = (size != i_val1); break; case LESS_THAN : remove = (size < i_val1); break; case GREATER_THAN : remove = (size > i_val1); break; case BETWEEN : remove = (size > i_val1 && size < i_val2); break; case OUTSIDE : remove = (size < i_val1 || size > i_val2); break; case UNKNOWN_S: case N_S : return CpptrajState::ERR; // Sanity check } if (remove) { mprintf("\t Removing set '%s' (size is %u)\n", (*ds)->legend(), size); State.RemoveDataSet( *ds ); ++Nremoved; } } } else if ( criterion == SMODE ) { MetaData::scalarMode mode_val = MetaData::ModeFromKeyword( val1 ); if (mode_val == MetaData::UNKNOWN_MODE) { mprinterr("Error: '%s' is not a valid mode.\n", val1.c_str()); return CpptrajState::ERR; } for (DataSetList::const_iterator ds = tempDSL.begin(); ds != tempDSL.end(); ++ds) { bool remove = false; MetaData::scalarMode mode = (*ds)->Meta().ScalarMode(); if (select == EQUAL ) remove = ( mode == mode_val ); else if (select == NOT_EQUAL) remove = ( mode != mode_val ); else return CpptrajState::ERR; // Sanity check if (remove) { mprintf("\t Removing set '%s' (mode is '%s')\n", (*ds)->legend(), MetaData::ModeString(mode)); State.RemoveDataSet( *ds ); ++Nremoved; } } } else if ( criterion == STYPE ) { MetaData::scalarType type_val = MetaData::TypeFromKeyword( val1, MetaData::UNKNOWN_MODE ); if (type_val == MetaData::UNDEFINED) { mprinterr("Error: '%s' is not a valid type.\n", val1.c_str()); return CpptrajState::ERR; } for (DataSetList::const_iterator ds = tempDSL.begin(); ds != tempDSL.end(); ++ds) { bool remove = false; MetaData::scalarType type = (*ds)->Meta().ScalarType(); if (select == EQUAL ) remove = ( type == type_val ); else if (select == NOT_EQUAL) remove = ( type != type_val ); else return CpptrajState::ERR; // Sanity check if (remove) { mprintf("\t Removing set '%s' (typeis '%s')\n", (*ds)->legend(), MetaData::TypeString(type)); State.RemoveDataSet( *ds ); ++Nremoved; } } } else { mprinterr("Internal Error: Criterion not yet implemented.\n"); return CpptrajState::ERR; } mprintf("\tRemoved %u of %zu sets.\n", Nremoved, tempDSL.size()); return CpptrajState::OK; }
// DataIO_Mdout::ReadData() int DataIO_Mdout::ReadData(FileName const& fname, DataSetList& datasetlist, std::string const& dsname) { mprintf("\tReading from mdout file: %s\n", fname.full()); BufferedLine buffer; if (buffer.OpenFileRead( fname )) return 1; const char* ptr = buffer.Line(); if (ptr == 0) { mprinterr("Error: Nothing in MDOUT file: %s\n", fname.full()); return 1; } // ----- PARSE THE INPUT SECTION ----- int imin = -1; // imin for this file const char* Trigger = 0; // Trigger for storing energies, must be 8 chars long. int frame = 0; // Frame counter for this file double dt = 1.0; // Timestep for this file (MD) double t0 = 0.0; // Initial time for this file (MD) int ntpr = 1; // Value of ntpr int irest = 0; // Value of irest while ( ptr != 0 && strncmp(ptr, " 2. CONTROL DATA", 20) != 0 ) ptr = buffer.Line(); if (ptr == 0) return EOF_ERROR(); // Determine whether this is dynamics or minimization, get dt ptr = buffer.Line(); // Dashes ptr = buffer.Line(); // Blank ptr = buffer.Line(); // title line while ( strncmp(ptr, " 3. ATOMIC", 13) != 0 ) { ArgList mdin_args( ptr, " ,=" ); // Remove commas, equal signs // Scan for stuff we want //mprintf("DEBUG:\tInput[%i] %s", mdin_args.Nargs(), mdin_args.ArgLine()); for (int col=0; col < mdin_args.Nargs(); col += 2) { int col1 = col + 1; if (mdin_args[col] == "imin") { imin = convertToInteger( mdin_args[ col1 ] ); if (debug_ > 0) mprintf("\t\tMDIN: imin is %i\n", imin); // Set a trigger for printing. For imin5 this is the word minimization. // For imin0 or imin1 this is NSTEP. if (imin==0) Trigger = " NSTEP ="; else if (imin==1) Trigger = " NSTEP"; else if (imin==5) Trigger = "minimiza"; // Since imin0 and imin1 first trigger has no data, set frame 1 lower. if (imin==1 || imin==0) frame = -1; } else if (mdin_args[col] == "dt") { dt = convertToDouble( mdin_args[ col1 ] ); if (debug_ > 0) mprintf("\t\tMDIN: dt is %f\n", dt); } else if (mdin_args[col] == "t") { t0 = convertToDouble( mdin_args[ col1 ] ); if (debug_ > 0) mprintf("\t\tMDIN: t is %f\n", t0); } else if (mdin_args[col] == "ntpr") { ntpr = convertToInteger( mdin_args[ col1 ] ); if (debug_ > 0) mprintf("\t\tMDIN: ntpr is %i\n", ntpr); } else if (mdin_args[col] == "irest") { irest = convertToInteger( mdin_args[ col1 ] ); if (debug_ > 0) mprintf("\t\tMDIN: irest is %i\n", irest); } } ptr = buffer.Line(); if (ptr == 0) return EOF_ERROR(); } if (Trigger == 0) { mprinterr("Error: Could not determine whether MDOUT is md, min, or post-process.\n"); return 1; } // ----- PARSE THE ATOMIC ... SECTION ----- while ( ptr != 0 && strncmp(ptr, " 4. RESULTS", 14) != 0 ) { ptr = buffer.Line(); // If run is a restart, set the initial time value. if (irest == 1) { if (strncmp(ptr, " begin time", 11) == 0) { sscanf(ptr, " begin time read from input coords = %lf", &t0); if (debug_ > 0) mprintf("\t\tMD restart initial time= %f\n", t0); } } } if (ptr == 0) return EOF_ERROR(); // ----- PARSE THE RESULTS SECTION ----- bool finalE = false; int nstep; int minStep = 0; // For imin=1 only if (irest == 0) nstep = 0; else nstep = ntpr; double Energy[N_FIELDTYPES]; std::fill( Energy, Energy+N_FIELDTYPES, 0.0 ); std::vector<bool> EnergyExists(N_FIELDTYPES, false); DataSetList::Darray TimeVals; DataSetList::DataListType inputSets(N_FIELDTYPES, 0); Sarray Name(2); double time = 0.0; while (ptr != 0) { // Check for end of imin 0 or 1 run; do not record Average and Stdevs if ( (imin == 1 && (strncmp(ptr, " FINAL", 25) == 0 || strncmp(ptr, " 5. TIMINGS", 14) == 0 )) || (imin == 0 && strncmp(ptr, " A V", 9) == 0)) finalE = true; // Check for '| TI region 2' to prevent reading duplicate energies if ( strncmp(ptr, "| TI region 2", 14) == 0 ) { while (ptr != 0 && !(ptr[0] == ' ' && ptr[1] == '-')) ptr = buffer.Line(); if (ptr == 0) return EOF_ERROR(); } // Record set for energy post-processing if (imin == 5 && strncmp(ptr, "minimizing", 10) == 0) nstep = atoi( ptr + 22 ); // MAIN OUTPUT ROUTINE // If the trigger has been reached print output. // For imin0 and imin1 the first trigger will have no data. // If the end of the file has been reached print then exit. if ( strncmp(ptr, Trigger, 8) == 0 || finalE ) { if (frame > -1) { // Store all energies present. for (int i = 0; i < (int)N_FIELDTYPES; i++) { if (EnergyExists[i]) { if (inputSets[i] == 0) { MetaData md( dsname, Enames[i] ); md.SetLegend( dsname + "_" + Enames[i] ); inputSets[i] = new DataSet_double(); inputSets[i]->SetMeta( md ); } // Since energy terms can appear and vanish over the course of the // mdout file, resize if necessary. if (frame > (int)inputSets[i]->Size()) ((DataSet_double*)inputSets[i])->Resize( frame ); ((DataSet_double*)inputSets[i])->AddElement( Energy[i] ); } } TimeVals.push_back( time ); nstep += ntpr; } frame++; if (finalE) break; } // Check for NSTEP in minimization or post-processing. Values will be // on the next line. NOTE: NSTEP means something different for imin=5. if ((imin == 1 || imin == 5) && strncmp(ptr, " NSTEP", 8) == 0) { ptr = buffer.Line(); // Get next line //sscanf(ptr, " %6lf %13lE %13lE %13lE", Energy+NSTEP, Energy+EPtot, Energy+RMS, Energy+GMAX); sscanf(ptr, " %i %lE %lE %lE", &minStep, Energy+EPtot, Energy+RMS, Energy+GMAX); EnergyExists[EPtot] = true; EnergyExists[RMS] = true; EnergyExists[GMAX] = true; ptr = buffer.Line(); } // Tokenize line, scan through until '=' is reached; value after is target. int ntokens = buffer.TokenizeLine(" "); if (ntokens > 0) { int nidx = 0; Name[0].clear(); Name[1].clear(); for (int tidx = 0; tidx < ntokens; tidx++) { const char* tkn = buffer.NextToken(); if (tkn[0] == '=') { FieldType Eindex = getEindex(Name); tkn = buffer.NextToken(); ++tidx; if (tkn == 0) mprintf("Warning: No numerical value, line %i column %i. Skipping.\n", buffer.LineNumber(), tidx+1); else if (tkn[0] == '*' || tkn[0] == 'N') // Assume if number begins with N it is NaN mprintf("Warning: Numerical overflow detected, line %i column %i. Skipping.\n", buffer.LineNumber(), tidx+1); else { if (Eindex != N_FIELDTYPES) { Energy[Eindex] = atof( tkn ); EnergyExists[Eindex] = true; } } nidx = 0; Name[0].clear(); Name[1].clear(); } else { if (nidx > 1) break; // Two tokens, no '=' found. Not an E line. Name[nidx++].assign( tkn ); } } } // Set time switch (imin) { case 5: time = (double)nstep + t0; break; case 1: time = (double)minStep + t0; break; case 0: time = ((double)nstep * dt) + t0; break; } // Read in next line ptr = buffer.Line(); } mprintf("\t%i frames\n", frame); buffer.CloseFile(); std::string Xlabel; if (imin == 5) Xlabel.assign("Set"); else if (imin == 1) Xlabel.assign("Nstep"); else Xlabel.assign("Time"); // imin == 0 if (datasetlist.AddOrAppendSets( Xlabel, TimeVals, inputSets )) return 1; return 0; }
/** Given an ArgList containing name,[min,max,step,bins,col,N], set up a * coordinate with that name and parameters min, max, step, bins. * If '*' or not specified, a default value will be set. * \return 1 if error occurs, 0 otherwise. */ int Analysis_Hist::setupDimension(ArgList &arglist, DataSet_1D const& dset, size_t& offset) { bool minArg = false; bool maxArg = false; bool stepArg = false; bool binsArg = false; if (debug_>1) arglist.PrintList(); // Set up dimension name // NOTE: arglist[0] should be same as dset name from CheckDimension std::string const& dLabel = arglist[0]; // Cycle through coordinate arguments. Any argument left blank will be // assigned a default value later. double dMin = 0.0; double dMax = 0.0; double dStep = 0.0; int dBins = -1; for (int i = 1; i < arglist.Nargs(); i++) { if (debug_>1) mprintf("DEBUG: setupCoord: Token %i (%s)\n", i, arglist[i].c_str()); // '*' means default explicitly requested if (arglist[i] == "*") continue; switch (i) { case 1 : dMin = convertToDouble( arglist[i]); minArg = true; break; case 2 : dMax = convertToDouble( arglist[i]); maxArg = true; break; case 3 : dStep = convertToDouble( arglist[i]); stepArg = true; break; case 4 : dBins = convertToInteger(arglist[i]); binsArg = true; break; } } // If no min arg and no default min arg, get min from dataset if (!minArg) { if (!minArgSet_) dMin = dset.Min(); else dMin = default_min_; } // If no max arg and no default max arg, get max from dataset if (!maxArg) { if (!maxArgSet_) dMax = dset.Max(); else dMax = default_max_; } // If bins/step not specified, use default if (!binsArg) dBins = default_bins_; if (!stepArg) dStep = default_step_; // Calculate dimension from given args. HistBin dim; if (dim.CalcBinsOrStep( dMin, dMax, dStep, dBins, dLabel )) { mprinterr("Error: Could not set up histogram dimension '%s'\n", dLabel.c_str()); return 1; } dim.PrintHistBin(); dimensions_.push_back( dim ); // Recalculate offsets for all dimensions starting at farthest coord. This // follows row major ordering. size_t last_offset = 1UL; // For checking overflow. offset = 1UL; binOffsets_.resize( dimensions_.size() ); OffType::iterator bOff = binOffsets_.begin(); for (HdimType::const_iterator rd = dimensions_.begin(); rd != dimensions_.end(); ++rd, ++bOff) { if (debug_>0) mprintf("\tHistogram: %s offset is %zu\n", rd->label(), offset); *bOff = (long int)offset; offset *= rd->Bins(); // Check for overflow. if ( offset < last_offset ) { mprinterr("Error: Too many bins for histogram. Try reducing the number of bins and/or\n" "Error: the number of dimensions.\n"); return 1; } last_offset = offset; } // offset should now be equal to the total number of bins across all dimensions if (debug_>0) mprintf("\tHistogram: Total Bins = %zu\n",offset); return 0; }
// Action_MakeStructure::Init() Action::RetType Action_MakeStructure::Init(ArgList& actionArgs, TopologyList* PFL, DataSetList* DSL, DataFileList* DFL, int debugIn) { debug_ = debugIn; secstruct_.clear(); // Get all arguments std::string ss_expr = actionArgs.GetStringNext(); while ( !ss_expr.empty() ) { ArgList ss_arg(ss_expr, ":"); if (ss_arg.Nargs() < 2) { mprinterr("Error: Malformed SS arg.\n"); Help(); return Action::ERR; } // Type is 1st arg, range is 2nd arg. SecStructHolder ss_holder(ss_arg[1], FindSStype(ss_arg[0])); if (ss_arg.Nargs() == 2) { // Find SS type: <ss type>:<range> if (ss_holder.sstype_idx == SS_EMPTY) { mprinterr("Error: SS type %s not found.\n", ss_arg[0].c_str()); return Action::ERR; } ss_holder.dihSearch_.SearchFor(MetaData::PHI); ss_holder.dihSearch_.SearchFor(MetaData::PSI); secstruct_.push_back( ss_holder ); } else if (ss_arg[0] == "ref") { // Use dihedrals from reference structure if (ss_arg.Nargs() < 3) { mprinterr("Error: Invalid 'ref' arg. Requires 'ref:<range>:<refname>[:<ref range>]'\n"); return Action::ERR; } ss_arg.MarkArg(0); ss_arg.MarkArg(1); // Sanity check: Currently only unique args of this type are allowed if (ss_holder.sstype_idx != SS_EMPTY) { mprinterr("Error: Ref backbone types must be unique [%s]\n", ss_arg[0].c_str()); return Action::ERR; } // Use backbone phi/psi from reference structure ss_holder.dihSearch_.SearchFor(MetaData::PHI); ss_holder.dihSearch_.SearchFor(MetaData::PSI); // Get reference structure DataSet_Coords_REF* REF = (DataSet_Coords_REF*) DSL->FindSetOfType(ss_arg.GetStringNext(), DataSet::REF_FRAME); // ss_arg[2] if (REF == 0) { mprinterr("Error: Could not get reference structure [%s]\n", ss_arg[2].c_str()); return Action::ERR; } // Get reference residue range, or use resRange Range refRange(ss_arg.GetStringNext(), -1); // ss_arg[3] if (!refRange.Empty()) { if (ss_holder.resRange.Size() != refRange.Size()) { mprinterr("Error: Reference range [%s] must match residue range [%s]\n", refRange.RangeArg(), ss_holder.resRange.RangeArg()); return Action::ERR; } } else refRange = ss_holder.resRange; // Look for phi/psi only in reference DihedralSearch refSearch; refSearch.SearchFor(MetaData::PHI); refSearch.SearchFor(MetaData::PSI); if (refSearch.FindDihedrals( REF->Top(), refRange )) return Action::ERR; // For each found dihedral, set theta for (DihedralSearch::mask_it dih = refSearch.begin(); dih != refSearch.end(); ++dih) { double torsion = Torsion( REF->RefFrame().XYZ(dih->A0()), REF->RefFrame().XYZ(dih->A1()), REF->RefFrame().XYZ(dih->A2()), REF->RefFrame().XYZ(dih->A3()) ); ss_holder.thetas_.push_back( (float)torsion ); } secstruct_.push_back( ss_holder ); } else if (ss_arg.Nargs() == 4 && isalpha(ss_arg[2][0])) { // Single dihedral type: <name>:<range>:<dih type>:<angle> DihedralSearch::DihedralType dtype = DihedralSearch::GetType(ss_arg[2]); if (ss_holder.sstype_idx == SS_EMPTY) { // Type not yet defined. Create new type. if (dtype == MetaData::UNDEFINED) { mprinterr("Error: Dihedral type %s not found.\n", ss_arg[2].c_str()); return Action::ERR; } if (!validDouble(ss_arg[3])) { mprinterr("Error: 4th arg (angle) is not a valid number.\n"); return Action::ERR; } SS.push_back( SS_TYPE(convertToDouble(ss_arg[3]), 0.0, 0.0, 0.0, 2, ss_arg[0]) ); ss_holder.sstype_idx = (int)(SS.size() - 1); } ss_holder.dihSearch_.SearchFor( dtype ); secstruct_.push_back( ss_holder ); } else if (ss_arg.Nargs() == 7 || ss_arg.Nargs() == 8) { // Single custom dihedral type: <name>:<range>:<at0>:<at1>:<at2>:<at3>:<angle>[:<offset>] if (ss_holder.sstype_idx == SS_EMPTY) { // Type not yet defined. Create new type. if (!validDouble(ss_arg[6])) { mprinterr("Error: 7th arg (angle) is not a valid number.\n"); return Action::ERR; } SS.push_back( SS_TYPE(convertToDouble(ss_arg[6]), 0.0, 0.0, 0.0, 2, ss_arg[0]) ); ss_holder.sstype_idx = (int)(SS.size() - 1); } int offset = 0; if (ss_arg.Nargs() == 8) { if (!validInteger(ss_arg[7])) { mprinterr("Error: 8th arg (offset) is not a valid number.\n"); return Action::ERR; } offset = convertToInteger(ss_arg[7]); } ss_holder.dihSearch_.SearchForNewType(offset,ss_arg[2],ss_arg[3],ss_arg[4],ss_arg[5], ss_arg[0]); secstruct_.push_back( ss_holder ); } else if (ss_arg.Nargs() == 4 || ss_arg.Nargs() == 6) { // Custom SS/turn type: <name>:<range>:<phi1>:<psi1>[:<phi2>:<psi2>] if (ss_holder.sstype_idx == SS_EMPTY) { // Type not yet defined. Create new type. if (!validDouble(ss_arg[2]) || !validDouble(ss_arg[3])) { mprinterr("Error: 3rd or 4th arg (phi1/psi1) is not a valid number.\n"); return Action::ERR; } double phi1 = convertToDouble(ss_arg[2]); double psi1 = convertToDouble(ss_arg[3]); int isTurn = 0; double phi2 = 0.0; double psi2 = 0.0; if (ss_arg.Nargs() == 6) { isTurn = 1; if (!validDouble(ss_arg[4]) || !validDouble(ss_arg[5])) { mprinterr("Error: 5th or 6th arg (phi2/psi2) is not a valid number.\n"); return Action::ERR; } phi2 = convertToDouble(ss_arg[4]); psi2 = convertToDouble(ss_arg[5]); } SS.push_back(SS_TYPE(phi1, psi1, phi2, psi2, isTurn, ss_arg[0] )); ss_holder.sstype_idx = (int)(SS.size() - 1); } ss_holder.dihSearch_.SearchFor(MetaData::PHI); ss_holder.dihSearch_.SearchFor(MetaData::PSI); secstruct_.push_back( ss_holder ); } else { mprinterr("Error: SS arg type [%s] not recognized.\n", ss_arg[0].c_str()); return Action::ERR; } ss_expr = actionArgs.GetStringNext(); } // End loop over args if (secstruct_.empty()) { mprinterr("Error: No SS types defined.\n"); return Action::ERR; } mprintf(" MAKESTRUCTURE:\n"); for (std::vector<SecStructHolder>::iterator ss = secstruct_.begin(); ss != secstruct_.end(); ++ss) { if (ss->sstype_idx != SS_EMPTY) { const SS_TYPE& myType = SS[ss->sstype_idx]; switch ( myType.isTurn ) { case 0: mprintf("\tSS type %s will be applied to residue(s) %s\n", myType.type_arg.c_str(), ss->resRange.RangeArg()); break; case 1: mprintf("\tTurn type %s will be applied to residue(s) %s\n", myType.type_arg.c_str(), ss->resRange.RangeArg()); break; case 2: mprintf("\tDihedral value of %.2f will be applied to %s dihedrals in residue(s) %s\n", myType.phi, myType.type_arg.c_str(), ss->resRange.RangeArg()); } } else mprintf("\tBackbone angles from reference will be applied to residue(s) %s\n", ss->resRange.RangeArg()); } return Action::OK; }