diff --git a/colvartools/poisson_integrator.cpp b/colvartools/poisson_integrator.cpp index 5ff2aa92e..4ad4f3080 100644 --- a/colvartools/poisson_integrator.cpp +++ b/colvartools/poisson_integrator.cpp @@ -14,11 +14,11 @@ int main (int argc, char *argv[]) { } colvarproxy *proxy = new colvarproxy(); - proxy->colvars = new colvarmodule(proxy); // This could be omitted if we used the colvarproxy_stub class + proxy->cvmodule = new colvarmodule(proxy); // This could be omitted if we used the colvarproxy_stub class std::string gradfile (argv[1]); std::shared_ptr grad_ptr = std::make_shared(gradfile); - if (cvm::get_error()) { return -1; } + if (proxy->cvmodule->get_error()) { return -1; } int itmax = 10000; cvm::real err; diff --git a/colvartools/poisson_integrator_conv.cpp b/colvartools/poisson_integrator_conv.cpp index 62fa030c2..e8a477ffc 100644 --- a/colvartools/poisson_integrator_conv.cpp +++ b/colvartools/poisson_integrator_conv.cpp @@ -14,11 +14,11 @@ int main (int argc, char *argv[]) { } colvarproxy *proxy = new colvarproxy(); - proxy->colvars = new colvarmodule(proxy); // This could be omitted if we used the colvarproxy_stub class + proxy->cvmodule = new colvarmodule(proxy); // This could be omitted if we used the colvarproxy_stub class std::string gradfile (argv[1]); std::shared_ptr grad_ptr = std::make_shared(gradfile); - if (cvm::get_error()) { return -1; } + if (proxy->cvmodule->get_error()) { return -1; } cvm::real err = 1.; cvm::real tol = 1e-10; @@ -28,10 +28,10 @@ int main (int argc, char *argv[]) { // Load reference colvar_grid_scalar ref(gradfile + ".ref"); - if (cvm::get_error()) { return -1; } + if (proxy->cvmodule->get_error()) { return -1; } if (ref.number_of_points() != fes.number_of_points()) { - cvm::error("Reference grid has wrong number of points: " + cvm::to_str(ref.number_of_points()) + "\n"); + proxy->cvmodule->error("Reference grid has wrong number of points: " + cvm::to_str(ref.number_of_points()) + "\n"); return -1; } diff --git a/gromacs/src/applied_forces/colvars/colvarproxygromacs.cpp.patch b/gromacs/src/applied_forces/colvars/colvarproxygromacs.cpp.patch new file mode 100644 index 000000000..cb8c0ab98 --- /dev/null +++ b/gromacs/src/applied_forces/colvars/colvarproxygromacs.cpp.patch @@ -0,0 +1,82 @@ +diff --git a/src/gromacs/applied_forces/colvars/colvarproxygromacs.cpp b/src/gromacs/applied_forces/colvars/colvarproxygromacs.cpp +index 76b350c611..e7cbe0dc28 100644 +--- a/src/gromacs/applied_forces/colvars/colvarproxygromacs.cpp ++++ b/src/gromacs/applied_forces/colvars/colvarproxygromacs.cpp +@@ -117,23 +117,23 @@ ColvarProxyGromacs::ColvarProxyGromacs(const std::string& colvarsConfigString, + input_streams_[inputName] = new std::istringstream(content); + } + +- colvars = new colvarmodule(this); +- cvm::log(cvm::line_marker); +- cvm::log("Start colvars Initialization."); ++ cvmodule = new colvarmodule(this); ++ cvmodule->log(cvmodule->line_marker); ++ cvmodule->log("Start colvars Initialization."); + + +- colvars->cite_feature("GROMACS engine"); +- colvars->cite_feature("Colvars-GROMACS interface"); ++ cvmodule->cite_feature("GROMACS engine"); ++ cvmodule->cite_feature("Colvars-GROMACS interface"); + + if (cvm::debug()) + { +- cvm::log("Initializing the colvars proxy object.\n"); ++ cvmodule->log("Initializing the colvars proxy object.\n"); + } + + int errorCode = colvarproxy::setup(); +- errorCode |= colvars->read_config_string(colvarsConfigString); +- errorCode |= colvars->update_engine_parameters(); +- errorCode |= colvars->setup_input(); ++ errorCode |= cvmodule->read_config_string(colvarsConfigString); ++ errorCode |= cvmodule->update_engine_parameters(); ++ errorCode |= cvmodule->setup_input(); + + if (errorCode != COLVARS_OK) + { +@@ -141,10 +141,10 @@ ColvarProxyGromacs::ColvarProxyGromacs(const std::string& colvarsConfigString, + } + + // Citation Reporter +- cvm::log(std::string("\n") + colvars->feature_report(0) + std::string("\n")); ++ cvmodule->log(std::string("\n") + cvmodule->feature_report(0) + std::string("\n")); + + // TODO get initial step number from MDModules +- // colvars->set_initial_step(static_cast(0L)); ++ // cvmodule->set_initial_step(static_cast(0L)); + } + } + +@@ -196,7 +196,7 @@ int ColvarProxyGromacs::set_unit_system(std::string const& unitsIn, bool /*colva + { + if (unitsIn != "gromacs") + { +- cvm::error( ++ cvmodule->error( + "Specified unit system \"" + unitsIn + + "\" is unsupported in Gromacs. Supported units are \"gromacs\" (nm, kJ/mol).\n"); + return COLVARS_ERROR; +@@ -218,7 +218,7 @@ int ColvarProxyGromacs::check_atom_id(int atomNumber) + } + if ((aid < 0) || (aid >= gmxAtoms_.nr)) + { +- cvm::error("Error: invalid atom number specified, " + cvm::to_str(atomNumber) + "\n", ++ cvmodule->error("Error: invalid atom number specified, " + cvm::to_str(atomNumber) + "\n", + COLVARS_INPUT_ERROR); + return COLVARS_INPUT_ERROR; + } +@@ -273,10 +273,10 @@ void ColvarProxyGromacs::updateAtomProperties(int index) + + ColvarProxyGromacs::~ColvarProxyGromacs() + { +- if (colvars != nullptr) ++ if (cvmodule != nullptr) + { +- delete colvars; +- colvars = nullptr; ++ delete cvmodule; ++ cvmodule = nullptr; + } + } + \ No newline at end of file diff --git a/gromacs/src/applied_forces/colvars/colvarproxygromacs.h.diff b/gromacs/src/applied_forces/colvars/colvarproxygromacs.h.patch similarity index 100% rename from gromacs/src/applied_forces/colvars/colvarproxygromacs.h.diff rename to gromacs/src/applied_forces/colvars/colvarproxygromacs.h.patch diff --git a/gromacs/src/applied_forces/colvars/colvarsMDModule.cpp.diff b/gromacs/src/applied_forces/colvars/colvarsMDModule.cpp.patch similarity index 100% rename from gromacs/src/applied_forces/colvars/colvarsMDModule.cpp.diff rename to gromacs/src/applied_forces/colvars/colvarsMDModule.cpp.patch diff --git a/gromacs/src/applied_forces/colvars/colvarsforceprovider.cpp.patch b/gromacs/src/applied_forces/colvars/colvarsforceprovider.cpp.patch new file mode 100644 index 000000000..85ddb97fe --- /dev/null +++ b/gromacs/src/applied_forces/colvars/colvarsforceprovider.cpp.patch @@ -0,0 +1,94 @@ +diff --git a/src/gromacs/applied_forces/colvars/colvarsforceprovider.cpp b/src/gromacs/applied_forces/colvars/colvarsforceprovider.cpp +index 5860eed790..8a3232131c 100644 +--- a/src/gromacs/applied_forces/colvars/colvarsforceprovider.cpp ++++ b/src/gromacs/applied_forces/colvars/colvarsforceprovider.cpp +@@ -201,7 +201,7 @@ ColvarsForceProvider::ColvarsForceProvider(const std::string& colvarsConfigStrin + + if (doParsing_) + { +- colvars->setup_output(); ++ cvmodule->setup_output(); + } + + +@@ -258,7 +258,7 @@ ColvarsForceProvider::ColvarsForceProvider(const std::string& colvarsConfigStrin + { + if (stateToCheckpoint_.nColvarsAtoms_ != nColvarsAtoms) + { +- cvm::error( ++ cvmodule->error( + "Number of colvars atoms in the .cpt file differs from the one in .tpr " + "file"); + } +@@ -271,8 +271,8 @@ ColvarsForceProvider::ColvarsForceProvider(const std::string& colvarsConfigStrin + + int errorCode = colvarproxy::setup(); + // Read input state file +- errorCode |= colvars->set_input_state_buffer(stateToCheckpoint_.colvarStateFile_); +- errorCode |= colvars->setup_input(); ++ errorCode |= cvmodule->set_input_state_buffer(stateToCheckpoint_.colvarStateFile_); ++ errorCode |= cvmodule->setup_input(); + + if (errorCode != COLVARS_OK) + { +@@ -303,19 +303,19 @@ ColvarsForceProvider::ColvarsForceProvider(const std::string& colvarsConfigStrin + + if (mpiComm.isMainRank() && cvm::debug()) + { +- cvm::log("atoms_ids = " + cvm::to_str(atoms_ids) + "\n"); +- cvm::log("atoms_refcount = " + cvm::to_str(atoms_refcount) + "\n"); +- cvm::log("positions = " + cvm::to_str(atoms_positions) + "\n"); +- cvm::log("total_forces = " + cvm::to_str(atoms_total_forces) + "\n"); +- cvm::log("atoms_new_colvar_forces = " + cvm::to_str(atoms_new_colvar_forces) + "\n"); +- cvm::log(cvm::line_marker); ++ cvmodule->log("atoms_ids = " + cvm::to_str(atoms_ids) + "\n"); ++ cvmodule->log("atoms_refcount = " + cvm::to_str(atoms_refcount) + "\n"); ++ cvmodule->log("positions = " + cvm::to_str(atoms_positions) + "\n"); ++ cvmodule->log("total_forces = " + cvm::to_str(atoms_total_forces) + "\n"); ++ cvmodule->log("atoms_new_colvar_forces = " + cvm::to_str(atoms_new_colvar_forces) + "\n"); ++ cvmodule->log(cvmodule->line_marker); + log("Done initializing the colvars proxy object.\n"); + } + + if (mpiComm.isMainRank()) + { +- cvm::log(cvm::line_marker); +- cvm::log("End colvars Initialization.\n\n"); ++ cvmodule->log(cvmodule->line_marker); ++ cvmodule->log("End colvars Initialization.\n\n"); + } + } + +@@ -347,8 +347,10 @@ void ColvarsForceProvider::calculateForces(const ForceProviderInput& forceProvid + const rvec* xPointer = &(x.data()->as_vec()); + const auto& box = forceProviderInput.box_; + +- colvars->it = forceProviderInput.step_; +- ++ if (cvmodule) // Only one thread has a pointer to the module ++ { ++ cvmodule->it = forceProviderInput.step_; // 'it' is not a static class member anymore ++ } + + // Eventually there needs to be an interface to update local data upon neighbor search + // We could check if by chance all atoms are in one node, and skip communication +@@ -389,9 +391,9 @@ void ColvarsForceProvider::calculateForces(const ForceProviderInput& forceProvid + + biasEnergy = 0.0; + // Call the collective variable module to fill atoms_new_colvar_forces +- if (colvars->calc() != COLVARS_OK) ++ if (cvmodule->calc() != COLVARS_OK) + { +- cvm::error("Error calling colvars->calc()\n"); ++ cvmodule->error("Error calling cvmodule->calc()\n"); + } + + // Copy the forces to C array for broadcasting +@@ -462,7 +464,7 @@ void ColvarsForceProvider::add_energy(cvm::real energy) + void ColvarsForceProvider::writeCheckpointData(MDModulesWriteCheckpointData checkpointWriting, + std::string_view moduleName) + { +- colvars->write_state_buffer(stateToCheckpoint_.colvarStateFile_); ++ cvmodule->write_state_buffer(stateToCheckpoint_.colvarStateFile_); + stateToCheckpoint_.writeState(checkpointWriting.builder_, moduleName); + } diff --git a/gromacs/src/applied_forces/colvars/colvarspreprocessor.cpp.patch b/gromacs/src/applied_forces/colvars/colvarspreprocessor.cpp.patch new file mode 100644 index 000000000..aefc26608 --- /dev/null +++ b/gromacs/src/applied_forces/colvars/colvarspreprocessor.cpp.patch @@ -0,0 +1,15 @@ +diff --git a/src/gromacs/applied_forces/colvars/colvarspreprocessor.cpp b/src/gromacs/applied_forces/colvars/colvarspreprocessor.cpp +index 16c0f8ceba..c671eef78d 100644 +--- a/src/gromacs/applied_forces/colvars/colvarspreprocessor.cpp ++++ b/src/gromacs/applied_forces/colvars/colvarspreprocessor.cpp +@@ -78,8 +78,8 @@ ColvarsPreProcessor::ColvarsPreProcessor(const std::string& colvarsConfigStrin + // Initialize t_pbc struct + set_pbc(&gmxPbc_, pbcType, box); + +- cvm::log(cvm::line_marker); +- cvm::log("End colvars Initialization.\n\n"); ++ cvmodule->log(cvmodule->line_marker); ++ cvmodule->log("End colvars Initialization.\n\n"); + } + + std::vector ColvarsPreProcessor::getColvarsCoords() diff --git a/lammps/src/COLVARS/colvarproxy_lammps.cpp b/lammps/src/COLVARS/colvarproxy_lammps.cpp index be216b0bf..112b28277 100644 --- a/lammps/src/COLVARS/colvarproxy_lammps.cpp +++ b/lammps/src/COLVARS/colvarproxy_lammps.cpp @@ -46,22 +46,22 @@ void colvarproxy_lammps::init() version_int = get_version_from_string(COLVARPROXY_VERSION); // create the colvarmodule instance - colvars = new colvarmodule(this); + cvmodule = new colvarmodule(this); // Create instance of scripting interface - script = new colvarscript(this, colvars); + script = new colvarscript(this, cvmodule); - cvm::log("Using LAMMPS interface, version " + cvm::to_str(COLVARPROXY_VERSION) + ".\n"); + cvmodule->log("Using LAMMPS interface, version " + cvm::to_str(COLVARPROXY_VERSION) + ".\n"); - colvars->cite_feature("LAMMPS engine"); - colvars->cite_feature("Colvars-LAMMPS interface"); + cvmodule->cite_feature("LAMMPS engine"); + cvmodule->cite_feature("Colvars-LAMMPS interface"); angstrom_value_ = _lmp->force->angstrom; boltzmann_ = _lmp->force->boltz; set_integration_timestep(_lmp->update->dt * _lmp->force->femtosecond); if (_lmp->update->ntimestep != 0) { - colvars->set_initial_step(static_cast(_lmp->update->ntimestep)); + cvmodule->set_initial_step(static_cast(_lmp->update->ntimestep)); } } @@ -94,9 +94,9 @@ int colvarproxy_lammps::setup() { int error_code = colvarproxy::setup(); set_integration_timestep(_lmp->update->dt * _lmp->force->femtosecond); - error_code |= colvars->update_engine_parameters(); - error_code |= colvars->setup_input(); - error_code |= colvars->setup_output(); + error_code |= cvmodule->update_engine_parameters(); + error_code |= cvmodule->setup_input(); + error_code |= cvmodule->setup_output(); return error_code; } @@ -106,8 +106,8 @@ int colvarproxy_lammps::setup() double colvarproxy_lammps::compute() { - if (cvm::debug()) { - cvm::log(std::string(cvm::line_marker) + + if (cvmodule->debug()) { + cvmodule->log(std::string(cvmodule->line_marker) + "colvarproxy_lammps step no. " + cvm::to_str(_lmp->update->ntimestep) + " [first - last = " + cvm::to_str(_lmp->update->beginstep) + " - " + @@ -119,7 +119,7 @@ double colvarproxy_lammps::compute() } else { // Use the time step number from LAMMPS Update object if (_lmp->update->ntimestep - previous_step == 1) { - colvarmodule::it++; + cvmodule->it++; b_simulation_continuing = false; } else { // Cases covered by this condition: @@ -152,9 +152,9 @@ double colvarproxy_lammps::compute() boundaries_type = boundaries_unsupported; } - if (cvm::debug()) { - cvm::log(std::string(cvm::line_marker) + - "colvarproxy_lammps, step no. " + cvm::to_str(colvarmodule::it) + "\n" + + if (cvmodule->debug()) { + cvmodule->log(std::string(cvmodule->line_marker) + + "colvarproxy_lammps, step no. " + cvm::to_str(cvmodule->it) + "\n" + "Updating internal data.\n"); } @@ -164,22 +164,22 @@ double colvarproxy_lammps::compute() bias_energy = 0.0; - if (cvm::debug()) { - cvm::log("atoms_ids = " + cvm::to_str(atoms_ids) + "\n"); - cvm::log("atoms_refcount = " + cvm::to_str(atoms_refcount) + "\n"); - cvm::log("atoms_positions = " + cvm::to_str(atoms_positions) + "\n"); - cvm::log("atoms_new_colvar_forces = " + cvm::to_str(atoms_new_colvar_forces) + "\n"); + if (cvmodule->debug()) { + cvmodule->log("atoms_ids = " + cvm::to_str(atoms_ids) + "\n"); + cvmodule->log("atoms_refcount = " + cvm::to_str(atoms_refcount) + "\n"); + cvmodule->log("atoms_positions = " + cvm::to_str(atoms_positions) + "\n"); + cvmodule->log("atoms_new_colvar_forces = " + cvm::to_str(atoms_new_colvar_forces) + "\n"); } // Call the collective variable module - if (colvars->calc() != COLVARS_OK) - cvm::error("Error in the collective variables module.\n", COLVARS_ERROR); - - if (cvm::debug()) { - cvm::log("atoms_ids = " + cvm::to_str(atoms_ids) + "\n"); - cvm::log("atoms_refcount = " + cvm::to_str(atoms_refcount) + "\n"); - cvm::log("atoms_positions = " + cvm::to_str(atoms_positions) + "\n"); - cvm::log("atoms_new_colvar_forces = " + cvm::to_str(atoms_new_colvar_forces) + "\n"); + if (cvmodule->calc() != COLVARS_OK) + cvmodule->error("Error in the collective variables module.\n", COLVARS_ERROR); + + if (cvmodule->debug()) { + cvmodule->log("atoms_ids = " + cvm::to_str(atoms_ids) + "\n"); + cvmodule->log("atoms_refcount = " + cvm::to_str(atoms_refcount) + "\n"); + cvmodule->log("atoms_positions = " + cvm::to_str(atoms_positions) + "\n"); + cvmodule->log("atoms_new_colvar_forces = " + cvm::to_str(atoms_new_colvar_forces) + "\n"); } return bias_energy; @@ -225,8 +225,8 @@ char const *colvarproxy_lammps::script_obj_to_str(unsigned char *obj) std::vector colvarproxy_lammps::script_obj_to_str_vector(unsigned char *obj) { - if (cvm::debug()) { - cvm::log("Called colvarproxy_lammps::script_obj_to_str_vector().\n"); + if (cvmodule->debug()) { + cvmodule->log("Called colvarproxy_lammps::script_obj_to_str_vector().\n"); } std::string const input(reinterpret_cast(obj)); return LAMMPS_NS::utils::split_words(input); // :-))) @@ -238,7 +238,7 @@ int colvarproxy_lammps::set_unit_system(std::string const &units_in, bool /*chec { std::string lmp_units = _lmp->update->unit_style; if (units_in != lmp_units) { - cvm::error("Error: Specified unit system for Colvars \"" + units_in + + cvmodule->error("Error: Specified unit system for Colvars \"" + units_in + "\" is incompatible with LAMMPS internal units (" + lmp_units + ").\n"); return COLVARS_ERROR; } @@ -251,12 +251,12 @@ int colvarproxy_lammps::check_atom_id(int atom_number) { int const aid = atom_number; - if (cvm::debug()) + if (cvmodule->debug()) log("Adding atom " + cvm::to_str(atom_number) + " for collective variables calculation.\n"); // TODO add upper boundary check? if ((aid < 0)) { - cvm::error("Error: invalid atom number specified, " + + cvmodule->error("Error: invalid atom number specified, " + cvm::to_str(atom_number) + "\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } diff --git a/lammps/src/COLVARS/fix_colvars.cpp b/lammps/src/COLVARS/fix_colvars.cpp index 468d8aa9e..22cff3459 100644 --- a/lammps/src/COLVARS/fix_colvars.cpp +++ b/lammps/src/COLVARS/fix_colvars.cpp @@ -880,7 +880,7 @@ void FixColvars::write_restart(FILE *fp) { if (comm->me == 0) { cvm::memory_stream ms; - if (proxy->colvars->write_state(ms)) { + if (proxy->cvmodule->write_state(ms)) { int len_cv_state = ms.length(); // Will write the buffer's length twice, so that the fix can read it later, too int len = len_cv_state + sizeof(int); @@ -901,7 +901,7 @@ void FixColvars::restart(char *buf) // Read the buffer's length, then load it into Colvars starting right past that location int length = *(reinterpret_cast(buf)); auto *colvars_state_buffer = reinterpret_cast(buf + sizeof(int)); - if (proxy->colvars->set_input_state_buffer(length, colvars_state_buffer) != COLVARS_OK) { + if (proxy->cvmodule->set_input_state_buffer(length, colvars_state_buffer) != COLVARS_OK) { error->all(FLERR, "Failed to set the Colvars input state from string buffer"); } } @@ -914,7 +914,7 @@ void FixColvars::post_run() if (comm->me == 0) { proxy->post_run(); if (lmp->citeme) { - lmp->citeme->add(proxy->colvars->feature_report(1)); + lmp->citeme->add(proxy->cvmodule->feature_report(1)); } } } diff --git a/misc_interfaces/C_fortran/colvarproxy_C.cpp b/misc_interfaces/C_fortran/colvarproxy_C.cpp index fd4eba7c4..6ccd68fcd 100644 --- a/misc_interfaces/C_fortran/colvarproxy_C.cpp +++ b/misc_interfaces/C_fortran/colvarproxy_C.cpp @@ -11,7 +11,7 @@ colvarproxy_C::colvarproxy_C() { std::cerr << "This is the colvarproxy_C constructor at address " << this << std::endl; colvars = new colvarmodule(this); - colvars->log("This is the Module speaking."); + cvmodule->log("This is the Module speaking."); } colvarproxy_C::~colvarproxy_C() diff --git a/misc_interfaces/stubs/colvarproxy_stub.cpp b/misc_interfaces/stubs/colvarproxy_stub.cpp index df2daabd7..37c3c1acb 100644 --- a/misc_interfaces/stubs/colvarproxy_stub.cpp +++ b/misc_interfaces/stubs/colvarproxy_stub.cpp @@ -29,15 +29,15 @@ colvarproxy_stub::colvarproxy_stub() // both fields are taken from data structures already available updated_masses_ = updated_charges_ = true; - colvars = new colvarmodule(this); - cvm::log("Using minimal testing interface.\n"); + cvmodule = new colvarmodule(this); + cvmodule->log("Using minimal testing interface.\n"); - colvars->cv_traj_freq = 0; // I/O will be handled explicitly - colvars->restart_out_freq = 0; + cvmodule->cv_traj_freq = 0; // I/O will be handled explicitly + cvmodule->restart_out_freq = 0; cvm::rotation::monitor_crossings = false; // Avoid unnecessary error messages - colvars->setup_input(); - colvars->setup_output(); + cvmodule->setup_input(); + cvmodule->setup_output(); colvarproxy_stub::setup(); } @@ -51,10 +51,10 @@ int colvarproxy_stub::setup() { boundaries_type = boundaries_non_periodic; reset_pbc_lattice(); - colvars->it = colvars->it_restart = 0; + cvmodule->it = cvmodule->it_restart = 0; - if (colvars) { - return colvars->update_engine_parameters(); + if (cvmodule) { + return cvmodule->update_engine_parameters(); } return COLVARS_OK; } @@ -85,7 +85,7 @@ int colvarproxy_stub::set_unit_system(std::string const &units_in, // colvarmodule sets this flag if new units are requested while colvars are already defined if (check_only) { if ((units != "" && units_in != units) || (units == "" && units_in != "real")) { - cvm::error("Specified unit system \"" + units_in + "\" is incompatible with previous setting \"" + cvmodule->error("Specified unit system \"" + units_in + "\" is incompatible with previous setting \"" + units + "\".\nReset the Colvars Module or delete all variables to change the unit.\n"); return COLVARS_ERROR; } else { @@ -107,7 +107,7 @@ int colvarproxy_stub::set_unit_system(std::string const &units_in, angstrom_value_ = 0.1; // nm kcal_mol_value_ = 4.184; // kJ/mol } else { - cvm::error("Unknown unit system specified: \"" + units_in + "\". Supported are real, metal, electron, and gromacs.\n"); + cvmodule->error("Unknown unit system specified: \"" + units_in + "\". Supported are real, metal, electron, and gromacs.\n"); return COLVARS_ERROR; } @@ -163,16 +163,16 @@ int colvarproxy_stub::init_atom(int atom_number) int colvarproxy_stub::read_frame_xyz(const char *filename, const bool write_force_file) { - int err = colvars->load_coords_xyz(filename, modify_atom_positions(), nullptr, true); + int err = cvmodule->load_coords_xyz(filename, modify_atom_positions(), nullptr, true); std::string force_filename; if (write_force_file) { - force_filename = colvars->output_prefix() + "_forces_" + cvm::to_str(colvars->it) + ".dat"; + force_filename = cvmodule->output_prefix() + "_forces_" + cvm::to_str(cvmodule->it) + ".dat"; } if ( !err ) { auto& new_forces = *(modify_atom_applied_forces()); std::fill(new_forces.begin(), new_forces.end(), cvm::rvector{0, 0, 0}); - colvars->calc(); - colvars->it++; + cvmodule->calc(); + cvmodule->it++; if (write_force_file) { const size_t numAtoms = modify_atom_positions()->size(); std::ofstream ofs(force_filename); diff --git a/misc_interfaces/stubs/colvarproxy_stub.h b/misc_interfaces/stubs/colvarproxy_stub.h index 9dc51809a..80c27084a 100644 --- a/misc_interfaces/stubs/colvarproxy_stub.h +++ b/misc_interfaces/stubs/colvarproxy_stub.h @@ -39,7 +39,7 @@ class colvarproxy_stub : public colvarproxy { int check_atom_id(int atom_number) override; - /// @brief Read next frame from XYZ file and call cvm::calc() + /// @brief Read next frame from XYZ file and call cvmodule->calc() /// @param filename Input XYZ file /// @param write_force_file Write the applied forces to files /// @return Error code diff --git a/namd/src/ScriptTcl.C.patch b/namd/src/ScriptTcl.C.patch new file mode 100644 index 000000000..7f43e88cd --- /dev/null +++ b/namd/src/ScriptTcl.C.patch @@ -0,0 +1,18 @@ +diff --git a/src/ScriptTcl.C b/src/ScriptTcl.C +index 682ebfa1..997c73cb 100644 +--- a/src/ScriptTcl.C ++++ b/src/ScriptTcl.C +@@ -1560,7 +1560,12 @@ int ScriptTcl::Tcl_colvars(ClientData clientData, + { + ScriptTcl *script = (ScriptTcl *) clientData; + script->initcheck(); +- return tcl_run_colvarscript_command(clientData, interp, objc, objv); ++ colvarmodule *cvmodule = Node::Object()->colvars; ++ if (!cvmodule) { ++ Tcl_SetResult(interp, (char *)"Colvars module not active", TCL_VOLATILE); ++ return TCL_ERROR; ++ } ++ return tcl_run_colvarscript_command(cvmodule->proxy->script, interp, objc, objv); + } + + int ScriptTcl::Tcl_checkpoint(ClientData clientData, diff --git a/namd/src/colvarproxy_namd.C b/namd/src/colvarproxy_namd.C index d4612686f..273f42c3c 100644 --- a/namd/src/colvarproxy_namd.C +++ b/namd/src/colvarproxy_namd.C @@ -112,12 +112,12 @@ colvarproxy_namd::colvarproxy_namd(GlobalMasterColvars *gm) init_atoms_map(); // initialize module: this object will be the communication proxy - colvars = new colvarmodule(this); + cvmodule = new colvarmodule(this); - cvm::log("Using NAMD interface, version "+ + cvmodule->log("Using NAMD interface, version "+ cvm::to_str(COLVARPROXY_VERSION)+".\n"); - colvars->cite_feature("NAMD engine"); - colvars->cite_feature("Colvars-NAMD interface"); + cvmodule->cite_feature("NAMD engine"); + cvmodule->cite_feature("Colvars-NAMD interface"); errno = 0; for ( ; config; config = config->next ) { @@ -127,12 +127,12 @@ colvarproxy_namd::colvarproxy_namd(GlobalMasterColvars *gm) // Trigger immediate initialization of the module colvarproxy::parse_module_config(); colvarproxy_namd::setup(); - colvars->update_engine_parameters(); - colvars->setup_input(); - colvars->setup_output(); + cvmodule->update_engine_parameters(); + cvmodule->setup_input(); + cvmodule->setup_output(); // save to Node for Tcl script access - Node::Object()->colvars = colvars; + Node::Object()->colvars = cvmodule; #ifdef NAMD_TCL have_scripts = true; @@ -141,7 +141,7 @@ colvarproxy_namd::colvarproxy_namd(GlobalMasterColvars *gm) #endif if (simparams->firstTimestep != 0) { - colvars->set_initial_step(static_cast(simparams->firstTimestep)); + cvmodule->set_initial_step(static_cast(simparams->firstTimestep)); } #if !defined (NAMD_UNIFIED_REDUCTION) @@ -229,7 +229,7 @@ int colvarproxy_namd::update_atoms_map(AtomIDList::const_iterator begin, } if (cvm::debug()) { - cvm::log("atoms_map = "+cvm::to_str(atoms_map)+".\n"); + cvmodule->log("atoms_map = "+cvm::to_str(atoms_map)+".\n"); } return COLVARS_OK; @@ -240,7 +240,7 @@ int colvarproxy_namd::setup() { int error_code = colvarproxy::setup(); - if (colvars->size() == 0) { + if (cvmodule->size() == 0) { // Module is empty, nothing to do return COLVARS_OK; } @@ -296,10 +296,10 @@ int colvarproxy_namd::setup() #endif size_t const new_features_hash = - std::hash{}(colvars->feature_report(0)); + std::hash{}(cvmodule->feature_report(0)); if (new_features_hash != features_hash) { // Nag only once, there may be many run commands - log(std::string("\n")+colvars->feature_report(0)+std::string("\n")); + log(std::string("\n")+cvmodule->feature_report(0)+std::string("\n")); features_hash = new_features_hash; } @@ -318,7 +318,7 @@ int colvarproxy_namd::setup() int colvarproxy_namd::reset() { if (cvm::debug()) { - cvm::log("colvarproxy_namd::reset()\n"); + cvmodule->log("colvarproxy_namd::reset()\n"); } int error_code = COLVARS_OK; @@ -345,9 +345,9 @@ void colvarproxy_namd::calculate() // First run after the proxy is constructed colvarproxy_namd::setup(); - colvars->update_engine_parameters(); - colvars->setup_input(); - colvars->setup_output(); + cvmodule->update_engine_parameters(); + cvmodule->setup_input(); + cvmodule->setup_output(); // Controller is only available after full startup phase, so now controller = &Node::Object()->state->getController(); @@ -357,7 +357,7 @@ void colvarproxy_namd::calculate() // Use the time step number inherited from GlobalMaster if ( step - previous_NAMD_step == time_step_factor() ) { - colvars->it += time_step_factor(); + cvmodule->it += time_step_factor(); b_simulation_continuing = false; } else { @@ -372,7 +372,7 @@ void colvarproxy_namd::calculate() colvarproxy_io::set_output_prefix(std::string(simparams->outputFilename)); colvarproxy_io::set_restart_output_prefix(std::string(simparams->restartFilename)); colvarproxy_io::set_default_restart_frequency(simparams->restartFrequency); - colvars->setup_output(); + cvmodule->setup_output(); } } @@ -406,8 +406,8 @@ void colvarproxy_namd::calculate() } if (cvm::debug()) { - cvm::log(std::string(cvm::line_marker)+ - "colvarproxy_namd, step no. "+cvm::to_str(colvars->it)+"\n"+ + cvmodule->log(std::string(cvmodule->line_marker)+ + "colvarproxy_namd, step no. "+cvm::to_str(cvmodule->it)+"\n"+ "Updating atomic data arrays.\n"); } @@ -447,7 +447,7 @@ void colvarproxy_namd::calculate() { if (cvm::debug()) { - cvm::log("Updating positions arrays.\n"); + cvmodule->log("Updating positions arrays.\n"); } size_t n_positions = 0; AtomIDList::const_iterator a_i = globalmaster->getAtomIdBeginPublic(); @@ -461,18 +461,18 @@ void colvarproxy_namd::calculate() // The following had to be relaxed because some atoms may be forced without their position being requested // if (n_positions < atoms_ids.size()) { - // cvm::error("Error: did not receive the positions of all atoms.\n", COLVARS_BUG_ERROR); + // cvmodule->error("Error: did not receive the positions of all atoms.\n", COLVARS_BUG_ERROR); // } } - if (total_force_requested && cvm::step_relative() > 0) { + if (total_force_requested && cvmodule->step_relative() > 0) { // sort the force arrays the previous step // (but only do so if there *is* a previous step!) { if (cvm::debug()) { - cvm::log("Updating total forces arrays.\n"); + cvmodule->log("Updating total forces arrays.\n"); } size_t n_total_forces = 0; AtomIDList::const_iterator a_i = globalmaster->getForceIdBeginPublic(); @@ -486,7 +486,7 @@ void colvarproxy_namd::calculate() if ( (! b_simulation_continuing) && (n_total_forces < atoms_ids.size()) ) { - cvm::error("Error: total forces were requested, but total forces " + cvmodule->error("Error: total forces were requested, but total forces " "were not received for all atoms.\n" "The most probable cause is combination of energy " "minimization with a biasing method that requires MD (e.g. ABF).\n" @@ -496,14 +496,14 @@ void colvarproxy_namd::calculate() { if (cvm::debug()) { - cvm::log("Updating group total forces arrays.\n"); + cvmodule->log("Updating group total forces arrays.\n"); } ForceList::const_iterator f_i = globalmaster->getGroupTotalForceBeginPublic(); ForceList::const_iterator f_e = globalmaster->getGroupTotalForceEndPublic(); size_t i = 0; if ( (! b_simulation_continuing) && ((f_e - f_i) != ((int) atom_groups_ids.size())) ) { - cvm::error("Error: total forces were requested for scalable groups, " + cvmodule->error("Error: total forces were requested for scalable groups, " "but they are not in the same number from the number of groups.\n" "The most probable cause is combination of energy " "minimization with a biasing method that requires MD (e.g. ABF).\n" @@ -517,7 +517,7 @@ void colvarproxy_namd::calculate() { if (cvm::debug()) { - cvm::log("Updating group positions arrays.\n"); + cvmodule->log("Updating group positions arrays.\n"); } // update group data (only coms available so far) size_t ig; @@ -557,8 +557,8 @@ void colvarproxy_namd::calculate() } // call the collective variable module - if (colvars->calc() != COLVARS_OK) { - cvm::error("Error in the collective variables module.\n", COLVARS_ERROR); + if (cvmodule->calc() != COLVARS_OK) { + cvmodule->error("Error in the collective variables module.\n", COLVARS_ERROR); } if (cvm::debug()) { @@ -687,12 +687,12 @@ void colvarproxy_namd::add_energy(cvm::real energy) void colvarproxy_namd::request_total_force(bool yesno) { if (cvm::debug()) { - cvm::log("colvarproxy_namd::request_total_force()\n"); + cvmodule->log("colvarproxy_namd::request_total_force()\n"); } total_force_requested = yesno; globalmaster->requestTotalForcePublic(total_force_requested); if (cvm::debug()) { - cvm::log("colvarproxy_namd::request_total_force() end\n"); + cvmodule->log("colvarproxy_namd::request_total_force() end\n"); } } @@ -710,7 +710,7 @@ void colvarproxy_namd::log(std::string const &message) void colvarproxy_namd::error(std::string const &message) { log(message); - switch (cvm::get_error()) { + switch (cvmodule->get_error()) { case COLVARS_FILE_ERROR: errno = EIO; break; case COLVARS_NOT_IMPLEMENTED: @@ -734,11 +734,11 @@ int colvarproxy_namd::check_atom_id(int atom_number) int const aid = (atom_number-1); if (cvm::debug()) - cvm::log("Adding atom "+cvm::to_str(atom_number)+ + cvmodule->log("Adding atom "+cvm::to_str(atom_number)+ " for collective variables calculation.\n"); if ( (aid < 0) || (aid >= Node::Object()->molecule->numAtoms) ) { - cvm::error("Error: invalid atom number specified, "+ + cvmodule->error("Error: invalid atom number specified, "+ cvm::to_str(atom_number)+"\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } @@ -796,7 +796,7 @@ int colvarproxy_namd::check_atom_id(cvm::residue_id const &residue, if (aid < 0) { // get_atom_from_name() has returned an error value - cvm::error("Error: could not find atom \""+ + cvmodule->error("Error: could not find atom \""+ atom_name+"\" in residue "+ cvm::to_str(residue)+ ( (segment_id != "MAIN") ? @@ -829,7 +829,7 @@ int colvarproxy_namd::init_atom(cvm::residue_id const &residue, } if (cvm::debug()) - cvm::log("Adding atom \""+ + cvmodule->log("Adding atom \""+ atom_name+"\" in residue "+ cvm::to_str(residue)+ " (index "+cvm::to_str(aid)+ @@ -878,21 +878,9 @@ cvm::rvector colvarproxy_namd::position_distance(cvm::atom_pos const &pos1, } - -enum e_pdb_field { - e_pdb_none, - e_pdb_occ, - e_pdb_beta, - e_pdb_x, - e_pdb_y, - e_pdb_z, - e_pdb_ntot -}; - - -e_pdb_field pdb_field_str2enum(std::string const &pdb_field_str) +colvarproxy_namd::e_pdb_field colvarproxy_namd::pdb_field_str2enum(std::string const &pdb_field_str) { - e_pdb_field pdb_field = e_pdb_none; + colvarproxy_namd::e_pdb_field pdb_field = e_pdb_none; if (colvarparse::to_lower_cppstr(pdb_field_str) == colvarparse::to_lower_cppstr("O")) { @@ -920,7 +908,7 @@ e_pdb_field pdb_field_str2enum(std::string const &pdb_field_str) } if (pdb_field == e_pdb_none) { - cvm::error("Error: unsupported PDB field, \""+ + cvmodule->error("Error: unsupported PDB field, \""+ pdb_field_str+"\".\n", COLVARS_INPUT_ERROR); } @@ -935,7 +923,7 @@ int colvarproxy_namd::load_coords_pdb(char const *pdb_filename, double const pdb_field_value) { if (pdb_field_str.size() == 0 && indices.size() == 0) { - cvm::error("Bug alert: either PDB field should be defined or list of " + cvmodule->error("Bug alert: either PDB field should be defined or list of " "atom IDs should be available when loading atom coordinates!\n", COLVARS_BUG_ERROR); } @@ -1002,7 +990,7 @@ int colvarproxy_namd::load_coords_pdb(char const *pdb_filename, if (!pos_allocated) { pos.push_back(cvm::atom_pos(0.0, 0.0, 0.0)); } else if (ipos >= pos.size()) { - cvm::error("Error: the PDB file \""+ + cvmodule->error("Error: the PDB file \""+ std::string(pdb_filename)+ "\" contains coordinates for " "more atoms than needed.\n", COLVARS_BUG_ERROR); @@ -1018,7 +1006,7 @@ int colvarproxy_namd::load_coords_pdb(char const *pdb_filename, if (ipos < pos.size() || (!use_pdb_field && current_index != indices.end())) { size_t n_requested = use_pdb_field ? pos.size() : indices.size(); - cvm::error("Error: number of matching records in the PDB file \""+ + cvmodule->error("Error: number of matching records in the PDB file \""+ std::string(pdb_filename)+"\" ("+cvm::to_str(ipos)+ ") does not match the number of requested coordinates ("+ cvm::to_str(n_requested)+").\n", COLVARS_INPUT_ERROR); @@ -1045,7 +1033,7 @@ int colvarproxy_namd::load_atoms_pdb(char const *pdb_filename, double const pdb_field_value) { if (pdb_field_str.size() == 0) - cvm::error("Error: must define which PDB field to use " + cvmodule->error("Error: must define which PDB field to use " "in order to define atoms from a PDB file.\n", COLVARS_INPUT_ERROR); PDB *pdb = new PDB(pdb_filename); @@ -1092,7 +1080,7 @@ int colvarproxy_namd::load_atoms_pdb(char const *pdb_filename, } delete pdb; - return (cvm::get_error() ? COLVARS_ERROR : COLVARS_OK); + return (cvmodule->get_error() ? COLVARS_ERROR : COLVARS_OK); } @@ -1100,11 +1088,11 @@ std::ostream & colvarproxy_namd::output_stream(std::string const &output_name, std::string const description) { if (cvm::debug()) { - cvm::log("Using colvarproxy_namd::output_stream()\n"); + cvmodule->log("Using colvarproxy_namd::output_stream()\n"); } if (!io_available()) { - cvm::error("Error: trying to access an output file/channel " + cvmodule->error("Error: trying to access an output file/channel " "from the wrong thread.\n", COLVARS_BUG_ERROR); return *output_stream_error_; } @@ -1117,7 +1105,7 @@ std::ostream & colvarproxy_namd::output_stream(std::string const &output_name, output_streams_[output_name] = new ofstream_namd(output_name.c_str(), std::ios::binary); if (! output_streams_[output_name]->good()) { - cvm::error("Error: cannot write to "+description+" \""+output_name+"\".\n", + cvmodule->error("Error: cannot write to "+description+" \""+output_name+"\".\n", COLVARS_FILE_ERROR); } @@ -1136,7 +1124,7 @@ int colvarproxy_namd::flush_output_stream(std::string const &output_name) return COLVARS_OK; } - return cvm::error("Error: trying to flush an output file/channel " + return cvmodule->error("Error: trying to flush an output file/channel " "that wasn't open.\n", COLVARS_BUG_ERROR); } @@ -1160,7 +1148,7 @@ int colvarproxy_namd::flush_output_streams() int colvarproxy_namd::close_output_stream(std::string const &output_name) { if (!io_available()) { - return cvm::error("Error: trying to access an output file/channel " + return cvmodule->error("Error: trying to access an output file/channel " "from the wrong thread.\n", COLVARS_BUG_ERROR); } @@ -1205,10 +1193,10 @@ int colvarproxy_namd::backup_file(char const *filename) int colvarproxy_namd::init_atom_group(std::vector const &atoms_ids) { if (cvm::debug()) - cvm::log("Requesting from NAMD a group of size "+cvm::to_str(atoms_ids.size())+ + cvmodule->log("Requesting from NAMD a group of size "+cvm::to_str(atoms_ids.size())+ " for collective variables calculation.\n"); - colvars->cite_feature("Scalable center-of-mass computation (NAMD)"); + cvmodule->cite_feature("Scalable center-of-mass computation (NAMD)"); // Note: modifyRequestedGroups is supposed to be in sync with the colvarproxy arrays, // and to stay that way during a simulation @@ -1234,7 +1222,7 @@ int colvarproxy_namd::init_atom_group(std::vector const &atoms_ids) if (b_match) { if (cvm::debug()) - cvm::log("Group was already added.\n"); + cvmodule->log("Group was already added.\n"); // this group already exists atom_groups_refcount[ig] += 1; return ig; @@ -1252,10 +1240,10 @@ int colvarproxy_namd::init_atom_group(std::vector const &atoms_ids) for (size_t ia = 0; ia < atoms_ids.size(); ia++) { int const aid = atoms_ids[ia]; if (cvm::debug()) - cvm::log("Adding atom "+cvm::to_str(aid+1)+ + cvmodule->log("Adding atom "+cvm::to_str(aid+1)+ " for collective variables calculation.\n"); if ( (aid < 0) || (aid >= n_all_atoms) ) { - cvm::error("Error: invalid atom number specified, "+ + cvmodule->error("Error: invalid atom number specified, "+ cvm::to_str(aid+1)+"\n", COLVARS_INPUT_ERROR); return -1; } @@ -1265,8 +1253,8 @@ int colvarproxy_namd::init_atom_group(std::vector const &atoms_ids) update_group_properties(index); if (cvm::debug()) { - cvm::log("Group has index "+cvm::to_str(index)+"\n"); - cvm::log("modifyRequestedGroups length = "+cvm::to_str(globalmaster->modifyRequestedGroupsPublic().size())+ + cvmodule->log("Group has index "+cvm::to_str(index)+"\n"); + cvmodule->log("modifyRequestedGroups length = "+cvm::to_str(globalmaster->modifyRequestedGroupsPublic().size())+ ", modifyGroupForces length = "+cvm::to_str(globalmaster->modifyGroupForcesPublic().size())+"\n"); } @@ -1285,7 +1273,7 @@ int colvarproxy_namd::update_group_properties(int index) { AtomIDList const &namd_group = globalmaster->modifyRequestedGroupsPublic()[index]; if (cvm::debug()) { - cvm::log("Re-calculating total mass and charge for scalable group no. "+cvm::to_str(index+1)+" ("+ + cvmodule->log("Re-calculating total mass and charge for scalable group no. "+cvm::to_str(index+1)+" ("+ cvm::to_str(namd_group.size())+" atoms).\n"); } @@ -1299,7 +1287,7 @@ int colvarproxy_namd::update_group_properties(int index) atom_groups_charges[index] = total_charge; if (cvm::debug()) { - cvm::log("total mass = "+cvm::to_str(total_mass)+ + cvmodule->log("total mass = "+cvm::to_str(total_mass)+ ", total charge = "+cvm::to_str(total_charge)+"\n"); } @@ -1311,7 +1299,7 @@ int colvarproxy_namd::update_group_properties(int index) int colvarproxy_namd::set_unit_system(std::string const &units_in, bool /*check_only*/) { if (units_in != "real") { - cvm::error("Error: Specified unit system \"" + units_in + "\" is unsupported in NAMD. Supported units are \"real\" (A, kcal/mol).\n"); + cvmodule->error("Error: Specified unit system \"" + units_in + "\" is unsupported in NAMD. Supported units are \"real\" (A, kcal/mol).\n"); return COLVARS_ERROR; } return COLVARS_OK; @@ -1351,7 +1339,7 @@ int colvarproxy_namd::init_volmap_by_id(int volmap_id) int colvarproxy_namd::init_volmap_by_name(char const *volmap_name) { if (volmap_name == NULL) { - return cvm::error("Error: no grid object name provided.", COLVARS_INPUT_ERROR); + return cvmodule->error("Error: no grid object name provided.", COLVARS_INPUT_ERROR); } int error_code = COLVARS_OK; @@ -1368,7 +1356,7 @@ int colvarproxy_namd::init_volmap_by_name(char const *volmap_name) GridforceGrid const *grid = mol->get_gridfrc_grid(volmap_id); Vector const gfScale = grid->get_scale(); if ((gfScale.x != 0.0) || (gfScale.y != 0.0) || (gfScale.z != 0.0)) { - error_code |= cvm::error("Error: GridForce map \""+ + error_code |= cvmodule->error("Error: GridForce map \""+ std::string(volmap_name)+ "\" has non-zero scale factors.\n", COLVARS_INPUT_ERROR); @@ -1394,10 +1382,10 @@ int colvarproxy_namd::check_volmap_by_id(int volmap_id) { Molecule *mol = Node::Object()->molecule; if ((volmap_id < 0) || (volmap_id >= mol->numGridforceGrids)) { - return cvm::error("Error: invalid numeric ID ("+cvm::to_str(volmap_id)+ + return cvmodule->error("Error: invalid numeric ID ("+cvm::to_str(volmap_id)+ ") for map.\n", COLVARS_INPUT_ERROR); } - colvars->cite_feature("GridForces volumetric map implementation for NAMD"); + cvmodule->cite_feature("GridForces volumetric map implementation for NAMD"); return COLVARS_OK; } @@ -1405,14 +1393,14 @@ int colvarproxy_namd::check_volmap_by_id(int volmap_id) int colvarproxy_namd::check_volmap_by_name(char const *volmap_name) { if (volmap_name == NULL) { - return cvm::error("Error: no grid object name provided.", COLVARS_INPUT_ERROR); + return cvmodule->error("Error: no grid object name provided.", COLVARS_INPUT_ERROR); } int volmap_id = simparams->mgridforcelist.index_for_key(volmap_name); if (volmap_id < 0) { - return cvm::error("Error: invalid map name \""+std::string(volmap_name)+ + return cvmodule->error("Error: invalid map name \""+std::string(volmap_name)+ "\".\n", COLVARS_INPUT_ERROR); } - colvars->cite_feature("GridForces volumetric map implementation for NAMD"); + cvmodule->cite_feature("GridForces volumetric map implementation for NAMD"); return COLVARS_OK; } @@ -1538,33 +1526,33 @@ int colvarproxy_namd::smp_loop(int n_items, std::function const &work const int numChunks = smp_num_threads() > n_items ? n_items : smp_num_threads(); - cvm::increase_depth(); + cvmodule->increase_depth(); CkLoop_Parallelize(numChunks, 0, n_items - 1, cmkWorker, nullptr, CKLOOP_NONE, nullptr); - cvm::decrease_depth(); + cvmodule->decrease_depth(); // CkLoop does not support bitwise-OR reduction, so we just return the global error flag - return cvm::get_error(); + return cvmodule->get_error(); } void calc_cv_biases_smp(int first, int last, void *result, int paramNum, void *param) { colvarproxy_namd *proxy = (colvarproxy_namd *) param; - colvarmodule *cv = proxy->colvars; + colvarmodule *cvmodule = proxy->cvmodule; #if CMK_TRACE_ENABLED double before = CmiWallTimer(); #endif - cvm::increase_depth(); + cvmodule->increase_depth(); for (int i = first; i <= last; i++) { - colvarbias *b = (*(cv->biases_active()))[i]; + colvarbias *b = (*(cvmodule->biases_active()))[i]; if (cvm::debug()) { - cvm::log("["+cvm::to_str(proxy->smp_thread_id())+"/"+cvm::to_str(proxy->smp_num_threads())+ + cvmodule->log("["+cvm::to_str(proxy->smp_thread_id())+"/"+cvm::to_str(proxy->smp_num_threads())+ "]: calc_cv_biases_smp(), first = "+cvm::to_str(first)+ ", last = "+cvm::to_str(last)+", bias = "+ b->name+"\n"); } b->update(); } - cvm::decrease_depth(); + cvmodule->decrease_depth(); #if CMK_TRACE_ENABLED traceUserBracketEvent(GLOBAL_MASTER_CKLOOP_CALC_BIASES,before,CmiWallTimer()); #endif @@ -1573,28 +1561,27 @@ void calc_cv_biases_smp(int first, int last, void *result, int paramNum, void *p int colvarproxy_namd::smp_biases_loop() { - colvarmodule *cv = this->colvars; - const int numChunks = smp_num_threads() > cv->variables_active_smp()->size() ? - cv->variables_active_smp()->size() : + const int numChunks = smp_num_threads() > cvmodule->variables_active_smp()->size() ? + cvmodule->variables_active_smp()->size() : smp_num_threads(); CkLoop_Parallelize(calc_cv_biases_smp, 1, this, - numChunks, 0, cv->biases_active()->size()-1); - return cvm::get_error(); + numChunks, 0, cvmodule->biases_active()->size()-1); + return cvmodule->get_error(); } void calc_cv_scripted_forces(int paramNum, void *param) { colvarproxy_namd *proxy = (colvarproxy_namd *) param; - colvarmodule *cv = proxy->colvars; + colvarmodule *cvmodule = proxy->cvmodule; #if CMK_TRACE_ENABLED double before = CmiWallTimer(); #endif if (cvm::debug()) { - cvm::log("["+cvm::to_str(proxy->smp_thread_id())+"/"+cvm::to_str(proxy->smp_num_threads())+ + cvmodule->log("["+cvm::to_str(proxy->smp_thread_id())+"/"+cvm::to_str(proxy->smp_num_threads())+ "]: calc_cv_scripted_forces()\n"); } - cv->calc_scripted_forces(); + cvmodule->calc_scripted_forces(); #if CMK_TRACE_ENABLED traceUserBracketEvent(GLOBAL_MASTER_CKLOOP_CALC_SCRIPTED_BIASES,before,CmiWallTimer()); #endif @@ -1603,12 +1590,11 @@ void calc_cv_scripted_forces(int paramNum, void *param) int colvarproxy_namd::smp_biases_script_loop() { - colvarmodule *cv = this->colvars; CkLoop_Parallelize(calc_cv_biases_smp, 1, this, - cv->biases_active()->size(), 0, cv->biases_active()->size()-1, + cvmodule->biases_active()->size(), 0, cvmodule->biases_active()->size()-1, 1, NULL, CKLOOP_NONE, calc_cv_scripted_forces, 1, this); - return cvm::get_error(); + return cvmodule->get_error(); } #endif // #if CMK_SMP && USE_CKLOOP @@ -1665,15 +1651,15 @@ int colvarproxy_namd::replica_comm_send(char* msg_data, int msg_len, int colvarproxy_namd::request_alch_energy_freq(int const freq) { // This test is only valid for NAMD3 if (freq % simparams->computeEnergies) { - cvm::error("computeEnergies must be a divisor of lambda-dynamics period (" + cvm::to_str(freq) + ").\n"); + cvmodule->error("computeEnergies must be a divisor of lambda-dynamics period (" + cvm::to_str(freq) + ").\n"); return COLVARS_INPUT_ERROR; } if (!simparams->alchOn) { - cvm::error("alchOn must be enabled for lambda-dynamics.\n"); + cvmodule->error("alchOn must be enabled for lambda-dynamics.\n"); return COLVARS_INPUT_ERROR; } if (!simparams->alchThermIntOn) { - cvm::error("alchType must be set to TI for lambda-dynamics.\n"); + cvmodule->error("alchType must be set to TI for lambda-dynamics.\n"); return COLVARS_INPUT_ERROR; } return COLVARS_OK; @@ -1690,7 +1676,7 @@ int colvarproxy_namd::get_alch_lambda(cvm::real* lambda) { /// Set value of alchemical lambda parameter in back-end int colvarproxy_namd::send_alch_lambda(void) { if (simparams->alchLambdaFreq > 0) { - cvm::error("Cannot set lambda from Colvars because alchLambdaFreq is enabled. " + cvmodule->error("Cannot set lambda from Colvars because alchLambdaFreq is enabled. " "Either remove biasing forces and extended Lagrangian dynamics on the alchemical coordinate, " "or disable alchLambdaFreq.\n"); return COLVARS_INPUT_ERROR; @@ -1704,7 +1690,7 @@ int colvarproxy_namd::send_alch_lambda(void) { /// Get energy derivative with respect to lambda int colvarproxy_namd::get_dE_dlambda(cvm::real* dE_dlambda) { // Force data at step zero is garbage in NAMD3, zero in NAMD2 - if (cvm::step_relative() > 0) { + if (cvmodule->step_relative() > 0) { *dE_dlambda = controller->getTIderivative(); } else { *dE_dlambda = 0.0; diff --git a/namd/src/colvarproxy_namd.h b/namd/src/colvarproxy_namd.h index ef86f615d..77c775aa5 100644 --- a/namd/src/colvarproxy_namd.h +++ b/namd/src/colvarproxy_namd.h @@ -201,6 +201,18 @@ class colvarproxy_namd : public colvarproxy { cvm::rvector position_distance(cvm::atom_pos const &pos1, cvm::atom_pos const &pos2) const; + enum e_pdb_field { + e_pdb_none, + e_pdb_occ, + e_pdb_beta, + e_pdb_x, + e_pdb_y, + e_pdb_z, + e_pdb_ntot + }; + + e_pdb_field pdb_field_str2enum(std::string const &pdb_field_str); + int load_atoms_pdb(char const *filename, cvm::atom_group &atoms, std::string const &pdb_field, diff --git a/src/colvar.cpp b/src/colvar.cpp index cae83a2d4..4a591b701 100644 --- a/src/colvar.cpp +++ b/src/colvar.cpp @@ -29,9 +29,11 @@ std::map colvar::global_cvc_desc_map = std::map(); -colvar::colvar() + +colvar::colvar(colvarmodule *cvmodule_in) + : colvardeps(cvmodule_in) { - time_step_factor = cvm::proxy->time_step_factor(); + time_step_factor = cvmodule->proxy->time_step_factor(); prev_timestep = -1L; after_restart = false; @@ -62,19 +64,17 @@ bool colvar::compare_cvc(const colvar::cvc* const i, const colvar::cvc* const j) int colvar::init(std::string const &conf) { - cvm::log("Initializing a new collective variable.\n"); + cvmodule->log("Initializing a new collective variable.\n"); colvarparse::set_string(conf); int error_code = COLVARS_OK; - colvarmodule *cv = cvm::main(); - get_keyval(conf, "name", this->name, - (std::string("colvar")+cvm::to_str(cv->variables()->size()))); + (std::string("colvar")+cvm::to_str(cvmodule->variables()->size()))); - if ((cvm::colvar_by_name(this->name) != NULL) && - (cvm::colvar_by_name(this->name) != this)) { - cvm::error("Error: this colvar cannot have the same name, \""+this->name+ + if ((cvmodule->colvar_by_name(this->name) != NULL) && + (cvmodule->colvar_by_name(this->name) != this)) { + cvmodule->error("Error: this colvar cannot have the same name, \""+this->name+ "\", as another colvar.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; @@ -87,7 +87,7 @@ int colvar::init(std::string const &conf) error_code |= init_components(conf); if (error_code != COLVARS_OK) { - return cvm::get_error(); + return cvmodule->get_error(); } size_t i; @@ -95,11 +95,11 @@ int colvar::init(std::string const &conf) #ifdef LEPTON error_code |= init_custom_function(conf); if (error_code != COLVARS_OK) { - return cvm::get_error(); + return cvmodule->get_error(); } #else if (key_lookup(conf, "customFunction")) { - return cvm::error( + return cvmodule->error( "Error: customFunction keyword is used, but the Lepton library is not available.\n", COLVARS_NOT_IMPLEMENTED); } @@ -110,8 +110,8 @@ int colvar::init(std::string const &conf) "", colvarparse::parse_silent)) { enable(f_cv_scripted); - cvm::log("This colvar uses scripted function \"" + scripted_function + "\".\n"); - cvm::main()->cite_feature("Scripted functions (Tcl)"); + cvmodule->log("This colvar uses scripted function \"" + scripted_function + "\".\n"); + cvmodule->cite_feature("Scripted functions (Tcl)"); std::string type_str; get_keyval(conf, "scriptedFunctionType", type_str, "scalar"); @@ -125,17 +125,17 @@ int colvar::init(std::string const &conf) } } if (x.type() == colvarvalue::type_notset) { - cvm::error("Could not parse scripted colvar type.", COLVARS_INPUT_ERROR); + cvmodule->error("Could not parse scripted colvar type.", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } - cvm::log(std::string("Expecting colvar value of type ") + cvmodule->log(std::string("Expecting colvar value of type ") + colvarvalue::type_desc(x.type())); if (x.type() == colvarvalue::type_vector) { int size; if (!get_keyval(conf, "scriptedFunctionVectorSize", size)) { - cvm::error("Error: no size specified for vector scripted function.", + cvmodule->error("Error: no size specified for vector scripted function.", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } @@ -156,9 +156,9 @@ int colvar::init(std::string const &conf) }); if(cvcs.size() > 1) { - cvm::log("Sorted list of components for this scripted colvar:\n"); + cvmodule->log("Sorted list of components for this scripted colvar:\n"); for (i = 0; i < cvcs.size(); i++) { - cvm::log(cvm::to_str(i+1) + " " + cvcs[i]->name); + cvmodule->log(cvm::to_str(i+1) + " " + cvcs[i]->name); } } @@ -172,7 +172,7 @@ int colvar::init(std::string const &conf) if (!(is_enabled(f_cv_scripted) || is_enabled(f_cv_custom_function))) { colvarvalue const &cvc_value = (cvcs[0])->value(); if (cvm::debug()) - cvm::log ("This collective variable is a "+ + cvmodule->log ("This collective variable is a "+ colvarvalue::type_desc(cvc_value.type())+ ((cvc_value.size() > 1) ? " with "+ cvm::to_str(cvc_value.size())+" individual components.\n" : @@ -195,13 +195,13 @@ int colvar::init(std::string const &conf) if ((cvcs[i])->sup_np != 1) { if (cvm::debug() && lin) - cvm::log("Warning: You are using a non-linear polynomial " + cvmodule->log("Warning: You are using a non-linear polynomial " "combination to define this collective variable, " "some biasing methods may be unavailable.\n"); lin = false; if ((cvcs[i])->sup_np < 0) { - cvm::log("Warning: you chose a negative exponent in the combination; " + cvmodule->log("Warning: you chose a negative exponent in the combination; " "if you apply forces, the simulation may become unstable " "when the component \""+ (cvcs[i])->function_type()+"\" approaches zero.\n"); @@ -246,7 +246,7 @@ int colvar::init(std::string const &conf) if (!cvcs[i]->is_enabled(f_cvc_periodic) || cvcs[i]->period != period) { b_periodic = false; period = 0.0; - cvm::log("Warning: although one component is periodic, this colvar will " + cvmodule->log("Warning: although one component is periodic, this colvar will " "not be treated as periodic, either because the exponent is not " "1, or because components of different periodicity are defined. " "Make sure that you know what you are doing!"); @@ -270,7 +270,7 @@ int colvar::init(std::string const &conf) // components may have different types only for scripted functions if (!(is_enabled(f_cv_scripted) || is_enabled(f_cv_custom_function)) && (colvarvalue::check_types(cvcs[i]->value(), cvcs[0]->value())) ) { - cvm::error("Error: you are defining this collective variable " + cvmodule->error("Error: you are defining this collective variable " "by using components of different types. " "You must use the same type in order to " "sum them together.\n", COLVARS_INPUT_ERROR); @@ -301,13 +301,13 @@ int colvar::init(std::string const &conf) get_keyval(conf, "timeStepFactor", time_step_factor, time_step_factor); if (time_step_factor < 1) { - error_code |= cvm::error("Error: timeStepFactor must be 1 or greater.\n", COLVARS_INPUT_ERROR); + error_code |= cvmodule->error("Error: timeStepFactor must be 1 or greater.\n", COLVARS_INPUT_ERROR); } - if (time_step_factor % cvm::proxy->time_step_factor() != 0) { + if (time_step_factor % cvmodule->proxy->time_step_factor() != 0) { error_code |= - cvm::error("timeStepFactor for this variable (currently " + cvm::to_str(time_step_factor) + + cvmodule->error("timeStepFactor for this variable (currently " + cvm::to_str(time_step_factor) + ") must be a multiple of the global Colvars timestep multiplier (" + - cvm::to_str(cvm::proxy->time_step_factor()) + ").\n", + cvm::to_str(cvmodule->proxy->time_step_factor()) + ").\n", COLVARS_INPUT_ERROR); } if (time_step_factor > 1) { @@ -326,7 +326,7 @@ int colvar::init(std::string const &conf) } // If using scripted biases, any colvar may receive bias forces - if (cvm::scripted_forces()) { + if (cvmodule->scripted_forces()) { enable(f_cv_apply_force); } @@ -350,7 +350,7 @@ int colvar::init(std::string const &conf) error_code |= parse_analysis(conf); if (cvm::debug()) - cvm::log("Done initializing collective variable \""+this->name+"\".\n"); + cvmodule->log("Done initializing collective variable \""+this->name+"\".\n"); return error_code; } @@ -369,21 +369,21 @@ int colvar::init_custom_function(std::string const &conf) return COLVARS_OK; } - cvm::main()->cite_feature("Custom functions (Lepton)"); + cvmodule->cite_feature("Custom functions (Lepton)"); enable(f_cv_custom_function); - cvm::log("This colvar uses a custom function.\n"); + cvmodule->log("This colvar uses a custom function.\n"); do { expr = expr_in; if (cvm::debug()) - cvm::log("Parsing expression \"" + expr + "\".\n"); + cvmodule->log("Parsing expression \"" + expr + "\".\n"); try { pexpr = Lepton::Parser::parse(expr); pexprs.push_back(pexpr); } catch (...) { - cvm::error("Error parsing expression \"" + expr + "\".\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error parsing expression \"" + expr + "\".\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } @@ -403,14 +403,14 @@ int colvar::init_custom_function(std::string const &conf) // To keep the same workflow, we use a pointer to a double here // that will receive CVC values - even though none was allocated by Lepton ref = &dev_null; - cvm::log("Warning: Variable " + vn + " is absent from expression \"" + expr + "\".\n"); + cvmodule->log("Warning: Variable " + vn + " is absent from expression \"" + expr + "\".\n"); } value_eval_var_refs.push_back(ref); } } } catch (...) { - cvm::error("Error compiling expression \"" + expr + "\".\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error compiling expression \"" + expr + "\".\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } } while (key_lookup(conf, "customFunction", &expr_in, &pos)); @@ -439,7 +439,7 @@ int colvar::init_custom_function(std::string const &conf) // To keep the same workflow, we use a pointer to a double here // that will receive CVC values - even though none was allocated by Lepton if (cvm::debug()) { - cvm::log("Warning: Variable " + vvn + " is absent from derivative of \"" + expr + "\" wrt " + vn + ".\n"); + cvmodule->log("Warning: Variable " + vvn + " is absent from derivative of \"" + expr + "\" wrt " + vn + ".\n"); } ref = &dev_null; } @@ -452,7 +452,7 @@ int colvar::init_custom_function(std::string const &conf) if (value_evaluators.size() == 0) { - cvm::error("Error: no custom function defined.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: no custom function defined.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } @@ -468,7 +468,7 @@ int colvar::init_custom_function(std::string const &conf) } } if (x.type() == colvarvalue::type_notset) { - cvm::error("Could not parse custom colvar type.", COLVARS_INPUT_ERROR); + cvmodule->error("Could not parse custom colvar type.", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } @@ -486,13 +486,13 @@ int colvar::init_custom_function(std::string const &conf) } x_reported.type(x); - cvm::log(std::string("Expecting colvar value of type ") + cvmodule->log(std::string("Expecting colvar value of type ") + colvarvalue::type_desc(x.type()) + (x.type()==colvarvalue::type_vector ? " of size " + cvm::to_str(x.size()) : "") + ".\n"); if (x.size() != value_evaluators.size()) { - cvm::error("Error: based on custom function type, expected " + cvmodule->error("Error: based on custom function type, expected " + cvm::to_str(x.size()) + " scalar expressions, but " + cvm::to_str(value_evaluators.size()) + " were found.\n"); return COLVARS_INPUT_ERROR; @@ -510,7 +510,7 @@ int colvar::init_custom_function(std::string const &conf) size_t pos = 0; if (key_lookup(conf, "customFunction", &expr, &pos)) { std::string msg("Error: customFunction requires the Lepton library."); - return cvm::error(msg, COLVARS_NOT_IMPLEMENTED); + return cvmodule->error(msg, COLVARS_NOT_IMPLEMENTED); } return COLVARS_OK; @@ -537,7 +537,7 @@ int colvar::init_grid_parameters(std::string const &conf) get_keyval(conf, "width", width, default_width); if (width <= 0.0) { - cvm::error("Error: \"width\" must be positive.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: \"width\" must be positive.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } @@ -606,7 +606,6 @@ int colvar::init_grid_parameters(std::string const &conf) int colvar::parse_legacy_wall_params(std::string const &conf) { int error_code = COLVARS_OK; - colvarmodule *cv = cvm::main(); if (is_enabled(f_cv_scalar)) { @@ -617,10 +616,10 @@ int colvar::parse_legacy_wall_params(std::string const &conf) if (get_keyval(conf, "lowerWallConstant", lower_wall_k, 0.0, parse_silent)) { - cvm::log("Reading legacy options lowerWall and lowerWallConstant: " + cvmodule->log("Reading legacy options lowerWall and lowerWallConstant: " "consider using a harmonicWalls restraint (caution: force constant would then be scaled by width^2).\n"); if (!get_keyval(conf, "lowerWall", lower_wall)) { - error_code |= cvm::error("Error: the value of lowerWall must be set " + error_code |= cvmodule->error("Error: the value of lowerWall must be set " "explicitly.\n", COLVARS_INPUT_ERROR); } lw_conf = std::string("\n\ @@ -630,10 +629,10 @@ int colvar::parse_legacy_wall_params(std::string const &conf) if (get_keyval(conf, "upperWallConstant", upper_wall_k, 0.0, parse_silent)) { - cvm::log("Reading legacy options upperWall and upperWallConstant: " + cvmodule->log("Reading legacy options upperWall and upperWallConstant: " "consider using a harmonicWalls restraint (caution: force constant would then be scaled by width^2).\n"); if (!get_keyval(conf, "upperWall", upper_wall)) { - error_code |= cvm::error("Error: the value of upperWall must be set " + error_code |= cvmodule->error("Error: the value of upperWall must be set " "explicitly.\n", COLVARS_INPUT_ERROR); } uw_conf = std::string("\n\ @@ -643,7 +642,7 @@ int colvar::parse_legacy_wall_params(std::string const &conf) if (lw_conf.size() && uw_conf.size()) { if (lower_wall >= upper_wall) { - error_code |= cvm::error("Error: the upper wall, "+ + error_code |= cvmodule->error("Error: the upper wall, "+ cvm::to_str(upper_wall)+ ", is not higher than the lower wall, "+ cvm::to_str(lower_wall)+".\n", @@ -652,14 +651,14 @@ int colvar::parse_legacy_wall_params(std::string const &conf) } if (lw_conf.size() || uw_conf.size()) { - cvm::log("Generating a new harmonicWalls bias for compatibility purposes.\n"); + cvmodule->log("Generating a new harmonicWalls bias for compatibility purposes.\n"); std::string const walls_conf("\n\ harmonicWalls {\n\ name "+this->name+"w\n\ colvars "+this->name+"\n"+lw_conf+uw_conf+"\ timeStepFactor "+cvm::to_str(time_step_factor)+"\n"+ "}\n"); - error_code |= cv->append_new_config(walls_conf); + error_code |= cvmodule->append_new_config(walls_conf); } } @@ -673,7 +672,7 @@ int colvar::check_grid_parameters() if (is_enabled(f_cv_lower_boundary) && is_enabled(f_cv_upper_boundary)) { if (lower_boundary >= upper_boundary) { - error_code |= cvm::error("Error: the upper boundary, "+ + error_code |= cvmodule->error("Error: the upper boundary, "+ cvm::to_str(upper_boundary)+ ", is not higher than the lower boundary, "+ cvm::to_str(lower_boundary)+".\n", @@ -682,14 +681,14 @@ int colvar::check_grid_parameters() } if (expand_boundaries && periodic_boundaries()) { - error_code |= cvm::error("Error: trying to expand boundaries that already " + error_code |= cvmodule->error("Error: trying to expand boundaries that already " "cover a whole period of a periodic colvar.\n", COLVARS_INPUT_ERROR); } if (expand_boundaries && is_enabled(f_cv_hard_lower_boundary) && is_enabled(f_cv_hard_upper_boundary)) { - error_code |= cvm::error("Error: inconsistent configuration " + error_code |= cvmodule->error("Error: inconsistent configuration " "(trying to expand boundaries, but both " "hardLowerBoundary and hardUpperBoundary " "are enabled).\n", COLVARS_INPUT_ERROR); @@ -701,13 +700,13 @@ int colvar::check_grid_parameters() int colvar::init_extended_Lagrangian(std::string const &conf) { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; get_keyval_feature(this, conf, "extendedLagrangian", f_cv_extended_Lagrangian, false); if (is_enabled(f_cv_extended_Lagrangian)) { cvm::real temp, tolerance, extended_period; - cvm::log("Enabling the extended Lagrangian term for colvar \""+ + cvmodule->log("Enabling the extended Lagrangian term for colvar \""+ this->name+"\".\n"); // Mark x_ext as uninitialized so we can initialize it to the colvar value when updating @@ -727,28 +726,28 @@ int colvar::init_extended_Lagrangian(std::string const &conf) // Standard case of coupling to a geometric colvar if (temp <= 0.0) { // Then a finite temperature is required if (temp_provided) - cvm::error("Error: \"extendedTemp\" must be positive.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: \"extendedTemp\" must be positive.\n", COLVARS_INPUT_ERROR); else - cvm::error("Error: a positive temperature must be provided, either " + cvmodule->error("Error: a positive temperature must be provided, either " "by enabling a thermostat, or through \"extendedTemp\".\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } get_keyval(conf, "extendedFluctuation", tolerance); if (tolerance <= 0.0) { - cvm::error("Error: \"extendedFluctuation\" must be positive.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: \"extendedFluctuation\" must be positive.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } ext_force_k = proxy->boltzmann() * temp / (tolerance * tolerance); - cvm::log("Computed extended system force constant: " + cvm::to_str(ext_force_k) + " [E]/U^2\n"); + cvmodule->log("Computed extended system force constant: " + cvm::to_str(ext_force_k) + " [E]/U^2\n"); get_keyval(conf, "extendedTimeConstant", extended_period, 200.0); if (extended_period <= 0.0) { - cvm::error("Error: \"extendedTimeConstant\" must be positive.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: \"extendedTimeConstant\" must be positive.\n", COLVARS_INPUT_ERROR); } ext_mass = (proxy->boltzmann() * temp * extended_period * extended_period) / (4.0 * PI * PI * tolerance * tolerance); - cvm::log("Computed fictitious mass: " + cvm::to_str(ext_mass) + " [E]/(U/fs)^2 (U: colvar unit)\n"); + cvmodule->log("Computed fictitious mass: " + cvm::to_str(ext_mass) + " [E]/(U/fs)^2 (U: colvar unit)\n"); } { bool b_output_energy; @@ -760,16 +759,16 @@ int colvar::init_extended_Lagrangian(std::string const &conf) get_keyval(conf, "extendedLangevinDamping", ext_gamma, 1.0); if (ext_gamma < 0.0) { - cvm::error("Error: \"extendedLangevinDamping\" may not be negative.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: \"extendedLangevinDamping\" may not be negative.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } if (ext_gamma != 0.0) { enable(f_cv_Langevin); - cvm::main()->cite_feature("BAOA integrator"); - ext_gamma *= 1.0e-3; // correct as long as input is required in ps-1 and cvm::dt() is in fs + cvmodule->cite_feature("BAOA integrator"); + ext_gamma *= 1.0e-3; // correct as long as input is required in ps-1 and cvmodule->dt() is in fs // Adjust Langevin sigma for slow time step if time_step_factor != 1 // Eq. (6a) in https://doi.org/10.1021/acs.jctc.2c00585 - ext_sigma = cvm::sqrt((1.0 - cvm::exp(-2.0 * ext_gamma * cvm::dt() * cvm::real(time_step_factor))) + ext_sigma = cvm::sqrt((1.0 - cvm::exp(-2.0 * ext_gamma * cvmodule->dt() * cvm::real(time_step_factor))) * ext_mass * proxy->boltzmann() * temp); } else { ext_sigma = 0.0; @@ -804,7 +803,7 @@ int colvar::init_output_flags(std::string const &conf) { bool temp; if (get_keyval(conf, "outputSystemForce", temp, false, colvarparse::parse_silent)) { - cvm::error("Option outputSystemForce is deprecated: only outputTotalForce is supported instead.\n" + cvmodule->error("Option outputSystemForce is deprecated: only outputTotalForce is supported instead.\n" "The two are NOT identical: see https://colvars.github.io/totalforce.html.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } @@ -840,14 +839,14 @@ int colvar::init_components_type(const std::string& conf, const char* def_config &def_conf, &pos) ) { - cvm::increase_depth(); - cvm::log("Initializing " + cvmodule->increase_depth(); + cvmodule->log("Initializing " "a new \""+std::string(def_config_key)+"\" component"+ (cvm::debug() ? ", with configuration:\n"+def_conf : ".\n")); cvc *cvcp = global_cvc_map[def_config_key](); if (!cvcp) { - return cvm::error("Error: in creating object of type \"" + std::string(def_config_key) + + return cvmodule->error("Error: in creating object of type \"" + std::string(def_config_key) + "\".\n", COLVARS_MEMORY_ERROR); } @@ -859,10 +858,10 @@ int colvar::init_components_type(const std::string& conf, const char* def_config // early-returns due to errors would raise false positives error_code_this |= cvcp->check_keywords(def_conf, def_config_key); } - cvm::decrease_depth(); + cvmodule->decrease_depth(); if (error_code_this != COLVARS_OK) { error_code |= - cvm::error("Error: in setting up component \"" + std::string(def_config_key) + "\".\n", + cvmodule->error("Error: in setting up component \"" + std::string(def_config_key) + "\".\n", COLVARS_INPUT_ERROR); } @@ -876,13 +875,13 @@ int colvar::init_components_type(const std::string& conf, const char* def_config cvcs.back()->setup(); if (cvm::debug()) { - cvm::log("Done initializing a \"" + std::string(def_config_key) + "\" component" + + cvmodule->log("Done initializing a \"" + std::string(def_config_key) + "\" component" + (cvm::debug() ? ", named \"" + cvcs.back()->name + "\"" : "") + ".\n"); } def_conf = ""; if (cvm::debug()) { - cvm::log("Parsed " + cvm::to_str(cvcs.size()) + " components at this time.\n"); + cvmodule->log("Parsed " + cvm::to_str(cvcs.size()) + " components at this time.\n"); } } @@ -892,7 +891,7 @@ int colvar::init_components_type(const std::string& conf, const char* def_config void colvar::define_component_types() { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; add_component_type("distance", "distance"); add_component_type("distance vector", "distanceVec"); @@ -967,8 +966,8 @@ int colvar::init_components(std::string const &conf) error_code |= init_components_type(conf, it->first.c_str()); // TODO: is it better to check the error code here? if (error_code != COLVARS_OK) { - cvm::log("Failed to initialize " + it->first + " with the following configuration:\n"); - cvm::log(conf); + cvmodule->log("Failed to initialize " + it->first + " with the following configuration:\n"); + cvmodule->log(conf); // TODO: should it stop here? break; } @@ -981,14 +980,14 @@ int colvar::init_components(std::string const &conf) msg += " " + it->first + " -- " + it->second + "\n"; } msg += "\nPlease note that some of the above types may still be unavailable, irrespective of this error.\n"; - error_code |= cvm::error(msg, COLVARS_INPUT_ERROR); + error_code |= cvmodule->error(msg, COLVARS_INPUT_ERROR); } // Check for uniqueness of CVC names (esp. if user-provided) for (i = 0; i < cvcs.size(); i++) { for (j = i + 1; j < cvcs.size(); j++) { if (cvcs[i]->name == cvcs[j]->name) { - error_code |= cvm::error("Components " + cvm::to_str(i) + " and " + cvm::to_str(j) + + error_code |= cvmodule->error("Components " + cvm::to_str(i) + " and " + cvm::to_str(j) + " cannot have the same name \"" + cvcs[i]->name + "\".\n", COLVARS_INPUT_ERROR); } @@ -1002,7 +1001,7 @@ int colvar::init_components(std::string const &conf) } // By default all CVCs are active at the start n_active_cvcs = cvcs.size(); - cvm::log("All components initialized.\n"); + cvmodule->log("All components initialized.\n"); } return error_code; @@ -1013,7 +1012,7 @@ void colvar::do_feature_side_effects(int id) { switch (id) { case f_cv_total_force_calc: - cvm::request_total_force(); + cvmodule->request_total_force(); break; case f_cv_collect_atom_ids: // Needed for getting gradients vias collect_gradients @@ -1059,9 +1058,9 @@ void colvar::build_atom_list(void) atomic_gradients.resize(atom_ids.size()); if (atom_ids.size()) { if (cvm::debug()) - cvm::log("Colvar: created atom list with " + cvm::to_str(atom_ids.size()) + " atoms.\n"); + cvmodule->log("Colvar: created atom list with " + cvm::to_str(atom_ids.size()) + " atoms.\n"); } else { - cvm::log("Warning: colvar components communicated no atom IDs.\n"); + cvmodule->log("Warning: colvar components communicated no atom IDs.\n"); } } @@ -1070,7 +1069,7 @@ int colvar::parse_analysis(std::string const &conf) { // if (cvm::debug()) - // cvm::log ("Parsing analysis flags for collective variable \""+ + // cvmodule->log ("Parsing analysis flags for collective variable \""+ // this->name+"\".\n"); runave_length = 0; @@ -1082,8 +1081,8 @@ int colvar::parse_analysis(std::string const &conf) get_keyval(conf, "runAveLength", runave_length, 1000); get_keyval(conf, "runAveStride", runave_stride, 1); - if ((cvm::restart_out_freq % runave_stride) != 0) { - cvm::error("Error: runAveStride must be commensurate with the restart frequency.\n", COLVARS_INPUT_ERROR); + if ((cvmodule->restart_out_freq % runave_stride) != 0) { + cvmodule->error("Error: runAveStride must be commensurate with the restart frequency.\n", COLVARS_INPUT_ERROR); } get_keyval(conf, "runAveOutputFile", runave_outfile, runave_outfile); @@ -1097,9 +1096,9 @@ int colvar::parse_analysis(std::string const &conf) get_keyval(conf, "corrFuncWithColvar", acf_colvar_name, this->name); if (acf_colvar_name == this->name) { - cvm::log("Calculating auto-correlation function.\n"); + cvmodule->log("Calculating auto-correlation function.\n"); } else { - cvm::log("Calculating correlation function with \""+ + cvmodule->log("Calculating correlation function with \""+ this->name+"\".\n"); } @@ -1110,32 +1109,32 @@ int colvar::parse_analysis(std::string const &conf) } else if (acf_type_str == to_lower_cppstr(std::string("velocity"))) { acf_type = acf_vel; enable(f_cv_fdiff_velocity); - colvar *cv2 = cvm::colvar_by_name(acf_colvar_name); + colvar *cv2 = cvmodule->colvar_by_name(acf_colvar_name); if (cv2 == NULL) { - return cvm::error("Error: collective variable \""+acf_colvar_name+ + return cvmodule->error("Error: collective variable \""+acf_colvar_name+ "\" is not defined at this time.\n", COLVARS_INPUT_ERROR); } cv2->enable(f_cv_fdiff_velocity); // Manual dependency to object of same type } else if (acf_type_str == to_lower_cppstr(std::string("coordinate_p2"))) { acf_type = acf_p2coor; } else { - cvm::log("Unknown type of correlation function, \""+ + cvmodule->log("Unknown type of correlation function, \""+ acf_type_str+"\".\n"); - cvm::set_error_bits(COLVARS_INPUT_ERROR); + cvmodule->set_error_bits(COLVARS_INPUT_ERROR); } get_keyval(conf, "corrFuncOffset", acf_offset, 0); get_keyval(conf, "corrFuncLength", acf_length, 1000); get_keyval(conf, "corrFuncStride", acf_stride, 1); - if ((cvm::restart_out_freq % acf_stride) != 0) { - cvm::error("Error: corrFuncStride must be commensurate with the restart frequency.\n", COLVARS_INPUT_ERROR); + if ((cvmodule->restart_out_freq % acf_stride) != 0) { + cvmodule->error("Error: corrFuncStride must be commensurate with the restart frequency.\n", COLVARS_INPUT_ERROR); } get_keyval(conf, "corrFuncNormalize", acf_normalize, true); get_keyval(conf, "corrFuncOutputFile", acf_outfile, acf_outfile); } - return (cvm::get_error() ? COLVARS_ERROR : COLVARS_OK); + return (cvmodule->get_error() ? COLVARS_ERROR : COLVARS_OK); } @@ -1274,7 +1273,7 @@ int colvar::init_dependencies() { // check that everything is initialized for (i = 0; i < colvardeps::f_cv_ntot; i++) { if (is_not_set(i)) { - cvm::error("Uninitialized feature " + cvm::to_str(i) + " in " + description); + cvmodule->error("Uninitialized feature " + cvm::to_str(i) + " in " + description); } } } @@ -1288,10 +1287,10 @@ int colvar::init_dependencies() { } feature_states[f_cv_fdiff_velocity].available = - cvm::main()->proxy->simulation_running(); + cvmodule->proxy->simulation_running(); // Some back-ends report current total forces for all colvars - if (cvm::main()->proxy->total_forces_same_step()) + if (cvmodule->proxy->total_forces_same_step()) enable(f_cv_total_force_current_step); return COLVARS_OK; @@ -1357,24 +1356,23 @@ colvar::~colvar() while (biases.size() > 0) { size_t const i = biases.size()-1; - cvm::log("Warning: before deleting colvar " + name + cvmodule->log("Warning: before deleting colvar " + name + ", deleting related bias " + biases[i]->name); delete biases[i]; } biases.clear(); // remove reference to this colvar from the module - colvarmodule *cv = cvm::main(); - for (std::vector::iterator cvi = cv->variables()->begin(); - cvi != cv->variables()->end(); + for (std::vector::iterator cvi = cvmodule->variables()->begin(); + cvi != cvmodule->variables()->end(); ++cvi) { if ( *cvi == this) { - cv->variables()->erase(cvi); + cvmodule->variables()->erase(cvi); break; } } - cv->config_changed(); + cvmodule->config_changed(); #ifdef LEPTON for (std::vector::iterator cei = value_evaluators.begin(); @@ -1417,7 +1415,7 @@ int colvar::calc() int colvar::calc_cvcs(int first_cvc, size_t num_cvcs) { if (cvm::debug()) - cvm::log("Calculating colvar \""+this->name+"\", components "+ + cvmodule->log("Calculating colvar \""+this->name+"\", components "+ cvm::to_str(first_cvc)+" through "+cvm::to_str(first_cvc+num_cvcs)+".\n"); int error_code = COLVARS_OK; @@ -1427,7 +1425,7 @@ int colvar::calc_cvcs(int first_cvc, size_t num_cvcs) return error_code; } - if ((cvm::step_relative() > 0) && (!is_enabled(f_cv_total_force_current_step))){ + if ((cvmodule->step_relative() > 0) && (!is_enabled(f_cv_total_force_current_step))){ // Use Jacobian derivative from previous timestep error_code |= calc_cvc_total_force(first_cvc, num_cvcs); } @@ -1441,7 +1439,7 @@ int colvar::calc_cvcs(int first_cvc, size_t num_cvcs) } if (cvm::debug()) - cvm::log("Done calculating colvar \""+this->name+"\".\n"); + cvmodule->log("Done calculating colvar \""+this->name+"\".\n"); return error_code; } @@ -1450,11 +1448,11 @@ int colvar::calc_cvcs(int first_cvc, size_t num_cvcs) int colvar::collect_cvc_data() { if (cvm::debug()) - cvm::log("Calculating colvar \""+this->name+"\"'s properties.\n"); + cvmodule->log("Calculating colvar \""+this->name+"\"'s properties.\n"); int error_code = COLVARS_OK; - if ((cvm::step_relative() > 0) && (!is_enabled(f_cv_total_force_current_step))){ + if ((cvmodule->step_relative() > 0) && (!is_enabled(f_cv_total_force_current_step))){ // Total force depends on Jacobian derivative from previous timestep // collect_cvc_total_forces() uses the previous value of jd error_code |= collect_cvc_total_forces(); @@ -1469,7 +1467,7 @@ int colvar::collect_cvc_data() error_code |= calc_colvar_properties(); if (cvm::debug()) - cvm::log("Done calculating colvar \""+this->name+"\"'s properties.\n"); + cvmodule->log("Done calculating colvar \""+this->name+"\"'s properties.\n"); return error_code; } @@ -1478,7 +1476,7 @@ int colvar::collect_cvc_data() int colvar::check_cvc_range(int first_cvc, size_t /* num_cvcs */) { if ((first_cvc < 0) || (first_cvc >= ((int) cvcs.size()))) { - cvm::error("Error: trying to address a component outside the " + cvmodule->error("Error: trying to address a component outside the " "range defined for colvar \""+name+"\".\n", COLVARS_BUG_ERROR); return COLVARS_BUG_ERROR; } @@ -1494,10 +1492,10 @@ int colvar::calc_cvc_values(int first_cvc, size_t num_cvcs) // calculate the value of the colvar if (cvm::debug()) - cvm::log("Calculating colvar components.\n"); + cvmodule->log("Calculating colvar components.\n"); // First, calculate component values - cvm::increase_depth(); + cvmodule->increase_depth(); for (i = first_cvc, cvc_count = 0; (i < cvcs.size()) && (cvc_count < cvc_max_count); i++) { @@ -1506,12 +1504,12 @@ int colvar::calc_cvc_values(int first_cvc, size_t num_cvcs) (cvcs[i])->read_data(); (cvcs[i])->calc_value(); if (cvm::debug()) - cvm::log("Colvar component no. "+cvm::to_str(i+1)+ + cvmodule->log("Colvar component no. "+cvm::to_str(i+1)+ " within colvar \""+this->name+"\" has value "+ cvm::to_str((cvcs[i])->value(), - cvm::cv_width, cvm::cv_prec)+".\n"); + cvmodule->cv_width, cvmodule->cv_prec)+".\n"); } - cvm::decrease_depth(); + cvmodule->decrease_depth(); return COLVARS_OK; } @@ -1524,13 +1522,13 @@ int colvar::collect_cvc_values() // combine them appropriately, using either a scripted function or a polynomial if (is_enabled(f_cv_scripted)) { // cvcs combined by user script - int res = cvm::proxy->run_colvar_callback(scripted_function, sorted_cvc_values, x); + int res = cvmodule->proxy->run_colvar_callback(scripted_function, sorted_cvc_values, x); if (res == COLVARS_NOT_IMPLEMENTED) { - cvm::error("Scripted colvars are not implemented."); + cvmodule->error("Scripted colvars are not implemented."); return COLVARS_NOT_IMPLEMENTED; } if (res != COLVARS_OK) { - cvm::error("Error running scripted colvar"); + cvmodule->error("Error running scripted colvar"); return COLVARS_OK; } @@ -1567,15 +1565,15 @@ int colvar::collect_cvc_values() } if (cvm::debug()) - cvm::log("Colvar \""+this->name+"\" has value "+ - cvm::to_str(x, cvm::cv_width, cvm::cv_prec)+".\n"); + cvmodule->log("Colvar \""+this->name+"\" has value "+ + cvm::to_str(x, cvmodule->cv_width, cvmodule->cv_prec)+".\n"); if (after_restart) { x_old = x_restart; - if (cvm::proxy->simulation_running()) { + if (cvmodule->proxy->simulation_running()) { cvm::real const jump2 = dist2(x, x_restart) / (width*width); if (jump2 > 0.25) { - cvm::error("Error: the calculated value of colvar \""+name+ + cvmodule->error("Error: the calculated value of colvar \""+name+ "\":\n"+cvm::to_str(x)+"\n differs greatly from the value " "last read from the state file:\n"+cvm::to_str(x_restart)+ "\nPossible causes are changes in configuration, " @@ -1596,10 +1594,10 @@ int colvar::calc_cvc_gradients(int first_cvc, size_t num_cvcs) size_t i, cvc_count; if (cvm::debug()) - cvm::log("Calculating gradients of colvar \""+this->name+"\".\n"); + cvmodule->log("Calculating gradients of colvar \""+this->name+"\".\n"); // calculate the gradients of each component - cvm::increase_depth(); + cvmodule->increase_depth(); for (i = first_cvc, cvc_count = 0; (i < cvcs.size()) && (cvc_count < cvc_max_count); i++) { @@ -1616,10 +1614,10 @@ int colvar::calc_cvc_gradients(int first_cvc, size_t num_cvcs) } if (cvm::debug()) - cvm::log("Done calculating gradients of colvar \""+this->name+"\".\n"); + cvmodule->log("Done calculating gradients of colvar \""+this->name+"\".\n"); } - cvm::decrease_depth(); + cvmodule->decrease_depth(); return COLVARS_OK; } @@ -1649,9 +1647,9 @@ int colvar::calc_cvc_total_force(int first_cvc, size_t num_cvcs) if (is_enabled(f_cv_total_force_calc)) { if (cvm::debug()) - cvm::log("Calculating total force of colvar \""+this->name+"\".\n"); + cvmodule->log("Calculating total force of colvar \""+this->name+"\".\n"); - cvm::increase_depth(); + cvmodule->increase_depth(); for (i = first_cvc, cvc_count = 0; (i < cvcs.size()) && (cvc_count < cvc_max_count); @@ -1660,11 +1658,11 @@ int colvar::calc_cvc_total_force(int first_cvc, size_t num_cvcs) cvc_count++; (cvcs[i])->calc_force_invgrads(); } - cvm::decrease_depth(); + cvmodule->decrease_depth(); if (cvm::debug()) - cvm::log("Done calculating total force of colvar \""+this->name+"\".\n"); + cvmodule->log("Done calculating total force of colvar \""+this->name+"\".\n"); } return COLVARS_OK; @@ -1679,10 +1677,10 @@ int colvar::collect_cvc_total_forces() for (size_t i = 0; i < cvcs.size(); i++) { if (!cvcs[i]->is_enabled()) continue; if (cvm::debug()) - cvm::log("Colvar component no. "+cvm::to_str(i+1)+ + cvmodule->log("Colvar component no. "+cvm::to_str(i+1)+ " within colvar \""+this->name+"\" has total force "+ cvm::to_str((cvcs[i])->total_force(), - cvm::cv_width, cvm::cv_prec)+".\n"); + cvmodule->cv_width, cvmodule->cv_prec)+".\n"); // linear combination is assumed ft += (cvcs[i])->total_force() * (cvcs[i])->sup_coeff / active_cvc_square_norm; } @@ -1710,7 +1708,7 @@ int colvar::calc_cvc_Jacobians(int first_cvc, size_t num_cvcs) size_t const cvc_max_count = num_cvcs ? num_cvcs : num_active_cvcs(); if (is_enabled(f_cv_Jacobian)) { - cvm::increase_depth(); + cvmodule->increase_depth(); size_t i, cvc_count; for (i = first_cvc, cvc_count = 0; (i < cvcs.size()) && (cvc_count < cvc_max_count); @@ -1719,7 +1717,7 @@ int colvar::calc_cvc_Jacobians(int first_cvc, size_t num_cvcs) cvc_count++; (cvcs[i])->calc_Jacobian_derivative(); } - cvm::decrease_depth(); + cvmodule->decrease_depth(); } return COLVARS_OK; @@ -1728,16 +1726,16 @@ int colvar::calc_cvc_Jacobians(int first_cvc, size_t num_cvcs) int colvar::collect_cvc_Jacobians() { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; if (is_enabled(f_cv_Jacobian)) { fj.reset(); for (size_t i = 0; i < cvcs.size(); i++) { if (!cvcs[i]->is_enabled()) continue; if (cvm::debug()) - cvm::log("Colvar component no. "+cvm::to_str(i+1)+ + cvmodule->log("Colvar component no. "+cvm::to_str(i+1)+ " within colvar \""+this->name+"\" has Jacobian derivative"+ cvm::to_str((cvcs[i])->Jacobian_derivative(), - cvm::cv_width, cvm::cv_prec)+".\n"); + cvmodule->cv_width, cvmodule->cv_prec)+".\n"); // linear combination is assumed fj += (cvcs[i])->Jacobian_derivative() * (cvcs[i])->sup_coeff / active_cvc_square_norm; } @@ -1752,7 +1750,7 @@ int colvar::calc_colvar_properties() { if (is_enabled(f_cv_fdiff_velocity)) { // calculate the velocity by finite differences - if (cvm::step_relative() == 0) { + if (cvmodule->step_relative() == 0) { x_old = x; v_fdiff.reset(); // Do not pretend we know anything about the actual velocity // eg. upon restarting. That would require saving v_fdiff or x_old to the state file @@ -1766,15 +1764,15 @@ int colvar::calc_colvar_properties() // initialize the restraint center in the first step to the value // just calculated from the cvcs // Do the same if no simulation is running (eg. VMD postprocessing) - if ((cvm::step_relative() == 0 && !after_restart) || x_ext.type() == colvarvalue::type_notset || !cvm::proxy->simulation_running()) { + if ((cvmodule->step_relative() == 0 && !after_restart) || x_ext.type() == colvarvalue::type_notset || !cvmodule->proxy->simulation_running()) { x_ext = x; - cvm::log("Initializing extended coordinate to colvar value.\n"); + cvmodule->log("Initializing extended coordinate to colvar value.\n"); if (is_enabled(f_cv_reflecting_lower_boundary) && x_ext < lower_boundary) { - cvm::log("Warning: initializing extended coordinate to reflective lower boundary, as colvar value is below.\n"); + cvmodule->log("Warning: initializing extended coordinate to reflective lower boundary, as colvar value is below.\n"); x_ext = lower_boundary; } if (is_enabled(f_cv_reflecting_upper_boundary) && x_ext > upper_boundary) { - cvm::log("Warning: initializing extended coordinate to reflective upper boundary, as colvar value is above.\n"); + cvmodule->log("Warning: initializing extended coordinate to reflective upper boundary, as colvar value is above.\n"); x_ext = upper_boundary; } @@ -1783,16 +1781,16 @@ int colvar::calc_colvar_properties() // Special case of a repeated timestep (eg. multiple NAMD "run" statements) // revert values of the extended coordinate and velocity prior to latest integration - if (cvm::proxy->simulation_running() && cvm::step_relative() == prev_timestep) { + if (cvmodule->proxy->simulation_running() && cvmodule->step_relative() == prev_timestep) { // Detect jumps due to discrete changes in coordinates (eg. in replica exchange schemes) cvm::real const jump2 = dist2(x, x_old) / (width*width); if (jump2 > 0.25) { - cvm::log("Detected discrete jump in colvar value from " + cvmodule->log("Detected discrete jump in colvar value from " + cvm::to_str(x_old) + " to " + cvm::to_str(x) + ".\n"); - cvm::log("Reinitializing extended coordinate to colvar value.\n"); + cvmodule->log("Reinitializing extended coordinate to colvar value.\n"); x_ext = x; } else { - cvm::log("Reinitializing extended coordinate to last value.\n"); + cvmodule->log("Reinitializing extended coordinate to last value.\n"); x_ext = prev_x_ext; v_ext = prev_v_ext; } @@ -1810,7 +1808,7 @@ int colvar::calc_colvar_properties() // giving the behavior of f_cv_subtract_applied_force - this is correct for WTM-eABF etc. } else { - if (is_enabled(f_cv_subtract_applied_force) && !cvm::proxy->total_forces_same_step()) { + if (is_enabled(f_cv_subtract_applied_force) && !cvmodule->proxy->total_forces_same_step()) { // correct the total force only if it has been measured // TODO add a specific test instead of relying on sq norm if (ft.norm2() > 0.0) { @@ -1831,7 +1829,7 @@ int colvar::calc_colvar_properties() cvm::real colvar::update_forces_energy() { if (cvm::debug()) - cvm::log("Updating colvar \""+this->name+"\".\n"); + cvmodule->log("Updating colvar \""+this->name+"\".\n"); // set to zero the applied force f.type(value()); @@ -1858,7 +1856,7 @@ cvm::real colvar::update_forces_energy() // At this point f is the force f from external biases that will be applied to the // extended variable if there is one - if (is_enabled(f_cv_extended_Lagrangian) && cvm::proxy->simulation_running()) { + if (is_enabled(f_cv_extended_Lagrangian) && cvmodule->proxy->simulation_running()) { update_extended_Lagrangian(); } @@ -1869,7 +1867,7 @@ cvm::real colvar::update_forces_energy() } if (cvm::debug()) - cvm::log("Done updating colvar \""+this->name+"\".\n"); + cvmodule->log("Done updating colvar \""+this->name+"\".\n"); return (potential_energy + kinetic_energy); } @@ -1877,25 +1875,25 @@ cvm::real colvar::update_forces_energy() void colvar::update_extended_Lagrangian() { if (cvm::debug()) { - cvm::log("Updating extended-Lagrangian degree of freedom.\n"); + cvmodule->log("Updating extended-Lagrangian degree of freedom.\n"); } if (prev_timestep > -1L) { // Keep track of slow timestep to integrate MTS colvars // the colvar checks the interval after waking up twice - cvm::step_number n_timesteps = cvm::step_relative() - prev_timestep; + cvm::step_number n_timesteps = cvmodule->step_relative() - prev_timestep; if (n_timesteps != 0 && n_timesteps != time_step_factor) { - cvm::error("Error: extended-Lagrangian " + description + " has timeStepFactor " + + cvmodule->error("Error: extended-Lagrangian " + description + " has timeStepFactor " + cvm::to_str(time_step_factor) + ", but was activated after " + cvm::to_str(n_timesteps) + - " steps at timestep " + cvm::to_str(cvm::step_absolute()) + " (relative step: " + - cvm::to_str(cvm::step_relative()) + ").\n" + + " steps at timestep " + cvm::to_str(cvmodule->step_absolute()) + " (relative step: " + + cvm::to_str(cvmodule->step_relative()) + ").\n" + "Make sure that this colvar is requested by biases at multiples of timeStepFactor.\n"); return; } } // Integrate with slow timestep (if time_step_factor != 1) - cvm::real dt = cvm::dt() * cvm::real(time_step_factor); + cvm::real dt = cvmodule->dt() * cvm::real(time_step_factor); // Force acting on the extended variable colvarvalue f_ext(fr.type()); @@ -1999,7 +1997,7 @@ void colvar::update_extended_Lagrangian() v_ext = -0.5 * (prev_v_ext + v_ext); if ((is_enabled(f_cv_reflecting_lower_boundary) && (x_ext - lower_boundary) < 0.0) || (is_enabled(f_cv_reflecting_upper_boundary) && (x_ext - upper_boundary) > 0.0)) { - cvm::error("Error: extended coordinate value " + cvm::to_str(x_ext) + " is still outside boundaries after reflection.\n"); + cvmodule->error("Error: extended coordinate value " + cvm::to_str(x_ext) + " is still outside boundaries after reflection.\n"); } } @@ -2017,7 +2015,7 @@ void colvar::update_extended_Lagrangian() int colvar::end_of_step() { if (cvm::debug()) - cvm::log("End of step for colvar \""+this->name+"\".\n"); + cvmodule->log("End of step for colvar \""+this->name+"\".\n"); // Used for fdiff_velocity and for detecting jumps for extended Lagrangian colvars x_old = x; @@ -2026,7 +2024,7 @@ int colvar::end_of_step() f_old = f; } - prev_timestep = cvm::step_relative(); + prev_timestep = cvmodule->step_relative(); return COLVARS_OK; } @@ -2036,8 +2034,8 @@ void colvar::communicate_forces() { size_t i; if (cvm::debug()) { - cvm::log("Communicating forces from colvar \""+this->name+"\".\n"); - cvm::log("Force to be applied: " + cvm::to_str(f) + "\n"); + cvmodule->log("Communicating forces from colvar \""+this->name+"\".\n"); + cvmodule->log("Force to be applied: " + cvm::to_str(f) + "\n"); } if (is_enabled(f_cv_scripted)) { @@ -2048,13 +2046,13 @@ void colvar::communicate_forces() func_grads.push_back(cvm::matrix2d (x.size(), cvcs[i]->value().size())); } - int res = cvm::proxy->run_colvar_gradient_callback(scripted_function, sorted_cvc_values, func_grads); + int res = cvmodule->proxy->run_colvar_gradient_callback(scripted_function, sorted_cvc_values, func_grads); if (res != COLVARS_OK) { if (res == COLVARS_NOT_IMPLEMENTED) { - cvm::error("Colvar gradient scripts are not implemented.", COLVARS_NOT_IMPLEMENTED); + cvmodule->error("Colvar gradient scripts are not implemented.", COLVARS_NOT_IMPLEMENTED); } else { - cvm::error("Error running colvar gradient script"); + cvmodule->error("Error running colvar gradient script"); } return; } @@ -2114,14 +2112,14 @@ void colvar::communicate_forces() } if (cvm::debug()) - cvm::log("Done communicating forces from colvar \""+this->name+"\".\n"); + cvmodule->log("Done communicating forces from colvar \""+this->name+"\".\n"); } int colvar::set_cvc_flags(std::vector const &flags) { if (flags.size() != cvcs.size()) { - cvm::error("Error: Wrong number of CVC flags provided."); + cvmodule->error("Error: Wrong number of CVC flags provided."); return COLVARS_ERROR; } // We cannot enable or disable cvcs in the middle of a timestep or colvar evaluation sequence @@ -2154,7 +2152,7 @@ int colvar::update_cvc_flags() } } if (!n_active_cvcs) { - cvm::error("Error: All CVCs are disabled for colvar " + this->name +"\n"); + cvmodule->error("Error: All CVCs are disabled for colvar " + this->name +"\n"); return COLVARS_ERROR; } cvc_flags.clear(); @@ -2168,10 +2166,10 @@ int colvar::update_cvc_flags() int colvar::update_cvc_config(std::vector const &confs) { - cvm::log("Updating configuration for colvar \""+name+"\"\n"); + cvmodule->log("Updating configuration for colvar \""+name+"\"\n"); if (confs.size() != cvcs.size()) { - return cvm::error("Error: Wrong number of CVC config strings. " + return cvmodule->error("Error: Wrong number of CVC config strings. " "For those CVCs that are not being changed, try passing " "an empty string.", COLVARS_INPUT_ERROR); } @@ -2181,17 +2179,17 @@ int colvar::update_cvc_config(std::vector const &confs) for (size_t i = 0; i < cvcs.size(); i++) { if (confs[i].size()) { std::string conf(confs[i]); - cvm::increase_depth(); + cvmodule->increase_depth(); error_code |= cvcs[i]->colvar::cvc::init(conf); error_code |= cvcs[i]->check_keywords(conf, cvcs[i]->config_key.c_str()); - cvm::decrease_depth(); + cvmodule->decrease_depth(); num_changes++; } } if (num_changes == 0) { - cvm::log("Warning: no changes were applied through modifycvcs; " + cvmodule->log("Warning: no changes were applied through modifycvcs; " "please check that its argument is a list of strings.\n"); } @@ -2206,7 +2204,7 @@ int colvar::cvc_param_exists(std::string const ¶m_name) if (is_enabled(f_cv_single_cvc)) { return cvcs[0]->param_exists(param_name); } - return cvm::error("Error: calling colvar::cvc_param_exists() for a variable " + return cvmodule->error("Error: calling colvar::cvc_param_exists() for a variable " "with more than one component.\n", COLVARS_NOT_IMPLEMENTED); } @@ -2216,7 +2214,7 @@ cvm::real colvar::get_cvc_param(std::string const ¶m_name) if (is_enabled(f_cv_single_cvc)) { return cvcs[0]->get_param(param_name); } - cvm::error("Error: calling colvar::get_cvc_param() for a variable " + cvmodule->error("Error: calling colvar::get_cvc_param() for a variable " "with more than one component.\n", COLVARS_NOT_IMPLEMENTED); return 0.0; } @@ -2227,7 +2225,7 @@ void const *colvar::get_cvc_param_ptr(std::string const ¶m_name) if (is_enabled(f_cv_single_cvc)) { return cvcs[0]->get_param_ptr(param_name); } - cvm::error("Error: calling colvar::get_cvc_param() for a variable " + cvmodule->error("Error: calling colvar::get_cvc_param() for a variable " "with more than one component.\n", COLVARS_NOT_IMPLEMENTED); return NULL; } @@ -2238,7 +2236,7 @@ colvarvalue const *colvar::get_cvc_param_grad(std::string const ¶m_name) if (is_enabled(f_cv_single_cvc)) { return cvcs[0]->get_param_grad(param_name); } - cvm::error("Error: calling colvar::get_cvc_param_grad() for a variable " + cvmodule->error("Error: calling colvar::get_cvc_param_grad() for a variable " "with more than one component.\n", COLVARS_NOT_IMPLEMENTED); return NULL; } @@ -2249,7 +2247,7 @@ int colvar::set_cvc_param(std::string const ¶m_name, void const *new_value) if (is_enabled(f_cv_single_cvc)) { return cvcs[0]->set_param(param_name, new_value); } - return cvm::error("Error: calling colvar::set_cvc_param() for a variable " + return cvmodule->error("Error: calling colvar::set_cvc_param() for a variable " "with more than one component.\n", COLVARS_NOT_IMPLEMENTED); } @@ -2392,13 +2390,13 @@ int colvar::check_matching_state(std::string const &conf) get_keyval(conf, "name", check_name, std::string(""), colvarparse::parse_silent); if (check_name.size() == 0) { - return cvm::error("Error: Collective variable in the " + return cvmodule->error("Error: Collective variable in the " "state file without any identifier.\n", COLVARS_INPUT_ERROR); } if (check_name != name) { if (cvm::debug()) { - cvm::log("Ignoring state of colvar \""+check_name+ + cvmodule->log("Ignoring state of colvar \""+check_name+ "\": this colvar is named \""+name+"\".\n"); } matching_state = false; @@ -2414,11 +2412,11 @@ int colvar::set_state_params(std::string const &conf) { int error_code = COLVARS_OK; if ( !(get_keyval(conf, "x", x, x, colvarparse::parse_silent)) ) { - error_code |= cvm::error("Error: restart file does not contain " + error_code |= cvmodule->error("Error: restart file does not contain " "the value of the colvar \""+ name+"\" .\n", COLVARS_INPUT_ERROR); } else { - cvm::log("Restarting collective variable \""+name+"\" from value: "+ + cvmodule->log("Restarting collective variable \""+name+"\" from value: "+ cvm::to_str(x)+"\n"); x_restart = x; after_restart = true; @@ -2434,7 +2432,7 @@ int colvar::set_state_params(std::string const &conf) colvarvalue(x.type()), colvarparse::parse_silent)) || !(get_keyval(conf, "extended_v", v_ext, colvarvalue(x.type()), colvarparse::parse_silent)) ) { - error_code |= cvm::error("Error: restart file does not contain " + error_code |= cvmodule->error("Error: restart file does not contain " "\"extended_x\" or \"extended_v\" for the colvar \""+ name+"\", but you requested \"extendedLagrangian\".\n", COLVARS_INPUT_ERROR); @@ -2448,7 +2446,7 @@ int colvar::set_state_params(std::string const &conf) if ( !(get_keyval(conf, "v", v_fdiff, colvarvalue(x.type()), colvarparse::parse_silent)) ) { - error_code |= cvm::error("Error: restart file does not contain " + error_code |= cvmodule->error("Error: restart file does not contain " "the velocity for the colvar \""+ name+"\", but you requested \"outputVelocity\".\n", COLVARS_INPUT_ERROR); @@ -2495,7 +2493,7 @@ cvm::memory_stream &colvar::read_state(cvm::memory_stream &is) error_msg += "; the configuration string read was not recognized"; } error_msg += ".\n"; - cvm::error(error_msg, COLVARS_INPUT_ERROR); + cvmodule->error(error_msg, COLVARS_INPUT_ERROR); return is; } @@ -2507,7 +2505,7 @@ std::istream & colvar::read_traj(std::istream &is) if (is_enabled(f_cv_output_value)) { if (!(is >> x)) { - cvm::log("Error: in reading the value of colvar \""+ + cvmodule->log("Error: in reading the value of colvar \""+ this->name+"\" from trajectory.\n"); is.clear(); is.seekg(start_pos); @@ -2555,7 +2553,7 @@ std::ostream & colvar::write_state(std::ostream &os) const os << "colvar {\n" << get_state_params() << "}\n\n"; if (runave_outfile.size() > 0) { - cvm::main()->proxy->flush_output_stream(runave_outfile); + cvmodule->proxy->flush_output_stream(runave_outfile); } return os; @@ -2568,8 +2566,8 @@ std::string const colvar::get_state_params() const os << " name " << name << "\n" << " x " - << std::setprecision(cvm::cv_prec) - << std::setw(cvm::cv_width); + << std::setprecision(cvmodule->cv_prec) + << std::setw(cvmodule->cv_width); if (is_enabled(f_cv_external) && is_enabled(f_cv_extended_Lagrangian)) { // For an external colvar, x is one timestep in the future after integration // write x at beginning of timestep @@ -2580,19 +2578,19 @@ std::string const colvar::get_state_params() const if (is_enabled(f_cv_output_velocity)) { os << " v " - << std::setprecision(cvm::cv_prec) - << std::setw(cvm::cv_width) + << std::setprecision(cvmodule->cv_prec) + << std::setw(cvmodule->cv_width) << v_reported << "\n"; } if (is_enabled(f_cv_extended_Lagrangian)) { os << " extended_x " - << std::setprecision(cvm::cv_prec) - << std::setw(cvm::cv_width) + << std::setprecision(cvmodule->cv_prec) + << std::setw(cvmodule->cv_width) << x_reported << "\n" << " extended_v " - << std::setprecision(cvm::cv_prec) - << std::setw(cvm::cv_width) + << std::setprecision(cvmodule->cv_prec) + << std::setw(cvmodule->cv_width) << v_reported << "\n"; } @@ -2605,7 +2603,7 @@ cvm::memory_stream & colvar::write_state(cvm::memory_stream &os) const os << std::string("colvar") << get_state_params(); if (runave_outfile.size() > 0) { - cvm::main()->proxy->flush_output_stream(runave_outfile); + cvmodule->proxy->flush_output_stream(runave_outfile); } return os; @@ -2614,49 +2612,49 @@ cvm::memory_stream & colvar::write_state(cvm::memory_stream &os) const std::ostream & colvar::write_traj_label(std::ostream & os) { - size_t const this_cv_width = x.output_width(cvm::cv_width); + size_t const this_cv_width = x.output_width(cvmodule->cv_width); os << " "; if (is_enabled(f_cv_output_value)) { os << " " - << cvm::wrap_string(this->name, this_cv_width); + << cvmodule->wrap_string(this->name, this_cv_width); if (is_enabled(f_cv_extended_Lagrangian) && !is_enabled(f_cv_external)) { // extended DOF os << " r_" - << cvm::wrap_string(this->name, this_cv_width-2); + << cvmodule->wrap_string(this->name, this_cv_width-2); } } if (is_enabled(f_cv_output_velocity)) { os << " v_" - << cvm::wrap_string(this->name, this_cv_width-2); + << cvmodule->wrap_string(this->name, this_cv_width-2); if (is_enabled(f_cv_extended_Lagrangian) && !is_enabled(f_cv_external)) { // extended DOF os << " vr_" - << cvm::wrap_string(this->name, this_cv_width-3); + << cvmodule->wrap_string(this->name, this_cv_width-3); } } if (is_enabled(f_cv_output_energy)) { os << " Ep_" - << cvm::wrap_string(this->name, this_cv_width-3) + << cvmodule->wrap_string(this->name, this_cv_width-3) << " Ek_" - << cvm::wrap_string(this->name, this_cv_width-3); + << cvmodule->wrap_string(this->name, this_cv_width-3); } if (is_enabled(f_cv_output_total_force)) { os << " ft_" - << cvm::wrap_string(this->name, this_cv_width-3); + << cvmodule->wrap_string(this->name, this_cv_width-3); } if (is_enabled(f_cv_output_applied_force)) { os << " fa_" - << cvm::wrap_string(this->name, this_cv_width-3); + << cvmodule->wrap_string(this->name, this_cv_width-3); } return os; @@ -2665,38 +2663,38 @@ std::ostream & colvar::write_traj_label(std::ostream & os) std::ostream & colvar::write_traj(std::ostream &os) { - os << " " << std::setprecision(cvm::cv_prec); + os << " " << std::setprecision(cvmodule->cv_prec); if (is_enabled(f_cv_output_value)) { if (is_enabled(f_cv_extended_Lagrangian) && !is_enabled(f_cv_external)) { - os << " " << std::setw(cvm::cv_width) << x; + os << " " << std::setw(cvmodule->cv_width) << x; } - os << " " << std::setw(cvm::cv_width) << x_reported; + os << " " << std::setw(cvmodule->cv_width) << x_reported; } if (is_enabled(f_cv_output_velocity)) { if (is_enabled(f_cv_extended_Lagrangian) && !is_enabled(f_cv_external)) { - os << " " << std::setw(cvm::cv_width) << v_fdiff; + os << " " << std::setw(cvmodule->cv_width) << v_fdiff; } - os << " " << std::setw(cvm::cv_width) << v_reported; + os << " " << std::setw(cvmodule->cv_width) << v_reported; } - os << std::setprecision(cvm::en_prec); + os << std::setprecision(cvmodule->en_prec); if (is_enabled(f_cv_output_energy)) { - os << " " << std::setw(cvm::en_width) << potential_energy + os << " " << std::setw(cvmodule->en_width) << potential_energy << " " << kinetic_energy; } if (is_enabled(f_cv_output_total_force)) { - os << " " << std::setw(cvm::en_width) << ft_reported; + os << " " << std::setw(cvmodule->en_width) << ft_reported; } if (is_enabled(f_cv_output_applied_force)) { - os << " " << std::setw(cvm::en_width) << applied_force(); + os << " " << std::setw(cvmodule->en_width) << applied_force(); } return os; @@ -2710,19 +2708,19 @@ int colvar::write_output_files() if (is_enabled(f_cv_corrfunc)) { if (acf.size()) { if (acf_outfile.size() == 0) { - acf_outfile = std::string(cvm::output_prefix()+"."+this->name+ + acf_outfile = std::string(cvmodule->output_prefix()+"."+this->name+ ".corrfunc.dat"); } - cvm::log("Writing correlation function to file \""+acf_outfile+"\".\n"); - cvm::backup_file(acf_outfile.c_str()); - std::ostream &acf_os = cvm::proxy->output_stream(acf_outfile, + cvmodule->log("Writing correlation function to file \""+acf_outfile+"\".\n"); + cvmodule->backup_file(acf_outfile.c_str()); + std::ostream &acf_os = cvmodule->proxy->output_stream(acf_outfile, "colvar ACF file"); if (!acf_os) { error_code |= COLVARS_FILE_ERROR; } else { error_code |= write_acf(acf_os); } - cvm::proxy->close_output_stream(acf_outfile); + cvmodule->proxy->close_output_stream(acf_outfile); } } @@ -2775,9 +2773,9 @@ int colvar::calc_acf() // representation but separated by acf_stride in the time series; // the pointer to each vector is changed at every step - colvar const *cfcv = cvm::colvar_by_name(acf_colvar_name); + colvar const *cfcv = cvmodule->colvar_by_name(acf_colvar_name); if (cfcv == NULL) { - return cvm::error("Error: collective variable \""+acf_colvar_name+ + return cvmodule->error("Error: collective variable \""+acf_colvar_name+ "\" is not defined at this time.\n", COLVARS_INPUT_ERROR); } @@ -2786,14 +2784,14 @@ int colvar::calc_acf() // first-step operations if (colvarvalue::check_types(cfcv->value(), value())) { - cvm::error("Error: correlation function between \""+cfcv->name+ + cvmodule->error("Error: correlation function between \""+cfcv->name+ "\" and \""+this->name+"\" cannot be calculated, " "because their value types are different.\n", COLVARS_INPUT_ERROR); } acf_nframes = 0; - cvm::log("Colvar \""+this->name+"\": initializing correlation function " + cvmodule->log("Colvar \""+this->name+"\": initializing correlation function " "calculation.\n"); if (acf.size() < acf_length+1) @@ -2824,7 +2822,7 @@ int colvar::calc_acf() break; } - } else if (cvm::step_relative() > prev_timestep) { + } else if (cvmodule->step_relative() > prev_timestep) { switch (acf_type) { @@ -2967,17 +2965,17 @@ int colvar::write_acf(std::ostream &os) os << acf_nframes << "\n"; } - os << "# " << cvm::wrap_string("step", cvm::it_width-2) << " " - << cvm::wrap_string("corrfunc(step)", cvm::cv_width) << "\n"; + os << "# " << cvmodule->wrap_string("step", cvmodule->it_width-2) << " " + << cvmodule->wrap_string("corrfunc(step)", cvmodule->cv_width) << "\n"; cvm::real const acf_norm = acf.front() / cvm::real(acf_nframes); std::vector::iterator acf_i; size_t it = acf_offset; for (acf_i = acf.begin(); acf_i != acf.end(); ++acf_i) { - os << std::setw(cvm::it_width) << acf_stride * (it++) << " " - << std::setprecision(cvm::cv_prec) - << std::setw(cvm::cv_width) + os << std::setw(cvmodule->it_width) << acf_stride * (it++) << " " + << std::setprecision(cvmodule->cv_prec) + << std::setw(cvmodule->cv_width) << ( acf_normalize ? (*acf_i)/(acf_norm * cvm::real(acf_nframes)) : (*acf_i)/(cvm::real(acf_nframes)) ) << "\n"; @@ -2990,7 +2988,7 @@ int colvar::write_acf(std::ostream &os) int colvar::calc_runave() { int error_code = COLVARS_OK; - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; if (x_history.empty()) { @@ -3000,7 +2998,7 @@ int colvar::calc_runave() // first-step operationsf if (cvm::debug()) - cvm::log("Colvar \""+this->name+ + cvmodule->log("Colvar \""+this->name+ "\": initializing running average calculation.\n"); acf_nframes = 0; @@ -3010,26 +3008,26 @@ int colvar::calc_runave() } else { - if ( (cvm::step_relative() % runave_stride) == 0 && - (cvm::step_relative() > prev_timestep) ) { + if ( (cvmodule->step_relative() % runave_stride) == 0 && + (cvmodule->step_relative() > prev_timestep) ) { if ((*x_history_p).size() >= runave_length-1) { if (runave_outfile.size() == 0) { - runave_outfile = std::string(cvm::output_prefix()+"."+ + runave_outfile = std::string(cvmodule->output_prefix()+"."+ this->name+".runave.traj"); } if (! proxy->output_stream_exists(runave_outfile)) { - size_t const this_cv_width = x.output_width(cvm::cv_width); + size_t const this_cv_width = x.output_width(cvmodule->cv_width); std::ostream &runave_os = proxy->output_stream(runave_outfile, "colvar running average"); runave_os.setf(std::ios::scientific, std::ios::floatfield); - runave_os << "# " << cvm::wrap_string("step", cvm::it_width-2) + runave_os << "# " << cvmodule->wrap_string("step", cvmodule->it_width-2) << " " - << cvm::wrap_string("running average", this_cv_width) + << cvmodule->wrap_string("running average", this_cv_width) << " " - << cvm::wrap_string("running stddev", this_cv_width) + << cvmodule->wrap_string("running stddev", this_cv_width) << "\n"; } @@ -3053,9 +3051,9 @@ int colvar::calc_runave() if (runave_outfile.size() > 0) { std::ostream &runave_os = proxy->output_stream(runave_outfile, "running average output file"); - runave_os << std::setw(cvm::it_width) << cvm::step_relative() << " " - << std::setprecision(cvm::cv_prec) << std::setw(cvm::cv_width) << runave << " " - << std::setprecision(cvm::cv_prec) << std::setw(cvm::cv_width) + runave_os << std::setw(cvmodule->it_width) << cvmodule->step_relative() << " " + << std::setprecision(cvmodule->cv_prec) << std::setw(cvmodule->cv_width) << runave << " " + << std::setprecision(cvmodule->cv_prec) << std::setw(cvmodule->cv_width) << cvm::sqrt(runave_variance) << "\n"; } } diff --git a/src/colvar.h b/src/colvar.h index 17343a7a7..27fff4683 100644 --- a/src/colvar.h +++ b/src/colvar.h @@ -50,7 +50,7 @@ /// \link colvarvalue \endlink type, you should also add its /// initialization line in the \link colvar \endlink constructor. -class colvar : public colvarparse, public colvardeps { +class colvar : public colvardeps { public: @@ -96,11 +96,11 @@ class colvar : public colvarparse, public colvardeps { static std::vector cv_features; /// \brief Implementation of the feature list accessor for colvar - virtual const std::vector &features() const + virtual const std::vector &features() const override { return cv_features; } - virtual std::vector &modify_features() + virtual std::vector &modify_features() override { return cv_features; } @@ -114,7 +114,7 @@ class colvar : public colvarparse, public colvardeps { /// Implements possible actions to be carried out /// when a given feature is enabled /// This overloads the base function in colvardeps - void do_feature_side_effects(int id); + void do_feature_side_effects(int id) override; /// List of biases that depend on this colvar std::vector biases; @@ -165,7 +165,7 @@ class colvar : public colvarparse, public colvardeps { // using the gradient of the square distance to calculate the // velocity (non-scalar variables automatically taken into // account) - cvm::real dt = cvm::dt(); + cvm::real dt = cvmodule->dt(); return ( ( (dt > 0.0) ? (1.0/dt) : 1.0 ) * 0.5 * dist2_lgrad(xnew, xold) ); } @@ -246,7 +246,7 @@ class colvar : public colvarparse, public colvardeps { /// Constructor - colvar(); + colvar(colvarmodule *cvmodule_in); /// Main init function int init(std::string const &conf); @@ -276,7 +276,7 @@ class colvar : public colvarparse, public colvardeps { int init_output_flags(std::string const &conf); /// \brief Initialize dependency tree - virtual int init_dependencies(); + int init_dependencies() override; private: @@ -765,10 +765,13 @@ inline colvarvalue const & colvar::total_force() const inline void colvar::add_bias_force(colvarvalue const &force) { - check_enabled(f_cv_apply_force, - std::string("applying a force to the variable \""+name+"\"")); + if (! is_enabled(f_cv_apply_force)) { + cvmodule->error("Error: applying a force to the variable \""+name+" requires that the feature \""+ + features()[f_cv_apply_force]->description+"\" is active.\n", COLVARS_BUG_ERROR); + } + if (cvm::debug()) { - cvm::log("Adding biasing force "+cvm::to_str(force)+" to colvar \""+name+"\".\n"); + cvmodule->log("Adding biasing force "+cvm::to_str(force)+" to colvar \""+name+"\".\n"); } fb += force; } @@ -777,7 +780,7 @@ inline void colvar::add_bias_force(colvarvalue const &force) inline void colvar::add_bias_force_actual_value(colvarvalue const &force) { if (cvm::debug()) { - cvm::log("Adding biasing force "+cvm::to_str(force)+" to colvar \""+name+"\".\n"); + cvmodule->log("Adding biasing force "+cvm::to_str(force)+" to colvar \""+name+"\".\n"); } fb_actual += force; } diff --git a/src/colvar_UIestimator.h b/src/colvar_UIestimator.h index 30a90a579..1de84c909 100644 --- a/src/colvar_UIestimator.h +++ b/src/colvar_UIestimator.h @@ -19,7 +19,7 @@ #include // only for colvar module! -// when integrated into other code, just remove this line and "...cvm::backup_file(...)" +// when integrated into other code, just remove this line and "...cvmodule->backup_file(...)" #include "colvarmodule.h" #include "colvarproxy.h" @@ -215,29 +215,30 @@ namespace UIestimator { class UIestimator { // the implemension of UI estimator public: + colvarmodule *cvmodule; + UIestimator() {} //called when (re)start an eabf simulation - UIestimator(const std::vector & lowerboundary_input, - const std::vector & upperboundary_input, - const std::vector & width_input, - const std::vector & krestr_input, // force constant in eABF - const std::string & output_filename_input, // the prefix of output files - const int output_freq_input, - const bool restart_input, // whether restart from a .count and a .grad file - const std::vector & input_filename_input, // the prefixes of input files - const double temperature_input) { - - // initialize variables - this->lowerboundary = lowerboundary_input; - this->upperboundary = upperboundary_input; - this->width = width_input; - this->krestr = krestr_input; - this->output_filename = output_filename_input; - this->output_freq = output_freq_input; - this->restart = restart_input; - this->input_filename = input_filename_input; - this->temperature = temperature_input; + UIestimator(colvarmodule * cvmodule_in, + const std::vector & lowerboundary_in, + const std::vector & upperboundary_in, + const std::vector & width_in, + const std::vector & krestr_in, // force constant in eABF + const std::string & output_filename_in, // the prefix of output files + const bool restart_in, // whether restart from a .count and a .grad file + const std::vector & input_filename_in, // the prefixes of input files + const double temperature_in) + : cvmodule(cvmodule_in), + lowerboundary(lowerboundary_in), + upperboundary(upperboundary_in), + width(width_in), + krestr(krestr_in), + output_filename(output_filename_in), + restart(restart_in), + input_filename(input_filename_in), + temperature(temperature_in) + { int i, j; @@ -358,7 +359,6 @@ namespace UIestimator { std::vector width; std::vector krestr; std::string output_filename; - int output_freq; bool restart; std::vector input_filename; double temperature; @@ -381,7 +381,7 @@ namespace UIestimator { public: // calculate gradients from the internal variables void calc_pmf() { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; int norm; int i, j, k; @@ -516,9 +516,9 @@ namespace UIestimator { std::string pmf_filename = output_filename + ".UI.pmf"; // only for colvars module! - if (written_1D) cvm::backup_file(pmf_filename.c_str()); + if (written_1D) cvmodule->backup_file(pmf_filename.c_str()); - std::ostream &ofile_pmf = cvm::proxy->output_stream(pmf_filename, + std::ostream &ofile_pmf = cvmodule->proxy->output_stream(pmf_filename, "PMF file"); std::vector position(1, 0); @@ -527,7 +527,7 @@ namespace UIestimator { position[0] = i + EPSILON; ofile_pmf << oneD_pmf.get_value(position) << std::endl; } - cvm::proxy->close_output_stream(pmf_filename); + cvmodule->proxy->close_output_stream(pmf_filename); written_1D = true; } @@ -545,7 +545,7 @@ namespace UIestimator { void write_interal_data() { std::string internal_filename = output_filename + ".UI.internal"; - std::ostream &ofile_internal = cvm::proxy->output_stream(internal_filename, + std::ostream &ofile_internal = cvmodule->proxy->output_stream(internal_filename, "UI internal file"); std::vector loop_flag(dimension, 0); @@ -585,7 +585,7 @@ namespace UIestimator { break; } } - cvm::proxy->close_output_stream(internal_filename.c_str()); + cvmodule->proxy->close_output_stream(internal_filename.c_str()); } // write output files @@ -597,15 +597,15 @@ namespace UIestimator { int i, j; // // only for colvars module! - if (written) cvm::backup_file(grad_filename.c_str()); - //if (written) cvm::backup_file(hist_filename.c_str()); - if (written) cvm::backup_file(count_filename.c_str()); + if (written) cvmodule->backup_file(grad_filename.c_str()); + //if (written) cvmodule->backup_file(hist_filename.c_str()); + if (written) cvmodule->backup_file(count_filename.c_str()); - std::ostream &ofile = cvm::proxy->output_stream(grad_filename, + std::ostream &ofile = cvmodule->proxy->output_stream(grad_filename, "gradient file"); - std::ostream &ofile_hist = cvm::proxy->output_stream(hist_filename, + std::ostream &ofile_hist = cvmodule->proxy->output_stream(hist_filename, "gradient history file"); - std::ostream &ofile_count = cvm::proxy->output_stream(count_filename, + std::ostream &ofile_count = cvmodule->proxy->output_stream(count_filename, "count file"); writehead(ofile); @@ -670,9 +670,9 @@ namespace UIestimator { break; } } - cvm::proxy->close_output_stream(grad_filename.c_str()); - // cvm::proxy->close_output_stream(hist_filename.c_str()); - cvm::proxy->close_output_stream(count_filename.c_str()); + cvmodule->proxy->close_output_stream(grad_filename.c_str()); + // cvmodule->proxy->close_output_stream(hist_filename.c_str()); + cvmodule->proxy->close_output_stream(count_filename.c_str()); written = true; } @@ -685,7 +685,7 @@ namespace UIestimator { int dimension_temp; int i, j, k, l, m; - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; std::vector loop_bin_size(dimension, 0); std::vector position_temp(dimension, 0); std::vector grad_temp(dimension, 0); diff --git a/src/colvar_arithmeticpath.h b/src/colvar_arithmeticpath.h index ee97390df..e2cda439a 100644 --- a/src/colvar_arithmeticpath.h +++ b/src/colvar_arithmeticpath.h @@ -18,7 +18,7 @@ class ArithmeticPathBase { public: ArithmeticPathBase() {} ~ArithmeticPathBase() {} - void initialize(size_t p_num_elements, size_t p_total_frames, scalar_type p_lambda, const vector& p_weights); + void initialize(size_t p_num_elements, size_t p_total_frames, scalar_type p_lambda, const vector& p_weights, colvarmodule* cvmodule_in); void reComputeLambda(const vector& rmsd_between_refs); template void computeValue(const vector>& frame_element_distances, scalar_type *s = nullptr, scalar_type *z = nullptr); @@ -35,10 +35,12 @@ class ArithmeticPathBase { scalar_type saved_exponent_sum; scalar_type normalization_factor; scalar_type saved_s; + colvarmodule* cvmodule; }; template -void ArithmeticPathBase::initialize(size_t p_num_elements, size_t p_total_frames, scalar_type p_lambda, const vector& p_weights) { +void ArithmeticPathBase::initialize(size_t p_num_elements, size_t p_total_frames, scalar_type p_lambda, + const vector& p_weights, colvarmodule* cvmodule_in) { lambda = p_lambda; for (size_t i = 0; i < p_weights.size(); ++i) squared_weights.push_back(p_weights[i] * p_weights[i]); num_elements = p_num_elements; @@ -48,6 +50,7 @@ void ArithmeticPathBase::initialize(size_t p_num_elements, size_t p saved_s = scalar_type(); saved_exponent_sum = scalar_type(); max_exponent = scalar_type(); + cvmodule = cvmodule_in; } template @@ -87,7 +90,8 @@ template void ArithmeticPathBase::reComputeLambda(const vector& rmsd_between_refs) { scalar_type mean_square_displacements = 0.0; for (size_t i_frame = 1; i_frame < total_frames; ++i_frame) { - cvm::log(std::string("Distance between frame ") + cvm::to_str(i_frame) + " and " + cvm::to_str(i_frame + 1) + " is " + cvm::to_str(rmsd_between_refs[i_frame - 1]) + std::string("\n")); + cvmodule->log(std::string("Distance between frame ") + cvm::to_str(i_frame) + " and " + cvm::to_str(i_frame + 1) + + " is " + cvm::to_str(rmsd_between_refs[i_frame - 1]) + std::string("\n")); mean_square_displacements += rmsd_between_refs[i_frame - 1] * rmsd_between_refs[i_frame - 1]; } mean_square_displacements /= scalar_type(total_frames - 1); diff --git a/src/colvar_gpu_calc.cpp b/src/colvar_gpu_calc.cpp index 54c0de00e..0acb751b6 100644 --- a/src/colvar_gpu_calc.cpp +++ b/src/colvar_gpu_calc.cpp @@ -20,7 +20,7 @@ int colvarmodule_gpu_calc::cv_update_flags(const std::vector& colvars) int colvarmodule_gpu_calc::cvc_calc_total_force( const std::vector& colvars, - colvarmodule* colvar_module, + colvarmodule* cvmodule, bool use_current_step) { int error_code = COLVARS_OK; #if defined (COLVARS_NVTX_PROFILING) @@ -34,8 +34,8 @@ int colvarmodule_gpu_calc::cvc_calc_total_force( (*cvi)->is_enabled(colvardeps::f_cv_total_force_current_step) : !(*cvi)->is_enabled(colvardeps::f_cv_total_force_current_step); if (do_total_force) { - if (colvar_module->debug()) { - colvar_module->log("Calculating total force of colvar \""+(*cvi)->name+"\".\n"); + if (cvmodule->debug()) { + cvmodule->log("Calculating total force of colvar \""+(*cvi)->name+"\".\n"); } const auto all_cvcs = (*cvi)->get_cvcs(); for (auto cvc = all_cvcs.begin(); cvc != all_cvcs.end(); ++cvc) { @@ -44,8 +44,8 @@ int colvarmodule_gpu_calc::cvc_calc_total_force( (*cvc)->calc_force_invgrads(); } } - if (colvar_module->debug()) { - colvar_module->log("Done calculating total force of colvar \""+(*cvi)->name+"\".\n"); + if (cvmodule->debug()) { + cvmodule->log("Done calculating total force of colvar \""+(*cvi)->name+"\".\n"); } } } @@ -58,8 +58,8 @@ int colvarmodule_gpu_calc::cvc_calc_total_force( int colvarmodule_gpu_calc::atom_group_read_data_gpu( const std::vector& colvars, colvarmodule_gpu_calc::compute_gpu_graph_t& g, - colvarmodule* colvar_module) { - colvarproxy* p = colvar_module->proxy; + colvarmodule* cvmodule) { + colvarproxy* p = cvmodule->proxy; cudaStream_t stream = p->get_default_stream(); int error_code = COLVARS_OK; if (!g.graph_exec_initialized) { @@ -140,10 +140,10 @@ int colvarmodule_gpu_calc::atom_group_read_data_gpu( error_code |= checkGPUError(cudaGraphInstantiate(&g.graph_exec, g.graph)); if (error_code != COLVARS_OK) return error_code; g.graph_exec_initialized = true; - if (colvar_module->debug()) { + if (cvmodule->debug()) { // Debug graph - const std::string filename = cvm::output_prefix() + "_read_data.dot"; - colvar_module->log("Writing read data graph to " + filename); + const std::string filename = cvmodule->output_prefix() + "_read_data.dot"; + cvmodule->log("Writing read data graph to " + filename); g.dump_graph(filename.c_str()); } } @@ -177,7 +177,7 @@ int colvarmodule_gpu_calc::atom_group_read_data_gpu( return error_code; } -int colvarmodule_gpu_calc::cvc_calc_value(const std::vector& colvars, colvarmodule* colvar_module) { +int colvarmodule_gpu_calc::cvc_calc_value(const std::vector& colvars, colvarmodule* cvmodule) { int error_code = COLVARS_OK; #if defined (COLVARS_NVTX_PROFILING) cvc_calc_value_prof.start(); @@ -188,12 +188,12 @@ int colvarmodule_gpu_calc::cvc_calc_value(const std::vector& colvars, c for (auto cvc = all_cvcs.begin(); cvc != all_cvcs.end(); ++cvc) { if (!(*cvc)->is_enabled(colvardeps::f_cvc_active)) continue; (*cvc)->calc_value(); - if (colvar_module->debug()) { - colvar_module->log( + if (cvmodule->debug()) { + cvmodule->log( "Colvar component "+(*cvc)->name+ " within colvar \""+(*cvi)->name+"\" has value "+ - colvar_module->to_str((*cvc)->value(), - colvar_module->cv_width, colvar_module->cv_prec)+".\n"); + cvmodule->to_str((*cvc)->value(), + cvmodule->cv_width, cvmodule->cv_prec)+".\n"); } } } @@ -203,7 +203,7 @@ int colvarmodule_gpu_calc::cvc_calc_value(const std::vector& colvars, c return error_code; } -int colvarmodule_gpu_calc::cvc_calc_gradients(const std::vector& colvars, colvarmodule* colvar_module) { +int colvarmodule_gpu_calc::cvc_calc_gradients(const std::vector& colvars, colvarmodule* cvmodule) { int error_code = COLVARS_OK; #if defined (COLVARS_NVTX_PROFILING) cvc_calc_gradients_prof.start(); @@ -227,9 +227,9 @@ int colvarmodule_gpu_calc::cvc_calc_gradients(const std::vector& colvar int colvarmodule_gpu_calc::atom_group_calc_fit_gradients( const std::vector& colvars, colvarmodule_gpu_calc::compute_gpu_graph_t& g, - colvarmodule* colvar_module) { + colvarmodule* cvmodule) { int error_code = COLVARS_OK; - colvarproxy* p = colvar_module->proxy; + colvarproxy* p = cvmodule->proxy; cudaStream_t stream = p->get_default_stream(); if (!g.graph_exec_initialized) { // Find all atom groups requiring fit gradients @@ -299,10 +299,10 @@ int colvarmodule_gpu_calc::atom_group_calc_fit_gradients( error_code |= checkGPUError(cudaGraphInstantiate(&g.graph_exec, g.graph)); if (error_code != COLVARS_OK) return error_code; g.graph_exec_initialized = true; - if (colvar_module->debug()) { + if (cvmodule->debug()) { // Debug graph - const std::string filename = cvm::output_prefix() + "_fit_gradients.dot"; - colvar_module->log("Writing fit gradients graph to " + filename); + const std::string filename = cvmodule->output_prefix() + "_fit_gradients.dot"; + cvmodule->log("Writing fit gradients graph to " + filename); g.dump_graph(filename.c_str()); } } @@ -320,7 +320,7 @@ int colvarmodule_gpu_calc::atom_group_calc_fit_gradients( return error_code; } -int colvarmodule_gpu_calc::cvc_debug_gradients(const std::vector& colvars, colvarmodule* colvar_module) { +int colvarmodule_gpu_calc::cvc_debug_gradients(const std::vector& colvars, colvarmodule* cvmodule) { int error_code = COLVARS_OK; for (auto cvi = colvars.begin(); cvi != colvars.end(); cvi++) { const auto all_cvcs = (*cvi)->get_cvcs(); @@ -334,7 +334,7 @@ int colvarmodule_gpu_calc::cvc_debug_gradients(const std::vector& colva return error_code; } -int colvarmodule_gpu_calc::cvc_calc_Jacobian_derivative(const std::vector& colvars, colvarmodule* colvar_module) { +int colvarmodule_gpu_calc::cvc_calc_Jacobian_derivative(const std::vector& colvars, colvarmodule* cvmodule) { int error_code = COLVARS_OK; #if defined (COLVARS_NVTX_PROFILING) cvc_calc_Jacobian_derivative_prof.start(); @@ -355,14 +355,14 @@ int colvarmodule_gpu_calc::cvc_calc_Jacobian_derivative(const std::vector& colvars, colvarmodule* colvar_module) { +int colvarmodule_gpu_calc::cv_collect_cvc_data(const std::vector& colvars, colvarmodule* cvmodule) { int error_code = COLVARS_OK; #if defined (COLVARS_NVTX_PROFILING) cv_collect_cvc_data_prof.start(); #endif // defined (COLVARS_NVTX_PROFILING) for (auto cvi = colvars.begin(); cvi != colvars.end(); cvi++) { error_code |= (*cvi)->collect_cvc_data(); - if (colvar_module->get_error()) { + if (cvmodule->get_error()) { return COLVARS_ERROR; } } @@ -432,51 +432,51 @@ int colvarmodule_gpu_calc::init() { return error_code; } -int colvarmodule_gpu_calc::calc_cvs(const std::vector& colvars, colvarmodule* colvar_module) { +int colvarmodule_gpu_calc::calc_cvs(const std::vector& colvars, colvarmodule* cvmodule) { int error_code = COLVARS_OK; #define checkColvarsError(stmt) do { \ error_code |= stmt; \ if (error_code != COLVARS_OK) return error_code;\ } while (0); - colvarproxy* p = colvar_module->proxy; + colvarproxy* p = cvmodule->proxy; // Update flags checkColvarsError(cv_update_flags(colvars)); // Calculate total force - if (colvar_module->step_relative() > 0) { - checkColvarsError(cvc_calc_total_force(colvars, colvar_module, false)); + if (cvmodule->step_relative() > 0) { + checkColvarsError(cvc_calc_total_force(colvars, cvmodule, false)); } // Read data to atom groups checkColvarsError(atom_group_read_data_gpu( - colvars, read_data_compute, colvar_module)); + colvars, read_data_compute, cvmodule)); // Wait for extra information (for example, lattice) from the MD engine // before the CPU loop checkColvarsError(p->wait_for_extra_info_ready()); // Calculate CVC values - checkColvarsError(cvc_calc_value(colvars, colvar_module)); + checkColvarsError(cvc_calc_value(colvars, cvmodule)); // Calculate CVC gradients - checkColvarsError(cvc_calc_gradients(colvars, colvar_module)); + checkColvarsError(cvc_calc_gradients(colvars, cvmodule)); // Calculate fit gradients for atom groups checkColvarsError(atom_group_calc_fit_gradients( - colvars, calc_fit_gradients_compute, colvar_module)); + colvars, calc_fit_gradients_compute, cvmodule)); // Debug gradients - checkColvarsError(cvc_debug_gradients(colvars, colvar_module)); + checkColvarsError(cvc_debug_gradients(colvars, cvmodule)); // Calculate the Jacobian terms - checkColvarsError(cvc_calc_Jacobian_derivative(colvars, colvar_module)); + checkColvarsError(cvc_calc_Jacobian_derivative(colvars, cvmodule)); // Calculate total force - checkColvarsError(cvc_calc_total_force(colvars, colvar_module, true)); + checkColvarsError(cvc_calc_total_force(colvars, cvmodule, true)); // Collect CVC data - checkColvarsError(cv_collect_cvc_data(colvars, colvar_module)); + checkColvarsError(cv_collect_cvc_data(colvars, cvmodule)); #undef checkColvarsError return error_code; } -int colvarmodule_gpu_calc::apply_forces(const std::vector& colvars, colvarmodule* colvar_module) { +int colvarmodule_gpu_calc::apply_forces(const std::vector& colvars, colvarmodule* cvmodule) { int error_code = COLVARS_OK; #define checkColvarsError(stmt) do { \ error_code |= stmt; \ if (error_code != COLVARS_OK) return error_code;\ } while (0); - colvarproxy* p = colvar_module->proxy; + colvarproxy* p = cvmodule->proxy; if (!apply_forces_compute.graph_exec_initialized) { forced_atom_groups.clear(); // Find all unique atom groups requiring forces @@ -523,7 +523,7 @@ int colvarmodule_gpu_calc::apply_forces(const std::vector& colvars, col for (auto cvi = colvars.begin(); cvi != colvars.end(); cvi++) { if ((*cvi)->is_enabled(colvardeps::f_cv_apply_force)) { (*cvi)->communicate_forces(); - if (colvar_module->get_error()) { + if (cvmodule->get_error()) { return COLVARS_ERROR; } } @@ -547,9 +547,9 @@ int colvarmodule_gpu_calc::apply_forces(const std::vector& colvars, col checkColvarsError(checkGPUError(cudaGraphInstantiate(&apply_forces_compute.graph_exec, apply_forces_compute.graph))); apply_forces_compute.graph_exec_initialized = true; // Debug graph - if (colvar_module->debug()) { - const std::string filename = cvm::output_prefix() + "_apply_forces.dot"; - colvar_module->log("Writing apply forces graph to " + filename); + if (cvmodule->debug()) { + const std::string filename = cvmodule->output_prefix() + "_apply_forces.dot"; + cvmodule->log("Writing apply forces graph to " + filename); apply_forces_compute.dump_graph(filename.c_str()); } } else { @@ -560,7 +560,7 @@ int colvarmodule_gpu_calc::apply_forces(const std::vector& colvars, col for (auto cvi = colvars.begin(); cvi != colvars.end(); cvi++) { if ((*cvi)->is_enabled(colvardeps::f_cv_apply_force)) { (*cvi)->communicate_forces(); - if (colvar_module->get_error()) { + if (cvmodule->get_error()) { return COLVARS_ERROR; } } diff --git a/src/colvar_gpu_calc.h b/src/colvar_gpu_calc.h index aaf0bd60e..4d68ba01c 100644 --- a/src/colvar_gpu_calc.h +++ b/src/colvar_gpu_calc.h @@ -22,16 +22,16 @@ namespace colvars_gpu { * @note This class is basically a GPU version of colvarmodule::calc_colvars(). * In the future, the atom groups are supposed to be shared among CVCs, * so instead of iterating over all colvars and computing them one by one, - * this class will flatten the colvardeps* tree, then compute all + * this class will flatten the colvardeps* tree, then compute all * atom groups in one pass with CUDA graphs, then all CVCs, and finally * collect the colvar values. */ class colvarmodule_gpu_calc { public: /** - * @brief A struct for holding a compute node in the CUDA graph + * @brief A struct for holding a compute node in the CUDA graph * and its corresponding atom group or CVC (child of colvardeps) - * + * * @note There should be an independent data structure for AST * For the time being I have to hack the colvardeps which serves * partially as an AST (without any type information). There are two @@ -80,7 +80,7 @@ class colvarmodule_gpu_calc { ~colvarmodule_gpu_calc() {} /** * @brief Initialize all the GPU compute graphs - * + * * @return COLVARS_OK if succeeded */ int init(); @@ -91,7 +91,7 @@ class colvarmodule_gpu_calc { * 1. Call `cv_update_flags` to update the flags of all colvars and cvcs * 2. If the current step is greater than 0, call `cvc_calc_total_force` * to calculate the total force on each CVC - * 3. Call `atom_group_read_data_gpu` to read the atom positions to GPU + * 3. Call `atom_group_read_data_gpu` to read the atom positions to GPU * buffers and calculate the required properties * 4. Call `cvc_calc_value` to calculate the values of all CVCs * 5. Call `cvc_calc_gradients` to calculate the gradients of all CVCs @@ -104,10 +104,10 @@ class colvarmodule_gpu_calc { * launched for "atom_group_read_data_gpu" and "atom_group_calc_fit_gradients". * * @param[in] colvars A vector of all colvar objects - * @param[in] colvar_module The main colvarmodule object + * @param[in] cvmodule The main colvarmodule object * @return COLVARS_OK if succeeded */ - int calc_cvs(const std::vector& colvars, colvarmodule* colvar_module); + int calc_cvs(const std::vector& colvars, colvarmodule* cvmodule); /** * @brief Apply the forces to the atom groups from the CVCs * @@ -115,10 +115,10 @@ class colvarmodule_gpu_calc { * instantiated. On subsequent calls, the existing CUDA graph will be launched. * * @param[in] colvars A vector of all colvar objects - * @param[in] colvar_module The main colvarmodule object + * @param[in] cvmodule The main colvarmodule object * @return COLVARS_OK if succeeded */ - int apply_forces(const std::vector& colvars, colvarmodule* colvar_module); + int apply_forces(const std::vector& colvars, colvarmodule* cvmodule); private: /// \brief CUDA graph for reading data to GPU and calculating required properties compute_gpu_graph_t read_data_compute; @@ -153,31 +153,31 @@ class colvarmodule_gpu_calc { int cv_update_flags(const std::vector& colvars); int cvc_calc_total_force( const std::vector& colvars, - colvarmodule* colvar_module, + colvarmodule* cvmodule, bool use_current_step = false); int atom_group_read_data_gpu( const std::vector& colvars, colvarmodule_gpu_calc::compute_gpu_graph_t& g, - colvarmodule* colvar_module); + colvarmodule* cvmodule); int cvc_calc_value( const std::vector& colvars, - colvarmodule* colvar_module); + colvarmodule* cvmodule); int cvc_calc_gradients( const std::vector& colvars, - colvarmodule* colvar_module); + colvarmodule* cvmodule); int atom_group_calc_fit_gradients( const std::vector& colvars, colvarmodule_gpu_calc::compute_gpu_graph_t& g, - colvarmodule* colvar_module); + colvarmodule* cvmodule); int cvc_debug_gradients( const std::vector& colvars, - colvarmodule* colvar_module); + colvarmodule* cvmodule); int cvc_calc_Jacobian_derivative( const std::vector& colvars, - colvarmodule* colvar_module); + colvarmodule* cvmodule); int cv_collect_cvc_data( const std::vector& colvars, - colvarmodule* colvar_module); + colvarmodule* cvmodule); /// @} }; } diff --git a/src/colvar_gpu_support.cpp b/src/colvar_gpu_support.cpp index 29307f241..0fecaf699 100644 --- a/src/colvar_gpu_support.cpp +++ b/src/colvar_gpu_support.cpp @@ -24,7 +24,7 @@ int gpuAssert(cudaError_t code, const char *file, int line) error += "\nBacktrace:\n" + std::to_string(std::stacktrace::current()) + "\n"; #endif #endif - return cvm::error(error, COLVARS_ERROR); + return cvm::error_static(error, COLVARS_ERROR); } return COLVARS_OK; } @@ -45,7 +45,7 @@ int add_clear_array_node_impl( memsetParams.width = width; memsetParams.height = 1; if (cvm::debug()) { - cvm::log( + cvm::log_static( "Add a memset clear node: ptr = " + cvm::to_str(dst) + " width = " + cvm::to_str(width) + " elementSize = " + cvm::to_str(elementSize) + "\n"); @@ -60,7 +60,7 @@ int add_copy_node_impl( cudaMemcpyKind kind, cudaGraphNode_t& node_out, cudaGraph_t& graph, const std::vector& dependencies) { if (cvm::debug()) { - cvm::log( + cvm::log_static( "Add a memcpy node: src = " + cvm::to_str(src) + " dst = " + cvm::to_str(dst) + " num_elements = " + cvm::to_str(num_elements) + "\n"); @@ -82,15 +82,15 @@ int prepare_dependencies( if (auto search = map.find(node_name); search != map.end()) { dependencies.push_back(search->second); if (cvm::debug()) { - cvm::log("Operation " + caller_operation_name + + cvm::log_static("Operation " + caller_operation_name + " depends on node\" " + node_name + "\"\n"); } } else { if (!allow_not_found) { - error_code |= cvm::error("BUG: cannot find node " + node_name + "\n"); + error_code |= cvm::error_static("BUG: cannot find node " + node_name + "\n"); } else { if (cvm::debug()) { - cvm::log("Operation " + caller_operation_name + + cvm::log_static("Operation " + caller_operation_name + " cannot depend on node\" " + node_name + "\"\n"); } } diff --git a/src/colvar_neuralnetworkcompute.cpp b/src/colvar_neuralnetworkcompute.cpp index b77db0cfa..ffbbda73b 100644 --- a/src/colvar_neuralnetworkcompute.cpp +++ b/src/colvar_neuralnetworkcompute.cpp @@ -13,6 +13,7 @@ #include "colvar_neuralnetworkcompute.h" #include "colvarparse.h" #include "colvarproxy.h" +#include "colvarmodule.h" namespace neuralnetworkCV { std::map, std::function>> activation_function_map @@ -34,17 +35,18 @@ std::map, std::functionsetExpression(source.expression); @@ -73,31 +75,31 @@ void customActivationFunction::setExpression(const std::string& expression_strin try { parsed_expression = Lepton::Parser::parse(expression); } catch (...) { - cvm::error("Error parsing or compiling expression \"" + expression + "\".\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error parsing or compiling expression \"" + expression + "\".\n", COLVARS_INPUT_ERROR); } // compile the expression try { value_evaluator = std::unique_ptr(new Lepton::CompiledExpression(parsed_expression.createCompiledExpression())); } catch (...) { - cvm::error("Error compiling expression \"" + expression + "\".\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error compiling expression \"" + expression + "\".\n", COLVARS_INPUT_ERROR); } // create a compiled expression for the derivative try { gradient_evaluator = std::unique_ptr(new Lepton::CompiledExpression(parsed_expression.differentiate(activation_input_variable).createCompiledExpression())); } catch (...) { - cvm::error("Error creating compiled expression for variable \"" + activation_input_variable + "\".\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error creating compiled expression for variable \"" + activation_input_variable + "\".\n", COLVARS_INPUT_ERROR); } // get the reference to the input variable in the compiled expression try { input_reference = &(value_evaluator->getVariableReference(activation_input_variable)); } catch (...) { - cvm::error("Error on getting the reference to variable \"" + activation_input_variable + "\" in the compiled expression.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error on getting the reference to variable \"" + activation_input_variable + "\" in the compiled expression.\n", COLVARS_INPUT_ERROR); } // get the reference to the input variable in the compiled derivative expression try { derivative_reference = &(gradient_evaluator->getVariableReference(activation_input_variable)); } catch (...) { - cvm::error("Error on getting the reference to variable \"" + activation_input_variable + "\" in the compiled derivative exprssion.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error on getting the reference to variable \"" + activation_input_variable + "\" in the compiled derivative exprssion.\n", COLVARS_INPUT_ERROR); } } @@ -116,7 +118,14 @@ double customActivationFunction::derivative(double x) const { } #endif -denseLayer::denseLayer(const std::string& weights_file, const std::string& biases_file, const std::function& f, const std::function& df): m_activation_function(f), m_activation_function_derivative(df) { +denseLayer::denseLayer(const std::string& weights_file, + const std::string& biases_file, + const std::function& f, + const std::function& df, + colvarmodule *cvmodule) + : m_activation_function(f), + m_activation_function_derivative(df), + cvmodule(cvmodule) { #ifdef LEPTON m_use_custom_activation = false; #endif @@ -124,9 +133,12 @@ denseLayer::denseLayer(const std::string& weights_file, const std::string& biase } #ifdef LEPTON -denseLayer::denseLayer(const std::string& weights_file, const std::string& biases_file, const std::string& custom_activation_expression) { +denseLayer::denseLayer(const std::string& weights_file, + const std::string& biases_file, + const std::string& custom_activation_expression, + colvarmodule *cvmodule) : cvmodule(cvmodule) { m_use_custom_activation = true; - m_custom_activation_function = customActivationFunction(custom_activation_expression); + m_custom_activation_function = customActivationFunction(custom_activation_expression, cvmodule); readFromFile(weights_file, biases_file); } #endif @@ -136,7 +148,7 @@ void denseLayer::readFromFile(const std::string& weights_file, const std::string m_weights.clear(); m_biases.clear(); std::string line; - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; auto &ifs_weights = proxy->input_stream(weights_file, "weights file"); while (std::getline(ifs_weights, line)) { if (!ifs_weights) { diff --git a/src/colvar_neuralnetworkcompute.h b/src/colvar_neuralnetworkcompute.h index 575ce3b40..8e575731f 100644 --- a/src/colvar_neuralnetworkcompute.h +++ b/src/colvar_neuralnetworkcompute.h @@ -21,6 +21,8 @@ #include "Lepton.h" #endif +class colvarmodule; // Forward declaration + namespace neuralnetworkCV { /// mapping from a string to the activation function and its derivative extern std::map, std::function>> activation_function_map; @@ -32,7 +34,7 @@ class customActivationFunction { /// empty constructor customActivationFunction(); /// construct by an mathematical expression - customActivationFunction(const std::string& expression_string); + customActivationFunction(const std::string& expression_string, colvarmodule *cvmodule); /// copy constructor customActivationFunction(const customActivationFunction& source); /// overload assignment operator @@ -51,6 +53,7 @@ class customActivationFunction { std::unique_ptr gradient_evaluator; double* input_reference; double* derivative_reference; + colvarmodule *cvmodule; }; #endif @@ -60,6 +63,7 @@ class denseLayer { size_t m_output_size; std::function m_activation_function; std::function m_activation_function_derivative; + colvarmodule *cvmodule; #ifdef LEPTON bool m_use_custom_activation; customActivationFunction m_custom_activation_function; @@ -78,13 +82,20 @@ class denseLayer { * @param[in] f activation function * @param[in] df derivative of the activation function */ - denseLayer(const std::string& weights_file, const std::string& biases_file, const std::function& f, const std::function& df); + denseLayer(const std::string& weights_file, + const std::string& biases_file, + const std::function& f, + const std::function& df, + colvarmodule *cvmodule); #ifdef LEPTON /*! @param[in] weights_file filename of the weights file * @param[in] biases_file filename of the biases file * @param[in] custom_activation_expression the expression of the custom activation function */ - denseLayer(const std::string& weights_file, const std::string& biases_file, const std::string& custom_activation_expression); + denseLayer(const std::string& weights_file, + const std::string& biases_file, + const std::string& custom_activation_expression, + colvarmodule *cvmodule); #endif /// read data from file void readFromFile(const std::string& weights_file, const std::string& biases_file); diff --git a/src/colvar_rotation_derivative.cpp b/src/colvar_rotation_derivative.cpp index 97c60eb11..a43372f97 100644 --- a/src/colvar_rotation_derivative.cpp +++ b/src/colvar_rotation_derivative.cpp @@ -6,7 +6,8 @@ #include "cuda/colvar_rotation_derivative_kernel.h" namespace colvars_gpu { -rotation_derivative_gpu::rotation_derivative_gpu(): +rotation_derivative_gpu::rotation_derivative_gpu(colvarmodule* cvmodule_in): + cvmodule(cvmodule_in), m_rot(nullptr), d_pos1x(nullptr), d_pos1y(nullptr), d_pos1z(nullptr), d_pos2x(nullptr), d_pos2y(nullptr), d_pos2z(nullptr), @@ -31,14 +32,14 @@ int rotation_derivative_gpu::init( d_pos2z = d_pos2y + num_atoms_pos2; m_num_atoms_pos1 = num_atoms_pos1; m_num_atoms_pos2 = num_atoms_pos2; - colvarproxy* p = cvm::main()->proxy; + colvarproxy* p = cvmodule->proxy; error_code |= p->reallocate_device(&tmp_Q0Q0, 4 * 4); error_code |= p->reallocate_device(&tmp_Q0Q0_L, 4 * 4 * 4); return error_code; } rotation_derivative_gpu::~rotation_derivative_gpu() { - colvarproxy* p = cvm::main()->proxy; + colvarproxy* p = cvmodule->proxy; p->deallocate_device(&tmp_Q0Q0); p->deallocate_device(&tmp_Q0Q0_L); tmp_Q0Q0 = nullptr; diff --git a/src/colvar_rotation_derivative.h b/src/colvar_rotation_derivative.h index 0cfd33933..f7d7ec1a3 100644 --- a/src/colvar_rotation_derivative.h +++ b/src/colvar_rotation_derivative.h @@ -620,6 +620,8 @@ struct rotation_derivative { #if defined(COLVARS_CUDA) || defined(COLVARS_HIP) namespace colvars_gpu { struct rotation_derivative_gpu { + /// \brief Pointer to the parent colvarmodule + colvarmodule* cvmodule; /// \brief Reference to the rotation const colvars_gpu::rotation_gpu *m_rot; /// \brief Reference to the atom positions of group 1 @@ -641,7 +643,7 @@ struct rotation_derivative_gpu { * * The object of this class is expected to be constructed on host-pinned memory. */ - rotation_derivative_gpu(); + rotation_derivative_gpu(colvarmodule* cmodule_in); /*! @brief Initialization of the rotation_derivative_gpu class * @param[in] rot The colvars_gpu::rotation_gpu object * @param[in] pos1 The atom positions of group 1 diff --git a/src/colvaratoms.cpp b/src/colvaratoms.cpp index 928001bc8..56d750fed 100644 --- a/src/colvaratoms.cpp +++ b/src/colvaratoms.cpp @@ -29,7 +29,7 @@ cvm::atom_group::simple_atom cvm::atom_group::init_atom_from_proxy( std::string const &atom_name, std::string const &segment_id) { int atom_proxy_index = p->init_atom(residue, atom_name, segment_id); - if (cvm::get_error()) { + if (p->cvmodule->get_error()) { // Error condition already reported by p->init_atom() // return bogus atom, counting on caller to check for errors return cvm::atom_group::simple_atom{ @@ -102,7 +102,7 @@ cvm::atom_group::atom_group(): { #if defined (COLVARS_CUDA) || defined (COLVARS_HIP) gpu_atom_group = std::unique_ptr( - new colvars_gpu::colvaratoms_gpu()); + new colvars_gpu::colvaratoms_gpu(cvmodule)); #endif key = "unnamed"; init(); @@ -116,7 +116,7 @@ cvm::atom_group::atom_group(char const *key_in): atom_group() { cvm::atom_group::~atom_group() { clear_soa(); if (is_enabled(f_ag_scalable) && !b_dummy) { - (cvm::main()->proxy)->clear_atom_group(index); + (cvmodule->proxy)->clear_atom_group(index); index = -1; } @@ -136,14 +136,14 @@ cvm::atom_group::atom_modifier::atom_modifier(cvm::atom_group* ag): m_ag(ag) if (m_ag->modify_lock.try_lock()) { update_from_soa(); } else { - throw cvm::error( + throw m_ag->cvmodule->error( "You are trying to modify the SOA atom group more than once at the same time", COLVARS_BUG_ERROR); } } cvm::atom_group::atom_modifier::~atom_modifier() { - if (cvm::get_error() == COLVARS_OK) { + if (m_ag->cvmodule->get_error() == COLVARS_OK) { sync_to_soa(); } m_ag->modify_lock.unlock(); @@ -214,7 +214,7 @@ int cvm::atom_group::init_dependencies() { // check that everything is initialized for (i = 0; i < colvardeps::f_ag_ntot; i++) { if (is_not_set(i)) { - cvm::error("Uninitialized feature " + cvm::to_str(i) + " in " + description); + cvmodule->error("Uninitialized feature " + cvm::to_str(i) + " in " + description); } } } @@ -246,10 +246,10 @@ int cvm::atom_group::init_dependencies() { int cvm::atom_group::setup() { // TODO: What should I do? // if (atoms_ids.size() == 0) { - // cvm::error("Bug: atoms_ids is empty!", COLVARS_BUG_ERROR); + // cvmodule->error("Bug: atoms_ids is empty!", COLVARS_BUG_ERROR); // } // Update masses and charges - const colvarproxy *p = cvm::proxy; + const colvarproxy *p = cvmodule->proxy; if (!b_dummy && !is_enabled(f_ag_scalable)) { atoms_charge.resize(size()); atoms_mass.resize(size()); @@ -292,9 +292,9 @@ void cvm::atom_group::atom_modifier::sync_to_soa() const { m_ag->atoms_grad.resize(3 * m_ag->num_atoms); m_ag->atoms_total_force.resize(3 * m_ag->num_atoms); m_ag->atoms_weight.resize(m_ag->num_atoms); - // colvarproxy *p = cvm::main()->proxy; + // colvarproxy *p = cvmodule->proxy; if (m_ag->atoms_ids.size() != m_atoms.size()) { - cvm::error("Number of atom IDs does not match the number of atoms!\n", + m_ag->cvmodule->error("Number of atom IDs does not match the number of atoms!\n", COLVARS_BUG_ERROR); } // for (size_t i = 0; i < m_ag->atoms_ids.size(); ++i) { @@ -329,12 +329,12 @@ void cvm::atom_group::atom_modifier::sync_to_soa() const { int cvm::atom_group::atom_modifier::add_atom(const simple_atom& a) { if (a.id < 0) { - return cvm::error("Error: invalid atom number " + cvm::to_str(a.id), COLVARS_INPUT_ERROR); + return m_ag->cvmodule->error("Error: invalid atom number " + cvm::to_str(a.id), COLVARS_INPUT_ERROR); } auto map_it = m_atoms_ids_count.find(a.id); if (map_it != m_atoms_ids_count.end()) { if (cvm::debug()) { - cvm::log("Discarding doubly counted atom with number "+ + m_ag->cvmodule->log("Discarding doubly counted atom with number "+ cvm::to_str(a.id+1)+".\n"); } map_it->second++; @@ -354,16 +354,16 @@ int cvm::atom_group::atom_modifier::add_atom(const simple_atom& a) { int cvm::atom_group::atom_modifier::remove_atom(atom_modifier::atom_iter ai) { if (m_ag->is_enabled(f_ag_scalable)) { - cvm::error("Error: cannot remove atoms from a scalable group.\n", COLVARS_INPUT_ERROR); + m_ag->cvmodule->error("Error: cannot remove atoms from a scalable group.\n", COLVARS_INPUT_ERROR); return COLVARS_ERROR; } if (!this->size()) { - cvm::error("Error: trying to remove an atom from an empty group.\n", COLVARS_INPUT_ERROR); + m_ag->cvmodule->error("Error: trying to remove an atom from an empty group.\n", COLVARS_INPUT_ERROR); return COLVARS_ERROR; } else { if (ai->proxy_index > 0) { - colvarproxy *p = cvm::main()->proxy; + colvarproxy *p = m_ag->cvmodule->proxy; p->clear_atom(ai->proxy_index); } m_total_mass -= ai->mass; @@ -397,19 +397,19 @@ int cvm::atom_group::atom_modifier::add_atom_numbers(std::string const &numbers_ if (m_ag->is_enabled(f_ag_scalable)) { for (size_t i = 0; i < atom_indexes.size(); i++) { - add_atom_id((cvm::proxy)->check_atom_id(atom_indexes[i])); + add_atom_id((m_ag->cvmodule->proxy)->check_atom_id(atom_indexes[i])); } } else { // if we are handling the group on rank 0, better allocate the vector in one shot m_atoms.reserve(m_atoms.size()+atom_indexes.size()); - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = m_ag->cvmodule->proxy; for (size_t i = 0; i < atom_indexes.size(); i++) { add_atom(init_atom_from_proxy(p, atom_indexes[i])); } } - if (cvm::get_error()) return COLVARS_ERROR; + if (m_ag->cvmodule->get_error()) return COLVARS_ERROR; } else { - return cvm::error("Error: no numbers provided for \"" + return m_ag->cvmodule->error("Error: no numbers provided for \"" "atomNumbers\".\n", COLVARS_INPUT_ERROR); } @@ -428,7 +428,7 @@ int cvm::atom_group::atom_modifier::add_atoms_of_group(atom_group const *ag) { } } else { m_atoms.reserve(m_atoms.size()+source_ids.size()); - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = m_ag->cvmodule->proxy; for (size_t i = 0; i < source_ids.size(); i++) { // We could use the atom copy constructor, but only if the source // group is not scalable - whereas this works in both cases @@ -437,9 +437,9 @@ int cvm::atom_group::atom_modifier::add_atoms_of_group(atom_group const *ag) { } } - if (cvm::get_error()) return COLVARS_ERROR; + if (m_ag->cvmodule->get_error()) return COLVARS_ERROR; } else { - cvm::error("Error: source atom group contains no atoms\".\n", COLVARS_INPUT_ERROR); + m_ag->cvmodule->error("Error: source atom group contains no atoms\".\n", COLVARS_INPUT_ERROR); return COLVARS_ERROR; } @@ -448,9 +448,9 @@ int cvm::atom_group::atom_modifier::add_atoms_of_group(atom_group const *ag) { int cvm::atom_group::atom_modifier::add_index_group(std::string const &index_group_name, bool silent) { std::vector const &index_group_names = - cvm::main()->index_group_names; + m_ag->cvmodule->index_group_names; std::vector *> const &index_groups = - cvm::main()->index_groups; + m_ag->cvmodule->index_groups; size_t i_group = 0; for ( ; i_group < index_groups.size(); i_group++) { if (index_group_names[i_group] == index_group_name) @@ -460,7 +460,7 @@ int cvm::atom_group::atom_modifier::add_index_group(std::string const &index_gro if (silent) return COLVARS_INPUT_ERROR; else - return cvm::error("Error: could not find index group "+ + return m_ag->cvmodule->error("Error: could not find index group "+ index_group_name+" among those already provided.\n", COLVARS_INPUT_ERROR); } @@ -473,11 +473,11 @@ int cvm::atom_group::atom_modifier::add_index_group(std::string const &index_gro if (m_ag->is_enabled(f_ag_scalable)) { for (size_t i = 0; i < index_group.size(); i++) { - error_code |= add_atom_id((cvm::proxy)->check_atom_id(index_group[i])); + error_code |= add_atom_id((m_ag->cvmodule->proxy)->check_atom_id(index_group[i])); } } else { m_atoms.reserve(m_atoms.size()+index_group.size()); - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = m_ag->cvmodule->proxy; for (size_t i = 0; i < index_group.size(); i++) { error_code |= add_atom(init_atom_from_proxy(p, index_group[i])); } @@ -499,20 +499,20 @@ int cvm::atom_group::atom_modifier::add_atom_numbers_range(std::string const &ra if (m_ag->is_enabled(f_ag_scalable)) { for (int anum = initial; anum <= final; anum++) { - add_atom_id((cvm::proxy)->check_atom_id(anum)); + add_atom_id((m_ag->cvmodule->proxy)->check_atom_id(anum)); } } else { m_atoms.reserve(m_atoms.size() + (final - initial + 1)); - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = m_ag->cvmodule->proxy; for (int anum = initial; anum <= final; anum++) { add_atom(init_atom_from_proxy(p, anum)); } } } - if (cvm::get_error()) return COLVARS_ERROR; + if (m_ag->cvmodule->get_error()) return COLVARS_ERROR; } else { - cvm::error("Error: no valid definition for \"atomNumbersRange\", \""+ + m_ag->cvmodule->error("Error: no valid definition for \"atomNumbersRange\", \""+ range_conf+"\".\n", COLVARS_INPUT_ERROR); return COLVARS_ERROR; } @@ -537,32 +537,32 @@ int cvm::atom_group::atom_modifier::add_atom_name_residue_range( if (m_ag->is_enabled(f_ag_scalable)) { for (int resid = initial; resid <= final; resid++) { - add_atom_id((cvm::proxy)->check_atom_id(resid, atom_name, psf_segid)); + add_atom_id((m_ag->cvmodule->proxy)->check_atom_id(resid, atom_name, psf_segid)); } } else { m_atoms.reserve(m_atoms.size() + (final - initial + 1)); - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = m_ag->cvmodule->proxy; for (int resid = initial; resid <= final; resid++) { add_atom(init_atom_from_proxy(p, resid, atom_name, psf_segid)); } } - if (cvm::get_error()) return COLVARS_ERROR; + if (m_ag->cvmodule->get_error()) return COLVARS_ERROR; } else { - cvm::error("Error: cannot parse definition for \"" + m_ag->cvmodule->error("Error: cannot parse definition for \"" "atomNameResidueRange\", \""+ range_conf+"\".\n"); return COLVARS_ERROR; } } else { - cvm::error("Error: atomNameResidueRange with empty definition.\n"); + m_ag->cvmodule->error("Error: atomNameResidueRange with empty definition.\n"); return COLVARS_ERROR; } return COLVARS_OK; } void cvm::atom_group::clear_soa() { - colvarproxy* p = cvm::main()->proxy; + colvarproxy* p = cvmodule->proxy; for (size_t i = 0; i < atoms_index.size(); ++i) { p->clear_atom(atoms_index[i]); } @@ -586,7 +586,7 @@ void cvm::atom_group::clear_soa() { int cvm::atom_group::parse(std::string const &group_conf) { - cvm::log("Initializing atom group \""+key+"\".\n"); + cvmodule->log("Initializing atom group \""+key+"\".\n"); // whether or not to include messages in the log // colvarparse::Parse_Mode mode = parse_silent; @@ -601,14 +601,14 @@ int cvm::atom_group::parse(std::string const &group_conf) // Optional group name will let other groups reuse atom definition if (get_keyval(group_conf, "name", name)) { - if ((cvm::atom_group_soa_by_name(this->name) != NULL) && - (cvm::atom_group_soa_by_name(this->name) != this)) { - cvm::error("Error: this atom group cannot have the same name, \""+this->name+ + if ((cvmodule->atom_group_soa_by_name(this->name) != NULL) && + (cvmodule->atom_group_soa_by_name(this->name) != this)) { + cvmodule->error("Error: this atom group cannot have the same name, \""+this->name+ "\", as another atom group.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } - cvm::main()->register_named_atom_group_soa(this); + cvmodule->register_named_atom_group_soa(this); description = "atom group " + name; } @@ -620,7 +620,7 @@ int cvm::atom_group::parse(std::string const &group_conf) b_defined_center |= get_keyval_feature(this, group_conf, "centerToReference", f_ag_center, is_enabled(f_ag_center)); if (is_enabled(f_ag_center_origin) && ! is_enabled(f_ag_center)) { - return cvm::error("centerToReference may not be disabled if centerToOrigin" + return cvmodule->error("centerToReference may not be disabled if centerToOrigin" "is enabled.\n", COLVARS_INPUT_ERROR); } // Legacy alias @@ -629,7 +629,7 @@ int cvm::atom_group::parse(std::string const &group_conf) if (is_enabled(f_ag_rotate) || is_enabled(f_ag_center) || is_enabled(f_ag_center_origin)) { - cvm::main()->cite_feature("Moving frame of reference"); + cvmodule->cite_feature("Moving frame of reference"); } // is the user setting explicit options? @@ -642,9 +642,9 @@ int cvm::atom_group::parse(std::string const &group_conf) { std::string atoms_of = ""; if (get_keyval(group_conf, "atomsOfGroup", atoms_of)) { - atom_group * ag = atom_group_soa_by_name(atoms_of); + atom_group * ag = cvmodule->atom_group_soa_by_name(atoms_of); if (ag == NULL) { - cvm::error("Error: cannot find atom group with name " + atoms_of + ".\n"); + cvmodule->error("Error: cannot find atom group with name " + atoms_of + ".\n"); return COLVARS_ERROR; } auto modify_atoms = get_atom_modifier(); @@ -694,7 +694,7 @@ int cvm::atom_group::parse(std::string const &group_conf) std::vector::iterator psii; for (psii = psf_segids.begin(); psii < psf_segids.end(); ++psii) { if ( (psii->size() == 0) || (psii->size() > 4) ) { - cvm::error("Error: invalid PSF segment identifier provided, \""+ + cvmodule->error("Error: invalid PSF segment identifier provided, \""+ (*psii)+"\".\n", COLVARS_INPUT_ERROR); } } @@ -707,7 +707,7 @@ int cvm::atom_group::parse(std::string const &group_conf) &range_conf, &pos)) { range_count++; if (psf_segids.size() && (range_count > psf_segids.size())) { - cvm::error("Error: more instances of \"atomNameResidueRange\" than " + cvmodule->error("Error: more instances of \"atomNameResidueRange\" than " "values of \"psfSegID\".\n", COLVARS_INPUT_ERROR); } else { auto modify_atoms = get_atom_modifier(); @@ -726,23 +726,23 @@ int cvm::atom_group::parse(std::string const &group_conf) std::string atoms_col; if (!get_keyval(group_conf, "atomsCol", atoms_col, std::string(""))) { - cvm::error("Error: parameter atomsCol is required if atomsFile is set.\n", + cvmodule->error("Error: parameter atomsCol is required if atomsFile is set.\n", COLVARS_INPUT_ERROR); } double atoms_col_value; bool const atoms_col_value_defined = get_keyval(group_conf, "atomsColValue", atoms_col_value, 0.0); if (atoms_col_value_defined && (!atoms_col_value)) { - cvm::error("Error: atomsColValue, if provided, must be non-zero.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: atomsColValue, if provided, must be non-zero.\n", COLVARS_INPUT_ERROR); } - error_code |= cvm::main()->proxy->load_atoms_pdb(atoms_file_name.c_str(), *this, atoms_col, + error_code |= cvmodule->proxy->load_atoms_pdb(atoms_file_name.c_str(), *this, atoms_col, atoms_col_value); } } // Catch any errors from all the initialization steps above - if (error_code || cvm::get_error()) return (error_code || cvm::get_error()); + if (error_code || cvmodule->get_error()) return (error_code || cvmodule->get_error()); // checks of doubly-counted atoms have been handled by add_atom() already @@ -754,7 +754,7 @@ int cvm::atom_group::parse(std::string const &group_conf) } else { if (!(atoms_ids.size())) { - error_code |= cvm::error("Error: no atoms defined for atom group \"" + key + "\".\n", + error_code |= cvmodule->error("Error: no atoms defined for atom group \"" + key + "\".\n", COLVARS_INPUT_ERROR); } @@ -768,8 +768,8 @@ int cvm::atom_group::parse(std::string const &group_conf) error_code |= parse_fitting_options(group_conf); if (is_enabled(f_ag_scalable) && !b_dummy) { - cvm::log("Enabling scalable calculation for group \""+this->key+"\".\n"); - index = (cvm::proxy)->init_atom_group(atoms_ids); + cvmodule->log("Enabling scalable calculation for group \""+this->key+"\".\n"); + index = (cvmodule->proxy)->init_atom_group(atoms_ids); } bool b_print_atom_ids = false; @@ -779,27 +779,27 @@ int cvm::atom_group::parse(std::string const &group_conf) setup(); if (cvm::debug()) - cvm::log("Done initializing atom group \""+key+"\".\n"); + cvmodule->log("Done initializing atom group \""+key+"\".\n"); { std::string init_msg; init_msg.append("Atom group \""+key+"\" defined with "+ cvm::to_str(atoms_ids.size())+" atoms requested"); - if ((cvm::proxy)->updated_masses()) { + if ((cvmodule->proxy)->updated_masses()) { init_msg.append(": total mass = "+ cvm::to_str(total_mass)); - if ((cvm::proxy)->updated_charges()) { + if ((cvmodule->proxy)->updated_charges()) { init_msg.append(", total charge = "+ cvm::to_str(total_charge)); } } init_msg.append(".\n"); - cvm::log(init_msg); + cvmodule->log(init_msg); } if (b_print_atom_ids) { - cvm::log("Internal definition of the atom group:\n"); - cvm::log(print_atom_ids()); + cvmodule->log("Internal definition of the atom group:\n"); + cvmodule->log(print_atom_ids()); } if (is_enabled(f_ag_rotate)) { @@ -816,32 +816,32 @@ int cvm::atom_group::parse_fitting_options(std::string const &group_conf) { if (is_enabled(f_ag_center) || is_enabled(f_ag_rotate)) { if (b_dummy) - cvm::error("Error: centerToReference or rotateToReference " + cvmodule->error("Error: centerToReference or rotateToReference " "cannot be defined for a dummy atom.\n"); bool b_ref_pos_group = false; std::string fitting_group_conf; if (key_lookup(group_conf, "refPositionsGroup", &fitting_group_conf)) { b_ref_pos_group = true; - cvm::log("Warning: keyword \"refPositionsGroup\" is deprecated: please use \"fittingGroup\" instead.\n"); + cvmodule->log("Warning: keyword \"refPositionsGroup\" is deprecated: please use \"fittingGroup\" instead.\n"); } if (b_ref_pos_group || key_lookup(group_conf, "fittingGroup", &fitting_group_conf)) { // instead of this group, define another group to compute the fit if (fitting_group) { - cvm::error("Error: the atom group \""+ + cvmodule->error("Error: the atom group \""+ key+"\" has already a reference group " "for the rototranslational fit, which was communicated by the " "colvar component. You should not use fittingGroup " "in this case.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } - cvm::log("Within atom group \""+key+"\":\n"); + cvmodule->log("Within atom group \""+key+"\":\n"); fitting_group = new atom_group("fittingGroup"); if (fitting_group->parse(fitting_group_conf) == COLVARS_OK) { fitting_group->check_keywords(fitting_group_conf, "fittingGroup"); - if (cvm::get_error()) { - cvm::error("Error setting up atom group \"fittingGroup\".", COLVARS_INPUT_ERROR); + if (cvmodule->get_error()) { + cvmodule->error("Error setting up atom group \"fittingGroup\".", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } } @@ -857,7 +857,7 @@ int cvm::atom_group::parse_fitting_options(std::string const &group_conf) { if (get_keyval(group_conf, "refPositionsFile", ref_pos_file, std::string(""))) { if (ref_pos_aos.size()) { - cvm::error("Error: cannot specify \"refPositionsFile\" and " + cvmodule->error("Error: cannot specify \"refPositionsFile\" and " "\"refPositions\" at the same time.\n"); } @@ -868,14 +868,14 @@ int cvm::atom_group::parse_fitting_options(std::string const &group_conf) { // if provided, use PDB column to select coordinates bool found = get_keyval(group_conf, "refPositionsColValue", ref_pos_col_value, 0.0); if (found && ref_pos_col_value == 0.0) { - cvm::error("Error: refPositionsColValue, " + cvmodule->error("Error: refPositionsColValue, " "if provided, must be non-zero.\n", COLVARS_INPUT_ERROR); return COLVARS_ERROR; } } ref_pos_aos.resize(group_for_fit->size()); - cvm::load_coords(ref_pos_file.c_str(), &ref_pos_aos, group_for_fit, + cvmodule->load_coords(ref_pos_file.c_str(), &ref_pos_aos, group_for_fit, ref_pos_col, ref_pos_col_value); } @@ -883,7 +883,7 @@ int cvm::atom_group::parse_fitting_options(std::string const &group_conf) { if (is_enabled(f_ag_rotate)) { if (ref_pos_aos.size() != group_for_fit->size()) - cvm::error("Error: the number of reference positions provided("+ + cvmodule->error("Error: the number of reference positions provided("+ cvm::to_str(ref_pos_aos.size())+ ") does not match the number of atoms within \""+ key+ @@ -904,12 +904,12 @@ int cvm::atom_group::parse_fitting_options(std::string const &group_conf) { center_ref_pos(); } else { - cvm::error("Error: no reference positions provided.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: no reference positions provided.\n", COLVARS_INPUT_ERROR); return COLVARS_ERROR; } if (is_enabled(f_ag_rotate) && !noforce) { - cvm::log("Warning: atom group \""+key+ + cvmodule->log("Warning: atom group \""+key+ "\" will be aligned to a fixed orientation given by the reference positions provided. " "If the internal structure of the group changes too much (i.e. its RMSD is comparable " "to its radius of gyration), the optimal rotation and its gradients may become discontinuous. " @@ -941,7 +941,7 @@ int cvm::atom_group::atom_modifier::add_atom_id(int aid) { // for (size_t i = 0; i < m_atoms_ids.size(); i++) { // if (m_atoms_ids[i] == aid) { // if (cvm::debug()) - // cvm::log("Discarding doubly counted atom with number "+ + // cvmodule->log("Discarding doubly counted atom with number "+ // cvm::to_str(aid+1)+".\n"); // return COLVARS_OK; // } @@ -949,7 +949,7 @@ int cvm::atom_group::atom_modifier::add_atom_id(int aid) { auto map_it = m_atoms_ids_count.find(aid); if (map_it != m_atoms_ids_count.end()) { if (cvm::debug()) { - cvm::log("Discarding doubly counted atom with number "+ + m_ag->cvmodule->log("Discarding doubly counted atom with number "+ cvm::to_str(aid+1)+".\n"); } map_it->second++; @@ -965,7 +965,7 @@ int cvm::atom_group::atom_modifier::add_atom_id(int aid) { int cvm::atom_group::set_dummy() { if (atoms_ids.size() > 0) { - return cvm::error("Error: setting group with keyword \""+key+ + return cvmodule->error("Error: setting group with keyword \""+key+ "\" and name \""+name+"\" as dummy, but it already " "contains atoms.\n", COLVARS_INPUT_ERROR); } @@ -977,7 +977,7 @@ int cvm::atom_group::set_dummy_pos(cvm::atom_pos const &pos) { if (b_dummy) { dummy_atom_pos = pos; } else { - return cvm::error("Error: setting dummy position for group with keyword \""+ + return cvmodule->error("Error: setting dummy position for group with keyword \""+ key+"\" and name \""+name+ "\", but it is not dummy.\n", COLVARS_INPUT_ERROR); } @@ -990,12 +990,12 @@ void cvm::atom_group::update_total_mass() { return; } - colvarproxy *p = cvm::main()->proxy; + colvarproxy *p = cvmodule->proxy; if (is_enabled(f_ag_scalable)) { total_mass = p->get_atom_group_mass(index); } else { // total_mass = 0.0 - // for (cvm::atom_iter ai = this->begin(); ai != this->end(); ai++) { + // for (cvmodule->atom_iter ai = this->begin(); ai != this->end(); ai++) { // total_mass += ai->mass; // } total_mass = std::accumulate(atoms_mass.begin(), atoms_mass.end(), 0.0); @@ -1013,7 +1013,7 @@ void cvm::atom_group::update_total_mass() { } } if (total_mass < 1e-15) { - cvm::error("Error: " + description + " has zero total mass.\n"); + cvmodule->error("Error: " + description + " has zero total mass.\n"); } } @@ -1023,12 +1023,12 @@ void cvm::atom_group::update_total_charge() { return; } - colvarproxy *p = cvm::main()->proxy; + colvarproxy *p = cvmodule->proxy; if (is_enabled(f_ag_scalable)) { total_charge = p->get_atom_group_charge(index); } else { // total_charge = 0.0; - // for (cvm::atom_iter ai = this->begin(); ai != this->end(); ai++) { + // for (cvmodule->atom_iter ai = this->begin(); ai != this->end(); ai++) { // total_charge += ai->charge; // } total_charge = std::accumulate(atoms_charge.begin(), atoms_charge.end(), 0.0); @@ -1036,8 +1036,8 @@ void cvm::atom_group::update_total_charge() { } void cvm::atom_group::print_properties(std::string const &colvar_name, int i, int j) { - if (cvm::proxy->updated_masses() && cvm::proxy->updated_charges()) { - cvm::log("Re-initialized atom group for variable \""+colvar_name+"\":"+ + if (cvmodule->proxy->updated_masses() && cvmodule->proxy->updated_charges()) { + cvmodule->log("Re-initialized atom group for variable \""+colvar_name+"\":"+ cvm::to_str(i)+"/"+ cvm::to_str(j)+". "+ cvm::to_str(atoms_ids.size())+ " atoms: total mass = "+cvm::to_str(total_mass)+ @@ -1072,7 +1072,7 @@ int cvm::atom_group::create_sorted_ids() sorted_atoms_ids_list.sort(); sorted_atoms_ids_list.unique(); if (sorted_atoms_ids_list.size() != atoms_ids.size()) { - return cvm::error("Error: duplicate atom IDs in atom group? (found " + + return cvmodule->error("Error: duplicate atom IDs in atom group? (found " + cvm::to_str(sorted_atoms_ids_list.size()) + " unique atom IDs instead of " + cvm::to_str(atoms_ids.size()) + ").\n", COLVARS_BUG_ERROR); @@ -1108,7 +1108,7 @@ void cvm::atom_group::read_positions() { if (b_dummy) return; - colvarproxy *p = cvm::main()->proxy; + colvarproxy *p = cvmodule->proxy; if (!is_enabled(f_ag_scalable)) { for (size_t i = 0; i < num_atoms; ++i) { const int proxy_index = atoms_index[i]; @@ -1209,7 +1209,7 @@ void cvm::atom_group::center_ref_pos() ref_pos_z(i) -= ref_pos_cog.z; } #if defined (COLVARS_CUDA) || defined (COLVARS_HIP) - colvarproxy* p = cvm::main()->proxy; + colvarproxy* p = cvmodule->proxy; if (p->get_smp_mode() == colvarproxy_smp::smp_mode_t::gpu) { gpu_atom_group->setup_rotation(this); } @@ -1230,16 +1230,16 @@ void cvm::atom_group::rotate(const cvm::rmatrix& rot_mat) { void cvm::atom_group::apply_translation(cvm::rvector const &t) { if (b_dummy) { - cvm::error("Error: cannot translate the coordinates of a dummy atom group.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: cannot translate the coordinates of a dummy atom group.\n", COLVARS_INPUT_ERROR); return; } if (is_enabled(f_ag_scalable)) { - cvm::error("Error: cannot translate the coordinates of a scalable atom group.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: cannot translate the coordinates of a scalable atom group.\n", COLVARS_INPUT_ERROR); return; } - // for (cvm::atom_iter ai = this->begin(); ai != this->end(); ai++) { + // for (cvmodule->atom_iter ai = this->begin(); ai != this->end(); ai++) { // ai->pos += t; // } for (size_t i = 0; i < num_atoms; ++i) { @@ -1253,7 +1253,7 @@ void cvm::atom_group::read_velocities() { if (b_dummy) return; - colvarproxy *p = cvm::main()->proxy; + colvarproxy *p = cvmodule->proxy; if (p->get_smp_mode() == colvarproxy_smp::smp_mode_t::gpu) { #if 0 // This is never used. @@ -1284,7 +1284,7 @@ void cvm::atom_group::read_total_forces() { if (b_dummy) return; - colvarproxy *p = cvm::main()->proxy; + colvarproxy *p = cvmodule->proxy; if (p->get_smp_mode() == colvarproxy_smp::smp_mode_t::gpu) { #if defined(COLVARS_CUDA) || defined(COLVARS_HIP) // TODO: At this point, I don't know if read_total_forces @@ -1325,7 +1325,7 @@ void cvm::atom_group::read_total_forces() int cvm::atom_group::calc_required_properties() { // TODO check if the com is needed? - // colvarproxy* p = cvm::main()->proxy; + // colvarproxy* p = cvmodule->proxy; calc_center_of_mass(); calc_center_of_geometry(); @@ -1348,7 +1348,7 @@ int cvm::atom_group::calc_required_properties() // TODO calculate elements of scalable cvc's here before reduction - return (cvm::get_error() ? COLVARS_ERROR : COLVARS_OK); + return (cvmodule->get_error() ? COLVARS_ERROR : COLVARS_OK); } int cvm::atom_group::calc_center_of_geometry() @@ -1357,7 +1357,7 @@ int cvm::atom_group::calc_center_of_geometry() cog = dummy_atom_pos; } else { cog.reset(); - // for (cvm::atom_const_iter ai = this->begin(); ai != this->end(); ai++) { + // for (cvmodule->atom_const_iter ai = this->begin(); ai != this->end(); ai++) { // cog += ai->pos; // } for (size_t i = 0; i < num_atoms; ++i) { @@ -1375,13 +1375,13 @@ int cvm::atom_group::calc_center_of_mass() if (b_dummy) { com = dummy_atom_pos; if (cvm::debug()) { - cvm::log("Dummy atom center of mass = "+cvm::to_str(com)+"\n"); + cvmodule->log("Dummy atom center of mass = "+cvm::to_str(com)+"\n"); } } else if (is_enabled(f_ag_scalable)) { - com = (cvm::proxy)->get_atom_group_com(index); + com = (cvmodule->proxy)->get_atom_group_com(index); } else { com.reset(); - // for (cvm::atom_const_iter ai = this->begin(); ai != this->end(); ai++) { + // for (cvmodule->atom_const_iter ai = this->begin(); ai != this->end(); ai++) { // com += ai->mass * ai->pos; // } for (size_t i = 0; i < num_atoms; ++i) { @@ -1397,11 +1397,11 @@ int cvm::atom_group::calc_center_of_mass() int cvm::atom_group::calc_dipole(cvm::atom_pos const &dipole_center) { if (b_dummy) { - return cvm::error("Error: trying to compute the dipole " + return cvmodule->error("Error: trying to compute the dipole " "of a dummy group.\n", COLVARS_INPUT_ERROR); } dip.reset(); - // for (cvm::atom_const_iter ai = this->begin(); ai != this->end(); ai++) { + // for (cvmodule->atom_const_iter ai = this->begin(); ai != this->end(); ai++) { // dip += ai->charge * (ai->pos - dipole_center); // } for (size_t i = 0; i < num_atoms; ++i) { @@ -1419,7 +1419,7 @@ void cvm::atom_group::set_weighted_gradient(cvm::rvector const &grad) scalar_com_gradient = grad; if (!is_enabled(f_ag_scalable)) { - // for (cvm::atom_iter ai = this->begin(); ai != this->end(); ai++) { + // for (cvmodule->atom_iter ai = this->begin(); ai != this->end(); ai++) { // ai->grad = (ai->mass/total_mass) * grad; // } for (size_t i = 0; i < num_atoms; ++i) { @@ -1435,7 +1435,7 @@ void cvm::atom_group::calc_fit_gradients() if (b_dummy || ! is_enabled(f_ag_fit_gradients)) return; if (cvm::debug()) - cvm::log("Calculating fit gradients.\n"); + cvmodule->log("Calculating fit gradients.\n"); cvm::atom_group *group_for_fit = fitting_group ? fitting_group : this; @@ -1459,7 +1459,7 @@ void cvm::atom_group::calc_fit_gradients() calc_fit_forces_impl(accessor_main, accessor_fitting); if (cvm::debug()) - cvm::log("Done calculating fit gradients.\n"); + cvmodule->log("Done calculating fit gradients.\n"); } template project_force_to_group1(j, dxdC); } if (cvm::debug()) { - cvm::log(cvm::to_str(fitting_force_grad)); + cvmodule->log(cvm::to_str(fitting_force_grad)); } accessor_fitting(j, fitting_force_grad); } @@ -1544,17 +1544,17 @@ void cvm::atom_group::calc_fit_forces( cvm::ag_vector_real_t cvm::atom_group::positions() const { if (b_dummy) { - cvm::error("Error: positions are not available " + cvmodule->error("Error: positions are not available " "from a dummy atom group.\n", COLVARS_INPUT_ERROR); } if (is_enabled(f_ag_scalable)) { - cvm::error("Error: atomic positions are not available " + cvmodule->error("Error: atomic positions are not available " "from a scalable atom group.\n", COLVARS_INPUT_ERROR); } // std::vector x(this->size(), 0.0); - // cvm::atom_const_iter ai = this->begin(); + // cvmodule->atom_const_iter ai = this->begin(); // std::vector::iterator xi = x.begin(); // for ( ; ai != this->end(); ++xi, ++ai) { // *xi = ai->pos; @@ -1566,17 +1566,17 @@ cvm::ag_vector_real_t cvm::atom_group::positions() const cvm::ag_vector_real_t cvm::atom_group::positions_shifted(cvm::rvector const &shift) const { if (b_dummy) { - cvm::error("Error: positions are not available " + cvmodule->error("Error: positions are not available " "from a dummy atom group.\n", COLVARS_INPUT_ERROR); } if (is_enabled(f_ag_scalable)) { - cvm::error("Error: atomic positions are not available " + cvmodule->error("Error: atomic positions are not available " "from a scalable atom group.\n", COLVARS_INPUT_ERROR); } // std::vector x(this->size(), 0.0); - // cvm::atom_const_iter ai = this->begin(); + // cvmodule->atom_const_iter ai = this->begin(); // std::vector::iterator xi = x.begin(); // for ( ; ai != this->end(); ++xi, ++ai) { // *xi = (ai->pos + shift); @@ -1593,12 +1593,12 @@ cvm::ag_vector_real_t cvm::atom_group::positions_shifted(cvm::rvector const &shi std::vector cvm::atom_group::velocities() const { if (b_dummy) { - cvm::error("Error: velocities are not available " + cvmodule->error("Error: velocities are not available " "from a dummy atom group.\n", COLVARS_INPUT_ERROR); } if (is_enabled(f_ag_scalable)) { - cvm::error("Error: atomic velocities are not available " + cvmodule->error("Error: atomic velocities are not available " "from a scalable atom group.\n", COLVARS_INPUT_ERROR); } @@ -1607,12 +1607,12 @@ std::vector cvm::atom_group::velocities() const { std::vector cvm::atom_group::total_forces() const { if (b_dummy) { - cvm::error("Error: velocities are not available " + cvmodule->error("Error: velocities are not available " "from a dummy atom group.\n", COLVARS_INPUT_ERROR); } if (is_enabled(f_ag_scalable)) { - cvm::error("Error: atomic velocities are not available " + cvmodule->error("Error: atomic velocities are not available " "from a scalable atom group.\n", COLVARS_INPUT_ERROR); } @@ -1621,12 +1621,12 @@ std::vector cvm::atom_group::total_forces() const { cvm::rvector cvm::atom_group::total_force() const { if (b_dummy) { - cvm::error("Error: total total forces are not available " + cvmodule->error("Error: total total forces are not available " "from a dummy atom group.\n", COLVARS_INPUT_ERROR); } if (is_enabled(f_ag_scalable)) { - return (cvm::proxy)->get_atom_group_total_force(index); + return (cvmodule->proxy)->get_atom_group_total_force(index); } cvm::rvector f(0, 0, 0); for (size_t i = 0; i < num_atoms; ++i) { @@ -1640,23 +1640,23 @@ cvm::rvector cvm::atom_group::total_force() const { void cvm::atom_group::apply_colvar_force(cvm::real const &force) { if (cvm::debug()) { - log("Communicating a colvar force from atom group to the MD engine.\n"); + cvmodule->log("Communicating a colvar force from atom group to the MD engine.\n"); } if (b_dummy) return; if (noforce) { - cvm::error("Error: sending a force to a group that has " + cvmodule->error("Error: sending a force to a group that has " "\"enableForces\" set to off.\n"); return; } if (is_enabled(f_ag_scalable)) { - (cvm::proxy)->apply_atom_group_force(index, force * scalar_com_gradient); + (cvmodule->proxy)->apply_atom_group_force(index, force * scalar_com_gradient); return; } - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = cvmodule->proxy; if (p->get_smp_mode() == colvarproxy_smp::smp_mode_t::gpu) { #if defined(COLVARS_CUDA) || defined(COLVARS_HIP) gpu_atom_group->apply_colvar_force_from_cpu(force); @@ -1679,7 +1679,7 @@ void cvm::atom_group::apply_colvar_force(cvm::real const &force) p->apply_atom_force(proxy_index, f); } } else { - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = cvmodule->proxy; for (size_t i = 0; i < num_atoms; ++i) { const int proxy_index = atoms_index[i]; const cvm::rvector f{ @@ -1709,19 +1709,19 @@ void cvm::atom_group::apply_colvar_force(cvm::real const &force) void cvm::atom_group::apply_force(cvm::rvector const &force) { if (cvm::debug()) { - log("Communicating a colvar force from atom group to the MD engine.\n"); + cvmodule->log("Communicating a colvar force from atom group to the MD engine.\n"); } if (b_dummy) return; if (noforce) { - cvm::error("Error: sending a force to a group that has " + cvmodule->error("Error: sending a force to a group that has " "\"enableForces\" set to off.\n"); return; } if (is_enabled(f_ag_scalable)) { - (cvm::proxy)->apply_atom_group_force(index, force); + (cvmodule->proxy)->apply_atom_group_force(index, force); return; } @@ -1760,7 +1760,7 @@ void cvm::atom_group::set_ref_pos_from_aos(const std::vector& pos num_ref_pos = pos_aos.size(); ref_pos = cvm::atom_group::pos_aos_to_soa(pos_aos); #if defined (COLVARS_CUDA) || defined (COLVARS_HIP) - colvarproxy* p = cvm::main()->proxy; + colvarproxy* p = cvmodule->proxy; if (p->get_smp_mode() == colvarproxy_smp::smp_mode_t::gpu) { // p->reallocate_device(&gpu_buffers.d_ref_pos, ref_pos.size()); // p->copy_HtoD(ref_pos.data(), gpu_buffers.d_ref_pos, ref_pos.size()); @@ -1777,7 +1777,7 @@ cvm::atom_group::group_force_object::group_force_object(cvm::atom_group* ag): m_ag(ag), m_group_for_fit(m_ag->fitting_group ? m_ag->fitting_group : m_ag), m_has_fitting_force(m_ag->is_enabled(f_ag_center) || m_ag->is_enabled(f_ag_rotate)) { // We need to store the CPU forces in case of the GPU-resident mode - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = m_ag->cvmodule->proxy; if (m_has_fitting_force || p->get_smp_mode() == colvarproxy_smp::smp_mode_t::gpu) { if (m_ag->group_forces.size() != 3 * m_ag->size()) { m_ag->group_forces.assign(3 * m_ag->size(), 0); @@ -1789,7 +1789,7 @@ m_has_fitting_force(m_ag->is_enabled(f_ag_center) || m_ag->is_enabled(f_ag_rotat } cvm::atom_group::group_force_object::~group_force_object() { - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = m_ag->cvmodule->proxy; if (p->get_smp_mode() == colvarproxy_smp::smp_mode_t::gpu) { #if defined (COLVARS_CUDA) || defined (COLVARS_HIP) m_ag->gpu_atom_group->set_use_cpu_group_force(true); @@ -1804,7 +1804,7 @@ cvm::atom_group::group_force_object::~group_force_object() { void cvm::atom_group::group_force_object::add_atom_force( size_t i, const cvm::rvector& force) { - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = m_ag->cvmodule->proxy; if (m_has_fitting_force || p->get_smp_mode() == colvarproxy_smp::smp_mode_t::gpu) { // m_ag->group_forces[i] += force; m_ag->group_forces_x(i) += force.x; @@ -1821,10 +1821,10 @@ void cvm::atom_group::group_force_object::add_atom_force( void cvm::atom_group::group_force_object::apply_force_with_fitting_group() { const cvm::rmatrix rot_inv = m_ag->rot.inverse().matrix(); if (cvm::debug()) { - cvm::log("Applying force on main group " + m_ag->name + ":\n"); + m_ag->cvmodule->log("Applying force on main group " + m_ag->name + ":\n"); } if (m_ag->b_dummy) return; - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = m_ag->cvmodule->proxy; if (m_ag->is_enabled(f_ag_rotate)) { for (size_t ia = 0; ia < m_ag->size(); ++ia) { // const cvm::rvector f_ia = rot_inv * m_ag->group_forces[ia]; @@ -1843,7 +1843,7 @@ void cvm::atom_group::group_force_object::apply_force_with_fitting_group() { }; p->apply_atom_force(proxy_index, f_ia); if (cvm::debug()) { - cvm::log(cvm::to_str(f_ia)); + m_ag->cvmodule->log(cvm::to_str(f_ia)); } } } else { @@ -1855,7 +1855,7 @@ void cvm::atom_group::group_force_object::apply_force_with_fitting_group() { m_ag->group_forces_z(ia)}; p->apply_atom_force(proxy_index, f_ia); if (cvm::debug()) { - cvm::log(cvm::to_str(f_ia)); + m_ag->cvmodule->log(cvm::to_str(f_ia)); } } } @@ -1865,7 +1865,7 @@ void cvm::atom_group::group_force_object::apply_force_with_fitting_group() { // group, but checking this flag can mimic results that the users expect (if // "enableFitGradients no" then there is no force on the fitting group). if (!m_ag->b_dummy && m_ag->is_enabled(f_ag_fit_gradients)) { - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = m_ag->cvmodule->proxy; auto accessor_main = [this](size_t i){ return cvm::rvector(m_ag->group_forces_x(i), m_ag->group_forces_y(i), @@ -1876,11 +1876,11 @@ void cvm::atom_group::group_force_object::apply_force_with_fitting_group() { p->apply_atom_force(proxy_index, fitting_force); }; if (cvm::debug()) { - cvm::log("Applying force on the fitting group of main group" + m_ag->name + ":\n"); + m_ag->cvmodule->log("Applying force on the fitting group of main group" + m_ag->name + ":\n"); } m_ag->calc_fit_forces(accessor_main, accessor_fitting); if (cvm::debug()) { - cvm::log("Done applying force on the fitting group of main group" + m_ag->name + ":\n"); + m_ag->cvmodule->log("Done applying force on the fitting group of main group" + m_ag->name + ":\n"); } } } diff --git a/src/colvaratoms.h b/src/colvaratoms.h index bfc3c6656..717d9a281 100644 --- a/src/colvaratoms.h +++ b/src/colvaratoms.h @@ -49,7 +49,7 @@ * a group never changes. * */ -class cvm::atom_group: public colvarparse, public colvardeps { +class cvm::atom_group: public colvardeps { public: /** * @brief A helper function to re-arrange the a vector of @@ -91,7 +91,7 @@ class cvm::atom_group: public colvarparse, public colvardeps { */ int init_dependencies() override; /// \brief Implementation of the feature list accessor for atom group - const std::vector &features() const override { return ag_features; } + virtual const std::vector &features() const override { return ag_features; } std::vector &modify_features() override { return ag_features; } static void delete_features() { diff --git a/src/colvaratoms_gpu.cpp b/src/colvaratoms_gpu.cpp index 570090aa5..ade4c2011 100644 --- a/src/colvaratoms_gpu.cpp +++ b/src/colvaratoms_gpu.cpp @@ -12,7 +12,8 @@ namespace colvars_gpu { #if defined(COLVARS_CUDA) || defined(COLVARS_HIP) -colvaratoms_gpu::colvaratoms_gpu() { +colvaratoms_gpu::colvaratoms_gpu(colvarmodule *cvmodule_in) + : cvmodule(cvmodule_in) { std::memset(&gpu_buffers, 0, sizeof(gpu_buffers)); std::memset(&debug_graphs, 0, sizeof(debug_graphs)); std::memset(&calc_fit_gradients_gpu_info, 0, sizeof(calc_fit_gradients_gpu_info)); @@ -29,7 +30,7 @@ colvaratoms_gpu::~colvaratoms_gpu() { int colvaratoms_gpu::init_gpu() { int error_code = COLVARS_OK; - colvarproxy *p = cvm::main()->proxy; + colvarproxy *p = cvmodule->proxy; // error_code |= checkGPUError(cudaStreamCreate(&stream)); error_code |= p->reallocate_device(&gpu_buffers.d_com, 1); error_code |= p->reallocate_device(&gpu_buffers.d_com_tmp, 1); @@ -79,7 +80,7 @@ int colvaratoms_gpu::init_gpu() { int colvaratoms_gpu::destroy_gpu() { int error_code = COLVARS_OK; - colvarproxy* p = cvm::main()->proxy; + colvarproxy* p = cvmodule->proxy; error_code |= p->deallocate_device(&gpu_buffers.d_atoms_index); error_code |= p->deallocate_device(&gpu_buffers.d_atoms_pos); error_code |= p->deallocate_device(&gpu_buffers.d_atoms_charge); @@ -131,7 +132,7 @@ int colvaratoms_gpu::destroy_gpu() { int colvaratoms_gpu::sync_to_gpu_buffers(const cvm::atom_group* cpu_atoms) { int error_code = COLVARS_OK; - colvarproxy* p = cvm::main()->proxy; + colvarproxy* p = cvmodule->proxy; #if defined(COLVARS_CUDA) || defined(COLVARS_HIP) error_code |= p->reallocate_device(&this->gpu_buffers.d_atoms_index, cpu_atoms->num_atoms); error_code |= p->reallocate_device(&this->gpu_buffers.d_atoms_charge, cpu_atoms->num_atoms); @@ -157,7 +158,7 @@ int colvaratoms_gpu::sync_to_gpu_buffers(const cvm::atom_group* cpu_atoms) { int colvaratoms_gpu::clear_gpu_buffers(const cvm::atom_group* cpu_atoms) { int error_code = COLVARS_OK; - colvarproxy* p = cvm::main()->proxy; + colvarproxy* p = cvmodule->proxy; size_t num_atoms = cpu_atoms->size(); #if defined(COLVARS_CUDA) || defined(COLVARS_HIP) error_code |= p->clear_device_array(gpu_buffers.d_atoms_index, num_atoms); @@ -205,7 +206,7 @@ int colvaratoms_gpu::add_read_positions_nodes( std::unordered_map& nodes_map) { int error_code = COLVARS_OK; if (cpu_atoms->b_dummy) return error_code; - colvarproxy *p = cvm::main()->proxy; + colvarproxy *p = cvmodule->proxy; if (!cpu_atoms->is_enabled(colvardeps::f_ag_scalable)) { cudaGraphNode_t read_positions_main; std::vector dependencies; @@ -241,7 +242,7 @@ int colvaratoms_gpu::add_calc_required_properties_nodes( if (cpu_atoms->b_dummy) { return error_code; } else if (cpu_atoms->is_enabled(colvardeps::f_ag_scalable)) { - error_code |= cvm::error("BUG: GPU buffers are not implemented with scalable atom group.\n"); + error_code |= cvmodule->error("BUG: GPU buffers are not implemented with scalable atom group.\n"); return error_code; } else { // Add kernel node for COG and COM @@ -534,10 +535,10 @@ int colvaratoms_gpu::after_read_data_sync( if (cpu_atoms->b_dummy) { cpu_atoms->com = cpu_atoms->dummy_atom_pos; if (cvm::debug()) { - cvm::log("Dummy atom center of mass = "+cvm::to_str(cpu_atoms->com)+"\n"); + cvmodule->log("Dummy atom center of mass = "+cvm::to_str(cpu_atoms->com)+"\n"); } } else if (cpu_atoms->is_enabled(colvardeps::f_ag_scalable)) { - cpu_atoms->com = (cvm::proxy)->get_atom_group_com(cpu_atoms->index); + cpu_atoms->com = (cvmodule->proxy)->get_atom_group_com(cpu_atoms->index); } else { cpu_atoms->com.reset(); if (copy_to_cpu) { @@ -692,7 +693,7 @@ int colvaratoms_gpu::add_apply_force_nodes( const std::vector& extra_initial_dependencies) { int error_code = COLVARS_OK; if (cpu_atoms->b_dummy) return error_code; - colvarproxy* p = cvm::main()->proxy; + colvarproxy* p = cvmodule->proxy; // Check if any of the parent CVCs require CPU buffers // Get all parents const std::vector parents = cpu_atoms->get_parents(); @@ -722,7 +723,7 @@ int colvaratoms_gpu::add_apply_force_nodes( if (!all_require_cpu_buffers) { const std::string error = "BUG: either none of the CVCs or " " all of the CVCs require CPU buffers!\n"; - return cvm::error(error); + return cvmodule->error(error); } } cudaGraphNode_t apply_main_colvar_force_to_proxy_node; @@ -858,7 +859,7 @@ int colvaratoms_gpu::read_positions_gpu_debug( size_t change_atom_i, int xyz, bool to_cpu, double sign, cudaStream_t stream) { int error_code = COLVARS_OK; - colvarproxy *p = cvm::main()->proxy; + colvarproxy *p = cvmodule->proxy; error_code |= colvars_gpu::atoms_pos_from_proxy( gpu_buffers.d_atoms_index, p->proxy_atoms_positions_gpu(), gpu_buffers.d_atoms_pos, cpu_atoms->num_atoms, p->get_atom_ids()->size(), @@ -874,12 +875,12 @@ int colvaratoms_gpu::read_positions_gpu_debug( if (!change_fitting_group) { error_code |= colvars_gpu::change_one_coordinate( gpu_buffers.d_atoms_pos, change_atom_i, xyz, - sign * cvm::debug_gradients_step_size, cpu_atoms->num_atoms, stream); + sign * cvmodule->debug_gradients_step_size, cpu_atoms->num_atoms, stream); } else { if (cpu_atoms->fitting_group) { error_code |= colvars_gpu::change_one_coordinate( cpu_atoms->fitting_group->gpu_atom_group->gpu_buffers.d_atoms_pos, change_atom_i, xyz, - sign * cvm::debug_gradients_step_size, cpu_atoms->fitting_group->num_atoms, stream); + sign * cvmodule->debug_gradients_step_size, cpu_atoms->fitting_group->num_atoms, stream); } } if (to_cpu) { @@ -921,11 +922,11 @@ int colvaratoms_gpu::calc_required_properties_gpu_debug( void colvaratoms_gpu::do_feature_side_effects_gpu( cvm::atom_group* cpu_atoms, int id) { if (cvm::debug()) { - cvm::log("cvm::atom_group::do_feature_side_effects_gpu.\n"); + cvmodule->log("cvm::atom_group::do_feature_side_effects_gpu.\n"); } switch (id) { case colvardeps::f_ag_fit_gradients: { - colvarproxy* p = cvm::main()->proxy; + colvarproxy* p = cvmodule->proxy; if (gpu_buffers.d_atoms_pos_unrotated == nullptr) { p->allocate_device(&gpu_buffers.d_atoms_pos_unrotated, 3 * cpu_atoms->num_atoms); } @@ -949,7 +950,7 @@ void colvaratoms_gpu::do_feature_side_effects_gpu( int colvaratoms_gpu::setup_rotation(const cvm::atom_group* cpu_atoms) { int error_code = COLVARS_OK; - colvarproxy* p = cvm::main()->proxy; + colvarproxy* p = cvmodule->proxy; error_code |= p->reallocate_device(&gpu_buffers.d_ref_pos, cpu_atoms->ref_pos.size()); error_code |=p->copy_HtoD(cpu_atoms->ref_pos.data(), gpu_buffers.d_ref_pos, cpu_atoms->ref_pos.size()); error_code |=p->copy_HtoD(&cpu_atoms->ref_pos_cog, gpu_buffers.d_ref_pos_cog, 1); @@ -960,13 +961,13 @@ int colvaratoms_gpu::setup_rotation(const cvm::atom_group* cpu_atoms) { int colvaratoms_gpu::setup_rotation_derivative(const cvm::atom_group* cpu_atoms) { int error_code = COLVARS_OK; auto* group_for_fit = cpu_atoms->fitting_group ? cpu_atoms->fitting_group : cpu_atoms; - colvarproxy* p = cvm::main()->proxy; + colvarproxy* p = cvmodule->proxy; if (rot_deriv_gpu != nullptr) { rot_deriv_gpu->~rotation_derivative_gpu(); error_code |= p->deallocate_host(&rot_deriv_gpu); } error_code |= p->allocate_host(&rot_deriv_gpu, 1); - rot_deriv_gpu = new (rot_deriv_gpu) colvars_gpu::rotation_derivative_gpu(); + rot_deriv_gpu = new (rot_deriv_gpu) colvars_gpu::rotation_derivative_gpu(cvmodule); error_code |= rot_deriv_gpu->init( &rot_gpu, group_for_fit->gpu_atom_group->gpu_buffers.d_atoms_pos, @@ -976,7 +977,7 @@ int colvaratoms_gpu::setup_rotation_derivative(const cvm::atom_group* cpu_atoms) int colvaratoms_gpu::read_total_forces(cvm::atom_group* cpu_atoms) { int error_code = COLVARS_OK; - colvarproxy *p = cvm::main()->proxy; + colvarproxy *p = cvmodule->proxy; cvm::quaternion* q_ptr = nullptr; if (cpu_atoms->is_enabled(colvardeps::f_ag_rotate)) { q_ptr = rot_gpu.get_q(); diff --git a/src/colvaratoms_gpu.h b/src/colvaratoms_gpu.h index 80b24136f..580d4a423 100644 --- a/src/colvaratoms_gpu.h +++ b/src/colvaratoms_gpu.h @@ -99,7 +99,7 @@ class colvaratoms_gpu { * * All variables are expected to initialize to 0. */ - colvaratoms_gpu(); + colvaratoms_gpu(colvarmodule *cvmodule_in); /** * @brief Destructor */ @@ -176,7 +176,7 @@ class colvaratoms_gpu { std::unordered_map& nodes_map); /** * @brief Add nodes for calculating the required properties to the CUDA graph - * + * * This function adds nodes for calculating COM, COG, rotation matrix, * rotated positions, and reference COG to the CUDA graph. * @@ -185,7 +185,7 @@ class colvaratoms_gpu { * @param[in,out] nodes_map A map to store the added nodes with operation name * @param[in] extra_initial_dependencies Additional dependencies to be added * to the initial nodes - * @return COLVARS_OK if succeeded + * @return COLVARS_OK if succeeded */ int add_calc_required_properties_nodes( const cvm::atom_group* cpu_atoms, cudaGraph_t& graph, @@ -207,7 +207,7 @@ class colvaratoms_gpu { std::unordered_map& nodes_map); /** * @brief Update the CPU COM, COG and rotation object after GPU synchronization - * + * * @param[in] cpu_atoms CPU atom group class * @param[in] copy_to_cpu If true, copy the COM, COG and rotation object to CPU buffers * @param[in] stream CUDA stream to be synchronized @@ -221,7 +221,7 @@ class colvaratoms_gpu { int begin_apply_force_gpu(); /** * @brief Add nodes for applying forces to the CUDA graph - * + * * @param[in] cpu_atoms CPU atom group class * @param[in] graph CUDA graph object * @param[in,out] nodes_map A map to store the added nodes with operation name @@ -235,7 +235,7 @@ class colvaratoms_gpu { const std::vector& extra_initial_dependencies = {}); /** * @brief Add nodes for calculating the fit gradients to the CUDA graph - * + * * @param[in] cpu_atoms CPU atom group class * @param[in] graph CUDA graph object * @param[in,out] nodes_map A map to store the added nodes with operation name @@ -251,7 +251,7 @@ class colvaratoms_gpu { * * This function reads the atom positions from the proxy buffer to the atom group GPU buffer, * and optionally modifies one of the coordinates for testing the numerical gradients. - * + * * @param[in] cpu_atoms CPU atom group class * @param[in] change_fitting_group If true, change the fitting group atom position * @param[in] change_atom_i Index of the atom to be changed @@ -266,7 +266,7 @@ class colvaratoms_gpu { int xyz, bool to_cpu, double sign, cudaStream_t stream); /** * @brief Function for calculating the required properties used for debug gradients - * + * * @param[in] cpu_atoms CPU atom group class * @param[in] to_cpu If true, copy the calculated properties to CPU buffers * @param[in] stream CUDA stream to be used @@ -278,7 +278,7 @@ class colvaratoms_gpu { * @brief Function to be called when a colvardeps feature is enabled * * This function performs any side effects needed when a feature is enabled. - * Specifically, it allocates the GPU buffers for unrotated positions if + * Specifically, it allocates the GPU buffers for unrotated positions if * f_ag_fit_gradients is enabled, and sets up the rotation object if * f_ag_rotate is enabled. * @@ -354,6 +354,8 @@ class colvaratoms_gpu { colvars_gpu::rotation_gpu rot_gpu; /// \brief GPU Rotation derivative; colvars_gpu::rotation_derivative_gpu* rot_deriv_gpu; + /// \brief Pointer to the parent colvarmodule + colvarmodule *cvmodule; }; #endif // defined (COLVARS_CUDA) || defined (COLVARS_HIP) diff --git a/src/colvarbias.cpp b/src/colvarbias.cpp index c5a29c1b5..065aec4d4 100644 --- a/src/colvarbias.cpp +++ b/src/colvarbias.cpp @@ -18,9 +18,10 @@ #include "colvars_memstream.h" -colvarbias::colvarbias(char const *key) +colvarbias::colvarbias(colvarmodule *cvmodule_in, char const *key) + : colvardeps(cvmodule_in) { - time_step_factor = cvm::proxy->time_step_factor(); + time_step_factor = cvmodule->proxy->time_step_factor(); bias_type = colvarparse::to_lower_cppstr(key); state_keyword = bias_type; @@ -32,7 +33,7 @@ colvarbias::colvarbias(char const *key) has_data = false; b_output_energy = false; - output_freq = cvm::restart_out_freq; + output_freq = cvmodule->restart_out_freq; colvarbias::reset(); state_file_step = 0L; @@ -53,16 +54,16 @@ int colvarbias::init(std::string const &conf) if (num_variables() == 0) { // First initialization - cvm::log("Initializing a new \""+bias_type+"\" instance.\n"); + cvmodule->log("Initializing a new \""+bias_type+"\" instance.\n"); // Only allow setting a non-default name on first init get_keyval(conf, "name", name, name); - colvarbias *bias_with_name = cvm::bias_by_name(this->name); + colvarbias *bias_with_name = cvmodule->bias_by_name(this->name); if (bias_with_name != NULL) { if ((bias_with_name->rank != this->rank) || (bias_with_name->bias_type != this->bias_type)) { - error_code |= cvm::error("Error: this bias cannot have the same name, \""+ + error_code |= cvmodule->error("Error: this bias cannot have the same name, \""+ this->name+"\", as another bias.\n", COLVARS_INPUT_ERROR); } @@ -74,7 +75,7 @@ int colvarbias::init(std::string const &conf) std::vector colvar_names; if (get_keyval(conf, "colvars", colvar_names)) { if (num_variables()) { - error_code |= cvm::error("Error: cannot redefine the colvars that " + error_code |= cvmodule->error("Error: cannot redefine the colvars that " "a bias was already defined on.\n", COLVARS_INPUT_ERROR); } @@ -85,12 +86,12 @@ int colvarbias::init(std::string const &conf) } if (!num_variables()) { - error_code |= cvm::error("Error: no collective variables specified.\n", + error_code |= cvmodule->error("Error: no collective variables specified.\n", COLVARS_INPUT_ERROR); } } else { - cvm::log("Reinitializing bias \""+name+"\".\n"); + cvmodule->log("Reinitializing bias \""+name+"\".\n"); } feature_states[f_cvb_step_zero_data].available = true; @@ -102,7 +103,7 @@ int colvarbias::init(std::string const &conf) previous_colvar_forces[i].type(colvar_values[i].type()); } - output_prefix = cvm::output_prefix(); + output_prefix = cvmodule->output_prefix(); get_keyval_feature(this, conf, "stepZeroData", f_cvb_step_zero_data, is_enabled(f_cvb_step_zero_data)); @@ -115,7 +116,7 @@ int colvarbias::init(std::string const &conf) // How often to write full output files? get_keyval(conf, "outputFreq", output_freq, output_freq); if (output_freq % time_step_factor != 0) { - error_code |= cvm::error( + error_code |= cvmodule->error( "Error: in bias " + name + ", outputFreq (currently " + cvm::to_str(output_freq) + ") must be a multiple of timeStepFactor (" + cvm::to_str(time_step_factor) + ").\n", COLVARS_INPUT_ERROR); @@ -152,21 +153,21 @@ int colvarbias::init_mts(std::string const &conf) { get_keyval(conf, "timeStepFactor", time_step_factor, time_step_factor); if (time_step_factor < 1) { - error_code |= cvm::error("Error: timeStepFactor must be 1 or greater.\n", COLVARS_INPUT_ERROR); + error_code |= cvmodule->error("Error: timeStepFactor must be 1 or greater.\n", COLVARS_INPUT_ERROR); } - if (time_step_factor % cvm::proxy->time_step_factor() != 0) { + if (time_step_factor % cvmodule->proxy->time_step_factor() != 0) { error_code |= - cvm::error("timeStepFactor for this bias (currently " + cvm::to_str(time_step_factor) + + cvmodule->error("timeStepFactor for this bias (currently " + cvm::to_str(time_step_factor) + ") must be a multiple of the global Colvars timestep multiplier (" + - cvm::to_str(cvm::proxy->time_step_factor()) + ").\n", + cvm::to_str(cvmodule->proxy->time_step_factor()) + ").\n", COLVARS_INPUT_ERROR); } for (auto *cv : colvars) { if (time_step_factor % cv->get_time_step_factor()) { - error_code |= cvm::error( - "Error: timeStepFactor for " + description + " (" + cvm::to_str(time_step_factor) + + error_code |= cvmodule->error( + "Error: timeStepFactor for " + cv->description + " (" + cvm::to_str(time_step_factor) + ") should be a multiple of that of " + cv->description + " (" + cvm::to_str(cv->get_time_step_factor()) + ").\n", COLVARS_INPUT_ERROR); @@ -204,7 +205,7 @@ int colvarbias::init_dependencies() { init_feature(f_cvb_get_total_force, "obtain_total_force", f_type_dynamic); require_feature_children(f_cvb_get_total_force, f_cv_total_force); // Depending on back-end, we may not obtain total force at step 0 - if (!cvm::main()->proxy->total_forces_same_step()) { + if (!cvmodule->proxy->total_forces_same_step()) { exclude_feature_self(f_cvb_get_total_force, f_cvb_step_zero_data); } @@ -240,7 +241,7 @@ int colvarbias::init_dependencies() { // check that everything is initialized for (i = 0; i < colvardeps::f_cvb_ntot; i++) { if (is_not_set(i)) { - cvm::error("Uninitialized feature " + cvm::to_str(i) + " in " + description); + cvmodule->error("Uninitialized feature " + cvm::to_str(i) + " in " + description); } } } @@ -278,7 +279,7 @@ int colvarbias::reset() colvarbias::colvarbias() - : colvarparse(), has_data(false) + : has_data(false) {} @@ -306,13 +307,12 @@ int colvarbias::clear() } } - colvarmodule *cv = cvm::main(); // ...and from the colvars module - for (std::vector::iterator bi = cv->biases.begin(); - bi != cv->biases.end(); + for (std::vector::iterator bi = cvmodule->biases.begin(); + bi != cvmodule->biases.end(); ++bi) { if ( *bi == this) { - cv->biases.erase(bi); + cvmodule->biases.erase(bi); break; } } @@ -323,7 +323,7 @@ int colvarbias::clear() biasing_force_scaling_factors_bin.clear(); } - cv->config_changed(); + cvmodule->config_changed(); return COLVARS_OK; } @@ -338,10 +338,10 @@ int colvarbias::clear_state_data() int colvarbias::add_colvar(std::string const &cv_name) { - if (colvar *cv = cvm::colvar_by_name(cv_name)) { + if (colvar *cv = cvmodule->colvar_by_name(cv_name)) { if (cvm::debug()) { - cvm::log("Applying this bias to collective variable \""+ + cvmodule->log("Applying this bias to collective variable \""+ cv->name+"\".\n"); } @@ -359,7 +359,7 @@ int colvarbias::add_colvar(std::string const &cv_name) previous_colvar_forces.push_back(colvar_forces.back()); } else { - cvm::error("Error: cannot find a colvar named \""+ + cvmodule->error("Error: cannot find a colvar named \""+ cv_name+"\".\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } @@ -371,7 +371,7 @@ int colvarbias::add_colvar(std::string const &cv_name) int colvarbias::update() { if (cvm::debug()) { - cvm::log("Updating the "+bias_type+" bias \""+this->name+"\".\n"); + cvmodule->log("Updating the "+bias_type+" bias \""+this->name+"\".\n"); } int error_code = COLVARS_OK; @@ -392,8 +392,8 @@ int colvarbias::update() bool colvarbias::can_accumulate_data() { - colvarproxy *proxy = cvm::main()->proxy; - if (((cvm::step_relative() > 0) && !proxy->simulation_continuing()) || + colvarproxy *proxy = cvmodule->proxy; + if (((cvmodule->step_relative() > 0) && !proxy->simulation_continuing()) || is_enabled(f_cvb_step_zero_data)) { return true; } @@ -435,7 +435,7 @@ int colvarbias::communicate_forces() } for (i = 0; i < num_variables(); i++) { if (cvm::debug()) { - cvm::log("Communicating a force to colvar \""+ + cvmodule->log("Communicating a force to colvar \""+ variables(i)->name+"\".\n"); } // Impulse-style multiple timestep @@ -462,7 +462,7 @@ int colvarbias::end_of_step() int colvarbias::change_configuration(std::string const & /* conf */) { - cvm::error("Error: change_configuration() not implemented.\n", + cvmodule->error("Error: change_configuration() not implemented.\n", COLVARS_NOT_IMPLEMENTED); return COLVARS_NOT_IMPLEMENTED; } @@ -470,7 +470,7 @@ int colvarbias::change_configuration(std::string const & /* conf */) cvm::real colvarbias::energy_difference(std::string const & /* conf */) { - cvm::error("Error: energy_difference() not implemented.\n", + cvmodule->error("Error: energy_difference() not implemented.\n", COLVARS_NOT_IMPLEMENTED); return 0.0; } @@ -479,31 +479,31 @@ cvm::real colvarbias::energy_difference(std::string const & /* conf */) // So far, these are only implemented in colvarbias_abf int colvarbias::bin_num() { - cvm::error("Error: bin_num() not implemented.\n"); + cvmodule->error("Error: bin_num() not implemented.\n"); return COLVARS_NOT_IMPLEMENTED; } int colvarbias::current_bin() { - cvm::error("Error: current_bin() not implemented.\n"); + cvmodule->error("Error: current_bin() not implemented.\n"); return COLVARS_NOT_IMPLEMENTED; } int colvarbias::bin_count(int /* bin_index */) { - cvm::error("Error: bin_count() not implemented.\n"); + cvmodule->error("Error: bin_count() not implemented.\n"); return COLVARS_NOT_IMPLEMENTED; } int colvarbias::local_sample_count(int /* radius */) { - cvm::error("Error: local_sample_count() not implemented.\n"); + cvmodule->error("Error: local_sample_count() not implemented.\n"); return COLVARS_NOT_IMPLEMENTED; } int colvarbias::replica_share() { - cvm::error("Error: replica_share() not implemented.\n"); + cvmodule->error("Error: replica_share() not implemented.\n"); return COLVARS_NOT_IMPLEMENTED; } @@ -516,7 +516,7 @@ size_t colvarbias::replica_share_freq() const std::string const colvarbias::get_state_params() const { std::ostringstream os; - os << " step " << cvm::step_absolute() << "\n" + os << " step " << cvmodule->step_absolute() << "\n" << " name " << this->name << "\n"; return os.str(); } @@ -529,13 +529,13 @@ int colvarbias::check_matching_state(std::string const &conf) std::string(""), colvarparse::parse_silent); if (check_name.size() == 0) { - return cvm::error("Error: \""+bias_type+"\" block within the state file " + return cvmodule->error("Error: \""+bias_type+"\" block within the state file " "has no identifiers.\n", COLVARS_INPUT_ERROR); } if (check_name != this->name) { if (cvm::debug()) { - cvm::log("Ignoring state of bias \""+check_name+ + cvmodule->log("Ignoring state of bias \""+check_name+ "\": this bias is named \""+name+"\".\n"); } matching_state = false; @@ -550,7 +550,7 @@ int colvarbias::check_matching_state(std::string const &conf) int colvarbias::set_state_params(std::string const &conf) { colvarparse::get_keyval(conf, "step", state_file_step, - cvm::step_absolute(), colvarparse::parse_silent); + cvmodule->step_absolute(), colvarparse::parse_silent); return COLVARS_OK; } @@ -559,10 +559,10 @@ int colvarbias::set_state_params(std::string const &conf) std::ostream & colvarbias::write_state(std::ostream &os) { if (cvm::debug()) { - cvm::log("Writing formatted state for bias \""+name+"\"\n"); + cvmodule->log("Writing formatted state for bias \""+name+"\"\n"); } os.setf(std::ios::scientific, std::ios::floatfield); - os.precision(cvm::cv_prec); + os.precision(cvmodule->cv_prec); os << state_keyword << " {\n" << " configuration {\n" << get_state_params() @@ -576,7 +576,7 @@ std::ostream & colvarbias::write_state(std::ostream &os) cvm::memory_stream & colvarbias::write_state(cvm::memory_stream &os) { if (cvm::debug()) { - cvm::log("Writing unformatted state for bias \""+name+"\"\n"); + cvmodule->log("Writing unformatted state for bias \""+name+"\"\n"); } os << state_keyword << std::string("configuration") << get_state_params(); write_state_data(os); @@ -586,20 +586,21 @@ cvm::memory_stream & colvarbias::write_state(cvm::memory_stream &os) template void raise_error_rewind(IST &is, SPT start_pos, std::string const &bias_type, - std::string const &bias_name, std::string const added_msg = "") + std::string const &bias_name, colvarmodule *cvmodule, + std::string const added_msg = "") { auto state = is.rdstate(); is.clear(); is.seekg(start_pos); is.setstate(state | std::ios::failbit); - cvm::error("Error: in reading state for \"" + bias_type + "\" bias \"" + bias_name + + cvmodule->error("Error: in reading state for \"" + bias_type + "\" bias \"" + bias_name + "\" at position " + cvm::to_str(static_cast(is.tellg())) + " in stream." + added_msg + "\n", COLVARS_INPUT_ERROR); } -template IST & colvarbias::read_state_template_(IST &is) +template IST & colvarbias::read_state_template_(IST &is, colvarmodule *cvmodule_in) { auto const start_pos = is.tellg(); @@ -610,14 +611,14 @@ template IST & colvarbias::read_state_template_(IST &is) if (! std::is_same::value) { // Formatted input only if (!(is >> brace) || !(brace == "{") ) { - raise_error_rewind(is, start_pos, bias_type, name); + raise_error_rewind(is, start_pos, bias_type, name, cvmodule_in); return is; } } if (!(is >> colvarparse::read_block("configuration", &conf)) || (check_matching_state(conf) != COLVARS_OK)) { - raise_error_rewind(is, start_pos, bias_type, name); + raise_error_rewind(is, start_pos, bias_type, name, cvmodule_in); return is; } @@ -628,7 +629,7 @@ template IST & colvarbias::read_state_template_(IST &is) } } else { - raise_error_rewind(is, start_pos, bias_type, name); + raise_error_rewind(is, start_pos, bias_type, name, cvmodule_in); return is; } @@ -639,21 +640,21 @@ template IST & colvarbias::read_state_template_(IST &is) } if ((set_state_params(conf) != COLVARS_OK) || !read_state_data(is)) { - raise_error_rewind(is, start_pos, bias_type, name); + raise_error_rewind(is, start_pos, bias_type, name, cvmodule_in); } if (! std::is_same::value) { is >> brace; if (brace != "}") { - cvm::error("Error: corrupt restart information for \""+bias_type+"\" bias \""+ + cvmodule_in->error("Error: corrupt restart information for \""+bias_type+"\" bias \""+ this->name+"\": no matching brace at position "+ cvm::to_str(static_cast(is.tellg()))+ " in stream.\n"); - raise_error_rewind(is, start_pos, bias_type, name); + raise_error_rewind(is, start_pos, bias_type, name, cvmodule_in); } } - cvm::log("Restarted " + bias_type + " bias \"" + name + "\" with step number " + + cvmodule_in->log("Restarted " + bias_type + " bias \"" + name + "\" with step number " + cvm::to_str(state_file_step) + ".\n"); return is; @@ -662,21 +663,21 @@ template IST & colvarbias::read_state_template_(IST &is) std::istream &colvarbias::read_state(std::istream &is) { - return read_state_template_(is); + return read_state_template_(is, cvmodule); } cvm::memory_stream &colvarbias::read_state(cvm::memory_stream &is) { - return read_state_template_(is); + return read_state_template_(is, cvmodule); } int colvarbias::write_state_prefix(std::string const &prefix) { std::string const filename = - cvm::state_file_prefix(prefix.c_str())+".colvars.state"; - std::ostream &os = cvm::proxy->output_stream(filename.c_str(), "bias state file"); + cvmodule->state_file_prefix(prefix.c_str())+".colvars.state"; + std::ostream &os = cvmodule->proxy->output_stream(filename.c_str(), "bias state file"); int error_code = COLVARS_OK; if (os) { os.setf(std::ios::scientific, std::ios::floatfield); @@ -684,7 +685,7 @@ int colvarbias::write_state_prefix(std::string const &prefix) } else { error_code = COLVARS_FILE_ERROR; } - cvm::proxy->close_output_stream(filename.c_str()); + cvmodule->proxy->close_output_stream(filename.c_str()); return error_code; } @@ -693,7 +694,7 @@ int colvarbias::write_state_string(std::string &output) { std::ostringstream os; if (!write_state(os)) { - return cvm::error("Error: in writing state of bias \""+name+ + return cvmodule->error("Error: in writing state of bias \""+name+ "\" to buffer.\n", COLVARS_FILE_ERROR); } output = os.str(); @@ -704,16 +705,16 @@ int colvarbias::write_state_string(std::string &output) int colvarbias::read_state_prefix(std::string const &prefix) { std::string filename(prefix+std::string(".colvars.state")); - std::istream *is = &(cvm::main()->proxy->input_stream(filename, + std::istream *is = &(cvmodule->proxy->input_stream(filename, "bias state file", false)); if (!*is) { filename = prefix; - is = &(cvm::main()->proxy->input_stream(filename, "bias state file")); + is = &(cvmodule->proxy->input_stream(filename, "bias state file")); } if (read_state(*is)) { - return cvm::main()->proxy->close_input_stream(filename); + return cvmodule->proxy->close_input_stream(filename); } return COLVARS_FILE_ERROR; } @@ -724,20 +725,20 @@ int colvarbias::read_state_string(char const *buffer) if (buffer != NULL) { size_t const buffer_size = strlen(buffer); if (cvm::debug()) { - cvm::log("colvarbias::read_state_string() with argument:\n"); - cvm::log(buffer); + cvmodule->log("colvarbias::read_state_string() with argument:\n"); + cvmodule->log(buffer); } if (buffer_size > 0) { std::istringstream is; is.rdbuf()->pubsetbuf(const_cast(buffer), buffer_size); return read_state(is).good() ? COLVARS_OK : - cvm::error("Error: in reading state for \""+name+"\" from buffer.\n", + cvmodule->error("Error: in reading state for \""+name+"\" from buffer.\n", COLVARS_FILE_ERROR); } return COLVARS_OK; } - return cvm::error("Error: NULL pointer for colvarbias::read_state_string()", + return cvmodule->error("Error: NULL pointer for colvarbias::read_state_string()", COLVARS_BUG_ERROR); } @@ -765,12 +766,12 @@ IST &colvarbias::read_state_data_key_template_(IST &is, std::string const &key) std::string key_in; if (is >> key_in) { if (key_in != key) { - raise_error_rewind(is, start_pos, bias_type, name, + raise_error_rewind(is, start_pos, bias_type, name, cvmodule, " Expected keyword \"" + std::string(key) + "\", found \"" + key_in + "\"."); } } else { - raise_error_rewind(is, start_pos, bias_type, name); + raise_error_rewind(is, start_pos, bias_type, name, cvmodule); } return is; } @@ -793,7 +794,7 @@ std::ostream & colvarbias::write_traj_label(std::ostream &os) os << " "; if (b_output_energy) os << " E_" - << cvm::wrap_string(this->name, cvm::en_width-2); + << cvmodule->wrap_string(this->name, cvmodule->en_width-2); return os; } @@ -803,17 +804,15 @@ std::ostream & colvarbias::write_traj(std::ostream &os) os << " "; if (b_output_energy) os << " " - << std::setprecision(cvm::en_prec) << std::setw(cvm::en_width) + << std::setprecision(cvmodule->en_prec) << std::setw(cvmodule->en_width) << bias_energy; return os; } - colvarbias_ti::colvarbias_ti(char const *key) - : colvarbias(key) { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; provide(f_cvb_calc_ti_samples); if (!proxy->total_forces_same_step()) { // Samples at step zero can not be collected @@ -846,7 +845,7 @@ int colvarbias_ti::init(std::string const &conf) } if ((num_variables() > 1) && is_enabled(f_cvb_write_ti_pmf)) { - return cvm::error("Error: only 1-dimensional PMFs can be written " + return cvmodule->error("Error: only 1-dimensional PMFs can be written " "on the fly.\n" "Consider using writeTISamples instead and " "post-processing the sampled free-energy gradients.\n", @@ -855,12 +854,12 @@ int colvarbias_ti::init(std::string const &conf) if (is_enabled(f_cvb_calc_ti_samples)) { std::vector const time_biases = - cvm::main()->time_dependent_biases(); + cvmodule->time_dependent_biases(); if (time_biases.size() > 0) { if ((time_biases.size() > 1) || (time_biases[0] != this->name)) { for (size_t i = 0; i < num_variables(); i++) { if (! variables(i)->is_enabled(f_cv_subtract_applied_force)) { - return cvm::error("Error: cannot collect TI samples while other " + return cvmodule->error("Error: cannot collect TI samples while other " "time-dependent biases are active and not all " "variables have subtractAppliedForces on.\n", COLVARS_INPUT_ERROR); @@ -873,7 +872,7 @@ int colvarbias_ti::init(std::string const &conf) error_code |= colvarbias_ti::init_grids(); if (is_enabled(f_cvb_write_ti_pmf) || is_enabled(f_cvb_write_ti_samples)) { - cvm::main()->cite_feature("Internal-forces free energy estimator"); + cvmodule->cite_feature("Internal-forces free energy estimator"); } return error_code; @@ -917,15 +916,15 @@ int colvarbias_ti::update_system_forces(std::vector const has_data = true; if (cvm::debug()) { - cvm::log("Updating system forces for bias "+this->name+"\n"); + cvmodule->log("Updating system forces for bias "+this->name+"\n"); } - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; size_t i; if (cvm::debug()) { - cvm::log("TI bin for bias \"" + name + "\" = " + cvm::to_str(ti_bin) + ".\n"); + cvmodule->log("TI bin for bias \"" + name + "\" = " + cvm::to_str(ti_bin) + ".\n"); } for (i = 0; i < num_variables(); i++) { @@ -935,11 +934,11 @@ int colvarbias_ti::update_system_forces(std::vector const } // Collect total colvar forces - if ((cvm::step_relative() > 0) || proxy->total_forces_same_step()) { + if ((cvmodule->step_relative() > 0) || proxy->total_forces_same_step()) { if (ti_avg_forces->index_ok(ti_bin)) { for (i = 0; i < num_variables(); i++) { if (variables(i)->is_enabled(f_cv_subtract_applied_force) || - (cvm::proxy->total_forces_same_step() && !variables(i)->is_enabled(f_cv_external))) { + (cvmodule->proxy->total_forces_same_step() && !variables(i)->is_enabled(f_cv_external))) { // this colvar is already subtracting all applied forces // or the "total force" is really a system force at current step ti_system_forces[i] = variables(i)->total_force(); @@ -949,9 +948,9 @@ int colvarbias_ti::update_system_forces(std::vector const (*subtract_forces)[i] : previous_colvar_forces[i]); } } - if (cvm::step_relative() > 0 || is_enabled(f_cvb_step_zero_data)) { + if (cvmodule->step_relative() > 0 || is_enabled(f_cvb_step_zero_data)) { if (cvm::debug()) { - cvm::log("Accumulating TI forces for bias \"" + name + "\".\n"); + cvmodule->log("Accumulating TI forces for bias \"" + name + "\".\n"); } ti_avg_forces->acc_value(ti_bin, ti_system_forces); } @@ -1013,7 +1012,7 @@ std::istream & colvarbias_ti::read_state_data(std::istream &is) return is; } if (cvm::debug()) { - cvm::log("Reading state data for the TI estimator.\n"); + cvmodule->log("Reading state data for the TI estimator.\n"); } if (! read_state_data_key(is, "histogram")) { return is; @@ -1028,7 +1027,7 @@ std::istream & colvarbias_ti::read_state_data(std::istream &is) return is; } if (cvm::debug()) { - cvm::log("Done reading state data for the TI estimator.\n"); + cvmodule->log("Done reading state data for the TI estimator.\n"); } return is; } @@ -1040,7 +1039,7 @@ cvm::memory_stream & colvarbias_ti::read_state_data(cvm::memory_stream &is) return is; } if (cvm::debug()) { - cvm::log("Reading state data for the TI estimator.\n"); + cvmodule->log("Reading state data for the TI estimator.\n"); } if (! read_state_data_key(is, "histogram")) { return is; @@ -1055,7 +1054,7 @@ cvm::memory_stream & colvarbias_ti::read_state_data(cvm::memory_stream &is) return is; } if (cvm::debug()) { - cvm::log("Done reading state data for the TI estimator.\n"); + cvmodule->log("Done reading state data for the TI estimator.\n"); } return is; } @@ -1070,7 +1069,7 @@ int colvarbias_ti::write_output_files() return COLVARS_OK; } - std::string const ti_output_prefix = cvm::output_prefix()+"."+this->name; + std::string const ti_output_prefix = cvmodule->output_prefix()+"."+this->name; if (is_enabled(f_cvb_write_ti_samples)) { std::string const ti_count_file_name(ti_output_prefix+".ti.count"); @@ -1082,14 +1081,14 @@ int colvarbias_ti::write_output_files() if (is_enabled(f_cvb_write_ti_pmf)) { std::string const pmf_file_name(ti_output_prefix+".ti.pmf"); - cvm::log("Writing TI PMF to file \""+pmf_file_name+"\".\n"); - std::ostream &os = cvm::proxy->output_stream(pmf_file_name, "TI PMF"); + cvmodule->log("Writing TI PMF to file \""+pmf_file_name+"\".\n"); + std::ostream &os = cvmodule->proxy->output_stream(pmf_file_name, "TI PMF"); if (os) { // get the FE gradient ti_avg_forces->multiply_constant(-1.0); ti_avg_forces->write_1D_integral(os); ti_avg_forces->multiply_constant(-1.0); - cvm::proxy->close_output_stream(pmf_file_name); + cvmodule->proxy->close_output_stream(pmf_file_name); } else { error_code |= COLVARS_FILE_ERROR; } diff --git a/src/colvarbias.h b/src/colvarbias.h index 8f7b86fdd..bf05fc5be 100644 --- a/src/colvarbias.h +++ b/src/colvarbias.h @@ -20,7 +20,7 @@ class colvar_grid_scalar; /// \brief Collective variable bias, base class class colvarbias - : public virtual colvarparse, public virtual colvardeps { + : public virtual colvardeps { public: /// Name of this bias @@ -107,7 +107,7 @@ class colvarbias virtual void analyze() {} /// \brief Constructor - colvarbias(char const *key); + colvarbias(colvarmodule *cvmodule_in, char const *key); /// \brief Parse config string and (re)initialize virtual int init(std::string const &conf); @@ -116,12 +116,12 @@ class colvarbias virtual int init_mts(std::string const &conf); /// \brief Initialize dependency tree - virtual int init_dependencies(); + int init_dependencies() override; /// \brief Set to zero all mutable data virtual int reset(); -private: +protected: /// Default constructor colvarbias(); @@ -208,7 +208,7 @@ class colvarbias private: /// Generic stream reading function (formatted and not) - template IST & read_state_template_(IST &is); + template IST & read_state_template_(IST &is, colvarmodule *cvmodule_in); public: @@ -275,11 +275,11 @@ class colvarbias static std::vector cvb_features; /// \brief Implementation of the feature list accessor for colvarbias - virtual const std::vector &features() const + virtual const std::vector &features() const override { return cvb_features; } - virtual std::vector &modify_features() + virtual std::vector &modify_features() override { return cvb_features; } diff --git a/src/colvarbias_abf.cpp b/src/colvarbias_abf.cpp index 12c1753d1..f5278bb9f 100644 --- a/src/colvarbias_abf.cpp +++ b/src/colvarbias_abf.cpp @@ -14,8 +14,8 @@ #include "colvarbias_abf.h" #include "colvars_memstream.h" -colvarbias_abf::colvarbias_abf(char const *key) - : colvarbias(key), +colvarbias_abf::colvarbias_abf(colvarmodule *cvmodule_in, char const *key) + : colvarbias(cvmodule_in, key), b_UI_estimator(false), b_CZAR_estimator(false), pabf_freq(0), @@ -26,33 +26,33 @@ colvarbias_abf::colvarbias_abf(char const *key) int colvarbias_abf::init(std::string const &conf) { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; int err = colvarbias::init(conf); if (err != COLVARS_OK) { return err; } - cvm::main()->cite_feature("ABF colvar bias implementation"); + cvmodule->cite_feature("ABF colvar bias implementation"); enable(f_cvb_scalar_variables); enable(f_cvb_calc_pmf); if ((proxy->target_temperature() == 0.0) && proxy->simulation_running()) { - cvm::log("WARNING: ABF should not be run without a thermostat or at 0 Kelvin!\n"); + cvmodule->log("WARNING: ABF should not be run without a thermostat or at 0 Kelvin!\n"); } // ************* parsing general ABF options *********************** get_keyval_feature(this, conf, "applyBias", f_cvb_apply_force, true); if (!is_enabled(f_cvb_apply_force)){ - cvm::log("WARNING: ABF biases will *not* be applied!\n"); + cvmodule->log("WARNING: ABF biases will *not* be applied!\n"); } get_keyval(conf, "hideJacobian", hide_Jacobian, false); if (hide_Jacobian) { - cvm::log("Jacobian (geometric) forces will be handled internally.\n"); + cvmodule->log("Jacobian (geometric) forces will be handled internally.\n"); } else { - cvm::log("Jacobian (geometric) forces will be included in reported free energy gradients.\n"); + cvmodule->log("Jacobian (geometric) forces will be included in reported free energy gradients.\n"); } full_samples = 200; @@ -64,7 +64,7 @@ int colvarbias_abf::init(std::string const &conf) min_samples = 0; } if (min_samples >= full_samples) { - return cvm::error("Error: minSamples must be lower than fullSamples\n"); + return cvmodule->error("Error: minSamples must be lower than fullSamples\n"); } get_keyval(conf, "inputPrefix", input_prefix, std::vector()); @@ -73,11 +73,11 @@ int colvarbias_abf::init(std::string const &conf) get_keyval(conf, "historyFreq", history_freq, 0); if (history_freq != 0) { if (output_freq == 0) { - cvm::error("Error: historyFreq cannot be non-zero when outputFreq is zero.\n", + cvmodule->error("Error: historyFreq cannot be non-zero when outputFreq is zero.\n", COLVARS_INPUT_ERROR); } else { if ((history_freq % output_freq) != 0) { - cvm::error("Error: historyFreq must be a multiple of outputFreq.\n", + cvmodule->error("Error: historyFreq must be a multiple of outputFreq.\n", COLVARS_INPUT_ERROR); } } @@ -86,30 +86,30 @@ int colvarbias_abf::init(std::string const &conf) // shared ABF get_keyval(conf, "shared", shared_on, false); if (shared_on) { - cvm::main()->cite_feature("Multiple-walker ABF implementation"); - cvm::main()->cite_feature("Updated multiple-walker ABF implementation"); + cvmodule->cite_feature("Multiple-walker ABF implementation"); + cvmodule->cite_feature("Updated multiple-walker ABF implementation"); // If shared_freq is not set, we default to output_freq get_keyval(conf, "sharedFreq", shared_freq, output_freq); if ( shared_freq && output_freq % shared_freq ) { - return cvm::error("Error: outputFreq must be a multiple of sharedFreq.\n"); + return cvmodule->error("Error: outputFreq must be a multiple of sharedFreq.\n"); } if ( shared_freq && shared_freq % time_step_factor ) { - return cvm::error("Error: sharedFreq must be a multiple of timeStepFactor.\n"); + return cvmodule->error("Error: sharedFreq must be a multiple of timeStepFactor.\n"); } } // ************* checking the associated colvars ******************* if (num_variables() == 0) { - return cvm::error("Error: no collective variables specified for the ABF bias.\n"); + return cvmodule->error("Error: no collective variables specified for the ABF bias.\n"); } size_t i; for (i = 0; i < num_variables(); i++) { if (colvars[i]->value().type() != colvarvalue::type_scalar) { - return cvm::error("Error: ABF bias can only use scalar-type variables.\n"); + return cvmodule->error("Error: ABF bias can only use scalar-type variables.\n"); } colvars[i]->enable(f_cv_grid); // Could be a child dependency of a f_cvb_use_grids feature if (hide_Jacobian) { @@ -128,7 +128,7 @@ int colvarbias_abf::init(std::string const &conf) provide(f_cvb_step_zero_data, false); // And we cannot do MTS either if (time_step_factor > 1) { - return cvm::error("Error: ABF cannot use timeStepFactor > 1 because " + + return cvmodule->error("Error: ABF cannot use timeStepFactor > 1 because " + colvars[i]->description + " does not provide total force estimates for the current timestep.\n"); } @@ -143,22 +143,22 @@ int colvarbias_abf::init(std::string const &conf) enable(f_cvb_history_dependent); enable(f_cvb_get_total_force); } else { - cvm::log("WARNING: ABF biases will *not* be updated!\n"); + cvmodule->log("WARNING: ABF biases will *not* be updated!\n"); } if (is_enabled(f_cvb_extended)) { - cvm::main()->cite_feature("eABF implementation"); + cvmodule->cite_feature("eABF implementation"); } else { - cvm::main()->cite_feature("Internal-forces free energy estimator"); + cvmodule->cite_feature("Internal-forces free energy estimator"); } if (get_keyval(conf, "maxForce", max_force)) { if (max_force.size() != num_variables()) { - cvm::error("Error: Number of parameters to maxForce does not match number of colvars."); + cvmodule->error("Error: Number of parameters to maxForce does not match number of colvars."); } for (i = 0; i < num_variables(); i++) { if (max_force[i] < 0.0) { - cvm::error("Error: maxForce should be non-negative."); + cvmodule->error("Error: maxForce should be non-negative."); return COLVARS_ERROR; } } @@ -173,7 +173,7 @@ int colvarbias_abf::init(std::string const &conf) // Construct empty grids based on the colvars if (cvm::debug()) { - cvm::log("Allocating count and free energy gradient grids.\n"); + cvmodule->log("Allocating count and free energy gradient grids.\n"); } { @@ -197,7 +197,7 @@ int colvarbias_abf::init(std::string const &conf) if (is_enabled(f_cvb_extended)) { get_keyval(conf, "CZARestimator", b_CZAR_estimator, true); if ( b_CZAR_estimator ) { - cvm::main()->cite_feature("CZAR eABF estimator"); + cvmodule->cite_feature("CZAR eABF estimator"); } // CZAR output files for stratified eABF get_keyval(conf, "writeCZARwindowFile", b_czar_window_file, false, @@ -215,7 +215,7 @@ int colvarbias_abf::init(std::string const &conf) if (b_integrate) { // For now, we integrate on-the-fly iff the grid is < 3D if ( num_variables() > 3 ) { - cvm::error("Error: cannot integrate free energy in dimension > 3.\n"); + cvmodule->error("Error: cannot integrate free energy in dimension > 3.\n"); return COLVARS_ERROR; } pmf.reset(new colvargrid_integrate(colvars, gradients)); @@ -234,7 +234,7 @@ int colvarbias_abf::init(std::string const &conf) get_keyval(conf, "pABFintegrateTol", pabf_integrate_tol, 1e-4, colvarparse::parse_silent); } - if (b_CZAR_estimator && shared_on && cvm::main()->proxy->replica_index() == 0) { + if (b_CZAR_estimator && shared_on && cvmodule->proxy->replica_index() == 0) { // The pointers below are used for outputting CZAR data // Allocate grids for collected global data, on replica 0 only global_z_samples.reset(new colvar_grid_count(colvars, samples)); @@ -259,7 +259,7 @@ int colvarbias_abf::init(std::string const &conf) last_samples.reset(new colvar_grid_count(colvars, samples)); last_gradients.reset(new colvar_grid_gradient(colvars, last_samples)); // Any data collected after now is new for shared ABF purposes - shared_last_step = cvm::step_absolute(); + shared_last_step = cvmodule->step_absolute(); // Read any custom input ABF data if ( input_prefix.size() > 0 ) { @@ -274,11 +274,11 @@ int colvarbias_abf::init(std::string const &conf) if (b_UI_estimator) { if (shared_on) { - cvm::error("Error: UI estimator is not available for multiple-walker (shared) ABF.\n"); + cvmodule->error("Error: UI estimator is not available for multiple-walker (shared) ABF.\n"); b_UI_estimator = false; return COLVARS_ERROR; } - cvm::main()->cite_feature("Umbrella-integration eABF estimator"); + cvmodule->cite_feature("Umbrella-integration eABF estimator"); std::vector UI_lowerboundary; std::vector UI_upperboundary; std::vector UI_width; @@ -292,19 +292,19 @@ int colvarbias_abf::init(std::string const &conf) UI_width.push_back(colvars[i]->width); UI_krestr.push_back(colvars[i]->force_constant()); } - eabf_UI = UIestimator::UIestimator(UI_lowerboundary, + eabf_UI = UIestimator::UIestimator(cvmodule, + UI_lowerboundary, UI_upperboundary, UI_width, UI_krestr, // force constant in eABF output_prefix, // the prefix of output files - cvm::restart_out_freq, UI_restart, // whether restart from a .count and a .grad file input_prefix, // the prefixes of input files proxy->target_temperature()); } } - cvm::log("Finished ABF setup.\n"); + cvmodule->log("Finished ABF setup.\n"); return COLVARS_OK; } @@ -319,7 +319,7 @@ colvarbias_abf::~colvarbias_abf() int colvarbias_abf::update() { - if (cvm::debug()) cvm::log("Updating ABF bias " + this->name); + if (cvm::debug()) cvmodule->log("Updating ABF bias " + this->name); size_t i; for (i = 0; i < num_variables(); i++) { @@ -338,16 +338,16 @@ int colvarbias_abf::update() // shared_on can be true with shared_freq 0 if we are sharing via script if (shared_freq && shared_last_step >= 0 && // we have already collected some data - cvm::step_absolute() > shared_last_step && // time has passed since the last sharing timestep + cvmodule->step_absolute() > shared_last_step && // time has passed since the last sharing timestep // (avoid re-sharing at last and first ts of successive run statements) - cvm::step_absolute() % shared_freq == 0) { + cvmodule->step_absolute() % shared_freq == 0) { // Share gradients and samples for shared ABF. replica_share(); } if (can_accumulate_data() && is_enabled(f_cvb_history_dependent)) { - if (cvm::step_relative() > 0 || cvm::proxy->total_forces_same_step()) { + if (cvmodule->step_relative() > 0 || cvmodule->proxy->total_forces_same_step()) { // Note: this will skip step 0 data when available in some cases (extended system), // but not doing so would make the code more complex if (samples->index_ok(force_bin)) { @@ -374,11 +374,11 @@ int colvarbias_abf::update() } } - if ( pabf_freq && cvm::step_relative() % pabf_freq == 0 ) { + if ( pabf_freq && cvmodule->step_relative() % pabf_freq == 0 ) { cvm::real err; int iter = pmf->integrate(integrate_iterations, integrate_tol, err); if ( iter == integrate_iterations ) { - cvm::log("Warning: PMF integration did not converge to " + cvm::to_str(integrate_tol) + cvmodule->log("Warning: PMF integration did not converge to " + cvm::to_str(integrate_tol) + " in " + cvm::to_str(integrate_iterations) + " steps. Residual error: " + cvm::to_str(err)); } @@ -420,11 +420,11 @@ int colvarbias_abf::update() // update the output prefix; TODO: move later to setup_output() function - if (cvm::main()->num_biases_feature(colvardeps::f_cvb_calc_pmf) == 1) { + if (cvmodule->num_biases_feature(colvardeps::f_cvb_calc_pmf) == 1) { // This is the only bias computing PMFs - output_prefix = cvm::output_prefix(); + output_prefix = cvmodule->output_prefix(); } else { - output_prefix = cvm::output_prefix() + "." + this->name; + output_prefix = cvmodule->output_prefix() + "." + this->name; } @@ -439,7 +439,7 @@ int colvarbias_abf::update() y[i] = colvars[i]->value(); } eabf_UI.update_output_filename(output_prefix); - eabf_UI.update(cvm::step_absolute(), x, y); + eabf_UI.update(cvmodule->step_absolute(), x, y); } /// Compute the bias energy @@ -534,23 +534,23 @@ int colvarbias_abf::calc_biasing_force(std::vector &force) int colvarbias_abf::replica_share() { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; // This check has to be deferred here rather than at init time, because the // replica communicator is not available at init time in Gromacs if (proxy->check_replicas_enabled() != COLVARS_OK) { - cvm::error("Error: shared ABF: No replicas.\n"); + cvmodule->error("Error: shared ABF: No replicas.\n"); return COLVARS_ERROR; } // We must have stored the last_gradients and last_samples. if (shared_last_step < 0 ) { - cvm::error("Error: shared ABF: Tried to apply shared ABF before any sampling had occurred.\n"); + cvmodule->error("Error: shared ABF: Tried to apply shared ABF before any sampling had occurred.\n"); return COLVARS_ERROR; } shared_on = true; // If called by a script, inform the rest of the code that we're sharing, eg. CZAR // Share gradients for shared ABF. - cvm::log("shared ABF: Sharing gradient and samples among replicas at step "+cvm::to_str(cvm::step_absolute()) ); + cvmodule->log("shared ABF: Sharing gradient and samples among replicas at step "+cvm::to_str(cvmodule->step_absolute()) ); if (!local_samples) { // We arrive here if sharing has just been enabled by a script @@ -576,13 +576,13 @@ int colvarbias_abf::replica_share() { int msg_total = samples_n * sizeof(size_t) + samp_start; char* msg_data = new char[msg_total]; - if (cvm::main()->proxy->replica_index() == 0) { + if (cvmodule->proxy->replica_index() == 0) { int p; // Replica 0 collects the delta gradient and count from the others. for (p = 1; p < proxy->num_replicas(); p++) { // Receive the deltas. if (proxy->replica_comm_recv(msg_data, msg_total, p) != msg_total) { - cvm::error("Error getting shared ABF data from replica."); + cvmodule->error("Error getting shared ABF data from replica."); return COLVARS_ERROR; } @@ -603,7 +603,7 @@ int colvarbias_abf::replica_share() { for (p = 1; p < proxy->num_replicas(); p++) { if (proxy->replica_comm_send(msg_data, msg_total, p) != msg_total) { - cvm::error("Error sending shared ABF data to replica."); + cvmodule->error("Error sending shared ABF data to replica."); return COLVARS_ERROR; } } @@ -615,12 +615,12 @@ int colvarbias_abf::replica_share() { last_samples->raw_data_out((size_t*)(&msg_data[samp_start])); if (proxy->replica_comm_send(msg_data, msg_total, 0) != msg_total) { - cvm::error("Error sending shared ABF data to replica."); + cvmodule->error("Error sending shared ABF data to replica."); return COLVARS_ERROR; } // We now receive the combined gradient from Replica 0. if (proxy->replica_comm_recv(msg_data, msg_total, 0) != msg_total) { - cvm::error("Error getting shared ABF data from replica 0."); + cvmodule->error("Error getting shared ABF data from replica 0."); return COLVARS_ERROR; } // We sync to the combined gradient computed by Replica 0. @@ -637,9 +637,9 @@ int colvarbias_abf::replica_share() { // Copy the current gradient and count values into last. last_gradients->copy_grid(*gradients); last_samples->copy_grid(*samples); - shared_last_step = cvm::step_absolute(); + shared_last_step = cvmodule->step_absolute(); - cvm::log("RMSD btw. local and global ABF gradients: " + cvm::to_str(gradients->grid_rmsd(*local_gradients))); + cvmodule->log("RMSD btw. local and global ABF gradients: " + cvm::to_str(gradients->grid_rmsd(*local_gradients))); if (b_integrate) { cvm::real err; @@ -651,16 +651,16 @@ int colvarbias_abf::replica_share() { local_pmf->set_div(); local_pmf->integrate(integrate_iterations, integrate_tol, err); local_pmf->set_zero_minimum(); - cvm::log("RMSD btw. local and global ABF FES: " + cvm::to_str(pmf->grid_rmsd(*local_pmf))); + cvmodule->log("RMSD btw. local and global ABF FES: " + cvm::to_str(pmf->grid_rmsd(*local_pmf))); } return COLVARS_OK; } int colvarbias_abf::replica_share_CZAR() { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; - cvm::log("shared eABF: Gathering CZAR gradient and samples from replicas at step "+cvm::to_str(cvm::step_absolute()) ); + cvmodule->log("shared eABF: Gathering CZAR gradient and samples from replicas at step "+cvm::to_str(cvmodule->step_absolute()) ); // Count of data items. size_t samples_n = z_samples->raw_data_num(); @@ -670,7 +670,7 @@ int colvarbias_abf::replica_share_CZAR() { int msg_total = samples_n*sizeof(size_t) + samp_start; char* msg_data = new char[msg_total]; - if (cvm::main()->proxy->replica_index() == 0) { + if (cvmodule->proxy->replica_index() == 0) { if (!global_z_samples) { // We arrive here if sharing has just been enabled by a script // Allocate grids for collective data, on replica 0 only @@ -689,7 +689,7 @@ int colvarbias_abf::replica_share_CZAR() { // Replica 0 collects the gradient and count from the others. for (p = 1; p < proxy->num_replicas(); p++) { if (proxy->replica_comm_recv(msg_data, msg_total, p) != msg_total) { - cvm::error("Error getting shared ABF data from replica."); + cvmodule->error("Error getting shared ABF data from replica."); return COLVARS_ERROR; } @@ -708,7 +708,7 @@ int colvarbias_abf::replica_share_CZAR() { z_gradients->raw_data_out((cvm::real*)(&msg_data[0])); z_samples->raw_data_out((size_t*)(&msg_data[samp_start])); if (proxy->replica_comm_send(msg_data, msg_total, 0) != msg_total) { - cvm::error("Error sending shared ABF data to replica."); + cvmodule->error("Error sending shared ABF data to replica."); return COLVARS_ERROR; } } @@ -737,17 +737,17 @@ size_t colvarbias_abf::replica_share_freq() const template int colvarbias_abf::write_grid_to_file(T const *grid, std::string const &filename, bool close) { - std::ostream &os = cvm::proxy->output_stream(filename, "multicolumn grid file"); + std::ostream &os = cvmodule->proxy->output_stream(filename, "multicolumn grid file"); if (!os) { - return cvm::error("Error opening file " + filename + " for writing.\n", COLVARS_ERROR | COLVARS_FILE_ERROR); + return cvmodule->error("Error opening file " + filename + " for writing.\n", COLVARS_ERROR | COLVARS_FILE_ERROR); } grid->write_multicol(os); if (close) { - cvm::proxy->close_output_stream(filename); + cvmodule->proxy->close_output_stream(filename); } else { // Insert empty line between frames in history files os << std::endl; - cvm::proxy->flush_output_stream(filename); + cvmodule->proxy->flush_output_stream(filename); } // In dimension higher than 2, dx is easier to handle and visualize @@ -755,13 +755,13 @@ template int colvarbias_abf::write_grid_to_file(T const *grid, // (could be implemented as multiple dx files) if (num_variables() > 2 && close) { std::string dx = filename + ".dx"; - std::ostream &dx_os = cvm::proxy->output_stream(dx, "OpenDX grid file"); + std::ostream &dx_os = cvmodule->proxy->output_stream(dx, "OpenDX grid file"); if (!dx_os) { - return cvm::error("Error opening file " + dx + " for writing.\n", COLVARS_ERROR | COLVARS_FILE_ERROR); + return cvmodule->error("Error opening file " + dx + " for writing.\n", COLVARS_ERROR | COLVARS_FILE_ERROR); } grid->write_opendx(dx_os); // if (close) { - cvm::proxy->close_output_stream(dx); + cvmodule->proxy->close_output_stream(dx); // } // else { // // TODO, decide convention for multiple datasets in dx file @@ -775,7 +775,7 @@ template int colvarbias_abf::write_grid_to_file(T const *grid, void colvarbias_abf::write_gradients_samples(const std::string &prefix, bool close, bool local) { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; // The following are local aliases for the class' unique pointers colvar_grid_count *samples_out, *z_samples_out; @@ -826,7 +826,7 @@ void colvarbias_abf::write_gradients_samples(const std::string &prefix, bool clo // Update the CZAR estimator of gradients, except at step 0 // in which case we preserve any existing data (e.g. read via inputPrefix, used to join strata in stratified eABF) - if (cvm::step_relative() > 0) { + if (cvmodule->step_relative() > 0) { for (std::vector iz_bin = czar_gradients_out->new_index(); czar_gradients_out->index_ok(iz_bin); czar_gradients_out->incr(iz_bin)) { for (size_t n = 0; n < czar_gradients_out->multiplicity(); n++) { @@ -864,7 +864,7 @@ int colvarbias_abf::current_bin() { /// Give the count at a given bin index. int colvarbias_abf::bin_count(int bin_index) { if (bin_index < 0 || bin_index >= bin_num()) { - cvm::error("Error: Tried to get bin count from invalid bin index "+cvm::to_str(bin_index)); + cvmodule->error("Error: Tried to get bin count from invalid bin index "+cvm::to_str(bin_index)); return -1; } return int(samples->get_value(bin_index)); @@ -968,7 +968,7 @@ cvm::memory_stream & colvarbias_abf::write_state_data(cvm::memory_stream& os) template IST &colvarbias_abf::read_state_data_template_(IST &is) { if ( input_prefix.size() > 0 ) { - cvm::error("Error: cannot provide both inputPrefix and a colvars state file.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: cannot provide both inputPrefix and a colvars state file.\n", COLVARS_INPUT_ERROR); } if (! read_state_data_key(is, "samples")) { @@ -1026,7 +1026,7 @@ template IST &colvarbias_abf::read_state_data_template_(IST &is) if (shared_on) { last_gradients->copy_grid(*gradients); last_samples->copy_grid(*samples); - shared_last_step = cvm::step_absolute(); + shared_last_step = cvmodule->step_absolute(); } return is; @@ -1048,7 +1048,7 @@ cvm::memory_stream & colvarbias_abf::read_state_data(cvm::memory_stream& is) int colvarbias_abf::write_output_files() { if (cvm::debug()) { - cvm::log("ABF bias trying to write gradients and samples to disk"); + cvmodule->log("ABF bias trying to write gradients and samples to disk"); } // In shared eABF/CZAR, the communication routine needs to run on all ranks @@ -1061,7 +1061,7 @@ int colvarbias_abf::write_output_files() // Write local data on all replicas write_gradients_samples(output_prefix, true, true); - if (cvm::main()->proxy->replica_index() > 0) { + if (cvmodule->proxy->replica_index() > 0) { // No need to report the same data as replica 0, let it do the I/O job return COLVARS_OK; } @@ -1073,11 +1073,11 @@ int colvarbias_abf::write_output_files() write_gradients_samples(master_prefix); if ((history_freq > 0) && - (!shared_on || cvm::main()->proxy->replica_index() == 0) && // if shared, only on replica 0 - (cvm::step_absolute() % history_freq == 0) && // at requested frequency - (cvm::step_absolute() != history_last_step)) { // not twice the same timestep + (!shared_on || cvmodule->proxy->replica_index() == 0) && // if shared, only on replica 0 + (cvmodule->step_absolute() % history_freq == 0) && // at requested frequency + (cvmodule->step_absolute() != history_last_step)) { // not twice the same timestep write_gradients_samples(master_prefix + ".hist", false); - history_last_step = cvm::step_absolute(); + history_last_step = cvmodule->step_absolute(); } if (b_UI_estimator) { diff --git a/src/colvarbias_abf.h b/src/colvarbias_abf.h index 94045722d..c3cad02da 100644 --- a/src/colvarbias_abf.h +++ b/src/colvarbias_abf.h @@ -31,7 +31,7 @@ class colvarbias_abf : public colvarbias { public: /// Constructor for ABF bias - colvarbias_abf(char const *key); + colvarbias_abf(colvarmodule *cvmodule_in, char const *key); /// Initializer for ABF bias int init(std::string const &conf) override; /// Default destructor for ABF bias diff --git a/src/colvarbias_abmd.cpp b/src/colvarbias_abmd.cpp index 0e44143b8..65031e401 100644 --- a/src/colvarbias_abmd.cpp +++ b/src/colvarbias_abmd.cpp @@ -13,8 +13,8 @@ #include -colvarbias_abmd::colvarbias_abmd(char const *key) - : colvarbias(key), +colvarbias_abmd::colvarbias_abmd(colvarmodule *cvmodule_in, char const *key) + : colvarbias(cvmodule_in, key), colvarbias_ti(key) { } @@ -22,7 +22,7 @@ colvarbias_abmd::colvarbias_abmd(char const *key) int colvarbias_abmd::init(std::string const &conf) { - cvm::main()->cite_feature("ABMD bias"); + cvmodule->cite_feature("ABMD bias"); int err = colvarbias::init(conf); err |= colvarbias_ti::init(conf); @@ -31,11 +31,11 @@ int colvarbias_abmd::init(std::string const &conf) enable(f_cvb_apply_force); if (num_variables() != 1) { - return cvm::error("ABMD requires exactly one collective variable.\n", COLVARS_INPUT_ERROR); + return cvmodule->error("ABMD requires exactly one collective variable.\n", COLVARS_INPUT_ERROR); } if ( ! (variables(0))->is_enabled(f_cv_scalar) ) { - return cvm::error("ABMD colvar must be scalar.\n", COLVARS_INPUT_ERROR); + return cvmodule->error("ABMD colvar must be scalar.\n", COLVARS_INPUT_ERROR); } get_keyval(conf, "forceConstant", k); @@ -48,7 +48,7 @@ int colvarbias_abmd::init(std::string const &conf) int colvarbias_abmd::update() { - if (!cvm::main()->proxy->simulation_running()) { + if (!cvmodule->proxy->simulation_running()) { return COLVARS_OK; } @@ -83,7 +83,7 @@ std::string const colvarbias_abmd::get_state_params() const os.setf(std::ios::scientific, std::ios::floatfield); os << " refValue " - << std::setprecision(cvm::cv_prec) << std::setw(cvm::cv_width) + << std::setprecision(cvmodule->cv_prec) << std::setw(cvmodule->cv_width) << ref_val << "\n"; os << " stoppingValue " << stopping_val << "\n"; os << " forceConstant " << k << "\n"; @@ -118,9 +118,9 @@ int colvarbias_abmd::set_state_params(std::string const &conf) std::ostream & colvarbias_abmd::write_traj_label(std::ostream &os) { - size_t const this_cv_width = (variables(0)->value()).output_width(cvm::cv_width); + size_t const this_cv_width = (variables(0)->value()).output_width(cvmodule->cv_width); os << " ref_" - << cvm::wrap_string(variables(0)->name, this_cv_width-4); + << cvmodule->wrap_string(variables(0)->name, this_cv_width-4); return os; } @@ -129,7 +129,7 @@ std::ostream & colvarbias_abmd::write_traj_label(std::ostream &os) std::ostream & colvarbias_abmd::write_traj(std::ostream &os) { os << " " - << std::setprecision(cvm::cv_prec) << std::setw(cvm::cv_width) + << std::setprecision(cvmodule->cv_prec) << std::setw(cvmodule->cv_width) << ref_val; return os; diff --git a/src/colvarbias_abmd.h b/src/colvarbias_abmd.h index 96278c2de..50ce7aa92 100644 --- a/src/colvarbias_abmd.h +++ b/src/colvarbias_abmd.h @@ -15,17 +15,40 @@ /// \brief Adiabatic Bias MD class colvarbias_abmd - : public colvarbias_ti + : public virtual colvarbias, + public virtual colvarbias_ti { public: - colvarbias_abmd(char const *key); - virtual int init(std::string const &conf); - virtual int update(); - virtual std::string const get_state_params() const; - virtual int set_state_params(std::string const &conf); - virtual std::ostream & write_traj_label(std::ostream &os); - virtual std::ostream & write_traj(std::ostream &os); + colvarbias_abmd(colvarmodule *cvmodule_in, char const *key); + ~colvarbias_abmd() = default; + + int init(std::string const &conf) override; + int update() override; + std::string const get_state_params() const override; + int set_state_params(std::string const &conf) override; + std::ostream & write_traj_label(std::ostream &os) override; + std::ostream & write_traj(std::ostream &os) override; + + std::ostream & write_state_data(std::ostream &os) override { + return colvarbias_ti::write_state_data(os); + } + + cvm::memory_stream & write_state_data(cvm::memory_stream &os) override { + return colvarbias_ti::write_state_data(os); + } + + std::istream & read_state_data(std::istream &is) override { + return colvarbias_ti::read_state_data(is); + } + + cvm::memory_stream & read_state_data(cvm::memory_stream &is) override { + return colvarbias_ti::read_state_data(is); + } + + int write_output_files() override { + return colvarbias_ti::write_output_files(); + } protected: diff --git a/src/colvarbias_alb.cpp b/src/colvarbias_alb.cpp index 039a772c2..1314b4876 100644 --- a/src/colvarbias_alb.cpp +++ b/src/colvarbias_alb.cpp @@ -30,21 +30,21 @@ double fmin(double A, double B) { return ( A < B ? A : B ); } * */ -colvarbias_alb::colvarbias_alb(char const *key) - : colvarbias(key), update_calls(0), b_equilibration(true) +colvarbias_alb::colvarbias_alb(colvarmodule *cvmodule_in, char const *key) + : colvarbias(cvmodule_in, key), update_calls(0), b_equilibration(true) { } int colvarbias_alb::init(std::string const &conf) { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; int error_code = colvarbias::init(conf); if (error_code != COLVARS_OK) { return error_code; } - cvm::main()->cite_feature("ALB colvar bias implementation"); + cvmodule->cite_feature("ALB colvar bias implementation"); enable(f_cvb_scalar_variables); @@ -81,22 +81,22 @@ int colvarbias_alb::init(std::string const &conf) } } else { colvar_centers.clear(); - error_code |= cvm::error("Error: must define the initial centers of adaptive linear bias.\n", + error_code |= cvmodule->error("Error: must define the initial centers of adaptive linear bias.\n", COLVARS_INPUT_ERROR); } if (colvar_centers.size() != num_variables()) { error_code |= - cvm::error("Error: number of centers does not match that of collective variables.\n"); + cvmodule->error("Error: number of centers does not match that of collective variables.\n"); } if (!get_keyval(conf, "updateFrequency", update_freq, 0)) { - error_code |= cvm::error("Error: must set updateFrequency for adaptive linear bias.\n", + error_code |= cvmodule->error("Error: must set updateFrequency for adaptive linear bias.\n", COLVARS_INPUT_ERROR); } if (update_freq % time_step_factor != 0) { - error_code |= cvm::error("updateFrequency (currently " + cvm::to_str(update_freq) + + error_code |= cvmodule->error("updateFrequency (currently " + cvm::to_str(update_freq) + ") must be a multiple of timeStepFactor (" + cvm::to_str(time_step_factor) + ").\n", COLVARS_INPUT_ERROR); @@ -107,7 +107,7 @@ int colvarbias_alb::init(std::string const &conf) if (update_freq <= 1) { error_code |= - cvm::error("Error: must set updateFrequency to greater than 2.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: must set updateFrequency to greater than 2.\n", COLVARS_INPUT_ERROR); } enable(f_cvb_history_dependent); @@ -148,7 +148,7 @@ int colvarbias_alb::init(std::string const &conf) if (cvm::debug()) - cvm::log(" bias.\n"); + cvmodule->log(" bias.\n"); return error_code; } @@ -161,13 +161,13 @@ colvarbias_alb::~colvarbias_alb() int colvarbias_alb::update() { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; bias_energy = 0.0; update_calls += time_step_factor; if (cvm::debug()) - cvm::log("Updating the adaptive linear bias \""+this->name+"\".\n"); + cvmodule->log("Updating the adaptive linear bias \""+this->name+"\".\n"); //log the moments of the CVs // Force and energy calculation @@ -212,7 +212,7 @@ int colvarbias_alb::update() max_coupling_range[i] *= 1.25; logStream << "Expanding coupling range to " << max_coupling_range[i] << ".\n"; - cvm::log(logStream.str()); + cvmodule->log(logStream.str()); } @@ -278,31 +278,31 @@ int colvarbias_alb::set_state_params(std::string const &conf) } if (!get_keyval(conf, "setCoupling", set_coupling)) - cvm::error("Error: current setCoupling is missing from the restart.\n"); + cvmodule->error("Error: current setCoupling is missing from the restart.\n"); if (!get_keyval(conf, "currentCoupling", current_coupling)) - cvm::error("Error: current setCoupling is missing from the restart.\n"); + cvmodule->error("Error: current setCoupling is missing from the restart.\n"); if (!get_keyval(conf, "maxCouplingRange", max_coupling_range)) - cvm::error("Error: maxCouplingRange is missing from the restart.\n"); + cvmodule->error("Error: maxCouplingRange is missing from the restart.\n"); if (!get_keyval(conf, "couplingRate", coupling_rate)) - cvm::error("Error: current setCoupling is missing from the restart.\n"); + cvmodule->error("Error: current setCoupling is missing from the restart.\n"); if (!get_keyval(conf, "couplingAccum", coupling_accum)) - cvm::error("Error: couplingAccum is missing from the restart.\n"); + cvmodule->error("Error: couplingAccum is missing from the restart.\n"); if (!get_keyval(conf, "mean", means)) - cvm::error("Error: current mean is missing from the restart.\n"); + cvmodule->error("Error: current mean is missing from the restart.\n"); if (!get_keyval(conf, "ssd", ssd)) - cvm::error("Error: current ssd is missing from the restart.\n"); + cvmodule->error("Error: current ssd is missing from the restart.\n"); if (!get_keyval(conf, "updateCalls", update_calls)) - cvm::error("Error: current updateCalls is missing from the restart.\n"); + cvmodule->error("Error: current updateCalls is missing from the restart.\n"); if (!get_keyval(conf, "b_equilibration", b_equilibration)) - cvm::error("Error: current updateCalls is missing from the restart.\n"); + cvmodule->error("Error: current updateCalls is missing from the restart.\n"); return COLVARS_OK; } @@ -314,38 +314,38 @@ std::string const colvarbias_alb::get_state_params() const os << " setCoupling "; size_t i; for (i = 0; i < num_variables(); i++) { - os << std::setprecision(cvm::en_prec) - << std::setw(cvm::en_width) << set_coupling[i] << "\n"; + os << std::setprecision(cvmodule->en_prec) + << std::setw(cvmodule->en_width) << set_coupling[i] << "\n"; } os << " currentCoupling "; for (i = 0; i < num_variables(); i++) { - os << std::setprecision(cvm::en_prec) - << std::setw(cvm::en_width) << current_coupling[i] << "\n"; + os << std::setprecision(cvmodule->en_prec) + << std::setw(cvmodule->en_width) << current_coupling[i] << "\n"; } os << " maxCouplingRange "; for (i = 0; i < num_variables(); i++) { - os << std::setprecision(cvm::en_prec) - << std::setw(cvm::en_width) << max_coupling_range[i] << "\n"; + os << std::setprecision(cvmodule->en_prec) + << std::setw(cvmodule->en_width) << max_coupling_range[i] << "\n"; } os << " couplingRate "; for (i = 0; i < num_variables(); i++) { - os << std::setprecision(cvm::en_prec) - << std::setw(cvm::en_width) << coupling_rate[i] << "\n"; + os << std::setprecision(cvmodule->en_prec) + << std::setw(cvmodule->en_width) << coupling_rate[i] << "\n"; } os << " couplingAccum "; for (i = 0; i < num_variables(); i++) { - os << std::setprecision(cvm::en_prec) - << std::setw(cvm::en_width) << coupling_accum[i] << "\n"; + os << std::setprecision(cvmodule->en_prec) + << std::setw(cvmodule->en_width) << coupling_accum[i] << "\n"; } os << " mean "; for (i = 0; i < num_variables(); i++) { - os << std::setprecision(cvm::en_prec) - << std::setw(cvm::en_width) << means[i] << "\n"; + os << std::setprecision(cvmodule->en_prec) + << std::setw(cvmodule->en_width) << means[i] << "\n"; } os << " ssd "; for (i = 0; i < num_variables(); i++) { - os << std::setprecision(cvm::en_prec) - << std::setw(cvm::en_width) << ssd[i] << "\n"; + os << std::setprecision(cvmodule->en_prec) + << std::setw(cvmodule->en_width) << ssd[i] << "\n"; } os << " updateCalls " << update_calls << "\n"; if (b_equilibration) @@ -363,26 +363,26 @@ std::ostream & colvarbias_alb::write_traj_label(std::ostream &os) if (b_output_energy) os << " E_" - << cvm::wrap_string(this->name, cvm::en_width-2); + << cvmodule->wrap_string(this->name, cvmodule->en_width-2); if (b_output_coupling) for (size_t i = 0; i < current_coupling.size(); i++) { os << " ForceConst_" << i - <en_width - 6 - (i / 10 + 1)) << ""; } if (b_output_grad) for (size_t i = 0; i < means.size(); i++) { os << "Grad_" - << cvm::wrap_string(colvars[i]->name, cvm::cv_width - 4); + << cvmodule->wrap_string(colvars[i]->name, cvmodule->cv_width - 4); } if (b_output_centers) for (size_t i = 0; i < num_variables(); i++) { - size_t const this_cv_width = (colvars[i]->value()).output_width(cvm::cv_width); + size_t const this_cv_width = (colvars[i]->value()).output_width(cvmodule->cv_width); os << " x0_" - << cvm::wrap_string(colvars[i]->name, this_cv_width-3); + << cvmodule->wrap_string(colvars[i]->name, this_cv_width-3); } return os; @@ -395,13 +395,13 @@ std::ostream & colvarbias_alb::write_traj(std::ostream &os) if (b_output_energy) os << " " - << std::setprecision(cvm::en_prec) << std::setw(cvm::en_width) + << std::setprecision(cvmodule->en_prec) << std::setw(cvmodule->en_width) << bias_energy; if (b_output_coupling) for (size_t i = 0; i < current_coupling.size(); i++) { os << " " - << std::setprecision(cvm::en_prec) << std::setw(cvm::en_width) + << std::setprecision(cvmodule->en_prec) << std::setw(cvmodule->en_width) << current_coupling[i]; } @@ -409,14 +409,14 @@ std::ostream & colvarbias_alb::write_traj(std::ostream &os) if (b_output_centers) for (size_t i = 0; i < num_variables(); i++) { os << " " - << std::setprecision(cvm::cv_prec) << std::setw(cvm::cv_width) + << std::setprecision(cvmodule->cv_prec) << std::setw(cvmodule->cv_width) << colvar_centers[i]; } if (b_output_grad) for (size_t i = 0; i < means.size(); i++) { os << " " - << std::setprecision(cvm::cv_prec) << std::setw(cvm::cv_width) + << std::setprecision(cvmodule->cv_prec) << std::setw(cvmodule->cv_width) << -2.0 * (means[i] / (static_cast(colvar_centers[i])) - 1) * ssd[i] / (fmax(update_calls, 2.0) - 1); } diff --git a/src/colvarbias_alb.h b/src/colvarbias_alb.h index 4d16a4e7e..e75605fa3 100644 --- a/src/colvarbias_alb.h +++ b/src/colvarbias_alb.h @@ -17,8 +17,7 @@ class colvarbias_alb : public colvarbias { public: - - colvarbias_alb(char const *key); + colvarbias_alb(colvarmodule *cvmodule_in, char const *key); virtual ~colvarbias_alb(); virtual int init(std::string const &conf); virtual int update(); diff --git a/src/colvarbias_histogram.cpp b/src/colvarbias_histogram.cpp index aab2c8f59..cd82afb5e 100644 --- a/src/colvarbias_histogram.cpp +++ b/src/colvarbias_histogram.cpp @@ -16,8 +16,8 @@ #include "colvars_memstream.h" -colvarbias_histogram::colvarbias_histogram(char const *key) - : colvarbias(key), +colvarbias_histogram::colvarbias_histogram(colvarmodule *cvmodule_in, char const *key) + : colvarbias(cvmodule_in, key), grid(NULL), out_name("") { provide(f_cvb_bypass_ext_lagrangian); // Allow histograms of actual cv for extended-Lagrangian @@ -30,7 +30,7 @@ int colvarbias_histogram::init(std::string const &conf) if (err != COLVARS_OK) { return err; } - cvm::main()->cite_feature("Histogram colvar bias implementation"); + cvmodule->cite_feature("Histogram colvar bias implementation"); enable(f_cvb_scalar_variables); enable(f_cvb_history_dependent); @@ -44,7 +44,7 @@ int colvarbias_histogram::init(std::string const &conf) /// with VMD, this may not be an error // if ( output_freq == 0 ) { - // cvm::error("User required histogram with zero output frequency"); + // cvmodule->error("User required histogram with zero output frequency"); // } colvar_array_size = 0; @@ -55,18 +55,18 @@ int colvarbias_histogram::init(std::string const &conf) if (colvar_array) { for (i = 0; i < num_variables(); i++) { // should be all vector if (colvars[i]->value().type() != colvarvalue::type_vector) { - cvm::error("Error: used gatherVectorColvars with non-vector colvar.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: used gatherVectorColvars with non-vector colvar.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } if (i == 0) { colvar_array_size = colvars[i]->value().size(); if (colvar_array_size < 1) { - cvm::error("Error: vector variable has dimension less than one.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: vector variable has dimension less than one.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } } else { if (colvar_array_size != colvars[i]->value().size()) { - cvm::error("Error: trying to combine vector colvars of different lengths.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: trying to combine vector colvars of different lengths.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } } @@ -74,7 +74,7 @@ int colvarbias_histogram::init(std::string const &conf) } else { for (i = 0; i < num_variables(); i++) { // should be all scalar if (colvars[i]->value().type() != colvarvalue::type_scalar) { - cvm::error("Error: only scalar colvars are supported when gatherVectorColvars is off.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: only scalar colvars are supported when gatherVectorColvars is off.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } } @@ -125,7 +125,7 @@ int colvarbias_histogram::update() error_code |= colvarbias::update(); if (cvm::debug()) { - cvm::log("Updating histogram bias " + this->name); + cvmodule->log("Updating histogram bias " + this->name); } // assign a valid bin size @@ -157,7 +157,7 @@ int colvarbias_histogram::update() } } - error_code |= cvm::get_error(); + error_code |= cvmodule->get_error(); return error_code; } @@ -172,22 +172,22 @@ int colvarbias_histogram::write_output_files() int error_code = COLVARS_OK; // Set default filenames, if none have been provided - if (!cvm::output_prefix().empty()) { + if (!cvmodule->output_prefix().empty()) { if (out_name.empty()) { - out_name = cvm::output_prefix() + "." + this->name + ".dat"; + out_name = cvmodule->output_prefix() + "." + this->name + ".dat"; } if (out_name_dx.empty()) { - out_name_dx = cvm::output_prefix() + "." + this->name + ".dx"; + out_name_dx = cvmodule->output_prefix() + "." + this->name + ".dx"; } } if (out_name.size() && out_name != "none") { - cvm::log("Writing the histogram file \""+out_name+"\".\n"); + cvmodule->log("Writing the histogram file \""+out_name+"\".\n"); error_code |= grid->write_multicol(out_name, "histogram output file"); } if (out_name_dx.size() && out_name_dx != "none") { - cvm::log("Writing the histogram file \""+out_name_dx+"\".\n"); + cvmodule->log("Writing the histogram file \""+out_name_dx+"\".\n"); error_code |= grid->write_opendx(out_name_dx, "histogram DX output file"); } diff --git a/src/colvarbias_histogram.h b/src/colvarbias_histogram.h index ed3ee346a..f1390cd87 100644 --- a/src/colvarbias_histogram.h +++ b/src/colvarbias_histogram.h @@ -22,7 +22,7 @@ class colvarbias_histogram : public colvarbias { public: - + colvarbias_histogram(colvarmodule *cvmodule_in, char const *key); colvarbias_histogram(char const *key); virtual ~colvarbias_histogram(); virtual int init(std::string const &conf); diff --git a/src/colvarbias_histogram_reweight_amd.cpp b/src/colvarbias_histogram_reweight_amd.cpp index b0e6b1c0f..2a1878310 100644 --- a/src/colvarbias_histogram_reweight_amd.cpp +++ b/src/colvarbias_histogram_reweight_amd.cpp @@ -11,15 +11,16 @@ #include "colvarproxy.h" #include "colvars_memstream.h" -colvarbias_reweightaMD::colvarbias_reweightaMD(char const *key) : colvarbias_histogram(key) {} +colvarbias_reweightaMD::colvarbias_reweightaMD(colvarmodule *cvmodule_in, char const *key) + : colvarbias_histogram(cvmodule_in, key) {} colvarbias_reweightaMD::~colvarbias_reweightaMD() {} int colvarbias_reweightaMD::init(std::string const &conf) { - if (cvm::proxy->accelMD_enabled() == false) { - cvm::error("Error: accelerated MD in your MD engine is not enabled.\n", COLVARS_INPUT_ERROR); + if (cvmodule->proxy->accelMD_enabled() == false) { + cvmodule->error("Error: accelerated MD in your MD engine is not enabled.\n", COLVARS_INPUT_ERROR); } - cvm::main()->cite_feature("reweightaMD colvar bias implementation (NAMD)"); + cvmodule->cite_feature("reweightaMD colvar bias implementation (NAMD)"); int error_code = colvarbias_histogram::init(conf); get_keyval(conf, "CollectAfterSteps", start_after_steps, 0); get_keyval(conf, "CumulantExpansion", b_use_cumulant_expansion, true); @@ -27,7 +28,7 @@ int colvarbias_reweightaMD::init(std::string const &conf) { get_keyval(conf, "historyFreq", history_freq, 0); if ((history_freq % output_freq) != 0) { error_code |= - cvm::error("Error: historyFreq must be a multiple of outputFreq.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: historyFreq must be a multiple of outputFreq.\n", COLVARS_INPUT_ERROR); } b_history_files = (history_freq > 0); grid_count.reset(new colvar_grid_scalar(colvars, nullptr, false, grid_conf)); @@ -52,17 +53,17 @@ int colvarbias_reweightaMD::init(std::string const &conf) { } int colvarbias_reweightaMD::update() { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; int error_code = COLVARS_OK; - if (cvm::step_relative() >= start_after_steps) { + if (cvmodule->step_relative() >= start_after_steps) { // update base class error_code |= colvarbias::update(); if (cvm::debug()) { - cvm::log("Updating histogram bias " + this->name); + cvmodule->log("Updating histogram bias " + this->name); } - if (cvm::step_relative() > 0) { + if (cvmodule->step_relative() > 0) { previous_bin = bin; } @@ -76,8 +77,8 @@ int colvarbias_reweightaMD::update() { bin[i] = grid->current_bin_scalar(i); } - if (grid->index_ok(previous_bin) && cvm::step_relative() > 0) { - const cvm::real reweighting_factor = cvm::proxy->get_accelMD_factor(); + if (grid->index_ok(previous_bin) && cvmodule->step_relative() > 0) { + const cvm::real reweighting_factor = cvmodule->proxy->get_accelMD_factor(); grid_count->acc_value(previous_bin, 1.0); grid->acc_value(previous_bin, reweighting_factor); if (b_use_cumulant_expansion) { @@ -95,8 +96,8 @@ int colvarbias_reweightaMD::update() { bin[i] = grid->current_bin_scalar(i, iv); } - if (grid->index_ok(previous_bin) && cvm::step_relative() > 0) { - const cvm::real reweighting_factor = cvm::proxy->get_accelMD_factor(); + if (grid->index_ok(previous_bin) && cvmodule->step_relative() > 0) { + const cvm::real reweighting_factor = cvmodule->proxy->get_accelMD_factor(); grid_count->acc_value(previous_bin, 1.0); grid->acc_value(previous_bin, reweighting_factor); if (b_use_cumulant_expansion) { @@ -110,7 +111,7 @@ int colvarbias_reweightaMD::update() { } previous_bin.assign(num_variables(), 0); - error_code |= cvm::get_error(); + error_code |= cvmodule->get_error(); } return error_code; } @@ -118,22 +119,22 @@ int colvarbias_reweightaMD::update() { int colvarbias_reweightaMD::write_output_files() { int error_code = COLVARS_OK; // error_code |= colvarbias_histogram::write_output_files(); - const std::string out_name_pmf = cvm::output_prefix() + "." + + const std::string out_name_pmf = cvmodule->output_prefix() + "." + this->name + ".reweight"; error_code |= write_exponential_reweighted_pmf(out_name_pmf); - const std::string out_count_prefix = cvm::output_prefix() + "." + + const std::string out_count_prefix = cvmodule->output_prefix() + "." + this->name; error_code |= write_count(out_count_prefix); const bool write_history = b_history_files && - (cvm::step_absolute() % history_freq) == 0; + (cvmodule->step_absolute() % history_freq) == 0; if (write_history) { error_code |= write_exponential_reweighted_pmf( out_name_pmf + ".hist", true); error_code |= write_count(out_count_prefix + ".hist", - (cvm::step_relative() > 0)); + (cvmodule->step_relative() > 0)); } if (b_use_cumulant_expansion) { - const std::string out_name_cumulant_pmf = cvm::output_prefix() + "." + + const std::string out_name_cumulant_pmf = cvmodule->output_prefix() + "." + this->name + ".cumulant"; error_code |= write_cumulant_expansion_pmf(out_name_cumulant_pmf); if (write_history) { @@ -141,7 +142,7 @@ int colvarbias_reweightaMD::write_output_files() { out_name_cumulant_pmf + ".hist", true); } } - error_code |= cvm::get_error(); + error_code |= cvmodule->get_error(); return error_code; } @@ -149,8 +150,8 @@ int colvarbias_reweightaMD::write_exponential_reweighted_pmf( const std::string& p_output_prefix, bool keep_open) { const std::string output_pmf = p_output_prefix + ".pmf"; - cvm::log("Writing the accelerated MD PMF file \"" + output_pmf + "\".\n"); - std::ostream &pmf_grid_os = cvm::proxy->output_stream(output_pmf, "PMF file"); + cvmodule->log("Writing the accelerated MD PMF file \"" + output_pmf + "\".\n"); + std::ostream &pmf_grid_os = cvmodule->proxy->output_stream(output_pmf, "PMF file"); if (!pmf_grid_os) { return COLVARS_FILE_ERROR; } @@ -166,14 +167,14 @@ int colvarbias_reweightaMD::write_exponential_reweighted_pmf( hist_to_pmf(pmf_grid_exp_avg.get(), grid_count.get()); pmf_grid_exp_avg->write_multicol(pmf_grid_os); if (!keep_open) { - cvm::proxy->close_output_stream(output_pmf); + cvmodule->proxy->close_output_stream(output_pmf); } if (b_write_gradients) { const std::string output_grad = p_output_prefix + ".grad"; - cvm::log("Writing the accelerated MD gradients file \"" + output_grad + + cvmodule->log("Writing the accelerated MD gradients file \"" + output_grad + "\".\n"); - std::ostream &grad_grid_os = cvm::proxy->output_stream(output_grad, "gradient file"); + std::ostream &grad_grid_os = cvmodule->proxy->output_stream(output_grad, "gradient file"); if (!grad_grid_os) { return COLVARS_FILE_ERROR; } @@ -186,7 +187,7 @@ int colvarbias_reweightaMD::write_exponential_reweighted_pmf( } grad_grid_exp_avg->write_multicol(grad_grid_os); if (!keep_open) { - cvm::proxy->close_output_stream(output_grad); + cvmodule->proxy->close_output_stream(output_grad); } } @@ -196,8 +197,8 @@ int colvarbias_reweightaMD::write_exponential_reweighted_pmf( int colvarbias_reweightaMD::write_cumulant_expansion_pmf( const std::string& p_output_prefix, bool keep_open) { const std::string output_pmf = p_output_prefix + ".pmf"; - cvm::log("Writing the accelerated MD PMF file using cumulant expansion: \"" + output_pmf + "\".\n"); - std::ostream &pmf_grid_cumulant_os = cvm::proxy->output_stream(output_pmf, "PMF file"); + cvmodule->log("Writing the accelerated MD PMF file using cumulant expansion: \"" + output_pmf + "\".\n"); + std::ostream &pmf_grid_cumulant_os = cvmodule->proxy->output_stream(output_pmf, "PMF file"); if (!pmf_grid_cumulant_os) { return COLVARS_FILE_ERROR; } @@ -206,13 +207,13 @@ int colvarbias_reweightaMD::write_cumulant_expansion_pmf( hist_to_pmf(pmf_grid_cumulant.get(), grid_count.get()); pmf_grid_cumulant->write_multicol(pmf_grid_cumulant_os); if (!keep_open) { - cvm::proxy->close_output_stream(output_pmf); + cvmodule->proxy->close_output_stream(output_pmf); } if (b_write_gradients) { const std::string output_grad = p_output_prefix + ".grad"; - cvm::log("Writing the accelerated MD gradients file \"" + output_grad + "\".\n"); - std::ostream &grad_grid_os = cvm::proxy->output_stream(output_grad, "grad file"); + cvmodule->log("Writing the accelerated MD gradients file \"" + output_grad + "\".\n"); + std::ostream &grad_grid_os = cvmodule->proxy->output_stream(output_grad, "grad file"); if (!grad_grid_os) { return COLVARS_FILE_ERROR; } @@ -224,21 +225,21 @@ int colvarbias_reweightaMD::write_cumulant_expansion_pmf( } } grad_grid_cumulant->write_multicol(grad_grid_os); - cvm::proxy->close_output_stream(output_grad); + cvmodule->proxy->close_output_stream(output_grad); } return COLVARS_OK; } int colvarbias_reweightaMD::write_count(const std::string& p_output_prefix, bool keep_open) { const std::string output_name = p_output_prefix + ".count"; - cvm::log("Writing the accelerated MD count file \""+output_name+"\".\n"); - std::ostream &grid_count_os = cvm::proxy->output_stream(output_name, "count file"); + cvmodule->log("Writing the accelerated MD count file \""+output_name+"\".\n"); + std::ostream &grid_count_os = cvmodule->proxy->output_stream(output_name, "count file"); if (!grid_count_os) { return COLVARS_FILE_ERROR; } grid_count->write_multicol(grid_count_os); if (!keep_open) { - cvm::proxy->close_output_stream(output_name); + cvmodule->proxy->close_output_stream(output_name); } return COLVARS_OK; } @@ -247,7 +248,7 @@ void colvarbias_reweightaMD::hist_to_pmf( colvar_grid_scalar* hist, const colvar_grid_scalar* hist_count) const { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; if (hist->raw_data_num() == 0) return; const cvm::real kbt = proxy->boltzmann() * proxy->target_temperature(); bool first_min_element = true; @@ -300,7 +301,7 @@ void colvarbias_reweightaMD::compute_cumulant_expansion_factor( const colvar_grid_scalar* hist_count, colvar_grid_scalar* cumulant_expansion_factor) const { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; const cvm::real beta = 1.0 / (proxy->boltzmann() * proxy->target_temperature()); size_t i = 0; for (i = 0; i < hist_dV->raw_data_num(); ++i) { diff --git a/src/colvarbias_histogram_reweight_amd.h b/src/colvarbias_histogram_reweight_amd.h index 3e3bdede2..8a1984d56 100644 --- a/src/colvarbias_histogram_reweight_amd.h +++ b/src/colvarbias_histogram_reweight_amd.h @@ -16,7 +16,7 @@ /// Gaussian aMD (GaMD) class colvarbias_reweightaMD : public colvarbias_histogram { public: - colvarbias_reweightaMD(char const *key); + colvarbias_reweightaMD(colvarmodule *cvmodule_in, char const *key); virtual ~colvarbias_reweightaMD(); virtual int init(std::string const &conf) override; virtual int update() override; diff --git a/src/colvarbias_meta.cpp b/src/colvarbias_meta.cpp index bad8f2caa..e06751788 100644 --- a/src/colvarbias_meta.cpp +++ b/src/colvarbias_meta.cpp @@ -19,8 +19,8 @@ #include "colvars_memstream.h" -colvarbias_meta::colvarbias_meta(char const *key) - : colvarbias(key), colvarbias_ti(key) +colvarbias_meta::colvarbias_meta(colvarmodule *cvmodule_in, char const *key) + : colvarbias(cvmodule_in, key), colvarbias_ti(key) { new_hills_begin = hills.end(); @@ -54,7 +54,7 @@ int colvarbias_meta::init(std::string const &conf) error_code |= colvarbias::init(conf); error_code |= colvarbias_ti::init(conf); - cvm::main()->cite_feature("Metadynamics colvar bias implementation"); + cvmodule->cite_feature("Metadynamics colvar bias implementation"); enable(f_cvb_calc_pmf); @@ -62,7 +62,7 @@ int colvarbias_meta::init(std::string const &conf) if (hill_weight > 0.0) { enable(f_cvb_apply_force); } else { - cvm::error("Error: hillWeight must be provided, and a positive number.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: hillWeight must be provided, and a positive number.\n", COLVARS_INPUT_ERROR); } get_keyval(conf, "newHillFrequency", new_hill_freq, new_hill_freq); @@ -70,7 +70,7 @@ int colvarbias_meta::init(std::string const &conf) enable(f_cvb_history_dependent); } if (new_hill_freq % time_step_factor != 0) { - error_code |= cvm::error("newHillFrequency (currently " + cvm::to_str(new_hill_freq) + + error_code |= cvmodule->error("newHillFrequency (currently " + cvm::to_str(new_hill_freq) + ") must be a multiple of timeStepFactor (" + cvm::to_str(time_step_factor) + ").\n", COLVARS_INPUT_ERROR); @@ -81,23 +81,23 @@ int colvarbias_meta::init(std::string const &conf) get_keyval(conf, "hillWidth", hill_width, hill_width); if ((colvar_sigmas.size() > 0) && (hill_width > 0.0)) { - error_code |= cvm::error("Error: hillWidth and gaussianSigmas are " + error_code |= cvmodule->error("Error: hillWidth and gaussianSigmas are " "mutually exclusive.", COLVARS_INPUT_ERROR); } if (hill_width > 0.0) { colvar_sigmas.resize(num_variables()); // Print the calculated sigma parameters - cvm::log("Half-widths of the Gaussian hills (sigma's):\n"); + cvmodule->log("Half-widths of the Gaussian hills (sigma's):\n"); for (i = 0; i < num_variables(); i++) { colvar_sigmas[i] = variables(i)->width * hill_width / 2.0; - cvm::log(variables(i)->name+std::string(": ")+ + cvmodule->log(variables(i)->name+std::string(": ")+ cvm::to_str(colvar_sigmas[i])); } } if (colvar_sigmas.size() == 0) { - error_code |= cvm::error("Error: positive values are required for " + error_code |= cvmodule->error("Error: positive values are required for " "either hillWidth or gaussianSigmas.", COLVARS_INPUT_ERROR); } @@ -106,7 +106,7 @@ int colvarbias_meta::init(std::string const &conf) bool b_replicas = false; get_keyval(conf, "multipleReplicas", b_replicas, false); if (b_replicas) { - cvm::main()->cite_feature("Multiple-walker metadynamics colvar bias implementation"); + cvmodule->cite_feature("Multiple-walker metadynamics colvar bias implementation"); comm = multiple_replicas; } else { comm = single_replica; @@ -124,14 +124,14 @@ int colvarbias_meta::init(std::string const &conf) for (i = 0; i < num_variables(); i++) { if (2.0*colvar_sigmas[i] < variables(i)->width) { - cvm::log("Warning: gaussianSigmas is too narrow for the grid " + cvmodule->log("Warning: gaussianSigmas is too narrow for the grid " "spacing along "+variables(i)->name+"."); } } get_keyval(conf, "gridsUpdateFrequency", grids_freq, grids_freq); if (grids_freq % time_step_factor != 0) { - error_code |= cvm::error("gridsUpdateFrequency (currently " + cvm::to_str(grids_freq) + + error_code |= cvmodule->error("gridsUpdateFrequency (currently " + cvm::to_str(grids_freq) + ") must be a multiple of timeStepFactor (" + cvm::to_str(time_step_factor) + ").\n", COLVARS_INPUT_ERROR); @@ -144,7 +144,7 @@ int colvarbias_meta::init(std::string const &conf) variables(i)->enable(f_cv_grid); // Could be a child dependency of a f_cvb_use_grids feature if (variables(i)->expand_boundaries) { expand_grids = true; - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ((comm != single_replica) ? ", replica \""+replica_id+"\"" : "")+ ": Will expand grids when the colvar \""+ variables(i)->name+"\" approaches its boundaries.\n"); @@ -173,7 +173,7 @@ int colvarbias_meta::init(std::string const &conf) error_code |= init_ebmeta_params(conf); if (cvm::debug()) - cvm::log("Done initializing the metadynamics bias \""+this->name+"\""+ + cvmodule->log("Done initializing the metadynamics bias \""+this->name+"\""+ ((comm != single_replica) ? ", replica \""+replica_id+"\"" : "")+".\n"); return error_code; @@ -183,7 +183,7 @@ int colvarbias_meta::init(std::string const &conf) int colvarbias_meta::init_replicas_params(std::string const &conf) { int error_code = COLVARS_OK; - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; // in all cases, the first replica is this bias itself if (replicas.size() == 0) { @@ -200,7 +200,7 @@ int colvarbias_meta::init_replicas_params(std::string const &conf) if (dump_replica_fes && (! dump_fes)) { dump_fes = true; - cvm::log("Enabling \"writeFreeEnergyFile\".\n"); + cvmodule->log("Enabling \"writeFreeEnergyFile\".\n"); } get_keyval(conf, "replicaID", replica_id, replica_id); @@ -208,10 +208,10 @@ int colvarbias_meta::init_replicas_params(std::string const &conf) if (proxy->check_replicas_enabled() == COLVARS_OK) { // Obtain replicaID from the communicator replica_id = cvm::to_str(proxy->replica_index()); - cvm::log("Setting replicaID from communication layer: replicaID = "+ + cvmodule->log("Setting replicaID from communication layer: replicaID = "+ replica_id+".\n"); } else { - error_code |= cvm::error("Error: using more than one replica, but replicaID " + error_code |= cvmodule->error("Error: using more than one replica, but replicaID " "could not be obtained.\n", COLVARS_INPUT_ERROR); } @@ -220,17 +220,17 @@ int colvarbias_meta::init_replicas_params(std::string const &conf) get_keyval(conf, "replicasRegistry", replicas_registry_file, replicas_registry_file); if (!replicas_registry_file.size()) { error_code |= - cvm::error("Error: the name of the \"replicasRegistry\" file must be provided.\n", + cvmodule->error("Error: the name of the \"replicasRegistry\" file must be provided.\n", COLVARS_INPUT_ERROR); } get_keyval(conf, "replicaUpdateFrequency", replica_update_freq, replica_update_freq); if (replica_update_freq == 0) { error_code |= - cvm::error("Error: replicaUpdateFrequency must be positive.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: replicaUpdateFrequency must be positive.\n", COLVARS_INPUT_ERROR); } if (replica_update_freq % time_step_factor != 0) { - error_code |= cvm::error( + error_code |= cvmodule->error( "replicaUpdateFrequency (currently " + cvm::to_str(replica_update_freq) + ") must be a multiple of timeStepFactor (" + cvm::to_str(time_step_factor) + ").\n", COLVARS_INPUT_ERROR); @@ -238,14 +238,14 @@ int colvarbias_meta::init_replicas_params(std::string const &conf) if (expand_grids) { error_code |= - cvm::error("Error: expandBoundaries is not supported when using more than one replicas; " + cvmodule->error("Error: expandBoundaries is not supported when using more than one replicas; " "please allocate wide enough boundaries for each colvar ahead of time.\n", COLVARS_INPUT_ERROR); } if (keep_hills) { error_code |= - cvm::error("Error: multipleReplicas and keepHills are not supported together.\n", + cvmodule->error("Error: multipleReplicas and keepHills are not supported together.\n", COLVARS_INPUT_ERROR); } } @@ -260,12 +260,12 @@ int colvarbias_meta::init_well_tempered_params(std::string const &conf) get_keyval(conf, "wellTempered", well_tempered, false); get_keyval(conf, "biasTemperature", bias_temperature, -1.0); if ((bias_temperature == -1.0) && well_tempered) { - cvm::error("Error: biasTemperature must be set to a positive value.\n", + cvmodule->error("Error: biasTemperature must be set to a positive value.\n", COLVARS_INPUT_ERROR); } if (well_tempered) { - cvm::log("Well-tempered metadynamics is used.\n"); - cvm::log("The bias temperature is "+cvm::to_str(bias_temperature)+".\n"); + cvmodule->log("Well-tempered metadynamics is used.\n"); + cvmodule->log("The bias temperature is "+cvm::to_str(bias_temperature)+".\n"); } return COLVARS_OK; } @@ -277,9 +277,9 @@ int colvarbias_meta::init_ebmeta_params(std::string const &conf) // for ebmeta get_keyval(conf, "ebMeta", ebmeta, false); if(ebmeta){ - cvm::main()->cite_feature("Ensemble-biased metadynamics (ebMetaD)"); + cvmodule->cite_feature("Ensemble-biased metadynamics (ebMetaD)"); if (use_grids && expand_grids) { - error_code |= cvm::error("Error: expandBoundaries is not supported with " + error_code |= cvmodule->error("Error: expandBoundaries is not supported with " "ebMeta; please allocate wide enough boundaries " "for each colvar ahead of time and set " "targetDistFile accordingly.\n", @@ -294,7 +294,7 @@ int colvarbias_meta::init_ebmeta_params(std::string const &conf) cvm::real min_val = target_dist->minimum_value(); cvm::real max_val = target_dist->maximum_value(); if (min_val < 0.0) { - error_code |= cvm::error("Error: Target distribution of EBMetaD " + error_code |= cvmodule->error("Error: Target distribution of EBMetaD " "has negative values!.\n", COLVARS_INPUT_ERROR); } @@ -305,21 +305,21 @@ int colvarbias_meta::init_ebmeta_params(std::string const &conf) target_dist->remove_small_values(target_dist_min_val); } else { if (target_dist_min_val==0) { - cvm::log("NOTE: targetDistMinVal is set to zero, the minimum value of the target \n"); - cvm::log(" distribution will be set as the minimum positive value.\n"); + cvmodule->log("NOTE: targetDistMinVal is set to zero, the minimum value of the target \n"); + cvmodule->log(" distribution will be set as the minimum positive value.\n"); cvm::real min_pos_val = target_dist->minimum_pos_value(); if (min_pos_val <= 0.0){ - error_code |= cvm::error("Error: Target distribution of EBMetaD has " + error_code |= cvmodule->error("Error: Target distribution of EBMetaD has " "negative or zero minimum positive value.\n", COLVARS_INPUT_ERROR); } if (min_val == 0.0){ - cvm::log("WARNING: Target distribution has zero values.\n"); - cvm::log("Zeros will be converted to the minimum positive value.\n"); + cvmodule->log("WARNING: Target distribution has zero values.\n"); + cvmodule->log("Zeros will be converted to the minimum positive value.\n"); target_dist->remove_small_values(min_pos_val); } } else { - error_code |= cvm::error("Error: targetDistMinVal must be a value " + error_code |= cvmodule->error("Error: targetDistMinVal must be a value " "between 0 and 1.\n", COLVARS_INPUT_ERROR); } } @@ -337,7 +337,7 @@ int colvarbias_meta::init_ebmeta_params(std::string const &conf) colvarbias_meta::~colvarbias_meta() { colvarbias_meta::clear_state_data(); - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; proxy->close_output_stream(replica_hills_file); proxy->close_output_stream(hills_traj_file_name()); } @@ -392,7 +392,7 @@ std::list::const_iterator colvarbias_meta::delete_hill(hill_iter &h) { if (cvm::debug()) { - cvm::log("Deleting hill from the metadynamics bias \""+this->name+"\""+ + cvmodule->log("Deleting hill from the metadynamics bias \""+this->name+"\""+ ((comm != single_replica) ? ", replica \""+replica_id+"\"" : "")+ ", with step number "+ cvm::to_str(h->it)+(h->replica.size() ? @@ -442,7 +442,7 @@ int colvarbias_meta::update() } if (comm != single_replica && - (cvm::step_absolute() % replica_update_freq) == 0) { + (cvmodule->step_absolute() % replica_update_freq) == 0) { // sync with the other replicas (if needed) error_code |= replica_share(); } @@ -460,7 +460,7 @@ int colvarbias_meta::update_grid_params() std::vector curr_bin = hills_energy->get_colvars_index(); if (cvm::debug()) { - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ((comm != single_replica) ? ", replica \""+replica_id+"\"" : "")+ ": current coordinates on the grid: "+ cvm::to_str(curr_bin)+".\n"); @@ -496,7 +496,7 @@ int colvarbias_meta::update_grid_params() curr_bin[i] += extra_points; changed_lb = true; - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ((comm != single_replica) ? ", replica \""+replica_id+"\"" : "")+ ": new lower boundary for colvar \""+ variables(i)->name+"\", at "+ @@ -510,7 +510,7 @@ int colvarbias_meta::update_grid_params() new_size += extra_points; changed_ub = true; - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ((comm != single_replica) ? ", replica \""+replica_id+"\"" : "")+ ": new upper boundary for colvar \""+ variables(i)->name+"\", at "+ @@ -548,7 +548,7 @@ int colvarbias_meta::update_grid_params() curr_bin = hills_energy->get_colvars_index(); if (cvm::debug()) - cvm::log("Coordinates on the new grid: "+ + cvmodule->log("Coordinates on the new grid: "+ cvm::to_str(curr_bin)+".\n"); } } @@ -559,24 +559,24 @@ int colvarbias_meta::update_grid_params() int colvarbias_meta::update_bias() { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; // add a new hill if the required time interval has passed - if (((cvm::step_absolute() % new_hill_freq) == 0) && + if (((cvmodule->step_absolute() % new_hill_freq) == 0) && can_accumulate_data() && is_enabled(f_cvb_history_dependent)) { if (cvm::debug()) { - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ((comm != single_replica) ? ", replica \""+replica_id+"\"" : "")+ - ": adding a new hill at step "+cvm::to_str(cvm::step_absolute())+".\n"); + ": adding a new hill at step "+cvm::to_str(cvmodule->step_absolute())+".\n"); } cvm::real hills_scale=1.0; if (ebmeta) { hills_scale *= 1.0/target_dist->value(target_dist->get_colvars_index()); - if(cvm::step_absolute() <= ebmeta_equil_steps) { + if(cvmodule->step_absolute() <= ebmeta_equil_steps) { cvm::real const hills_lambda = - (cvm::real(ebmeta_equil_steps - cvm::step_absolute())) / + (cvm::real(ebmeta_equil_steps - cvmodule->step_absolute())) / (cvm::real(ebmeta_equil_steps)); hills_scale = hills_lambda + (1-hills_lambda)*hills_scale; } @@ -605,7 +605,7 @@ int colvarbias_meta::update_bias() hills_energy_sum_here, &colvar_values); } - // cvm::log("WARNING: computing bias factor for off-grid hills. Hills energy: " + cvm::to_str(hills_energy_sum_here) + "\n"); + // cvmodule->log("WARNING: computing bias factor for off-grid hills. Hills energy: " + cvm::to_str(hills_energy_sum_here) + "\n"); } } else { calc_hills(new_hills_begin, hills.end(), hills_energy_sum_here, NULL); @@ -617,20 +617,20 @@ int colvarbias_meta::update_bias() case single_replica: - add_hill(hill(cvm::step_absolute(), hill_weight*hills_scale, + add_hill(hill(cvmodule, cvmodule->step_absolute(), hill_weight*hills_scale, colvar_values, colvar_sigmas)); break; case multiple_replicas: - add_hill(hill(cvm::step_absolute(), hill_weight*hills_scale, + add_hill(hill(cvmodule, cvmodule->step_absolute(), hill_weight*hills_scale, colvar_values, colvar_sigmas, replica_id)); std::ostream &replica_hills_os = - cvm::proxy->output_stream(replica_hills_file, "replica hills file"); + cvmodule->proxy->output_stream(replica_hills_file, "replica hills file"); if (replica_hills_os) { write_hill(replica_hills_os, hills.back()); } else { - return cvm::error("Error: in metadynamics bias \""+this->name+"\""+ + return cvmodule->error("Error: in metadynamics bias \""+this->name+"\""+ ((comm != single_replica) ? ", replica \""+replica_id+"\"" : "")+ " while writing hills for the other replicas.\n", COLVARS_FILE_ERROR); } @@ -644,7 +644,7 @@ int colvarbias_meta::update_bias() int colvarbias_meta::update_grid_data() { - if ((cvm::step_absolute() % grids_freq) == 0) { + if ((cvmodule->step_absolute() % grids_freq) == 0) { // map the most recent gaussians to the grids project_hills(new_hills_begin, hills.end(), hills_energy.get(), hills_energy_gradients.get()); new_hills_begin = hills.end(); @@ -693,11 +693,11 @@ int colvarbias_meta::calc_energy(std::vector const *values) bias_energy += replicas[ir]->hills_energy->value(curr_bin); if (cvm::debug()) { - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ((comm != single_replica) ? ", replica \""+replica_id+"\"" : "")+ ": current coordinates on the grid: "+ cvm::to_str(curr_bin)+".\n"); - cvm::log("Grid energy = "+cvm::to_str(bias_energy)+".\n"); + cvmodule->log("Grid energy = "+cvm::to_str(bias_energy)+".\n"); } } } else { @@ -719,7 +719,7 @@ int colvarbias_meta::calc_energy(std::vector const *values) bias_energy, values); if (cvm::debug()) { - cvm::log("Hills energy = "+cvm::to_str(bias_energy)+".\n"); + cvmodule->log("Hills energy = "+cvm::to_str(bias_energy)+".\n"); } } @@ -774,7 +774,7 @@ int colvarbias_meta::calc_forces(std::vector const *values) // from new_hills_begin) if (cvm::debug()) { - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ((comm != single_replica) ? ", replica \""+replica_id+"\"" : "")+ ": adding the forces from the other replicas.\n"); } @@ -787,7 +787,7 @@ int colvarbias_meta::calc_forces(std::vector const *values) colvar_forces, values); if (cvm::debug()) { - cvm::log("Hills forces = "+cvm::to_str(colvar_forces)+".\n"); + cvmodule->log("Hills forces = "+cvm::to_str(colvar_forces)+".\n"); } } } @@ -909,7 +909,7 @@ void colvarbias_meta::project_hills(colvarbias_meta::hill_iter h_first, bool print_progress) { if (cvm::debug()) - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ((comm != single_replica) ? ", replica \""+replica_id+"\"" : "")+ ": projecting hills.\n"); @@ -960,18 +960,18 @@ void colvarbias_meta::project_hills(colvarbias_meta::hill_iter h_first, os << std::setw(6) << std::setprecision(2) << 100.0 * progress << "% done."; - cvm::log(os.str()); + cvmodule->log(os.str()); } } } } else { - cvm::error("No grid object provided in metadynamics::project_hills()\n", + cvmodule->error("No grid object provided in metadynamics::project_hills()\n", COLVARS_BUG_ERROR); } if (print_progress) { - cvm::log("100.00% done.\n"); + cvmodule->log("100.00% done.\n"); } if (! keep_hills) { @@ -1005,7 +1005,7 @@ int colvarbias_meta::replica_share() int error_code = COLVARS_OK; // sync with the other replicas (if needed) if (comm == multiple_replicas) { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; // reread the replicas registry error_code |= update_replicas_registry(); // empty the output buffer @@ -1025,10 +1025,10 @@ size_t colvarbias_meta::replica_share_freq() const int colvarbias_meta::update_replicas_registry() { int error_code = COLVARS_OK; - auto *proxy = cvm::main()->proxy; + auto *proxy = cvmodule->proxy; if (cvm::debug()) - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ": updating the list of replicas, currently containing "+ cvm::to_str(replicas.size())+" elements.\n"); @@ -1065,7 +1065,7 @@ int colvarbias_meta::update_replicas_registry() if (new_replica == (replicas[ir])->replica_id) { // this replica was already added if (cvm::debug()) - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ((comm != single_replica) ? ", replica \""+replica_id+"\"" : "")+ ": skipping a replica already loaded, \""+ (replicas[ir])->replica_id+"\".\n"); @@ -1076,9 +1076,9 @@ int colvarbias_meta::update_replicas_registry() if (!already_loaded) { // add this replica to the registry - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ": accessing replica \""+new_replica+"\".\n"); - replicas.push_back(new colvarbias_meta("metadynamics")); + replicas.push_back(new colvarbias_meta(cvmodule, "metadynamics")); (replicas.back())->replica_id = new_replica; (replicas.back())->replica_list_file = new_replica_file; (replicas.back())->replica_state_file = ""; @@ -1112,14 +1112,14 @@ int colvarbias_meta::update_replicas_registry() } } } else { - error_code |= cvm::error("Error: cannot read the replicas registry file \""+ + error_code |= cvmodule->error("Error: cannot read the replicas registry file \""+ replicas_registry+"\".\n", COLVARS_FILE_ERROR); } // now (re)read the list file of each replica for (size_t ir = 0; ir < replicas.size(); ir++) { if (cvm::debug()) - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ": reading the list file for replica \""+ (replicas[ir])->replica_id+"\".\n"); @@ -1133,14 +1133,14 @@ int colvarbias_meta::update_replicas_registry() !(list_is >> key) || !(key == std::string("hillsFile")) || !(list_is >> new_hills_file)) { - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ": failed to read the file \""+ (replicas[ir])->replica_list_file+"\": will try again after "+ cvm::to_str(replica_update_freq)+" steps.\n"); (replicas[ir])->update_status++; } else { if (new_state_file != (replicas[ir])->replica_state_file) { - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ": replica \""+(replicas[ir])->replica_id+ "\" has supplied a new state file, \""+new_state_file+ "\".\n"); @@ -1153,7 +1153,7 @@ int colvarbias_meta::update_replicas_registry() } if (cvm::debug()) - cvm::log("Metadynamics bias \""+this->name+"\": the list of replicas contains "+ + cvmodule->log("Metadynamics bias \""+this->name+"\": the list of replicas contains "+ cvm::to_str(replicas.size())+" elements.\n"); return error_code; @@ -1162,7 +1162,7 @@ int colvarbias_meta::update_replicas_registry() int colvarbias_meta::read_replica_files() { - auto *proxy = cvm::main()->proxy; + auto *proxy = cvmodule->proxy; // Note: we start from the 2nd replica. for (size_t ir = 1; ir < replicas.size(); ir++) { @@ -1171,7 +1171,7 @@ int colvarbias_meta::read_replica_files() if ( (! (replicas[ir])->has_data) || (! (replicas[ir])->replica_state_file_in_sync) ) { if ((replicas[ir])->replica_state_file.size()) { - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ": reading the state of replica \""+ (replicas[ir])->replica_id+"\" from file \""+ (replicas[ir])->replica_state_file+"\".\n"); @@ -1182,7 +1182,7 @@ int colvarbias_meta::read_replica_files() (replicas[ir])->replica_state_file_in_sync = true; (replicas[ir])->update_status = 0; } else { - cvm::log("Failed to read the file \""+ + cvmodule->log("Failed to read the file \""+ (replicas[ir])->replica_state_file+ "\": will try again in "+ cvm::to_str(replica_update_freq)+" steps.\n"); @@ -1191,7 +1191,7 @@ int colvarbias_meta::read_replica_files() } proxy->close_input_stream((replicas[ir])->replica_state_file); } else { - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ": the state file of replica \""+ (replicas[ir])->replica_id+"\" is currently undefined: " "will try again after "+ @@ -1209,7 +1209,7 @@ int colvarbias_meta::read_replica_files() if ((replicas[ir])->replica_hills_file.size()) { if (cvm::debug()) - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ": checking for new hills from replica \""+ (replicas[ir])->replica_id+"\" in the file \""+ (replicas[ir])->replica_hills_file+"\".\n"); @@ -1236,13 +1236,13 @@ int colvarbias_meta::read_replica_files() (replicas[ir])->replica_state_file_in_sync = false; // and record the failure (replicas[ir])->update_status++; - cvm::log("Failed to read the file \""+(replicas[ir])->replica_hills_file+ + cvmodule->log("Failed to read the file \""+(replicas[ir])->replica_hills_file+ "\" at the previous position: will try again in "+ cvm::to_str(replica_update_freq)+" steps.\n"); } else { while ((replicas[ir])->read_hill(is)) { - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ": received a hill from replica \""+ (replicas[ir])->replica_id+ "\" at step "+ @@ -1252,7 +1252,7 @@ int colvarbias_meta::read_replica_files() // store the position for the next read (replicas[ir])->replica_hills_file_pos = is.tellg(); if (cvm::debug()) { - cvm::log("Metadynamics bias \""+this->name+"\""+ + cvmodule->log("Metadynamics bias \""+this->name+"\""+ ": stopped reading file \""+ (replicas[ir])->replica_hills_file+ "\" at position "+ @@ -1269,7 +1269,7 @@ int colvarbias_meta::read_replica_files() } } else { - cvm::log("Failed to read the file \""+ + cvmodule->log("Failed to read the file \""+ (replicas[ir])->replica_hills_file+ "\": will try again in "+ cvm::to_str(replica_update_freq)+" steps.\n"); @@ -1281,7 +1281,7 @@ int colvarbias_meta::read_replica_files() size_t const n_flush = (replica_update_freq/new_hill_freq + 1); if ((replicas[ir])->update_status > 3*n_flush) { // TODO: suspend the calculation? - cvm::log("WARNING: metadynamics bias \""+this->name+"\""+ + cvmodule->log("WARNING: metadynamics bias \""+this->name+"\""+ " could not read information from replica \""+ (replicas[ir])->replica_id+ "\" after more than "+ @@ -1304,16 +1304,16 @@ int colvarbias_meta::set_state_params(std::string const &state_conf) colvarparse::get_keyval(state_conf, "keepHills", restart_keep_hills, false, colvarparse::parse_restart); - if ((!restart_keep_hills) && (cvm::main()->restart_version_number() < 20210604)) { + if ((!restart_keep_hills) && (cvmodule->restart_version_number() < 20210604)) { if (keep_hills) { - cvm::log("Warning: could not ensure that keepHills was enabled when " + cvmodule->log("Warning: could not ensure that keepHills was enabled when " "this state file was written; because it is enabled now, " "it is assumed that it was also then, but please verify.\n"); restart_keep_hills = true; } } else { if (restart_keep_hills) { - cvm::log("This state file/stream contains explicit hills.\n"); + cvmodule->log("This state file/stream contains explicit hills.\n"); } } @@ -1321,7 +1321,7 @@ int colvarbias_meta::set_state_params(std::string const &state_conf) if (colvarparse::get_keyval(state_conf, "replicaID", check_replica, std::string(""), colvarparse::parse_restart) && (check_replica != this->replica_id)) { - return cvm::error("Error: in the state file , the " + return cvmodule->error("Error: in the state file , the " "\"metadynamics\" block has a different replicaID ("+ check_replica+" instead of "+replica_id+").\n", COLVARS_INPUT_ERROR); @@ -1344,7 +1344,7 @@ IST & colvarbias_meta::read_grid_data_template_(IST& is, std::string const &key, is.setstate(std::ios::failbit); if (!rebin_grids) { if ((backup_grid == nullptr) || (comm == single_replica)) { - cvm::error("Error: couldn't read grid data for metadynamics bias \""+ + cvmodule->error("Error: couldn't read grid data for metadynamics bias \""+ this->name+"\""+ ((comm != single_replica) ? ", replica \""+replica_id+"\"" : "")+ "; if useGrids was off when the state file was written, " @@ -1372,7 +1372,7 @@ template IST &colvarbias_meta::read_state_data_template_(IST &is) if (need_backup) { if (cvm::debug()) - cvm::log("Backing up grids for metadynamics bias \"" + this->name + "\"" + + cvmodule->log("Backing up grids for metadynamics bias \"" + this->name + "\"" + ((comm != single_replica) ? ", replica \"" + replica_id + "\"" : "") + ".\n"); hills_energy_backup = std::move(hills_energy); @@ -1389,11 +1389,11 @@ template IST &colvarbias_meta::read_state_data_template_(IST &is) hills_energy_gradients_backup.get()); if (is) { - cvm::log(" successfully read the biasing potential and its gradients from grids.\n"); + cvmodule->log(" successfully read the biasing potential and its gradients from grids.\n"); } else { if (need_backup) { if (cvm::debug()) - cvm::log("Restoring grids from backup for metadynamics bias \"" + this->name + "\"" + + cvmodule->log("Restoring grids from backup for metadynamics bias \"" + this->name + "\"" + ((comm != single_replica) ? ", replica \"" + replica_id + "\"" : "") + ".\n"); // Restoring content from original grid hills_energy->copy_grid(*hills_energy_backup); @@ -1410,14 +1410,14 @@ template IST &colvarbias_meta::read_state_data_template_(IST &is) hill_iter old_hills_end = hills.end(); hill_iter old_hills_off_grid_end = hills_off_grid.end(); if (cvm::debug()) { - cvm::log("Before reading hills from the state file, there are "+ + cvmodule->log("Before reading hills from the state file, there are "+ cvm::to_str(hills.size())+" hills in memory.\n"); } // Read any hills following the grid data (if any) while (read_hill(is)) { if (cvm::debug()) { - cvm::log("Read a previously saved hill under the " + cvmodule->log("Read a previously saved hill under the " "metadynamics bias \"" + this->name + "\", created at step " + cvm::to_str((hills.back()).it) + "; position in stream is " + cvm::to_str(is.tellg()) + ".\n"); @@ -1427,7 +1427,7 @@ template IST &colvarbias_meta::read_state_data_template_(IST &is) is.clear(); new_hills_begin = hills.end(); - cvm::log(" successfully read "+cvm::to_str(hills.size() - old_hills_size)+ + cvmodule->log(" successfully read "+cvm::to_str(hills.size() - old_hills_size)+ " explicit hills from state.\n"); if (existing_hills) { @@ -1435,7 +1435,7 @@ template IST &colvarbias_meta::read_state_data_template_(IST &is) hills.erase(hills.begin(), old_hills_end); hills_off_grid.erase(hills_off_grid.begin(), old_hills_off_grid_end); if (cvm::debug()) { - cvm::log("After pruning the old hills, there are now "+ + cvmodule->log("After pruning the old hills, there are now "+ cvm::to_str(hills.size())+" hills in memory.\n"); } } @@ -1445,7 +1445,7 @@ template IST &colvarbias_meta::read_state_data_template_(IST &is) if (use_grids) { if (!hills_off_grid.empty()) { - cvm::log(cvm::to_str(hills_off_grid.size())+" hills are near the " + cvmodule->log(cvm::to_str(hills_off_grid.size())+" hills are near the " "grid boundaries: they will be computed analytically " "and saved to the state files.\n"); } @@ -1454,7 +1454,7 @@ template IST &colvarbias_meta::read_state_data_template_(IST &is) colvarbias_ti::read_state_data(is); if (cvm::debug()) - cvm::log("colvarbias_meta::read_restart() done\n"); + cvmodule->log("colvarbias_meta::read_restart() done\n"); has_data = true; @@ -1499,20 +1499,20 @@ void colvarbias_meta::rebin_grids_after_restart() tmp_os << hills_energy->get_state_params(); tmp_os << "new_hills_energy parameters:\n"; tmp_os << new_hills_energy->get_state_params(); - cvm::log(tmp_os.str()); + cvmodule->log(tmp_os.str()); } if (restart_keep_hills && !hills.empty()) { // if there are hills, recompute the new grids from them - cvm::log("Rebinning the energy and forces grids from "+ + cvmodule->log("Rebinning the energy and forces grids from "+ cvm::to_str(hills.size())+" hills (this may take a bit)...\n"); project_hills(hills.begin(), hills.end(), new_hills_energy.get(), new_hills_energy_gradients.get(), true); - cvm::log("rebinning done.\n"); + cvmodule->log("rebinning done.\n"); } else { // otherwise, use the grids in the restart file - cvm::log("Rebinning the energy and forces grids " + cvmodule->log("Rebinning the energy and forces grids " "from the grids in the restart file.\n"); new_hills_energy->map_grid(*hills_energy); new_hills_energy_gradients->map_grid(*hills_energy_gradients); @@ -1545,14 +1545,14 @@ OST &colvarbias_meta::write_hill_template_(OST &os, colvarbias_meta::hill const write_state_data_key(os, "step", false); if (formatted) - os << std::setw(cvm::it_width); + os << std::setw(cvmodule->it_width); os << h.it; if (formatted) os << "\n"; write_state_data_key(os, "weight", false); if (formatted) - os << std::setprecision(cvm::en_prec) << std::setw(cvm::en_width); + os << std::setprecision(cvmodule->en_prec) << std::setw(cvmodule->en_width); os << h.W; if (formatted) os << "\n"; @@ -1561,7 +1561,7 @@ OST &colvarbias_meta::write_hill_template_(OST &os, colvarbias_meta::hill const write_state_data_key(os, "centers", false); for (i = 0; i < (h.centers).size(); i++) { if (formatted) - os << " " << std::setprecision(cvm::cv_prec) << std::setw(cvm::cv_width); + os << " " << std::setprecision(cvmodule->cv_prec) << std::setw(cvmodule->cv_width); os << h.centers[i]; } if (formatted) @@ -1571,7 +1571,7 @@ OST &colvarbias_meta::write_hill_template_(OST &os, colvarbias_meta::hill const write_state_data_key(os, "widths", false); for (i = 0; i < (h.sigmas).size(); i++) { if (formatted) - os << " " << std::setprecision(cvm::cv_prec) << std::setw(cvm::cv_width); + os << " " << std::setprecision(cvmodule->cv_prec) << std::setw(cvmodule->cv_width); os << 2.0 * h.sigmas[i]; } if (formatted) @@ -1604,18 +1604,18 @@ cvm::memory_stream &colvarbias_meta::write_hill(cvm::memory_stream &os, } -template IST &hill_stream_error(IST &is, size_t start_pos, std::string const &key) +template IST &hill_stream_error(IST &is, size_t start_pos, std::string const &key, colvarmodule *cvmodule_in) { is.clear(); is.seekg(start_pos); is.setstate(std::ios::failbit); - cvm::error("Error: in reading data for keyword \"" + key + "\" from stream.\n", + cvmodule_in->error("Error: in reading data for keyword \"" + key + "\" from stream.\n", COLVARS_INPUT_ERROR); return is; } -template IST &colvarbias_meta::read_hill_template_(IST &is) +template IST &colvarbias_meta::read_hill_template_(IST &is, colvarmodule *cvmodule_in) { if (!is) return is; // do nothing if failbit is set @@ -1635,7 +1635,7 @@ template IST &colvarbias_meta::read_hill_template_(IST &is) if (formatted) { std::string brace; if (!(is >> brace) || (brace != "{")) { - return hill_stream_error(is, start_pos, "hill"); + return hill_stream_error(is, start_pos, "hill", cvmodule_in); } } @@ -1649,19 +1649,19 @@ template IST &colvarbias_meta::read_hill_template_(IST &is) std::string h_replica; if (!read_state_data_key(is, "step") || !(is >> h_it)) { - return hill_stream_error(is, start_pos, "step"); + return hill_stream_error(is, start_pos, "step", cvmodule_in); } if (read_state_data_key(is, "weight")) { if (!(is >> h_weight)) { - return hill_stream_error(is, start_pos, "weight"); + return hill_stream_error(is, start_pos, "weight", cvmodule_in); } } if (read_state_data_key(is, "centers")) { for (size_t i = 0; i < num_variables(); i++) { if (!(is >> h_centers[i])) { - return hill_stream_error(is, start_pos, "centers"); + return hill_stream_error(is, start_pos, "centers", cvmodule_in); } } } @@ -1669,7 +1669,7 @@ template IST &colvarbias_meta::read_hill_template_(IST &is) if (read_state_data_key(is, "widths")) { for (size_t i = 0; i < num_variables(); i++) { if (!(is >> h_sigmas[i])) { - return hill_stream_error(is, start_pos, "widths"); + return hill_stream_error(is, start_pos, "widths", cvmodule_in); } // For backward compatibility, read the widths instead of the sigmas h_sigmas[i] /= 2.0; @@ -1679,13 +1679,13 @@ template IST &colvarbias_meta::read_hill_template_(IST &is) if (comm != single_replica) { if (read_state_data_key(is, "replicaID")) { if (!(is >> h_replica)) { - return hill_stream_error(is, start_pos, "replicaID"); + return hill_stream_error(is, start_pos, "replicaID", cvmodule_in); } if (h_replica != replica_id) { - cvm::error("Error: trying to read a hill created by replica \"" + h_replica + + cvmodule_in->error("Error: trying to read a hill created by replica \"" + h_replica + "\" for replica \"" + replica_id + "\"; did you swap output files?\n", COLVARS_INPUT_ERROR); - return hill_stream_error(is, start_pos, "replicaID"); + return hill_stream_error(is, start_pos, "replicaID", cvmodule_in); } } } @@ -1693,19 +1693,19 @@ template IST &colvarbias_meta::read_hill_template_(IST &is) if (formatted) { std::string brace; if (!(is >> brace) || (brace != "}")) { - return hill_stream_error(is, start_pos, "hill"); + return hill_stream_error(is, start_pos, "hill", cvmodule_in); } } if ((h_it <= state_file_step) && !restart_keep_hills) { if (cvm::debug()) - cvm::log("Skipping a hill older than the state file for metadynamics bias \"" + this->name + + cvmodule->log("Skipping a hill older than the state file for metadynamics bias \"" + this->name + "\"" + ((comm != single_replica) ? ", replica \"" + replica_id + "\"" : "") + "\n"); return is; } hill_iter const hills_end = hills.end(); - hills.push_back(hill(h_it, h_weight, h_centers, h_sigmas, h_replica)); + hills.push_back(hill(cvmodule, h_it, h_weight, h_centers, h_sigmas, h_replica)); if (new_hills_begin == hills_end) { // if new_hills_begin is unset, set it for the first time new_hills_begin = hills.end(); @@ -1729,13 +1729,13 @@ template IST &colvarbias_meta::read_hill_template_(IST &is) std::istream &colvarbias_meta::read_hill(std::istream &is) { - return read_hill_template_(is); + return read_hill_template_(is, cvmodule); } cvm::memory_stream &colvarbias_meta::read_hill(cvm::memory_stream &is) { - return read_hill_template_(is); + return read_hill_template_(is, cvmodule); } @@ -1743,8 +1743,8 @@ int colvarbias_meta::setup_output() { int error_code = COLVARS_OK; - output_prefix = cvm::output_prefix(); - if (cvm::main()->num_biases_feature(colvardeps::f_cvb_calc_pmf) > 1) { + output_prefix = cvmodule->output_prefix(); + if (cvmodule->num_biases_feature(colvardeps::f_cvb_calc_pmf) > 1) { // if this is not the only free energy integrator, append // this bias's name, to distinguish it from the output of the other // biases producing a .pmf file @@ -1753,17 +1753,17 @@ int colvarbias_meta::setup_output() if (comm == multiple_replicas) { - auto const pwd = cvm::main()->proxy->get_current_work_dir(); + auto const pwd = cvmodule->proxy->get_current_work_dir(); replica_list_file = - cvm::main()->proxy->join_paths(pwd, this->name + "." + replica_id + ".files.txt"); + cvmodule->proxy->join_paths(pwd, this->name + "." + replica_id + ".files.txt"); // replica_hills_file and replica_state_file are those written // by the current replica; within the mirror biases, they are // those by another replica - replica_hills_file = cvm::main()->proxy->join_paths( - pwd, cvm::output_prefix() + ".colvars." + this->name + "." + replica_id + ".hills"); + replica_hills_file = cvmodule->proxy->join_paths( + pwd, cvmodule->output_prefix() + ".colvars." + this->name + "." + replica_id + ".hills"); - replica_state_file = cvm::main()->proxy->join_paths( - pwd, cvm::output_prefix() + ".colvars." + this->name + "." + replica_id + ".state"); + replica_state_file = cvmodule->proxy->join_paths( + pwd, cvmodule->output_prefix() + ".colvars." + this->name + "." + replica_id + ".state"); // now register this replica @@ -1771,7 +1771,7 @@ int colvarbias_meta::setup_output() bool registered_replica = false; // Open without failing on error: the file may not be there yet std::istream ®_is = - cvm::main()->proxy->input_stream(replicas_registry_file, "replicas registry file", false); + cvmodule->proxy->input_stream(replicas_registry_file, "replicas registry file", false); if (reg_is) { std::string existing_replica(""); std::string existing_replica_file(""); @@ -1785,7 +1785,7 @@ int colvarbias_meta::setup_output() } } } - cvm::main()->proxy->close_input_stream(replicas_registry_file); + cvmodule->proxy->close_input_stream(replicas_registry_file); // if this replica was not included yet, we should generate a // new record for it: but first, we write this replica's files, @@ -1804,11 +1804,11 @@ int colvarbias_meta::setup_output() // if we're running without grids, use a growing list of "hills" files // otherwise, just one state file and one "hills" file as buffer - std::ostream &list_os = cvm::proxy->output_stream(replica_list_file, "replica list file"); + std::ostream &list_os = cvmodule->proxy->output_stream(replica_list_file, "replica list file"); if (list_os) { list_os << "stateFile " << replica_state_file << "\n"; list_os << "hillsFile " << replica_hills_file << "\n"; - cvm::proxy->close_output_stream(replica_list_file); + cvmodule->proxy->close_output_stream(replica_list_file); } else { error_code |= COLVARS_FILE_ERROR; } @@ -1826,7 +1826,7 @@ int colvarbias_meta::setup_output() if (b_hills_traj) { std::ostream &hills_traj_os = - cvm::proxy->output_stream(hills_traj_file_name(), "hills trajectory file"); + cvmodule->proxy->output_stream(hills_traj_file_name(), "hills trajectory file"); if (!hills_traj_os) { error_code |= COLVARS_FILE_ERROR; } @@ -1838,7 +1838,7 @@ int colvarbias_meta::setup_output() std::string const colvarbias_meta::hills_traj_file_name() const { - return std::string(cvm::output_prefix()+ + return std::string(cvmodule->output_prefix()+ ".colvars."+this->name+ ( (comm != single_replica) ? ("."+replica_id) : @@ -1929,9 +1929,9 @@ int colvarbias_meta::write_output_files() } if (b_hills_traj) { std::ostream &hills_traj_os = - cvm::proxy->output_stream(hills_traj_file_name(), "hills trajectory file"); + cvmodule->proxy->output_stream(hills_traj_file_name(), "hills trajectory file"); hills_traj_os << hills_traj_os_buf.str(); - cvm::proxy->flush_output_stream(hills_traj_file_name()); + cvmodule->proxy->flush_output_stream(hills_traj_file_name()); // clear the buffer hills_traj_os_buf.str(""); hills_traj_os_buf.clear(); @@ -1942,7 +1942,7 @@ int colvarbias_meta::write_output_files() void colvarbias_meta::write_pmf() { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; // allocate a new grid to store the pmf colvar_grid_scalar *pmf = new colvar_grid_scalar(*hills_energy); pmf->setup(); @@ -1976,7 +1976,7 @@ void colvarbias_meta::write_pmf() std::string const fes_file_name(this->output_prefix + ((comm != single_replica) ? ".partial" : "") + (dump_fes_save ? - "."+cvm::to_str(cvm::step_absolute()) : "") + + "."+cvm::to_str(cvmodule->step_absolute()) : "") + ".pmf"); pmf->write_multicol(fes_file_name, "PMF file"); } @@ -2012,7 +2012,7 @@ void colvarbias_meta::write_pmf() } std::string const fes_file_name(this->output_prefix + (dump_fes_save ? - "."+cvm::to_str(cvm::step_absolute()) : "") + + "."+cvm::to_str(cvmodule->step_absolute()) : "") + ".pmf"); pmf->write_multicol(fes_file_name, "partial PMF file"); } @@ -2024,10 +2024,10 @@ void colvarbias_meta::write_pmf() int colvarbias_meta::write_replica_state_file() { - colvarproxy *proxy = cvm::proxy; + colvarproxy *proxy = cvmodule->proxy; if (cvm::debug()) { - cvm::log("Writing replica state file for bias \""+name+"\"\n"); + cvmodule->log("Writing replica state file for bias \""+name+"\"\n"); } int error_code = COLVARS_OK; @@ -2035,10 +2035,10 @@ int colvarbias_meta::write_replica_state_file() // Write to temporary state file std::string const tmp_state_file(replica_state_file+".tmp"); error_code |= proxy->remove_file(tmp_state_file); - std::ostream &rep_state_os = cvm::proxy->output_stream(tmp_state_file, "temporary state file"); + std::ostream &rep_state_os = cvmodule->proxy->output_stream(tmp_state_file, "temporary state file"); if (rep_state_os) { if (!write_state(rep_state_os)) { - error_code |= cvm::error("Error: in writing to temporary file \""+ + error_code |= cvmodule->error("Error: in writing to temporary file \""+ tmp_state_file+"\".\n", COLVARS_FILE_ERROR); } } @@ -2053,7 +2053,7 @@ int colvarbias_meta::write_replica_state_file() int colvarbias_meta::reopen_replica_buffer_file() { int error_code = COLVARS_OK; - colvarproxy *proxy = cvm::proxy; + colvarproxy *proxy = cvmodule->proxy; if (proxy->output_stream(replica_hills_file, "replica hills file")) { error_code |= proxy->close_output_stream(replica_hills_file); } @@ -2072,7 +2072,7 @@ std::string colvarbias_meta::hill::output_traj() { std::ostringstream os; os.setf(std::ios::fixed, std::ios::floatfield); - os << std::setw(cvm::it_width) << it << " "; + os << std::setw(cvmodule->it_width) << it << " "; os.setf(std::ios::scientific, std::ios::floatfield); @@ -2080,26 +2080,27 @@ std::string colvarbias_meta::hill::output_traj() os << " "; for (i = 0; i < centers.size(); i++) { os << " "; - os << std::setprecision(cvm::cv_prec) - << std::setw(cvm::cv_width) << centers[i]; + os << std::setprecision(cvmodule->cv_prec) + << std::setw(cvmodule->cv_width) << centers[i]; } os << " "; for (i = 0; i < sigmas.size(); i++) { os << " "; - os << std::setprecision(cvm::cv_prec) - << std::setw(cvm::cv_width) << sigmas[i]; + os << std::setprecision(cvmodule->cv_prec) + << std::setw(cvmodule->cv_width) << sigmas[i]; } os << " "; - os << std::setprecision(cvm::en_prec) - << std::setw(cvm::en_width) << W << "\n"; + os << std::setprecision(cvmodule->en_prec) + << std::setw(cvmodule->en_width) << W << "\n"; return os.str(); } -colvarbias_meta::hill::hill(cvm::step_number it_in, +colvarbias_meta::hill::hill(colvarmodule *cvmodule_in, + cvm::step_number it_in, cvm::real W_in, std::vector const &cv_values, std::vector const &cv_sigmas, @@ -2109,7 +2110,8 @@ colvarbias_meta::hill::hill(cvm::step_number it_in, W(W_in), centers(cv_values.size()), sigmas(cv_values.size()), - replica(replica_in) + replica(replica_in), + cvmodule(cvmodule_in) { hill_value = 0.0; for (size_t i = 0; i < cv_values.size(); i++) { @@ -2118,7 +2120,7 @@ colvarbias_meta::hill::hill(cvm::step_number it_in, sigmas[i] = cv_sigmas[i]; } if (cvm::debug()) { - cvm::log("New hill, applied to "+cvm::to_str(cv_values.size())+ + cvmodule->log("New hill, applied to "+cvm::to_str(cv_values.size())+ " collective variables, with centers "+ cvm::to_str(centers)+", sigmas "+ cvm::to_str(sigmas)+" and weight "+ @@ -2134,7 +2136,8 @@ colvarbias_meta::hill::hill(colvarbias_meta::hill const &h) W(h.W), centers(h.centers), sigmas(h.sigmas), - replica(h.replica) + replica(h.replica), + cvmodule(h.cvmodule) { hill_value = 0.0; } diff --git a/src/colvarbias_meta.h b/src/colvarbias_meta.h index c9a1d602f..47e2de458 100644 --- a/src/colvarbias_meta.h +++ b/src/colvarbias_meta.h @@ -41,7 +41,7 @@ class colvarbias_meta /// Communication between different replicas Communication comm; - colvarbias_meta(char const *key); + colvarbias_meta(colvarmodule *cvmodule_in, char const *key); ~colvarbias_meta(); int init(std::string const &conf) override; @@ -138,7 +138,7 @@ class colvarbias_meta /// Write a hill to an unformatted stream cvm::memory_stream &write_hill(cvm::memory_stream &os, hill const &h); - template IST &read_hill_template_(IST &is); + template IST &read_hill_template_(IST &is, colvarmodule *cvmodule_in); /// Read a new hill from a formatted stream std::istream & read_hill(std::istream &is); @@ -326,17 +326,20 @@ class colvarbias_meta::hill { /// Identity of the replica who added this hill std::string replica; + colvarmodule *cvmodule; public: friend class colvarbias_meta; /// Constructor of a hill object + /// \param cvmodule Pointer to the colvarmodule object /// \param it Step number at which the hill was added /// \param W Weight of the hill (energy units) /// \param cv_values Array of collective variable values /// \param cv_sigmas Array of collective variable values /// \param replica ID of the replica that creates the hill (optional) - hill(cvm::step_number it, cvm::real W, + hill(colvarmodule *cvmodule, + cvm::step_number it, cvm::real W, std::vector const &cv_values, std::vector const &cv_sigmas, std::string const &replica = ""); diff --git a/src/colvarbias_opes.cpp b/src/colvarbias_opes.cpp index f022f472d..c9373b7f1 100644 --- a/src/colvarbias_opes.cpp +++ b/src/colvarbias_opes.cpp @@ -43,8 +43,8 @@ #include -colvarbias_opes::colvarbias_opes(char const *key): - colvarbias(key), m_kbt(0), m_barrier(0), m_biasfactor(0), +colvarbias_opes::colvarbias_opes(colvarmodule *cvmodule_in, char const *key): + colvarbias(cvmodule_in, key), m_kbt(0), m_barrier(0), m_biasfactor(0), m_bias_prefactor(0), m_temperature(0), m_pace(0), m_adaptive_sigma_stride(0), m_adaptive_counter(0), m_counter(1), @@ -65,7 +65,7 @@ colvarbias_opes::colvarbias_opes(char const *key): m_explore(false), m_inf_biasfactor(false) { #ifdef OPES_THREADING - provide(f_cvb_smp, cvm::proxy->get_smp_mode() == colvarproxy_smp::smp_mode_t::inner_loop); + provide(f_cvb_smp, cvmodule->proxy->get_smp_mode() == colvarproxy_smp::smp_mode_t::inner_loop); if (is_available(f_cvb_smp)){ enable(f_cvb_smp); // Enabled by default } @@ -76,11 +76,11 @@ int colvarbias_opes::init(const std::string& conf) { int error_code = colvarbias::init(conf); enable(f_cvb_scalar_variables); get_keyval_feature(this, conf, "applyBias", f_cvb_apply_force, true); - m_temperature = cvm::proxy->target_temperature(); - m_kbt = m_temperature * cvm::proxy->boltzmann(); + m_temperature = cvmodule->proxy->target_temperature(); + m_kbt = m_temperature * cvmodule->proxy->boltzmann(); get_keyval(conf, "newHillFrequency", m_pace); if (m_pace % time_step_factor != 0) { - error_code |= cvm::error("newHillFrequency (currently " + cvm::to_str(m_pace) + + error_code |= cvmodule->error("newHillFrequency (currently " + cvm::to_str(m_pace) + ") must be a multiple of timeStepFactor (" + cvm::to_str(time_step_factor) + ").\n", COLVARS_INPUT_ERROR); @@ -88,12 +88,12 @@ int colvarbias_opes::init(const std::string& conf) { get_keyval(conf, "barrier", m_barrier); get_keyval(conf, "explore", m_explore, false); if (m_barrier < 0) { - return cvm::error("the barrier should be greater than zero", COLVARS_INPUT_ERROR); + return cvmodule->error("the barrier should be greater than zero", COLVARS_INPUT_ERROR); } std::string biasfactor_str; get_keyval(conf, "biasfactor", biasfactor_str); - if ((cvm::proxy->target_temperature() == 0.0) && cvm::proxy->simulation_running()) { - cvm::log("WARNING: OPES should not be run without a thermostat or at 0 Kelvin!\n"); + if ((cvmodule->proxy->target_temperature() == 0.0) && cvmodule->proxy->simulation_running()) { + cvmodule->log("WARNING: OPES should not be run without a thermostat or at 0 Kelvin!\n"); } m_biasfactor = m_barrier / m_kbt; m_inf_biasfactor = biasfactor_str == "inf" || biasfactor_str == "INF"; @@ -101,18 +101,18 @@ int colvarbias_opes::init(const std::string& conf) { m_biasfactor = std::numeric_limits::infinity(); m_bias_prefactor = 1; if (m_explore) { - return cvm::error("biasfactor cannot be infinity in the explore mode."); + return cvmodule->error("biasfactor cannot be infinity in the explore mode."); } } else { if (biasfactor_str.size() > 0) { try { m_biasfactor = std::stod(biasfactor_str); } catch (const std::exception& e) { - return cvm::error(e.what(), COLVARS_INPUT_ERROR); + return cvmodule->error(e.what(), COLVARS_INPUT_ERROR); } } if (m_biasfactor <= 1.0) { - return cvm::error("biasfactor must be greater than one (use \"inf\" for uniform target)"); + return cvmodule->error("biasfactor must be greater than one (use \"inf\" for uniform target)"); } m_bias_prefactor = 1 - 1.0 / m_biasfactor; } @@ -127,18 +127,18 @@ int colvarbias_opes::init(const std::string& conf) { if (m_adaptive_sigma) { get_keyval(conf, "adaptiveSigmaStride", m_adaptive_sigma_stride, 0); if (m_inf_biasfactor) { - return cvm::error("cannot use infinite biasfactor with adaptive sigma", + return cvmodule->error("cannot use infinite biasfactor with adaptive sigma", COLVARS_INPUT_ERROR); } if (m_adaptive_sigma_stride == 0) { m_adaptive_sigma_stride = m_pace * 10; } if (m_adaptive_sigma_stride < m_pace) { - return cvm::error("It is better to choose an adaptiveSigmaStride >= newHillFrequency.\n", COLVARS_INPUT_ERROR); + return cvmodule->error("It is better to choose an adaptiveSigmaStride >= newHillFrequency.\n", COLVARS_INPUT_ERROR); } } else { if (m_sigma0.size() != num_variables()) { - return cvm::error("number of sigma parameters does not match the number of variables", + return cvmodule->error("number of sigma parameters does not match the number of variables", COLVARS_INPUT_ERROR); } if (m_explore) { @@ -149,18 +149,18 @@ int colvarbias_opes::init(const std::string& conf) { } get_keyval(conf, "gaussianSigmaMin", m_sigma_min); if ((m_sigma_min.size() != 0) && (m_sigma_min.size() != num_variables())) { - return cvm::error("incorrect number of parameters of gaussianSigmaMin"); + return cvmodule->error("incorrect number of parameters of gaussianSigmaMin"); } if (m_sigma_min.size() > 0 && !m_adaptive_sigma) { for (size_t i = 0; i < num_variables(); ++i) { if (m_sigma_min[i] > m_sigma0[i]) { - return cvm::error("gaussianSigmaMin of variable " + cvm::to_str(i) + " should be smaller than sigma"); + return cvmodule->error("gaussianSigmaMin of variable " + cvm::to_str(i) + " should be smaller than sigma"); } } } get_keyval(conf, "epsilon", m_epsilon, std::exp(-m_barrier/m_bias_prefactor/m_kbt)); if (m_epsilon <= 0) { - return cvm::error("you must choose a value of epsilon greater than zero"); + return cvmodule->error("you must choose a value of epsilon greater than zero"); } m_sum_weights = std::pow(m_epsilon, m_bias_prefactor); m_sum_weights2 = m_sum_weights * m_sum_weights; @@ -170,14 +170,14 @@ int colvarbias_opes::init(const std::string& conf) { get_keyval(conf, "kernelCutoff", m_cutoff, std::sqrt(2.0*m_barrier/m_bias_prefactor/m_kbt)); } if (m_cutoff <= 0) { - return cvm::error("you must choose a value of kernelCutoff greater than zero"); + return cvmodule->error("you must choose a value of kernelCutoff greater than zero"); } m_cutoff2 = m_cutoff * m_cutoff; m_val_at_cutoff = std::exp(-0.5 * m_cutoff2); get_keyval(conf, "compressionThreshold", m_compression_threshold, 1); if (m_compression_threshold != 0) { if (m_compression_threshold < 0 || m_compression_threshold > m_cutoff) { - return cvm::error("compressionThreshold cannot be smaller than 0 or larger than kernelCutoff", COLVARS_INPUT_ERROR); + return cvmodule->error("compressionThreshold cannot be smaller than 0 or larger than kernelCutoff", COLVARS_INPUT_ERROR); } } m_compression_threshold2 = m_compression_threshold * m_compression_threshold; @@ -191,17 +191,17 @@ int colvarbias_opes::init(const std::string& conf) { m_nlist_param[1] = 0.5; //*nlist_dev2_[i] -> condition for rebuilding } else { if (nlist_param.size() != 2) { - return cvm::error("two cutoff parameters are needed for the neighbor list", COLVARS_INPUT_ERROR); + return cvmodule->error("two cutoff parameters are needed for the neighbor list", COLVARS_INPUT_ERROR); } if (nlist_param[0] <= 1.0) { - return cvm::error("the first of neighborListParam must be greater than 1.0. The smaller the first, the smaller should be the second as well", COLVARS_INPUT_ERROR); + return cvmodule->error("the first of neighborListParam must be greater than 1.0. The smaller the first, the smaller should be the second as well", COLVARS_INPUT_ERROR); } const cvm::real min_PARAM_1 = (1.-1./std::sqrt(nlist_param[0]))+0.16; if (nlist_param[1] <= 0) { - return cvm::error("the second of neighborListParam must be greater than 0", COLVARS_INPUT_ERROR); + return cvmodule->error("the second of neighborListParam must be greater than 0", COLVARS_INPUT_ERROR); } if (nlist_param[1] > min_PARAM_1) { - return cvm::error("the second of neighborListParam must be smaller to avoid systematic errors. Largest suggested value is: 1.16-1/sqrt(param_0) = " + cvm::to_str(min_PARAM_1), COLVARS_INPUT_ERROR); + return cvmodule->error("the second of neighborListParam must be smaller to avoid systematic errors. Largest suggested value is: 1.16-1/sqrt(param_0) = " + cvm::to_str(min_PARAM_1), COLVARS_INPUT_ERROR); } m_nlist_param = nlist_param; } @@ -224,13 +224,13 @@ int colvarbias_opes::init(const std::string& conf) { #ifdef OPES_THREADING get_keyval_feature(this, conf, "smp", f_cvb_smp, is_enabled(f_cvb_smp)); if (is_enabled(f_cvb_smp)) { - m_num_threads = cvm::proxy->smp_num_threads(); + m_num_threads = cvmodule->proxy->smp_num_threads(); } else { m_num_threads = 1; } #else if (m_num_threads > 1) { - return cvm::error("Multi-threading requested in OPES, which is not supported by this build.\n"); + return cvmodule->error("Multi-threading requested in OPES, which is not supported by this build.\n"); } #endif bool serial = false; @@ -238,11 +238,11 @@ int colvarbias_opes::init(const std::string& conf) { if (serial) m_num_threads = 1; comm = b_replicas ? multiple_replicas : single_replica; if (comm == multiple_replicas) { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; get_keyval(conf, "replicaID", replica_id, replica_id); get_keyval(conf, "sharedFreq", shared_freq, output_freq); if (shared_freq % time_step_factor != 0) { - error_code |= cvm::error("sharedFreq (currently " + cvm::to_str(shared_freq) + + error_code |= cvmodule->error("sharedFreq (currently " + cvm::to_str(shared_freq) + ") must be a multiple of timeStepFactor (" + cvm::to_str(time_step_factor) + ").\n", COLVARS_INPUT_ERROR); @@ -251,11 +251,11 @@ int colvarbias_opes::init(const std::string& conf) { if (proxy->check_replicas_enabled() == COLVARS_OK) { // Obtain replicaID from the communicator replica_id = cvm::to_str(proxy->replica_index()); - cvm::log("Setting replicaID from communication layer: replicaID = "+ + cvmodule->log("Setting replicaID from communication layer: replicaID = "+ replica_id+".\n"); } else { error_code |= - cvm::error("Error: using more than one replica, but replicaID could not be obtained.\n", + cvmodule->error("Error: using more than one replica, but replicaID could not be obtained.\n", COLVARS_INPUT_ERROR); } } @@ -270,7 +270,7 @@ int colvarbias_opes::init(const std::string& conf) { for (size_t i = 0; i < num_variables(); ++i) { if (variables(i)->name == (*it)) { if (variables(i)->enable(f_cv_grid) != COLVARS_OK) { - return cvm::error("CV " + (*it) + " does not support grid\n"); + return cvmodule->error("CV " + (*it) + " does not support grid\n"); } m_pmf_cvs.push_back(variables(i)); found = true; @@ -278,7 +278,7 @@ int colvarbias_opes::init(const std::string& conf) { } } if (!found) { - return cvm::error("CV " + (*it) + " not found\n"); + return cvmodule->error("CV " + (*it) + " not found\n"); } } key_lookup(conf, "grid", &grid_conf); @@ -286,7 +286,7 @@ int colvarbias_opes::init(const std::string& conf) { m_pmf_grid.reset(new colvar_grid_scalar(m_pmf_cvs, m_reweight_grid)); get_keyval(conf, "pmfHistoryFrequency", m_pmf_hist_freq, output_freq); if ((m_pmf_hist_freq % output_freq) != 0) { - error_code |= cvm::error("Error: pmfHistoryFrequency must be a multiple of outputFreq.\n", + error_code |= cvmodule->error("Error: pmfHistoryFrequency must be a multiple of outputFreq.\n", COLVARS_INPUT_ERROR); } if (comm == multiple_replicas) { @@ -303,9 +303,9 @@ int colvarbias_opes::init(const std::string& conf) { m_traj_line.zed = m_zed; m_traj_line.neff = (1 + m_sum_weights) * (1 + m_sum_weights) / (1 + m_sum_weights2); m_traj_line.nker = m_kernels.size(); - get_keyval(conf, "printTrajectoryFrequency", m_traj_output_frequency, cvm::cv_traj_freq); + get_keyval(conf, "printTrajectoryFrequency", m_traj_output_frequency, cvmodule->cv_traj_freq); if (m_traj_output_frequency % time_step_factor != 0) { - error_code |= cvm::error( + error_code |= cvmodule->error( "printTrajectoryFrequency (currently " + cvm::to_str(m_traj_output_frequency) + ") must be a multiple of timeStepFactor (" + cvm::to_str(time_step_factor) + ").\n", COLVARS_INPUT_ERROR); @@ -318,18 +318,18 @@ int colvarbias_opes::init(const std::string& conf) { void colvarbias_opes::showInfo() const { // Print information about this bias auto printInfo = [&](const std::string& info, const std::string& val){ - cvm::log(this->name + ": " + info + val + "\n"); + cvmodule->log(this->name + ": " + info + val + "\n"); }; - printInfo("temperature = ", cvm::to_str(m_kbt / cvm::proxy->boltzmann())); + printInfo("temperature = ", cvm::to_str(m_kbt / cvmodule->proxy->boltzmann())); printInfo("beta = ", cvm::to_str(1.0 / m_kbt)); printInfo("depositing new kernels with newHillFrequency = ", cvm::to_str(m_pace)); printInfo("expected barrier is ", cvm::to_str(m_barrier)); printInfo("using target distribution with biasfactor (gamma) = ", m_inf_biasfactor ? "inf" : cvm::to_str(m_biasfactor)); if (m_inf_biasfactor) { - cvm::log(" (thus a uniform flat target distribution, no well-tempering)\n"); - cvm::log(this->name + ": " + "the equivalent bias temperature = inf\n"); + cvmodule->log(" (thus a uniform flat target distribution, no well-tempering)\n"); + cvmodule->log(this->name + ": " + "the equivalent bias temperature = inf\n"); } else { - cvm::log(this->name + ": " + "the equivalent bias temperature = " + cvm::to_str(cvm::proxy->target_temperature() * (m_biasfactor - 1))); + cvmodule->log(this->name + ": " + "the equivalent bias temperature = " + cvm::to_str(cvmodule->proxy->target_temperature() * (m_biasfactor - 1))); } if (m_adaptive_sigma) { printInfo("adaptive sigma will be used, with adaptiveSigmaStride = ", cvm::to_str(m_adaptive_sigma_stride)); @@ -340,45 +340,45 @@ void colvarbias_opes::showInfo() const { for (size_t i = 0; i < num_variables(); ++i) { sigmas += " " + cvm::to_str(m_sigma0[i]); } - cvm::log(this->name + ": kernels have initial gaussianSigma = " + sigmas + "\n"); + cvmodule->log(this->name + ": kernels have initial gaussianSigma = " + sigmas + "\n"); } if (m_fixed_sigma) { - cvm::log(this->name + " fixedGaussianSigma: gaussianSigma will not decrease as the simulation proceeds\n"); + cvmodule->log(this->name + " fixedGaussianSigma: gaussianSigma will not decrease as the simulation proceeds\n"); } printInfo("kernels are truncated with kernelCutoff = ", cvm::to_str(m_cutoff)); if (m_cutoff < 3.5) { - cvm::log(this->name + " +++ WARNING +++ probably kernels are truncated too much\n"); + cvmodule->log(this->name + " +++ WARNING +++ probably kernels are truncated too much\n"); } printInfo("the value at cutoff is = ", cvm::to_str(m_val_at_cutoff)); printInfo("regularization epsilon = ", cvm::to_str(m_epsilon)); if (m_val_at_cutoff > m_epsilon*(1+1e-6)) { - cvm::log(this->name + " +++ WARNING +++ the kernelCutoff might be too small for the given epsilon\n"); + cvmodule->log(this->name + " +++ WARNING +++ the kernelCutoff might be too small for the given epsilon\n"); } printInfo("kernels will be compressed when closer than compression_threshold = ", cvm::to_str(m_compression_threshold)); if (m_compression_threshold2 == 0) { - cvm::log(this->name + " +++ WARNING +++ kernels will never merge, expect slowdowns\n"); + cvmodule->log(this->name + " +++ WARNING +++ kernels will never merge, expect slowdowns\n"); } if (!m_recursive_merge) { - cvm::log(this->name + " -- RECURSIVE_MERGE_OFF: only one merge for each new kernel will be attempted. This is faster only if total number of kernels does not grow too much\n"); + cvmodule->log(this->name + " -- RECURSIVE_MERGE_OFF: only one merge for each new kernel will be attempted. This is faster only if total number of kernels does not grow too much\n"); } if (m_nlist) { - cvm::log(this->name + " neighborList: using neighbor list for kernels, with parameters: " + cvm::to_str(m_nlist_param[0]) + " " + cvm::to_str(m_nlist_param[1]) + "\n"); + cvmodule->log(this->name + " neighborList: using neighbor list for kernels, with parameters: " + cvm::to_str(m_nlist_param[0]) + " " + cvm::to_str(m_nlist_param[1]) + "\n"); if (m_nlist_pace_reset) { - cvm::log(this->name + " neighborListNewHillReset: forcing the neighbor list to update every time when depositing a new hill\n"); + cvmodule->log(this->name + " neighborListNewHillReset: forcing the neighbor list to update every time when depositing a new hill\n"); } } if (m_no_zed) { printInfo("noZed: using fixed normalization factor = ", cvm::to_str(m_zed)); } if (comm == multiple_replicas && m_num_walkers > 1) { - cvm::log(this->name + " if multiple replicas are present, they will share the same bias\n"); + cvmodule->log(this->name + " if multiple replicas are present, they will share the same bias\n"); } if (m_num_threads > 1) { printInfo("using multiple threads per simulation: ", cvm::to_str(m_num_threads)); } - cvm::main()->cite_feature("OPES"); + cvmodule->cite_feature("OPES"); if (m_adaptive_sigma || m_explore) { - cvm::main()->cite_feature("OPES explore or adaptive kernels"); + cvmodule->cite_feature("OPES explore or adaptive kernels"); } } @@ -450,7 +450,7 @@ cvm::real colvarbias_opes::getProbAndDerivatives( std::vector> derivs(m_num_threads, std::vector(num_variables(), 0)); std::vector> dists(m_num_threads, std::vector(num_variables(), 0)); auto worker = [&](int start, int end, void* result){ - const int tid = cvm::proxy->smp_thread_id(); + const int tid = cvmodule->proxy->smp_thread_id(); double tmp_prob = 0; for (int i = start; i <= end; ++i) { tmp_prob += evaluateKernel(m_kernels[i], cv, derivs[tid], dists[tid]); @@ -469,7 +469,7 @@ cvm::real colvarbias_opes::getProbAndDerivatives( } } #else - cvm::error("multiple threads required in OPES, but this binary is not linked with a supported threading library.\n"); + cvmodule->error("multiple threads required in OPES, but this binary is not linked with a supported threading library.\n"); #endif } } else { @@ -503,7 +503,7 @@ cvm::real colvarbias_opes::getProbAndDerivatives( std::vector> derivs(m_num_threads, std::vector(num_variables(), 0)); std::vector> dists(m_num_threads, std::vector(num_variables(), 0)); auto worker = [&](int start, int end, void* result){ - const int tid = cvm::proxy->smp_thread_id(); + const int tid = cvmodule->proxy->smp_thread_id(); double tmp_prob = 0; for (int i = start; i <= end; ++i) { const size_t k = m_nlist_index[i]; @@ -523,7 +523,7 @@ cvm::real colvarbias_opes::getProbAndDerivatives( } } #else - cvm::error("multiple threads required in OPES, but this binary is not linked with a supported threading library.\n"); + cvmodule->error("multiple threads required in OPES, but this binary is not linked with a supported threading library.\n"); #endif } } @@ -539,7 +539,7 @@ int colvarbias_opes::calculate_opes() { ++m_nlist_steps; const bool exchange_step = (comm == multiple_replicas) && - cvm::step_absolute() % shared_freq == 0; + cvmodule->step_absolute() % shared_freq == 0; if (exchange_step) { m_nlist_update = true; } else { @@ -582,7 +582,7 @@ int colvarbias_opes::update_opes() { return COLVARS_OK;; } } - if (cvm::step_absolute() % m_pace == 0) { + if (cvmodule->step_absolute() % m_pace == 0) { m_old_kdenorm = m_kdenorm; m_delta_kernels.clear(); const size_t old_nker = m_kernels.size(); @@ -592,66 +592,66 @@ int colvarbias_opes::update_opes() { cvm::real sum_heights = height; cvm::real sum_heights2 = height * height; if (m_num_walkers > 1) { - std::vector replica_sum_heights(cvm::proxy->num_replicas() - 1, 0); + std::vector replica_sum_heights(cvmodule->proxy->num_replicas() - 1, 0); // Send all sum_heights to PE 0 - if (cvm::proxy->replica_index() == 0) { - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { - if (cvm::proxy->replica_comm_recv((char*)&(replica_sum_heights[p - 1]), sizeof(cvm::real), p) != sizeof(cvm::real)) { - return cvm::error("Error: receiving sum of weights from replica " + cvm::to_str(p)); + if (cvmodule->proxy->replica_index() == 0) { + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { + if (cvmodule->proxy->replica_comm_recv((char*)&(replica_sum_heights[p - 1]), sizeof(cvm::real), p) != sizeof(cvm::real)) { + return cvmodule->error("Error: receiving sum of weights from replica " + cvm::to_str(p)); } } } else { - if (cvm::proxy->replica_comm_send((char*)&sum_heights, sizeof(cvm::real), 0) != sizeof(cvm::real)) { - return cvm::error("Error: sending sum of weights to replica 0."); + if (cvmodule->proxy->replica_comm_send((char*)&sum_heights, sizeof(cvm::real), 0) != sizeof(cvm::real)) { + return cvmodule->error("Error: sending sum of weights to replica 0."); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // PE 0 sum all sum_heights and broadcast - if (cvm::proxy->replica_index() == 0) { + if (cvmodule->proxy->replica_index() == 0) { for (auto it = replica_sum_heights.begin(); it != replica_sum_heights.end(); ++it) { sum_heights += (*it); } - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { - if (cvm::proxy->replica_comm_send((char*)&sum_heights, sizeof(cvm::real), p) != sizeof(cvm::real)) { - return cvm::error("Error: sending sum of weights to replica " + cvm::to_str(p)); + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { + if (cvmodule->proxy->replica_comm_send((char*)&sum_heights, sizeof(cvm::real), p) != sizeof(cvm::real)) { + return cvmodule->error("Error: sending sum of weights to replica " + cvm::to_str(p)); } } } else { - if (cvm::proxy->replica_comm_recv((char*)&sum_heights, sizeof(cvm::real), 0) != sizeof(cvm::real)) { - return cvm::error("Error: receiving sum of weights from replica 0."); + if (cvmodule->proxy->replica_comm_recv((char*)&sum_heights, sizeof(cvm::real), 0) != sizeof(cvm::real)) { + return cvmodule->error("Error: receiving sum of weights from replica 0."); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // Send all sum_heights2 to PE 0 - std::vector replica_sum_heights2(cvm::proxy->num_replicas() - 1, 0); - if (cvm::proxy->replica_index() == 0) { - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { - if (cvm::proxy->replica_comm_recv((char*)&(replica_sum_heights2[p - 1]), sizeof(cvm::real), p) != sizeof(cvm::real)) { - return cvm::error("Error: getting sum of weights2 from replica " + cvm::to_str(p)); + std::vector replica_sum_heights2(cvmodule->proxy->num_replicas() - 1, 0); + if (cvmodule->proxy->replica_index() == 0) { + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { + if (cvmodule->proxy->replica_comm_recv((char*)&(replica_sum_heights2[p - 1]), sizeof(cvm::real), p) != sizeof(cvm::real)) { + return cvmodule->error("Error: getting sum of weights2 from replica " + cvm::to_str(p)); } } } else { - if (cvm::proxy->replica_comm_send((char*)&sum_heights2, sizeof(cvm::real), 0) != sizeof(cvm::real)) { - return cvm::error("Error: sending sum of weights2 from replica."); + if (cvmodule->proxy->replica_comm_send((char*)&sum_heights2, sizeof(cvm::real), 0) != sizeof(cvm::real)) { + return cvmodule->error("Error: sending sum of weights2 from replica."); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // PE 0 sum all sum_heights2 and broadcast - if (cvm::proxy->replica_index() == 0) { + if (cvmodule->proxy->replica_index() == 0) { for (auto it = replica_sum_heights2.begin(); it != replica_sum_heights2.end(); ++it) { sum_heights2 += (*it); } - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { - if (cvm::proxy->replica_comm_send((char*)&sum_heights2, sizeof(cvm::real), p) != sizeof(cvm::real)) { - return cvm::error("Error: sending sum of weights2 to replica " + cvm::to_str(p)); + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { + if (cvmodule->proxy->replica_comm_send((char*)&sum_heights2, sizeof(cvm::real), p) != sizeof(cvm::real)) { + return cvmodule->error("Error: sending sum of weights2 to replica " + cvm::to_str(p)); } } } else { - if (cvm::proxy->replica_comm_recv((char*)&sum_heights2, sizeof(cvm::real), 0) != sizeof(cvm::real)) { - return cvm::error("Error: receiving sum of weights2 from replica."); + if (cvmodule->proxy->replica_comm_recv((char*)&sum_heights2, sizeof(cvm::real), 0) != sizeof(cvm::real)) { + return cvmodule->error("Error: receiving sum of weights2 from replica."); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); } m_counter += m_num_walkers; m_sum_weights += sum_heights; @@ -679,7 +679,7 @@ int colvarbias_opes::update_opes() { if (m_sigma_min.size() == 0) { for (size_t i = 0; i < num_variables(); ++i) { if (m_sigma0[i] < 1e-6) { - cvm::error("Adaptive sigma is suspiciously small for CV " + cvm::to_str(i) + "\nManually provide sigma or set a safe sigma_min to avoid possible issues\n"); + cvmodule->error("Adaptive sigma is suspiciously small for CV " + cvm::to_str(i) + "\nManually provide sigma or set a safe sigma_min to avoid possible issues\n"); return COLVARS_ERROR; } } @@ -696,7 +696,7 @@ int colvarbias_opes::update_opes() { bool sigma_less_than_threshold = false; for (size_t i = 0; i < num_variables(); ++i) { if (sigma[i] < 1e-6) { - cvm::log("The adaptive sigma is suspiciously small, you should set a safe sigma_min. 1e-6 will be used here\n"); + cvmodule->log("The adaptive sigma is suspiciously small, you should set a safe sigma_min. 1e-6 will be used here\n"); sigma[i] = 1e-6; sigma_less_than_threshold = true; } @@ -736,167 +736,167 @@ int colvarbias_opes::update_opes() { std::vector all_center(m_num_walkers * num_variables(), 0.0); std::vector all_sigma(m_num_walkers * num_variables(), 0.0); std::vector all_logweight(m_num_walkers, 0.0); - const int my_replica = cvm::proxy->replica_index(); + const int my_replica = cvmodule->proxy->replica_index(); // Allgather of heights if (my_replica == 0) { all_height[0] = height; - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { - if (cvm::proxy->replica_comm_recv((char*)&(all_height[p]), sizeof(decltype(all_height)::value_type), p) != sizeof(decltype(all_height)::value_type)) { - return cvm::error("Error: on receiving height on replica 0 from replica " + cvm::to_str(p)); + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { + if (cvmodule->proxy->replica_comm_recv((char*)&(all_height[p]), sizeof(decltype(all_height)::value_type), p) != sizeof(decltype(all_height)::value_type)) { + return cvmodule->error("Error: on receiving height on replica 0 from replica " + cvm::to_str(p)); } } } else { - if (cvm::proxy->replica_comm_send((char*)&height, sizeof(decltype(height)), 0) != sizeof(cvm::real)) { - return cvm::error("Error: on sending height to replica 0 from replica " + cvm::to_str(my_replica)); + if (cvmodule->proxy->replica_comm_send((char*)&height, sizeof(decltype(height)), 0) != sizeof(cvm::real)) { + return cvmodule->error("Error: on sending height to replica 0 from replica " + cvm::to_str(my_replica)); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // Broadcast heights if (my_replica == 0) { const int send_size = sizeof(decltype(all_height)::value_type) * all_height.size(); - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { - if (cvm::proxy->replica_comm_send((char*)all_height.data(), send_size, p) != send_size) { - return cvm::error("Error: on sending heights from replica 0 to replica " + cvm::to_str(p)); + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { + if (cvmodule->proxy->replica_comm_send((char*)all_height.data(), send_size, p) != send_size) { + return cvmodule->error("Error: on sending heights from replica 0 to replica " + cvm::to_str(p)); } } } else { const int recv_size = sizeof(decltype(all_height)::value_type) * all_height.size(); - if (cvm::proxy->replica_comm_recv((char*)all_height.data(), recv_size, 0) != recv_size) { - return cvm::error("Error: on receiving heights from replica 0 to replica " + cvm::to_str(my_replica)); + if (cvmodule->proxy->replica_comm_recv((char*)all_height.data(), recv_size, 0) != recv_size) { + return cvmodule->error("Error: on receiving heights from replica 0 to replica " + cvm::to_str(my_replica)); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // Allgather of centers if (my_replica == 0) { std::copy(m_cv.begin(), m_cv.end(), all_center.begin()); const int recv_size = sizeof(decltype(m_cv)::value_type) * m_cv.size(); - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { cvm::real* recv_start_ptr = &(all_center[p * m_cv.size()]); - if (cvm::proxy->replica_comm_recv((char*)recv_start_ptr, recv_size, p) != recv_size) { - return cvm::error("Error on receiving centers from replica 0 to replica " + cvm::to_str(p)); + if (cvmodule->proxy->replica_comm_recv((char*)recv_start_ptr, recv_size, p) != recv_size) { + return cvmodule->error("Error on receiving centers from replica 0 to replica " + cvm::to_str(p)); } } } else { const int send_size = sizeof(decltype(m_cv)::value_type) * m_cv.size(); - if (cvm::proxy->replica_comm_send((char*)m_cv.data(), send_size, 0) != send_size) { - return cvm::error("Error on sending centers to replica 0 from replica " + cvm::to_str(my_replica)); + if (cvmodule->proxy->replica_comm_send((char*)m_cv.data(), send_size, 0) != send_size) { + return cvmodule->error("Error on sending centers to replica 0 from replica " + cvm::to_str(my_replica)); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // Broadcast centers if (my_replica == 0) { const int send_size = sizeof(decltype(all_center)::value_type) * all_center.size(); - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { - if (cvm::proxy->replica_comm_send((char*)all_center.data(), send_size, p) != send_size) { - return cvm::error("Error on sending centers from replica 0 to replica " + cvm::to_str(p)); + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { + if (cvmodule->proxy->replica_comm_send((char*)all_center.data(), send_size, p) != send_size) { + return cvmodule->error("Error on sending centers from replica 0 to replica " + cvm::to_str(p)); } } } else { const int recv_size = sizeof(decltype(all_center)::value_type) * all_center.size(); - if (cvm::proxy->replica_comm_recv((char*)all_center.data(), recv_size, 0) != recv_size) { - return cvm::error("Error on receiving centers from replica 0 to replica " + cvm::to_str(my_replica)); + if (cvmodule->proxy->replica_comm_recv((char*)all_center.data(), recv_size, 0) != recv_size) { + return cvmodule->error("Error on receiving centers from replica 0 to replica " + cvm::to_str(my_replica)); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // Allgather of sigmas if (my_replica == 0) { std::copy(sigma.begin(), sigma.end(), all_sigma.begin()); const int recv_size = sizeof(decltype(sigma)::value_type) * sigma.size(); - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { cvm::real* recv_start_ptr = &(all_sigma[p * m_cv.size()]); - if (cvm::proxy->replica_comm_recv((char*)recv_start_ptr, recv_size, p) != recv_size) { - return cvm::error("Error on receiving sigmas from replica 0 to replica " + cvm::to_str(p)); + if (cvmodule->proxy->replica_comm_recv((char*)recv_start_ptr, recv_size, p) != recv_size) { + return cvmodule->error("Error on receiving sigmas from replica 0 to replica " + cvm::to_str(p)); } } } else { const int send_size = sizeof(decltype(sigma)::value_type) * sigma.size(); - if (cvm::proxy->replica_comm_send((char*)sigma.data(), send_size, 0) != send_size) { - return cvm::error("Error on sending sigmas to replica 0 from replica " + cvm::to_str(my_replica)); + if (cvmodule->proxy->replica_comm_send((char*)sigma.data(), send_size, 0) != send_size) { + return cvmodule->error("Error on sending sigmas to replica 0 from replica " + cvm::to_str(my_replica)); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // Broadcast sigmas if (my_replica == 0) { const int send_size = sizeof(decltype(all_sigma)::value_type) * all_sigma.size(); - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { - if (cvm::proxy->replica_comm_send((char*)all_sigma.data(), send_size, p) != send_size) { - return cvm::error("Error on sending sigmas from replica 0 to replica " + cvm::to_str(p)); + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { + if (cvmodule->proxy->replica_comm_send((char*)all_sigma.data(), send_size, p) != send_size) { + return cvmodule->error("Error on sending sigmas from replica 0 to replica " + cvm::to_str(p)); } } } else { const int recv_size = sizeof(decltype(all_sigma)::value_type) * all_sigma.size(); - if (cvm::proxy->replica_comm_recv((char*)all_sigma.data(), recv_size, 0) != recv_size) { - return cvm::error("Error on receiving sigmas from replica 0 to replica " + cvm::to_str(my_replica)); + if (cvmodule->proxy->replica_comm_recv((char*)all_sigma.data(), recv_size, 0) != recv_size) { + return cvmodule->error("Error on receiving sigmas from replica 0 to replica " + cvm::to_str(my_replica)); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // Allgather of logweights if (my_replica == 0) { all_logweight[0] = log_weight; - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { - if (cvm::proxy->replica_comm_recv((char*)&(all_logweight[p]), sizeof(decltype(all_logweight)::value_type), p) != sizeof(decltype(all_logweight)::value_type)) { - return cvm::error("Error on receiving log_weight on replica 0 from replica " + cvm::to_str(p)); + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { + if (cvmodule->proxy->replica_comm_recv((char*)&(all_logweight[p]), sizeof(decltype(all_logweight)::value_type), p) != sizeof(decltype(all_logweight)::value_type)) { + return cvmodule->error("Error on receiving log_weight on replica 0 from replica " + cvm::to_str(p)); } } } else { - if (cvm::proxy->replica_comm_send((char*)&log_weight, sizeof(decltype(log_weight)), 0) != sizeof(cvm::real)) { - return cvm::error("Error on sending log_weight to replica 0 from replica " + cvm::to_str(my_replica)); + if (cvmodule->proxy->replica_comm_send((char*)&log_weight, sizeof(decltype(log_weight)), 0) != sizeof(cvm::real)) { + return cvmodule->error("Error on sending log_weight to replica 0 from replica " + cvm::to_str(my_replica)); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // Broadcast log_weight if (my_replica == 0) { const int send_size = sizeof(decltype(all_logweight)::value_type) * all_logweight.size(); - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { - if (cvm::proxy->replica_comm_send((char*)all_logweight.data(), send_size, p) != send_size) { - return cvm::error("Error on sending log_weight from replica 0 to replica " + cvm::to_str(p)); + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { + if (cvmodule->proxy->replica_comm_send((char*)all_logweight.data(), send_size, p) != send_size) { + return cvmodule->error("Error on sending log_weight from replica 0 to replica " + cvm::to_str(p)); } } } else { const int recv_size = sizeof(decltype(all_logweight)::value_type) * all_logweight.size(); - if (cvm::proxy->replica_comm_recv((char*)all_logweight.data(), recv_size, 0) != recv_size) { - return cvm::error("Error on receiving log_weight from replica 0 to replica " + cvm::to_str(my_replica)); + if (cvmodule->proxy->replica_comm_recv((char*)all_logweight.data(), recv_size, 0) != recv_size) { + return cvmodule->error("Error on receiving log_weight from replica 0 to replica " + cvm::to_str(my_replica)); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); if (m_nlist) { std::vector all_nlist_size(m_num_walkers); - const int my_replica = cvm::proxy->replica_index(); + const int my_replica = cvmodule->proxy->replica_index(); // Get the size of the neighbor list of each replica if (my_replica == 0) { all_nlist_size[0] = m_nlist_index.size(); - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { - if (cvm::proxy->replica_comm_recv((char*)&(all_nlist_size[p]), sizeof(int), p) != sizeof(int)) { - return cvm::error("Error on receiving neighbor list size from replica " + cvm::to_str(p)); + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { + if (cvmodule->proxy->replica_comm_recv((char*)&(all_nlist_size[p]), sizeof(int), p) != sizeof(int)) { + return cvmodule->error("Error on receiving neighbor list size from replica " + cvm::to_str(p)); } } } else { const int nlist_size = m_nlist_index.size(); - if (cvm::proxy->replica_comm_send((char*)&nlist_size, sizeof(int), 0) != sizeof(int)) { - return cvm::error("Error on sending neighbor list size from replica " + cvm::to_str(my_replica)); + if (cvmodule->proxy->replica_comm_send((char*)&nlist_size, sizeof(int), 0) != sizeof(int)) { + return cvmodule->error("Error on sending neighbor list size from replica " + cvm::to_str(my_replica)); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // Broadcast the neighbor list sizes to all replicas if (my_replica == 0) { const int send_size = sizeof(int) * all_nlist_size.size(); - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { - if (cvm::proxy->replica_comm_send((char*)all_nlist_size.data(), send_size, p) != send_size) { - return cvm::error("Error on sending neighbor list sizes from replica 0 to replica " + cvm::to_str(p)); + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { + if (cvmodule->proxy->replica_comm_send((char*)all_nlist_size.data(), send_size, p) != send_size) { + return cvmodule->error("Error on sending neighbor list sizes from replica 0 to replica " + cvm::to_str(p)); } } } else { const int recv_size = sizeof(int) * all_nlist_size.size(); - if (cvm::proxy->replica_comm_recv((char*)all_nlist_size.data(), recv_size, 0) != recv_size) { - return cvm::error("Error on receiving neighbor list sizes to replica " + cvm::to_str(my_replica)); + if (cvmodule->proxy->replica_comm_recv((char*)all_nlist_size.data(), recv_size, 0) != recv_size) { + return cvmodule->error("Error on receiving neighbor list sizes to replica " + cvm::to_str(my_replica)); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // Gather all neighbor lists from replicas const int tot_size = std::accumulate(all_nlist_size.begin(), all_nlist_size.end(), 0); if (tot_size > 0) { @@ -908,35 +908,35 @@ int colvarbias_opes::update_opes() { recv_start[0] = 0; std::partial_sum(all_nlist_size.begin(), all_nlist_size.end() - 1, recv_start.begin() + 1); std::copy(m_nlist_index.begin(), m_nlist_index.end(), all_nlist_index.begin()); - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { size_t* recv_start_ptr = &(all_nlist_index[recv_start[p]]); const int recv_size = all_nlist_size[p] * sizeof(decltype(all_nlist_index)::value_type); - if (cvm::proxy->replica_comm_recv((char*)recv_start_ptr, recv_size, p) != recv_size) { - return cvm::error("Error on receiving neighbor list from replica " + cvm::to_str(p)); + if (cvmodule->proxy->replica_comm_recv((char*)recv_start_ptr, recv_size, p) != recv_size) { + return cvmodule->error("Error on receiving neighbor list from replica " + cvm::to_str(p)); } } } else { const int send_size = sizeof(decltype(m_nlist_index)::value_type) * m_nlist_index.size(); - if (cvm::proxy->replica_comm_send((char*)m_nlist_index.data(), send_size, 0) != send_size) { - return cvm::error("Error on sending neighbor list from replica " + cvm::to_str(my_replica)); + if (cvmodule->proxy->replica_comm_send((char*)m_nlist_index.data(), send_size, 0) != send_size) { + return cvmodule->error("Error on sending neighbor list from replica " + cvm::to_str(my_replica)); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // Broadcast the neighbor list if (my_replica == 0) { const int send_size = sizeof(decltype(all_nlist_index)::value_type) * tot_size; - for (int p = 1; p < cvm::proxy->num_replicas(); ++p) { - if (cvm::proxy->replica_comm_send((char*)all_nlist_index.data(), send_size, p) != send_size) { - return cvm::error("Error on sending total neighbor list to replica " + cvm::to_str(p)); + for (int p = 1; p < cvmodule->proxy->num_replicas(); ++p) { + if (cvmodule->proxy->replica_comm_send((char*)all_nlist_index.data(), send_size, p) != send_size) { + return cvmodule->error("Error on sending total neighbor list to replica " + cvm::to_str(p)); } } } else { const int recv_size = sizeof(decltype(all_nlist_index)::value_type) * tot_size; - if (cvm::proxy->replica_comm_recv((char*)all_nlist_index.data(), recv_size, 0) != recv_size) { - return cvm::error("Error on receiving total neighbor list on replica " + cvm::to_str(my_replica)); + if (cvmodule->proxy->replica_comm_recv((char*)all_nlist_index.data(), recv_size, 0) != recv_size) { + return cvmodule->error("Error on receiving total neighbor list on replica " + cvm::to_str(my_replica)); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // Deduplicate and sort the merged neighbor list std::unordered_set all_nlist_index_set; for (auto it = all_nlist_index.cbegin(); it != all_nlist_index.cend(); ++it) { @@ -1006,11 +1006,11 @@ int colvarbias_opes::update_opes() { m_num_threads, lowerRange, upperRange, worker, &sum_uprob, CKLOOP_DOUBLE_SUM, NULL); #else - cvm::error("OPES cannot run because this binary is not linked with a supported threading library.\n"); + cvmodule->error("OPES cannot run because this binary is not linked with a supported threading library.\n"); #endif } if (num_parallel > 1) { - return cvm::error("Unimplemented feature: OPES in parallel running.\n"); + return cvmodule->error("Unimplemented feature: OPES in parallel running.\n"); } } else { cvm::real delta_sum_uprob = 0; @@ -1051,7 +1051,7 @@ int colvarbias_opes::update_opes() { m_num_threads, lowerRange, upperRange, worker, &delta_sum_uprob, CKLOOP_DOUBLE_SUM, NULL); #else - cvm::error("OPES cannot run because this binary is not linked with a supported threading library.\n"); + cvmodule->error("OPES cannot run because this binary is not linked with a supported threading library.\n"); #endif } } else { @@ -1094,12 +1094,12 @@ int colvarbias_opes::update_opes() { m_num_threads, lowerRange, upperRange, worker, &delta_sum_uprob, CKLOOP_DOUBLE_SUM, NULL); #else - cvm::error("OPES cannot run because this binary is not linked with a supported threading library.\n"); + cvmodule->error("OPES cannot run because this binary is not linked with a supported threading library.\n"); #endif } } if (num_parallel > 1) { - return cvm::error("Unimplemented feature: OPES in parallel running.\n"); + return cvmodule->error("Unimplemented feature: OPES in parallel running.\n"); } if (m_num_threads == 1) { for (size_t d = 0; d < m_delta_kernels.size(); ++d) { @@ -1139,7 +1139,7 @@ int colvarbias_opes::update_opes() { worker, &tmp, CKLOOP_DOUBLE_SUM, NULL); delta_sum_uprob -= tmp; #else - cvm::error("OPES cannot run because this binary is not linked with a supported threading library.\n"); + cvmodule->error("OPES cannot run because this binary is not linked with a supported threading library.\n"); #endif } sum_uprob = m_zed * m_old_kdenorm * old_nker + delta_sum_uprob; @@ -1159,7 +1159,7 @@ int colvarbias_opes::update_opes() { } void colvarbias_opes::save_state() { - if (cvm::step_absolute() % cvm::restart_out_freq == 0) { + if (cvmodule->step_absolute() % cvmodule->restart_out_freq == 0) { m_saved_zed = m_zed; m_saved_sum_weights = m_sum_weights; m_saved_sum_weights2 = m_sum_weights2; @@ -1221,7 +1221,7 @@ template OST& colvarbias_opes::write_state_data_template_(OST &os auto printFieldReal = [&](const std::string& s, cvm::real x){ write_state_data_key(os, s, false); if (formatted) - os << std::setprecision(cvm::en_prec) << std::setw(cvm::en_width); + os << std::setprecision(cvmodule->en_prec) << std::setw(cvmodule->en_width); os << x; if (formatted) os << "\n"; @@ -1229,7 +1229,7 @@ template OST& colvarbias_opes::write_state_data_template_(OST &os auto printFieldULL = [&](const std::string& s, unsigned long long x){ write_state_data_key(os, s, false); if (formatted) - os << std::setprecision(cvm::en_prec) << std::setw(cvm::en_width); + os << std::setprecision(cvmodule->en_prec) << std::setw(cvmodule->en_width); os << x; if (formatted) os << "\n"; @@ -1237,7 +1237,7 @@ template OST& colvarbias_opes::write_state_data_template_(OST &os auto printFieldString = [&](const std::string& s, const std::string& x){ write_state_data_key(os, s, false); if (formatted) - os << std::setprecision(cvm::en_prec) << std::setw(cvm::en_width); + os << std::setprecision(cvmodule->en_prec) << std::setw(cvmodule->en_width); os << x; if (formatted) os << "\n"; @@ -1296,7 +1296,7 @@ std::ostream& colvarbias_opes::write_state_data(std::ostream &os) { auto& s = write_state_data_template_(os); return s; } catch (const std::exception& e) { - cvm::error(e.what()); + cvmodule->error(e.what()); } return os; } @@ -1306,7 +1306,7 @@ cvm::memory_stream& colvarbias_opes::write_state_data(cvm::memory_stream& os) { auto& s = write_state_data_template_(os); return s; } catch (const std::exception& e) { - cvm::error(e.what()); + cvmodule->error(e.what()); } return os; } @@ -1357,21 +1357,21 @@ template IST& colvarbias_opes::read_state_data_template_(IST &is) m_inf_biasfactor = false; } if (std::abs(old_biasfactor - m_biasfactor) > 1e-6 * m_biasfactor) { - cvm::log("WARNING: previous bias factor was " + cvm::to_str(old_biasfactor) + + cvmodule->log("WARNING: previous bias factor was " + cvm::to_str(old_biasfactor) + " while now it is " + cvm::to_str(m_biasfactor) + " (the new one is used).\n"); } cvm::real old_epsilon; readFieldReal("epsilon", old_epsilon); if (std::abs(old_epsilon - m_epsilon) > 1e-6 * m_epsilon) { - cvm::log("WARNING: previous epsilon was " + cvm::to_str(old_epsilon) + + cvmodule->log("WARNING: previous epsilon was " + cvm::to_str(old_epsilon) + " while now it is " + cvm::to_str(m_epsilon) + " (the new one is used).\n"); } cvm::real old_cutoff; readFieldReal("kernel_cutoff", old_cutoff); if (std::abs(old_cutoff - m_cutoff) > 1e-6 * m_cutoff) { - cvm::log("WARNING: previous cutoff was " + cvm::to_str(old_cutoff) + + cvmodule->log("WARNING: previous cutoff was " + cvm::to_str(old_cutoff) + " while now it is " + cvm::to_str(m_cutoff) + " (the new one is used).\n"); } @@ -1379,7 +1379,7 @@ template IST& colvarbias_opes::read_state_data_template_(IST &is) cvm::real old_compression_threshold; readFieldReal("compression_threshold", old_compression_threshold); if (std::abs(old_compression_threshold - m_compression_threshold) > 1e-6 * m_compression_threshold) { - cvm::log("WARNING: previous cutoff was " + cvm::to_str(old_compression_threshold) + + cvmodule->log("WARNING: previous cutoff was " + cvm::to_str(old_compression_threshold) + " while now it is " + cvm::to_str(m_compression_threshold) + " (the new one is used).\n"); } @@ -1452,7 +1452,7 @@ std::istream& colvarbias_opes::read_state_data(std::istream &is) { auto& ret = read_state_data_template_(is); return ret; } catch (const std::exception& e) { - cvm::error(e.what()); + cvmodule->error(e.what()); } return is; } @@ -1462,7 +1462,7 @@ cvm::memory_stream& colvarbias_opes::read_state_data(cvm::memory_stream &is) { auto& ret = read_state_data_template_(is); return ret; } catch (const std::exception& e) { - cvm::error(e.what()); + cvmodule->error(e.what()); } return is; } @@ -1472,7 +1472,7 @@ void colvarbias_opes::addKernel(const double height, const std::vectorstep_absolute() * cvmodule->dt()) * 1e-3; for (size_t i = 0; i < num_variables(); ++i) { m_kernels_output << " " << std::setw(24) << std::setprecision(16) << center[i]; } @@ -1515,7 +1515,7 @@ void colvarbias_opes::addKernel(const double height, const std::vectorerror("problem with merging and nlist\n"); } m_nlist_index.erase(m_nlist_index.begin() + giver_nk); } @@ -1607,7 +1607,7 @@ size_t colvarbias_opes::getMergeableKernel(const std::vector& giver_c std::vector min_k_smp(m_num_threads, min_k); std::vector min_norm2_smp(m_num_threads, m_compression_threshold2); auto worker = [&](int start, int end, void* unused) { - const int tid = cvm::proxy->smp_thread_id(); + const int tid = cvmodule->proxy->smp_thread_id(); for (int k = start; k <= end; ++k) { if (k == giver_k) continue; double norm2 = 0; @@ -1630,7 +1630,7 @@ size_t colvarbias_opes::getMergeableKernel(const std::vector& giver_c min_norm2 = *it_min; min_k = min_k_smp[std::distance(min_norm2_smp.begin(), it_min)]; #else - cvm::error("OPES cannot run because this binary is not linked with a supported threading library.\n"); + cvmodule->error("OPES cannot run because this binary is not linked with a supported threading library.\n"); #endif (void) min_norm2; // Silence Clang analyzer } @@ -1685,7 +1685,7 @@ size_t colvarbias_opes::getMergeableKernel(const std::vector& giver_c std::vector min_k_smp(m_num_threads, min_k); std::vector min_norm2_smp(m_num_threads, m_compression_threshold2); auto worker = [&](int start, int end, void* unused) { - const int tid = cvm::proxy->smp_thread_id(); + const int tid = cvmodule->proxy->smp_thread_id(); for (int nk = start; nk <= end; ++nk) { const size_t k = m_nlist_index[nk]; if (k == giver_k) continue; @@ -1709,19 +1709,19 @@ size_t colvarbias_opes::getMergeableKernel(const std::vector& giver_c min_norm2 = *it_min; min_k = min_k_smp[std::distance(min_norm2_smp.begin(), it_min)]; #else - cvm::error("OPES cannot run because this binary is not linked with a supported threading library.\n"); + cvmodule->error("OPES cannot run because this binary is not linked with a supported threading library.\n"); #endif (void) min_norm2; // Silence Clang analyzer } } if (num_parallel > 1) { - cvm::error("The Colvars OPES implementation does not support running OPES in parallel across nodes.\n"); + cvmodule->error("The Colvars OPES implementation does not support running OPES in parallel across nodes.\n"); } return min_k; } std::string const colvarbias_opes::traj_file_name(const std::string& suffix) const { - return std::string(cvm::output_prefix()+ + return std::string(cvmodule->output_prefix()+ ".colvars."+this->name+ ( (comm != single_replica) ? ("."+replica_id) : @@ -1734,7 +1734,7 @@ int colvarbias_opes::write_output_files() { thread_local static bool firsttime = true; // Write the kernels const std::string kernels_filename = traj_file_name(".kernels.dat"); - std::ostream& os_kernels = cvm::proxy->output_stream(kernels_filename, "kernels file"); + std::ostream& os_kernels = cvmodule->proxy->output_stream(kernels_filename, "kernels file"); const std::ios_base::fmtflags format_kernels = os_kernels.flags(); if (firsttime) { os_kernels << "#! FIELDS time "; @@ -1769,13 +1769,13 @@ int colvarbias_opes::write_output_files() { } os_kernels << m_kernels_output.str(); os_kernels.setf(format_kernels); - error_code |= cvm::proxy->flush_output_stream(kernels_filename); + error_code |= cvmodule->proxy->flush_output_stream(kernels_filename); m_kernels_output.str(""); m_kernels_output.clear(); // Write the trajectory const std::string traj_filename = traj_file_name(".misc.traj"); - std::ostream& os_traj = cvm::proxy->output_stream(traj_filename, "trajectory of various OPES properties"); + std::ostream& os_traj = cvmodule->proxy->output_stream(traj_filename, "trajectory of various OPES properties"); const std::ios_base::fmtflags format_traj = os_traj.flags(); if (firsttime) { os_traj << "#! FIELDS time "; @@ -1802,7 +1802,7 @@ int colvarbias_opes::write_output_files() { } os_traj << m_traj_oss.str(); os_traj.setf(format_traj); - error_code |= cvm::proxy->flush_output_stream(traj_filename); + error_code |= cvmodule->proxy->flush_output_stream(traj_filename); m_traj_oss.str(""); m_traj_oss.clear(); if (firsttime) firsttime = false; @@ -1811,16 +1811,16 @@ int colvarbias_opes::write_output_files() { const std::string pmf_filename = traj_file_name(".pmf"); error_code |= writePMF(m_pmf_grid, pmf_filename, false); if (comm == multiple_replicas && m_pmf_shared) { - if (cvm::proxy->replica_index() == 0) { + if (cvmodule->proxy->replica_index() == 0) { const std::string global_pmf_filename = traj_file_name(".global.pmf"); error_code |= writePMF(m_global_pmf_grid, global_pmf_filename, false); } } - if (m_pmf_hist_freq > 0 && cvm::step_absolute() % m_pmf_hist_freq == 0) { + if (m_pmf_hist_freq > 0 && cvmodule->step_absolute() % m_pmf_hist_freq == 0) { const std::string pmf_hist_filename = traj_file_name(".hist.pmf"); error_code |= writePMF(m_pmf_grid, pmf_hist_filename, true); if (comm == multiple_replicas && m_pmf_shared) { - if (cvm::proxy->replica_index() == 0) { + if (cvmodule->proxy->replica_index() == 0) { const std::string global_hist_pmf_filename = traj_file_name(".global.hist.pmf"); error_code |= writePMF(m_global_pmf_grid, global_hist_pmf_filename, true); } @@ -1828,7 +1828,7 @@ int colvarbias_opes::write_output_files() { } } // To prevent the case that one replica exits earlier and then destroys all streams - if (comm == multiple_replicas) cvm::proxy->replica_comm_barrier(); + if (comm == multiple_replicas) cvmodule->proxy->replica_comm_barrier(); return error_code; } @@ -1864,26 +1864,26 @@ int colvarbias_opes::computePMF() { const size_t samples_n = m_reweight_grid->raw_data_num(); const int msg_size = samples_n * sizeof(cvm::real); std::vector buffer; - if (cvm::main()->proxy->replica_index() == 0) { - buffer.resize(samples_n * (cvm::proxy->num_replicas() - 1)); - for (int p = 1; p < cvm::proxy->num_replicas(); p++) { + if (cvmodule->proxy->replica_index() == 0) { + buffer.resize(samples_n * (cvmodule->proxy->num_replicas() - 1)); + for (int p = 1; p < cvmodule->proxy->num_replicas(); p++) { const size_t start_pos = (p - 1) * samples_n; - if (cvm::proxy->replica_comm_recv((char*)&(buffer[start_pos]), msg_size, p) != msg_size) { - return cvm::error("Error getting shared OPES reweighting histogram from replica " + cvm::to_str(p)); + if (cvmodule->proxy->replica_comm_recv((char*)&(buffer[start_pos]), msg_size, p) != msg_size) { + return cvmodule->error("Error getting shared OPES reweighting histogram from replica " + cvm::to_str(p)); } } } else { - if (cvm::proxy->replica_comm_send((char*)(&(m_reweight_grid->data[0])), msg_size, 0) != msg_size) { - return cvm::error("Error sending shared OPES reweighting histogram from replica " + cvm::to_str(cvm::main()->proxy->replica_index())); + if (cvmodule->proxy->replica_comm_send((char*)(&(m_reweight_grid->data[0])), msg_size, 0) != msg_size) { + return cvmodule->error("Error sending shared OPES reweighting histogram from replica " + cvm::to_str(cvmodule->proxy->replica_index())); } } - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); // Broadcast m_reweight_grid to all replicas auto& global_data = m_global_reweight_grid->data; - if (cvm::main()->proxy->replica_index() == 0) { + if (cvmodule->proxy->replica_index() == 0) { global_data = m_reweight_grid->data; // Sum the samples on PE 0 - for (int p = 1; p < cvm::proxy->num_replicas(); p++) { + for (int p = 1; p < cvmodule->proxy->num_replicas(); p++) { const size_t start_pos = (p - 1) * samples_n; for (size_t i = 0 ; i < samples_n; ++i) { global_data[i] += buffer[start_pos+i]; @@ -1894,42 +1894,42 @@ int colvarbias_opes::computePMF() { // Get the sum of probabilities of all grids hist_to_pmf(m_kbt, m_reweight_grid.get(), m_pmf_grid); if (comm == multiple_replicas && m_pmf_shared) { - if (cvm::main()->proxy->replica_index() == 0) { + if (cvmodule->proxy->replica_index() == 0) { hist_to_pmf(m_kbt, m_global_reweight_grid.get(), m_global_pmf_grid); } } if (comm == multiple_replicas) { - cvm::proxy->replica_comm_barrier(); + cvmodule->proxy->replica_comm_barrier(); } return COLVARS_OK; } int colvarbias_opes::writePMF(const std::unique_ptr& pmf_grid, const std::string &filename, bool keep_open) { - std::ostream& os = cvm::proxy->output_stream(filename, "output stream of " + filename); + std::ostream& os = cvmodule->proxy->output_stream(filename, "output stream of " + filename); if (!os) { return COLVARS_FILE_ERROR; } pmf_grid->write_multicol(os); if (!keep_open) { - cvm::proxy->close_output_stream(filename); + cvmodule->proxy->close_output_stream(filename); } else { - cvm::proxy->flush_output_stream(filename); + cvmodule->proxy->flush_output_stream(filename); } return COLVARS_OK; } void colvarbias_opes::writeTrajBuffer() { - if (m_traj_output_frequency > 0 && cvm::step_absolute() % m_traj_output_frequency == 0) { + if (m_traj_output_frequency > 0 && cvmodule->step_absolute() % m_traj_output_frequency == 0) { m_traj_oss << std::right; - m_traj_oss << std::scientific << " " << std::setw(cvm::cv_width) << std::setprecision(cvm::cv_prec) << (cvm::step_absolute() * cvm::dt()) * 1e-3; + m_traj_oss << std::scientific << " " << std::setw(cvmodule->cv_width) << std::setprecision(cvmodule->cv_prec) << (cvmodule->step_absolute() * cvmodule->dt()) * 1e-3; for (size_t i = 0; i < num_variables(); ++i) { - m_traj_oss << std::scientific << " " << std::setw(cvm::cv_width) << std::setprecision(cvm::cv_prec) << variables(i)->value().real_value; + m_traj_oss << std::scientific << " " << std::setw(cvmodule->cv_width) << std::setprecision(cvmodule->cv_prec) << variables(i)->value().real_value; } - m_traj_oss << std::scientific << " " << std::setw(cvm::cv_width) << std::setprecision(cvm::cv_prec) << bias_energy; - m_traj_oss << std::scientific << " " << std::setw(cvm::cv_width) << std::setprecision(cvm::cv_prec) << m_traj_line.rct; - if (!m_no_zed) m_traj_oss << std::scientific << " " << std::setw(cvm::cv_width) << std::setprecision(cvm::cv_prec) << m_traj_line.zed; - m_traj_oss << std::scientific << " " << std::setw(cvm::cv_width) << std::setprecision(cvm::cv_prec) << m_traj_line.neff; - if (m_calc_work) m_traj_oss << std::scientific << " " << std::setw(cvm::cv_width) << std::setprecision(cvm::cv_prec) << m_traj_line.work; + m_traj_oss << std::scientific << " " << std::setw(cvmodule->cv_width) << std::setprecision(cvmodule->cv_prec) << bias_energy; + m_traj_oss << std::scientific << " " << std::setw(cvmodule->cv_width) << std::setprecision(cvmodule->cv_prec) << m_traj_line.rct; + if (!m_no_zed) m_traj_oss << std::scientific << " " << std::setw(cvmodule->cv_width) << std::setprecision(cvmodule->cv_prec) << m_traj_line.zed; + m_traj_oss << std::scientific << " " << std::setw(cvmodule->cv_width) << std::setprecision(cvmodule->cv_prec) << m_traj_line.neff; + if (m_calc_work) m_traj_oss << std::scientific << " " << std::setw(cvmodule->cv_width) << std::setprecision(cvmodule->cv_prec) << m_traj_line.work; m_traj_oss << " " << m_traj_line.nker; if (m_nlist) m_traj_oss << " " << m_traj_line.nlker; if (m_nlist) m_traj_oss << " " << m_traj_line.nlsteps; @@ -1972,7 +1972,7 @@ void colvarbias_opes::updateNlist(const std::vector& center) { #elif CMK_SMP && USE_CKLOOP std::vector> private_nlist_index(m_num_threads); auto worker = [&](int start, int end, void* unused){ - const int tid = cvm::proxy->smp_thread_id(); + const int tid = cvmodule->proxy->smp_thread_id(); for (int k = start; k <= end; ++k) { cvm::real norm2_k = 0; for (size_t i = 0; i < num_variables(); ++i) { @@ -1992,7 +1992,7 @@ void colvarbias_opes::updateNlist(const std::vector& center) { m_nlist_index.insert(m_nlist_index.end(), private_nlist_index[i].begin(), private_nlist_index[i].end()); } #else - cvm::error("OPES cannot run because this binary is not linked with a supported threading library.\n"); + cvmodule->error("OPES cannot run because this binary is not linked with a supported threading library.\n"); #endif if (m_recursive_merge) { std::sort(m_nlist_index.begin(), m_nlist_index.end()); diff --git a/src/colvarbias_opes.h b/src/colvarbias_opes.h index 0c52ba241..eaf6bce44 100644 --- a/src/colvarbias_opes.h +++ b/src/colvarbias_opes.h @@ -48,7 +48,7 @@ class colvarbias_opes: public colvarbias { multiple_replicas }; /// Constructor - colvarbias_opes(char const *key); + colvarbias_opes(colvarmodule *cvmodule_in, char const *key); /// Initializer int init(std::string const &conf) override; /// Per-timestep update diff --git a/src/colvarbias_restraint.cpp b/src/colvarbias_restraint.cpp index 2a3ecef2b..072597ae2 100644 --- a/src/colvarbias_restraint.cpp +++ b/src/colvarbias_restraint.cpp @@ -19,7 +19,8 @@ colvarbias_restraint::colvarbias_restraint(char const *key) - : colvarbias(key), colvarbias_ti(key) + : colvarbias_ti(key) + // intermediate in virtual inheritance, no need to initialize base class colvarbias {} @@ -36,7 +37,7 @@ int colvarbias_restraint::init(std::string const &conf) colvarbias_ti::init(conf); if (cvm::debug()) - cvm::log("Initializing a new restraint bias.\n"); + cvmodule->log("Initializing a new restraint bias.\n"); return COLVARS_OK; } @@ -56,10 +57,10 @@ int colvarbias_restraint::update() } if (cvm::debug()) - cvm::log("Done updating the restraint bias \""+this->name+"\".\n"); + cvmodule->log("Done updating the restraint bias \""+this->name+"\".\n"); if (cvm::debug()) - cvm::log("Current forces for the restraint bias \""+ + cvmodule->log("Current forces for the restraint bias \""+ this->name+"\": "+cvm::to_str(colvar_forces)+".\n"); return COLVARS_OK; @@ -97,7 +98,7 @@ std::ostream & colvarbias_restraint::write_traj(std::ostream &os) colvarbias_restraint_centers::colvarbias_restraint_centers(char const *key) - : colvarbias(key), colvarbias_ti(key), colvarbias_restraint(key) + : colvarbias_ti(key) { } @@ -119,7 +120,7 @@ int colvarbias_restraint_centers::init(std::string const &conf) if (get_keyval(conf, "centers", colvar_centers, colvar_centers)) { for (i = 0; i < num_variables(); i++) { if (cvm::debug()) { - cvm::log("colvarbias_restraint: parsing initial centers, i = "+cvm::to_str(i)+".\n"); + cvmodule->log("colvarbias_restraint: parsing initial centers, i = "+cvm::to_str(i)+".\n"); } colvar_centers[i].apply_constraints(); } @@ -128,12 +129,12 @@ int colvarbias_restraint_centers::init(std::string const &conf) if (null_centers) { colvar_centers.clear(); - cvm::error("Error: must define the initial centers of the restraints.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: must define the initial centers of the restraints.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } if (colvar_centers.size() != num_variables()) { - cvm::error("Error: number of centers does not match " + cvmodule->error("Error: number of centers does not match " "that of collective variables.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } @@ -156,7 +157,7 @@ int colvarbias_restraint_centers::change_configuration(std::string const &conf) colvarbias_restraint_k::colvarbias_restraint_k(char const *key) - : colvarbias(key), colvarbias_ti(key), colvarbias_restraint(key) + : colvarbias_ti(key), colvarbias_restraint(key) { force_k = -1.0; check_positive_k = true; @@ -167,7 +168,7 @@ int colvarbias_restraint_k::init(std::string const &conf) { get_keyval(conf, "forceConstant", force_k, (force_k > 0.0 ? force_k : 1.0)); if (check_positive_k && (force_k < 0.0)) { - cvm::error("Error: undefined or invalid force constant.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: undefined or invalid force constant.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } return COLVARS_OK; @@ -184,43 +185,43 @@ int colvarbias_restraint_k::change_configuration(std::string const &conf) int colvarbias_restraint_moving::init(std::string const &conf) { if (b_chg_centers && b_chg_force_k) { - cvm::error("Error: cannot specify both targetCenters and targetForceConstant.\n", + cvmodule->error("Error: cannot specify both targetCenters and targetForceConstant.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } if (b_chg_centers && b_chg_walls) { - cvm::error("Error: cannot specify both targetCenters and targetUpperWalls/targetLowerWalls.\n", + cvmodule->error("Error: cannot specify both targetCenters and targetUpperWalls/targetLowerWalls.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } if (b_chg_centers || b_chg_force_k || b_chg_walls) { - first_step = cvm::step_absolute(); + first_step = cvmodule->step_absolute(); - cvm::log("Initial step for restraint change: " + cvm::to_str(first_step) + "\n"); + cvmodule->log("Initial step for restraint change: " + cvm::to_str(first_step) + "\n"); get_keyval(conf, "targetNumSteps", target_nsteps, target_nsteps); if (!target_nsteps) { - return cvm::error("Error: targetNumSteps must be non-zero.\n", COLVARS_INPUT_ERROR); + return cvmodule->error("Error: targetNumSteps must be non-zero.\n", COLVARS_INPUT_ERROR); } get_keyval(conf, "targetEquilSteps", target_equil_steps, target_equil_steps); if ( target_nsteps && target_nsteps % time_step_factor ) { - return cvm::error("Error: targetNumSteps must be a multiple of timeStepFactor.\n", COLVARS_INPUT_ERROR); + return cvmodule->error("Error: targetNumSteps must be a multiple of timeStepFactor.\n", COLVARS_INPUT_ERROR); } if (get_keyval(conf, "targetNumStages", target_nstages, target_nstages) && lambda_schedule.size()) { - return cvm::error("Error: targetNumStages and lambdaSchedule are incompatible.\n", COLVARS_INPUT_ERROR); + return cvmodule->error("Error: targetNumStages and lambdaSchedule are incompatible.\n", COLVARS_INPUT_ERROR); } get_keyval_feature(this, conf, "outputAccumulatedWork", f_cvb_output_acc_work, is_enabled(f_cvb_output_acc_work)); if (is_enabled(f_cvb_output_acc_work) && (target_nstages > 0)) { - return cvm::error("Error: outputAccumulatedWork and targetNumStages " + return cvmodule->error("Error: outputAccumulatedWork and targetNumStages " "are incompatible.\n", COLVARS_INPUT_ERROR); } } @@ -230,25 +231,25 @@ int colvarbias_restraint_moving::init(std::string const &conf) int colvarbias_restraint_moving::update() { - if (!cvm::main()->proxy->simulation_running()) return COLVARS_OK; + if (!cvmodule->proxy->simulation_running()) return COLVARS_OK; if (target_nstages) { // Accumulate free energy derivative at every step except 0 // (there are n+1 calls to update() in an n-step simulation) - if (cvm::step_absolute() - first_step > 0) { + if (cvmodule->step_absolute() - first_step > 0) { if (b_chg_force_k) dA_dlambda += dU_dlambda_k(); if (b_chg_centers) dA_dlambda += dU_dlambda_centers(); if (b_chg_walls) dA_dlambda += dU_dlambda_walls(); - if ((cvm::step_absolute() - first_step) % target_nsteps == 0) { + if ((cvmodule->step_absolute() - first_step) % target_nsteps == 0) { cvm::real lambda = current_lambda(); dA_dlambda /= cvm::real(target_nsteps - target_equil_steps); std::string msg = "Restraint \"" + this->name + "\" end of stage " + cvm::to_str(stage) + - " at step " + cvm::to_str(cvm::step_absolute()) + + " at step " + cvm::to_str(cvmodule->step_absolute()) + ", lambda= " + cvm::to_str(lambda) + " : dA/dlambda= " + cvm::to_str(dA_dlambda); - cvm::log(msg); + cvmodule->log(msg); dA_dlambda = 0.0; update_stage(); @@ -258,7 +259,7 @@ int colvarbias_restraint_moving::update() { if (b_chg_walls) update_walls(lambda); } } - } else if (cvm::step_absolute() - first_step <= target_nsteps) { + } else if (cvmodule->step_absolute() - first_step <= target_nsteps) { // Continuous update (slow growth) cvm::real lambda = current_lambda(); if (b_chg_force_k) update_k(lambda); @@ -280,7 +281,7 @@ cvm::real colvarbias_restraint_moving::current_lambda() const { if (b_decoupling) lambda = 1.0 - lambda; } } else { - lambda = cvm::real(cvm::step_absolute() - first_step) / cvm::real(target_nsteps); + lambda = cvm::real(cvmodule->step_absolute() - first_step) / cvm::real(target_nsteps); if (lambda > 1.0) lambda = 1.0; if (b_decoupling) lambda = 1.0 - lambda; } @@ -293,9 +294,9 @@ std::string const colvarbias_restraint_moving::get_state_params() const std::ostringstream os; os.setf(std::ios::scientific, std::ios::floatfield); if (b_chg_centers || b_chg_force_k) { - os << "firstStep " << std::setw(cvm::it_width) << first_step << "\n"; + os << "firstStep " << std::setw(cvmodule->it_width) << first_step << "\n"; if (target_nstages) { - os << "stage " << std::setw(cvm::it_width) << stage << "\n"; + os << "stage " << std::setw(cvmodule->it_width) << stage << "\n"; } } return os.str(); @@ -306,7 +307,7 @@ int colvarbias_restraint_moving::set_state_params(std::string const &conf) { if (b_chg_centers || b_chg_force_k) { auto first_step_flags = colvarparse::parse_restart; - if (cvm::main()->restart_version_number() > 20230906) { + if (cvmodule->restart_version_number() > 20230906) { // Only require the first step when the code could produce it first_step_flags = colvarparse::parse_restart | colvarparse::parse_required; } @@ -321,8 +322,7 @@ int colvarbias_restraint_moving::set_state_params(std::string const &conf) colvarbias_restraint_centers_moving::colvarbias_restraint_centers_moving(char const *key) - : colvarbias(key), - colvarbias_ti(key), + : colvarbias_ti(key), colvarbias_restraint(key), colvarbias_restraint_centers(key), colvarbias_restraint_moving(key) @@ -337,13 +337,13 @@ int colvarbias_restraint_centers_moving::init(std::string const &conf) colvarbias_restraint_centers::init(conf); if (cvm::debug()) { - cvm::log("colvarbias_restraint: parsing target centers.\n"); + cvmodule->log("colvarbias_restraint: parsing target centers.\n"); } size_t i; if (get_keyval(conf, "targetCenters", target_centers, colvar_centers)) { if (target_centers.size() != num_variables()) { - cvm::error("Error: number of target centers does not match " + cvmodule->error("Error: number of target centers does not match " "that of collective variables.\n", COLVARS_INPUT_ERROR); } b_chg_centers = true; @@ -384,7 +384,7 @@ int colvarbias_restraint_centers_moving::init(std::string const &conf) void colvarbias_restraint_centers_moving::update_centers(cvm::real lambda) { if (cvm::debug()) { - cvm::log("Updating centers for the restraint bias \""+ + cvmodule->log("Updating centers for the restraint bias \""+ this->name+"\": "+cvm::to_str(colvar_centers)+".\n"); } size_t i; @@ -397,11 +397,11 @@ void colvarbias_restraint_centers_moving::update_centers(cvm::real lambda) variables(i)->wrap(colvar_centers[i]); } if (cvm::debug()) { - cvm::log("New centers for the restraint bias \""+ + cvmodule->log("New centers for the restraint bias \""+ this->name+"\": "+cvm::to_str(colvar_centers)+".\n"); } - if (!target_nstages && (cvm::step_absolute() - first_step > target_nsteps)) { + if (!target_nstages && (cvmodule->step_absolute() - first_step > target_nsteps)) { for (size_t i = 0; i < num_variables(); i++) { centers_incr[i].reset(); } @@ -422,12 +422,12 @@ cvm::real colvarbias_restraint_centers_moving::dU_dlambda_centers() const int colvarbias_restraint_centers_moving::update_acc_work() { - if (!cvm::main()->proxy->simulation_running()) { + if (!cvmodule->proxy->simulation_running()) { return COLVARS_OK; } if (b_chg_centers && is_enabled(f_cvb_output_acc_work)) { - if ((cvm::step_relative() > 0) && - (cvm::step_absolute() - first_step <= target_nsteps)) { + if ((cvmodule->step_relative() > 0) && + (cvmodule->step_absolute() - first_step <= target_nsteps)) { for (size_t i = 0; i < num_variables(); i++) { // project forces on the calculated increments at this step acc_work += colvar_forces[i] * centers_incr[i]; @@ -448,14 +448,14 @@ std::string const colvarbias_restraint_centers_moving::get_state_params() const os << "centers "; for (i = 0; i < num_variables(); i++) { os << " " - << std::setprecision(cvm::cv_prec) << std::setw(cvm::cv_width) + << std::setprecision(cvmodule->cv_prec) << std::setw(cvmodule->cv_width) << colvar_centers[i]; } os << "\n"; if (is_enabled(f_cvb_output_acc_work)) { os << "accumulatedWork " - << std::setprecision(cvm::en_prec) << std::setw(cvm::en_width) + << std::setprecision(cvmodule->en_prec) << std::setw(cvmodule->en_width) << acc_work << "\n"; } } @@ -486,15 +486,15 @@ std::ostream & colvarbias_restraint_centers_moving::write_traj_label(std::ostrea { if (b_output_centers) { for (size_t i = 0; i < num_variables(); i++) { - size_t const this_cv_width = (variables(i)->value()).output_width(cvm::cv_width); + size_t const this_cv_width = (variables(i)->value()).output_width(cvmodule->cv_width); os << " x0_" - << cvm::wrap_string(variables(i)->name, this_cv_width-3); + << cvmodule->wrap_string(variables(i)->name, this_cv_width-3); } } if (b_chg_centers && is_enabled(f_cvb_output_acc_work)) { os << " W_" - << cvm::wrap_string(this->name, cvm::en_width-2); + << cvmodule->wrap_string(this->name, cvmodule->en_width-2); } return os; @@ -506,14 +506,14 @@ std::ostream & colvarbias_restraint_centers_moving::write_traj(std::ostream &os) if (b_output_centers) { for (size_t i = 0; i < num_variables(); i++) { os << " " - << std::setprecision(cvm::cv_prec) << std::setw(cvm::cv_width) + << std::setprecision(cvmodule->cv_prec) << std::setw(cvmodule->cv_width) << colvar_centers[i]; } } if (b_chg_centers && is_enabled(f_cvb_output_acc_work)) { os << " " - << std::setprecision(cvm::en_prec) << std::setw(cvm::en_width) + << std::setprecision(cvmodule->en_prec) << std::setw(cvmodule->en_width) << acc_work; } @@ -523,8 +523,7 @@ std::ostream & colvarbias_restraint_centers_moving::write_traj(std::ostream &os) colvarbias_restraint_k_moving::colvarbias_restraint_k_moving(char const *key) - : colvarbias(key), - colvarbias_ti(key), + : colvarbias_ti(key), colvarbias_restraint(key), colvarbias_restraint_k(key), colvarbias_restraint_moving(key) @@ -551,7 +550,7 @@ int colvarbias_restraint_k_moving::init(std::string const &conf) if (get_keyval(conf, "targetForceConstant", target_force_k, target_force_k)) { if (b_decoupling) { - cvm::error("Error: targetForceConstant may not be specified together with decoupling.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: targetForceConstant may not be specified together with decoupling.\n", COLVARS_INPUT_ERROR); return COLVARS_ERROR; } b_chg_force_k = true; @@ -567,8 +566,8 @@ int colvarbias_restraint_k_moving::init(std::string const &conf) if (get_keyval(conf, "lambdaSchedule", lambda_schedule, lambda_schedule) && target_nstages > 0) { - cvm::error("Error: targetNumStages and lambdaSchedule are incompatible.\n", COLVARS_INPUT_ERROR); - return cvm::get_error(); + cvmodule->error("Error: targetNumStages and lambdaSchedule are incompatible.\n", COLVARS_INPUT_ERROR); + return cvmodule->get_error(); } if (lambda_schedule.size()) { @@ -579,10 +578,10 @@ int colvarbias_restraint_k_moving::init(std::string const &conf) if ((get_keyval(conf, "targetForceExponent", lambda_exp, lambda_exp, parse_deprecated) || get_keyval(conf, "lambdaExponent", lambda_exp, lambda_exp)) && !b_chg_force_k) { - cvm::error("Error: cannot set lambdaExponent unless a changing force constant is active.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: cannot set lambdaExponent unless a changing force constant is active.\n", COLVARS_INPUT_ERROR); } if (lambda_exp < 1.0) { - cvm::log("Warning: for all practical purposes, lambdaExponent should be 1.0 or greater.\n"); + cvmodule->log("Warning: for all practical purposes, lambdaExponent should be 1.0 or greater.\n"); } return COLVARS_OK; @@ -594,10 +593,10 @@ void colvarbias_restraint_k_moving::update_k(cvm::real lambda) { force_k = starting_force_k + (target_force_k - starting_force_k) * cvm::pow(lambda, lambda_exp); force_k_incr = force_k - force_k_old; - if (!target_nstages && (cvm::step_absolute() > first_step + target_nsteps)) { + if (!target_nstages && (cvmodule->step_absolute() > first_step + target_nsteps)) { force_k_incr = 0.0; } - cvm::log("Updated force constant for the restraint bias \""+ + cvmodule->log("Updated force constant for the restraint bias \""+ this->name+"\": "+cvm::to_str(force_k)+".\n"); } @@ -614,12 +613,12 @@ cvm::real colvarbias_restraint_k_moving::dU_dlambda_k() const { int colvarbias_restraint_k_moving::update_acc_work() { - if (!cvm::main()->proxy->simulation_running()) { + if (!cvmodule->proxy->simulation_running()) { return COLVARS_OK; } if (b_chg_force_k && is_enabled(f_cvb_output_acc_work)) { - if ((cvm::step_relative() > 0) && - (cvm::step_absolute() - first_step <= target_nsteps)) { + if ((cvmodule->step_relative() > 0) && + (cvmodule->step_absolute() - first_step <= target_nsteps)) { cvm::real dU_dk = 0.0; for (size_t i = 0; i < num_variables(); i++) { dU_dk += d_restraint_potential_dk(i); @@ -637,12 +636,12 @@ std::string const colvarbias_restraint_k_moving::get_state_params() const os.setf(std::ios::scientific, std::ios::floatfield); if (b_chg_force_k) { os << "forceConstant " - << std::setprecision(cvm::en_prec) - << std::setw(cvm::en_width) << force_k << "\n"; + << std::setprecision(cvmodule->en_prec) + << std::setw(cvmodule->en_width) << force_k << "\n"; if (is_enabled(f_cvb_output_acc_work)) { os << "accumulatedWork " - << std::setprecision(cvm::en_prec) << std::setw(cvm::en_width) + << std::setprecision(cvmodule->en_prec) << std::setw(cvmodule->en_width) << acc_work << "\n"; } } @@ -672,7 +671,7 @@ std::ostream & colvarbias_restraint_k_moving::write_traj_label(std::ostream &os) { if (b_chg_force_k && is_enabled(f_cvb_output_acc_work)) { os << " W_" - << cvm::wrap_string(this->name, cvm::en_width-2); + << cvmodule->wrap_string(this->name, cvmodule->en_width-2); } return os; } @@ -682,7 +681,7 @@ std::ostream & colvarbias_restraint_k_moving::write_traj(std::ostream &os) { if (b_chg_force_k && is_enabled(f_cvb_output_acc_work)) { os << " " - << std::setprecision(cvm::en_prec) << std::setw(cvm::en_width) + << std::setprecision(cvmodule->en_prec) << std::setw(cvmodule->en_width) << acc_work; } return os; @@ -690,8 +689,8 @@ std::ostream & colvarbias_restraint_k_moving::write_traj(std::ostream &os) -colvarbias_restraint_harmonic::colvarbias_restraint_harmonic(char const *key) - : colvarbias(key), +colvarbias_restraint_harmonic::colvarbias_restraint_harmonic(colvarmodule *cvmodule_in, char const *key) + : colvarbias(cvmodule_in, key), colvarbias_ti(key), colvarbias_restraint(key), colvarbias_restraint_centers(key), @@ -710,11 +709,11 @@ int colvarbias_restraint_harmonic::init(std::string const &conf) colvarbias_restraint_centers_moving::init(conf); colvarbias_restraint_k_moving::init(conf); - cvm::main()->cite_feature("Harmonic colvar bias implementation"); + cvmodule->cite_feature("Harmonic colvar bias implementation"); for (size_t i = 0; i < num_variables(); i++) { cvm::real const w = variables(i)->width; - cvm::log("The force constant for colvar \""+variables(i)->name+ + cvmodule->log("The force constant for colvar \""+variables(i)->name+ "\" will be rescaled to "+ cvm::to_str(force_k/(w*w))+ " according to the specified width ("+cvm::to_str(w)+").\n"); @@ -806,7 +805,7 @@ std::ostream & colvarbias_restraint_harmonic::write_traj(std::ostream &os) int colvarbias_restraint_harmonic::change_configuration(std::string const &conf) { - cvm::log("Warning: Updating configuration mid-run for an existing restraint is unsupported, and will raise an error in a future release. The supported method is deleting the restraint and re-creating, which will also do a better error check."); + cvmodule->log("Warning: Updating configuration mid-run for an existing restraint is unsupported, and will raise an error in a future release. The supported method is deleting the restraint and re-creating, which will also do a better error check."); return colvarbias_restraint_centers::change_configuration(conf) | colvarbias_restraint_k::change_configuration(conf); } @@ -832,8 +831,8 @@ cvm::real colvarbias_restraint_harmonic::energy_difference(std::string const &co -colvarbias_restraint_harmonic_walls::colvarbias_restraint_harmonic_walls(char const *key) - : colvarbias(key), +colvarbias_restraint_harmonic_walls::colvarbias_restraint_harmonic_walls(colvarmodule *cvmodule_in, char const *key) + : colvarbias(cvmodule_in, key), colvarbias_ti(key), colvarbias_restraint(key), colvarbias_restraint_k(key), @@ -864,7 +863,7 @@ get_keyval(conf, "targetUpperWalls", target_upper_walls, target_upper_walls); colvarbias_restraint_moving::init(conf); colvarbias_restraint_k_moving::init(conf); - cvm::main()->cite_feature("harmonicWalls colvar bias implementation"); + cvmodule->cite_feature("harmonicWalls colvar bias implementation"); enable(f_cvb_scalar_variables); @@ -881,7 +880,7 @@ get_keyval(conf, "targetUpperWalls", target_upper_walls, target_upper_walls); } if (!get_keyval(conf, "lowerWalls", lower_walls, lower_walls) && b_null_lower_walls) { - cvm::log("Lower walls were not provided.\n"); + cvmodule->log("Lower walls were not provided.\n"); lower_walls.clear(); } @@ -896,12 +895,12 @@ get_keyval(conf, "targetUpperWalls", target_upper_walls, target_upper_walls); } if (!get_keyval(conf, "upperWalls", upper_walls, upper_walls) && b_null_upper_walls) { - cvm::log("Upper walls were not provided.\n"); + cvmodule->log("Upper walls were not provided.\n"); upper_walls.clear(); } if ((lower_walls.size() == 0) && (upper_walls.size() == 0)) { - return cvm::error("Error: no walls provided.\n", COLVARS_INPUT_ERROR); + return cvmodule->error("Error: no walls provided.\n", COLVARS_INPUT_ERROR); } if (lower_walls.size() > 0) { @@ -916,7 +915,7 @@ get_keyval(conf, "targetUpperWalls", target_upper_walls, target_upper_walls); if ((lower_walls.size() == 0) || (upper_walls.size() == 0)) { for (i = 0; i < num_variables(); i++) { if (variables(i)->is_enabled(f_cv_periodic)) { - return cvm::error("Error: at least one variable is periodic, " + return cvmodule->error("Error: at least one variable is periodic, " "both walls must be provided.\n", COLVARS_INPUT_ERROR); } } @@ -933,7 +932,7 @@ bool b_null_target_lower_walls = false; } if (!get_keyval(conf, "targetLowerWalls", target_lower_walls, target_lower_walls) && b_null_target_lower_walls) { - cvm::log("Target lower walls were not provided.\n"); + cvmodule->log("Target lower walls were not provided.\n"); target_lower_walls.clear(); } @@ -948,31 +947,31 @@ bool b_null_target_lower_walls = false; } if (!get_keyval(conf, "targetUpperWalls", target_upper_walls, target_upper_walls) && b_null_target_upper_walls) { - cvm::log("Target upper walls were not provided.\n"); + cvmodule->log("Target upper walls were not provided.\n"); target_upper_walls.clear(); } if (target_upper_walls.size() > upper_walls.size()) { - cvm::error("At least 1 target wall was provided with no initial wall!.\n", + cvmodule->error("At least 1 target wall was provided with no initial wall!.\n", COLVARS_INPUT_ERROR); } if (target_lower_walls.size() > lower_walls.size()) { - cvm::error("At least 1 target wall was provided with no initial wall!.\n", + cvmodule->error("At least 1 target wall was provided with no initial wall!.\n", COLVARS_INPUT_ERROR); } if ((lower_walls.size() > 0) && (upper_walls.size() > 0)) { for (i = 0; i < num_variables(); i++) { if (lower_walls[i] >= upper_walls[i]) { - return cvm::error("Error: one upper wall, "+ + return cvmodule->error("Error: one upper wall, "+ cvm::to_str(upper_walls[i])+ ", is not higher than the lower wall, "+ cvm::to_str(lower_walls[i])+".\n", COLVARS_INPUT_ERROR); } if (variables(i)->dist2(lower_walls[i], upper_walls[i]) < 1.0e-12) { - return cvm::error("Error: lower wall and upper wall are equal " + return cvmodule->error("Error: lower wall and upper wall are equal " "in the domain of the variable \""+ variables(i)->name+"\".\n", COLVARS_INPUT_ERROR); } @@ -980,7 +979,7 @@ bool b_null_target_lower_walls = false; if ((target_lower_walls.size() > 0) && (target_upper_walls.size() > 0)){ for (i = 0; i < num_variables(); i++) { if (target_lower_walls[i] >= target_upper_walls[i]) { - return cvm::error("Error: one target upper wall, "+ + return cvmodule->error("Error: one target upper wall, "+ cvm::to_str(target_upper_walls[i])+ ", will be lower then the target lower wall, "+ cvm::to_str(target_lower_walls[i])+".\n", @@ -991,7 +990,7 @@ bool b_null_target_lower_walls = false; if ((target_lower_walls.size() > 0) && !(target_upper_walls.size() > 0)){ for (i = 0; i < num_variables(); i++) { if (target_lower_walls[i] >= upper_walls[i]) { - return cvm::error("Error: one upper wall, "+ + return cvmodule->error("Error: one upper wall, "+ cvm::to_str(upper_walls[i])+ ", will be surpressed by the target lower wall, "+ cvm::to_str(target_lower_walls[i])+".\n", @@ -1003,7 +1002,7 @@ bool b_null_target_lower_walls = false; if (!(target_lower_walls.size() > 0) && (target_upper_walls.size() > 0)){ for (i = 0; i < num_variables(); i++) { if (lower_walls[i] >= target_upper_walls[i]) { - return cvm::error("Error: one target upper wall, "+ + return cvmodule->error("Error: one target upper wall, "+ cvm::to_str(target_upper_walls[i])+ ", will surpress the lower wall, "+ cvm::to_str(lower_walls[i])+".\n", @@ -1014,7 +1013,7 @@ bool b_null_target_lower_walls = false; if (lower_wall_k * upper_wall_k == 0.0) { - cvm::error("Error: lowerWallConstant and upperWallConstant, " + cvmodule->error("Error: lowerWallConstant and upperWallConstant, " "when defined, must both be positive.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; @@ -1043,7 +1042,7 @@ bool b_null_target_lower_walls = false; if (lower_walls.size() > 0) { for (i = 0; i < num_variables(); i++) { cvm::real const w = variables(i)->width; - cvm::log("The lower wall force constant for colvar \""+ + cvmodule->log("The lower wall force constant for colvar \""+ variables(i)->name+"\" will be rescaled to "+ cvm::to_str(lower_wall_k * force_k / (w*w))+ " according to the specified width ("+cvm::to_str(w)+").\n"); @@ -1053,7 +1052,7 @@ bool b_null_target_lower_walls = false; if (upper_walls.size() > 0) { for (i = 0; i < num_variables(); i++) { cvm::real const w = variables(i)->width; - cvm::log("The upper wall force constant for colvar \""+ + cvmodule->log("The upper wall force constant for colvar \""+ variables(i)->name+"\" will be rescaled to "+ cvm::to_str(upper_wall_k * force_k / (w*w))+ " according to the specified width ("+cvm::to_str(w)+").\n"); @@ -1086,7 +1085,7 @@ void colvarbias_restraint_harmonic_walls::update_walls(cvm::real lambda) if (target_upper_walls.size() > 0){ if (cvm::debug()) { - cvm::log("Updating upper walls for the restraint bias \""+ + cvmodule->log("Updating upper walls for the restraint bias \""+ this->name+"\": "+cvm::to_str(lower_walls)+".\n"); } @@ -1101,14 +1100,14 @@ void colvarbias_restraint_harmonic_walls::update_walls(cvm::real lambda) variables(i)->wrap(upper_walls[i]); } if (cvm::debug()) { - cvm::log("New upper walls for the restraint bias \""+ + cvmodule->log("New upper walls for the restraint bias \""+ this->name+"\": "+cvm::to_str(upper_walls)+".\n"); } } if (target_lower_walls.size() > 0){ if (cvm::debug()) { - cvm::log("Updating lower walls for the restraint bias \""+ + cvmodule->log("Updating lower walls for the restraint bias \""+ this->name+"\": "+cvm::to_str(lower_walls)+".\n"); } @@ -1122,11 +1121,11 @@ void colvarbias_restraint_harmonic_walls::update_walls(cvm::real lambda) variables(i)->wrap(lower_walls[i]); } if (cvm::debug()) { - cvm::log("New lower walls for the restraint bias \""+ + cvmodule->log("New lower walls for the restraint bias \""+ this->name+"\": "+cvm::to_str(lower_walls)+".\n"); } } - if (!target_nstages && (cvm::step_absolute() - first_step > target_nsteps)) { + if (!target_nstages && (cvmodule->step_absolute() - first_step > target_nsteps)) { for (size_t i = 0; i < num_variables(); i++) { if(lower_walls_incr.size() > 0) { lower_walls_incr[i].reset(); @@ -1173,12 +1172,12 @@ int colvarbias_restraint_harmonic_walls::update() int colvarbias_restraint_harmonic_walls::update_acc_work() { - if (!cvm::main()->proxy->simulation_running()) { + if (!cvmodule->proxy->simulation_running()) { return COLVARS_OK; } if (b_chg_walls && is_enabled(f_cvb_output_acc_work)) { - if ((cvm::step_relative() > 0) && - (cvm::step_absolute() - first_step <= target_nsteps)) { + if ((cvmodule->step_relative() > 0) && + (cvmodule->step_absolute() - first_step <= target_nsteps)) { for (size_t i = 0; i < num_variables(); i++) { cvm::real const dist = colvar_distance(i); if (dist > 0.0) { @@ -1274,7 +1273,7 @@ int colvarbias_restraint_harmonic_walls::set_state_params(std::string const &con int colvarbias_restraint_harmonic_walls::change_configuration(std::string const &conf) { - return cvm::error("Updating configuration mid-run is not supported for harmonicWalls.", + return cvmodule->error("Updating configuration mid-run is not supported for harmonicWalls.", COLVARS_NOT_IMPLEMENTED); } @@ -1295,8 +1294,8 @@ std::ostream & colvarbias_restraint_harmonic_walls::write_traj(std::ostream &os) -colvarbias_restraint_linear::colvarbias_restraint_linear(char const *key) - : colvarbias(key), +colvarbias_restraint_linear::colvarbias_restraint_linear(colvarmodule *cvmodule_in, char const *key) + : colvarbias(cvmodule_in, key), colvarbias_ti(key), colvarbias_restraint(key), colvarbias_restraint_centers(key), @@ -1316,16 +1315,16 @@ int colvarbias_restraint_linear::init(std::string const &conf) colvarbias_restraint_centers_moving::init(conf); colvarbias_restraint_k_moving::init(conf); - cvm::main()->cite_feature("harmonicWalls colvar bias implementation"); + cvmodule->cite_feature("harmonicWalls colvar bias implementation"); for (size_t i = 0; i < num_variables(); i++) { if (variables(i)->is_enabled(f_cv_periodic)) { - cvm::error("Error: linear biases cannot be applied to periodic variables.\n", + cvmodule->error("Error: linear biases cannot be applied to periodic variables.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } cvm::real const w = variables(i)->width; - cvm::log("The force constant for colvar \""+variables(i)->name+ + cvmodule->log("The force constant for colvar \""+variables(i)->name+ "\" will be rescaled to "+ cvm::to_str(force_k / w)+ " according to the specified width ("+cvm::to_str(w)+").\n"); @@ -1358,7 +1357,7 @@ int colvarbias_restraint_linear::update() int colvarbias_restraint_linear::change_configuration(std::string const &conf) { - return cvm::error("Updating configuration mid-run is not supported for a linear bias.", + return cvmodule->error("Updating configuration mid-run is not supported for a linear bias.", COLVARS_NOT_IMPLEMENTED); } @@ -1441,8 +1440,8 @@ std::ostream & colvarbias_restraint_linear::write_traj(std::ostream &os) -colvarbias_restraint_histogram::colvarbias_restraint_histogram(char const *key) - : colvarbias(key) +colvarbias_restraint_histogram::colvarbias_restraint_histogram(colvarmodule *cvmodule_in, char const *key) + : colvarbias(cvmodule_in, key) { lower_boundary = 0.0; upper_boundary = 0.0; @@ -1461,14 +1460,14 @@ int colvarbias_restraint_histogram::init(std::string const &conf) } enable(f_cvb_apply_force); - cvm::main()->cite_feature("histogramRestraint colvar bias implementation"); + cvmodule->cite_feature("histogramRestraint colvar bias implementation"); get_keyval(conf, "lowerBoundary", lower_boundary, lower_boundary); get_keyval(conf, "upperBoundary", upper_boundary, upper_boundary); get_keyval(conf, "width", width, width); if (width <= 0.0) { - error_code |= cvm::error("Error: \"width\" must be positive.\n", + error_code |= cvmodule->error("Error: \"width\" must be positive.\n", COLVARS_INPUT_ERROR); } @@ -1476,7 +1475,7 @@ int colvarbias_restraint_histogram::init(std::string const &conf) get_keyval(conf, "gaussianSigma", gaussian_width, 2.0 * width); if (lower_boundary >= upper_boundary) { - error_code |= cvm::error("Error: the upper boundary, "+ + error_code |= cvmodule->error("Error: the upper boundary, "+ cvm::to_str(upper_boundary)+ ", is not higher than the lower boundary, "+ cvm::to_str(lower_boundary)+".\n", @@ -1487,11 +1486,11 @@ int colvarbias_restraint_histogram::init(std::string const &conf) int const nbins_round = (int)(nbins); if (cvm::fabs(nbins - cvm::real(nbins_round)) > 1.0E-10) { - cvm::log("Warning: grid interval ("+ - cvm::to_str(lower_boundary, cvm::cv_width, cvm::cv_prec)+" - "+ - cvm::to_str(upper_boundary, cvm::cv_width, cvm::cv_prec)+ + cvmodule->log("Warning: grid interval ("+ + cvm::to_str(lower_boundary, cvmodule->cv_width, cvmodule->cv_prec)+" - "+ + cvm::to_str(upper_boundary, cvmodule->cv_width, cvmodule->cv_prec)+ ") is not commensurate to its bin width ("+ - cvm::to_str(width, cvm::cv_width, cvm::cv_prec)+").\n"); + cvm::to_str(width, cvmodule->cv_width, cvmodule->cv_prec)+").\n"); } p.resize(nbins_round); @@ -1504,12 +1503,12 @@ int colvarbias_restraint_histogram::init(std::string const &conf) get_keyval(conf, "refHistogramFile", ref_p_file, std::string("")); if (ref_p_file.size()) { if (inline_ref_p) { - error_code |= cvm::error("Error: cannot specify both refHistogram and refHistogramFile at the same time.\n", + error_code |= cvmodule->error("Error: cannot specify both refHistogram and refHistogramFile at the same time.\n", COLVARS_INPUT_ERROR); } else { std::istream &is = - cvm::main()->proxy->input_stream(ref_p_file, + cvmodule->proxy->input_stream(ref_p_file, "reference histogram file"); std::string data_s = ""; @@ -1518,15 +1517,15 @@ int colvarbias_restraint_histogram::init(std::string const &conf) data_s.append(line+"\n"); } if (data_s.size() == 0) { - error_code |= cvm::error("Error: file \""+ref_p_file+ + error_code |= cvmodule->error("Error: file \""+ref_p_file+ "\" empty or unreadable.\n", COLVARS_FILE_ERROR); } - error_code |= cvm::main()->proxy->close_input_stream(ref_p_file); + error_code |= cvmodule->proxy->close_input_stream(ref_p_file); cvm::vector1d data; if (data.from_simple_string(data_s) != 0) { - error_code |= cvm::error("Error: could not read histogram from file \""+ + error_code |= cvmodule->error("Error: could not read histogram from file \""+ ref_p_file+"\".\n"); } if (data.size() == 2*ref_p.size()) { @@ -1538,7 +1537,7 @@ int colvarbias_restraint_histogram::init(std::string const &conf) } else if (data.size() == ref_p.size()) { ref_p = data; } else { - error_code |= cvm::error("Error: file \""+ref_p_file+ + error_code |= cvmodule->error("Error: file \""+ref_p_file+ "\" contains a histogram of different length.\n", COLVARS_INPUT_ERROR); } @@ -1547,7 +1546,7 @@ int colvarbias_restraint_histogram::init(std::string const &conf) cvm::real const ref_integral = ref_p.sum() * width; if (cvm::fabs(ref_integral - 1.0) > 1.0e-03) { - cvm::log("Reference distribution not normalized, normalizing to unity.\n"); + cvmodule->log("Reference distribution not normalized, normalizing to unity.\n"); ref_p /= ref_integral; } @@ -1569,7 +1568,7 @@ colvarbias_restraint_histogram::~colvarbias_restraint_histogram() int colvarbias_restraint_histogram::update() { if (cvm::debug()) - cvm::log("Updating the histogram restraint bias \""+this->name+"\".\n"); + cvmodule->log("Updating the histogram restraint bias \""+this->name+"\".\n"); size_t vector_size = 0; size_t icv; @@ -1603,7 +1602,7 @@ int colvarbias_restraint_histogram::update() } } } else { - cvm::error("Error: unsupported type for variable "+variables(icv)->name+".\n", + cvmodule->error("Error: unsupported type for variable "+variables(icv)->name+".\n", COLVARS_NOT_IMPLEMENTED); return COLVARS_NOT_IMPLEMENTED; } @@ -1659,12 +1658,12 @@ int colvarbias_restraint_histogram::update() int colvarbias_restraint_histogram::write_output_files() { if (b_write_histogram) { - colvarproxy *proxy = cvm::main()->proxy; - std::string file_name(cvm::output_prefix()+"."+this->name+".hist.dat"); + colvarproxy *proxy = cvmodule->proxy; + std::string file_name(cvmodule->output_prefix()+"."+this->name+".hist.dat"); std::ostream &os = proxy->output_stream(file_name, "histogram output file"); - os << "# " << cvm::wrap_string(variables(0)->name, cvm::cv_width) - << " " << "p(" << cvm::wrap_string(variables(0)->name, cvm::cv_width-3) + os << "# " << cvmodule->wrap_string(variables(0)->name, cvmodule->cv_width) + << " " << "p(" << cvmodule->wrap_string(variables(0)->name, cvmodule->cv_width-3) << ")\n"; os.setf(std::ios::fixed, std::ios::floatfield); @@ -1673,12 +1672,12 @@ int colvarbias_restraint_histogram::write_output_files() for (igrid = 0; igrid < p.size(); igrid++) { cvm::real const x_grid = (lower_boundary + (igrid+1)*width); os << " " - << std::setprecision(cvm::cv_prec) - << std::setw(cvm::cv_width) + << std::setprecision(cvmodule->cv_prec) + << std::setw(cvmodule->cv_width) << x_grid << " " - << std::setprecision(cvm::cv_prec) - << std::setw(cvm::cv_width) + << std::setprecision(cvmodule->cv_prec) + << std::setw(cvmodule->cv_width) << p[igrid] << "\n"; } proxy->close_output_stream(file_name); @@ -1692,7 +1691,7 @@ std::ostream & colvarbias_restraint_histogram::write_traj_label(std::ostream &os os << " "; if (b_output_energy) { os << " E_" - << cvm::wrap_string(this->name, cvm::en_width-2); + << cvmodule->wrap_string(this->name, cvmodule->en_width-2); } return os; } @@ -1703,7 +1702,7 @@ std::ostream & colvarbias_restraint_histogram::write_traj(std::ostream &os) os << " "; if (b_output_energy) { os << " " - << std::setprecision(cvm::en_prec) << std::setw(cvm::en_width) + << std::setprecision(cvmodule->en_prec) << std::setw(cvmodule->en_width) << bias_energy; } return os; diff --git a/src/colvarbias_restraint.h b/src/colvarbias_restraint.h index ba29db2ad..402f35e12 100644 --- a/src/colvarbias_restraint.h +++ b/src/colvarbias_restraint.h @@ -101,13 +101,11 @@ class colvarbias_restraint_k /// Options to change the restraint configuration over time (shared between centers and k moving) class colvarbias_restraint_moving : public virtual colvarbias_restraint, - public virtual colvarparse, public virtual colvardeps { public: colvarbias_restraint_moving(char const *key) - : colvarbias(key), - colvarbias_ti(key), + : colvarbias_ti(key), colvarbias_restraint(key) {} // Note: despite the diamond inheritance, most of this function gets only executed once virtual int init(std::string const &conf) override; @@ -160,7 +158,7 @@ class colvarbias_restraint_moving /// \brief Update the stage number based on the current step /// Note: this is idempotent so multiple calls are safe inline void update_stage() { - stage = (cvm::step_absolute() - first_step) / target_nsteps; + stage = (cvmodule->step_absolute() - first_step) / target_nsteps; if (stage > target_nstages) { stage = target_nstages; } @@ -234,7 +232,8 @@ class colvarbias_restraint_k_moving public virtual colvarbias_restraint_moving { public: - + // Do not initialize colvarbias here to avoid diamond inheritance issues + // because this is an intermediate class colvarbias_restraint_k_moving(char const *key); virtual int init(std::string const &conf) override; virtual int change_configuration(std::string const & /* conf */) override { return COLVARS_NOT_IMPLEMENTED; } @@ -277,7 +276,7 @@ class colvarbias_restraint_harmonic public colvarbias_restraint_k_moving { public: - colvarbias_restraint_harmonic(char const *key); + colvarbias_restraint_harmonic(colvarmodule *cvmodule_in, char const *key); virtual int init(std::string const &conf); virtual int update(); virtual std::string const get_state_params() const; @@ -302,7 +301,7 @@ class colvarbias_restraint_harmonic_walls { public: - colvarbias_restraint_harmonic_walls(char const *key); + colvarbias_restraint_harmonic_walls(colvarmodule *cvmodule_in, char const *key); virtual int init(std::string const &conf) override; virtual int update() override; virtual int update_acc_work(); @@ -369,7 +368,7 @@ class colvarbias_restraint_linear { public: - colvarbias_restraint_linear(char const *key); + colvarbias_restraint_linear(colvarmodule *cvmodule_in, char const *key); virtual int init(std::string const &conf); virtual int update(); virtual int change_configuration(std::string const &conf); @@ -394,7 +393,7 @@ class colvarbias_restraint_histogram : public colvarbias { public: - colvarbias_restraint_histogram(char const *key); + colvarbias_restraint_histogram(colvarmodule *cvmodule_in, char const *key); int init(std::string const &conf); ~colvarbias_restraint_histogram(); diff --git a/src/colvarcomp.cpp b/src/colvarcomp.cpp index ffd385b11..0c327dfbe 100644 --- a/src/colvarcomp.cpp +++ b/src/colvarcomp.cpp @@ -20,6 +20,15 @@ colvar::cvc::cvc() + : colvardeps(cvm::main()) +{ + description = "uninitialized colvar component"; + cvc::init_dependencies(); +} + + +colvar::cvc::cvc(colvarmodule *cvmodule_in) + : colvardeps(cvmodule_in) { description = "uninitialized colvar component"; cvc::init_dependencies(); @@ -51,9 +60,9 @@ int colvar::cvc::set_function_type(std::string const &type) { function_types.push_back(type); update_description(); - cvm::main()->cite_feature(function_types[0]+" colvar component"); + cvmodule->cite_feature(function_types[0]+" colvar component"); for (size_t i = function_types.size()-1; i > 0; i--) { - cvm::main()->cite_feature(function_types[i]+" colvar component"+ + cvmodule->cite_feature(function_types[i]+" colvar component"+ " (derived from "+function_types[i-1]+")"); } return COLVARS_OK; @@ -63,19 +72,19 @@ int colvar::cvc::set_function_type(std::string const &type) int colvar::cvc::init(std::string const &conf) { if (cvm::debug()) - cvm::log("Initializing cvc base object.\n"); + cvmodule->log("Initializing cvc base object.\n"); int error_code = COLVARS_OK; std::string const old_name(name); if (name.size() > 0) { - cvm::log("Updating configuration for component \""+name+"\"\n"); + cvmodule->log("Updating configuration for component \""+name+"\"\n"); } if (get_keyval(conf, "name", name, name)) { if ((name != old_name) && (old_name.size() > 0)) { - error_code |= cvm::error("Error: cannot rename component \"" + old_name + + error_code |= cvmodule->error("Error: cannot rename component \"" + old_name + "\" after initialization (new name = \"" + name + "\")", COLVARS_INPUT_ERROR); name = old_name; @@ -86,7 +95,7 @@ int colvar::cvc::init(std::string const &conf) get_keyval(conf, "componentCoeff", sup_coeff, sup_coeff); get_keyval(conf, "componentExp", sup_np, sup_np); if (sup_coeff != 1.0 || sup_np != 1) { - cvm::main()->cite_feature("Linear and polynomial combination of colvar components"); + cvmodule->cite_feature("Linear and polynomial combination of colvar components"); } // TODO these could be condensed into get_keyval() register_param("componentCoeff", reinterpret_cast(&sup_coeff)); @@ -101,7 +110,7 @@ int colvar::cvc::init(std::string const &conf) if (period != 0.0) { if (!is_available(f_cvc_periodic)) { error_code |= - cvm::error("Error: invalid use of period and/or " + cvmodule->error("Error: invalid use of period and/or " "wrapAround in a \"" + function_type() + "\" component.\n" + "Period: " + cvm::to_str(period) + " wrapAround: " + cvm::to_str(wrap_center), @@ -112,7 +121,7 @@ int colvar::cvc::init(std::string const &conf) } if ((wrap_center != 0.0) && !is_enabled(f_cvc_periodic)) { - error_code |= cvm::error("Error: wrapAround was defined for a non-periodic component.\n", + error_code |= cvmodule->error("Error: wrapAround was defined for a non-periodic component.\n", COLVARS_INPUT_ERROR); } @@ -131,7 +140,7 @@ int colvar::cvc::init(std::string const &conf) get_keyval(conf, "scalable", b_try_scalable, b_try_scalable); if (cvm::debug()) - cvm::log("Done initializing cvc base object.\n"); + cvmodule->log("Done initializing cvc base object.\n"); return error_code; } @@ -139,16 +148,16 @@ int colvar::cvc::init(std::string const &conf) int colvar::cvc::init_total_force_params(std::string const &conf) { - if (cvm::get_error()) return COLVARS_ERROR; + if (cvmodule->get_error()) return COLVARS_ERROR; if (get_keyval_feature(this, conf, "oneSiteSystemForce", f_cvc_one_site_total_force, is_enabled(f_cvc_one_site_total_force))) { - cvm::log("Warning: keyword \"oneSiteSystemForce\" is deprecated: " + cvmodule->log("Warning: keyword \"oneSiteSystemForce\" is deprecated: " "please use \"oneSiteTotalForce\" instead.\n"); } if (get_keyval_feature(this, conf, "oneSiteTotalForce", f_cvc_one_site_total_force, is_enabled(f_cvc_one_site_total_force))) { - cvm::log("Computing total force on group 1 only\n"); + cvmodule->log("Computing total force on group 1 only\n"); } if (! is_enabled(f_cvc_one_site_total_force)) { @@ -192,7 +201,7 @@ cvm::atom_group *colvar::cvc::parse_group(std::string const &conf, } if (group_conf.empty()) { - error_code |= cvm::error("Error: atom group \"" + group->key + "\" has no definition.\n", + error_code |= cvmodule->error("Error: atom group \"" + group->key + "\" has no definition.\n", COLVARS_INPUT_ERROR); delete group; group = nullptr; @@ -201,11 +210,11 @@ cvm::atom_group *colvar::cvc::parse_group(std::string const &conf, return group; } - cvm::increase_depth(); + cvmodule->increase_depth(); error_code |= group->parse(group_conf); if (error_code != COLVARS_OK) { error_code |= - cvm::error("Error: in definition of atom group \"" + std::string(group_key) + "\".", + cvmodule->error("Error: in definition of atom group \"" + std::string(group_key) + "\".", COLVARS_INPUT_ERROR); delete group; group = nullptr; @@ -213,13 +222,13 @@ cvm::atom_group *colvar::cvc::parse_group(std::string const &conf, register_atom_group(group); error_code |= group->check_keywords(group_conf, group_key); } - cvm::decrease_depth(); + cvmodule->decrease_depth(); } else { if (!optional) { error_code |= - cvm::error("Error: atom group \"" + std::string(group_key) + "\" is required.\n", + cvmodule->error("Error: atom group \"" + std::string(group_key) + "\" is required.\n", COLVARS_INPUT_ERROR); } } @@ -301,7 +310,7 @@ int colvar::cvc::init_dependencies() { // check that everything is initialized for (i = 0; i < colvardeps::f_cvc_ntot; i++) { if (is_not_set(i)) { - cvm::error("Uninitialized feature " + cvm::to_str(i) + " in " + description); + cvmodule->error("Uninitialized feature " + cvm::to_str(i) + " in " + description); } } } @@ -339,7 +348,7 @@ int colvar::cvc::init_dependencies() { feature_states[f_cvc_one_site_total_force].available = true; // Features That are implemented only for certain simulation engine configurations - feature_states[f_cvc_scalable_com].available = (cvm::proxy->scalable_group_coms() == COLVARS_OK); + feature_states[f_cvc_scalable_com].available = (cvmodule->proxy->scalable_group_coms() == COLVARS_OK); feature_states[f_cvc_scalable].available = feature_states[f_cvc_scalable_com].available; return COLVARS_OK; @@ -524,7 +533,7 @@ void colvar::cvc::collect_gradients(std::vector const &atom_ids, std::vecto void colvar::cvc::calc_force_invgrads() { - cvm::error("Error: calculation of inverse gradients is not implemented " + cvmodule->error("Error: calculation of inverse gradients is not implemented " "for colvar components of type \""+function_type()+"\".\n", COLVARS_NOT_IMPLEMENTED); } @@ -532,7 +541,7 @@ void colvar::cvc::calc_force_invgrads() void colvar::cvc::calc_Jacobian_derivative() { - cvm::error("Error: calculation of Jacobian derivatives is not implemented " + cvmodule->error("Error: calculation of Jacobian derivatives is not implemented " "for colvar components of type \""+function_type()+"\".\n", COLVARS_NOT_IMPLEMENTED); } @@ -566,8 +575,8 @@ void colvar::cvc::debug_gradients() // NOTE: this assumes that groups for this cvc are non-overlapping, // since atom coordinates are modified only within the current group - cvm::log("Debugging gradients for " + description); - colvarproxy *p = cvm::main()->proxy; + cvmodule->log("Debugging gradients for " + description); + colvarproxy *p = cvmodule->proxy; #if defined (COLVARS_CUDA) || defined (COLVARS_HIP) cudaStream_t stream = p->get_default_stream(); checkGPUError(cudaStreamSynchronize(stream)); @@ -618,7 +627,7 @@ void colvar::cvc::debug_gradients() const auto rot_0 = group->rot.matrix(); - // cvm::log("gradients = "+cvm::to_str (gradients)+"\n"); + // cvmodule->log("gradients = "+cvm::to_str (gradients)+"\n"); auto *group_for_fit = group->fitting_group ? group->fitting_group : group; cvm::atom_pos fit_gradient_sum, gradient_sum; @@ -629,13 +638,13 @@ void colvar::cvc::debug_gradients() size_t j; // fit_gradients are in the simulation frame: we should print them in the rotated frame - cvm::log("Fit gradients for group " + group->key + ":\n"); + cvmodule->log("Fit gradients for group " + group->key + ":\n"); for (j = 0; j < group_for_fit->size(); j++) { const cvm::rvector fit_grad( group_for_fit->fit_gradients_x(j), group_for_fit->fit_gradients_y(j), group_for_fit->fit_gradients_z(j)); - cvm::log((group->fitting_group ? std::string("fittingGroup") : group->key) + + cvmodule->log((group->fitting_group ? std::string("fittingGroup") : group->key) + "[" + cvm::to_str(j) + "] = " + (group->is_enabled(f_ag_rotate) ? cvm::to_str(rot_0 * (fit_grad)) : @@ -644,7 +653,7 @@ void colvar::cvc::debug_gradients() } } - cvm::log("Gradients for group " + group->key + ":\n"); + cvmodule->log("Gradients for group " + group->key + ":\n"); std::vector gradients = ag_gradients.at(group)[0]; // debug the gradients for (size_t ia = 0; ia < group->size(); ia++) { @@ -668,9 +677,9 @@ void colvar::cvc::debug_gradients() group->read_positions(); // change one coordinate switch (id) { - case 0: group->pos_x(ia) += cvm::debug_gradients_step_size; break; - case 1: group->pos_y(ia) += cvm::debug_gradients_step_size; break; - case 2: group->pos_z(ia) += cvm::debug_gradients_step_size; break; + case 0: group->pos_x(ia) += cvmodule->debug_gradients_step_size; break; + case 1: group->pos_y(ia) += cvmodule->debug_gradients_step_size; break; + case 2: group->pos_z(ia) += cvmodule->debug_gradients_step_size; break; } group->calc_required_properties(); } @@ -689,9 +698,9 @@ void colvar::cvc::debug_gradients() group->read_positions(); // change one coordinate switch (id) { - case 0: group->pos_x(ia) -= cvm::debug_gradients_step_size; break; - case 1: group->pos_y(ia) -= cvm::debug_gradients_step_size; break; - case 2: group->pos_z(ia) -= cvm::debug_gradients_step_size; break; + case 0: group->pos_x(ia) -= cvmodule->debug_gradients_step_size; break; + case 1: group->pos_y(ia) -= cvmodule->debug_gradients_step_size; break; + case 2: group->pos_z(ia) -= cvmodule->debug_gradients_step_size; break; } group->calc_required_properties(); } @@ -700,11 +709,11 @@ void colvar::cvc::debug_gradients() if ((x.type() == colvarvalue::type_vector) && (x.size() == 1)) x_2 = x[0]; cvm::real const num_diff = 0.5 * (x_1 - x_2); - cvm::real const dx_pred = cvm::debug_gradients_step_size * gradients[ia][id]; + cvm::real const dx_pred = cvmodule->debug_gradients_step_size * gradients[ia][id]; cvm::real rel_error = cvm::fabs (num_diff - dx_pred) / (cvm::fabs (num_diff) + cvm::fabs(dx_pred)); - cvm::main()->record_gradient_error(rel_error); + cvmodule->record_gradient_error(rel_error); - cvm::log("Atom "+cvm::to_str(ia) + ", ID " + cvm::to_str(this_atom.id) + \ + cvmodule->log("Atom "+cvm::to_str(ia) + ", ID " + cvm::to_str(this_atom.id) + \ ", comp. " + cvm::to_str(id) + ":" + \ " dx(actual) = " + cvm::to_str (num_diff, 19, 12) + \ " dx(interp) = " + cvm::to_str (dx_pred, 19, 12) + \ @@ -752,9 +761,9 @@ void colvar::cvc::debug_gradients() ref_group->read_positions(); // change one coordinate switch (id) { - case 0: ref_group->pos_x(ia) += cvm::debug_gradients_step_size; break; - case 1: ref_group->pos_y(ia) += cvm::debug_gradients_step_size; break; - case 2: ref_group->pos_z(ia) += cvm::debug_gradients_step_size; break; + case 0: ref_group->pos_x(ia) += cvmodule->debug_gradients_step_size; break; + case 1: ref_group->pos_y(ia) += cvmodule->debug_gradients_step_size; break; + case 2: ref_group->pos_z(ia) += cvmodule->debug_gradients_step_size; break; } group->calc_required_properties(); } @@ -776,9 +785,9 @@ void colvar::cvc::debug_gradients() ref_group->read_positions(); // change one coordinate switch (id) { - case 0: ref_group->pos_x(ia) -= cvm::debug_gradients_step_size; break; - case 1: ref_group->pos_y(ia) -= cvm::debug_gradients_step_size; break; - case 2: ref_group->pos_z(ia) -= cvm::debug_gradients_step_size; break; + case 0: ref_group->pos_x(ia) -= cvmodule->debug_gradients_step_size; break; + case 1: ref_group->pos_y(ia) -= cvmodule->debug_gradients_step_size; break; + case 2: ref_group->pos_z(ia) -= cvmodule->debug_gradients_step_size; break; } group->calc_required_properties(); } @@ -786,11 +795,11 @@ void colvar::cvc::debug_gradients() cvm::real const x_2 = x.real_value; cvm::real const num_diff = 0.5 * (x_1 - x_2); - cvm::real const dx_pred = cvm::debug_gradients_step_size * atom_grad[id]; + cvm::real const dx_pred = cvmodule->debug_gradients_step_size * atom_grad[id]; cvm::real rel_error = cvm::fabs (num_diff - dx_pred) / (cvm::fabs (num_diff) + cvm::fabs(dx_pred)); - cvm::main()->record_gradient_error(rel_error); + cvmodule->record_gradient_error(rel_error); - cvm::log("fittingGroup atom " + cvm::to_str(ia) + ", ID " + cvm::to_str(this_atom.id) + \ + cvmodule->log("fittingGroup atom " + cvm::to_str(ia) + ", ID " + cvm::to_str(this_atom.id) + \ ", comp. " + cvm::to_str(id) + ":" + \ " dx(actual) = " + cvm::to_str (num_diff, 19, 12) + \ " dx(interp) = " + cvm::to_str (dx_pred, 19, 12) + \ @@ -799,7 +808,7 @@ void colvar::cvc::debug_gradients() } } - cvm::log("Gradient sum: " + cvm::to_str(gradient_sum) + + cvmodule->log("Gradient sum: " + cvm::to_str(gradient_sum) + " Fit gradient sum: " + cvm::to_str(fit_gradient_sum) + " Total " + cvm::to_str(gradient_sum + fit_gradient_sum)); } diff --git a/src/colvarcomp.h b/src/colvarcomp.h index 863e5bdc0..9a9506d22 100644 --- a/src/colvarcomp.h +++ b/src/colvarcomp.h @@ -67,7 +67,7 @@ /// class colvar::cvc - : public colvarparse, public colvardeps + : public colvardeps { public: @@ -96,6 +96,8 @@ class colvar::cvc /// Constructor cvc(); + cvc(colvarmodule *cvmodule_in); + /// Destructor virtual ~cvc(); @@ -105,18 +107,18 @@ class colvar::cvc virtual int init(std::string const &conf); /// \brief Initialize dependency tree - virtual int init_dependencies(); + int init_dependencies() override; /// \brief After construction, set data related to dependency handling int setup(); /// \brief Implementation of the feature list accessor for colvar - virtual const std::vector &features() const + virtual const std::vector &features() const override { return cvc_features; } - virtual std::vector &modify_features() + virtual std::vector &modify_features() override { return cvc_features; } @@ -227,7 +229,7 @@ class colvar::cvc virtual colvarvalue const *get_param_grad(std::string const ¶m_name); /// Set the named parameter to the given value - virtual int set_param(std::string const ¶m_name, void const *new_value); + virtual int set_param(std::string const ¶m_name, void const *new_value) override; /// \brief Whether or not this CVC will be computed in parallel whenever possible bool b_try_scalable = true; @@ -237,10 +239,10 @@ class colvar::cvc inline void set_value(colvarvalue const &new_value, bool now=false) { x = new_value; // Cache value to be communicated to back-end between time steps - cvm::proxy->set_alch_lambda(x.real_value); + cvmodule->proxy->set_alch_lambda(x.real_value); if (now) { // If requested (e.g. upon restarting), sync to back-end - cvm::proxy->send_alch_lambda(); + cvmodule->proxy->send_alch_lambda(); } } @@ -825,7 +827,8 @@ class colvar::coordnum cvm::real& g2y, cvm::real& g2z, bool **pairlist_elem, - cvm::real tolerance); + cvm::real tolerance, + colvarmodule *cvmodule_in); /// Workhorse function template int compute_coordnum(); diff --git a/src/colvarcomp_alchlambda.cpp b/src/colvarcomp_alchlambda.cpp index 29168d87c..7a780791b 100644 --- a/src/colvarcomp_alchlambda.cpp +++ b/src/colvarcomp_alchlambda.cpp @@ -30,7 +30,7 @@ colvar::alch_lambda::alch_lambda() x.type(colvarvalue::type_scalar); // Query initial value from back-end; will be overwritten if restarting from a state file - cvm::proxy->get_alch_lambda(&x.real_value); + cvmodule->proxy->get_alch_lambda(&x.real_value); } @@ -43,9 +43,9 @@ int colvar::alch_lambda::init_alchemy(int factor) // Forbid MTS until fully implemented if (factor != 1) { - return cvm::error("Error: timeStepFactor > 1 is not yet supported for alchemical variables."); + return cvmodule->error("Error: timeStepFactor > 1 is not yet supported for alchemical variables."); } - cvm::proxy->request_alch_energy_freq(factor); + cvmodule->proxy->request_alch_energy_freq(factor); return COLVARS_OK; } @@ -56,14 +56,14 @@ void colvar::alch_lambda::calc_value() // By default, follow external parameter // This might get overwritten by driving extended dynamics // (in apply_force() below) - cvm::proxy->get_alch_lambda(&x.real_value); + cvmodule->proxy->get_alch_lambda(&x.real_value); - cvm::proxy->get_dE_dlambda(&ft.real_value); + cvmodule->proxy->get_dE_dlambda(&ft.real_value); ft.real_value *= -1.0; // Convert energy derivative to force // Include any force due to bias on Flambda - ft.real_value += cvm::proxy->indirect_lambda_biasing_force; - cvm::proxy->indirect_lambda_biasing_force = 0.0; + ft.real_value += cvmodule->proxy->indirect_lambda_biasing_force; + cvmodule->proxy->indirect_lambda_biasing_force = 0.0; } @@ -102,7 +102,7 @@ void colvar::alch_Flambda::calc_value() // at the beginning of the timestep we get a force instead of calculating the value // Query initial value from back-end - cvm::proxy->get_dE_dlambda(&x.real_value); + cvmodule->proxy->get_dE_dlambda(&x.real_value); x.real_value *= -1.0; // Energy derivative to force } @@ -117,13 +117,13 @@ void colvar::alch_Flambda::apply_force(colvarvalue const &force) // Convert force on Flambda to force on dE/dlambda cvm::real f = -1.0 * force.real_value; // Send scalar force to back-end, which will distribute it onto atoms - cvm::proxy->apply_force_dE_dlambda(&f); + cvmodule->proxy->apply_force_dE_dlambda(&f); // Propagate force on Flambda to lambda internally cvm::real d2E_dlambda2; - cvm::proxy->get_d2E_dlambda2(&d2E_dlambda2); + cvmodule->proxy->get_d2E_dlambda2(&d2E_dlambda2); // This accumulates a force, it needs to be zeroed when taken into account by lambda - cvm::proxy->indirect_lambda_biasing_force += d2E_dlambda2 * f; + cvmodule->proxy->indirect_lambda_biasing_force += d2E_dlambda2 * f; } diff --git a/src/colvarcomp_angles.cpp b/src/colvarcomp_angles.cpp index 1f603aa0d..f77698c1d 100644 --- a/src/colvarcomp_angles.cpp +++ b/src/colvarcomp_angles.cpp @@ -64,11 +64,11 @@ void colvar::angle::calc_value() cvm::atom_pos const g3_pos = group3->center_of_mass(); r21 = is_enabled(f_cvc_pbc_minimum_image) ? - cvm::position_distance(g2_pos, g1_pos) : + cvmodule->position_distance(g2_pos, g1_pos) : g1_pos - g2_pos; r21l = r21.norm(); r23 = is_enabled(f_cvc_pbc_minimum_image) ? - cvm::position_distance(g2_pos, g3_pos) : + cvmodule->position_distance(g2_pos, g3_pos) : g3_pos - g2_pos; r23l = r23.norm(); @@ -157,10 +157,10 @@ void colvar::dipole_angle::calc_value() group1->calc_dipole(g1_pos); r21 = group1->dipole(); - cvm::log("r21 = " + cvm::to_str(r21) + " ; g1_pos = " + cvm::to_str(g1_pos) + "\n"); + cvmodule->log("r21 = " + cvm::to_str(r21) + " ; g1_pos = " + cvm::to_str(g1_pos) + "\n"); r21l = r21.norm(); r23 = is_enabled(f_cvc_pbc_minimum_image) ? - cvm::position_distance(g2_pos, g3_pos) : + cvmodule->position_distance(g2_pos, g3_pos) : g3_pos - g2_pos; r23l = r23.norm(); @@ -270,13 +270,13 @@ void colvar::dihedral::calc_value() // Usual sign convention: r12 = r2 - r1 r12 = is_enabled(f_cvc_pbc_minimum_image) ? - cvm::position_distance(g1_pos, g2_pos) : + cvmodule->position_distance(g1_pos, g2_pos) : g2_pos - g1_pos; r23 = is_enabled(f_cvc_pbc_minimum_image) ? - cvm::position_distance(g2_pos, g3_pos) : + cvmodule->position_distance(g2_pos, g3_pos) : g3_pos - g2_pos; r34 = is_enabled(f_cvc_pbc_minimum_image) ? - cvm::position_distance(g3_pos, g4_pos) : + cvmodule->position_distance(g3_pos, g4_pos) : g4_pos - g3_pos; cvm::rvector const n1 = cvm::rvector::outer(r12, r23); diff --git a/src/colvarcomp_apath.cpp b/src/colvarcomp_apath.cpp index 78e201071..bbec9dd80 100644 --- a/src/colvarcomp_apath.cpp +++ b/src/colvarcomp_apath.cpp @@ -48,8 +48,8 @@ struct ArithmeticPathImpl: public ArithmeticPathCV::ArithmeticPathBase& p_weights) { - ArithmeticPathCV::ArithmeticPathBase::initialize(p_num_elements, p_total_frames, p_lambda, p_weights); + ArithmeticPathImpl(size_t p_num_elements, size_t p_total_frames, cvm::real p_lambda, const std::vector& p_weights, colvarmodule *cvmodule_in) { + ArithmeticPathCV::ArithmeticPathBase::initialize(p_num_elements, p_total_frames, p_lambda, p_weights, cvmodule_in); frame_element_distances.resize(p_total_frames, std::vector(p_num_elements, colvarvalue(colvarvalue::Type::type_notset))); dsdx.resize(p_total_frames, std::vector(p_num_elements, colvarvalue(colvarvalue::Type::type_notset))); dzdx.resize(p_total_frames, std::vector(p_num_elements, colvarvalue(colvarvalue::Type::type_notset))); @@ -145,15 +145,15 @@ int colvar::aspath::init(std::string const &conf) { int error_code = CartesianBasedPath::init(conf); if (error_code != COLVARS_OK) return error_code; - cvm::log(std::string("Total number of frames: ") + cvm::to_str(total_reference_frames) + std::string("\n")); + cvmodule->log(std::string("Total number of frames: ") + cvm::to_str(total_reference_frames) + std::string("\n")); cvm::real p_lambda; get_keyval(conf, "lambda", p_lambda, -1.0); const size_t num_atoms = atoms->size(); std::vector p_weights(num_atoms, std::sqrt(1.0 / num_atoms)); // ArithmeticPathCV::ArithmeticPathBase::initialize(num_atoms, total_reference_frames, p_lambda, reference_frames[0], p_weights); if (impl_) impl_.reset(); - impl_ = std::unique_ptr(new ArithmeticPathImpl(num_atoms, total_reference_frames, p_lambda, p_weights)); - cvm::log(std::string("Lambda is ") + cvm::to_str(impl_->get_lambda()) + std::string("\n")); + impl_ = std::unique_ptr(new ArithmeticPathImpl(num_atoms, total_reference_frames, p_lambda, p_weights, cvmodule)); + cvmodule->log(std::string("Lambda is ") + cvm::to_str(impl_->get_lambda()) + std::string("\n")); return error_code; } @@ -163,12 +163,12 @@ void colvar::aspath::calc_value() { if (impl_->get_lambda() < 0) { // this implies that the user may not set a valid lambda value // so recompute it by the suggested value in Parrinello's paper - cvm::log("A non-positive value of lambda is detected, which implies that it may not set in the configuration.\n"); - cvm::log("This component (aspath) will recompute a value for lambda following the suggestion in the origin paper.\n"); + cvmodule->log("A non-positive value of lambda is detected, which implies that it may not set in the configuration.\n"); + cvmodule->log("This component (aspath) will recompute a value for lambda following the suggestion in the origin paper.\n"); std::vector rmsd_between_refs(total_reference_frames - 1, 0.0); computeDistanceBetweenReferenceFrames(rmsd_between_refs); impl_->reComputeLambda(rmsd_between_refs); - cvm::log("Ok, the value of lambda is updated to " + cvm::to_str(impl_->get_lambda())); + cvmodule->log("Ok, the value of lambda is updated to " + cvm::to_str(impl_->get_lambda())); } impl_->updateCartesianDistanceToReferenceFrames(this); x = impl_->compute_s(); @@ -202,15 +202,15 @@ int colvar::azpath::init(std::string const &conf) { int error_code = CartesianBasedPath::init(conf); if (error_code != COLVARS_OK) return error_code; - cvm::log(std::string("Total number of frames: ") + cvm::to_str(total_reference_frames) + std::string("\n")); + cvmodule->log(std::string("Total number of frames: ") + cvm::to_str(total_reference_frames) + std::string("\n")); x.type(colvarvalue::type_scalar); cvm::real p_lambda; get_keyval(conf, "lambda", p_lambda, -1.0); const size_t num_atoms = atoms->size(); std::vector p_weights(num_atoms, std::sqrt(1.0 / num_atoms)); if (impl_) impl_.reset(); - impl_ = std::unique_ptr(new ArithmeticPathImpl(num_atoms, total_reference_frames, p_lambda, p_weights)); - cvm::log(std::string("Lambda is ") + cvm::to_str(impl_->get_lambda()) + std::string("\n")); + impl_ = std::unique_ptr(new ArithmeticPathImpl(num_atoms, total_reference_frames, p_lambda, p_weights, cvmodule)); + cvmodule->log(std::string("Lambda is ") + cvm::to_str(impl_->get_lambda()) + std::string("\n")); return error_code; } @@ -220,12 +220,12 @@ void colvar::azpath::calc_value() { if (impl_->get_lambda() < 0) { // this implies that the user may not set a valid lambda value // so recompute it by the suggested value in Parrinello's paper - cvm::log("A non-positive value of lambda is detected, which implies that it may not set in the configuration.\n"); - cvm::log("This component (azpath) will recompute a value for lambda following the suggestion in the origin paper.\n"); + cvmodule->log("A non-positive value of lambda is detected, which implies that it may not set in the configuration.\n"); + cvmodule->log("This component (azpath) will recompute a value for lambda following the suggestion in the origin paper.\n"); std::vector rmsd_between_refs(total_reference_frames - 1, 0.0); computeDistanceBetweenReferenceFrames(rmsd_between_refs); impl_->reComputeLambda(rmsd_between_refs); - cvm::log("Ok, the value of lambda is updated to " + cvm::to_str(impl_->get_lambda())); + cvmodule->log("Ok, the value of lambda is updated to " + cvm::to_str(impl_->get_lambda())); } impl_->updateCartesianDistanceToReferenceFrames(this); x = impl_->compute_z(); @@ -259,20 +259,20 @@ int colvar::aspathCV::init(std::string const &conf) { int error_code = CVBasedPath::init(conf); if (error_code != COLVARS_OK) return error_code; - cvm::log(std::string("Total number of frames: ") + cvm::to_str(total_reference_frames) + std::string("\n")); + cvmodule->log(std::string("Total number of frames: ") + cvm::to_str(total_reference_frames) + std::string("\n")); std::vector p_weights(cv.size(), 1.0); get_keyval(conf, "weights", p_weights, std::vector(cv.size(), 1.0)); use_explicit_gradients = true; cvm::real p_lambda; get_keyval(conf, "lambda", p_lambda, -1.0); if (impl_) impl_.reset(); - impl_ = std::unique_ptr(new ArithmeticPathImpl(cv.size(), total_reference_frames, p_lambda, p_weights)); - cvm::log(std::string("Lambda is ") + cvm::to_str(impl_->get_lambda()) + std::string("\n")); + impl_ = std::unique_ptr(new ArithmeticPathImpl(cv.size(), total_reference_frames, p_lambda, p_weights, cvmodule)); + cvmodule->log(std::string("Lambda is ") + cvm::to_str(impl_->get_lambda()) + std::string("\n")); for (size_t i_cv = 0; i_cv < cv.size(); ++i_cv) { if (!cv[i_cv]->is_enabled(f_cvc_explicit_gradient)) { use_explicit_gradients = false; } - cvm::log(std::string("The weight of CV ") + cvm::to_str(i_cv) + std::string(" is ") + cvm::to_str(p_weights[i_cv]) + std::string("\n")); + cvmodule->log(std::string("The weight of CV ") + cvm::to_str(i_cv) + std::string(" is ") + cvm::to_str(p_weights[i_cv]) + std::string("\n")); } return error_code; } @@ -283,12 +283,12 @@ void colvar::aspathCV::calc_value() { if (impl_->get_lambda() < 0) { // this implies that the user may not set a valid lambda value // so recompute it by the suggested value in Parrinello's paper - cvm::log("A non-positive value of lambda is detected, which implies that it may not set in the configuration.\n"); - cvm::log("This component (aspathCV) will recompute a value for lambda following the suggestion in the origin paper.\n"); + cvmodule->log("A non-positive value of lambda is detected, which implies that it may not set in the configuration.\n"); + cvmodule->log("This component (aspathCV) will recompute a value for lambda following the suggestion in the origin paper.\n"); std::vector rmsd_between_refs(total_reference_frames - 1, 0.0); computeDistanceBetweenReferenceFrames(rmsd_between_refs); impl_->reComputeLambda(rmsd_between_refs); - cvm::log("Ok, the value of lambda is updated to " + cvm::to_str(impl_->get_lambda())); + cvmodule->log("Ok, the value of lambda is updated to " + cvm::to_str(impl_->get_lambda())); } impl_->updateCVDistanceToReferenceFrames(this); x = impl_->compute_s(); @@ -338,20 +338,20 @@ void colvar::aspathCV::apply_force(colvarvalue const &force) { cv[i_cv]->apply_force(force.real_value * grad); // try my best to debug gradients even if the sub-CVs do not have explicit gradients if (is_enabled(f_cvc_debug_gradient)) { - cvm::log("Debugging gradients for " + description + + cvmodule->log("Debugging gradients for " + description + " with respect to sub-CV " + cv[i_cv]->description + ", which has no explicit gradient with respect to its own input(s)"); colvarvalue analytical_grad(cv[i_cv]->value().type()); for (size_t m_frame = 0; m_frame < impl_->dsdx.size(); ++m_frame) { analytical_grad += impl_->compute_s_analytical_derivative_ij( - m_frame, i_cv, cvm::debug_gradients_step_size, this); + m_frame, i_cv, cvmodule->debug_gradients_step_size, this); } - cvm::log("dx(actual) = "+cvm::to_str(analytical_grad, 21, 14)+"\n"); - cvm::log("dx(interp) = "+cvm::to_str(grad, 21, 14)+"\n"); + cvmodule->log("dx(actual) = "+cvm::to_str(analytical_grad, 21, 14)+"\n"); + cvmodule->log("dx(interp) = "+cvm::to_str(grad, 21, 14)+"\n"); cvm::real rel_error = (analytical_grad - grad).norm() / (analytical_grad).norm(); - cvm::main()->record_gradient_error(rel_error); - cvm::log ("|dx(actual) - dx(interp)|/|dx(actual)| = "+ + cvmodule->record_gradient_error(rel_error); + cvmodule->log ("|dx(actual) - dx(interp)|/|dx(actual)| = "+ cvm::to_str(rel_error, 12, 5) + ".\n"); } } @@ -368,20 +368,20 @@ int colvar::azpathCV::init(std::string const &conf) { int error_code = CVBasedPath::init(conf); if (error_code != COLVARS_OK) return error_code; - cvm::log(std::string("Total number of frames: ") + cvm::to_str(total_reference_frames) + std::string("\n")); + cvmodule->log(std::string("Total number of frames: ") + cvm::to_str(total_reference_frames) + std::string("\n")); std::vector p_weights(cv.size(), 1.0); get_keyval(conf, "weights", p_weights, std::vector(cv.size(), 1.0)); use_explicit_gradients = true; cvm::real p_lambda; get_keyval(conf, "lambda", p_lambda, -1.0); if (impl_) impl_.reset(); - impl_ = std::unique_ptr(new ArithmeticPathImpl(cv.size(), total_reference_frames, p_lambda, p_weights)); - cvm::log(std::string("Lambda is ") + cvm::to_str(impl_->get_lambda()) + std::string("\n")); + impl_ = std::unique_ptr(new ArithmeticPathImpl(cv.size(), total_reference_frames, p_lambda, p_weights, cvmodule)); + cvmodule->log(std::string("Lambda is ") + cvm::to_str(impl_->get_lambda()) + std::string("\n")); for (size_t i_cv = 0; i_cv < cv.size(); ++i_cv) { if (!cv[i_cv]->is_enabled(f_cvc_explicit_gradient)) { use_explicit_gradients = false; } - cvm::log(std::string("The weight of CV ") + cvm::to_str(i_cv) + std::string(" is ") + cvm::to_str(p_weights[i_cv]) + std::string("\n")); + cvmodule->log(std::string("The weight of CV ") + cvm::to_str(i_cv) + std::string(" is ") + cvm::to_str(p_weights[i_cv]) + std::string("\n")); } return error_code; } @@ -390,12 +390,12 @@ void colvar::azpathCV::calc_value() { if (impl_->get_lambda() < 0) { // this implies that the user may not set a valid lambda value // so recompute it by the suggested value in Parrinello's paper - cvm::log("A non-positive value of lambda is detected, which implies that it may not set in the configuration.\n"); - cvm::log("This component (azpathCV) will recompute a value for lambda following the suggestion in the origin paper.\n"); + cvmodule->log("A non-positive value of lambda is detected, which implies that it may not set in the configuration.\n"); + cvmodule->log("This component (azpathCV) will recompute a value for lambda following the suggestion in the origin paper.\n"); std::vector rmsd_between_refs(total_reference_frames - 1, 0.0); computeDistanceBetweenReferenceFrames(rmsd_between_refs); impl_->reComputeLambda(rmsd_between_refs); - cvm::log("Ok, the value of lambda is updated to " + cvm::to_str(impl_->get_lambda())); + cvmodule->log("Ok, the value of lambda is updated to " + cvm::to_str(impl_->get_lambda())); } impl_->updateCVDistanceToReferenceFrames(this); x = impl_->compute_z(); @@ -446,20 +446,20 @@ void colvar::azpathCV::apply_force(colvarvalue const &force) { cv[i_cv]->apply_force(force.real_value * grad); // try my best to debug gradients even if the sub-CVs do not have explicit gradients if (is_enabled(f_cvc_debug_gradient)) { - cvm::log("Debugging gradients for " + description + + cvmodule->log("Debugging gradients for " + description + " with respect to sub-CV " + cv[i_cv]->description + ", which has no explicit gradient with respect to its own input(s)"); colvarvalue analytical_grad(cv[i_cv]->value().type()); for (size_t m_frame = 0; m_frame < impl_->dzdx.size(); ++m_frame) { analytical_grad += impl_->compute_z_analytical_derivative_ij( - m_frame, i_cv, cvm::debug_gradients_step_size, this); + m_frame, i_cv, cvmodule->debug_gradients_step_size, this); } - cvm::log("dx(actual) = "+cvm::to_str(analytical_grad, 21, 14)+"\n"); - cvm::log("dx(interp) = "+cvm::to_str(grad, 21, 14)+"\n"); + cvmodule->log("dx(actual) = "+cvm::to_str(analytical_grad, 21, 14)+"\n"); + cvmodule->log("dx(interp) = "+cvm::to_str(grad, 21, 14)+"\n"); cvm::real rel_error = (analytical_grad - grad).norm() / (analytical_grad).norm(); - cvm::main()->record_gradient_error(rel_error); - cvm::log ("|dx(actual) - dx(interp)|/|dx(actual)| = "+ + cvmodule->record_gradient_error(rel_error); + cvmodule->log ("|dx(actual) - dx(interp)|/|dx(actual)| = "+ cvm::to_str(rel_error, 12, 5) + ".\n"); } } diff --git a/src/colvarcomp_combination.cpp b/src/colvarcomp_combination.cpp index bf64abf0a..d0f5890d9 100644 --- a/src/colvarcomp_combination.cpp +++ b/src/colvarcomp_combination.cpp @@ -41,7 +41,7 @@ int colvar::linearCombination::init(std::string const &conf) } // Show useful error messages and prevent crashes if no sub CVC is found if (cv.size() == 0) { - return cvm::error("Error: the CV " + name + " expects one or more nesting components.\n", + return cvmodule->error("Error: the CV " + name + " expects one or more nesting components.\n", COLVARS_INPUT_ERROR); } else { x.type(cv[0]->value()); @@ -185,16 +185,16 @@ int colvar::customColvar::init(std::string const &conf) if (key_lookup(conf, "customFunction", &expr_in, &pos)) { #ifdef LEPTON use_custom_function = true; - cvm::log("This colvar uses a custom function.\n"); + cvmodule->log("This colvar uses a custom function.\n"); do { expr = expr_in; if (cvm::debug()) - cvm::log("Parsing expression \"" + expr + "\".\n"); + cvmodule->log("Parsing expression \"" + expr + "\".\n"); try { pexpr = Lepton::Parser::parse(expr); pexprs.push_back(pexpr); } catch (...) { - return cvm::error("Error parsing expression \"" + expr + "\".\n", COLVARS_INPUT_ERROR); + return cvmodule->error("Error parsing expression \"" + expr + "\".\n", COLVARS_INPUT_ERROR); } try { value_evaluators.push_back(new Lepton::CompiledExpression(pexpr.createCompiledExpression())); @@ -206,13 +206,13 @@ int colvar::customColvar::init(std::string const &conf) ref = &value_evaluators.back()->getVariableReference(vn); } catch (...) { ref = &dev_null; - cvm::log("Warning: Variable " + vn + " is absent from expression \"" + expr + "\".\n"); + cvmodule->log("Warning: Variable " + vn + " is absent from expression \"" + expr + "\".\n"); } value_eval_var_refs.push_back(ref); } } } catch (...) { - return cvm::error("Error compiling expression \"" + expr + "\".\n", COLVARS_INPUT_ERROR); + return cvmodule->error("Error compiling expression \"" + expr + "\".\n", COLVARS_INPUT_ERROR); } } while (key_lookup(conf, "customFunction", &expr_in, &pos)); // Now define derivative with respect to each scalar sub-component @@ -227,7 +227,7 @@ int colvar::customColvar::init(std::string const &conf) try { ref = &gradient_evaluators.back()->getVariableReference(vvn); } catch (...) { - cvm::log("Warning: Variable " + vvn + " is absent from derivative of \"" + expr + "\" wrt " + vn + ".\n"); + cvmodule->log("Warning: Variable " + vvn + " is absent from derivative of \"" + expr + "\" wrt " + vn + ".\n"); ref = &dev_null; } grad_eval_var_refs.push_back(ref); @@ -237,7 +237,7 @@ int colvar::customColvar::init(std::string const &conf) } } if (value_evaluators.size() == 0) { - return cvm::error("Error: no custom function defined.\n", COLVARS_INPUT_ERROR); + return cvmodule->error("Error: no custom function defined.\n", COLVARS_INPUT_ERROR); } if (value_evaluators.size() != 1) { x.type(colvarvalue::type_vector); @@ -245,15 +245,15 @@ int colvar::customColvar::init(std::string const &conf) x.type(colvarvalue::type_scalar); } #else - return cvm::error( + return cvmodule->error( "customFunction requires the Lepton library, but it is not enabled during compilation.\n" "Please refer to the Compilation Notes section of the Colvars manual for more " "information.\n", COLVARS_NOT_IMPLEMENTED); #endif } else { - cvm::log("Warning: no customFunction specified.\n"); - cvm::log("Warning: use linear combination instead.\n"); + cvmodule->log("Warning: no customFunction specified.\n"); + cvmodule->log("Warning: use linear combination instead.\n"); } return error_code; } @@ -293,7 +293,7 @@ void colvar::customColvar::calc_value() { x[i] = value_evaluators[i]->evaluate(); } #else - cvm::error("customFunction requires the Lepton library, but it is not enabled during compilation.\n" + cvmodule->error("customFunction requires the Lepton library, but it is not enabled during compilation.\n" "Please refer to the Compilation Notes section of the Colvars manual for more information.\n", COLVARS_INPUT_ERROR); #endif @@ -333,7 +333,7 @@ void colvar::customColvar::calc_gradients() { } } #else - cvm::error("customFunction requires the Lepton library, but it is not enabled during compilation.\n" + cvmodule->error("customFunction requires the Lepton library, but it is not enabled during compilation.\n" "Please refer to the Compilation Notes section of the Colvars manual for more information.\n", COLVARS_INPUT_ERROR); #endif @@ -374,7 +374,7 @@ void colvar::customColvar::apply_force(colvarvalue const &force) { } } #else - cvm::error("customFunction requires the Lepton library, but it is not enabled during compilation.\n" + cvmodule->error("customFunction requires the Lepton library, but it is not enabled during compilation.\n" "Please refer to the Compilation Notes section of the Colvars manual for more information.\n", COLVARS_INPUT_ERROR); #endif diff --git a/src/colvarcomp_coordnums.cpp b/src/colvarcomp_coordnums.cpp index 30632c187..a5efa12c0 100644 --- a/src/colvarcomp_coordnums.cpp +++ b/src/colvarcomp_coordnums.cpp @@ -33,7 +33,8 @@ cvm::real colvar::coordnum::switching_function(cvm::real const &r0, cvm::real& g2y, cvm::real& g2z, bool **pairlist_elem, - cvm::real pairlist_tol) + cvm::real pairlist_tol, + colvarmodule *cvmodule_in) { if ((flags & ef_use_pairlist) && !(flags & ef_rebuild_pairlist)) { bool const within = **pairlist_elem; @@ -45,7 +46,7 @@ cvm::real colvar::coordnum::switching_function(cvm::real const &r0, const cvm::atom_pos pos1{a1x, a1y, a1z}; const cvm::atom_pos pos2{a2x, a2y, a2z}; - cvm::rvector const diff = cvm::position_distance(pos1, pos2); + cvm::rvector const diff = cvmodule_in->proxy->position_distance(pos1, pos2); cvm::rvector const scal_diff(diff.x * inv_r0_vec.x, diff.y * inv_r0_vec.y, diff.z * inv_r0_vec.z); @@ -111,7 +112,7 @@ colvar::coordnum::coordnum() { set_function_type("coordNum"); x.type(colvarvalue::type_scalar); - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; r0 = proxy->angstrom_to_internal(4.0); r0_vec = cvm::rvector(proxy->angstrom_to_internal(4.0), proxy->angstrom_to_internal(4.0), @@ -131,21 +132,21 @@ int colvar::coordnum::init(std::string const &conf) } if (int atom_number = cvm::atom_group::overlap(*group1, *group2)) { - error_code |= cvm::error( + error_code |= cvmodule->error( "Error: group1 and group2 share a common atom (number: " + cvm::to_str(atom_number) + ")\n", COLVARS_INPUT_ERROR); } if (group1->b_dummy) { error_code |= - cvm::error("Error: only group2 is allowed to be a dummy atom\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: only group2 is allowed to be a dummy atom\n", COLVARS_INPUT_ERROR); } bool const b_isotropic = get_keyval(conf, "cutoff", r0, r0); if (get_keyval(conf, "cutoff3", r0_vec, r0_vec)) { if (b_isotropic) { - error_code |= cvm::error("Error: cannot specify \"cutoff\" and \"cutoff3\" " + error_code |= cvmodule->error("Error: cannot specify \"cutoff\" and \"cutoff3\" " "at the same time.\n", COLVARS_INPUT_ERROR); } @@ -161,27 +162,27 @@ int colvar::coordnum::init(std::string const &conf) get_keyval(conf, "expDenom", ed, ed); if ( (en%2) || (ed%2) ) { - error_code |= cvm::error("Error: odd exponent(s) provided, can only use even ones.\n", + error_code |= cvmodule->error("Error: odd exponent(s) provided, can only use even ones.\n", COLVARS_INPUT_ERROR); } if ( (en <= 0) || (ed <= 0) ) { - error_code |= cvm::error("Error: negative exponent(s) provided.\n", + error_code |= cvmodule->error("Error: negative exponent(s) provided.\n", COLVARS_INPUT_ERROR); } if (!is_enabled(f_cvc_pbc_minimum_image)) { - cvm::log("Warning: only minimum-image distances are used by this variable.\n"); + cvmodule->log("Warning: only minimum-image distances are used by this variable.\n"); } get_keyval(conf, "group2CenterOnly", b_group2_center_only, group2->b_dummy); get_keyval(conf, "tolerance", tolerance, tolerance); if (tolerance > 0) { - cvm::main()->cite_feature("coordNum pairlist"); + cvmodule->cite_feature("coordNum pairlist"); get_keyval(conf, "pairListFrequency", pairlist_freq, pairlist_freq); if ( ! (pairlist_freq > 0) ) { - return cvm::error("Error: non-positive pairlistfrequency provided.\n", + return cvmodule->error("Error: non-positive pairlistfrequency provided.\n", COLVARS_INPUT_ERROR); // return and do not allocate the pairlists below } @@ -241,7 +242,8 @@ template void colvar::coordnum::main_loop(bool **pairlist_elem) group2_com_grad.y, group2_com_grad.z, pairlist_elem, - tolerance); + tolerance, + cvmodule); } if (b_group2_center_only) { group2->set_weighted_gradient(group2_com_grad); @@ -264,7 +266,8 @@ template void colvar::coordnum::main_loop(bool **pairlist_elem) group2->grad_y(j), group2->grad_z(j), pairlist_elem, - tolerance); + tolerance, + cvmodule); } } } @@ -275,7 +278,7 @@ template int colvar::coordnum::compute_coordnum() { bool const use_pairlist = (pairlist != NULL); bool const rebuild_pairlist = (pairlist != NULL) && - (cvm::step_relative() % pairlist_freq == 0); + (cvmodule->step_relative() % pairlist_freq == 0); bool *pairlist_elem = use_pairlist ? pairlist : NULL; @@ -342,7 +345,7 @@ void colvar::coordnum::calc_gradients() colvar::h_bond::h_bond() { - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; r0 = proxy->angstrom_to_internal(3.3); set_function_type("hBond"); x.type(colvarvalue::type_scalar); @@ -355,7 +358,7 @@ int colvar::h_bond::init(std::string const &conf) int error_code = cvc::init(conf); if (cvm::debug()) - cvm::log("Initializing h_bond object.\n"); + cvmodule->log("Initializing h_bond object.\n"); set_function_type("hBond"); x.type(colvarvalue::type_scalar); @@ -366,12 +369,12 @@ int colvar::h_bond::init(std::string const &conf) get_keyval(conf, "donor", d_num, a_num); if ( (a_num == -1) || (d_num == -1) ) { - error_code |= cvm::error("Error: either acceptor or donor undefined.\n", COLVARS_INPUT_ERROR); + error_code |= cvmodule->error("Error: either acceptor or donor undefined.\n", COLVARS_INPUT_ERROR); } register_atom_group(new cvm::atom_group); { - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = cvmodule->proxy; auto modify_atom = atom_groups[0]->get_atom_modifier(); modify_atom.add_atom(cvm::atom_group::init_atom_from_proxy(p, a_num)); modify_atom.add_atom(cvm::atom_group::init_atom_from_proxy(p, d_num)); @@ -382,16 +385,16 @@ int colvar::h_bond::init(std::string const &conf) get_keyval(conf, "expDenom", ed, ed); if ((en % 2) || (ed % 2)) { - error_code |= cvm::error("Error: odd exponent(s) provided, can only use even ones.\n", + error_code |= cvmodule->error("Error: odd exponent(s) provided, can only use even ones.\n", COLVARS_INPUT_ERROR); } if ((en <= 0) || (ed <= 0)) { - error_code |= cvm::error("Error: negative exponent(s) provided.\n", COLVARS_INPUT_ERROR); + error_code |= cvmodule->error("Error: negative exponent(s) provided.\n", COLVARS_INPUT_ERROR); } if (cvm::debug()) - cvm::log("Done initializing h_bond object.\n"); + cvmodule->log("Done initializing h_bond object.\n"); return error_code; } @@ -444,7 +447,7 @@ void colvar::h_bond::calc_value() atom_groups[0]->grad_x(1), atom_groups[0]->grad_y(1), atom_groups[0]->grad_z(1), - NULL, 0.0); + NULL, 0.0, cvmodule); // Skip the gradient } @@ -474,7 +477,7 @@ void colvar::h_bond::calc_gradients() atom_groups[0]->grad_x(1), atom_groups[0]->grad_y(1), atom_groups[0]->grad_z(1), - NULL, 0.0); + NULL, 0.0, cvmodule); } @@ -483,7 +486,7 @@ colvar::selfcoordnum::selfcoordnum() { set_function_type("selfCoordNum"); x.type(colvarvalue::type_scalar); - r0 = cvm::main()->proxy->angstrom_to_internal(4.0); + r0 = cvmodule->proxy->angstrom_to_internal(4.0); } @@ -503,23 +506,23 @@ int colvar::selfcoordnum::init(std::string const &conf) if ((en % 2) || (ed % 2)) { - error_code |= cvm::error("Error: odd exponent(s) provided, can only use even ones.\n", + error_code |= cvmodule->error("Error: odd exponent(s) provided, can only use even ones.\n", COLVARS_INPUT_ERROR); } if ((en <= 0) || (ed <= 0)) { - error_code |= cvm::error("Error: negative exponent(s) provided.\n", COLVARS_INPUT_ERROR); + error_code |= cvmodule->error("Error: negative exponent(s) provided.\n", COLVARS_INPUT_ERROR); } if (!is_enabled(f_cvc_pbc_minimum_image)) { - cvm::log("Warning: only minimum-image distances are used by this variable.\n"); + cvmodule->log("Warning: only minimum-image distances are used by this variable.\n"); } get_keyval(conf, "tolerance", tolerance, tolerance); if (tolerance > 0) { get_keyval(conf, "pairListFrequency", pairlist_freq, pairlist_freq); if ( ! (pairlist_freq > 0) ) { - error_code |= cvm::error("Error: non-positive pairlistfrequency provided.\n", + error_code |= cvmodule->error("Error: non-positive pairlistfrequency provided.\n", COLVARS_INPUT_ERROR); } size_t n = (group1->size()-1) * (group1->size()-1); @@ -548,7 +551,7 @@ template int colvar::selfcoordnum::compute_selfcoordnum() bool const use_pairlist = (pairlist != NULL); bool const rebuild_pairlist = (pairlist != NULL) && - (cvm::step_relative() % pairlist_freq == 0); + (cvmodule->step_relative() % pairlist_freq == 0); bool *pairlist_elem = use_pairlist ? pairlist : NULL; size_t i = 0, j = 0; @@ -581,7 +584,7 @@ template int colvar::selfcoordnum::compute_selfcoordnum() group1->grad_x(j), \ group1->grad_y(j), \ group1->grad_z(j), \ - &pairlist_elem, tolerance); \ + &pairlist_elem, tolerance, cvmodule); \ } \ } \ } while (0); @@ -627,7 +630,7 @@ colvar::groupcoordnum::groupcoordnum() set_function_type("groupCoord"); x.type(colvarvalue::type_scalar); init_scalar_boundaries(0.0, 1.0); - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; r0 = proxy->angstrom_to_internal(4.0); r0_vec = cvm::rvector(proxy->angstrom_to_internal(4.0), proxy->angstrom_to_internal(4.0), @@ -641,7 +644,7 @@ int colvar::groupcoordnum::init(std::string const &conf) // group1 and group2 are already initialized by distance() if (group1->b_dummy || group2->b_dummy) { - return cvm::error("Error: neither group can be a dummy atom\n", COLVARS_INPUT_ERROR); + return cvmodule->error("Error: neither group can be a dummy atom\n", COLVARS_INPUT_ERROR); } bool const b_scale = get_keyval(conf, "cutoff", r0, r0); @@ -649,7 +652,7 @@ int colvar::groupcoordnum::init(std::string const &conf) if (get_keyval(conf, "cutoff3", r0_vec, r0_vec)) { if (b_scale) { error_code |= - cvm::error("Error: cannot specify \"cutoff\" and \"cutoff3\" at the same time.\n", + cvmodule->error("Error: cannot specify \"cutoff\" and \"cutoff3\" at the same time.\n", COLVARS_INPUT_ERROR); } b_anisotropic = true; @@ -663,16 +666,16 @@ int colvar::groupcoordnum::init(std::string const &conf) get_keyval(conf, "expDenom", ed, ed); if ((en % 2) || (ed % 2)) { - error_code |= cvm::error("Error: odd exponent(s) provided, can only use even ones.\n", + error_code |= cvmodule->error("Error: odd exponent(s) provided, can only use even ones.\n", COLVARS_INPUT_ERROR); } if ((en <= 0) || (ed <= 0)) { - error_code |= cvm::error("Error: negative exponent(s) provided.\n", COLVARS_INPUT_ERROR); + error_code |= cvmodule->error("Error: negative exponent(s) provided.\n", COLVARS_INPUT_ERROR); } if (!is_enabled(f_cvc_pbc_minimum_image)) { - cvm::log("Warning: only minimum-image distances are used by this variable.\n"); + cvmodule->log("Warning: only minimum-image distances are used by this variable.\n"); } return error_code; @@ -700,7 +703,7 @@ void colvar::groupcoordnum::calc_value() A1.x, A1.y, A1.z, \ A2.x, A2.y, A2.z, \ G1.x, G1.y, G1.z, \ - G2.x, G2.y, G2.z, NULL, 0.0); \ + G2.x, G2.y, G2.z, NULL, 0.0, cvmodule); \ } while (0); if (b_anisotropic) { int const flags = coordnum::ef_anisotropic; @@ -731,7 +734,7 @@ void colvar::groupcoordnum::calc_gradients() A1.x, A1.y, A1.z, \ A2.x, A2.y, A2.z, \ G1.x, G1.y, G1.z, \ - G2.x, G2.y, G2.z, NULL, 0.0); \ + G2.x, G2.y, G2.z, NULL, 0.0, cvmodule); \ } while (0); if (b_anisotropic) { int const flags = coordnum::ef_gradients | coordnum::ef_anisotropic; diff --git a/src/colvarcomp_distances.cpp b/src/colvarcomp_distances.cpp index f13e81420..5b6725943 100644 --- a/src/colvarcomp_distances.cpp +++ b/src/colvarcomp_distances.cpp @@ -50,7 +50,7 @@ void colvar::distance::calc_value() if (!is_enabled(f_cvc_pbc_minimum_image)) { dist_v = group2->center_of_mass() - group1->center_of_mass(); } else { - dist_v = cvm::position_distance(group1->center_of_mass(), + dist_v = cvmodule->position_distance(group1->center_of_mass(), group2->center_of_mass()); } x.real_value = dist_v.norm(); @@ -97,7 +97,7 @@ void colvar::distance_vec::calc_value() if (!is_enabled(f_cvc_pbc_minimum_image)) { x.rvector_value = group2->center_of_mass() - group1->center_of_mass(); } else { - x.rvector_value = cvm::position_distance(group1->center_of_mass(), + x.rvector_value = cvmodule->position_distance(group1->center_of_mass(), group2->center_of_mass()); } } @@ -123,7 +123,7 @@ void colvar::distance_vec::apply_force(colvarvalue const &force) cvm::real colvar::distance_vec::dist2(colvarvalue const &x1, colvarvalue const &x2) const { if (is_enabled(f_cvc_pbc_minimum_image)) { - return (cvm::position_distance(x1.rvector_value, x2.rvector_value)).norm2(); + return (cvmodule->position_distance(x1.rvector_value, x2.rvector_value)).norm2(); } return (x2.rvector_value - x1.rvector_value).norm2(); } @@ -132,7 +132,7 @@ cvm::real colvar::distance_vec::dist2(colvarvalue const &x1, colvarvalue const & colvarvalue colvar::distance_vec::dist2_lgrad(colvarvalue const &x1, colvarvalue const &x2) const { if (is_enabled(f_cvc_pbc_minimum_image)) { - return 2.0 * cvm::position_distance(x2.rvector_value, x1.rvector_value); + return 2.0 * cvmodule->position_distance(x2.rvector_value, x1.rvector_value); } return 2.0 * (x2.rvector_value - x1.rvector_value); } @@ -168,18 +168,18 @@ int colvar::distance_z::init(std::string const &conf) ref2 = parse_group(conf, "ref2", true); if ( ref2 ) { - cvm::log("Using axis joining the centers of mass of groups \"ref\" and \"ref2\"\n"); + cvmodule->log("Using axis joining the centers of mass of groups \"ref\" and \"ref2\"\n"); fixed_axis = false; if (key_lookup(conf, "axis")) - cvm::log("Warning: explicit axis definition will be ignored!\n"); + cvmodule->log("Warning: explicit axis definition will be ignored!\n"); } else { if (get_keyval(conf, "axis", axis, cvm::rvector(0.0, 0.0, 1.0))) { if (axis.norm2() == 0.0) { - error_code |= cvm::error("Axis vector is zero!", COLVARS_INPUT_ERROR); + error_code |= cvmodule->error("Axis vector is zero!", COLVARS_INPUT_ERROR); } if (axis.norm2() != 1.0) { axis = axis.unit(); - cvm::log("The normalized axis is: "+cvm::to_str(axis)+".\n"); + cvmodule->log("The normalized axis is: "+cvm::to_str(axis)+".\n"); } } fixed_axis = true; @@ -199,7 +199,7 @@ void colvar::distance_z::calc_value() if (!is_enabled(f_cvc_pbc_minimum_image)) { dist_v = M - R1; } else { - dist_v = cvm::position_distance(R1, M); + dist_v = cvmodule->position_distance(R1, M); } } else { cvm::rvector const R2 = ref2->center_of_mass(); @@ -208,8 +208,8 @@ void colvar::distance_z::calc_value() dist_v = M - C; axis = R2 - R1; } else { - dist_v = cvm::position_distance(C, M); - axis = cvm::position_distance(R1, R2); + dist_v = cvmodule->position_distance(C, M); + axis = cvmodule->position_distance(R1, R2); } axis_norm = axis.norm(); axis = axis.unit(); @@ -271,14 +271,14 @@ void colvar::distance_xy::calc_value() if (!is_enabled(f_cvc_pbc_minimum_image)) { dist_v = main->center_of_mass() - ref1->center_of_mass(); } else { - dist_v = cvm::position_distance(ref1->center_of_mass(), + dist_v = cvmodule->position_distance(ref1->center_of_mass(), main->center_of_mass()); } if (!fixed_axis) { if (!is_enabled(f_cvc_pbc_minimum_image)) { v12 = ref2->center_of_mass() - ref1->center_of_mass(); } else { - v12 = cvm::position_distance(ref1->center_of_mass(), + v12 = cvmodule->position_distance(ref1->center_of_mass(), ref2->center_of_mass()); } axis_norm = v12.norm(); @@ -307,7 +307,7 @@ void colvar::distance_xy::calc_gradients() if (!is_enabled(f_cvc_pbc_minimum_image)) { v13 = main->center_of_mass() - ref1->center_of_mass(); } else { - v13 = cvm::position_distance(ref1->center_of_mass(), + v13 = cvmodule->position_distance(ref1->center_of_mass(), main->center_of_mass()); } A = (dist_v * axis) / axis_norm; @@ -353,7 +353,7 @@ void colvar::distance_dir::calc_value() if (!is_enabled(f_cvc_pbc_minimum_image)) { dist_v = group2->center_of_mass() - group1->center_of_mass(); } else { - dist_v = cvm::position_distance(group1->center_of_mass(), + dist_v = cvmodule->position_distance(group1->center_of_mass(), group2->center_of_mass()); } x.rvector_value = dist_v.unit(); @@ -424,20 +424,20 @@ int colvar::distance_inv::init(std::string const &conf) get_keyval(conf, "exponent", exponent, exponent); if (exponent % 2) { error_code |= - cvm::error("Error: odd exponent provided, can only use even ones.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: odd exponent provided, can only use even ones.\n", COLVARS_INPUT_ERROR); } if (exponent <= 0) { - error_code |= cvm::error("Error: negative or zero exponent provided.\n", COLVARS_INPUT_ERROR); + error_code |= cvmodule->error("Error: negative or zero exponent provided.\n", COLVARS_INPUT_ERROR); } if (cvm::atom_group::overlap(*group1, *group2) != 0) { - error_code |= cvm::error("Error: group1 and group2 have some atoms in common: this is not " + error_code |= cvmodule->error("Error: group1 and group2 have some atoms in common: this is not " "allowed for distanceInv.\n", COLVARS_INPUT_ERROR); } if (is_enabled(f_cvc_debug_gradient)) { - cvm::log("Warning: debugGradients will not give correct results " + cvmodule->log("Warning: debugGradients will not give correct results " "for distanceInv, because its value and gradients are computed " "simultaneously.\n"); } @@ -461,7 +461,7 @@ void colvar::distance_inv::calc_value() group2->pos_z(j)); \ cvm::rvector dv; \ if (USE_PBC_MINIMUM_IMAGE) { \ - dv = cvm::position_distance(pos1, pos2); \ + dv = cvmodule->position_distance(pos1, pos2); \ } else { \ dv = pos2 - pos1; \ } \ @@ -544,7 +544,7 @@ void colvar::distance_pairs::calc_value() group2->pos_y(i2), \ group2->pos_z(i2)); \ const cvm::rvector dv = USE_PBC_MINIMUM_IMAGE ? \ - cvm::position_distance(pos1, pos2) : \ + cvmodule->position_distance(pos1, pos2) : \ pos2 - pos1; \ cvm::real const d = dv.norm(); \ x.vector1d_value[i1*group2->size() + i2] = d; \ @@ -589,7 +589,7 @@ void colvar::distance_pairs::apply_force(colvarvalue const &force) group2->pos_y(i2), \ group2->pos_z(i2)); \ const cvm::rvector dv = USE_PBC_MINIMUM_IMAGE ? \ - cvm::position_distance(pos1, pos2) : \ + cvmodule->position_distance(pos1, pos2) : \ pos2 - pos1; \ cvm::real const d = dv.norm(); \ x.vector1d_value[i1*group2->size() + i2] = d; \ @@ -686,7 +686,7 @@ int colvar::gyration::init(std::string const &conf) atoms = parse_group(conf, "atoms"); if (atoms->b_user_defined_fit) { - cvm::log("WARNING: explicit fitting parameters were provided for atom group \"atoms\".\n"); + cvmodule->log("WARNING: explicit fitting parameters were provided for atom group \"atoms\".\n"); } else { atoms->enable(f_ag_center); std::vector ref_pos_aos{cvm::atom_pos(0, 0, 0)}; @@ -777,11 +777,11 @@ int colvar::inertia_z::init(std::string const &conf) int error_code = inertia::init(conf); if (get_keyval(conf, "axis", axis, cvm::rvector(0.0, 0.0, 1.0))) { if (axis.norm2() == 0.0) { - error_code |= cvm::error("Axis vector is zero!", COLVARS_INPUT_ERROR); + error_code |= cvmodule->error("Axis vector is zero!", COLVARS_INPUT_ERROR); } if (axis.norm2() != 1.0) { axis = axis.unit(); - cvm::log("The normalized axis is: "+cvm::to_str(axis)+".\n"); + cvmodule->log("The normalized axis is: "+cvm::to_str(axis)+".\n"); } } return error_code; @@ -837,7 +837,7 @@ int colvar::rmsd::init(std::string const &conf) bool b_Jacobian_derivative = true; if (atoms->fitting_group != NULL && b_Jacobian_derivative) { - cvm::log("The option \"fittingGroup\" (alternative group for fitting) was enabled: " + cvmodule->log("The option \"fittingGroup\" (alternative group for fitting) was enabled: " "Jacobian derivatives of the RMSD will not be calculated.\n"); b_Jacobian_derivative = false; } @@ -847,9 +847,9 @@ int colvar::rmsd::init(std::string const &conf) // we need this because the reference coordinates defined inside the atom group // may be used only for fitting, and even more so if fitting_group is used if (get_keyval(conf, "refPositions", ref_pos, ref_pos)) { - cvm::log("Using reference positions from configuration file to calculate the variable.\n"); + cvmodule->log("Using reference positions from configuration file to calculate the variable.\n"); if (ref_pos.size() != atoms->size()) { - error_code |= cvm::error("Error: the number of reference positions provided (" + + error_code |= cvmodule->error("Error: the number of reference positions provided (" + cvm::to_str(ref_pos.size()) + ") does not match the number of atoms of group \"atoms\" (" + cvm::to_str(atoms->size()) + ").\n", @@ -860,7 +860,7 @@ int colvar::rmsd::init(std::string const &conf) if (get_keyval(conf, "refPositionsFile", ref_pos_file, std::string(""))) { if (ref_pos.size()) { - error_code |= cvm::error("Error: cannot specify \"refPositionsFile\" and " + error_code |= cvmodule->error("Error: cannot specify \"refPositionsFile\" and " "\"refPositions\" at the same time.\n", COLVARS_INPUT_ERROR); } @@ -872,7 +872,7 @@ int colvar::rmsd::init(std::string const &conf) // if provided, use PDB column to select coordinates bool found = get_keyval(conf, "refPositionsColValue", ref_pos_col_value, 0.0); if (found && ref_pos_col_value==0.0) { - error_code |= cvm::error("Error: refPositionsColValue, " + error_code |= cvmodule->error("Error: refPositionsColValue, " "if provided, must be non-zero.\n", COLVARS_INPUT_ERROR); } @@ -880,10 +880,10 @@ int colvar::rmsd::init(std::string const &conf) ref_pos.resize(atoms->size()); - cvm::load_coords(ref_pos_file.c_str(), &ref_pos, atoms, + cvmodule->load_coords(ref_pos_file.c_str(), &ref_pos, atoms, ref_pos_col, ref_pos_col_value); } else { - error_code |= cvm::error( + error_code |= cvmodule->error( "Error: no reference positions for RMSD; use either refPositions of refPositionsFile.", COLVARS_INPUT_ERROR); } @@ -891,16 +891,16 @@ int colvar::rmsd::init(std::string const &conf) if (ref_pos.size() != atoms->size()) { error_code |= - cvm::error("Error: found " + cvm::to_str(ref_pos.size()) + + cvmodule->error("Error: found " + cvm::to_str(ref_pos.size()) + " reference positions for RMSD; expected " + cvm::to_str(atoms->size()), COLVARS_INPUT_ERROR); } if (atoms->b_user_defined_fit) { - cvm::log("WARNING: explicit fitting parameters were provided for atom group \"atoms\".\n"); + cvmodule->log("WARNING: explicit fitting parameters were provided for atom group \"atoms\".\n"); } else { // Default: fit everything - cvm::log("Enabling \"centerToReference\" and \"rotateToReference\", to minimize RMSD before calculating it as a variable: " + cvmodule->log("Enabling \"centerToReference\" and \"rotateToReference\", to minimize RMSD before calculating it as a variable: " "if this is not the desired behavior, disable them explicitly within the \"atoms\" block.\n"); atoms->enable(f_ag_center); atoms->enable(f_ag_rotate); @@ -909,7 +909,7 @@ int colvar::rmsd::init(std::string const &conf) atoms->set_ref_pos_from_aos(ref_pos); atoms->center_ref_pos(); - cvm::log("This is a standard minimum RMSD, derivatives of the optimal rotation " + cvmodule->log("This is a standard minimum RMSD, derivatives of the optimal rotation " "will not be computed as they cancel out in the gradients."); atoms->disable(f_ag_fit_gradients); } @@ -929,7 +929,7 @@ int colvar::rmsd::init_permutation(std::string const &conf) n_permutations = 1; while (key_lookup(conf, "atomPermutation", &perm_conf, &pos)) { - cvm::main()->cite_feature("Symmetry-adapted RMSD"); + cvmodule->cite_feature("Symmetry-adapted RMSD"); std::vector perm; if (perm_conf.size()) { std::istringstream is(perm_conf); @@ -938,24 +938,24 @@ int colvar::rmsd::init_permutation(std::string const &conf) std::vector const &ids = atoms->ids(); size_t const ia = std::find(ids.begin(), ids.end(), index-1) - ids.begin(); if (ia == atoms->size()) { - error_code |= cvm::error("Error: atom id " + cvm::to_str(index) + + error_code |= cvmodule->error("Error: atom id " + cvm::to_str(index) + " is not a member of group \"atoms\".", COLVARS_INPUT_ERROR); } if (std::find(perm.begin(), perm.end(), ia) != perm.end()) { - error_code |= cvm::error("Error: atom id " + cvm::to_str(index) + + error_code |= cvmodule->error("Error: atom id " + cvm::to_str(index) + " is mentioned more than once in atomPermutation list.", COLVARS_INPUT_ERROR); } perm.push_back(ia); } if (perm.size() != atoms->size()) { - error_code |= cvm::error( + error_code |= cvmodule->error( "Error: symmetry permutation in input contains " + cvm::to_str(perm.size()) + " indices, but group \"atoms\" contains " + cvm::to_str(atoms->size()) + " atoms.", COLVARS_INPUT_ERROR); } - cvm::log("atomPermutation = " + cvm::to_str(perm)); + cvmodule->log("atomPermutation = " + cvm::to_str(perm)); n_permutations++; // Record a copy of reference positions in new order for (size_t ia = 0; ia < atoms->size(); ia++) { @@ -1117,9 +1117,9 @@ int colvar::eigenvector::init(std::string const &conf) bool const b_inline = get_keyval(conf, "refPositions", ref_pos, ref_pos); if (b_inline) { - cvm::log("Using reference positions from input file.\n"); + cvmodule->log("Using reference positions from input file.\n"); if (ref_pos.size() != atoms->size()) { - error_code |= cvm::error("Error: reference positions do not " + error_code |= cvmodule->error("Error: reference positions do not " "match the number of requested atoms.\n", COLVARS_INPUT_ERROR); } @@ -1129,7 +1129,7 @@ int colvar::eigenvector::init(std::string const &conf) if (get_keyval(conf, "refPositionsFile", file_name)) { if (b_inline) { - error_code |= cvm::error( + error_code |= cvmodule->error( "Error: refPositions and refPositionsFile cannot be specified at the same time.\n", COLVARS_INPUT_ERROR); } @@ -1139,24 +1139,24 @@ int colvar::eigenvector::init(std::string const &conf) // use PDB flags if column is provided bool found = get_keyval(conf, "refPositionsColValue", file_col_value, 0.0); if (found && file_col_value == 0.0) { - error_code |= cvm::error("Error: refPositionsColValue, if provided, must be non-zero.\n", + error_code |= cvmodule->error("Error: refPositionsColValue, if provided, must be non-zero.\n", COLVARS_INPUT_ERROR); } } ref_pos.resize(atoms->size()); - cvm::load_coords(file_name.c_str(), &ref_pos, atoms, + cvmodule->load_coords(file_name.c_str(), &ref_pos, atoms, file_col, file_col_value); } } if (ref_pos.size() == 0) { error_code |= - cvm::error("Error: reference positions were not provided.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: reference positions were not provided.\n", COLVARS_INPUT_ERROR); } if (ref_pos.size() != atoms->size()) { - error_code |= cvm::error("Error: reference positions do not " + error_code |= cvmodule->error("Error: reference positions do not " "match the number of requested atoms.\n", COLVARS_INPUT_ERROR); } @@ -1169,10 +1169,10 @@ int colvar::eigenvector::init(std::string const &conf) ref_pos_center *= 1.0 / atoms->size(); if (atoms->b_user_defined_fit) { - cvm::log("WARNING: explicit fitting parameters were provided for atom group \"atoms\".\n"); + cvmodule->log("WARNING: explicit fitting parameters were provided for atom group \"atoms\".\n"); } else { // default: fit everything - cvm::log("Enabling \"centerToReference\" and \"rotateToReference\", to minimize RMSD before calculating the vector projection: " + cvmodule->log("Enabling \"centerToReference\" and \"rotateToReference\", to minimize RMSD before calculating the vector projection: " "if this is not the desired behavior, disable them explicitly within the \"atoms\" block.\n"); atoms->enable(f_ag_center); atoms->enable(f_ag_rotate); @@ -1186,9 +1186,9 @@ int colvar::eigenvector::init(std::string const &conf) bool const b_inline = get_keyval(conf, "vector", eigenvec, eigenvec); // now load the eigenvector if (b_inline) { - cvm::log("Using vector components from input file.\n"); + cvmodule->log("Using vector components from input file.\n"); if (eigenvec.size() != atoms->size()) { - error_code |= cvm::error("Error: vector components do not " + error_code |= cvmodule->error("Error: vector components do not " "match the number of requested atoms->\n", COLVARS_INPUT_ERROR); } } @@ -1198,7 +1198,7 @@ int colvar::eigenvector::init(std::string const &conf) if (b_inline) { error_code |= - cvm::error("Error: vector and vectorFile cannot be specified at the same time.\n", + cvmodule->error("Error: vector and vectorFile cannot be specified at the same time.\n", COLVARS_INPUT_ERROR); } @@ -1208,19 +1208,19 @@ int colvar::eigenvector::init(std::string const &conf) // use PDB flags if column is provided bool found = get_keyval(conf, "vectorColValue", file_col_value, 0.0); if (found && file_col_value==0.0) { - error_code |= cvm::error("Error: vectorColValue, if provided, must be non-zero.\n", + error_code |= cvmodule->error("Error: vectorColValue, if provided, must be non-zero.\n", COLVARS_INPUT_ERROR); } } eigenvec.resize(atoms->size()); - cvm::load_coords(file_name.c_str(), &eigenvec, atoms, + cvmodule->load_coords(file_name.c_str(), &eigenvec, atoms, file_col, file_col_value); } } if (!ref_pos.size() || !eigenvec.size()) { - error_code |= cvm::error("Error: both reference coordinates and eigenvector must be defined.\n", + error_code |= cvmodule->error("Error: both reference coordinates and eigenvector must be defined.\n", COLVARS_INPUT_ERROR); } @@ -1229,7 +1229,7 @@ int colvar::eigenvector::init(std::string const &conf) eig_center += eigenvec[eil]; } eig_center *= 1.0 / atoms->size(); - cvm::log("Geometric center of the provided vector: "+cvm::to_str(eig_center)+"\n"); + cvmodule->log("Geometric center of the provided vector: "+cvm::to_str(eig_center)+"\n"); bool b_difference_vector = false; get_keyval(conf, "differenceVector", b_difference_vector, false); @@ -1250,7 +1250,7 @@ int colvar::eigenvector::init(std::string const &conf) eigenvec[i] = rot_mat * eigenvec[i]; } } - cvm::log("\"differenceVector\" is on: subtracting the reference positions from the provided vector: v = x_vec - x_ref.\n"); + cvmodule->log("\"differenceVector\" is on: subtracting the reference positions from the provided vector: v = x_vec - x_ref.\n"); for (size_t i = 0; i < atoms->size(); i++) { eigenvec[i] -= ref_pos[i]; } @@ -1262,7 +1262,7 @@ int colvar::eigenvector::init(std::string const &conf) } } else { - cvm::log("Centering the provided vector to zero.\n"); + cvmodule->log("Centering the provided vector to zero.\n"); for (size_t i = 0; i < atoms->size(); i++) { eigenvec[i] -= eig_center; } @@ -1280,19 +1280,19 @@ int colvar::eigenvector::init(std::string const &conf) get_keyval(conf, "normalizeVector", normalize, normalize); if (normalize) { - cvm::log("Normalizing the vector so that |v| = 1.\n"); + cvmodule->log("Normalizing the vector so that |v| = 1.\n"); for (size_t i = 0; i < atoms->size(); i++) { eigenvec[i] *= cvm::sqrt(eigenvec_invnorm2); } eigenvec_invnorm2 = 1.0; } else if (b_difference_vector) { - cvm::log("Normalizing the vector so that the norm of the projection |v â‹… (x_vec - x_ref)| = 1.\n"); + cvmodule->log("Normalizing the vector so that the norm of the projection |v â‹… (x_vec - x_ref)| = 1.\n"); for (size_t i = 0; i < atoms->size(); i++) { eigenvec[i] *= eigenvec_invnorm2; } eigenvec_invnorm2 = 1.0/eigenvec_invnorm2; } else { - cvm::log("The norm of the vector is |v| = "+ + cvmodule->log("The norm of the vector is |v| = "+ cvm::to_str(1.0/cvm::sqrt(eigenvec_invnorm2))+".\n"); } @@ -1413,7 +1413,7 @@ int colvar::cartesian::init(std::string const &conf) if (axes.size() == 0) { error_code |= - cvm::error("Error: a \"cartesian\" component was defined with all three axes disabled.\n", + cvmodule->error("Error: a \"cartesian\" component was defined with all three axes disabled.\n", COLVARS_INPUT_ERROR); } diff --git a/src/colvarcomp_gpath.cpp b/src/colvarcomp_gpath.cpp index f16d062db..aaf998f98 100644 --- a/src/colvarcomp_gpath.cpp +++ b/src/colvarcomp_gpath.cpp @@ -47,7 +47,7 @@ int colvar::CartesianBasedPath::init(std::string const &conf) if (get_keyval(conf, "refPositionsCol", reference_column, std::string(""))) { bool found = get_keyval(conf, "refPositionsColValue", reference_column_value, reference_column_value); if (found && reference_column_value == 0.0) { - return cvm::error("Error: refPositionsColValue, if provided, must be non-zero.\n", + return cvmodule->error("Error: refPositionsColValue, if provided, must be non-zero.\n", COLVARS_INPUT_ERROR); } } @@ -60,7 +60,7 @@ int colvar::CartesianBasedPath::init(std::string const &conf) std::string reference_position_filename; get_keyval(conf, reference_position_file_lookup.c_str(), reference_position_filename, std::string("")); std::vector reference_position(atoms->size()); - cvm::load_coords(reference_position_filename.c_str(), &reference_position, atoms, reference_column, reference_column_value); + cvmodule->load_coords(reference_position_filename.c_str(), &reference_position, atoms, reference_column, reference_column_value); reference_frames.push_back(reference_position); ++total_reference_frames; } else { @@ -88,7 +88,7 @@ int colvar::CartesianBasedPath::init(std::string const &conf) std::string reference_position_filename; get_keyval(conf, reference_position_file_lookup.c_str(), reference_position_filename, std::string("")); std::vector reference_fitting_position(tmp_fitting_atoms->size()); - cvm::load_coords(reference_position_filename.c_str(), &reference_fitting_position, tmp_fitting_atoms, reference_column, reference_column_value); + cvmodule->load_coords(reference_position_filename.c_str(), &reference_fitting_position, tmp_fitting_atoms, reference_column, reference_column_value); // setup the atom group for calculating tmp_atoms->enable(f_ag_center); tmp_atoms->enable(f_ag_rotate); @@ -172,7 +172,7 @@ void colvar::CartesianBasedPath::computeDistanceBetweenReferenceFrames(std::vect void colvar::CartesianBasedPath::apply_force(colvarvalue const &force) { - cvm::error("Error: using apply_force() in a component of type CartesianBasedPath, which is abstract.\n", + cvmodule->error("Error: using apply_force() in a component of type CartesianBasedPath, which is abstract.\n", COLVARS_BUG_ERROR); } @@ -191,24 +191,24 @@ int colvar::gspath::init(std::string const &conf) get_keyval(conf, "useSecondClosestFrame", use_second_closest_frame, true); if (use_second_closest_frame == true) { - cvm::log(std::string("Geometric path s(σ) will use the second closest frame to compute s_(m-1)\n")); + cvmodule->log(std::string("Geometric path s(σ) will use the second closest frame to compute s_(m-1)\n")); } else { - cvm::log(std::string("Geometric path s(σ) will use the neighbouring frame to compute s_(m-1)\n")); + cvmodule->log(std::string("Geometric path s(σ) will use the neighbouring frame to compute s_(m-1)\n")); } get_keyval(conf, "useThirdClosestFrame", use_third_closest_frame, false); if (use_third_closest_frame == true) { - cvm::log(std::string("Geometric path s(σ) will use the third closest frame to compute s_(m+1)\n")); + cvmodule->log(std::string("Geometric path s(σ) will use the third closest frame to compute s_(m+1)\n")); } else { - cvm::log(std::string("Geometric path s(σ) will use the neighbouring frame to compute s_(m+1)\n")); + cvmodule->log(std::string("Geometric path s(σ) will use the neighbouring frame to compute s_(m+1)\n")); } if (total_reference_frames < 2) { - return cvm::error("Error: you have specified " + cvm::to_str(total_reference_frames) + + return cvmodule->error("Error: you have specified " + cvm::to_str(total_reference_frames) + " reference frames, but gspath requires at least 2 frames.\n", COLVARS_INPUT_ERROR); } GeometricPathCV::GeometricPathBase::initialize(atoms->size(), cvm::atom_pos(), total_reference_frames, use_second_closest_frame, use_third_closest_frame); - cvm::log(std::string("Geometric pathCV(s) is initialized.\n")); - cvm::log(std::string("Geometric pathCV(s) loaded ") + cvm::to_str(reference_frames.size()) + std::string(" frames.\n")); + cvmodule->log(std::string("Geometric pathCV(s) is initialized.\n")); + cvmodule->log(std::string("Geometric pathCV(s) loaded ") + cvm::to_str(reference_frames.size()) + std::string(" frames.\n")); return error_code; } @@ -354,30 +354,30 @@ int colvar::gzpath::init(std::string const &conf) get_keyval(conf, "useSecondClosestFrame", use_second_closest_frame, true); if (use_second_closest_frame == true) { - cvm::log(std::string("Geometric path z(σ) will use the second closest frame to compute s_(m-1)\n")); + cvmodule->log(std::string("Geometric path z(σ) will use the second closest frame to compute s_(m-1)\n")); } else { - cvm::log(std::string("Geometric path z(σ) will use the neighbouring frame to compute s_(m-1)\n")); + cvmodule->log(std::string("Geometric path z(σ) will use the neighbouring frame to compute s_(m-1)\n")); } get_keyval(conf, "useThirdClosestFrame", use_third_closest_frame, false); if (use_third_closest_frame == true) { - cvm::log(std::string("Geometric path z(σ) will use the third closest frame to compute s_(m+1)\n")); + cvmodule->log(std::string("Geometric path z(σ) will use the third closest frame to compute s_(m+1)\n")); } else { - cvm::log(std::string("Geometric path z(σ) will use the neighbouring frame to compute s_(m+1)\n")); + cvmodule->log(std::string("Geometric path z(σ) will use the neighbouring frame to compute s_(m+1)\n")); } bool b_use_z_square = false; get_keyval(conf, "useZsquare", b_use_z_square, false); if (b_use_z_square == true) { - cvm::log(std::string("Geometric path z(σ) will use the square of distance from current frame to path compute z\n")); + cvmodule->log(std::string("Geometric path z(σ) will use the square of distance from current frame to path compute z\n")); } if (total_reference_frames < 2) { - return cvm::error("Error: you have specified " + cvm::to_str(total_reference_frames) + + return cvmodule->error("Error: you have specified " + cvm::to_str(total_reference_frames) + " reference frames, but gzpath requires at least 2 frames.\n", COLVARS_INPUT_ERROR); } GeometricPathCV::GeometricPathBase::initialize(atoms->size(), cvm::atom_pos(), total_reference_frames, use_second_closest_frame, use_third_closest_frame, b_use_z_square); // Logging - cvm::log(std::string("Geometric pathCV(z) is initialized.\n")); - cvm::log(std::string("Geometric pathCV(z) loaded ") + cvm::to_str(reference_frames.size()) + std::string(" frames.\n")); + cvmodule->log(std::string("Geometric pathCV(z) is initialized.\n")); + cvmodule->log(std::string("Geometric pathCV(z) loaded ") + cvm::to_str(reference_frames.size()) + std::string(" frames.\n")); return error_code; } @@ -535,8 +535,8 @@ int colvar::CVBasedPath::init(std::string const &conf) // Lookup all reference CV values std::string path_filename; get_keyval(conf, "pathFile", path_filename); - cvm::log(std::string("Reading path file: ") + path_filename + std::string("\n")); - auto &ifs_path = cvm::main()->proxy->input_stream(path_filename); + cvmodule->log(std::string("Reading path file: ") + path_filename + std::string("\n")); + auto &ifs_path = cvmodule->proxy->input_stream(path_filename); if (!ifs_path) { return COLVARS_INPUT_ERROR; } @@ -547,19 +547,19 @@ int colvar::CVBasedPath::init(std::string const &conf) std::vector fields; split_string(line, token, fields); size_t num_value_required = 0; - cvm::log(std::string("Reading reference frame ") + cvm::to_str(total_reference_frames + 1) + std::string("\n")); + cvmodule->log(std::string("Reading reference frame ") + cvm::to_str(total_reference_frames + 1) + std::string("\n")); for (size_t i_cv = 0; i_cv < tmp_cv.size(); ++i_cv) { const size_t value_size = tmp_cv[i_cv].size(); num_value_required += value_size; - cvm::log(std::string("Reading CV ") + cv[i_cv]->name + std::string(" with ") + cvm::to_str(value_size) + std::string(" value(s)\n")); + cvmodule->log(std::string("Reading CV ") + cv[i_cv]->name + std::string(" with ") + cvm::to_str(value_size) + std::string(" value(s)\n")); if (num_value_required <= fields.size()) { size_t start_index = num_value_required - value_size; for (size_t i = start_index; i < num_value_required; ++i) { tmp_cv[i_cv][i - start_index] = std::atof(fields[i].c_str()); - cvm::log(cvm::to_str(tmp_cv[i_cv][i - start_index])); + cvmodule->log(cvm::to_str(tmp_cv[i_cv][i - start_index])); } } else { - error_code = cvm::error("Error: incorrect format of path file.\n", COLVARS_INPUT_ERROR); + error_code = cvmodule->error("Error: incorrect format of path file.\n", COLVARS_INPUT_ERROR); return error_code; } } @@ -568,16 +568,16 @@ int colvar::CVBasedPath::init(std::string const &conf) ++total_reference_frames; } } - cvm::main()->proxy->close_input_stream(path_filename); + cvmodule->proxy->close_input_stream(path_filename); if (total_reference_frames <= 1) { - error_code = cvm::error( + error_code = cvmodule->error( "Error: there is only 1 or 0 reference frame, which doesn't constitute a path.\n", COLVARS_INPUT_ERROR); return error_code; } if (cv.size() == 0) { error_code = - cvm::error("Error: the CV " + name + " expects one or more nesting components.\n", + cvmodule->error("Error: the CV " + name + " expects one or more nesting components.\n", COLVARS_INPUT_ERROR); return error_code; } @@ -665,7 +665,7 @@ colvar::CVBasedPath::~CVBasedPath() { void colvar::CVBasedPath::apply_force(colvarvalue const &force) { - cvm::error("Error: using apply_force() in a component of type CVBasedPath, which is abstract.\n", + cvmodule->error("Error: using apply_force() in a component of type CVBasedPath, which is abstract.\n", COLVARS_BUG_ERROR); } @@ -703,22 +703,22 @@ int colvar::gspathCV::init(std::string const &conf) int error_code = CVBasedPath::init(conf); if (error_code != COLVARS_OK) return error_code; - cvm::log(std::string("Total number of frames: ") + cvm::to_str(total_reference_frames) + std::string("\n")); + cvmodule->log(std::string("Total number of frames: ") + cvm::to_str(total_reference_frames) + std::string("\n")); // Initialize variables for future calculation get_keyval(conf, "useSecondClosestFrame", use_second_closest_frame, true); if (use_second_closest_frame == true) { - cvm::log(std::string("Geometric path s(σ) will use the second closest frame to compute s_(m-1)\n")); + cvmodule->log(std::string("Geometric path s(σ) will use the second closest frame to compute s_(m-1)\n")); } else { - cvm::log(std::string("Geometric path s(σ) will use the neighbouring frame to compute s_(m-1)\n")); + cvmodule->log(std::string("Geometric path s(σ) will use the neighbouring frame to compute s_(m-1)\n")); } get_keyval(conf, "useThirdClosestFrame", use_third_closest_frame, false); if (use_third_closest_frame == true) { - cvm::log(std::string("Geometric path s(σ) will use the third closest frame to compute s_(m+1)\n")); + cvmodule->log(std::string("Geometric path s(σ) will use the third closest frame to compute s_(m+1)\n")); } else { - cvm::log(std::string("Geometric path s(σ) will use the neighbouring frame to compute s_(m+1)\n")); + cvmodule->log(std::string("Geometric path s(σ) will use the neighbouring frame to compute s_(m+1)\n")); } if (total_reference_frames < 2) { - return cvm::error("Error: you have specified " + cvm::to_str(total_reference_frames) + " reference frames, but gspathCV requires at least 2 frames.\n", COLVARS_INPUT_ERROR); + return cvmodule->error("Error: you have specified " + cvm::to_str(total_reference_frames) + " reference frames, but gspathCV requires at least 2 frames.\n", COLVARS_INPUT_ERROR); } GeometricPathCV::GeometricPathBase::initialize(cv.size(), ref_cv[0], total_reference_frames, use_second_closest_frame, use_third_closest_frame); return error_code; @@ -840,29 +840,29 @@ int colvar::gzpathCV::init(std::string const &conf) { int error_code = CVBasedPath::init(conf); if (error_code != COLVARS_OK) return error_code; - cvm::log(std::string("Total number of frames: ") + cvm::to_str(total_reference_frames) + std::string("\n")); + cvmodule->log(std::string("Total number of frames: ") + cvm::to_str(total_reference_frames) + std::string("\n")); // Initialize variables for future calculation M = cvm::real(total_reference_frames - 1); m = 1.0; get_keyval(conf, "useSecondClosestFrame", use_second_closest_frame, true); if (use_second_closest_frame == true) { - cvm::log(std::string("Geometric path z(σ) will use the second closest frame to compute s_(m-1)\n")); + cvmodule->log(std::string("Geometric path z(σ) will use the second closest frame to compute s_(m-1)\n")); } else { - cvm::log(std::string("Geometric path z(σ) will use the neighbouring frame to compute s_(m-1)\n")); + cvmodule->log(std::string("Geometric path z(σ) will use the neighbouring frame to compute s_(m-1)\n")); } get_keyval(conf, "useThirdClosestFrame", use_third_closest_frame, false); if (use_third_closest_frame == true) { - cvm::log(std::string("Geometric path z(σ) will use the third closest frame to compute s_(m+1)\n")); + cvmodule->log(std::string("Geometric path z(σ) will use the third closest frame to compute s_(m+1)\n")); } else { - cvm::log(std::string("Geometric path z(σ) will use the neighbouring frame to compute s_(m+1)\n")); + cvmodule->log(std::string("Geometric path z(σ) will use the neighbouring frame to compute s_(m+1)\n")); } bool b_use_z_square = false; get_keyval(conf, "useZsquare", b_use_z_square, false); if (b_use_z_square == true) { - cvm::log(std::string("Geometric path z(σ) will use the square of distance from current frame to path compute z\n")); + cvmodule->log(std::string("Geometric path z(σ) will use the square of distance from current frame to path compute z\n")); } if (total_reference_frames < 2) { - return cvm::error("Error: you have specified " + cvm::to_str(total_reference_frames) + + return cvmodule->error("Error: you have specified " + cvm::to_str(total_reference_frames) + " reference frames, but gzpathCV requires at least 2 frames.\n", COLVARS_INPUT_ERROR); } diff --git a/src/colvarcomp_neuralnetwork.cpp b/src/colvarcomp_neuralnetwork.cpp index 2e5d7429c..f82719ea2 100644 --- a/src/colvarcomp_neuralnetwork.cpp +++ b/src/colvarcomp_neuralnetwork.cpp @@ -39,7 +39,7 @@ int colvar::neuralNetwork::init(std::string const &conf) std::string weight_filename; get_keyval(conf, lookup_key.c_str(), weight_filename, std::string("")); weight_files.push_back(weight_filename); - cvm::log(std::string{"Will read layer["} + cvm::to_str(num_layers_weight + 1) + std::string{"] weights from "} + weight_filename + '\n'); + cvmodule->log(std::string{"Will read layer["} + cvm::to_str(num_layers_weight + 1) + std::string{"] weights from "} + weight_filename + '\n'); ++num_layers_weight; } else { has_weight_files = false; @@ -55,7 +55,7 @@ int colvar::neuralNetwork::init(std::string const &conf) std::string bias_filename; get_keyval(conf, lookup_key.c_str(), bias_filename, std::string("")); bias_files.push_back(bias_filename); - cvm::log(std::string{"Will read layer["} + cvm::to_str(num_layers_bias + 1) + std::string{"] biases from "} + bias_filename + '\n'); + cvmodule->log(std::string{"Will read layer["} + cvm::to_str(num_layers_bias + 1) + std::string{"] biases from "} + bias_filename + '\n'); ++num_layers_bias; } else { has_bias_files = false; @@ -74,18 +74,18 @@ int colvar::neuralNetwork::init(std::string const &conf) std::string function_name; get_keyval(conf, lookup_key.c_str(), function_name, std::string("")); if (activation_function_map.find(function_name) == activation_function_map.end()) { - return cvm::error("Unknown activation function name: \"" + function_name + "\".\n", + return cvmodule->error("Unknown activation function name: \"" + function_name + "\".\n", COLVARS_INPUT_ERROR); } activation_functions.push_back(std::make_pair(false, function_name)); - cvm::log(std::string{"The activation function for layer["} + cvm::to_str(num_activation_functions + 1) + std::string{"] is "} + function_name + '\n'); + cvmodule->log(std::string{"The activation function for layer["} + cvm::to_str(num_activation_functions + 1) + std::string{"] is "} + function_name + '\n'); ++num_activation_functions; #ifdef LEPTON } else if (key_lookup(conf, lookup_key_custom.c_str())) { std::string function_expression; get_keyval(conf, lookup_key_custom.c_str(), function_expression, std::string("")); activation_functions.push_back(std::make_pair(true, function_expression)); - cvm::log(std::string{"The custom activation function for layer["} + cvm::to_str(num_activation_functions + 1) + std::string{"] is "} + function_expression + '\n'); + cvmodule->log(std::string{"The custom activation function for layer["} + cvm::to_str(num_activation_functions + 1) + std::string{"] is "} + function_expression + '\n'); ++num_activation_functions; #endif } else { @@ -94,7 +94,7 @@ int colvar::neuralNetwork::init(std::string const &conf) } // expect the three numbers are equal if ((num_layers_weight != num_layers_bias) || (num_layers_bias != num_activation_functions)) { - return cvm::error( + return cvmodule->error( "Error: the numbers of weights, biases and activation functions do not match.\n", COLVARS_INPUT_ERROR); } @@ -108,9 +108,9 @@ int colvar::neuralNetwork::init(std::string const &conf) if (activation_functions[i_layer].first) { // use custom function as activation function try { - d = denseLayer(weight_files[i_layer], bias_files[i_layer], activation_functions[i_layer].second); + d = denseLayer(weight_files[i_layer], bias_files[i_layer], activation_functions[i_layer].second, cvmodule); } catch (std::exception &ex) { - return cvm::error("Error on initializing layer " + cvm::to_str(i_layer) + + return cvmodule->error("Error on initializing layer " + cvm::to_str(i_layer) + " (" + ex.what() + ")\n", COLVARS_INPUT_ERROR); } @@ -120,9 +120,9 @@ int colvar::neuralNetwork::init(std::string const &conf) const auto& f = activation_function_map[activation_functions[i_layer].second].first; const auto& df = activation_function_map[activation_functions[i_layer].second].second; try { - d = denseLayer(weight_files[i_layer], bias_files[i_layer], f, df); + d = denseLayer(weight_files[i_layer], bias_files[i_layer], f, df, cvmodule); } catch (std::exception &ex) { - return cvm::error("Error on initializing layer " + cvm::to_str(i_layer) + + return cvmodule->error("Error on initializing layer " + cvm::to_str(i_layer) + " (" + ex.what() + ")\n", COLVARS_INPUT_ERROR); } @@ -133,16 +133,16 @@ int colvar::neuralNetwork::init(std::string const &conf) if (nn->addDenseLayer(d)) { if (cvm::debug()) { // show information about the neural network - cvm::log("Layer " + cvm::to_str(i_layer) + " : has " + cvm::to_str(d.getInputSize()) + " input nodes and " + cvm::to_str(d.getOutputSize()) + " output nodes.\n"); + cvmodule->log("Layer " + cvm::to_str(i_layer) + " : has " + cvm::to_str(d.getInputSize()) + " input nodes and " + cvm::to_str(d.getOutputSize()) + " output nodes.\n"); for (size_t i_output = 0; i_output < d.getOutputSize(); ++i_output) { for (size_t j_input = 0; j_input < d.getInputSize(); ++j_input) { - cvm::log(" weights[" + cvm::to_str(i_output) + "][" + cvm::to_str(j_input) + "] = " + cvm::to_str(d.getWeight(i_output, j_input))); + cvmodule->log(" weights[" + cvm::to_str(i_output) + "][" + cvm::to_str(j_input) + "] = " + cvm::to_str(d.getWeight(i_output, j_input))); } - cvm::log(" biases[" + cvm::to_str(i_output) + "] = " + cvm::to_str(d.getBias(i_output)) + "\n"); + cvmodule->log(" biases[" + cvm::to_str(i_output) + "] = " + cvm::to_str(d.getBias(i_output)) + "\n"); } } } else { - return cvm::error("Error: error on adding a new dense layer.\n", COLVARS_INPUT_ERROR); + return cvmodule->error("Error: error on adding a new dense layer.\n", COLVARS_INPUT_ERROR); } } nn->input().resize(cv.size()); @@ -161,7 +161,7 @@ void colvar::neuralNetwork::calc_value() { if (current_cv_value.type() == colvarvalue::type_scalar) { nn->input()[i_cv] = cv[i_cv]->sup_coeff * (cvm::pow(current_cv_value.real_value, cv[i_cv]->sup_np)); } else { - cvm::error("Error: using of non-scaler component.\n"); + cvmodule->error("Error: using of non-scaler component.\n"); return; } } diff --git a/src/colvarcomp_protein.cpp b/src/colvarcomp_protein.cpp index d5b37ff9d..e68d3951f 100644 --- a/src/colvarcomp_protein.cpp +++ b/src/colvarcomp_protein.cpp @@ -20,7 +20,7 @@ colvar::alpha_angles::alpha_angles() set_function_type("alpha"); enable(f_cvc_explicit_gradient); x.type(colvarvalue::type_scalar); - colvarproxy *proxy = cvm::main()->proxy; + colvarproxy *proxy = cvmodule->proxy; r0 = proxy->angstrom_to_internal(3.3); } @@ -53,11 +53,11 @@ int colvar::alpha_angles::init(std::string const &conf) } } } else { - return cvm::error("Error: no residues defined in \"residueRange\".\n", COLVARS_INPUT_ERROR); + return cvmodule->error("Error: no residues defined in \"residueRange\".\n", COLVARS_INPUT_ERROR); } if (residues.size() < 5) { - return cvm::error("Error: not enough residues defined in \"residueRange\".\n", COLVARS_INPUT_ERROR); + return cvmodule->error("Error: not enough residues defined in \"residueRange\".\n", COLVARS_INPUT_ERROR); } get_keyval(conf, "psfSegID", segment_id, std::string("MAIN")); @@ -80,11 +80,11 @@ int colvar::alpha_angles::init(std::string const &conf) int nn = group_N.size(); int no = group_O.size(); if ((nn != 0 || no != 0) && (nn != no)) { - return cvm::error("Error: If either is provided, atom groups " + prefix + "N and " + prefix + "O must have the same number of atoms.", + return cvmodule->error("Error: If either is provided, atom groups " + prefix + "N and " + prefix + "O must have the same number of atoms.", COLVARS_INPUT_ERROR); } if (nn != 0 && na != 0 && nn != na) { - return cvm::error("Error: If both are provided, atom groups " + prefix + "N and " + prefix + "CA must have the same number of atoms.", + return cvmodule->error("Error: If both are provided, atom groups " + prefix + "N and " + prefix + "CA must have the same number of atoms.", COLVARS_INPUT_ERROR); } } @@ -95,7 +95,7 @@ int colvar::alpha_angles::init(std::string const &conf) get_keyval(conf, "hBondCoeff", hb_coeff, hb_coeff); if ((hb_coeff < 0.0) || (hb_coeff > 1.0)) { - return cvm::error("Error: hBondCoeff must be defined between 0 and 1.\n", COLVARS_INPUT_ERROR); + return cvmodule->error("Error: hBondCoeff must be defined between 0 and 1.\n", COLVARS_INPUT_ERROR); } @@ -105,7 +105,7 @@ int colvar::alpha_angles::init(std::string const &conf) if (hb_coeff < 1.0) { if (b_use_index_groups) { if (group_CA.size() < 5) { - return cvm::error("Not enough atoms (" + cvm::to_str(group_CA.size()) + ") in index group \"" + prefix + "CA\"", + return cvmodule->error("Not enough atoms (" + cvm::to_str(group_CA.size()) + ") in index group \"" + prefix + "CA\"", COLVARS_INPUT_ERROR); } for (size_t i = 0; i < group_CA.size()-2; i++) { @@ -118,7 +118,7 @@ int colvar::alpha_angles::init(std::string const &conf) register_atom_group(theta.back()->atom_groups[2]); } } else { - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = cvmodule->proxy; for (size_t i = 0; i < residues.size()-2; i++) { theta.push_back( new colvar::angle( @@ -132,7 +132,7 @@ int colvar::alpha_angles::init(std::string const &conf) } } else { - cvm::log("The hBondCoeff specified will disable the Calpha-Calpha-Calpha angle terms.\n"); + cvmodule->log("The hBondCoeff specified will disable the Calpha-Calpha-Calpha angle terms.\n"); } { @@ -141,10 +141,10 @@ int colvar::alpha_angles::init(std::string const &conf) get_keyval(conf, "hBondExpDenom", ed, ed); if (hb_coeff > 0.0) { - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = cvmodule->proxy; if (b_use_index_groups) { if (group_N.size() < 5) { - return cvm::error("Not enough atoms (" + cvm::to_str(group_N.size()) + ") in index group \"" + prefix + "N\"", + return cvmodule->error("Not enough atoms (" + cvm::to_str(group_N.size()) + ") in index group \"" + prefix + "N\"", COLVARS_INPUT_ERROR); } for (size_t i = 0; i < group_N.size()-4; i++) { @@ -166,7 +166,7 @@ int colvar::alpha_angles::init(std::string const &conf) } } } else { - cvm::log("The hBondCoeff specified will disable the hydrogen bond terms.\n"); + cvmodule->log("The hBondCoeff specified will disable the hydrogen bond terms.\n"); } } @@ -209,7 +209,7 @@ void colvar::alpha_angles::calc_value() x.real_value += theta_norm * f; if (cvm::debug()) - cvm::log("Calpha-Calpha angle no. "+cvm::to_str(i+1)+" in \""+ + cvmodule->log("Calpha-Calpha angle no. "+cvm::to_str(i+1)+" in \""+ this->name+"\" has a value of "+ (cvm::to_str((theta[i])->value().real_value))+ " degrees, f = "+cvm::to_str(f)+".\n"); @@ -225,7 +225,7 @@ void colvar::alpha_angles::calc_value() (hb[i])->calc_value(); x.real_value += hb_norm * (hb[i])->value().real_value; if (cvm::debug()) - cvm::log("Hydrogen bond no. "+cvm::to_str(i+1)+" in \""+ + cvmodule->log("Hydrogen bond no. "+cvm::to_str(i+1)+" in \""+ this->name+"\" has a value of "+ (cvm::to_str((hb[i])->value().real_value))+".\n"); } @@ -352,7 +352,7 @@ int colvar::dihedPC::init(std::string const &conf) int error_code = cvc::init(conf); if (cvm::debug()) - cvm::log("Initializing dihedral PC object.\n"); + cvmodule->log("Initializing dihedral PC object.\n"); bool b_use_index_groups = false; std::string segment_id; @@ -376,7 +376,7 @@ int colvar::dihedPC::init(std::string const &conf) } } } else { - return cvm::error("Error: no residues defined in \"residueRange\".\n", COLVARS_INPUT_ERROR); + return cvmodule->error("Error: no residues defined in \"residueRange\".\n", COLVARS_INPUT_ERROR); } n_residues = residues.size(); get_keyval(conf, "psfSegID", segment_id, std::string("MAIN")); @@ -399,14 +399,14 @@ int colvar::dihedPC::init(std::string const &conf) int nn = group_N.size(); int nc = group_C.size(); if ((nn != na || na != nc)) { - return cvm::error("Error: atom groups " + prefix + "N, " + prefix + "CA, and " + prefix + + return cvmodule->error("Error: atom groups " + prefix + "N, " + prefix + "CA, and " + prefix + "C must have the same number of atoms.", COLVARS_INPUT_ERROR); } n_residues = nn; } if (n_residues < 2) { error_code |= - cvm::error("Error: dihedralPC requires at least two residues.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: dihedralPC requires at least two residues.\n", COLVARS_INPUT_ERROR); } std::string const &sid = segment_id; @@ -418,11 +418,11 @@ int colvar::dihedPC::init(std::string const &conf) get_keyval(conf, "vectorNumber", vecNumber, 0); if (vecNumber < 1) { error_code |= - cvm::error("A positive value of vectorNumber is required.", COLVARS_INPUT_ERROR); + cvmodule->error("A positive value of vectorNumber is required.", COLVARS_INPUT_ERROR); } std::istream &vecFile = - cvm::main()->proxy->input_stream(vecFileName, + cvmodule->proxy->input_stream(vecFileName, "dihedral PCA vector file"); if (!vecFile) { return COLVARS_INPUT_ERROR; @@ -448,7 +448,7 @@ int colvar::dihedPC::init(std::string const &conf) vecFile.ignore(999999, '\n'); if (!vecFile.good()) { - cvm::error("Error reading dihedral PCA vector file " + vecFileName); + cvmodule->error("Error reading dihedral PCA vector file " + vecFileName); } std::string line; @@ -461,19 +461,19 @@ int colvar::dihedPC::init(std::string const &conf) } } */ - cvm::main()->proxy->close_input_stream(vecFileName); + cvmodule->proxy->close_input_stream(vecFileName); } else { get_keyval(conf, "vector", coeffs, coeffs); } if ( coeffs.size() != 4 * (n_residues - 1)) { - error_code |= cvm::error("Error: wrong number of coefficients: " + cvm::to_str(coeffs.size()) + + error_code |= cvmodule->error("Error: wrong number of coefficients: " + cvm::to_str(coeffs.size()) + ". Expected " + cvm::to_str(4 * (n_residues - 1)) + " (4 coeffs per residue, minus one residue).\n", COLVARS_INPUT_ERROR); } - colvarproxy* const p = cvm::main()->proxy; + colvarproxy* const p = cvmodule->proxy; for (size_t i = 0; i < n_residues-1; i++) { // Psi if (b_use_index_groups) { @@ -489,8 +489,8 @@ int colvar::dihedPC::init(std::string const &conf) cvm::atom_group::init_atom_from_proxy(p,r[i ], "C", sid), cvm::atom_group::init_atom_from_proxy(p,r[i+1], "N", sid))); } - if (cvm::get_error()) { - return cvm::get_error(); + if (cvmodule->get_error()) { + return cvmodule->get_error(); } register_atom_group(theta.back()->atom_groups[0]); register_atom_group(theta.back()->atom_groups[1]); @@ -509,8 +509,8 @@ int colvar::dihedPC::init(std::string const &conf) cvm::atom_group::init_atom_from_proxy(p,r[i+1], "CA", sid), cvm::atom_group::init_atom_from_proxy(p,r[i+1], "C", sid))); } - if (cvm::get_error()) { - return cvm::get_error(); + if (cvmodule->get_error()) { + return cvmodule->get_error(); } register_atom_group(theta.back()->atom_groups[0]); register_atom_group(theta.back()->atom_groups[1]); @@ -519,7 +519,7 @@ int colvar::dihedPC::init(std::string const &conf) } if (cvm::debug()) - cvm::log("Done initializing dihedPC object.\n"); + cvmodule->log("Done initializing dihedPC object.\n"); return error_code; } diff --git a/src/colvarcomp_rotations.cpp b/src/colvarcomp_rotations.cpp index 72b12bd8d..7c2b5b2b6 100644 --- a/src/colvarcomp_rotations.cpp +++ b/src/colvarcomp_rotations.cpp @@ -50,9 +50,9 @@ int colvar::orientation::init(std::string const &conf) ref_pos.reserve(atoms->size()); if (get_keyval(conf, "refPositions", ref_pos, ref_pos)) { - cvm::log("Using reference positions from input file.\n"); + cvmodule->log("Using reference positions from input file.\n"); if (ref_pos.size() != atoms->size()) { - return cvm::error("Error: reference positions do not " + return cvmodule->error("Error: reference positions do not " "match the number of requested atoms.\n", COLVARS_INPUT_ERROR); } } @@ -67,13 +67,13 @@ int colvar::orientation::init(std::string const &conf) // use PDB flags if column is provided bool found = get_keyval(conf, "refPositionsColValue", file_col_value, 0.0); if (found && file_col_value==0.0) { - return cvm::error("Error: refPositionsColValue, " + return cvmodule->error("Error: refPositionsColValue, " "if provided, must be non-zero.\n", COLVARS_INPUT_ERROR); } } ref_pos.resize(atoms->size()); - error_code |= cvm::load_coords(file_name.c_str(), &ref_pos, atoms, + error_code |= cvmodule->load_coords(file_name.c_str(), &ref_pos, atoms, file_col, file_col_value); } } @@ -81,7 +81,7 @@ int colvar::orientation::init(std::string const &conf) if (error_code != COLVARS_OK) return error_code; if (!ref_pos.size()) { - return cvm::error("Error: must define a set of " + return cvmodule->error("Error: must define a set of " "reference coordinates.\n", COLVARS_INPUT_ERROR); } @@ -91,7 +91,7 @@ int colvar::orientation::init(std::string const &conf) ref_cog += ref_pos[i]; } ref_cog /= cvm::real(ref_pos.size()); - cvm::log("Centering the reference coordinates on the origin by subtracting " + cvmodule->log("Centering the reference coordinates on the origin by subtracting " "the center of geometry at "+ cvm::to_str(-1.0 * ref_cog)+"; it is " "assumed that each atom is the closest " @@ -299,7 +299,7 @@ int colvar::tilt::init(std::string const &conf) get_keyval(conf, "axis", axis, cvm::rvector(0.0, 0.0, 1.0)); if (axis.norm2() != 1.0) { axis /= axis.norm(); - cvm::log("Normalizing rotation axis to "+cvm::to_str(axis)+".\n"); + cvmodule->log("Normalizing rotation axis to "+cvm::to_str(axis)+".\n"); } return error_code; diff --git a/src/colvarcomp_torchann.cpp b/src/colvarcomp_torchann.cpp index b40b32a38..f4f580a0e 100644 --- a/src/colvarcomp_torchann.cpp +++ b/src/colvarcomp_torchann.cpp @@ -36,15 +36,15 @@ int colvar::torchANN::init(std::string const &conf) { try { nn = torch::jit::load(model_file); nn.to(torch::kCPU); - cvm::log("torch model loaded.") ; + cvmodule->log("torch model loaded.") ; } catch (const std::exception & e) { - return cvm::error("Error: couldn't load libtorch model (see below).\n" + cvm::to_str(e.what()), + return cvmodule->error("Error: couldn't load libtorch model (see below).\n" + cvm::to_str(e.what()), COLVARS_INPUT_ERROR); } auto const legacy_keyword = get_keyval(conf, "m_output_index", m_output_index, m_output_index); if (legacy_keyword) { - cvm::log("Warning: m_output_index is a deprecated keyword, please use output_component instead.\n"); + cvmodule->log("Warning: m_output_index is a deprecated keyword, please use output_component instead.\n"); } get_keyval(conf, "output_component", m_output_index, m_output_index); @@ -61,7 +61,7 @@ int colvar::torchANN::init(std::string const &conf) { if (i_cv < cv.size() - 1) cvc_indices[i_cv+1] = num_inputs; } - cvm::log("Input dimension of model: " + cvm::to_str(num_inputs)); + cvmodule->log("Input dimension of model: " + cvm::to_str(num_inputs)); // initialize the input tensor auto options = torch::TensorOptions().dtype(torch::kFloat32).requires_grad(true); @@ -72,19 +72,19 @@ int colvar::torchANN::init(std::string const &conf) { try { nn.to(torch::kCUDA); } catch(const std::exception & e) { - cvm::error("Failed to move model to GPU."); + cvmodule->error("Failed to move model to GPU."); use_gpu = false; } } else { use_gpu = false; - cvm::log("GPU not available."); + cvmodule->log("GPU not available."); } } if (use_gpu) { options = options.device(torch::kCUDA); if (use_double_input) { - cvm::log("Data type reset to Float for GPU computation!"); + cvmodule->log("Data type reset to Float for GPU computation!"); use_double_input = false; } } @@ -93,9 +93,9 @@ int colvar::torchANN::init(std::string const &conf) { if (use_double_input) { // set type to double options = options.dtype(torch::kFloat64); nn.to(torch::kFloat64); - cvm::log("Model's dtype: kFloat64."); + cvmodule->log("Model's dtype: kFloat64."); } else { - cvm::log("Model's dtype: kFloat32."); + cvmodule->log("Model's dtype: kFloat32."); } input_tensor = torch::zeros({1,(long int) num_inputs}, options); @@ -103,9 +103,9 @@ int colvar::torchANN::init(std::string const &conf) { try { // test the model std::vector inputs={input_tensor}; nn_outputs = nn.forward(inputs).toTensor()[0][m_output_index]; - cvm::log("Evaluating model with zero tensor succeeded."); + cvmodule->log("Evaluating model with zero tensor succeeded."); } catch (const std::exception & e) { - error_code |= cvm::error("Error: evaluating model with zero tensor failed (see below).\n" + + error_code |= cvmodule->error("Error: evaluating model with zero tensor failed (see below).\n" + cvm::to_str(e.what()), COLVARS_INPUT_ERROR); } @@ -222,7 +222,7 @@ colvar::torchANN::~torchANN() {} int colvar::torchANN::init(std::string const &conf) { - return cvm::error( + return cvmodule->error( "torchANN requires the libtorch library, but it is not enabled during compilation.\n" "Please refer to the Compilation Notes section of the Colvars manual for more " "information.\n", diff --git a/src/colvarcomp_volmaps.cpp b/src/colvarcomp_volmaps.cpp index 96bcaef55..b6acb65de 100644 --- a/src/colvarcomp_volmaps.cpp +++ b/src/colvarcomp_volmaps.cpp @@ -33,7 +33,7 @@ int colvar::map_total::init(std::string const &conf) if ((volmap_name.size() > 0) && (volmap_id >= 0)) { error_code |= - cvm::error("Error: mapName and mapID are mutually exclusive.\n", COLVARS_INPUT_ERROR); + cvm::error_static("Error: mapName and mapID are mutually exclusive.\n", COLVARS_INPUT_ERROR); } // Parse optional group @@ -62,12 +62,12 @@ int colvar::map_total::init(std::string const &conf) if (get_keyval(conf, "atomWeights", atom_weights, atom_weights)) { if (!atoms) { - error_code |= cvm::error("Error: weights can only be assigned when atoms " + error_code |= cvm::error_static("Error: weights can only be assigned when atoms " "are selected explicitly in Colvars.\n", COLVARS_INPUT_ERROR); } else { if (atoms->size() != atom_weights.size()) { - error_code |= cvm::error("Error: if defined, the number of weights ("+ + error_code |= cvm::error_static("Error: if defined, the number of weights ("+ cvm::to_str(atom_weights.size())+ ") must equal the number of atoms ("+ cvm::to_str(atoms->size())+ diff --git a/src/colvardeps.cpp b/src/colvardeps.cpp index 772921c98..5860f03f4 100644 --- a/src/colvardeps.cpp +++ b/src/colvardeps.cpp @@ -13,7 +13,15 @@ #include "colvardeps.h" -colvardeps::colvardeps() {} +// Temporary cheat using global static pointer +colvardeps::colvardeps() + : colvarparse(cvm::main()) +{} + + +colvardeps::colvardeps(colvarmodule *cvmodulein) + : colvarparse(cvmodulein) +{} colvardeps::~colvardeps() { @@ -21,9 +29,9 @@ colvardeps::~colvardeps() { // Protest if we are deleting an object while a parent object may still depend on it if (parents.size()) { - cvm::log("Warning: destroying \"" + description + "\" before its parents objects:"); + cvmodule->log("Warning: destroying \"" + description + "\" before its parents objects:"); for (i=0; idescription + "\n"); + cvmodule->log(parents[i]->description + "\n"); } } @@ -46,22 +54,22 @@ void colvardeps::free_children_deps() { // Cannot be in the base class destructor because it needs the derived class features() size_t i,j,fid; - if (cvm::debug()) cvm::log("DEPS: freeing children deps for " + description + "\n"); + if (cvm::debug()) cvmodule->log("DEPS: freeing children deps for " + description + "\n"); - cvm::increase_depth(); + cvmodule->increase_depth(); for (fid = 0; fid < feature_states.size(); fid++) { if (is_enabled(fid)) { for (i=0; irequires_children.size(); i++) { int g = features()[fid]->requires_children[i]; for (j=0; jlog("DEPS: dereferencing children's " + children[j]->features()[g]->description + "\n"); children[j]->decr_ref_count(g); } } } } - cvm::decrease_depth(); + cvmodule->decrease_depth(); } @@ -70,20 +78,20 @@ void colvardeps::free_children_deps() { void colvardeps::restore_children_deps() { size_t i,j,fid; - cvm::increase_depth(); + cvmodule->increase_depth(); for (fid = 0; fid < feature_states.size(); fid++) { if (is_enabled(fid)) { for (i=0; irequires_children.size(); i++) { int g = features()[fid]->requires_children[i]; for (j=0; jlog("DEPS: re-enabling children's " + children[j]->features()[g]->description + "\n"); children[j]->enable(g, false, false); } } } } - cvm::decrease_depth(); + cvmodule->decrease_depth(); } @@ -109,7 +117,7 @@ bool colvardeps::get_keyval_feature(colvarparse *cvp, colvarparse::Parse_Mode const parse_mode) { if (!is_user(feature_id)) { - cvm::error("Cannot set feature \"" + features()[feature_id]->description + "\" from user input in \"" + description + "\".\n"); + cvmodule->error("Cannot set feature \"" + features()[feature_id]->description + "\" from user input in \"" + description + "\".\n"); return false; } bool value; @@ -131,7 +139,7 @@ int colvardeps::enable(int feature_id, bool ok; if (feature_id < 0 || feature_id >= int(features().size())) { - cvm::error("Error: colvardeps::enable() called with invalid feature_id " + cvm::to_str(feature_id) + "\n"); + cvmodule->error("Error: colvardeps::enable() called with invalid feature_id " + cvm::to_str(feature_id) + "\n"); return COLVARS_ERROR; } feature *f = features()[feature_id]; @@ -141,7 +149,7 @@ int colvardeps::enable(int feature_id, // then error is set to true if (cvm::debug()) { - cvm::log("DEPS: " + description + + cvmodule->log("DEPS: " + description + (dry_run ? " testing " : " enabling ") + (error ? " [error] " : "") + "\"" + f->description +"\"\n"); } @@ -152,7 +160,7 @@ int colvardeps::enable(int feature_id, // as requirement is enabled fs->ref_count++; if (cvm::debug()) - cvm::log("DEPS: bumping ref_count to " + cvm::to_str(fs->ref_count) + "\n"); + cvmodule->log("DEPS: bumping ref_count to " + cvm::to_str(fs->ref_count) + "\n"); } // Do not try to further resolve deps return COLVARS_OK; @@ -164,10 +172,10 @@ int colvardeps::enable(int feature_id, if (!fs->available) { if (!dry_run || error) { if (toplevel) { - cvm::error("Error: " + feature_type_descr + " feature unavailable: \"" + cvmodule->error("Error: " + feature_type_descr + " feature unavailable: \"" + f->description + "\" in " + description + ".\n"); } else { - cvm::log(feature_type_descr + " feature unavailable: \"" + cvmodule->log(feature_type_descr + " feature unavailable: \"" + f->description + "\" in " + description + ".\n"); } } @@ -176,10 +184,10 @@ int colvardeps::enable(int feature_id, if (!toplevel && !is_dynamic(feature_id)) { if (!dry_run || error) { - cvm::log(feature_type_descr + " feature \"" + f->description + cvmodule->log(feature_type_descr + " feature \"" + f->description + "\" cannot be enabled automatically in " + description + ".\n"); if (is_user(feature_id)) { - cvm::log("Try setting it manually.\n"); + cvmodule->log("Try setting it manually.\n"); } } return COLVARS_ERROR; @@ -190,13 +198,13 @@ int colvardeps::enable(int feature_id, for (i=0; irequires_exclude.size(); i++) { feature *g = features()[f->requires_exclude[i]]; if (cvm::debug()) - cvm::log(f->description + " requires exclude " + g->description + "\n"); + cvmodule->log(f->description + " requires exclude " + g->description + "\n"); if (is_enabled(f->requires_exclude[i])) { if (!dry_run || error) { - cvm::log("Feature \"" + f->description + "\" is incompatible with \"" + cvmodule->log("Feature \"" + f->description + "\" is incompatible with \"" + g->description + "\" in " + description + ".\n"); if (toplevel) { - cvm::error("Error: Failed dependency in " + description + ".\n"); + cvmodule->error("Error: Failed dependency in " + description + ".\n"); } } return COLVARS_ERROR; @@ -206,17 +214,17 @@ int colvardeps::enable(int feature_id, // 2) solve internal deps (self) for (i=0; irequires_self.size(); i++) { if (cvm::debug()) - cvm::log(f->description + " requires self " + features()[f->requires_self[i]]->description + "\n"); + cvmodule->log(f->description + " requires self " + features()[f->requires_self[i]]->description + "\n"); res = enable(f->requires_self[i], dry_run, false, error); if (res != COLVARS_OK) { if (!dry_run || error) { if (toplevel) { - cvm::log("Cannot enable \"" + f->description + "\" in " + description + "\n"); + cvmodule->log("Cannot enable \"" + f->description + "\" in " + description + "\n"); } else { - cvm::log("...required by \"" + f->description + "\" in " + description + "\n"); + cvmodule->log("...required by \"" + f->description + "\" in " + description + "\n"); } if (toplevel) { - cvm::error("Error: Failed dependency in " + description + ".\n"); + cvmodule->error("Error: Failed dependency in " + description + ".\n"); } } return res; @@ -231,7 +239,7 @@ int colvardeps::enable(int feature_id, for (j=0; jrequires_alt[i].size(); j++) { int g = f->requires_alt[i][j]; if (cvm::debug()) - cvm::log(f->description + " requires alt " + features()[g]->description + "\n"); + cvmodule->log(f->description + " requires alt " + features()[g]->description + "\n"); res = enable(g, true, false, error); // see if available if (res == COLVARS_OK) { ok = true; @@ -245,19 +253,19 @@ int colvardeps::enable(int feature_id, } if (!ok) { if (!dry_run) { - cvm::log("\"" + f->description + "\" in " + description + cvmodule->log("\"" + f->description + "\" in " + description + " requires one of the following features, none of which can be enabled:\n"); - cvm::log("-----------------------------------------\n"); - cvm::increase_depth(); + cvmodule->log("-----------------------------------------\n"); + cvmodule->increase_depth(); for (j=0; jrequires_alt[i].size(); j++) { int g = f->requires_alt[i][j]; - cvm::log(cvm::to_str(j+1) + ". " + features()[g]->description + "\n"); + cvmodule->log(cvm::to_str(j+1) + ". " + features()[g]->description + "\n"); enable(g, false, false, true); // Just for printing error output } - cvm::decrease_depth(); - cvm::log("-----------------------------------------\n"); + cvmodule->decrease_depth(); + cvmodule->log("-----------------------------------------\n"); if (toplevel) { - cvm::error("Error: Failed dependency in " + description + ".\n"); + cvmodule->error("Error: Failed dependency in " + description + ".\n"); } } return COLVARS_ERROR; @@ -267,7 +275,7 @@ int colvardeps::enable(int feature_id, // 4) solve deps in children // if the object is inactive, we solve but do not enable: will be enabled // when the object becomes active - cvm::increase_depth(); + cvmodule->increase_depth(); for (i=0; irequires_children.size(); i++) { int g = f->requires_children[i]; for (j=0; jdescription + "\" in " + description + "\n"); + cvmodule->log("Cannot enable \"" + f->description + "\" in " + description + "\n"); } else { - cvm::log("...required by \"" + f->description + "\" in " + description + "\n"); + cvmodule->log("...required by \"" + f->description + "\" in " + description + "\n"); } if (toplevel) { - cvm::error("Error: Failed dependency in " + description + ".\n"); + cvmodule->error("Error: Failed dependency in " + description + ".\n"); } } return res; } } } - cvm::decrease_depth(); + cvmodule->decrease_depth(); // Actually enable feature only once everything checks out if (!dry_run) { @@ -300,7 +308,7 @@ int colvardeps::enable(int feature_id, } do_feature_side_effects(feature_id); if (cvm::debug()) - cvm::log("DEPS: feature \"" + f->description + "\" in " + cvmodule->log("DEPS: feature \"" + f->description + "\" in " + description + " enabled, ref_count = 1." + "\n"); } return COLVARS_OK; @@ -312,7 +320,7 @@ int colvardeps::disable(int feature_id) { feature *f = features()[feature_id]; feature_state *fs = &feature_states[feature_id]; - if (cvm::debug()) cvm::log("DEPS: disabling feature \"" + if (cvm::debug()) cvmodule->log("DEPS: disabling feature \"" + f->description + "\" in " + description + "\n"); if (fs->enabled == false) { @@ -320,7 +328,7 @@ int colvardeps::disable(int feature_id) { } if (fs->ref_count > 1) { - cvm::error("Error: cannot disable feature \"" + f->description + cvmodule->error("Error: cannot disable feature \"" + f->description + "\" in " + description + " because of " + cvm::to_str(fs->ref_count-1) + " remaining references.\n" ); return COLVARS_ERROR; @@ -328,14 +336,14 @@ int colvardeps::disable(int feature_id) { // internal deps (self) for (i=0; irequires_self.size(); i++) { - if (cvm::debug()) cvm::log("DEPS: dereferencing self " + if (cvm::debug()) cvmodule->log("DEPS: dereferencing self " + features()[f->requires_self[i]]->description + "\n"); decr_ref_count(f->requires_self[i]); } // alternates for (i=0; ialternate_refs.size(); i++) { - if (cvm::debug()) cvm::log("DEPS: dereferencing alt " + if (cvm::debug()) cvmodule->log("DEPS: dereferencing alt " + features()[fs->alternate_refs[i]]->description + "\n"); decr_ref_count(fs->alternate_refs[i]); } @@ -348,16 +356,16 @@ int colvardeps::disable(int feature_id) { // (or never referenced if feature was enabled while the object // was inactive) if (is_enabled()) { - cvm::increase_depth(); + cvmodule->increase_depth(); for (i=0; irequires_children.size(); i++) { int g = f->requires_children[i]; for (j=0; jlog("DEPS: dereferencing children's " + children[j]->features()[g]->description + "\n"); children[j]->decr_ref_count(g); } } - cvm::decrease_depth(); + cvmodule->decrease_depth(); } fs->enabled = false; @@ -375,11 +383,11 @@ int colvardeps::decr_ref_count(int feature_id) { feature *f = features()[feature_id]; if (cvm::debug()) - cvm::log("DEPS: decreasing reference count of \"" + f->description + cvmodule->log("DEPS: decreasing reference count of \"" + f->description + "\" in " + description + ".\n"); if (rc <= 0) { - cvm::error("Error: cannot decrease reference count of feature \"" + f->description + cvmodule->error("Error: cannot decrease reference count of feature \"" + f->description + "\" in " + description + ", which is " + cvm::to_str(rc) + ".\n"); return COLVARS_ERROR; } @@ -388,7 +396,7 @@ int colvardeps::decr_ref_count(int feature_id) { if (rc == 0 && f->is_dynamic()) { // we can auto-disable this feature if (cvm::debug()) - cvm::log("DEPS will now auto-disable dynamic feature \"" + f->description + cvmodule->log("DEPS will now auto-disable dynamic feature \"" + f->description + "\" in " + description + ".\n"); disable(feature_id); } @@ -446,20 +454,20 @@ void colvardeps::require_feature_alt(int f, int g, int h, int i, int j) { void colvardeps::print_state() { size_t i; - cvm::log("Features of \"" + description + "\" (refcount)\n"); + cvmodule->log("Features of \"" + description + "\" (refcount)\n"); for (i = 0; i < feature_states.size(); i++) { std::string onoff = is_enabled(i) ? "ON " : " "; // Only display refcount if non-zero for less clutter std::string refcount = feature_states[i].ref_count != 0 ? " (" + cvm::to_str(feature_states[i].ref_count) + ") " : ""; - cvm::log("- " + onoff + features()[i]->description + refcount + "\n"); + cvmodule->log("- " + onoff + features()[i]->description + refcount + "\n"); } - cvm::increase_depth(); + cvmodule->increase_depth(); for (i=0; ilog("* child " + cvm::to_str(i+1)); children[i]->print_state(); } - cvm::decrease_depth(); + cvmodule->decrease_depth(); } @@ -472,18 +480,18 @@ void colvardeps::add_child(colvardeps *child) { // in the new child size_t i, fid; - cvm::increase_depth(); + cvmodule->increase_depth(); for (fid = 0; fid < feature_states.size(); fid++) { if (is_enabled(fid)) { for (i=0; irequires_children.size(); i++) { int g = features()[fid]->requires_children[i]; - if (cvm::debug()) cvm::log("DEPS: re-enabling children's " + if (cvm::debug()) cvmodule->log("DEPS: re-enabling children's " + child->features()[g]->description + "\n"); child->enable(g, false, false); } } } - cvm::decrease_depth(); + cvmodule->decrease_depth(); } @@ -499,7 +507,7 @@ void colvardeps::remove_child(colvardeps *child) { } } if (!found) { - cvm::error("Trying to remove missing child reference from " + description + "\n"); + cvmodule->error("Trying to remove missing child reference from " + description + "\n"); } found = false; for (i = child->parents.size()-1; i>=0; --i) { @@ -510,7 +518,7 @@ void colvardeps::remove_child(colvardeps *child) { } } if (!found) { - cvm::error("Trying to remove missing parent reference from " + child->description + "\n"); + cvmodule->error("Trying to remove missing parent reference from " + child->description + "\n"); } } @@ -530,7 +538,7 @@ void colvardeps::remove_all_children() { } } if (!found) { - cvm::error("Trying to remove missing parent reference from " + children[i]->description + "\n"); + cvmodule->error("Trying to remove missing parent reference from " + children[i]->description + "\n"); } } children.clear(); diff --git a/src/colvardeps.h b/src/colvardeps.h index f267221d9..113e97edb 100644 --- a/src/colvardeps.h +++ b/src/colvardeps.h @@ -31,10 +31,11 @@ /// all its children dependencies are dereferenced (free_children_deps) /// While the object is inactive, no dependency solving is done on children /// it is done when the object is activated back (restore_children_deps) -class colvardeps { +class colvardeps : public colvarparse { public: - colvardeps(); + colvardeps (); + colvardeps(colvarmodule *cvmodule_in); virtual ~colvardeps(); // Subclasses should initialize the following members: @@ -444,15 +445,6 @@ class colvardeps { /// \brief print all enabled features and those of children, for debugging void print_state(); - /// \brief Check that a feature is enabled, raising COLVARS_BUG_ERROR if not - inline void check_enabled(int f, std::string const &reason) const - { - if (! is_enabled(f)) { - cvm::error("Error: "+reason+" requires that the feature \""+ - features()[f]->description+"\" is active.\n", COLVARS_BUG_ERROR); - } - } - /// Return the parents std::vector get_parents() const {return parents;} diff --git a/src/colvargrid.cpp b/src/colvargrid.cpp index 354b95f8a..00c573521 100644 --- a/src/colvargrid.cpp +++ b/src/colvargrid.cpp @@ -305,7 +305,7 @@ cvm::real colvar_grid_scalar::entropy() const cvm::real colvar_grid_scalar::grid_rmsd(colvar_grid_scalar const &other_grid) const { if (other_grid.data.size() != this->data.size()) { - cvm::error("Error: trying to subtract two grids with " + cvm::error_static("Error: trying to subtract two grids with " "different size.\n"); return -1.; } @@ -461,7 +461,7 @@ void colvar_grid_gradient::write_1D_integral(std::ostream &os) os << "# xi A(xi)\n"; if (cv.size() != 1) { - cvm::error("Cannot write integral for multi-dimensional gradient grids."); + cvm::error_static("Cannot write integral for multi-dimensional gradient grids."); return; } @@ -494,14 +494,14 @@ void colvar_grid_gradient::write_1D_integral(std::ostream &os) bin = 0.0; for ( int i = 0; i < nx[0]; i++, bin += 1.0 ) { os << std::setw(10) << cv[0]->lower_boundary.real_value + cv[0]->width * bin << " " - << std::setw(cvm::cv_width) - << std::setprecision(cvm::cv_prec) + << std::setw(cvmodule->cv_width) + << std::setprecision(cvmodule->cv_prec) << int_vals[i] - min << "\n"; } os << std::setw(10) << cv[0]->lower_boundary.real_value + cv[0]->width * bin << " " - << std::setw(cvm::cv_width) - << std::setprecision(cvm::cv_prec) + << std::setw(cvmodule->cv_width) + << std::setprecision(cvmodule->cv_prec) << int_vals[nx[0]] - min << "\n"; return; @@ -513,13 +513,13 @@ void colvar_grid_gradient::write_1D_integral(std::ostream &os) cvm::real colvar_grid_gradient::grid_rmsd(colvar_grid_gradient const &other_grid) const { if (other_grid.multiplicity() != this->multiplicity()) { - cvm::error("Error: trying to subtract two grids with " + cvm::error_static("Error: trying to subtract two grids with " "different multiplicity.\n"); return -1.; } if (other_grid.data.size() != this->data.size()) { - cvm::error("Error: trying to subtract two grids with " + cvm::error_static("Error: trying to subtract two grids with " "different size.\n"); return -1.; } diff --git a/src/colvargrid.h b/src/colvargrid.h index 9d5822e07..eaf1e9fab 100644 --- a/src/colvargrid.h +++ b/src/colvargrid.h @@ -81,7 +81,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp addr += ix[i]*static_cast(nxc[i]); if (cvm::debug()) { if (ix[i] >= nx[i]) { - cvm::error("Error: exceeding bounds in colvar_grid.\n", COLVARS_BUG_ERROR); + cvmodule->error("Error: exceeding bounds in colvar_grid.\n", COLVARS_BUG_ERROR); return 0; } } @@ -161,7 +161,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp size_t const &mult_i = 1) { if (cvm::debug()) { - cvm::log("Allocating grid: multiplicity = "+cvm::to_str(mult_i)+ + cvmodule->log("Allocating grid: multiplicity = "+cvm::to_str(mult_i)+ ", dimensions = "+cvm::to_str(nx_i)+".\n"); } @@ -178,7 +178,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp nt = mult; for (int i = nd-1; i >= 0; i--) { if (nx[i] <= 0) { - cvm::error("Error: providing an invalid number of grid points, "+ + cvm::error_static("Error: providing an invalid number of grid points, "+ cvm::to_str(nx[i])+".\n", COLVARS_BUG_ERROR); return COLVARS_ERROR; } @@ -187,7 +187,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp } if (cvm::debug()) { - cvm::log("Total number of grid elements = "+cvm::to_str(nt)+".\n"); + cvmodule->log("Total number of grid elements = "+cvm::to_str(nt)+".\n"); } data.reserve(nt); @@ -210,7 +210,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp /// Default constructor - colvar_grid() : has_data(false) + colvar_grid() : colvarparse(cvm::main()), has_data(false) { nd = nt = 0; mult = 1; @@ -226,7 +226,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp /// parameters from another grid, but doesn't reallocate stuff; /// setup() must be called after that; colvar_grid(colvar_grid const &g) : colvar_grid_params(colvar_grid_params(g)), - colvarparse(), + colvarparse(cvm::main()), mult(g.mult), data(), cv(g.cv), @@ -245,7 +245,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp colvar_grid(std::vector const &nx_i, T const &t = T(), size_t mult_i = 1) - : has_parent_data(false), has_data(false) + : colvarparse(cvm::main()), has_parent_data(false), has_data(false) { this->setup(nx_i, t, mult_i); } @@ -259,7 +259,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp bool add_extra_bin = false, std::shared_ptr params = nullptr, std::string config = std::string()) - : has_parent_data(false), has_data(false) + : colvarparse(cvm::main()), has_parent_data(false), has_data(false) { (void) t; this->init_from_colvars(colvars, mult_i, add_extra_bin, params, config); @@ -277,7 +277,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp std::string config = std::string()) { if (cvm::debug()) { - cvm::log("Reading grid configuration from collective variables.\n"); + cvmodule->log("Reading grid configuration from collective variables.\n"); } cv = colvars; @@ -287,13 +287,13 @@ template class colvar_grid : public colvar_grid_params, public colvarp size_t i; if (cvm::debug()) { - cvm::log("Allocating a grid for "+cvm::to_str(colvars.size())+ + cvmodule->log("Allocating a grid for "+cvm::to_str(colvars.size())+ " collective variables, multiplicity = "+cvm::to_str(mult_i)+".\n"); } for (i = 0; i < nd; i++) { if (cv[i]->value().type() != colvarvalue::type_scalar) { - cvm::error("Colvar grids can only be automatically " + cvm::error_static("Colvar grids can only be automatically " "constructed for scalar variables. " "ABF and histogram can not be used; metadynamics " "can be used with useGrids disabled.\n", COLVARS_INPUT_ERROR); @@ -301,7 +301,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp } if (cv[i]->width <= 0.0) { - cvm::error("Tried to initialize a grid on a " + cvm::error_static("Tried to initialize a grid on a " "variable with negative or zero width.\n", COLVARS_INPUT_ERROR); return COLVARS_ERROR; } @@ -331,14 +331,14 @@ template class colvar_grid : public colvar_grid_params, public colvarp this->check_keywords(config, "grid"); if (params) { - cvm::error("Error: init_from_colvars was passed both a grid config and a template grid.", COLVARS_BUG_ERROR); + cvm::error_static("Error: init_from_colvars was passed both a grid config and a template grid.", COLVARS_BUG_ERROR); return COLVARS_BUG_ERROR; } } else if (params) { // Match grid sizes with template if (params->nd != nd) { - cvm::error("Trying to initialize grid from template with wrong dimension (" + + cvm::error_static("Trying to initialize grid from template with wrong dimension (" + cvm::to_str(params->nd) + " instead of " + cvm::to_str(this->nd) + ")."); return COLVARS_ERROR; @@ -376,7 +376,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp int init_from_boundaries() { if (cvm::debug()) { - cvm::log("Configuring grid dimensions from colvars boundaries.\n"); + cvmodule->log("Configuring grid dimensions from colvars boundaries.\n"); } // these will have to be updated @@ -394,17 +394,17 @@ template class colvar_grid : public colvar_grid_params, public colvarp int nbins_round = (int)(nbins+0.5); if (cvm::fabs(nbins - cvm::real(nbins_round)) > 1.0E-10) { - cvm::log("Warning: grid interval("+ - cvm::to_str(lower_boundaries[i], cvm::cv_width, cvm::cv_prec)+" - "+ - cvm::to_str(upper_boundaries[i], cvm::cv_width, cvm::cv_prec)+ + cvmodule->log("Warning: grid interval("+ + cvm::to_str(lower_boundaries[i], cvmodule->cv_width, cvmodule->cv_prec)+" - "+ + cvm::to_str(upper_boundaries[i], cvmodule->cv_width, cvmodule->cv_prec)+ ") is not commensurate to its bin width("+ - cvm::to_str(widths[i], cvm::cv_width, cvm::cv_prec)+").\n"); + cvm::to_str(widths[i], cvmodule->cv_width, cvmodule->cv_prec)+").\n"); upper_boundaries[i].real_value = lower_boundaries[i].real_value + (nbins_round * widths[i]); } if (cvm::debug()) - cvm::log("Number of points is "+cvm::to_str((int) nbins_round)+ + cvmodule->log("Number of points is "+cvm::to_str((int) nbins_round)+ " for the colvar no. "+cvm::to_str(i+1)+".\n"); nx.push_back(nbins_round); @@ -422,7 +422,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp ix[i] = (ix[i] + nx[i]) % nx[i]; // Avoid modulo with negative operands (implementation-defined) } else { if (ix[i] < 0 || ix[i] >= nx[i]) { - cvm::error("Trying to wrap illegal index vector (non-PBC) for a grid point: " + cvm::error_static("Trying to wrap illegal index vector (non-PBC) for a grid point: " + cvm::to_str(ix), COLVARS_BUG_ERROR); return; } @@ -586,13 +586,13 @@ template class colvar_grid : public colvar_grid_params, public colvarp { if (other_grid.multiplicity() != this->multiplicity()) { - cvm::error("Error: trying to subtract two grids with " + cvm::error_static("Error: trying to subtract two grids with " "different multiplicity.\n"); return; } if (other_grid.data.size() != this->data.size()) { - cvm::error("Error: trying to subtract two grids with " + cvm::error_static("Error: trying to subtract two grids with " "different size.\n"); return; } @@ -610,13 +610,13 @@ template class colvar_grid : public colvar_grid_params, public colvarp void copy_grid(colvar_grid const &other_grid) { if (other_grid.multiplicity() != this->multiplicity()) { - cvm::error("Error: trying to copy two grids with " + cvm::error_static("Error: trying to copy two grids with " "different multiplicity.\n"); return; } if (other_grid.data.size() != this->data.size()) { - cvm::error("Error: trying to copy two grids with " + cvm::error_static("Error: trying to copy two grids with " "different size.\n"); return; } @@ -759,7 +759,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp void map_grid(colvar_grid const &other_grid) { if (other_grid.multiplicity() != this->multiplicity()) { - cvm::error("Error: trying to merge two grids with values of " + cvm::error_static("Error: trying to merge two grids with values of " "different multiplicity.\n"); return; } @@ -773,7 +773,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp std::vector oix = other_grid.new_index(); if (cvm::debug()) - cvm::log("Remapping grid...\n"); + cvmodule->log("Remapping grid...\n"); for ( ; this->index_ok(ix); this->incr(ix)) { for (size_t i = 0; i < nd; i++) { @@ -794,7 +794,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp has_data = true; if (cvm::debug()) - cvm::log("Remapping done.\n"); + cvmodule->log("Remapping done.\n"); } /// \brief Add data from another grid of the same type, AND @@ -803,7 +803,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp cvm::real scale_factor = 1.0) { if (other_grid.multiplicity() != this->multiplicity()) { - cvm::error("Error: trying to sum togetehr two grids with values of " + cvm::error_static("Error: trying to sum togetehr two grids with values of " "different multiplicity.\n"); return; } @@ -912,7 +912,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp upper_boundaries[i])) > 1.0E-10) || (cvm::sqrt(cv[i]->dist2(cv[i]->width, widths[i])) > 1.0E-10) ) { - cvm::error("Error: restart information for a grid is " + cvm::error_static("Error: restart information for a grid is " "inconsistent with that of its colvars.\n"); return; } @@ -935,7 +935,7 @@ template class colvar_grid : public colvar_grid_params, public colvarp (cvm::fabs(other_grid.widths[i] - widths[i]) > 1.0E-10) || (data.size() != other_grid.data.size()) ) { - cvm::error("Error: inconsistency between " + cvm::error_static("Error: inconsistency between " "two grids that are supposed to be equal, " "aside from the data stored.\n"); return; @@ -961,6 +961,16 @@ template class colvar_grid : public colvar_grid_params, public colvarp /// Read all grid parameters and data from an unformatted stream cvm::memory_stream &read_raw(cvm::memory_stream &is); +private: + + /// Helper method for read_restart + template IST& read_restart_template_(IST& is); + + /// Helper method for read_raw + template IST& read_raw_template_(IST& is); + +public: + /// Write all grid data to a formatted stream (without labels, as they are represented in memory) /// \param[in,out] os Stream object /// \param[in] buf_size Number of values per line @@ -1169,7 +1179,7 @@ class colvar_grid_count : public colvar_grid } break; default: - cvm::error("Error: local_sample_count is not implemented for grids of dimension > 3", COLVARS_NOT_IMPLEMENTED); + cvm::error_static("Error: local_sample_count is not implemented for grids of dimension > 3", COLVARS_NOT_IMPLEMENTED); break; } @@ -1200,7 +1210,7 @@ class colvar_grid_count : public colvar_grid if (A0 * A1 == 0) { return 0.; // can't handle empty bins } else { - return (cvm::logn(A1) - cvm::logn(A0)) + return (cvmodule->logn(A1) - cvmodule->logn(A0)) / (widths[n] * 2.); } } else if (ix[n] > 0 && ix[n] < nx[n]-1) { // not an edge @@ -1212,7 +1222,7 @@ class colvar_grid_count : public colvar_grid if (A0 * A1 == 0) { return 0.; // can't handle empty bins } else { - return (cvm::logn(A1) - cvm::logn(A0)) + return (cvmodule->logn(A1) - cvmodule->logn(A0)) / (widths[n] * 2.); } } else { @@ -1225,8 +1235,8 @@ class colvar_grid_count : public colvar_grid if (A0 * A1 * A2 == 0) { return 0.; // can't handle empty bins } else { - return (-1.5 * cvm::logn(A0) + 2. * cvm::logn(A1) - - 0.5 * cvm::logn(A2)) * increment / widths[n]; + return (-1.5 * cvmodule->logn(A0) + 2. * cvmodule->logn(A1) + - 0.5 * cvmodule->logn(A2)) * increment / widths[n]; } } } @@ -1424,7 +1434,7 @@ class colvar_grid_scalar : public colvar_grid // 001 011 101 111 000 010 100 110 grad[2] = 0.25 * ((p[1] + p[3] + p[5] + p[7]) - (p[0] + p[2] + p[4] + p[6])) / widths[2]; } else { - cvm::error("Finite differences available in dimension 2 and 3 only."); + cvm::error_static("Finite differences available in dimension 2 and 3 only."); } } @@ -1448,7 +1458,7 @@ class colvar_grid_scalar : public colvar_grid if (A0 * A1 == 0) { return 0.; // can't handle empty bins } else { - return (cvm::logn(A1) - cvm::logn(A0)) + return (cvmodule->logn(A1) - cvmodule->logn(A0)) / (widths[n] * 2.); } } else if (ix[n] > 0 && ix[n] < nx[n]-1) { // not an edge @@ -1460,7 +1470,7 @@ class colvar_grid_scalar : public colvar_grid if (A0 * A1 == 0) { return 0.; // can't handle empty bins } else { - return (cvm::logn(A1) - cvm::logn(A0)) + return (cvmodule->logn(A1) - cvmodule->logn(A0)) / (widths[n] * 2.); } } else { @@ -1473,8 +1483,8 @@ class colvar_grid_scalar : public colvar_grid if (A0 * A1 * A2 == 0) { return 0.; // can't handle empty bins } else { - return (-1.5 * cvm::logn(A0) + 2. * cvm::logn(A1) - - 0.5 * cvm::logn(A2)) * increment / widths[n]; + return (-1.5 * cvmodule->logn(A0) + 2. * cvmodule->logn(A1) + - 0.5 * cvmodule->logn(A2)) * increment / widths[n]; } } } @@ -1532,7 +1542,7 @@ class colvar_grid_scalar : public colvar_grid { int s; if (imult > 0) { - cvm::error("Error: trying to access a component " + cvm::error_static("Error: trying to access a component " "larger than 1 in a scalar data grid.\n"); return 0.; } @@ -1552,7 +1562,7 @@ class colvar_grid_scalar : public colvar_grid bool add = false) override { if (imult > 0) { - cvm::error("Error: trying to access a component " + cvm::error_static("Error: trying to access a component " "larger than 1 in a scalar data grid.\n"); return; } diff --git a/src/colvargrid_def.h b/src/colvargrid_def.h index 96075e1ff..24e025d94 100644 --- a/src/colvargrid_def.h +++ b/src/colvargrid_def.h @@ -24,6 +24,7 @@ template colvar_grid::colvar_grid(std::string const &filename, size_t mult_i) + : colvarparse(cvm::main()) { std::istream &is = cvm::main()->proxy->input_stream(filename, "multicol grid file"); if (!is) { @@ -37,7 +38,7 @@ std::string hash; size_t i; if ( !(is >> hash) || (hash != "#") ) { - cvm::error("Error reading grid at position "+ + cvmodule->error("Error reading grid at position "+ cvm::to_str(static_cast(is.tellg()))+ " in stream(read \"" + hash + "\")\n"); return; @@ -52,7 +53,7 @@ std::vector periodic_in(nd); for (i = 0; i < nd; i++ ) { if ( !(is >> hash) || (hash != "#") ) { - cvm::error("Error reading grid at position "+ + cvmodule->error("Error reading grid at position "+ cvm::to_str(static_cast(is.tellg()))+ " in stream(read \"" + hash + "\")\n"); return; @@ -78,34 +79,33 @@ cvm::main()->proxy->close_input_stream(filename); } -template IST &read_restart_template_(colvar_grid &g, IST &is) -{ +template +template +IST& colvar_grid::read_restart_template_(IST& is) { auto const start_pos = is.tellg(); std::string conf; if ((is >> colvarparse::read_block("grid_parameters", &conf)) && - (g.parse_params(conf, colvarparse::parse_restart) == COLVARS_OK) && g.read_raw(is)) { + (parse_params(conf, colvarparse::parse_restart) == COLVARS_OK) && + read_raw(is)) { return is; } auto const error_pos = is.tellg(); is.clear(); is.seekg(start_pos); is.setstate(std::ios::failbit); - cvm::error("Error: in reading grid state from stream at position " + cvm::to_str(error_pos) + - "\n", - COLVARS_INPUT_ERROR); + cvmodule->error("Error: in reading grid state from stream at position " + + cvm::to_str(error_pos) + "\n", COLVARS_INPUT_ERROR); return is; } -template std::istream &colvar_grid::read_restart(std::istream &is) -{ - return read_restart_template_(*this, is); +template std::istream &colvar_grid::read_restart(std::istream &is) { + return read_restart_template_(is); } -template cvm::memory_stream &colvar_grid::read_restart(cvm::memory_stream &is) -{ - return read_restart_template_(*this, is); +template cvm::memory_stream &colvar_grid::read_restart(cvm::memory_stream &is) { + return read_restart_template_(is); } @@ -124,21 +124,22 @@ template cvm::memory_stream &colvar_grid::write_restart(cvm::memory return os; } - -template IST &read_raw_template_(colvar_grid &g, IST &is) +template +template +IST &colvar_grid::read_raw_template_(IST &is) { auto const start_pos = is.tellg(); - for (std::vector ix = g.new_index(); g.index_ok(ix); g.incr(ix)) { - for (size_t imult = 0; imult < g.mult; imult++) { + for (std::vector ix = new_index(); index_ok(ix); incr(ix)) { + for (size_t imult = 0; imult < mult; imult++) { T new_value; if (is >> new_value) { - g.value_input(ix, new_value, imult); + value_input(ix, new_value, imult); } else { is.clear(); is.seekg(start_pos); is.setstate(std::ios::failbit); - cvm::error( + cvmodule->error( "Error: failed to read all of the grid points from file. Possible explanations: grid " "parameters in the configuration (lowerBoundary, upperBoundary, width) are different " "from those in the file, or the file is corrupt/incomplete.\n", @@ -148,20 +149,20 @@ template IST &read_raw_template_(colvar_grid &g, IST &is } } - g.has_data = true; + has_data = true; return is; } template std::istream &colvar_grid::read_raw(std::istream &is) { - return read_raw_template_(*this, is); + return read_raw_template_(is); } template cvm::memory_stream &colvar_grid::read_raw(cvm::memory_stream &is) { - return read_raw_template_(*this, is); + return read_raw_template_(is); } @@ -233,7 +234,7 @@ template int colvar_grid::parse_params(std::string const &conf, colvarparse::Parse_Mode const parse_mode) { if (cvm::debug()) - cvm::log("Reading grid configuration from string.\n"); + cvmodule->log("Reading grid configuration from string.\n"); std::vector old_nx = nx; std::vector old_lb = lower_boundaries; @@ -245,7 +246,7 @@ template int colvar_grid::parse_params(std::string const &conf, // this is only used in state files colvarparse::get_keyval(conf, "n_colvars", nd_in, nd, colvarparse::parse_silent); if (nd_in != nd) { - cvm::error("Error: trying to read data for a grid " + cvmodule->error("Error: trying to read data for a grid " "that contains a different number of colvars ("+ cvm::to_str(nd_in)+") than the grid defined " "in the configuration file("+cvm::to_str(nd)+ @@ -321,12 +322,12 @@ std::istream & colvar_grid::read_multicol(std::istream &is, bool add) std::vector bin; if ( cv.size() > 0 && cv.size() != nd ) { - cvm::error("Cannot read grid file: number of variables in file differs from number referenced by grid.\n"); + cvmodule->error("Cannot read grid file: number of variables in file differs from number referenced by grid.\n"); return is; } if ( !(is >> hash) || (hash != "#") ) { - cvm::error("Error reading grid at position "+ + cvmodule->error("Error reading grid at position "+ cvm::to_str(static_cast(is.tellg()))+ " in stream(read \"" + hash + "\")\n", COLVARS_INPUT_ERROR); return is; @@ -334,7 +335,7 @@ std::istream & colvar_grid::read_multicol(std::istream &is, bool add) is >> n; if ( n != nd ) { - cvm::error("Error reading grid: wrong number of collective variables.\n"); + cvmodule->error("Error reading grid: wrong number of collective variables.\n"); return is; } @@ -349,7 +350,7 @@ std::istream & colvar_grid::read_multicol(std::istream &is, bool add) remap = false; for (size_t i = 0; i < nd; i++ ) { if ( !(is >> hash) || (hash != "#") ) { - cvm::error("Error reading grid at position "+ + cvmodule->error("Error reading grid at position "+ cvm::to_str(static_cast(is.tellg()))+ " in stream(read \"" + hash + "\")\n"); return is; @@ -361,7 +362,7 @@ std::istream & colvar_grid::read_multicol(std::istream &is, bool add) if ( (cvm::fabs(lower - lower_boundaries[i].real_value) > 1.0e-10) || (cvm::fabs(width - widths[i] ) > 1.0e-10) || (nx_read[i] != nx[i]) ) { - cvm::log("Warning: reading from different grid definition (colvar " + cvmodule->log("Warning: reading from different grid definition (colvar " + cvm::to_str(i+1) + "); remapping data on new grid.\n"); remap = true; } @@ -439,8 +440,8 @@ std::ostream & colvar_grid::write_multicol(std::ostream &os) const os.setf(std::ios::scientific, std::ios::floatfield); for (size_t i = 0; i < nd; i++) { os << "# " - << std::setw(cvm::cv_width) << std::setprecision(cvm::cv_prec) << lower_boundaries[i] << " " - << std::setw(cvm::cv_width) << std::setprecision(cvm::cv_prec) << widths[i] << " " + << std::setw(cvmodule->cv_width) << std::setprecision(cvmodule->cv_prec) << lower_boundaries[i] << " " + << std::setw(cvmodule->cv_width) << std::setprecision(cvmodule->cv_prec) << widths[i] << " " << std::setw(10) << nx[i] << " " << periodic[i] << "\n"; } @@ -454,13 +455,13 @@ std::ostream & colvar_grid::write_multicol(std::ostream &os) const for (size_t i = 0; i < nd; i++) { os << " " - << std::setw(cvm::cv_width) << std::setprecision(cvm::cv_prec) + << std::setw(cvmodule->cv_width) << std::setprecision(cvmodule->cv_prec) << bin_to_value_scalar(ix[i], i); } os << " "; for (size_t imult = 0; imult < mult; imult++) { os << " " - << std::setw(cvm::cv_width) << std::setprecision(cvm::cv_prec) + << std::setw(cvmodule->cv_width) << std::setprecision(cvmodule->cv_prec) << value_output(ix, imult); } os << "\n"; diff --git a/src/colvargrid_integrate.cpp b/src/colvargrid_integrate.cpp index 9d4828eac..e43d28177 100644 --- a/src/colvargrid_integrate.cpp +++ b/src/colvargrid_integrate.cpp @@ -14,24 +14,24 @@ colvargrid_integrate::colvargrid_integrate(std::vector &colvars, // hence PMF grid is wider than gradient grid if non-PBC if (nd > 1) { - cvm::main()->cite_feature("Poisson integration of 2D/3D free energy surfaces"); + cvmodule->cite_feature("Poisson integration of 2D/3D free energy surfaces"); divergence.resize(nt); // Compute inverse of Laplacian diagonal for Jacobi preconditioning // For now all code related to preconditioning is commented out // until a method better than Jacobi is implemented -// cvm::log("Preparing inverse diagonal for preconditioning...\n"); +// cvmodule->log("Preparing inverse diagonal for preconditioning...\n"); // inv_lap_diag.resize(nt); // std::vector id(nt), lap_col(nt); // for (int i = 0; i < nt; i++) { // if (i % (nt / 100) == 0) -// cvm::log(cvm::to_str(i)); +// cvmodule->log(cvm::to_str(i)); // id[i] = 1.; // atimes(id, lap_col); // id[i] = 0.; // inv_lap_diag[i] = 1. / lap_col[i]; // } -// cvm::log("Done.\n"); +// cvmodule->log("Done.\n"); } } @@ -90,10 +90,10 @@ int colvargrid_integrate::integrate(const int itmax, const cvm::real &tol, cvm:: nr_linbcg_sym(divergence, data, tol, itmax, iter, err); if (verbose) - cvm::log("Integrated in " + cvm::to_str(iter) + " steps, error: " + cvm::to_str(err)); + cvmodule->log("Integrated in " + cvm::to_str(iter) + " steps, error: " + cvm::to_str(err)); } else { - cvm::error("Cannot integrate PMF in dimension > 3\n"); + cvmodule->error("Cannot integrate PMF in dimension > 3\n"); } return iter; diff --git a/src/colvarmodule.cpp b/src/colvarmodule.cpp index 17f5dbecd..ef8c9c782 100644 --- a/src/colvarmodule.cpp +++ b/src/colvarmodule.cpp @@ -58,7 +58,7 @@ class colvarmodule::usage { public: /// Constructor - usage(); + usage(colvarmodule *cvmodule_in); /// Increment usage count for the given feature; return error if not found int cite_feature(std::string const &feature); @@ -69,6 +69,8 @@ class colvarmodule::usage { /// Generate a report for used features (0 = URL, 1 = BibTeX) std::string report(int flag); + colvarmodule *cvmodule; + protected: /// Usage count for each feature @@ -107,60 +109,62 @@ colvarmodule::colvarmodule(colvarproxy *proxy_in) restart_version_str.clear(); restart_version_int = 0; - usage_ = new usage(); + usage_ = new usage(this); usage_->cite_feature("Colvars module"); if (proxy != NULL) { // TODO relax this error to handle multiple molecules in VMD // once the module is not static anymore - cvm::error("Error: trying to allocate the collective " + this->error("Error: trying to allocate the collective " "variable module twice.\n", COLVARS_BUG_ERROR); return; } proxy = proxy_in; // Pointer to the proxy object - parse = new colvarparse(); // Parsing object for global options + proxy_static = proxy_in; // Temporary - assume single proxy & module objects + + parse = new colvarparse(this); // Parsing object for global options version_int = proxy->get_version_from_string(COLVARS_VERSION); - cvm::log(cvm::line_marker); - cvm::log( + this->log(this->line_marker); + this->log( "Initializing the collective variables module, version " + version() + - (patch_version_number() ? (" (patch " + cvm::to_str(patch_version_number()) + ")") : "") + + (patch_version_number() ? (" (patch " + this->to_str(patch_version_number()) + ")") : "") + ".\n"); - cvm::log("Please cite Fiorin et al, Mol Phys 2013:\n" + this->log("Please cite Fiorin et al, Mol Phys 2013:\n" " https://doi.org/10.1080/00268976.2013.813594\n" "as well as all other papers listed below for individual features used.\n"); - cvm::log("Summary of compile-time features available in this build:\n"); + this->log("Summary of compile-time features available in this build:\n"); - std::string cxx_lang_msg(" - C++ language version: " + cvm::to_str(__cplusplus)); + std::string cxx_lang_msg(" - C++ language version: " + this->to_str(__cplusplus)); #if defined(_WIN32) && !defined(__CYGWIN__) cxx_lang_msg += std::string(" (warning: may not be accurate for this build)"); #endif cxx_lang_msg += std::string("\n"); - cvm::log(cxx_lang_msg); + this->log(cxx_lang_msg); if (proxy->check_replicas_enabled() == COLVARS_NOT_IMPLEMENTED) { - cvm::log(" - Multiple replicas: not available\n"); + this->log(" - Multiple replicas: not available\n"); } else { if (proxy->check_replicas_enabled() == COLVARS_OK) { - cvm::log(" - Multiple replicas: enabled (replica number " + + this->log(" - Multiple replicas: enabled (replica number " + to_str(proxy->replica_index() + 1) + " of " + to_str(proxy->num_replicas()) + ")\n"); } else { - cvm::log(" - Multiple replicas: available, but not (yet) enabled\n"); + this->log(" - Multiple replicas: available, but not (yet) enabled\n"); } } #if defined(LEPTON) - cvm::log(" - Lepton custom functions: available\n"); + this->log(" - Lepton custom functions: available\n"); #else - cvm::log(" - Lepton custom functions: not available\n"); + this->log(" - Lepton custom functions: not available\n"); #endif #if defined(COLVARS_TCL) - cvm::log(" - Tcl interpreter: available\n"); + this->log(" - Tcl interpreter: available\n"); #else - cvm::log(" - Tcl interpreter: not available\n"); + this->log(" - Tcl interpreter: not available\n"); #endif // set initial default values @@ -173,7 +177,7 @@ colvarmodule::colvarmodule(colvarproxy *proxy_in) // "it_restart" will be set by the input state file, if any; // "it" should be updated by the proxy - colvarmodule::it = colvarmodule::it_restart = 0; + it = it_restart = 0; use_scripted_forces = false; scripting_after_biases = false; @@ -199,7 +203,7 @@ colvarmodule::colvarmodule(colvarproxy *proxy_in) colvarmodule * colvarmodule::main() { - return proxy ? proxy->colvars : NULL; + return proxy_static ? proxy_static->cvmodule : nullptr; } @@ -231,11 +235,11 @@ int colvarmodule::calc_component_smp(int i) { colvar *x = (*(variables_active_smp()))[i]; int x_item = (*(variables_active_smp_items()))[i]; - if (cvm::debug()) { - cvm::log("Thread "+cvm::to_str(proxy->smp_thread_id())+"/"+ - cvm::to_str(proxy->smp_num_threads())+ - ": calc_component_smp(), i = "+cvm::to_str(i)+", cv = "+ - x->name+", cvc = "+cvm::to_str(x_item)+"\n"); + if (this->debug()) { + this->log("Thread "+this->to_str(proxy->smp_thread_id())+"/"+ + this->to_str(proxy->smp_num_threads())+ + ": calc_component_smp(), i = "+this->to_str(i)+", cv = "+ + x->name+", cvc = "+this->to_str(x_item)+"\n"); } return x->calc_cvcs(x_item, 1); } @@ -255,22 +259,22 @@ size_t colvarmodule::size() const void colvarmodule::set_initial_step(step_number it_in) { - cvm::log("Setting initial step number from MD engine: " + cvm::to_str(it_in) + "\n"); + this->log("Setting initial step number from MD engine: " + this->to_str(it_in) + "\n"); it = it_restart = it_in; } int colvarmodule::read_config_file(char const *config_filename) { - cvm::log(cvm::line_marker); - cvm::log("Reading new configuration from file \""+ + this->log(this->line_marker); + this->log("Reading new configuration from file \""+ std::string(config_filename)+"\":\n"); // open the configfile std::istream &config_s = proxy->input_stream(config_filename, "configuration file/string"); if (!config_s) { - return cvm::error("Error: in opening configuration file \""+ + return this->error("Error: in opening configuration file \""+ std::string(config_filename)+"\".\n", COLVARS_FILE_ERROR); } @@ -291,8 +295,8 @@ int colvarmodule::read_config_file(char const *config_filename) int colvarmodule::read_config_string(std::string const &config_str) { - cvm::log(cvm::line_marker); - cvm::log("Reading new configuration:\n"); + this->log(this->line_marker); + this->log("Reading new configuration:\n"); std::istringstream new_config_s(config_str); // strip the comments away @@ -335,12 +339,12 @@ int colvarmodule::parse_config(std::string &conf) // Check that the input has matching braces if (colvarparse::check_braces(conf, 0) != COLVARS_OK) { - return cvm::error("Error: unmatched curly braces in configuration.\n", + return this->error("Error: unmatched curly braces in configuration.\n", COLVARS_INPUT_ERROR); } // Check that the input has only ASCII characters, and warn otherwise - colvarparse::check_ascii(conf); + parse->check_ascii(conf); // Parse global options if (catch_input_errors(parse_global_params(conf))) { @@ -372,9 +376,9 @@ int colvarmodule::parse_config(std::string &conf) if (get_error() != COLVARS_OK) return get_error(); } - cvm::log(cvm::line_marker); - cvm::log("Collective variables module (re)initialized.\n"); - cvm::log(cvm::line_marker); + this->log(this->line_marker); + this->log("Collective variables module (re)initialized.\n"); + this->log(this->line_marker); if (source_Tcl_script.size() > 0) { run_tcl_script(source_Tcl_script); @@ -421,7 +425,7 @@ int colvarmodule::parse_global_params(std::string const &conf) std::string index_file_name; size_t pos = 0; while (parse->key_lookup(conf, "indexFile", &index_file_name, &pos)) { - cvm::log("# indexFile = \""+index_file_name+"\"\n"); + this->log("# indexFile = \""+index_file_name+"\"\n"); error_code |= read_index_file(index_file_name.c_str()); index_file_name.clear(); } @@ -431,68 +435,68 @@ int colvarmodule::parse_global_params(std::string const &conf) if (parse->get_keyval(conf, "smp", smp)) { if (smp == "cvcs" || smp == "on" || smp == "yes") { if (proxy->set_smp_mode(colvarproxy_smp::smp_mode_t::cvcs) != COLVARS_OK) { - cvm::error("Colvars component-based parallelism is not implemented.\n"); + this->error("Colvars component-based parallelism is not implemented.\n"); return COLVARS_INPUT_ERROR; } } else if (smp == "inner_loop") { if (proxy->set_smp_mode(colvarproxy_smp::smp_mode_t::inner_loop) != COLVARS_OK) { - cvm::error("SMP parallelism inside the calculation of Colvars components is not implemented.\n"); + this->error("SMP parallelism inside the calculation of Colvars components is not implemented.\n"); return COLVARS_INPUT_ERROR; } } else if (smp == "gpu") { if (proxy->set_smp_mode(colvarproxy_smp::smp_mode_t::gpu) != COLVARS_OK) { - cvm::error("GPU parallelism is not implemented.\n"); + this->error("GPU parallelism is not implemented.\n"); return COLVARS_INPUT_ERROR; } else { #if defined (COLVARS_CUDA) || defined (COLVARS_HIP) gpu_calc = std::unique_ptr( new colvars_gpu::colvarmodule_gpu_calc); gpu_calc->init(); - cvm::log("EXPERIMENTAL GPU parallelism will be applied inside:\n"); - cvm::log(" - atom groups\n"); + this->log("EXPERIMENTAL GPU parallelism will be applied inside:\n"); + this->log(" - atom groups\n"); #endif } } else { proxy->set_smp_mode(colvarproxy_smp::smp_mode_t::none); - cvm::log("SMP parallelism has been disabled.\n"); + this->log("SMP parallelism has been disabled.\n"); } } else { - cvm::log("SMP parallelism is not set.\n"); - cvm::log("Available SMP parallelism modes of this proxy are:\n"); + this->log("SMP parallelism is not set.\n"); + this->log("Available SMP parallelism modes of this proxy are:\n"); const auto available_smp_modes = proxy->get_available_smp_modes(); for (size_t i = 0; i < available_smp_modes.size(); ++i) { switch (available_smp_modes[i]) { case colvarproxy_smp::smp_mode_t::cvcs: { - cvm::log(" - cvcs\n"); + this->log(" - cvcs\n"); break; } case colvarproxy_smp::smp_mode_t::inner_loop: { - cvm::log(" - inner_loop\n"); + this->log(" - inner_loop\n"); break; } case colvarproxy_smp::smp_mode_t::gpu: { - cvm::log(" - gpu\n"); + this->log(" - gpu\n"); break; } case colvarproxy_smp::smp_mode_t::none: { - cvm::log(" - none\n"); + this->log(" - none\n"); break; } } } - cvm::log("Set SMP parallelism to the preferred (default) mode to the proxy.\n"); + this->log("Set SMP parallelism to the preferred (default) mode to the proxy.\n"); // Find the proxy's preferred SMP mode if SMP is not defined colvarproxy_smp::smp_mode_t preferred_smp_mode = proxy->get_preferred_smp_mode(); proxy->set_smp_mode(preferred_smp_mode); switch (preferred_smp_mode) { case colvarproxy_smp::smp_mode_t::cvcs: { - cvm::log("SMP parallelism will be applied to Colvars components.\n"); - cvm::log(" - SMP parallelism: enabled (num. threads = " + to_str(proxy->smp_num_threads()) + ")\n"); + this->log("SMP parallelism will be applied to Colvars components.\n"); + this->log(" - SMP parallelism: enabled (num. threads = " + to_str(proxy->smp_num_threads()) + ")\n"); break; } case colvarproxy_smp::smp_mode_t::inner_loop: { - cvm::log("SMP parallelism will be applied inside the Colvars components.\n"); - cvm::log(" - SMP parallelism: enabled (num. threads = " + to_str(proxy->smp_num_threads()) + ")\n"); + this->log("SMP parallelism will be applied inside the Colvars components.\n"); + this->log(" - SMP parallelism: enabled (num. threads = " + to_str(proxy->smp_num_threads()) + ")\n"); break; } case colvarproxy_smp::smp_mode_t::gpu: { @@ -501,12 +505,12 @@ int colvarmodule::parse_global_params(std::string const &conf) new colvars_gpu::colvarmodule_gpu_calc); gpu_calc->init(); #endif - cvm::log("EXPERIMENTAL GPU parallelism will be applied inside:\n"); - cvm::log(" - atom groups\n"); + this->log("EXPERIMENTAL GPU parallelism will be applied inside:\n"); + this->log(" - atom groups\n"); break; } case colvarproxy_smp::smp_mode_t::none: { - cvm::log("SMP parallelism is disabled by default.\n"); + this->log("SMP parallelism is disabled by default.\n"); break; } } @@ -514,7 +518,7 @@ int colvarmodule::parse_global_params(std::string const &conf) bool b_analysis = true; if (parse->get_keyval(conf, "analysis", b_analysis, true, colvarparse::parse_silent)) { - cvm::log("Warning: keyword \"analysis\" is deprecated: it is now always set " + this->log("Warning: keyword \"analysis\" is deprecated: it is now always set " "to true; individual analyses are performed only if requested."); } @@ -532,18 +536,18 @@ int colvarmodule::parse_global_params(std::string const &conf) colvarparse::parse_silent); parse->get_keyval(conf, "colvarsTrajFrequency", cv_traj_freq, cv_traj_freq); - if (cv_traj_freq % cvm::proxy->time_step_factor() != 0) { - cvm::error("colvarsTrajFrequency (currently " + cvm::to_str(cv_traj_freq) + if (cv_traj_freq % this->proxy->time_step_factor() != 0) { + this->error("colvarsTrajFrequency (currently " + this->to_str(cv_traj_freq) + ") must be a multiple of the global Colvars timestep multiplier (" - + cvm::to_str(cvm::proxy->time_step_factor()) + ").\n", COLVARS_INPUT_ERROR); + + this->to_str(this->proxy->time_step_factor()) + ").\n", COLVARS_INPUT_ERROR); } parse->get_keyval(conf, "colvarsRestartFrequency", restart_out_freq, restart_out_freq); - if (restart_out_freq % cvm::proxy->time_step_factor() != 0) { - cvm::error("colvarsRestartFrequency (currently " + cvm::to_str(restart_out_freq) + if (restart_out_freq % this->proxy->time_step_factor() != 0) { + this->error("colvarsRestartFrequency (currently " + this->to_str(restart_out_freq) + ") must be a multiple of the global Colvars timestep multiplier (" - + cvm::to_str(cvm::proxy->time_step_factor()) + ").\n", COLVARS_INPUT_ERROR); + + this->to_str(this->proxy->time_step_factor()) + ").\n", COLVARS_INPUT_ERROR); } parse->get_keyval(conf, "scriptedColvarForces", @@ -579,31 +583,31 @@ int colvarmodule::run_tcl_script(std::string const &filename) { int colvarmodule::parse_colvars(std::string const &conf) { - if (cvm::debug()) - cvm::log("Initializing the collective variables.\n"); + if (this->debug()) + this->log("Initializing the collective variables.\n"); std::string colvar_conf = ""; size_t pos = 0; while (parse->key_lookup(conf, "colvar", &colvar_conf, &pos)) { if (colvar_conf.size()) { - cvm::log(cvm::line_marker); - cvm::increase_depth(); - colvars.push_back(new colvar()); + this->log(this->line_marker); + this->increase_depth(); + colvars.push_back(new colvar(this)); if (((colvars.back())->init(colvar_conf) != COLVARS_OK) || ((colvars.back())->check_keywords(colvar_conf, "colvar") != COLVARS_OK)) { - cvm::log("Error while constructing colvar number " + - cvm::to_str(colvars.size()) + " : deleting."); + this->log("Error while constructing colvar number " + + this->to_str(colvars.size()) + " : deleting."); delete colvars.back(); // the colvar destructor updates the colvars array - cvm::decrease_depth(); + this->decrease_depth(); return COLVARS_ERROR; } - cvm::decrease_depth(); + this->decrease_depth(); } else { - cvm::error("Error: \"colvar\" keyword found without any configuration.\n", COLVARS_INPUT_ERROR); + this->error("Error: \"colvar\" keyword found without any configuration.\n", COLVARS_INPUT_ERROR); return COLVARS_ERROR; } - cvm::decrease_depth(); + this->decrease_depth(); colvar_conf = ""; } @@ -613,25 +617,25 @@ int colvarmodule::parse_colvars(std::string const &conf) } if (!colvars.size()) { - cvm::log("Warning: no collective variables defined.\n"); + this->log("Warning: no collective variables defined.\n"); } if (colvars.size()) - cvm::log(cvm::line_marker); - cvm::log("Collective variables initialized, "+ - cvm::to_str(colvars.size())+ + this->log(this->line_marker); + this->log("Collective variables initialized, "+ + this->to_str(colvars.size())+ " in total.\n"); - return (cvm::get_error() ? COLVARS_ERROR : COLVARS_OK); + return (this->get_error() ? COLVARS_ERROR : COLVARS_OK); } bool colvarmodule::check_new_bias(std::string &conf, char const *key) { - if (cvm::get_error() || + if (this->get_error() || (biases.back()->check_keywords(conf, key) != COLVARS_OK)) { - cvm::log("Error while constructing bias number " + - cvm::to_str(biases.size()) + " : deleting.\n"); + this->log("Error while constructing bias number " + + this->to_str(biases.size()) + " : deleting.\n"); delete biases.back(); // the bias destructor updates the biases array return true; } @@ -658,19 +662,19 @@ int colvarmodule::parse_biases_type(std::string const &conf, size_t conf_saved_pos = 0; while (parse->key_lookup(conf, keyword, &bias_conf, &conf_saved_pos)) { if (bias_conf.size()) { - cvm::log(cvm::line_marker); - cvm::increase_depth(); + this->log(this->line_marker); + this->increase_depth(); int &bias_count = (*num_biases_types_used)[type_keyword]; - biases.push_back(new bias_type(type_keyword.c_str())); + biases.push_back(new bias_type(this, type_keyword.c_str())); bias_count += 1; biases.back()->rank = bias_count; biases.back()->init(bias_conf); - if (cvm::check_new_bias(bias_conf, keyword) != COLVARS_OK) { + if (this->check_new_bias(bias_conf, keyword) != COLVARS_OK) { return COLVARS_ERROR; } - cvm::decrease_depth(); + this->decrease_depth(); } else { - cvm::error("Error: keyword \""+std::string(keyword)+"\" found without configuration.\n", + this->error("Error: keyword \""+std::string(keyword)+"\" found without configuration.\n", COLVARS_INPUT_ERROR); return COLVARS_ERROR; } @@ -686,8 +690,8 @@ int colvarmodule::parse_biases_type(std::string const &conf, int colvarmodule::parse_biases(std::string const &conf) { - if (cvm::debug()) - cvm::log("Initializing the collective variables biases.\n"); + if (this->debug()) + this->log("Initializing the collective variables biases.\n"); /// initialize ABF instances parse_biases_type(conf, "abf"); @@ -723,31 +727,31 @@ int colvarmodule::parse_biases(std::string const &conf) parse_biases_type(conf, "opes_metad"); if (use_scripted_forces) { - cvm::log(cvm::line_marker); - cvm::increase_depth(); - cvm::log("User forces script will be run at each bias update.\n"); - cvm::decrease_depth(); + this->log(this->line_marker); + this->increase_depth(); + this->log("User forces script will be run at each bias update.\n"); + this->decrease_depth(); } std::vector const time_biases = time_dependent_biases(); if (time_biases.size() > 1) { - cvm::log("WARNING: there are "+cvm::to_str(time_biases.size())+ + this->log("WARNING: there are "+this->to_str(time_biases.size())+ " time-dependent biases with non-zero force parameters:\n"+ - cvm::to_str(time_biases)+"\n"+ + this->to_str(time_biases)+"\n"+ "Please ensure that their forces do not counteract each other.\n"); } if (num_biases() || use_scripted_forces) { - cvm::log(cvm::line_marker); - cvm::log("Collective variables biases initialized, "+ - cvm::to_str(num_biases())+" in total.\n"); + this->log(this->line_marker); + this->log("Collective variables biases initialized, "+ + this->to_str(num_biases())+" in total.\n"); } else { if (!use_scripted_forces) { - cvm::log("No collective variables biases were defined.\n"); + this->log("No collective variables biases were defined.\n"); } } - return (cvm::get_error() ? COLVARS_ERROR : COLVARS_OK); + return (this->get_error() ? COLVARS_ERROR : COLVARS_OK); } @@ -835,9 +839,8 @@ int colvarmodule::catch_input_errors(int result) colvarbias * colvarmodule::bias_by_name(std::string const &name) { - colvarmodule *cv = cvm::main(); - for (std::vector::iterator bi = cv->biases.begin(); - bi != cv->biases.end(); + for (std::vector::iterator bi = this->biases.begin(); + bi != this->biases.end(); bi++) { if ((*bi)->name == name) { return (*bi); @@ -849,9 +852,8 @@ colvarbias * colvarmodule::bias_by_name(std::string const &name) colvar *colvarmodule::colvar_by_name(std::string const &name) { - colvarmodule *cv = cvm::main(); - for (std::vector::iterator cvi = cv->colvars.begin(); - cvi != cv->colvars.end(); + for (std::vector::iterator cvi = this->colvars.begin(); + cvi != this->colvars.end(); cvi++) { if ((*cvi)->name == name) { return (*cvi); @@ -861,9 +863,8 @@ colvar *colvarmodule::colvar_by_name(std::string const &name) } cvm::atom_group *colvarmodule::atom_group_soa_by_name(std::string const& name) { - colvarmodule *cv = cvm::main(); - for (std::vector::iterator agi = cv->named_atom_groups_soa.begin(); - agi != cv->named_atom_groups_soa.end(); + for (std::vector::iterator agi = this->named_atom_groups_soa.begin(); + agi != this->named_atom_groups_soa.end(); agi++) { if ((*agi)->name == name) { return (*agi); @@ -892,31 +893,31 @@ int colvarmodule::change_configuration(std::string const &bias_name, { // This is deprecated; supported strategy is to delete the bias // and parse the new config - cvm::increase_depth(); + this->increase_depth(); colvarbias *b; b = bias_by_name(bias_name); if (b == NULL) { - cvm::error("Error: bias not found: " + bias_name); + this->error("Error: bias not found: " + bias_name); return COLVARS_ERROR; } b->change_configuration(conf); - cvm::decrease_depth(); - return (cvm::get_error() ? COLVARS_ERROR : COLVARS_OK); + this->decrease_depth(); + return (this->get_error() ? COLVARS_ERROR : COLVARS_OK); } std::string colvarmodule::read_colvar(std::string const &name) { - cvm::increase_depth(); + this->increase_depth(); colvar *c; std::stringstream ss; c = colvar_by_name(name); if (c == NULL) { - cvm::error("Error: colvar not found: " + name); + this->error("Error: colvar not found: " + name); return std::string(); } ss << c->value(); - cvm::decrease_depth(); + this->decrease_depth(); return ss.str(); } @@ -924,16 +925,16 @@ std::string colvarmodule::read_colvar(std::string const &name) cvm::real colvarmodule::energy_difference(std::string const &bias_name, std::string const &conf) { - cvm::increase_depth(); + this->increase_depth(); colvarbias *b; cvm::real energy_diff = 0.; b = bias_by_name(bias_name); if (b == NULL) { - cvm::error("Error: bias not found: " + bias_name); + this->error("Error: bias not found: " + bias_name); return 0.; } energy_diff = b->energy_difference(conf); - cvm::decrease_depth(); + this->decrease_depth(); return energy_diff; } @@ -942,10 +943,10 @@ int colvarmodule::calc() { int error_code = COLVARS_OK; - if (cvm::debug()) { - cvm::log(cvm::line_marker); - cvm::log("Collective variables module, step no. "+ - cvm::to_str(cvm::step_absolute())+"\n"); + if (this->debug()) { + this->log(this->line_marker); + this->log("Collective variables module, step no. "+ + this->to_str(this->step_absolute())+"\n"); } error_code |= calc_colvars(); @@ -960,8 +961,8 @@ int colvarmodule::calc() } // write restart files and similar data - if (restart_out_freq && (cvm::step_relative() > 0) && - ((cvm::step_absolute() % restart_out_freq) == 0)) { + if (restart_out_freq && (this->step_relative() > 0) && + ((this->step_absolute() % restart_out_freq) == 0)) { if (restart_out_name.size()) { // Write restart file, if different from main output @@ -971,7 +972,7 @@ int colvarmodule::calc() } if (output_prefix().size()) { - cvm::increase_depth(); + this->increase_depth(); for (std::vector::iterator cvi = colvars.begin(); cvi != colvars.end(); cvi++) { // TODO remove this when corrFunc becomes a bias error_code |= (*cvi)->write_output_files(); @@ -979,23 +980,23 @@ int colvarmodule::calc() for (std::vector::iterator bi = biases.begin(); bi != biases.end(); bi++) { error_code |= (*bi)->write_state_to_replicas(); } - cvm::decrease_depth(); + this->decrease_depth(); } } // Write output files for biases, at the specified frequency for each - cvm::increase_depth(); + this->increase_depth(); for (std::vector::iterator bi = biases.begin(); bi != biases.end(); bi++) { if ((*bi)->output_freq > 0) { - if ((cvm::step_relative() > 0) && - ((cvm::step_absolute() % (*bi)->output_freq) == 0) ) { + if ((this->step_relative() > 0) && + ((this->step_absolute() % (*bi)->output_freq) == 0) ) { error_code |= (*bi)->write_output_files(); } } } - cvm::decrease_depth(); + this->decrease_depth(); error_code |= end_of_step(); @@ -1008,8 +1009,8 @@ int colvarmodule::calc() int colvarmodule::calc_colvars() { - if (cvm::debug()) - cvm::log("Calculating collective variables.\n"); + if (this->debug()) + this->log("Calculating collective variables.\n"); // calculate collective variables and their gradients // First, we need to decide which biases are awake @@ -1060,7 +1061,7 @@ int colvarmodule::calc_colvars() variables_active_smp_items()->reserve(variables_active()->size()); // set up a vector containing all components - cvm::increase_depth(); + this->increase_depth(); for (cvi = variables_active()->begin(); cvi != variables_active()->end(); cvi++) { error_code |= (*cvi)->update_cvc_flags(); @@ -1073,40 +1074,40 @@ int colvarmodule::calc_colvars() variables_active_smp_items()->push_back(icvc); } } - cvm::decrease_depth(); + this->decrease_depth(); // calculate active colvar components in parallel - error_code |= proxy->smp_loop(variables_active_smp()->size(), [](int i) { - return cvm::main()->calc_component_smp(i); + error_code |= proxy->smp_loop(variables_active_smp()->size(), [this](int i) { + return this->calc_component_smp(i); }); - cvm::increase_depth(); + this->increase_depth(); for (cvi = variables_active()->begin(); cvi != variables_active()->end(); cvi++) { error_code |= (*cvi)->collect_cvc_data(); } - cvm::decrease_depth(); + this->decrease_depth(); } else if (proxy->get_smp_mode() == colvarproxy_smp::smp_mode_t::gpu) { - cvm::increase_depth(); + this->increase_depth(); #if defined (COLVARS_CUDA) || defined (COLVARS_HIP) error_code |= gpu_calc->calc_cvs(*variables_active(), this); #else - return cvm::error("GPU calculation is not implemented.\n"); + return this->error("GPU calculation is not implemented.\n"); #endif - cvm::decrease_depth(); + this->decrease_depth(); } else { - cvm::increase_depth(); + this->increase_depth(); // calculate colvars one at a time for (cvi = variables_active()->begin(); cvi != variables_active()->end(); cvi++) { error_code |= (*cvi)->calc(); - if (cvm::get_error()) { + if (this->get_error()) { return COLVARS_ERROR; } } - cvm::decrease_depth(); + this->decrease_depth(); } - error_code |= cvm::get_error(); + error_code |= this->get_error(); return error_code; } @@ -1115,8 +1116,8 @@ int colvarmodule::calc_biases() { // update the biases and communicate their forces to the collective // variables - if (cvm::debug() && num_biases()) - cvm::log("Updating collective variable biases.\n"); + if (this->debug() && num_biases()) + this->log("Updating collective variable biases.\n"); // set biasing forces to zero before biases are calculated and summed over for (std::vector::iterator cvi = colvars.begin(); @@ -1166,15 +1167,15 @@ int colvarmodule::calc_biases() } // Straight loop over biases on a single thread - cvm::increase_depth(); + this->increase_depth(); for (bi = biases_active()->begin(); bi != biases_active()->end(); bi++) { error_code |= (*bi)->update(); - if (cvm::get_error()) { - cvm::decrease_depth(); + if (this->get_error()) { + this->decrease_depth(); return error_code; } } - cvm::decrease_depth(); + this->decrease_depth(); } for (bi = biases_active()->begin(); bi != biases_active()->end(); bi++) { @@ -1193,45 +1194,45 @@ int colvarmodule::update_colvar_forces() std::vector::iterator bi; // sum the forces from all biases for each collective variable - if (cvm::debug() && num_biases()) - cvm::log("Collecting forces from all biases.\n"); - cvm::increase_depth(); + if (this->debug() && num_biases()) + this->log("Collecting forces from all biases.\n"); + this->increase_depth(); for (bi = biases_active()->begin(); bi != biases_active()->end(); bi++) { error_code |= (*bi)->communicate_forces(); } - cvm::decrease_depth(); + this->decrease_depth(); if (use_scripted_forces && scripting_after_biases) { error_code |= calc_scripted_forces(); } // Now we have collected energies from both built-in and scripted biases - if (cvm::debug()) - cvm::log("Adding total bias energy: " + cvm::to_str(total_bias_energy) + "\n"); + if (this->debug()) + this->log("Adding total bias energy: " + this->to_str(total_bias_energy) + "\n"); proxy->add_energy(total_bias_energy); cvm::real total_colvar_energy = 0.0; // sum up the forces for each colvar, including wall forces // and integrate any internal // equation of motion (extended system) - if (cvm::debug()) - cvm::log("Updating the internal degrees of freedom " + if (this->debug()) + this->log("Updating the internal degrees of freedom " "of colvars (if they have any).\n"); - cvm::increase_depth(); + this->increase_depth(); for (cvi = variables()->begin(); cvi != variables()->end(); cvi++) { // Inactive colvars will only reset their forces and return 0 energy total_colvar_energy += (*cvi)->update_forces_energy(); } - cvm::decrease_depth(); - if (cvm::debug()) - cvm::log("Adding total colvar energy: " + cvm::to_str(total_colvar_energy) + "\n"); + this->decrease_depth(); + if (this->debug()) + this->log("Adding total colvar energy: " + this->to_str(total_colvar_energy) + "\n"); proxy->add_energy(total_colvar_energy); // make collective variables communicate their forces to their // coupled degrees of freedom (i.e. atoms) - if (cvm::debug()) - cvm::log("Communicating forces from the colvars to the atoms.\n"); - cvm::increase_depth(); + if (this->debug()) + this->log("Communicating forces from the colvars to the atoms.\n"); + this->increase_depth(); if (proxy->get_smp_mode() == colvarproxy_smp::smp_mode_t::gpu) { #if defined (COLVARS_CUDA) || defined (COLVARS_HIP) error_code |= gpu_calc->apply_forces(*variables_active(), this); @@ -1240,13 +1241,13 @@ int colvarmodule::update_colvar_forces() for (cvi = variables_active()->begin(); cvi != variables_active()->end(); cvi++) { if ((*cvi)->is_enabled(colvardeps::f_cv_apply_force)) { (*cvi)->communicate_forces(); - if (cvm::get_error()) { + if (this->get_error()) { return COLVARS_ERROR; } } } } - cvm::decrease_depth(); + this->decrease_depth(); return error_code; } @@ -1259,11 +1260,11 @@ int colvarmodule::calc_scripted_forces() int res; res = proxy->run_force_callback(); if (res == COLVARS_NOT_IMPLEMENTED) { - cvm::error("Colvar forces scripts are not implemented."); + this->error("Colvar forces scripts are not implemented."); return COLVARS_NOT_IMPLEMENTED; } if (res != COLVARS_OK) { - cvm::error("Error running user colvar forces script"); + this->error("Error running user colvar forces script"); return COLVARS_ERROR; } return COLVARS_OK; @@ -1272,22 +1273,22 @@ int colvarmodule::calc_scripted_forces() int colvarmodule::write_restart_file(std::string const &out_name) { - cvm::log("Saving collective variables state to \""+out_name+"\".\n"); + this->log("Saving collective variables state to \""+out_name+"\".\n"); std::ostream &restart_out_os = proxy->output_stream(out_name, "state file"); if (!restart_out_os) return COLVARS_FILE_ERROR; if (binary_restart) { cvm::memory_stream mem_os; if (!write_state(mem_os)) { - return cvm::error("Error: in writing binary state information to file.\n", COLVARS_ERROR); + return this->error("Error: in writing binary state information to file.\n", COLVARS_ERROR); } if (!restart_out_os.write(reinterpret_cast(mem_os.output_buffer()), mem_os.length())) { - return cvm::error("Error: in writing restart file.\n", COLVARS_FILE_ERROR); + return this->error("Error: in writing restart file.\n", COLVARS_FILE_ERROR); } } else { if (!write_state(restart_out_os)) { - return cvm::error("Error: in writing restart file.\n", COLVARS_FILE_ERROR); + return this->error("Error: in writing restart file.\n", COLVARS_FILE_ERROR); } } @@ -1295,16 +1296,16 @@ int colvarmodule::write_restart_file(std::string const &out_name) // Take the opportunity to flush colvars.traj - return (cvm::get_error() ? COLVARS_ERROR : COLVARS_OK); + return (this->get_error() ? COLVARS_ERROR : COLVARS_OK); } int colvarmodule::write_restart_string(std::string &output) { - cvm::log("Saving state to output buffer.\n"); + this->log("Saving state to output buffer.\n"); std::ostringstream os; if (!write_state(os)) { - return cvm::error("Error: in writing restart to buffer.\n", COLVARS_FILE_ERROR); + return this->error("Error: in writing restart to buffer.\n", COLVARS_FILE_ERROR); } output = os.str(); return COLVARS_OK; @@ -1315,8 +1316,8 @@ int colvarmodule::write_traj_files() { int error_code = COLVARS_OK; - if (cvm::debug()) { - cvm::log("colvarmodule::write_traj_files()\n"); + if (this->debug()) { + this->log("colvarmodule::write_traj_files()\n"); } std::ostream &cv_traj_os = proxy->output_stream(cv_traj_name, @@ -1327,27 +1328,27 @@ int colvarmodule::write_traj_files() } // Write labels in the traj file at beginning and then every 1000 lines - if ( (cvm::step_relative() == 0) || cv_traj_write_labels || - ((cvm::step_absolute() % (cv_traj_freq * 1000)) == 0) ) { + if ( (this->step_relative() == 0) || cv_traj_write_labels || + ((this->step_absolute() % (cv_traj_freq * 1000)) == 0) ) { error_code |= write_traj_label(cv_traj_os) ? COLVARS_OK : COLVARS_FILE_ERROR; cv_traj_write_labels = false; } - if (cvm::debug()) { + if (this->debug()) { proxy->flush_output_stream(cv_traj_name); } - if ((cvm::step_absolute() % cv_traj_freq) == 0) { + if ((this->step_absolute() % cv_traj_freq) == 0) { error_code |= write_traj(cv_traj_os) ? COLVARS_OK : COLVARS_FILE_ERROR; } - if (cvm::debug()) { + if (this->debug()) { proxy->flush_output_stream(cv_traj_name); } - if (restart_out_freq && ((cvm::step_absolute() % restart_out_freq) == 0)) { - cvm::log("Synchronizing (emptying the buffer of) trajectory file \""+ + if (restart_out_freq && ((this->step_absolute() % restart_out_freq) == 0)) { + this->log("Synchronizing (emptying the buffer of) trajectory file \""+ cv_traj_name+"\".\n"); error_code |= proxy->flush_output_stream(cv_traj_name); } @@ -1358,56 +1359,56 @@ int colvarmodule::write_traj_files() int colvarmodule::analyze() { - if (cvm::debug()) { - cvm::log("colvarmodule::analyze(), step = "+cvm::to_str(it)+".\n"); + if (this->debug()) { + this->log("colvarmodule::analyze(), step = "+this->to_str(it)+".\n"); } // perform colvar-specific analysis for (std::vector::iterator cvi = variables_active()->begin(); cvi != variables_active()->end(); cvi++) { - cvm::increase_depth(); + this->increase_depth(); (*cvi)->analyze(); - cvm::decrease_depth(); + this->decrease_depth(); } // perform bias-specific analysis for (std::vector::iterator bi = biases.begin(); bi != biases.end(); bi++) { - cvm::increase_depth(); + this->increase_depth(); (*bi)->analyze(); - cvm::decrease_depth(); + this->decrease_depth(); } - return (cvm::get_error() ? COLVARS_ERROR : COLVARS_OK); + return (this->get_error() ? COLVARS_ERROR : COLVARS_OK); } int colvarmodule::end_of_step() { - if (cvm::debug()) { - cvm::log("colvarmodule::end_of_step(), step = "+cvm::to_str(it)+".\n"); + if (this->debug()) { + this->log("colvarmodule::end_of_step(), step = "+this->to_str(it)+".\n"); } for (std::vector::iterator cvi = variables_active()->begin(); cvi != variables_active()->end(); cvi++) { - cvm::increase_depth(); + this->increase_depth(); (*cvi)->end_of_step(); - cvm::decrease_depth(); + this->decrease_depth(); } // perform bias-specific analysis for (std::vector::iterator bi = biases.begin(); bi != biases.end(); bi++) { - cvm::increase_depth(); + this->increase_depth(); (*bi)->end_of_step(); - cvm::decrease_depth(); + this->decrease_depth(); } - return (cvm::get_error() ? COLVARS_ERROR : COLVARS_OK); + return (this->get_error() ? COLVARS_ERROR : COLVARS_OK); } @@ -1415,18 +1416,18 @@ int colvarmodule::update_engine_parameters() { if (size() == 0) { // No-op if no variables or biases are defined - return cvm::get_error(); + return this->get_error(); } if (proxy->simulation_running()) { - cvm::log("Current simulation parameters: initial step = " + cvm::to_str(it) + - ", integration timestep = " + cvm::to_str(dt()) + "\n"); + this->log("Current simulation parameters: initial step = " + this->to_str(it) + + ", integration timestep = " + this->to_str(dt()) + "\n"); } - cvm::log("Updating atomic parameters (masses, charges, etc).\n"); + this->log("Updating atomic parameters (masses, charges, etc).\n"); for (std::vector::iterator cvi = variables()->begin(); cvi != variables()->end(); cvi++) { (*cvi)->setup(); } - return (cvm::get_error() ? COLVARS_ERROR : COLVARS_OK); + return (this->get_error() ? COLVARS_ERROR : COLVARS_OK); } @@ -1466,7 +1467,6 @@ int colvarmodule::reset() // Iterate backwards because we are deleting the elements as we go while (!biases.empty()) { colvarbias* tail = biases.back(); - biases.pop_back(); delete tail; // the bias destructor updates the biases array } biases.clear(); @@ -1478,7 +1478,6 @@ int colvarmodule::reset() // Iterate backwards because we are deleting the elements as we go while (!colvars.empty()) { colvar* cvi = colvars.back(); - colvars.pop_back(); delete cvi; // the colvar destructor updates the colvars array }; colvars.clear(); @@ -1522,7 +1521,7 @@ int colvarmodule::setup_input() // will not be executed twice proxy->set_input_prefix(""); - cvm::log(cvm::line_marker); + this->log(this->line_marker); input_is->seekg(0, std::ios::end); size_t const file_size = input_is->tellg(); @@ -1541,27 +1540,27 @@ int colvarmodule::setup_input() } if (binary_state_file) { - cvm::log("Loading state from binary file \"" + restart_in_name + "\".\n"); + this->log("Loading state from binary file \"" + restart_in_name + "\".\n"); // TODO integrate istream.read() into memory_stream to avoid copying auto *buf = new unsigned char[file_size]; if (input_is->read(reinterpret_cast(buf), file_size)) { cvm::memory_stream mem_is(file_size, buf); if (!read_state(mem_is)) { input_is->setstate(std::ios::failbit); - cvm::error("Error: cannot interpret contents of binary file \"" + restart_in_name + + this->error("Error: cannot interpret contents of binary file \"" + restart_in_name + "\".\n", COLVARS_INPUT_ERROR); } } else { - cvm::error("Error: cannot read from binary file \"" + restart_in_name + "\".\n", + this->error("Error: cannot read from binary file \"" + restart_in_name + "\".\n", COLVARS_INPUT_ERROR); } delete[] buf; } else { - cvm::log("Loading state from text file \"" + restart_in_name + "\".\n"); + this->log("Loading state from text file \"" + restart_in_name + "\".\n"); read_state(*input_is); } - cvm::log(cvm::line_marker); + this->log(this->line_marker); // Now that an explicit state file was read, we shall ignore any other restart info if (proxy->input_stream_exists("input state string")) { @@ -1575,25 +1574,25 @@ int colvarmodule::setup_input() if (proxy->input_stream_exists("input state string")) { if (!input_state_buffer_.empty()) { - return cvm::error("Error: formatted/text and unformatted/binary input state buffers are " + return this->error("Error: formatted/text and unformatted/binary input state buffers are " "defined at the same time.\n", COLVARS_BUG_ERROR); } - cvm::log(cvm::line_marker); - cvm::log("Loading state from formatted string.\n"); + this->log(this->line_marker); + this->log("Loading state from formatted string.\n"); read_state(proxy->input_stream("input state string")); - cvm::log(cvm::line_marker); + this->log(this->line_marker); proxy->delete_input_stream("input state string"); } if (!input_state_buffer_.empty()) { - cvm::log(cvm::line_marker); - cvm::log("Loading state from unformatted memory.\n"); + this->log(this->line_marker); + this->log("Loading state from unformatted memory.\n"); cvm::memory_stream ms(input_state_buffer_.size(), input_state_buffer_.data()); read_state(ms); - cvm::log(cvm::line_marker); + this->log(this->line_marker); input_state_buffer_.clear(); } @@ -1616,14 +1615,14 @@ int colvarmodule::setup_output() std::string const state_file_format(binary_restart ? " (binary format)" : ""); if (restart_out_name.size()) { - cvm::log("The restart output state file" + state_file_format + " will be \""+ + this->log("The restart output state file" + state_file_format + " will be \""+ restart_out_name+"\".\n"); } if (output_prefix() != proxy->output_prefix()) { output_prefix() = proxy->output_prefix(); if (output_prefix().size()) { - cvm::log("The final output state file will be \"" + + this->log("The final output state file will be \"" + (output_prefix().size() ? std::string(output_prefix() + ".colvars.state") : std::string("colvars.state")) + "\".\n"); @@ -1655,7 +1654,7 @@ std::string colvarmodule::state_file_prefix(char const *filename) std::string const prefix = filename_str.substr(0, filename_str.find(".colvars.state")); if (prefix.size() == 0) { - cvm::error("Error: invalid filename/prefix value \""+filename_str+"\".", + this->error("Error: invalid filename/prefix value \""+filename_str+"\".", COLVARS_INPUT_ERROR); } return prefix; @@ -1688,9 +1687,9 @@ template IST & colvarmodule::read_state_template_(IST &is) } if (restart_version() != version()) { - cvm::log("This state file was generated with version " + restart_version() + "\n"); + this->log("This state file was generated with version " + restart_version() + "\n"); if (std::is_same::value) { - cvm::log("Warning: compatibility between differetn Colvars versions is not " + this->log("Warning: compatibility between differetn Colvars versions is not " "guaranteed for unformatted (binary) state files.\n"); } } @@ -1708,7 +1707,7 @@ template IST & colvarmodule::read_state_template_(IST &is) colvarparse::parse_restart)) { units_restart = colvarparse::to_lower_cppstr(units_restart); if ((proxy->units.size() > 0) && (units_restart != proxy->units)) { - cvm::error("Error: the state file has units \""+units_restart+ + this->error("Error: the state file has units \""+units_restart+ "\", but the current unit system is \""+proxy->units+ "\".\n", COLVARS_INPUT_ERROR); } @@ -1743,10 +1742,10 @@ cvm::memory_stream &colvarmodule::read_state(cvm::memory_stream &is) return read_state_template_(is); } else { is.setstate(std::ios::failbit); - cvm::error("Error: magic number of binary file (" + - cvm::to_str(static_cast(file_magic_number)) + + this->error("Error: magic number of binary file (" + + this->to_str(static_cast(file_magic_number)) + ") does not match the expected magic number for a Colvars state file (" + - cvm::to_str(static_cast(colvars_magic_number)) + ").\n", + this->to_str(static_cast(colvars_magic_number)) + ").\n", COLVARS_INPUT_ERROR); } return is; @@ -1782,24 +1781,24 @@ std::istream & colvarmodule::read_objects_state(std::istream &is) if (word == "colvar") { - cvm::increase_depth(); + this->increase_depth(); for (std::vector::iterator cvi = colvars.begin(); cvi != colvars.end(); cvi++) { if (!((*cvi)->read_state(is))) { // Here an error signals that the variable is a match, but the // state is corrupt; otherwise, the variable rewinds is silently - cvm::error("Error: in reading state for collective variable \"" + - (*cvi)->name + "\" at position " + cvm::to_str(is.tellg()) + + this->error("Error: in reading state for collective variable \"" + + (*cvi)->name + "\" at position " + this->to_str(is.tellg()) + " in stream.\n", COLVARS_INPUT_ERROR); } if (is.tellg() > pos) break; // found it } - cvm::decrease_depth(); + this->decrease_depth(); } else { - cvm::increase_depth(); + this->increase_depth(); for (std::vector::iterator bi = biases.begin(); bi != biases.end(); bi++) { @@ -1810,14 +1809,14 @@ std::istream & colvarmodule::read_objects_state(std::istream &is) } if (!((*bi)->read_state(is))) { // Same as above, an error means a match but the state is incorrect - cvm::error("Error: in reading state for bias \"" + (*bi)->name + "\" at position " + - cvm::to_str(is.tellg()) + " in stream.\n", + this->error("Error: in reading state for bias \"" + (*bi)->name + "\" at position " + + this->to_str(is.tellg()) + " in stream.\n", COLVARS_INPUT_ERROR); } if (is.tellg() > pos) break; // found it } - cvm::decrease_depth(); + this->decrease_depth(); } } @@ -1837,7 +1836,7 @@ std::istream & colvarmodule::read_objects_state(std::istream &is) cvm::memory_stream &colvarmodule::read_objects_state(cvm::memory_stream &is) { // An unformatted stream must match the objects' exact configuration - cvm::increase_depth(); + this->increase_depth(); for (std::vector::iterator cvi = colvars.begin(); cvi != colvars.end(); cvi++) { if (!(*cvi)->read_state(is)) { return is; @@ -1848,7 +1847,7 @@ cvm::memory_stream &colvarmodule::read_objects_state(cvm::memory_stream &is) return is; } } - cvm::decrease_depth(); + this->decrease_depth(); return is; } @@ -1856,20 +1855,20 @@ cvm::memory_stream &colvarmodule::read_objects_state(cvm::memory_stream &is) int colvarmodule::print_total_forces_errning(bool warn_total_forces) { if (warn_total_forces) { - cvm::log(cvm::line_marker); - cvm::log("WARNING: The definition of system forces has changed. Please see:\n"); - cvm::log(" https://colvars.github.io/README-totalforce.html\n"); + this->log(this->line_marker); + this->log("WARNING: The definition of system forces has changed. Please see:\n"); + this->log(" https://colvars.github.io/README-totalforce.html\n"); // update this ahead of time in this special case output_prefix() = proxy->input_prefix(); - cvm::log("All output files will now be saved with the prefix \""+output_prefix()+".tmp.*\".\n"); - cvm::log("Please review the important warning above. After that, you may rename:\n\ + this->log("All output files will now be saved with the prefix \""+output_prefix()+".tmp.*\".\n"); + this->log("Please review the important warning above. After that, you may rename:\n\ \""+output_prefix()+".tmp.colvars.state\"\n\ to:\n\ \""+proxy->input_prefix()+".colvars.state\"\n\ and load it to continue this simulation.\n"); output_prefix() = output_prefix()+".tmp"; write_restart_file(output_prefix()+".colvars.state"); - return cvm::error("Exiting with error until issue is addressed.\n", + return this->error("Exiting with error until issue is addressed.\n", COLVARS_INPUT_ERROR); } @@ -1886,19 +1885,19 @@ int colvarmodule::backup_file(char const *filename) int colvarmodule::write_output_files() { int error_code = COLVARS_OK; - cvm::increase_depth(); + this->increase_depth(); for (std::vector::iterator bi = biases.begin(); bi != biases.end(); bi++) { // Only write output files if they have not already been written this time step if ((*bi)->output_freq == 0 || - cvm::step_relative() == 0 || - (cvm::step_absolute() % (*bi)->output_freq) != 0) { + this->step_relative() == 0 || + (this->step_absolute() % (*bi)->output_freq) != 0) { error_code |= (*bi)->write_output_files(); } error_code |= (*bi)->write_state_to_replicas(); } - cvm::decrease_depth(); + this->decrease_depth(); return error_code; } @@ -1907,7 +1906,7 @@ int colvarmodule::read_traj(char const *traj_filename, long traj_read_begin, long traj_read_end) { - cvm::log("Opening trajectory file \""+ + this->log("Opening trajectory file \""+ std::string(traj_filename)+"\".\n"); // NB: this function is not currently used, but when it will it should // retain the ability for direct file-based access (in case traj files @@ -1921,7 +1920,7 @@ int colvarmodule::read_traj(char const *traj_filename, do { if (!colvarparse::getline_nocomments(traj_is, line)) { - cvm::log("End of file \""+std::string(traj_filename)+ + this->log("End of file \""+std::string(traj_filename)+ "\" reached, or corrupted file.\n"); traj_is.close(); return false; @@ -1949,8 +1948,8 @@ int colvarmodule::read_traj(char const *traj_filename, if ( (traj_read_end > traj_read_begin) && (it > traj_read_end) ) { std::cerr << "\n"; - cvm::error("Reached the end of the trajectory, " - "read_end = "+cvm::to_str(traj_read_end)+"\n", + this->error("Reached the end of the trajectory, " + "read_end = "+this->to_str(traj_read_end)+"\n", COLVARS_FILE_ERROR); return COLVARS_ERROR; } @@ -1959,7 +1958,7 @@ int colvarmodule::read_traj(char const *traj_filename, cvi != colvars.end(); cvi++) { if (!(*cvi)->read_traj(is)) { - cvm::error("Error: in reading colvar \""+(*cvi)->name+ + this->error("Error: in reading colvar \""+(*cvi)->name+ "\" from trajectory file \""+ std::string(traj_filename)+"\".\n", COLVARS_FILE_ERROR); @@ -1971,7 +1970,7 @@ int colvarmodule::read_traj(char const *traj_filename, } } } - return (cvm::get_error() ? COLVARS_ERROR : COLVARS_OK); + return (this->get_error() ? COLVARS_ERROR : COLVARS_OK); } @@ -1996,7 +1995,7 @@ template OST &colvarmodule::write_state_template_(OST &os) int error_code = COLVARS_OK; - cvm::increase_depth(); + this->increase_depth(); for (std::vector::iterator cvi = colvars.begin(); cvi != colvars.end(); cvi++) { @@ -2008,7 +2007,7 @@ template OST &colvarmodule::write_state_template_(OST &os) bi++) { (*bi)->write_state(os); } - cvm::decrease_depth(); + this->decrease_depth(); if (error_code != COLVARS_OK) { // TODO make this function return an int instead @@ -2048,10 +2047,10 @@ std::ostream &colvarmodule::write_traj_label(std::ostream &os) { os.setf(std::ios::scientific, std::ios::floatfield); - os << "# " << cvm::wrap_string("step", cvm::it_width-2) + os << "# " << this->wrap_string("step", this->it_width-2) << " "; - cvm::increase_depth(); + this->increase_depth(); for (std::vector::iterator cvi = colvars.begin(); cvi != colvars.end(); cvi++) { @@ -2064,7 +2063,7 @@ std::ostream &colvarmodule::write_traj_label(std::ostream &os) } os << "\n"; - cvm::decrease_depth(); + this->decrease_depth(); return os; } @@ -2073,10 +2072,10 @@ std::ostream & colvarmodule::write_traj(std::ostream &os) { os.setf(std::ios::scientific, std::ios::floatfield); - os << std::setw(cvm::it_width) << it + os << std::setw(this->it_width) << it << " "; - cvm::increase_depth(); + this->increase_depth(); for (std::vector::iterator cvi = colvars.begin(); cvi != colvars.end(); cvi++) { @@ -2089,21 +2088,21 @@ std::ostream & colvarmodule::write_traj(std::ostream &os) } os << "\n"; - cvm::decrease_depth(); + this->decrease_depth(); return os; } void colvarmodule::log(std::string const &message, int min_log_level) { - if (cvm::log_level() < min_log_level) return; + if (this->log_level() < min_log_level) return; std::string const trailing_newline = (message.size() > 0) ? (message[message.size()-1] == '\n' ? "" : "\n") : ""; if (proxy) { // This may run before cvm construction // allow logging when the module is not fully initialized - size_t const d = (cvm::main() != NULL) ? depth() : 0; + size_t const d = depth(); if (d > 0) { proxy->log((std::string(2*d, ' ')) + message + trailing_newline); } else { @@ -2132,27 +2131,26 @@ void colvarmodule::decrease_depth() size_t & colvarmodule::depth() { // NOTE: do not call log() or error() here, to avoid recursion - colvarmodule *cv = cvm::main(); if (proxy->get_smp_mode() == colvarproxy::smp_mode_t::cvcs) { int const nt = proxy->smp_num_threads(); - if (int(cv->depth_v.size()) != nt) { + if (int(this->depth_v.size()) != nt) { proxy->smp_lock(); // update array of depths - if (cv->depth_v.size() > 0) { cv->depth_s = cv->depth_v[0]; } - cv->depth_v.clear(); - cv->depth_v.assign(nt, cv->depth_s); + if (this->depth_v.size() > 0) { this->depth_s = this->depth_v[0]; } + this->depth_v.clear(); + this->depth_v.assign(nt, this->depth_s); proxy->smp_unlock(); } - return cv->depth_v[proxy->smp_thread_id()]; + return this->depth_v[proxy->smp_thread_id()]; } - return cv->depth_s; + return this->depth_s; } void colvarmodule::set_error_bits(int code) { if (code < 0) { - cvm::log("Error: set_error_bits() received negative error code.\n"); + this->log("Error: set_error_bits() received negative error code.\n"); return; } if (proxy) { // This may run before cvm construction @@ -2208,7 +2206,7 @@ int colvarmodule::error(std::string const &message, int code) } -int cvm::read_index_file(char const *filename) +int colvarmodule::read_index_file(char const *filename) { std::istream &is = proxy->input_stream(filename, "index file"); @@ -2238,7 +2236,7 @@ int cvm::read_index_file(char const *filename) index_of_group = index_groups.size()-1; } } else { - return cvm::error("Error: in parsing index file \""+ + return this->error("Error: in parsing index file \""+ std::string(filename)+"\".\n", COLVARS_INPUT_ERROR); } @@ -2265,7 +2263,7 @@ int cvm::read_index_file(char const *filename) new_index_group->clear(); delete new_index_group; new_index_group = NULL; - return cvm::error("Error: the index group \""+group_name+ + return this->error("Error: the index group \""+group_name+ "\" was redefined.\n", COLVARS_INPUT_ERROR); } else { old_index_group->clear(); @@ -2288,11 +2286,11 @@ int cvm::read_index_file(char const *filename) } } - cvm::log("The following index groups are currently defined:\n"); + this->log("The following index groups are currently defined:\n"); size_t i = 0; for ( ; i < index_group_names.size(); i++) { - cvm::log(" "+(index_group_names[i])+" ("+ - cvm::to_str((index_groups[i])->size())+" atoms)\n"); + this->log(" "+(index_group_names[i])+" ("+ + this->to_str((index_groups[i])->size())+" atoms)\n"); } return proxy->close_input_stream(filename); @@ -2312,7 +2310,7 @@ int colvarmodule::reset_index_groups() return COLVARS_OK; } -int cvm::load_coords(char const *file_name, +int colvarmodule::load_coords(char const *file_name, std::vector *pos, cvm::atom_group *atoms, std::string const &pdb_field, @@ -2331,11 +2329,11 @@ int cvm::load_coords(char const *file_name, // Differentiate between PDB and XYZ files if (colvarparse::to_lower_cppstr(ext) == std::string(".xyz")) { if (pdb_field.size() > 0) { - return cvm::error("Error: PDB column may not be specified " + return this->error("Error: PDB column may not be specified " "for XYZ coordinate files.\n", COLVARS_INPUT_ERROR); } // For XYZ files, use internal parser - error_code |= cvm::main()->load_coords_xyz(file_name, &sorted_pos, atoms); + error_code |= this->load_coords_xyz(file_name, &sorted_pos, atoms); } else { // Otherwise, call proxy function for PDB error_code |= proxy->load_coords_pdb(file_name, sorted_pos, atoms->sorted_ids(), pdb_field, @@ -2352,7 +2350,7 @@ int cvm::load_coords(char const *file_name, return error_code; } -int cvm::load_coords_xyz(char const *filename, +int colvarmodule::load_coords_xyz(char const *filename, std::vector *pos, cvm::atom_group *atoms, bool keep_open) @@ -2368,28 +2366,28 @@ int cvm::load_coords_xyz(char const *filename, if ( ! (xyz_is >> natoms) ) { // Return silent error when reaching the end of multi-frame files - return keep_open ? COLVARS_NO_SUCH_FRAME : cvm::error(error_msg, COLVARS_INPUT_ERROR); + return keep_open ? COLVARS_NO_SUCH_FRAME : this->error(error_msg, COLVARS_INPUT_ERROR); } ++xyz_reader_use_count; if (xyz_reader_use_count < 2) { - cvm::log("Warning: beginning from 2019-11-26 the XYZ file reader assumes Angstrom units.\n"); + this->log("Warning: beginning from 2019-11-26 the XYZ file reader assumes Angstrom units.\n"); } if (xyz_is.good()) { // skip comment line - cvm::getline(xyz_is, line); - cvm::getline(xyz_is, line); + this->getline(xyz_is, line); + this->getline(xyz_is, line); xyz_is.width(255); } else { proxy->close_input_stream(filename); - return cvm::error(error_msg, COLVARS_INPUT_ERROR); + return this->error(error_msg, COLVARS_INPUT_ERROR); } if (pos->size() > natoms) { proxy->close_input_stream(filename); - return cvm::error("File \"" + std::string(filename) + "\" contains fewer atoms (" + cvm::to_str(natoms) - + ") than expected (" + cvm::to_str(pos->size()) + ").", COLVARS_INPUT_ERROR); + return this->error("File \"" + std::string(filename) + "\" contains fewer atoms (" + this->to_str(natoms) + + ") than expected (" + this->to_str(pos->size()) + ").", COLVARS_INPUT_ERROR); } std::vector::iterator pos_i = pos->begin(); @@ -2399,21 +2397,21 @@ int cvm::load_coords_xyz(char const *filename, if (!atoms) { // In the other branch of this test, reading all positions from the file, // a valid atom group pointer is not necessary - return cvm::error("Trying to read partial positions with invalid atom group pointer", + return this->error("Trying to read partial positions with invalid atom group pointer", COLVARS_BUG_ERROR); } if (static_cast(atoms->sorted_ids().back()) > natoms) { proxy->close_input_stream(filename); - return cvm::error("File \"" + std::string(filename) + "\" contains fewer atoms (" + cvm::to_str(natoms) - + ") than expected (" + cvm::to_str(atoms->sorted_ids().back()) + ").", COLVARS_INPUT_ERROR); + return this->error("File \"" + std::string(filename) + "\" contains fewer atoms (" + this->to_str(natoms) + + ") than expected (" + this->to_str(atoms->sorted_ids().back()) + ").", COLVARS_INPUT_ERROR); } std::vector::const_iterator index = atoms->sorted_ids().begin(); for ( ; pos_i != pos->end() ; pos_i++, index++) { while ( next < *index ) { - cvm::getline(xyz_is, line); + this->getline(xyz_is, line); next++; } if (xyz_is.good()) { @@ -2426,7 +2424,7 @@ int cvm::load_coords_xyz(char const *filename, xyz_natoms++; } else { proxy->close_input_stream(filename); - return cvm::error(error_msg, COLVARS_INPUT_ERROR); + return this->error(error_msg, COLVARS_INPUT_ERROR); } } @@ -2442,17 +2440,17 @@ int cvm::load_coords_xyz(char const *filename, xyz_natoms++; } else { proxy->close_input_stream(filename); - return cvm::error(error_msg, COLVARS_INPUT_ERROR); + return this->error(error_msg, COLVARS_INPUT_ERROR); } } } if (xyz_natoms != pos->size()) { proxy->close_input_stream(filename); - return cvm::error("Error: The number of positions read from file \""+ + return this->error("Error: The number of positions read from file \""+ std::string(filename)+"\" does not match the number of "+ - "positions required: "+cvm::to_str(xyz_natoms)+" vs. "+ - cvm::to_str(pos->size())+".\n", COLVARS_INPUT_ERROR); + "positions required: "+this->to_str(xyz_natoms)+" vs. "+ + this->to_str(pos->size())+".\n", COLVARS_INPUT_ERROR); } if (keep_open) { @@ -2465,26 +2463,26 @@ int cvm::load_coords_xyz(char const *filename, // Wrappers to proxy functions: these may go in the future -cvm::real cvm::dt() +cvm::real colvarmodule::dt() { return proxy->dt(); } -void cvm::request_total_force() +void colvarmodule::request_total_force() { proxy->request_total_force(true); } -cvm::rvector cvm::position_distance(cvm::atom_pos const &pos1, +cvm::rvector colvarmodule::position_distance(cvm::atom_pos const &pos1, cvm::atom_pos const &pos2) { return proxy->position_distance(pos1, pos2); } -cvm::real cvm::rand_gaussian(void) +cvm::real colvarmodule::rand_gaussian(void) { return proxy->rand_gaussian(); } @@ -2671,7 +2669,7 @@ std::string colvarmodule::to_str(std::vectorlog("Warning: cannot cite unknown feature \""+feature+"\"\n"); return COLVARS_OK; } @@ -2716,7 +2715,7 @@ int colvarmodule::usage::cite_paper(std::string const &paper) paper_count_[paper] += 1; return COLVARS_OK; } - cvm::log("Warning: cannot cite unknown paper \""+paper+"\"\n"); + cvmodule->log("Warning: cannot cite unknown paper \""+paper+"\"\n"); return COLVARS_OK; } @@ -2765,26 +2764,7 @@ std::string colvarmodule::usage::report(int flag) return result; } +// Static pointer to the proxy object +colvarproxy *colvarmodule::proxy_static = nullptr; -// shared pointer to the proxy object -colvarproxy *colvarmodule::proxy = nullptr; - -// static runtime data cvm::real colvarmodule::debug_gradients_step_size = 1.0e-07; -int colvarmodule::errorCode = 0; -int colvarmodule::log_level_ = 10; -cvm::step_number colvarmodule::it = 0; -cvm::step_number colvarmodule::it_restart = 0; -size_t colvarmodule::restart_out_freq = 0; -size_t colvarmodule::cv_traj_freq = 0; -bool colvarmodule::use_scripted_forces = false; -bool colvarmodule::scripting_after_biases = true; - -// i/o constants -size_t const colvarmodule::it_width = 12; -size_t const colvarmodule::cv_prec = 14; -size_t const colvarmodule::cv_width = 21; -size_t const colvarmodule::en_prec = 14; -size_t const colvarmodule::en_width = 21; -const char * const colvarmodule::line_marker = (const char *) - "----------------------------------------------------------------------\n"; diff --git a/src/colvarmodule.h b/src/colvarmodule.h index 83dccb7f8..62f23293a 100644 --- a/src/colvarmodule.h +++ b/src/colvarmodule.h @@ -241,35 +241,35 @@ static inline real acos(real const &x) /// see constants at the top of this file private: - static int errorCode; + int errorCode = 0; public: - static void set_error_bits(int code); + void set_error_bits(int code); - static bool get_error_bit(int code); + bool get_error_bit(int code); - static inline int get_error() + inline int get_error() { return errorCode; } - static void clear_error(); + void clear_error(); /// Current step number - static step_number it; + step_number it = 0; /// Starting step number for this run - static step_number it_restart; + step_number it_restart = 0; /// Return the current step number from the beginning of this run - static inline step_number step_relative() + inline step_number step_relative() { return it - it_restart; } /// Return the current step number from the beginning of the whole /// calculation - static inline step_number step_absolute() + inline step_number step_absolute() { return it; } @@ -288,10 +288,9 @@ static inline real acos(real const &x) public: /// Accessor for the above - static inline std::string &output_prefix() + inline std::string &output_prefix() { - colvarmodule *cv = colvarmodule::main(); - return cv->cvm_output_prefix; + return this->cvm_output_prefix; } private: @@ -321,7 +320,7 @@ static inline real acos(real const &x) /* TODO: implement named CVCs /// Array of named (reusable) collective variable components - static std::vector cvcs; + std::vector cvcs; /// Named cvcs register themselves at initialization time inline void register_cvc(cvc *p) { cvcs.push_back(p); @@ -538,7 +537,7 @@ static inline real acos(real const &x) int write_state_buffer(std::vector &buffer); /// Strips .colvars.state from filename and checks that it is not empty - static std::string state_file_prefix(char const *filename); + std::string state_file_prefix(char const *filename); /// Open a trajectory file if requested (and leave it open) int open_traj_file(std::string const &file_name); @@ -556,19 +555,19 @@ static inline real acos(real const &x) /// Write all other output files int write_output_files(); /// Backup a file before writing it - static int backup_file(char const *filename); + int backup_file(char const *filename); /// Write the state into a string int write_restart_string(std::string &output); /// Look up a bias by name; returns NULL if not found - static colvarbias * bias_by_name(std::string const &name); + colvarbias * bias_by_name(std::string const &name); /// Look up a colvar by name; returns NULL if not found - static colvar * colvar_by_name(std::string const &name); + colvar * colvar_by_name(std::string const &name); /// Look up a named atom group by name; returns NULL if not found - static atom_group * atom_group_soa_by_name(std::string const& name); + atom_group * atom_group_soa_by_name(std::string const& name); /// Load new configuration for the given bias - /// currently works for harmonic (force constant and/or centers) @@ -605,6 +604,8 @@ static inline real acos(real const &x) long traj_read_begin, long traj_read_end); + // In a first phase, keep to_str() static + /// Convert to string for output purposes static std::string to_str(char const *s); @@ -702,27 +703,29 @@ static inline real acos(real const &x) static std::string wrap_string(std::string const &s, size_t nchars); + // i/o constants + /// Number of characters to represent a time step - static size_t const it_width; + size_t const it_width = 12; /// Number of digits to represent a collective variables value(s) - static size_t const cv_prec; + size_t const cv_prec = 14; /// Number of characters to represent a collective variables value(s) - static size_t const cv_width; + size_t const cv_width = 21; /// Number of digits to represent the collective variables energy - static size_t const en_prec; + size_t const en_prec = 14; /// Number of characters to represent the collective variables energy - static size_t const en_width; + size_t const en_width = 21; /// Line separator in the log output - static const char * const line_marker; - + const char * const line_marker = (const char *) + "----------------------------------------------------------------------\n"; // proxy functions /// \brief Time step of MD integrator (fs) - static real dt(); + real dt(); /// Request calculation of total force from MD engine - static void request_total_force(); + void request_total_force(); /// Track usage of the given Colvars feature int cite_feature(std::string const &feature); @@ -732,58 +735,81 @@ static inline real acos(real const &x) /// Print a message to the main log /// \param message Message to print - /// \param min_log_level Only print if cvm::log_level() >= min_log_level - static void log(std::string const &message, int min_log_level = 10); + /// \param min_log_level Only print if cvmodule->log_level() >= min_log_level + void log(std::string const &message, int min_log_level = 10); + + /// Print a message to stderr + /// Used in lightweight objects that do not have access to cvmodule + static void log_static(std::string const &message) { + if (colvarmodule::main()) { + colvarmodule::main()->log(message); + } else { + std::cout << "colvars: " << message << std::endl; + } + } /// Print a message to the main log and set global error code - static int error(std::string const &message, int code = -1); + int error(std::string const &message, int code = -1); + + /// Print an error message to stderr + /// Used in lightweight objects that do not have access to cvmodule + /// Typically fatal errors that reflect bugs, so hopefully rare + static int error_static(std::string const &message, int code = -1) { + if (colvarmodule::main()) { + code = colvarmodule::main()->error(message, code); + } else { + std::cerr << "colvars: " << message << std::endl; + exit(-1); + } + return code; + } private: /// Level of logging requested by the user - static int log_level_; + int log_level_ = 10; public: /// Level of logging requested by the user - static inline int log_level() + inline int log_level() { return log_level_; } /// Level at which initialization messages are logged - static inline int log_init_messages() + inline int log_init_messages() { return 1; } /// Level at which a keyword's user-provided value is logged - static inline int log_user_params() + inline int log_user_params() { return 2; } /// Level at which a keyword's default value is logged - static inline int log_default_params() + inline int log_default_params() { return 3; } /// Level at which output-file operations are logged - static inline int log_output_files() + inline int log_output_files() { return 4; } /// Level at which input-file operations (configuration, state) are logged - static inline int log_input_files() + inline int log_input_files() { return 5; } /// \brief Get the distance between two atomic positions with pbcs handled /// correctly - static rvector position_distance(atom_pos const &pos1, + rvector position_distance(atom_pos const &pos1, atom_pos const &pos2); /// \brief Names of .ndx files that have been loaded @@ -809,7 +835,7 @@ static inline real acos(real const &x) /// and this string is non-empty, select atoms for which this field is /// non-zero \param pdb_field_value (optional) if non-zero, select only /// atoms whose pdb_field equals this - static int load_coords(char const *filename, + int load_coords(char const *filename, std::vector *pos, atom_group *atoms, std::string const &pdb_field, @@ -822,15 +848,15 @@ static inline real acos(real const &x) bool keep_open = false); /// Frequency for collective variables trajectory output - static size_t cv_traj_freq; + size_t cv_traj_freq = 0; /// Frequency for saving output restarts - static size_t restart_out_freq; + size_t restart_out_freq = 0; /// Output restart file name std::string restart_out_name; /// Pseudo-random number with Gaussian distribution - static real rand_gaussian(); + real rand_gaussian(); protected: @@ -880,24 +906,24 @@ static inline real acos(real const &x) } /// Get the current object depth in the hierarchy - static size_t & depth(); + size_t & depth(); /// Increase the depth (number of indentations in the output) - static void increase_depth(); + void increase_depth(); /// Decrease the depth (number of indentations in the output) - static void decrease_depth(); + void decrease_depth(); - static inline bool scripted_forces() + inline bool scripted_forces() { return use_scripted_forces; } /// Use scripted colvars forces? - static bool use_scripted_forces; + bool use_scripted_forces = false; /// Wait for all biases before calculating scripted forces? - static bool scripting_after_biases; + bool scripting_after_biases = true; /// Calculate the energy and forces of scripted biases int calc_scripted_forces(); @@ -914,11 +940,12 @@ static inline real acos(real const &x) } /// \brief Pointer to the proxy object, used to retrieve atomic data - /// from the hosting program; it is static in order to be accessible - /// from static functions in the colvarmodule class - static colvarproxy *proxy; + /// from the hosting program + colvarproxy *proxy = nullptr; + /// Temporary static pointer to unique proxy object + static colvarproxy *proxy_static; - /// \brief Access the one instance of the Colvars module + /// \brief Access the main instance of the Colvars module static colvarmodule *main(); #if defined (COLVARS_CUDA) || defined (COLVARS_HIP) diff --git a/src/colvarparams.cpp b/src/colvarparams.cpp index 9c326572b..bcb713355 100644 --- a/src/colvarparams.cpp +++ b/src/colvarparams.cpp @@ -75,7 +75,7 @@ void const *colvarparams::get_param_ptr(std::string const ¶m_name) if (param_map.count(param_name) > 0) { return param_map[param_name]; } - cvm::error("Error: parameter \""+param_name+"\" not found.\n", COLVARS_INPUT_ERROR); + cvm::error_static("Error: parameter \""+param_name+"\" not found.\n", COLVARS_INPUT_ERROR); return NULL; } @@ -85,7 +85,7 @@ void const *colvarparams::get_param_grad_ptr(std::string const ¶m_name) if (param_grad_map.count(param_name) > 0) { return param_grad_map[param_name]; } - cvm::error("Error: gradient of parameter \""+param_name+"\" not found.\n", + cvm::error_static("Error: gradient of parameter \""+param_name+"\" not found.\n", COLVARS_INPUT_ERROR); return NULL; } @@ -103,9 +103,9 @@ int colvarparams::set_param(std::string const ¶m_name, void const * /* new_value */) { if (param_map.count(param_name) > 0) { - return cvm::error("Error: parameter \""+param_name+"\" cannot be " + return cvm::error_static("Error: parameter \""+param_name+"\" cannot be " "modified.\n", COLVARS_NOT_IMPLEMENTED); } - return cvm::error("Error: parameter \""+param_name+"\" not found.\n", + return cvm::error_static("Error: parameter \""+param_name+"\" not found.\n", COLVARS_INPUT_ERROR); } diff --git a/src/colvarparse.cpp b/src/colvarparse.cpp index cf3096ba5..cd857a3b4 100644 --- a/src/colvarparse.cpp +++ b/src/colvarparse.cpp @@ -32,12 +32,28 @@ namespace { } -colvarparse::colvarparse() - : keyword_delimiters_left("\n"+std::string(white_space)+"}"), +// colvarparse::colvarparse() +// : keyword_delimiters_left("\n"+std::string(white_space)+"}"), +// keyword_delimiters_right("\n"+std::string(white_space)+"{") +// { +// colvarparse::clear(); +// } + + +colvarparse::colvarparse(colvarmodule *cvmodule_in) + : cvmodule(cvmodule_in), + keyword_delimiters_left("\n"+std::string(white_space)+"}"), keyword_delimiters_right("\n"+std::string(white_space)+"{") -{ - colvarparse::clear(); -} +{} + + +// colvarparse::colvarparse(colvarmodule *cvmodule_in, const std::string& conf) +// : cvmodule(cvmodule_in), +// keyword_delimiters_left("\n"+std::string(white_space)+"}"), +// keyword_delimiters_right("\n"+std::string(white_space)+"{") +// { +// colvarparse::set_string(conf); +// } void colvarparse::clear() @@ -46,15 +62,6 @@ void colvarparse::clear() clear_keyword_registry(); } - -colvarparse::colvarparse(const std::string& conf) - : keyword_delimiters_left("\n"+std::string(white_space)+"}"), - keyword_delimiters_right("\n"+std::string(white_space)+"{") -{ - colvarparse::set_string(conf); -} - - void colvarparse::set_string(std::string const &conf) { if (! config_string.size()) { @@ -89,7 +96,7 @@ bool colvarparse::get_key_string_value(std::string const &conf, } while (b_found); if (found_count > 1) { - cvm::error("Error: found more than one instance of \""+ + cvmodule->error("Error: found more than one instance of \""+ std::string(key)+"\".\n", COLVARS_INPUT_ERROR); } @@ -125,11 +132,11 @@ void colvarparse::mark_key_set_user(std::string const &key_str, { key_set_modes[to_lower_cppstr(key_str)] = key_set_user; if (parse_mode & parse_echo) { - cvm::log("# "+key_str+" = "+cvm::to_str(value)+"\n", - cvm::log_user_params()); + cvmodule->log("# "+key_str+" = "+cvm::to_str(value)+"\n", + cvmodule->log_user_params()); } if (parse_mode & parse_deprecation_warning) { - cvm::log("Warning: keyword "+key_str+ + cvmodule->log("Warning: keyword "+key_str+ " is deprecated. Check the documentation for the current equivalent.\n"); } } @@ -142,8 +149,8 @@ void colvarparse::mark_key_set_default(std::string const &key_str, { key_set_modes[to_lower_cppstr(key_str)] = key_set_default; if (parse_mode & parse_echo_default) { - cvm::log("# "+key_str+" = "+cvm::to_str(def_value)+ - " [default]\n", cvm::log_default_params()); + cvmodule->log("# "+key_str+" = "+cvm::to_str(def_value)+ + " [default]\n", cvmodule->log_default_params()); } } @@ -155,10 +162,10 @@ void colvarparse::error_key_required(std::string const &key_str, return; } if (parse_mode & parse_restart) { - cvm::error("Error: keyword \""+key_str+ + cvmodule->error("Error: keyword \""+key_str+ "\" is missing from the restart.\n", COLVARS_INPUT_ERROR); } else { - cvm::error("Error: keyword \""+key_str+ + cvmodule->error("Error: keyword \""+key_str+ "\" is required.\n", COLVARS_INPUT_ERROR); } } @@ -180,12 +187,12 @@ int colvarparse::_get_keyval_scalar_value_(std::string const &key_str, } if (value_count == 0) { - return cvm::error("Error: in parsing \""+ + return cvmodule->error("Error: in parsing \""+ key_str+"\".\n", COLVARS_INPUT_ERROR); } if (value_count > 1) { - return cvm::error("Error: multiple values " + return cvmodule->error("Error: multiple values " "are not allowed for keyword \""+ key_str+"\".\n", COLVARS_INPUT_ERROR); } @@ -209,7 +216,7 @@ int colvarparse::_get_keyval_scalar_value_(std::string const &key_str, (data == std::string("false")) ) { set_bool(reinterpret_cast(&value), false); } else { - return cvm::error("Error: boolean values only are allowed " + return cvmodule->error("Error: boolean values only are allowed " "for \""+key_str+"\".\n", COLVARS_INPUT_ERROR); } return COLVARS_OK; @@ -221,7 +228,7 @@ int colvarparse::_get_keyval_scalar_novalue_(std::string const &key_str, TYPE & /* value */, Parse_Mode const & /* parse_mode */) { - return cvm::error("Error: improper or missing value " + return cvmodule->error("Error: improper or missing value " "for \""+key_str+"\".\n", COLVARS_INPUT_ERROR); } @@ -263,8 +270,8 @@ bool colvarparse::_get_keyval_scalar_(std::string const &conf, } else { if (parse_mode & parse_required) { - if (cvm::debug()) { - cvm::log("get_keyval, parse_required = "+cvm::to_str(parse_mode & parse_required)+ + if (cvmodule->debug()) { + cvmodule->log("get_keyval, parse_required = "+cvm::to_str(parse_mode & parse_required)+ "\n"); } error_key_required(key_str, parse_mode); @@ -320,7 +327,7 @@ bool colvarparse::_get_keyval_vector_(std::string const &conf, if (is >> x) { values[i] = x; } else { - cvm::error("Error: in parsing \""+ + cvmodule->error("Error: in parsing \""+ key_str+"\".\n", COLVARS_INPUT_ERROR); } } @@ -331,12 +338,12 @@ bool colvarparse::_get_keyval_vector_(std::string const &conf, } else { if (b_found_any) { - cvm::error("Error: improper or missing values for \""+ + cvmodule->error("Error: improper or missing values for \""+ key_str+"\".\n", COLVARS_INPUT_ERROR); } else { if ((values.size() > 0) && (values.size() != def_values.size())) { - cvm::error("Error: the number of default values for \""+ + cvmodule->error("Error: the number of default values for \""+ key_str+"\" is different from the number of " "current values.\n", COLVARS_BUG_ERROR); } @@ -590,8 +597,8 @@ void colvarparse::clear_keyword_registry() int colvarparse::check_keywords(std::string &conf, char const *key) { - if (cvm::debug()) - cvm::log("Configuration string for \""+std::string(key)+ + if (cvmodule->debug()) + cvmodule->log("Configuration string for \""+std::string(key)+ "\":\n\""+conf+"\".\n"); strip_values(conf); @@ -600,7 +607,7 @@ int colvarparse::check_keywords(std::string &conf, char const *key) std::string line; std::istringstream is(conf); - while (cvm::getline(is, line)) { + while (cvmodule->getline(is, line)) { if (line.size() == 0) continue; if (line.find_first_not_of(white_space) == @@ -610,8 +617,8 @@ int colvarparse::check_keywords(std::string &conf, char const *key) std::string uk; std::istringstream line_is(line); line_is >> uk; - // if (cvm::debug()) - // cvm::log ("Checking the validity of \""+uk+"\" from line:\n" + line); + // if (cvmodule->debug()) + // cvmodule->log ("Checking the validity of \""+uk+"\" from line:\n" + line); uk = to_lower_cppstr(uk); bool found_keyword = false; @@ -623,7 +630,7 @@ int colvarparse::check_keywords(std::string &conf, char const *key) } } if (!found_keyword) { - cvm::error("Error: keyword \""+uk+"\" is not supported, " + cvmodule->error("Error: keyword \""+uk+"\" is not supported, " "or not recognized in this context.\n", COLVARS_INPUT_ERROR); return COLVARS_INPUT_ERROR; } @@ -638,7 +645,7 @@ int colvarparse::check_keywords(std::string &conf, char const *key) std::istream & colvarparse::read_config_line(std::istream &is, std::string &line) { - cvm::getline(is, line); + cvmodule->getline(is, line); config_string += line+'\n'; size_t const comment = line.find('#'); if (comment != std::string::npos) { @@ -665,8 +672,8 @@ bool colvarparse::key_lookup(std::string const &conf, std::string *data, size_t *save_pos) { - if (cvm::debug()) { - cvm::log("Looking for the keyword \""+std::string(key_in)+ + if (cvmodule->debug()) { + cvmodule->log("Looking for the keyword \""+std::string(key_in)+ "\" and its value.\n"); } @@ -693,8 +700,8 @@ bool colvarparse::key_lookup(std::string const &conf, if (pos == std::string::npos) { // no valid instance of the keyword has been found - if (cvm::debug()) { - cvm::log("Keyword \""+std::string(key_in)+"\" not found.\n"); + if (cvmodule->debug()) { + cvmodule->log("Keyword \""+std::string(key_in)+"\" not found.\n"); } return false; } @@ -770,8 +777,8 @@ bool colvarparse::key_lookup(std::string const &conf, // find the matching closing brace -// if (cvm::debug()) { -// cvm::log("Multi-line value, config is now \""+line+"\".\n"); +// if (cvmodule->debug()) { +// cvmodule->log("Multi-line value, config is now \""+line+"\".\n"); // } int brace_count = 1; @@ -798,7 +805,7 @@ bool colvarparse::key_lookup(std::string const &conf, // add a new line if (line_end >= conf.size()) { - cvm::error("Parse error: reached the end while " + cvmodule->error("Parse error: reached the end while " "looking for closing brace; until now " "the following was parsed: \"\n"+ line+"\".\n", COLVARS_INPUT_ERROR); @@ -813,13 +820,13 @@ bool colvarparse::key_lookup(std::string const &conf, line_end = nl; line.append(conf, line_begin, (line_end-line_begin)); -// if (cvm::debug()) { -// cvm::log("Added a new line, config is now \""+line+"\".\n"); +// if (cvmodule->debug()) { +// cvmodule->log("Added a new line, config is now \""+line+"\".\n"); // } } if (brace_count < 0) { - cvm::error("Error: found closing brace without opening brace.\n", COLVARS_INPUT_ERROR); + cvmodule->error("Error: found closing brace without opening brace.\n", COLVARS_INPUT_ERROR); } } @@ -837,8 +844,8 @@ bool colvarparse::key_lookup(std::string const &conf, if (data != NULL && data_end > data_begin) { data->append(line, data_begin, (data_end-data_begin)); - if (cvm::debug()) { - cvm::log("Keyword value = \""+*data+"\".\n"); + if (cvmodule->debug()) { + cvmodule->log("Keyword value = \""+*data+"\".\n"); } if (data->size()) { @@ -991,12 +998,12 @@ int colvarparse::check_ascii(std::string const &conf) // Check for non-ASCII characters std::string line; std::istringstream is(conf); - while (cvm::getline(is, line)) { + while (cvmodule->getline(is, line)) { unsigned char const * const uchars = reinterpret_cast(line.c_str()); for (size_t i = 0; i < line.size(); i++) { if (uchars[i] & 0x80U) { - cvm::log("Warning: non-ASCII character detected in this line: \""+ + cvmodule->log("Warning: non-ASCII character detected in this line: \""+ line+"\".\n"); } } diff --git a/src/colvarparse.h b/src/colvarparse.h index 105a0857a..b617b1a63 100644 --- a/src/colvarparse.h +++ b/src/colvarparse.h @@ -26,13 +26,23 @@ /// need to parse input inherit from this class colvarparse : public colvarparams { +protected: + + colvarmodule *cvmodule = nullptr; + public: + colvarmodule *get_cvmodule() { return cvmodule; } + /// Default constructor - colvarparse(); + // colvarparse(); + + /// Constructor that stores the colvarmodule pointer + colvarparse(colvarmodule *cvmodule_in); - /// Constructor that stores the object's config string - colvarparse(const std::string& conf); + // UNUSED + // /// Constructor that stores the object's config string + // colvarparse(colvarmodule *cvmodule_in, const std::string& conf); /// Set the object ready to parse a new configuration string void clear(); @@ -332,7 +342,7 @@ class colvarparse : public colvarparams { /// \brief Check that a config string contains non-ASCII characters /// \param conf The configuration string - static int check_ascii(std::string const &conf); + int check_ascii(std::string const &conf); /// \brief Split a string with a specified delimiter into a vector /// \param data The string to be splitted diff --git a/src/colvarproxy.cpp b/src/colvarproxy.cpp index d1315c529..6e8c7b17e 100644 --- a/src/colvarproxy.cpp +++ b/src/colvarproxy.cpp @@ -84,7 +84,7 @@ int colvarproxy_atoms::init_atom(cvm::residue_id const & /* residue */, std::string const & /* atom_name */, std::string const & /* segment_id */) { - cvm::error("Error: initializing an atom by name and residue number is currently not supported.\n", + cvm::error_static("Error: initializing an atom by name and residue number is currently not supported.\n", COLVARS_NOT_IMPLEMENTED); return COLVARS_NOT_IMPLEMENTED; } @@ -102,7 +102,7 @@ int colvarproxy_atoms::check_atom_id(cvm::residue_id const &residue, void colvarproxy_atoms::clear_atom(int index) { if (((size_t) index) >= atoms_ids.size()) { - cvm::error("Error: trying to disable an atom that was not previously requested.\n", + cvm::error_static("Error: trying to disable an atom that was not previously requested.\n", COLVARS_INPUT_ERROR); } if (atoms_refcount[index] > 0) { @@ -196,7 +196,7 @@ int colvarproxy_atom_groups::scalable_group_coms() int colvarproxy_atom_groups::init_atom_group(std::vector const & /* atoms_ids */) { - cvm::error("Error: initializing a group outside of the Colvars module " + cvm::error_static("Error: initializing a group outside of the Colvars module " "is currently not supported.\n", COLVARS_NOT_IMPLEMENTED); return COLVARS_NOT_IMPLEMENTED; @@ -206,7 +206,7 @@ int colvarproxy_atom_groups::init_atom_group(std::vector const & /* atoms_i void colvarproxy_atom_groups::clear_atom_group(int index) { if (((size_t) index) >= atom_groups_ids.size()) { - cvm::error("Error: trying to disable an atom group " + cvm::error_static("Error: trying to disable an atom group " "that was not previously requested.\n", COLVARS_INPUT_ERROR); } @@ -300,14 +300,14 @@ int colvarproxy_smp::smp_loop(int n_items, std::function const &worke { int error_code = COLVARS_OK; #if defined(_OPENMP) - cvm::increase_depth(); + cvm::main()->increase_depth(); #pragma omp parallel for for (int i = 0; i < n_items; i++) { int const retcode = worker(i); #pragma omp atomic error_code |= retcode; } - cvm::decrease_depth(); + cvm::main()->decrease_depth(); #else error_code |= COLVARS_NOT_IMPLEMENTED; #endif @@ -318,20 +318,19 @@ int colvarproxy_smp::smp_loop(int n_items, std::function const &worke int colvarproxy_smp::smp_biases_loop() { #if defined(_OPENMP) - colvarmodule *cv = cvm::main(); #pragma omp parallel { #pragma omp for - for (int i = 0; i < static_cast(cv->biases_active()->size()); i++) { - colvarbias *b = (*(cv->biases_active()))[i]; - if (cvm::debug()) { - cvm::log("Calculating bias \""+b->name+"\" on thread "+ + for (int i = 0; i < static_cast(cvm::main()->biases_active()->size()); i++) { + colvarbias *b = (*(cvm::main()->biases_active()))[i]; + if (cvm::main()->debug()) { + cvm::main()->log("Calculating bias \""+b->name+"\" on thread "+ cvm::to_str(smp_thread_id())+"\n"); } b->update(); } } - return cvm::get_error(); + return cvm::main()->get_error(); #else return COLVARS_NOT_IMPLEMENTED; #endif @@ -341,24 +340,23 @@ int colvarproxy_smp::smp_biases_loop() int colvarproxy_smp::smp_biases_script_loop() { #if defined(_OPENMP) - colvarmodule *cv = cvm::main(); #pragma omp parallel { #pragma omp single nowait { - cv->calc_scripted_forces(); + cvm::main()->calc_scripted_forces(); } #pragma omp for - for (int i = 0; i < static_cast(cv->biases_active()->size()); i++) { - colvarbias *b = (*(cv->biases_active()))[i]; - if (cvm::debug()) { - cvm::log("Calculating bias \""+b->name+"\" on thread "+ + for (int i = 0; i < static_cast(cvm::main()->biases_active()->size()); i++) { + colvarbias *b = (*(cvm::main()->biases_active()))[i]; + if (cvm::main()->debug()) { + cvm::main()->log("Calculating bias \""+b->name+"\" on thread "+ cvm::to_str(smp_thread_id())+"\n"); } b->update(); } } - return cvm::get_error(); + return cvm::main()->get_error(); #else return COLVARS_NOT_IMPLEMENTED; #endif @@ -457,7 +455,7 @@ int colvarproxy_script::run_colvar_gradient_callback(std::string const & /* name colvarproxy::colvarproxy() { - colvars = NULL; + cvmodule = NULL; // By default, simulation engines allow to immediately request atoms engine_ready_ = true; b_simulation_running = true; @@ -472,9 +470,9 @@ colvarproxy::colvarproxy() colvarproxy::~colvarproxy() { close_output_streams(); - if (colvars != NULL) { - delete colvars; - colvars = NULL; + if (cvmodule != NULL) { + delete cvmodule; + cvmodule = NULL; } delete reinterpret_cast > *>(config_queue_); } @@ -491,7 +489,7 @@ bool colvarproxy::io_available() int colvarproxy::reset() { if (cvm::debug()) { - cvm::log("colvarproxy::reset()\n"); + cvmodule->log("colvarproxy::reset()\n"); } int error_code = COLVARS_OK; error_code |= colvarproxy_atoms::reset(); @@ -504,7 +502,7 @@ int colvarproxy::reset() int colvarproxy::request_deletion() { - return cvm::error("Error: \"delete\" command is only available in VMD; " + return cvmodule->error("Error: \"delete\" command is only available in VMD; " "please use \"reset\" instead.\n", COLVARS_NOT_IMPLEMENTED); } @@ -530,11 +528,11 @@ int colvarproxy::parse_module_config() while (config_queue->size() > 0) { std::pair const &p = config_queue->front(); if (p.first == "config") { - error_code |= colvars->read_config_string(p.second); + error_code |= cvmodule->read_config_string(p.second); } else if (p.first == "configfile") { - error_code |= colvars->read_config_file(p.second.c_str()); + error_code |= cvmodule->read_config_file(p.second.c_str()); } else { - error_code |= cvm::error(std::string("Error: invalid keyword \"") + + error_code |= cvmodule->error(std::string("Error: invalid keyword \"") + p.first + std::string("\" in colvarproxy::setup()\n"), COLVARS_BUG_ERROR); @@ -549,7 +547,7 @@ int colvarproxy::load_atoms_pdb(char const * /* filename */, std::string const & /* pdb_field */, double /* pdb_field_value */) { - return cvm::error( + return cvmodule->error( "Error: loading atom indices from a PDB file is currently not implemented in " + engine_name() + ".\n", COLVARS_NOT_IMPLEMENTED); @@ -561,7 +559,7 @@ int colvarproxy::load_coords_pdb(char const * /* filename */, std::string const & /* pdb_field */, double /* pdb_field_value */) { - return cvm::error( + return cvmodule->error( "Error: loading atomic coordinates from a PDB file is currently not implemented in " + engine_name() + ".\n", COLVARS_NOT_IMPLEMENTED); @@ -604,9 +602,9 @@ int colvarproxy::end_of_step() int colvarproxy::post_run() { int error_code = COLVARS_OK; - if (colvars->output_prefix().size()) { - error_code |= colvars->write_restart_file(cvm::output_prefix()+".colvars.state"); - error_code |= colvars->write_output_files(); + if (cvmodule->output_prefix().size()) { + error_code |= cvmodule->write_restart_file(cvmodule->output_prefix()+".colvars.state"); + error_code |= cvmodule->write_output_files(); } error_code |= flush_output_streams(); return error_code; @@ -615,108 +613,108 @@ int colvarproxy::post_run() void colvarproxy::print_input_atomic_data() { - cvm::log(cvm::line_marker); + cvmodule->log(cvmodule->line_marker); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "atoms_ids[size = "+cvm::to_str(atoms_ids.size())+ "] = "+cvm::to_str(atoms_ids)+"\n"); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "atoms_refcount[size = "+cvm::to_str(atoms_refcount.size())+ "] = "+cvm::to_str(atoms_refcount)+"\n"); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "atoms_masses[size = "+cvm::to_str(atoms_masses.size())+ "] = "+cvm::to_str(atoms_masses)+"\n"); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "atoms_charges[size = "+cvm::to_str(atoms_charges.size())+ "] = "+cvm::to_str(atoms_charges)+"\n"); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "atoms_positions[size = "+cvm::to_str(atoms_positions.size())+ "] = "+cvm::to_str(atoms_positions, - cvm::cv_width, - cvm::cv_prec)+"\n"); + cvmodule->cv_width, + cvmodule->cv_prec)+"\n"); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "atoms_total_forces[size = "+ cvm::to_str(atoms_total_forces.size())+ "] = "+cvm::to_str(atoms_total_forces, - cvm::cv_width, - cvm::cv_prec)+"\n"); + cvmodule->cv_width, + cvmodule->cv_prec)+"\n"); - cvm::log(cvm::line_marker); + cvmodule->log(cvmodule->line_marker); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "atom_groups_ids[size = "+cvm::to_str(atom_groups_ids.size())+ "] = "+cvm::to_str(atom_groups_ids)+"\n"); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "atom_groups_refcount[size = "+ cvm::to_str(atom_groups_refcount.size())+ "] = "+cvm::to_str(atom_groups_refcount)+"\n"); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "atom_groups_masses[size = "+ cvm::to_str(atom_groups_masses.size())+ "] = "+cvm::to_str(atom_groups_masses)+"\n"); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "atom_groups_charges[size = "+ cvm::to_str(atom_groups_charges.size())+ "] = "+cvm::to_str(atom_groups_charges)+"\n"); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "atom_groups_coms[size = "+ cvm::to_str(atom_groups_coms.size())+ "] = "+cvm::to_str(atom_groups_coms, - cvm::cv_width, - cvm::cv_prec)+"\n"); + cvmodule->cv_width, + cvmodule->cv_prec)+"\n"); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "atom_groups_total_forces[size = "+ cvm::to_str(atom_groups_total_forces.size())+ "] = "+cvm::to_str(atom_groups_total_forces, - cvm::cv_width, - cvm::cv_prec)+"\n"); + cvmodule->cv_width, + cvmodule->cv_prec)+"\n"); - cvm::log(cvm::line_marker); + cvmodule->log(cvmodule->line_marker); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "volmaps_ids[size = "+cvm::to_str(volmaps_ids.size())+ "] = "+cvm::to_str(volmaps_ids)+"\n"); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "volmaps_values[size = "+cvm::to_str(volmaps_values.size())+ "] = "+cvm::to_str(volmaps_values)+"\n"); - cvm::log(cvm::line_marker); + cvmodule->log(cvmodule->line_marker); } void colvarproxy::print_output_atomic_data() { - cvm::log(cvm::line_marker); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log(cvmodule->line_marker); + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "atoms_new_colvar_forces = "+cvm::to_str(atoms_new_colvar_forces, - colvarmodule::cv_width, - colvarmodule::cv_prec)+"\n"); - cvm::log(cvm::line_marker); + cvmodule->cv_width, + cvmodule->cv_prec)+"\n"); + cvmodule->log(cvmodule->line_marker); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "atom_groups_new_colvar_forces = "+ cvm::to_str(atom_groups_new_colvar_forces, - colvarmodule::cv_width, - colvarmodule::cv_prec)+"\n"); + cvmodule->cv_width, + cvmodule->cv_prec)+"\n"); - cvm::log(cvm::line_marker); + cvmodule->log(cvmodule->line_marker); - cvm::log("Step "+cvm::to_str(cvm::step_absolute())+", "+ + cvmodule->log("Step "+cvm::to_str(cvmodule->step_absolute())+", "+ "volmaps_new_colvar_forces = "+ cvm::to_str(volmaps_new_colvar_forces)+"\n"); - cvm::log(cvm::line_marker); + cvmodule->log(cvmodule->line_marker); } diff --git a/src/colvarproxy.h b/src/colvarproxy.h index a1e99eff0..bca1a516d 100644 --- a/src/colvarproxy.h +++ b/src/colvarproxy.h @@ -144,7 +144,7 @@ class colvarproxy_atoms { /// Read the current velocity of the given atom inline cvm::rvector get_atom_velocity(int /* index */) { - cvm::error("Error: reading the current velocity of an atom " + cvm::error_static("Error: reading the current velocity of an atom " "is not yet implemented.\n", COLVARS_NOT_IMPLEMENTED); return cvm::rvector(0.0); @@ -363,7 +363,7 @@ class colvarproxy_atom_groups { /// Read the current velocity of the given atom group inline cvm::rvector get_atom_group_velocity(int /* index */) { - cvm::error("Error: reading the current velocity of an atom group is not yet implemented.\n", + cvm::error_static("Error: reading the current velocity of an atom group is not yet implemented.\n", COLVARS_NOT_IMPLEMENTED); return cvm::rvector(0.0); } @@ -511,7 +511,7 @@ class colvarproxy_smp { omp_lock_t *omp_lock_state; /// Whether threaded parallelization should be used (TODO: make this a - /// cvm::deps feature) + /// cvmodule->deps feature) smp_mode_t smp_mode; }; @@ -568,8 +568,8 @@ class colvarproxy public: - /// Pointer to the main object - colvarmodule *colvars; + /// Pointer to the associated colvarmodule object + colvarmodule *cvmodule; /// Constructor colvarproxy(); diff --git a/src/colvarproxy_io.cpp b/src/colvarproxy_io.cpp index ecfeec6ae..015a7699e 100644 --- a/src/colvarproxy_io.cpp +++ b/src/colvarproxy_io.cpp @@ -100,7 +100,7 @@ std::string colvarproxy_io::get_current_work_dir() const #endif if (getcwd_result == nullptr) { - cvm::error("Error: cannot read the current working directory.\n", COLVARS_INPUT_ERROR); + cvm::error_static("Error: cannot read the current working directory.\n", COLVARS_INPUT_ERROR); return std::string(""); } @@ -145,7 +145,7 @@ int colvarproxy_io::backup_file(char const *filename) // File does not exist return COLVARS_OK; } else { - return cvm::error("Unknown error while checking if file \""+ + return cvm::error_static("Unknown error while checking if file \""+ std::string(filename)+"\" exists.\n", COLVARS_ERROR); } } @@ -185,7 +185,7 @@ int colvarproxy_io::remove_file(char const *filename) } #endif if (error_code != COLVARS_OK) { - return cvm::error("Error: in removing file \""+std::string(filename)+ + return cvm::error_static("Error: in removing file \""+std::string(filename)+ "\".\n.", error_code); } @@ -206,7 +206,7 @@ int colvarproxy_io::rename_file(char const *filename, char const *newfilename) while ((rename_exit_code = std::rename(filename, newfilename)) != 0) { if (errno == EINTR) continue; // Call log() instead of error to allow the next try - cvm::log("Error: in renaming file \""+std::string(filename)+"\" to \""+ + cvm::main()->log("Error: in renaming file \""+std::string(filename)+"\" to \""+ std::string(newfilename)+"\".\n."); error_code |= COLVARS_FILE_ERROR; if (errno == EXDEV) continue; @@ -266,7 +266,7 @@ std::istream &colvarproxy_io::input_stream(std::string const &input_name, bool error_on_fail) { if (!io_available()) { - cvm::error("Error: trying to access an input file/channel " + cvm::error_static("Error: trying to access an input file/channel " "from the wrong thread.\n", COLVARS_BUG_ERROR); return *input_stream_error_; } @@ -286,7 +286,7 @@ std::istream &colvarproxy_io::input_stream(std::string const &input_name, } if (input_streams_[input_name]->fail() && error_on_fail) { - cvm::error("Error: cannot open "+description+" \""+input_name+"\".\n", + cvm::error_static("Error: cannot open "+description+" \""+input_name+"\".\n", COLVARS_FILE_ERROR); } @@ -300,7 +300,7 @@ colvarproxy_io::input_stream_from_string(std::string const &input_name, std::string const description) { if (!io_available()) { - cvm::error("Error: trying to access an input file/channel " + cvm::error_static("Error: trying to access an input file/channel " "from the wrong thread.\n", COLVARS_BUG_ERROR); return *input_stream_error_; } @@ -353,7 +353,7 @@ int colvarproxy_io::close_input_stream(std::string const &input_name) } return COLVARS_OK; } - return cvm::error("Error: input file/channel \""+input_name+ + return cvm::error_static("Error: input file/channel \""+input_name+ "\" does not exist.\n", COLVARS_FILE_ERROR); } @@ -373,7 +373,7 @@ int colvarproxy_io::delete_input_stream(std::string const &input_name) input_streams_.erase(input_name); return COLVARS_OK; } - return cvm::error("Error: input file/channel \""+input_name+ + return cvm::error_static("Error: input file/channel \""+input_name+ "\" does not exist.\n", COLVARS_FILE_ERROR); } @@ -408,11 +408,11 @@ std::ostream & colvarproxy_io::output_stream(std::string const &output_name, std::string const description) { if (cvm::debug()) { - cvm::log("Using colvarproxy_io::output_stream()\n"); + cvm::main()->log("Using colvarproxy_io::output_stream()\n"); } if (!io_available()) { - cvm::error("Error: trying to access an output file/channel " + cvm::error_static("Error: trying to access an output file/channel " "from the wrong thread.\n", COLVARS_BUG_ERROR); return *output_stream_error_; } @@ -425,7 +425,7 @@ std::ostream & colvarproxy_io::output_stream(std::string const &output_name, output_streams_[output_name] = new std::ofstream(output_name.c_str(), std::ios::binary); if (!*(output_streams_[output_name])) { - cvm::error("Error: cannot write to "+description+" \""+output_name+"\".\n", + cvm::error_static("Error: cannot write to "+description+" \""+output_name+"\".\n", COLVARS_FILE_ERROR); } @@ -474,7 +474,7 @@ int colvarproxy_io::flush_output_streams() int colvarproxy_io::close_output_stream(std::string const &output_name) { if (!io_available()) { - return cvm::error("Error: trying to access an output file/channel " + return cvm::error_static("Error: trying to access an output file/channel " "from the wrong thread.\n", COLVARS_BUG_ERROR); } diff --git a/src/colvarproxy_io.h b/src/colvarproxy_io.h index eaf750366..2d2492a0c 100644 --- a/src/colvarproxy_io.h +++ b/src/colvarproxy_io.h @@ -34,7 +34,7 @@ class colvarproxy_io { // Returns error code virtual int get_frame(long int &); - /// \brief Set the current frame number (as well as colvarmodule::it) + /// \brief Set the current frame number (as well as cvmodule->it) // Returns error code virtual int set_frame(long int); diff --git a/src/colvarproxy_replicas.cpp b/src/colvarproxy_replicas.cpp index ec7ffdd8d..342ad3752 100644 --- a/src/colvarproxy_replicas.cpp +++ b/src/colvarproxy_replicas.cpp @@ -30,7 +30,7 @@ void colvarproxy_replicas::set_replicas_mpi_communicator(replicas_mpi_comm_t com if (comm != MPI_COMM_NULL) { MPI_Comm_rank(comm, &replicas_mpi_rank); MPI_Comm_size(comm, &replicas_mpi_num); - cvm::log("Enabling multiple replicas: this is replica number " + + cvm::log_static("Enabling multiple replicas: this is replica number " + cvm::to_str(replica_index() + 1) + " of " + cvm::to_str(num_replicas()) + ".\n"); } #endif diff --git a/src/colvarproxy_system.cpp b/src/colvarproxy_system.cpp index 401bb4c59..e8a8e51cb 100644 --- a/src/colvarproxy_system.cpp +++ b/src/colvarproxy_system.cpp @@ -72,7 +72,7 @@ void colvarproxy_system::add_energy(cvm::real /* energy */) {} void colvarproxy_system::request_total_force(bool yesno) { if (yesno == true) - cvm::error("Error: total forces are currently not implemented.\n", + cvm::error_static("Error: total forces are currently not implemented.\n", COLVARS_NOT_IMPLEMENTED); } @@ -101,7 +101,7 @@ void colvarproxy_system::update_pbc_lattice() if (boundaries_type == boundaries_unsupported || boundaries_type == boundaries_non_periodic) { - cvm::error("Error: setting PBC lattice with unsupported boundaries.\n", + cvm::error_static("Error: setting PBC lattice with unsupported boundaries.\n", COLVARS_BUG_ERROR); return; } @@ -137,7 +137,7 @@ cvm::rvector colvarproxy_system::position_distance(cvm::atom_pos const &pos1, const { if (boundaries_type == boundaries_unsupported) { - cvm::error("Error: unsupported boundary conditions.\n", COLVARS_INPUT_ERROR); + cvm::error_static("Error: unsupported boundary conditions.\n", COLVARS_INPUT_ERROR); } cvm::rvector diff = (pos2 - pos1); @@ -161,7 +161,7 @@ cvm::rvector colvarproxy_system::position_distance(cvm::atom_pos const &pos1, int colvarproxy_system::get_molid(int &) { - cvm::error("Error: only VMD allows the use of multiple \"molecules\", " + cvm::error_static("Error: only VMD allows the use of multiple \"molecules\", " "i.e. multiple molecular systems.", COLVARS_NOT_IMPLEMENTED); return -1; } @@ -169,7 +169,7 @@ int colvarproxy_system::get_molid(int &) int colvarproxy_system::get_alch_lambda(cvm::real * /* lambda */) { - return cvm::error("Error in get_alch_lambda: alchemical lambda dynamics is not supported by this build.", + return cvm::error_static("Error in get_alch_lambda: alchemical lambda dynamics is not supported by this build.", COLVARS_NOT_IMPLEMENTED); } @@ -183,27 +183,27 @@ void colvarproxy_system::set_alch_lambda(cvm::real lambda) int colvarproxy_system::send_alch_lambda() { - return cvm::error("Error in set_alch_lambda: alchemical lambda dynamics is not supported by this build.", + return cvm::error_static("Error in set_alch_lambda: alchemical lambda dynamics is not supported by this build.", COLVARS_NOT_IMPLEMENTED); } int colvarproxy_system::get_dE_dlambda(cvm::real * /* force */) { - return cvm::error("Error in get_dE_dlambda: alchemical lambda dynamics is not supported by this build.", + return cvm::error_static("Error in get_dE_dlambda: alchemical lambda dynamics is not supported by this build.", COLVARS_NOT_IMPLEMENTED); } int colvarproxy_system::apply_force_dE_dlambda(cvm::real* /* force */) { - return cvm::error("Error in apply_force_dE_dlambda: function is not implemented by this build.", + return cvm::error_static("Error in apply_force_dE_dlambda: function is not implemented by this build.", COLVARS_NOT_IMPLEMENTED); } int colvarproxy_system::get_d2E_dlambda2(cvm::real*) { - return cvm::error("Error in get_d2E_dlambda2: function is not implemented by this build.", + return cvm::error_static("Error in get_d2E_dlambda2: function is not implemented by this build.", COLVARS_NOT_IMPLEMENTED); } diff --git a/src/colvarproxy_system.h b/src/colvarproxy_system.h index 38f3b5a64..b746ef99f 100644 --- a/src/colvarproxy_system.h +++ b/src/colvarproxy_system.h @@ -138,7 +138,7 @@ class colvarproxy_system { /// Get weight factor from accelMD virtual cvm::real get_accelMD_factor() const { - cvm::error("Error: accessing the reweighting factor of accelerated MD " + cvm::error_static("Error: accessing the reweighting factor of accelerated MD " "is not yet implemented in the MD engine.\n", COLVARS_NOT_IMPLEMENTED); return 1.0; diff --git a/src/colvarproxy_tcl.cpp b/src/colvarproxy_tcl.cpp index a97fa955b..390c4f3bf 100644 --- a/src/colvarproxy_tcl.cpp +++ b/src/colvarproxy_tcl.cpp @@ -23,7 +23,7 @@ colvarproxy_tcl::colvarproxy_tcl() { - tcl_interp_ = NULL; + tcl_interp_ = nullptr; } @@ -36,15 +36,16 @@ void colvarproxy_tcl::init_tcl_pointers() { // This is overloaded by NAMD and VMD proxies to use the local interpreters #if defined(COLVARS_TCL) - if (tcl_interp_ == NULL) { + if (tcl_interp_ == nullptr) { // Allocate a dedicated Tcl interpreter for Colvars - cvm::log("colvars: Allocating Tcl interpreter.\n"); + // We may not have an allocated module yet + cvm::log_static("Allocating Tcl interpreter.\n"); set_tcl_interp(Tcl_CreateInterp()); } else { - cvm::error("Error: init_tcl_pointers called with non-NULL tcl_interp_\n"); + cvm::error_static("Error: init_tcl_pointers called with non-NULL tcl_interp_\n"); } #else - cvm::error("Error: Tcl support is not available in this build.\n"); + cvm::error_static("Error: Tcl support is not available in this build.\n"); #endif } @@ -66,11 +67,11 @@ int colvarproxy_tcl::tcl_run_script(std::string const &script) Tcl_Interp *const interp = get_tcl_interp(); int err = Tcl_Eval(interp, script.c_str()); if (err != TCL_OK) { - cvm::log("Error while executing Tcl script:\n"); - cvm::error(Tcl_GetStringResult(interp)); + cvm::main()->log("Error while executing Tcl script:\n"); + cvm::error_static(Tcl_GetStringResult(interp)); return COLVARS_ERROR; } - return cvm::get_error(); + return cvm::main()->get_error(); #else return COLVARS_NOT_IMPLEMENTED; #endif @@ -83,11 +84,11 @@ int colvarproxy_tcl::tcl_run_file(std::string const &fileName) Tcl_Interp *const interp = get_tcl_interp(); int err = Tcl_EvalFile(interp, fileName.c_str()); if (err != TCL_OK) { - cvm::log("Error while executing Tcl script file \"" + fileName + "\":\n"); - cvm::error(Tcl_GetStringResult(interp)); + cvm::main()->log("Error while executing Tcl script file \"" + fileName + "\":\n"); + cvm::error_static(Tcl_GetStringResult(interp)); return COLVARS_ERROR; } - return cvm::get_error(); + return cvm::main()->get_error(); #else return COLVARS_NOT_IMPLEMENTED; #endif @@ -99,19 +100,19 @@ int colvarproxy_tcl::tcl_run_force_callback() #if defined(COLVARS_TCL) Tcl_Interp *const interp = get_tcl_interp(); if (Tcl_FindCommand(interp, "calc_colvar_forces", NULL, 0) == NULL) { - cvm::error("Error: Colvars force procedure calc_colvar_forces is not defined.\n"); + cvm::error_static("Error: Colvars force procedure calc_colvar_forces is not defined.\n"); return COLVARS_ERROR; } std::string cmd = std::string("calc_colvar_forces ") - + cvm::to_str(cvm::step_absolute()); + + cvm::to_str(cvm::main()->step_absolute()); int err = Tcl_Eval(interp, cmd.c_str()); if (err != TCL_OK) { - cvm::log("Error while executing calc_colvar_forces:\n"); - cvm::error(Tcl_GetStringResult(interp)); + cvm::main()->log("Error while executing calc_colvar_forces:\n"); + cvm::error_static(Tcl_GetStringResult(interp)); return COLVARS_ERROR; } - return cvm::get_error(); + return cvm::main()->get_error(); #else return COLVARS_NOT_IMPLEMENTED; #endif @@ -130,7 +131,7 @@ int colvarproxy_tcl::tcl_run_colvar_callback( std::string cmd = std::string("calc_") + name; if (Tcl_FindCommand(interp, cmd.c_str(), NULL, 0) == NULL) { - cvm::error("Error: scripted colvar procedure \"" + cmd + "\" is not defined.\n"); + cvm::error_static("Error: scripted colvar procedure \"" + cmd + "\" is not defined.\n"); return COLVARS_ERROR; } @@ -141,18 +142,18 @@ int colvarproxy_tcl::tcl_run_colvar_callback( int err = Tcl_Eval(interp, cmd.c_str()); const char *result = Tcl_GetStringResult(interp); if (err != TCL_OK) { - return cvm::error(std::string("Error while executing ") + return cvm::error_static(std::string("Error while executing ") + cmd + std::string(":\n") + std::string(Tcl_GetStringResult(interp)), COLVARS_ERROR); } std::istringstream is(result); if (value.from_simple_string(is.str()) != COLVARS_OK) { - cvm::log("Error parsing colvar value from script:"); - cvm::error(result); + cvm::main()->log("Error parsing colvar value from script:"); + cvm::error_static(result); return COLVARS_ERROR; } - return cvm::get_error(); + return cvm::main()->get_error(); #else @@ -177,7 +178,7 @@ int colvarproxy_tcl::tcl_run_colvar_gradient_callback( std::string cmd = std::string("calc_") + name + "_gradient"; if (Tcl_FindCommand(interp, cmd.c_str(), NULL, 0) == NULL) { - cvm::error("Error: scripted colvar gradient procedure \"" + cmd + "\" is not defined.\n"); + cvm::error_static("Error: scripted colvar gradient procedure \"" + cmd + "\" is not defined.\n"); return COLVARS_ERROR; } @@ -187,7 +188,7 @@ int colvarproxy_tcl::tcl_run_colvar_gradient_callback( } int err = Tcl_Eval(interp, cmd.c_str()); if (err != TCL_OK) { - return cvm::error(std::string("Error while executing ") + return cvm::error_static(std::string("Error while executing ") + cmd + std::string(":\n") + std::string(Tcl_GetStringResult(interp)), COLVARS_ERROR); @@ -197,7 +198,7 @@ int colvarproxy_tcl::tcl_run_colvar_gradient_callback( Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp), &n, &list); if (n != int(gradient.size())) { - cvm::error("Error parsing list of gradient values from script: found " + cvm::error_static("Error parsing list of gradient values from script: found " + cvm::to_str(n) + " values instead of " + cvm::to_str(gradient.size())); return COLVARS_ERROR; @@ -205,14 +206,14 @@ int colvarproxy_tcl::tcl_run_colvar_gradient_callback( for (i = 0; i < gradient.size(); i++) { std::istringstream is(Tcl_GetString(list[i])); if (gradient[i].from_simple_string(is.str()) != COLVARS_OK) { - cvm::log("Gradient matrix size: " + cvm::to_str(gradient[i].size())); - cvm::log("Gradient string: " + cvm::to_str(Tcl_GetString(list[i]))); - cvm::error("Error parsing gradient value from script", COLVARS_ERROR); + cvm::main()->log("Gradient matrix size: " + cvm::to_str(gradient[i].size())); + cvm::main()->log("Gradient string: " + cvm::to_str(Tcl_GetString(list[i]))); + cvm::error_static("Error parsing gradient value from script", COLVARS_ERROR); return COLVARS_ERROR; } } - return cvm::get_error(); + return cvm::main()->get_error(); #else diff --git a/src/colvarproxy_volmaps.cpp b/src/colvarproxy_volmaps.cpp index deda874a8..a96d8e825 100644 --- a/src/colvarproxy_volmaps.cpp +++ b/src/colvarproxy_volmaps.cpp @@ -52,14 +52,14 @@ int colvarproxy_volmaps::add_volmap_slot(int volmap_id) int colvarproxy_volmaps::check_volmap_by_id(int /* volmap_id */) { - return cvm::error("Error: selecting volumetric maps is not available.\n", + return cvm::error_static("Error: selecting volumetric maps is not available.\n", COLVARS_NOT_IMPLEMENTED); } int colvarproxy_volmaps::check_volmap_by_name(const char * /* volmap_name */) { - return cvm::error("Error: selecting volumetric maps by name is not " + return cvm::error_static("Error: selecting volumetric maps by name is not " "available.\n", COLVARS_NOT_IMPLEMENTED); } @@ -91,7 +91,7 @@ int colvarproxy_volmaps::check_volmap_by_name(std::string const &volmap_name) void colvarproxy_volmaps::clear_volmap(int index) { if (((size_t) index) >= volmaps_ids.size()) { - cvm::error("Error: trying to unrequest a volumetric map that was not " + cvm::error_static("Error: trying to unrequest a volumetric map that was not " "previously requested.\n", COLVARS_INPUT_ERROR); } diff --git a/src/colvarscript.cpp b/src/colvarscript.cpp index 5c0b837d9..ae5155cd8 100644 --- a/src/colvarscript.cpp +++ b/src/colvarscript.cpp @@ -2,7 +2,7 @@ // This file is part of the Collective Variables module (Colvars). // The original version of Colvars and its updates are located at: -// https://github.com/Colvars/colvars +// https://github.com/Colvars/cvmodule // Please update all Colvars source files before making any changes. // If you wish to distribute your changes, please submit them to the // Colvars repository at GitHub. @@ -31,7 +31,7 @@ extern "C" int tcl_run_colvarscript_command(ClientData clientData, colvarscript::colvarscript(colvarproxy *p, colvarmodule *m) : proxy_(p), - colvars(m) + cvmodule(m) { cmdline_main_cmd_ = std::string("cv"); cmd_names = NULL; @@ -42,13 +42,14 @@ colvarscript::colvarscript(colvarproxy *p, colvarmodule *m) // TODO put this in backend functions so we don't have to delete Tcl_Interp *const interp = proxy()->get_tcl_interp(); if (interp == NULL) { - cvm::error("Error: trying to construct colvarscript without a Tcl interpreter.\n"); + cvm::error_static("Error: trying to construct colvarscript without a Tcl interpreter.\n"); return; } - Tcl_DeleteCommand(interp, "cv"); + bool deleted = (Tcl_DeleteCommand(interp, "cv") == TCL_OK); Tcl_CreateObjCommand(interp, "cv", tcl_run_colvarscript_command, (ClientData) this, (Tcl_CmdDeleteProc *) NULL); - cvm::log("Redefining the Tcl \"cv\" command to the new script interface.\n"); + if (deleted) + cvmodule->log("Redefining the Tcl \"cv\" command to the new script interface.\n"); #endif } @@ -65,7 +66,7 @@ colvarscript::~colvarscript() int colvarscript::init_commands() { if (cvm::debug()) { - cvm::log("Called colvarcript::init_commands()\n"); + cvmodule->log("Called colvarscript::init_commands()\n"); } cmd_help.resize(colvarscript::cv_n_commands); @@ -132,7 +133,7 @@ int colvarscript::init_command(colvarscript::command const &comm, std::string line; for (int iarg = 0; iarg < n_args_max; iarg++) { if (! std::getline(is, line)) { - return cvm::error("Error: could not initialize help string for scripting " + return cvm::error_static("Error: could not initialize help string for scripting " "command \""+std::string(name)+"\".\n", COLVARS_BUG_ERROR); } cmd_arghelp[comm].push_back(line); @@ -159,8 +160,8 @@ int colvarscript::init_command(colvarscript::command const &comm, cmd_fns[comm] = fn; if (cvm::debug()) { - cvm::log("Defined command \""+std::string(name)+"\", with help string:\n"); - cvm::log(get_command_full_help(name)); + cvmodule->log("Defined command \""+std::string(name)+"\", with help string:\n"); + cvmodule->log(get_command_full_help(name)); } return COLVARS_OK; @@ -177,7 +178,7 @@ std::string colvarscript::get_cmd_prefix(colvarscript::Object_type t) case use_bias: return std::string("bias_"); break; default: - cvm::error("Error: undefined colvarscript object type.", COLVARS_BUG_ERROR); + cvm::error_static("Error: undefined colvarscript object type.", COLVARS_BUG_ERROR); return std::string(""); } } @@ -190,7 +191,7 @@ char const *colvarscript::get_command_help(char const *cmd) colvarscript::command const c = cmd_str_map[std::string(cmd)]; return cmd_help[c].c_str(); } - cvm::error("Error: command "+std::string(cmd)+ + cvm::error_static("Error: command "+std::string(cmd)+ " is not implemented.\n", COLVARS_INPUT_ERROR); return NULL; } @@ -202,7 +203,7 @@ char const *colvarscript::get_command_rethelp(char const *cmd) colvarscript::command const c = cmd_str_map[std::string(cmd)]; return cmd_rethelp[c].c_str(); } - cvm::error("Error: command "+std::string(cmd)+ + cvm::error_static("Error: command "+std::string(cmd)+ " is not implemented.\n", COLVARS_INPUT_ERROR); return NULL; } @@ -214,7 +215,7 @@ char const *colvarscript::get_command_arghelp(char const *cmd, int i) colvarscript::command const c = cmd_str_map[std::string(cmd)]; return cmd_arghelp[c][i].c_str(); } - cvm::error("Error: command "+std::string(cmd)+ + cvm::error_static("Error: command "+std::string(cmd)+ " is not implemented.\n", COLVARS_INPUT_ERROR); return NULL; } @@ -226,7 +227,7 @@ int colvarscript::get_command_n_args_min(char const *cmd) colvarscript::command const c = cmd_str_map[std::string(cmd)]; return cmd_n_args_min[c]; } - cvm::error("Error: command "+std::string(cmd)+ + cvm::error_static("Error: command "+std::string(cmd)+ " is not implemented.\n", COLVARS_INPUT_ERROR); return -1; } @@ -238,7 +239,7 @@ int colvarscript::get_command_n_args_max(char const *cmd) colvarscript::command const c = cmd_str_map[std::string(cmd)]; return cmd_n_args_max[c]; } - cvm::error("Error: command "+std::string(cmd)+ + cvm::error_static("Error: command "+std::string(cmd)+ " is not implemented.\n", COLVARS_INPUT_ERROR); return -1; } @@ -250,7 +251,7 @@ char const *colvarscript::get_command_full_help(char const *cmd) colvarscript::command const c = cmd_str_map[std::string(cmd)]; return cmd_full_help[c].c_str(); } - cvm::error("Error: command "+std::string(cmd)+ + cvm::error_static("Error: command "+std::string(cmd)+ " is not implemented.\n", COLVARS_INPUT_ERROR); return NULL; } @@ -339,7 +340,7 @@ std::string colvarscript::get_command_cmdline_help(colvarscript::Object_type t, return get_command_cmdline_syntax(t, c)+"\n\n"+ get_command_full_help(cmd_names[c]); } - cvm::set_error_bits(COLVARS_INPUT_ERROR); + cvmodule->set_error_bits(COLVARS_INPUT_ERROR); return std::string("Could not find scripting command \""+cmd+"\"."); } @@ -349,9 +350,9 @@ int colvarscript::run(int objc, unsigned char *const objv[]) clear_str_result(); if (cvm::debug()) { - cvm::log("Called script run with " + cvm::to_str(objc) + " args:"); + cvmodule->log("Called script run with " + cvm::to_str(objc) + " args:"); for (int i = 0; i < objc; i++) { - cvm::log(obj_to_str(objv[i])); + cvmodule->log(obj_to_str(objv[i])); } } @@ -385,13 +386,15 @@ int colvarscript::run(int objc, unsigned char *const objv[]) } std::string const name(obj_to_str(objv[2])); std::string const subcmd(obj_to_str(objv[3])); - obj_for_cmd = reinterpret_cast(cvm::colvar_by_name(name)); + obj_for_cmd = reinterpret_cast(cvmodule->colvar_by_name(name)); if (obj_for_cmd == NULL) { if (subcmd != std::string("help")) { // Unless asking for help, a valid colvar name must be given add_error_msg("Colvar not found: " + name); return COLVARSCRIPT_ERROR; } + // Pass script pointer instead + obj_for_cmd = reinterpret_cast(this); } cmd_fn = get_cmd_fn(get_cmd_prefix(use_colvar)+subcmd); cmdline += std::string(" name ")+subcmd; @@ -408,13 +411,15 @@ int colvarscript::run(int objc, unsigned char *const objv[]) } std::string const name(obj_to_str(objv[2])); std::string const subcmd(obj_to_str(objv[3])); - obj_for_cmd = reinterpret_cast(cvm::bias_by_name(name)); + obj_for_cmd = reinterpret_cast(cvmodule->bias_by_name(name)); if (obj_for_cmd == NULL) { if ((subcmd == "") || (subcmd != std::string("help"))) { // Unless asking for help, a valid bias name must be given add_error_msg("Bias not found: " + name); return COLVARSCRIPT_ERROR; } + // Pass script pointer instead + obj_for_cmd = reinterpret_cast(this); } cmd_fn = get_cmd_fn(get_cmd_prefix(use_bias)+subcmd); cmdline += std::string(" name ")+subcmd; @@ -453,7 +458,7 @@ char *colvarscript::obj_to_str(unsigned char *obj) { char *strobj = reinterpret_cast(obj); if (cvm::debug()) { - cvm::log("Using simple-cast script::obj_to_str(): result = \"" + + cvmodule->log("Using simple-cast script::obj_to_str(): result = \"" + (strobj ? std::string(strobj) : std::string("(null)")) + "\""); } return strobj; @@ -463,7 +468,7 @@ char *colvarscript::obj_to_str(unsigned char *obj) std::vector colvarscript::obj_to_str_vector(unsigned char *obj) { if (cvm::debug()) { - cvm::log("Using simple-cast colvarscript::obj_to_str_vector().\n"); + cvmodule->log("Using simple-cast colvarscript::obj_to_str_vector().\n"); } std::vector new_result; @@ -477,7 +482,7 @@ std::vector colvarscript::obj_to_str_vector(unsigned char *obj) if (c == '\"') { i++; if (i >= str.length()) { - cvm::error("Error: could not split the following string:\n"+ + cvm::error_static("Error: could not split the following string:\n"+ str+"\n", COLVARS_INPUT_ERROR); break; } @@ -485,7 +490,7 @@ std::vector colvarscript::obj_to_str_vector(unsigned char *obj) while (str[i] != '\"') { new_result.back().append(1, str[i]); if (i >= str.length()) { - cvm::error("Error: could not split the following string:\n"+ + cvm::error_static("Error: could not split the following string:\n"+ str+"\n", COLVARS_INPUT_ERROR); break; } else { @@ -496,7 +501,7 @@ std::vector colvarscript::obj_to_str_vector(unsigned char *obj) } if (cvm::debug()) { - cvm::log("result = "+cvm::to_str(new_result)+".\n"); + cvmodule->log("result = "+cvm::to_str(new_result)+".\n"); } return new_result; @@ -510,9 +515,9 @@ int colvarscript::proc_features(colvardeps *obj, std::string const subcmd(obj_to_str(objv[3])); if (cvm::debug()) { - cvm::log("Called proc_features() with " + cvm::to_str(objc) + " args:"); + cvmodule->log("Called proc_features() with " + cvm::to_str(objc) + " args:"); for (int i = 0; i < objc; i++) { - cvm::log(obj_to_str(objv[i])); + cvmodule->log(obj_to_str(objv[i])); } } @@ -576,14 +581,14 @@ int colvarscript::proc_features(colvardeps *obj, int colvarscript::unsupported_op() { - return cvm::error("Error: unsupported script operation.\n", + return cvm::error_static("Error: unsupported script operation.\n", COLVARS_NOT_IMPLEMENTED); } int colvarscript::set_result_str(std::string const &s) { - if (cvm::get_error() != COLVARS_OK) { + if (cvmodule->get_error() != COLVARS_OK) { // Avoid overwriting the error message modify_str_result() += s; } else { @@ -611,12 +616,10 @@ int colvarscript::clear_str_result() extern "C" -int run_colvarscript_command(int objc, unsigned char *const objv[]) +int run_colvarscript_command(colvarscript *script, int objc, unsigned char *const objv[]) { - colvarmodule *cv = cvm::main(); - colvarscript *script = cv ? cv->proxy->script : NULL; if (!script) { - cvm::error("Called run_colvarscript_command without a script object.\n", + cvm::error_static("Called run_colvarscript_command without a script object.\n", COLVARS_BUG_ERROR); return -1; } @@ -630,7 +633,7 @@ const char * get_colvarscript_result() { colvarscript *script = colvarscript_obj(); if (!script) { - cvm::error("Called get_colvarscript_result without a script object.\n"); + cvm::error_static("Called get_colvarscript_result without a script object.\n"); return NULL; } return script->str_result().c_str(); @@ -644,16 +647,16 @@ const char * get_colvarscript_result() int tcl_colvars_vmd_init(Tcl_Interp *interp, int molid); #endif + #if !defined(VMDTCL) && !defined(NAMD_TCL) // Initialize Colvars when loaded as a shared library into Tcl interpreter extern "C" { int Colvars_Init(Tcl_Interp *interp) { colvarproxy *proxy = new colvarproxy(); - colvarmodule *colvars = new colvarmodule(proxy); + proxy->cvmodule = new colvarmodule(proxy); proxy->set_tcl_interp(interp); - proxy->colvars = colvars; Tcl_CreateObjCommand(interp, "cv", tcl_run_colvarscript_command, - (ClientData *) NULL, (Tcl_CmdDeleteProc *) NULL); + (ClientData *) proxy->script, (Tcl_CmdDeleteProc *) nullptr); Tcl_EvalEx(interp, "package provide colvars", -1, 0); return TCL_OK; } @@ -661,14 +664,19 @@ extern "C" { #endif -extern "C" int tcl_run_colvarscript_command(ClientData /* clientData */, +extern "C" int tcl_run_colvarscript_command(ClientData clientData, Tcl_Interp *my_interp, int objc, Tcl_Obj *const objv[]) { - colvarmodule *colvars = cvm::main(); + colvarscript *script = colvarscript_obj(clientData); + colvarmodule *cvmodule = nullptr; + + if (!colvarscript::is_valid(script)) { - if (!colvars) { #if defined(VMDTCL) + // In VMD, tell the user to initialize using the script interface + // This code should be moved to a function in colvarproxy_vmd.C + // possibly a general proxy routine for initializing Colvars on demand if (objc == 2) { if (!strcmp(Tcl_GetString(objv[1]), "molid")) { @@ -706,18 +714,27 @@ extern "C" int tcl_run_colvarscript_command(ClientData /* clientData */, Tcl_SetResult(my_interp, (char *) "First, setup the Colvars module with: " "cv molid |top", TCL_STATIC); - + return TCL_OK; + } #else + // Other engines than VMD cannot continue without a valid colvarscript object + char const *errstr = "Error: invalid colvarscript pointer - Colvars may be compiled with an incompatible back-end version.\n"; + Tcl_SetResult(my_interp, const_cast(errstr), TCL_VOLATILE); + return TCL_ERROR; + } +#endif + + cvmodule = script->module(); + if (!cvmodule) { Tcl_SetResult(my_interp, const_cast("Error: Colvars module not yet initialized"), TCL_STATIC); -#endif return TCL_ERROR; } - colvarproxy *proxy = colvars->proxy; + colvarproxy *proxy = cvmodule->proxy; Tcl_Interp *interp = my_interp ? my_interp : proxy->get_tcl_interp(); - colvarscript *script = colvarscript_obj(); + if (!script) { char const *errstr = "Called tcl_run_colvarscript_command " "without a Colvars script interface set up.\n"; @@ -725,7 +742,7 @@ extern "C" int tcl_run_colvarscript_command(ClientData /* clientData */, return TCL_ERROR; } - cvm::clear_error(); + cvmodule->clear_error(); unsigned char * arg_pointers_[100]; if (objc > 100) { diff --git a/src/colvarscript.h b/src/colvarscript.h index e1edb8572..80b24520c 100644 --- a/src/colvarscript.h +++ b/src/colvarscript.h @@ -23,15 +23,28 @@ #define COLVARSCRIPT_ERROR -1 #define COLVARSCRIPT_OK 0 +#define COLVARSCRIPT_MAGIC 0x5349474E class colvardeps; -class colvarscript { +class colvarscript { + +public: + /// This magic number is used to validate colvarscript pointers + uint32_t const magic = COLVARSCRIPT_MAGIC; + + /// Validate colvarscript pointer to catch invalid pointers passed by legacy code + /// e.g. legacy NAMD Tcl interface + static bool is_valid(const colvarscript* script_ptr) { + if (!script_ptr) return false; + // if address is inaccessible, this will sefgault + return script_ptr->magic == COLVARSCRIPT_MAGIC; + } private: colvarproxy *proxy_; - colvarmodule *colvars; + colvarmodule *cvmodule; inline colvarscript() {} // no-argument construction forbidden @@ -191,7 +204,7 @@ class colvarscript { /// Pointer to the Colvars main object inline colvarmodule *module() { - return this->colvars; + return this->cvmodule; } /// Pointer to the colvarproxy object (interface with host engine) @@ -324,13 +337,18 @@ class colvarscript { }; +/// Get a pointer to the colvarscript object pointed to by pobj +inline static colvarscript *colvarscript_obj(void *pobj) +{ + return reinterpret_cast(pobj); +} + /// Get a pointer to the main colvarscript object inline static colvarscript *colvarscript_obj() { return cvm::main()->proxy->script; } - /// Get a pointer to the colvar object pointed to by pobj inline static colvar *colvar_obj(void *pobj) { @@ -447,12 +465,12 @@ int colvarscript::cmd_arg_shift() extern "C" { /// Generic wrapper for string-based scripting - int run_colvarscript_command(int objc, unsigned char *const objv[]); + // New: requires pointer to colvarscript object - TODO - pass it in ctypes Python example + int run_colvarscript_command(colvarscript *script, int objc, unsigned char *const objv[]); /// Get the string result of a script call const char * get_colvarscript_result(); } - #endif // #ifndef COLVARSCRIPT_H diff --git a/src/colvarscript_commands.cpp b/src/colvarscript_commands.cpp index 5db3b96f0..10900561c 100644 --- a/src/colvarscript_commands.cpp +++ b/src/colvarscript_commands.cpp @@ -87,10 +87,11 @@ int cvscript_command_n_args_max(char const *c) int CVSCRIPT_COMM_FNAME(COMM)(void *pobj, \ int objc, unsigned char *const objv[]) \ { \ - if (cvm::debug()) { \ - cvm::log("Executing script function \""+std::string(#COMM)+"\""); \ + colvarscript *script = colvarscript_obj(pobj); \ + colvarmodule *cvmodule = script->module(); \ + if (cvm::debug()) { \ + cvmodule->log("Executing script function \""+std::string(#COMM)+"\""); \ } \ - colvarscript *script = colvarscript_obj(); \ script->clear_str_result(); \ if (script->check_module_cmd_nargs(#COMM, \ objc, N_ARGS_MIN, N_ARGS_MAX) != \ @@ -99,7 +100,6 @@ int cvscript_command_n_args_max(char const *c) } \ if (objc > 1) { \ /* Silence unused parameter warning */ \ - (void) pobj; \ (void) objv[0]; \ } \ FN_BODY; \ diff --git a/src/colvarscript_commands.h b/src/colvarscript_commands.h index d627f27ba..9db6c903b 100644 --- a/src/colvarscript_commands.h +++ b/src/colvarscript_commands.h @@ -103,8 +103,8 @@ CVSCRIPT(cv_addenergy, "E : float - Amount of energy to add", char const *Earg = script->obj_to_str(script->get_module_cmd_arg(0, objc, objv)); - cvm::main()->total_bias_energy += strtod(Earg, NULL); - return cvm::get_error(); // TODO Make this multi-language + script->module()->total_bias_energy += strtod(Earg, NULL); + return script->module()->get_error(); // TODO Make this multi-language ) CVSCRIPT(cv_bias, @@ -307,7 +307,7 @@ CVSCRIPT(cv_getconfig, "conf : string - Current configuration string", 0, 0, "", - script->set_result_str(cvm::main()->get_config()); + script->set_result_str(script->module()->get_config()); return COLVARS_OK; ) @@ -316,7 +316,7 @@ CVSCRIPT(cv_getenergy, "E : float - Amount of energy (internal units)", 0, 0, "", - script->set_result_real(cvm::main()->total_bias_energy); + script->set_result_real(script->module()->total_bias_energy); return COLVARS_OK; ) @@ -352,7 +352,7 @@ CVSCRIPT(cv_getstepabsolute, "step : int - Absolute step number", 0, 0, "", - script->set_result_int(cvm::step_absolute()); + script->set_result_int(script->module()->step_absolute()); return COLVARS_OK; ) @@ -361,7 +361,7 @@ CVSCRIPT(cv_getsteprelative, "step : int - Relative step number", 0, 0, "", - script->set_result_int(cvm::step_relative()); + script->set_result_int(script->module()->step_relative()); return COLVARS_OK; ) @@ -383,7 +383,7 @@ CVSCRIPT(cv_help, script->set_result_str(script->get_command_cmdline_help(colvarscript::use_module, cmdstr)); } - return cvm::get_error(); + return script->module()->get_error(); } else { return COLVARSCRIPT_ERROR; } @@ -488,7 +488,7 @@ CVSCRIPT(cv_load, char const *arg = script->obj_to_str(script->get_module_cmd_arg(0, objc, objv)); int error_code = - script->proxy()->set_input_prefix(cvm::state_file_prefix(arg)); + script->proxy()->set_input_prefix(script->module()->state_file_prefix(arg)); error_code |= script->module()->setup_input(); if (error_code != COLVARS_OK) { script->add_error_msg("Error loading state file"); @@ -546,7 +546,7 @@ CVSCRIPT(cv_patchversion, "version : string - Colvars version", 0, 0, "", - script->set_result_int(cvm::main()->patch_version_number()); + script->set_result_int(script->module()->patch_version_number()); return COLVARS_OK; ) @@ -565,7 +565,7 @@ CVSCRIPT(cv_reset, "Delete all internal configuration", 0, 0, "", - cvm::log("Resetting the Collective Variables module."); + script->module()->log("Resetting the Collective Variables module."); return script->module()->reset(); ) @@ -573,8 +573,8 @@ CVSCRIPT(cv_resetindexgroups, "Clear the index groups loaded so far, allowing to replace them", 0, 0, "", - cvm::main()->index_group_names.clear(); - cvm::main()->index_groups.clear(); + script->module()->index_group_names.clear(); + script->module()->index_groups.clear(); return COLVARS_OK; ) @@ -583,7 +583,7 @@ CVSCRIPT(cv_save, 1, 1, "prefix : string - Output prefix with trailing \".colvars.state\" gets removed)", std::string const prefix = - cvm::state_file_prefix(script->obj_to_str(script->get_module_cmd_arg(0, objc, objv))); + script->module()->state_file_prefix(script->obj_to_str(script->get_module_cmd_arg(0, objc, objv))); int error_code = script->proxy()->set_output_prefix(prefix); error_code |= script->module()->setup_output(); error_code |= script->module()->write_restart_file(prefix+ @@ -636,9 +636,9 @@ CVSCRIPT(cv_units, char const *argstr = script->obj_to_str(script->get_module_cmd_arg(0, objc, objv)); if (argstr) { - return cvm::proxy->set_unit_system(argstr, false); + return script->module()->proxy->set_unit_system(argstr, false); } else { - script->set_result_str(cvm::proxy->units); + script->set_result_str(script->module()->proxy->units); return COLVARS_OK; } ) @@ -669,7 +669,7 @@ CVSCRIPT(cv_version, "version : string - Colvars version", 0, 0, "", - script->set_result_str(cvm::main()->version()); + script->set_result_str(script->module()->version()); return COLVARS_OK; ) diff --git a/src/colvarscript_commands_bias.cpp b/src/colvarscript_commands_bias.cpp index 0efab64a5..ec8ed76fa 100644 --- a/src/colvarscript_commands_bias.cpp +++ b/src/colvarscript_commands_bias.cpp @@ -24,10 +24,19 @@ int CVSCRIPT_COMM_FNAME(COMM)(void *pobj, \ int objc, unsigned char *const objv[]) \ { \ + colvarbias *this_bias = nullptr; \ + colvarmodule *cvmodule = nullptr; \ + if (colvarscript::is_valid(static_cast(pobj))) { \ + colvarscript *script = colvarscript_obj(pobj); \ + cvmodule = script->module(); \ + } else { \ + this_bias = colvarbias_obj(pobj); \ + cvmodule = this_bias->get_cvmodule(); \ + } \ if (cvm::debug()) { \ - cvm::log("Executing script function \""+std::string(#COMM)+"\""); \ + cvmodule->log("Executing script function \""+std::string(#COMM)+"\""); \ } \ - colvarscript *script = colvarscript_obj(); \ + colvarscript *script = cvmodule->proxy->script; \ script->clear_str_result(); \ if (script->check_bias_cmd_nargs(#COMM, \ objc, N_ARGS_MIN, N_ARGS_MAX) != \ @@ -38,7 +47,6 @@ /* Silence unused parameter warning */ \ (void) objv; \ } \ - colvarbias *this_bias = colvarbias_obj(pobj); \ FN_BODY; \ } #undef CVSCRIPT diff --git a/src/colvarscript_commands_bias.h b/src/colvarscript_commands_bias.h index 5cecfcaca..62b44388b 100644 --- a/src/colvarscript_commands_bias.h +++ b/src/colvarscript_commands_bias.h @@ -120,7 +120,7 @@ CVSCRIPT(bias_help, if (cmdstr.size()) { script->set_result_str(script->get_command_cmdline_help(colvarscript::use_bias, cmdstr)); - return cvm::get_error(); + return cvmodule->get_error(); } else { return COLVARSCRIPT_ERROR; } @@ -152,7 +152,7 @@ CVSCRIPT(bias_save, 1, 1, "prefix : string - Prefix for the state file of this bias", std::string const prefix = - cvm::state_file_prefix(script->obj_to_str(script->get_bias_cmd_arg(0, objc, objv))); + cvmodule->state_file_prefix(script->obj_to_str(script->get_bias_cmd_arg(0, objc, objv))); return this_bias->write_state_prefix(prefix); ) diff --git a/src/colvarscript_commands_colvar.cpp b/src/colvarscript_commands_colvar.cpp index 0d03baaa8..e880d6190 100644 --- a/src/colvarscript_commands_colvar.cpp +++ b/src/colvarscript_commands_colvar.cpp @@ -26,10 +26,19 @@ int CVSCRIPT_COMM_FNAME(COMM)(void *pobj, \ int objc, unsigned char *const objv[]) \ { \ + colvar *this_colvar = nullptr; \ + colvarmodule *cvmodule = nullptr; \ + if (colvarscript::is_valid(static_cast(pobj))) { \ + colvarscript *script = colvarscript_obj(pobj); \ + cvmodule = script->module(); \ + } else { \ + this_colvar = colvar_obj(pobj); \ + cvmodule = this_colvar->get_cvmodule(); \ + } \ if (cvm::debug()) { \ - cvm::log("Executing script function \""+std::string(#COMM)+"\""); \ + cvmodule->log("Executing script function \""+std::string(#COMM)+"\""); \ } \ - colvarscript *script = colvarscript_obj(); \ + colvarscript *script = cvmodule->proxy->script; \ script->clear_str_result(); \ if (script->check_colvar_cmd_nargs(#COMM, \ objc, N_ARGS_MIN, N_ARGS_MAX) != \ @@ -38,9 +47,8 @@ } \ if (objc > 1) { \ /* Silence unused parameter warning */ \ - (void) objv[0]; \ + (void) objv[0]; \ } \ - colvar *this_colvar = colvar_obj(pobj); \ FN_BODY; \ } #undef CVSCRIPT diff --git a/src/colvarscript_commands_colvar.h b/src/colvarscript_commands_colvar.h index c641b321d..f11c47465 100644 --- a/src/colvarscript_commands_colvar.h +++ b/src/colvarscript_commands_colvar.h @@ -15,8 +15,8 @@ CVSCRIPT(colvar_addforce, "force : float or array - Applied force; must match colvar dimensionality", std::string const f_str(script->obj_to_str(script->get_colvar_cmd_arg(0, objc, objv))); std::istringstream is(f_str); - is.width(cvm::cv_width); - is.precision(cvm::cv_prec); + is.width(script->module()->cv_width); + is.precision(script->module()->cv_prec); colvarvalue force(this_colvar->value()); force.is_derivative(); if (force.from_simple_string(is.str()) != COLVARS_OK) { @@ -169,7 +169,7 @@ CVSCRIPT(colvar_help, if (cmdstr.size()) { script->set_result_str(script->get_command_cmdline_help(colvarscript::use_colvar, cmdstr)); - return cvm::get_error(); + return script->module()->get_error(); } else { return COLVARSCRIPT_ERROR; } @@ -184,9 +184,9 @@ CVSCRIPT(colvar_modifycvcs, 1, 1, "confs : sequence of strings - New configurations; empty strings are skipped", std::vector const confs(script->obj_to_str_vector(script->get_colvar_cmd_arg(0, objc, objv))); - cvm::increase_depth(); + script->module()->increase_depth(); int res = this_colvar->update_cvc_config(confs); - cvm::decrease_depth(); + script->module()->decrease_depth(); if (res != COLVARS_OK) { script->add_error_msg("Error setting CVC flags"); return COLVARSCRIPT_ERROR; @@ -256,6 +256,6 @@ CVSCRIPT(colvar_width, 0, 0, "", script->set_result_str(cvm::to_str(this_colvar->width, 0, - cvm::cv_prec)); + script->module()->cv_prec)); return COLVARS_OK; ) diff --git a/src/colvartypes.cpp b/src/colvartypes.cpp index a499e5439..d2926930b 100644 --- a/src/colvartypes.cpp +++ b/src/colvartypes.cpp @@ -35,7 +35,7 @@ std::string cvm::rvector::to_simple_string() const { std::ostringstream os; os.setf(std::ios::scientific, std::ios::floatfield); - os.precision(cvm::cv_prec); + os.precision(cvm::main()->cv_prec); os << x << " " << y << " " << z; return os.str(); } @@ -90,7 +90,7 @@ std::string cvm::quaternion::to_simple_string() const { std::ostringstream os; os.setf(std::ios::scientific, std::ios::floatfield); - os.precision(cvm::cv_prec); + os.precision(cvm::main()->cv_prec); os << q0 << " " << q1 << " " << q2 << " " << q3; return os.str(); } @@ -310,21 +310,21 @@ void colvarmodule::rotation::debug_gradients( cvm::quaternion const Q2(rot.S_eigvec[2]); cvm::quaternion const Q3(rot.S_eigvec[3]); - cvm::log("L0 = "+cvm::to_str(L0, cvm::cv_width, cvm::cv_prec)+ - ", Q0 = "+cvm::to_str(Q0, cvm::cv_width, cvm::cv_prec)+ - ", Q0*Q0 = "+cvm::to_str(Q0.inner(Q0), cvm::cv_width, cvm::cv_prec)+ + cvm::log_static("L0 = "+cvm::to_str(L0, cvm::main()->cv_width, cvm::main()->cv_prec)+ + ", Q0 = "+cvm::to_str(Q0, cvm::main()->cv_width, cvm::main()->cv_prec)+ + ", Q0*Q0 = "+cvm::to_str(Q0.inner(Q0), cvm::main()->cv_width, cvm::main()->cv_prec)+ "\n"); - cvm::log("L1 = "+cvm::to_str(L1, cvm::cv_width, cvm::cv_prec)+ - ", Q1 = "+cvm::to_str(Q1, cvm::cv_width, cvm::cv_prec)+ - ", Q0*Q1 = "+cvm::to_str(Q0.inner(Q1), cvm::cv_width, cvm::cv_prec)+ + cvm::log_static("L1 = "+cvm::to_str(L1, cvm::main()->cv_width, cvm::main()->cv_prec)+ + ", Q1 = "+cvm::to_str(Q1, cvm::main()->cv_width, cvm::main()->cv_prec)+ + ", Q0*Q1 = "+cvm::to_str(Q0.inner(Q1), cvm::main()->cv_width, cvm::main()->cv_prec)+ "\n"); - cvm::log("L2 = "+cvm::to_str(L2, cvm::cv_width, cvm::cv_prec)+ - ", Q2 = "+cvm::to_str(Q2, cvm::cv_width, cvm::cv_prec)+ - ", Q0*Q2 = "+cvm::to_str(Q0.inner(Q2), cvm::cv_width, cvm::cv_prec)+ + cvm::log_static("L2 = "+cvm::to_str(L2, cvm::main()->cv_width, cvm::main()->cv_prec)+ + ", Q2 = "+cvm::to_str(Q2, cvm::main()->cv_width, cvm::main()->cv_prec)+ + ", Q0*Q2 = "+cvm::to_str(Q0.inner(Q2), cvm::main()->cv_width, cvm::main()->cv_prec)+ "\n"); - cvm::log("L3 = "+cvm::to_str(L3, cvm::cv_width, cvm::cv_prec)+ - ", Q3 = "+cvm::to_str(Q3, cvm::cv_width, cvm::cv_prec)+ - ", Q0*Q3 = "+cvm::to_str(Q0.inner(Q3), cvm::cv_width, cvm::cv_prec)+ + cvm::log_static("L3 = "+cvm::to_str(L3, cvm::main()->cv_width, cvm::main()->cv_prec)+ + ", Q3 = "+cvm::to_str(Q3, cvm::main()->cv_width, cvm::main()->cv_prec)+ + ", Q0*Q3 = "+cvm::to_str(Q0.inner(Q3), cvm::main()->cv_width, cvm::main()->cv_prec)+ "\n"); rotation_derivative deriv(rot, pos1, pos2, num_atoms_pos1, num_atoms_pos2); cvm::rvector dl0_2; @@ -371,10 +371,10 @@ void colvarmodule::rotation::debug_gradients( dq0_2[2][comp] * colvarmodule::debug_gradients_step_size, dq0_2[3][comp] * colvarmodule::debug_gradients_step_size); - cvm::log( "|(l_0+dl_0) - l_0^new|/l_0 = "+ - cvm::to_str(cvm::fabs(L0+DL0 - L0_new)/L0, cvm::cv_width, cvm::cv_prec)+ + cvm::log_static( "|(l_0+dl_0) - l_0^new|/l_0 = "+ + cvm::to_str(cvm::fabs(L0+DL0 - L0_new)/L0, cvm::main()->cv_width, cvm::main()->cv_prec)+ ", |(q_0+dq_0) - q_0^new| = "+ - cvm::to_str((Q0+DQ0 - Q0_new).norm(), cvm::cv_width, cvm::cv_prec)+ + cvm::to_str((Q0+DQ0 - Q0_new).norm(), cvm::main()->cv_width, cvm::main()->cv_prec)+ "\n"); } } @@ -445,7 +445,7 @@ void colvarmodule::rotation::calc_optimal_rotation_impl() { S_backup_out[i][j] = S_backup[i][j]; } } - cvm::log("S = "+cvm::to_str(S_backup_out, cvm::cv_width, cvm::cv_prec)+"\n"); + cvm::log_static("S = "+cvm::to_str(S_backup_out, cvm::main()->cv_width, cvm::main()->cv_prec)+"\n"); } @@ -462,18 +462,18 @@ void colvarmodule::rotation::calc_optimal_rotation_impl() { int ierror = NR::diagonalize_matrix(S, S_eigval, S_eigvec); #endif if (ierror) { - cvm::log("Failed to diagonalize the following overlapping matrix:\n"); + cvm::log_static("Failed to diagonalize the following overlapping matrix:\n"); for (size_t i = 0; i < 4; ++i) { for (size_t j = 0; j < 4; ++j) { - cvm::log(cvm::to_str(S[i][j]) + " "); + cvm::log_static(cvm::to_str(S[i][j]) + " "); } - cvm::log("\n"); + cvm::log_static("\n"); } - cvm::log("The corresponding correlation matrix is:\n"); - cvm::log(" " + cvm::to_str(C.xx) + " " + cvm::to_str(C.xy) + " " + cvm::to_str(C.xz)); - cvm::log(" " + cvm::to_str(C.yx) + " " + cvm::to_str(C.yy) + " " + cvm::to_str(C.yz)); - cvm::log(" " + cvm::to_str(C.zx) + " " + cvm::to_str(C.zy) + " " + cvm::to_str(C.zz) + "\n"); - cvm::error("Too many iterations in jacobi diagonalization.\n" + cvm::log_static("The corresponding correlation matrix is:\n"); + cvm::log_static(" " + cvm::to_str(C.xx) + " " + cvm::to_str(C.xy) + " " + cvm::to_str(C.xz)); + cvm::log_static(" " + cvm::to_str(C.yx) + " " + cvm::to_str(C.yy) + " " + cvm::to_str(C.yz)); + cvm::log_static(" " + cvm::to_str(C.zx) + " " + cvm::to_str(C.zy) + " " + cvm::to_str(C.zz) + "\n"); + cvm::error_static("Too many iterations in jacobi diagonalization.\n" "This is usually the result of an ill-defined set of atoms for " "rotational alignment (RMSD, rotateReference, etc).\n"); } @@ -483,7 +483,7 @@ void colvarmodule::rotation::calc_optimal_rotation_impl() { if (q_old.norm2() > 0.0) { q.match(q_old); if (q_old.inner(q) < (1.0 - crossing_threshold)) { - cvm::log("Warning: one molecular orientation has changed by more than "+ + cvm::log_static("Warning: one molecular orientation has changed by more than "+ cvm::to_str(crossing_threshold)+": discontinuous rotation ?\n"); } } @@ -620,14 +620,14 @@ int rotation_gpu::add_optimal_rotation_nodes( void rotation_gpu::after_sync_check() const { if (max_iteration_reached[0]) { - cvm::error("Too many iterations in jacobi diagonalization.\n" + cvm::error_static("Too many iterations in jacobi diagonalization.\n" "This is usually the result of an ill-defined set of atoms for " "rotational alignment (RMSD, rotateReference, etc).\n"); max_iteration_reached[0] = 0; } if (colvarmodule::rotation::monitor_crossings) { if (discontinuous_rotation[0]) { - cvm::log("Warning: one molecular orientation has changed by more than "+ + cvm::main()->log("Warning: one molecular orientation has changed by more than "+ cvm::to_str(colvarmodule::rotation::crossing_threshold)+ ": discontinuous rotation ?\n"); } diff --git a/src/colvartypes.h b/src/colvartypes.h index 5f3b1bd61..2271ff3a0 100644 --- a/src/colvartypes.h +++ b/src/colvartypes.h @@ -123,7 +123,7 @@ template class colvarmodule::vector1d inline static void check_sizes(vector1d const &v1, vector1d const &v2) { if (v1.size() != v2.size()) { - cvm::error("Error: trying to perform an operation between vectors of different sizes, "+ + cvm::error_static("Error: trying to perform an operation between vectors of different sizes, "+ cvm::to_str(v1.size())+" and "+cvm::to_str(v2.size())+".\n"); } } @@ -253,7 +253,7 @@ template class colvarmodule::vector1d inline vector1d const slice(size_t const i1, size_t const i2) const { if ((i2 < i1) || (i2 >= this->size())) { - cvm::error("Error: trying to slice a vector using incorrect boundaries.\n"); + cvm::error_static("Error: trying to slice a vector using incorrect boundaries.\n"); } vector1d result(i2 - i1); size_t i; @@ -268,7 +268,7 @@ template class colvarmodule::vector1d vector1d const &v) { if ((i2 < i1) || (i2 >= this->size())) { - cvm::error("Error: trying to slice a vector using incorrect boundaries.\n"); + cvm::error_static("Error: trying to slice a vector using incorrect boundaries.\n"); } size_t i; for (i = 0; i < (i2 - i1); i++) { @@ -331,7 +331,8 @@ template class colvarmodule::vector1d if (this->size() == 0) return std::string(""); std::ostringstream os; os.setf(std::ios::scientific, std::ios::floatfield); - os.precision(cvm::cv_prec); + // os.precision(cvmodule->cv_prec); + os.precision(14); os << (*this)[0]; size_t i; for (i = 1; i < this->size(); i++) { @@ -401,7 +402,7 @@ template class colvarmodule::matrix2d inline int set(cvm::vector1d const &v) const { if (v.size() != length) { - return cvm::error("Error: setting a matrix row from a vector of " + return cvm::error_static("Error: setting a matrix row from a vector of " "incompatible size.\n", COLVARS_BUG_ERROR); } for (size_t i = 0; i < length; i++) data[i] = v[i]; @@ -551,7 +552,7 @@ template class colvarmodule::matrix2d { if ((m1.outer_length != m2.outer_length) || (m1.inner_length != m2.inner_length)) { - cvm::error("Error: trying to perform an operation between " + cvm::error_static("Error: trying to perform an operation between " "matrices of different sizes, "+ cvm::to_str(m1.outer_length)+"x"+ cvm::to_str(m1.inner_length)+" and "+ @@ -649,7 +650,7 @@ template class colvarmodule::matrix2d { vector1d result(m.inner_length); if (m.outer_length != v.size()) { - cvm::error("Error: trying to multiply a vector and a matrix " + cvm::error_static("Error: trying to multiply a vector and a matrix " "of incompatible sizes, "+ cvm::to_str(v.size()) + " and " + cvm::to_str(m.outer_length)+"x"+cvm::to_str(m.inner_length) + @@ -697,7 +698,8 @@ template class colvarmodule::matrix2d if (this->size() == 0) return std::string(""); std::ostringstream os; os.setf(std::ios::scientific, std::ios::floatfield); - os.precision(cvm::cv_prec); + // os.precision(cvmodule->cv_prec); + os.precision(14); os << (*this)[0]; size_t i; for (i = 1; i < data.size(); i++) { @@ -1037,7 +1039,7 @@ class colvarmodule::quaternion { return this->q3; default: #if !(defined(__NVCC__) || defined(__HIPCC__)) - cvm::error("Error: incorrect quaternion component.\n"); + cvm::error_static("Error: incorrect quaternion component.\n"); #endif return q0; } @@ -1056,7 +1058,7 @@ class colvarmodule::quaternion { return this->q3; default: #if !(defined(__NVCC__) || defined(__HIPCC__)) - cvm::error("Error: trying to access a quaternion " + cvm::error_static("Error: trying to access a quaternion " "component which is not between 0 and 3.\n"); #endif return 0.0; diff --git a/src/colvarvalue.cpp b/src/colvarvalue.cpp index 66baf35ee..3801859da 100644 --- a/src/colvarvalue.cpp +++ b/src/colvarvalue.cpp @@ -74,7 +74,7 @@ colvarvalue::colvarvalue(cvm::vector1d const &v, : real_value(0.0) { if ((vti != type_vector) && (v.size() != num_dimensions(vti))) { - cvm::error("Error: trying to initialize a variable of type \""+type_desc(vti)+ + cvm::error_static("Error: trying to initialize a variable of type \""+type_desc(vti)+ "\" using a vector of size "+cvm::to_str(v.size())+ ".\n"); value_type = type_notset; @@ -291,7 +291,7 @@ void colvarvalue::is_derivative() void colvarvalue::add_elem(colvarvalue const &x) { if (this->value_type != type_vector) { - cvm::error("Error: trying to set an element for a variable that is not set to be a vector.\n"); + cvm::error_static("Error: trying to set an element for a variable that is not set to be a vector.\n"); return; } size_t const n = vector1d_value.size(); @@ -310,7 +310,7 @@ colvarvalue const colvarvalue::get_elem(int const i_begin, int const i_end, Type cvm::vector1d const v(vector1d_value.slice(i_begin, i_end)); return colvarvalue(v, vt); } else { - cvm::error("Error: trying to get an element from a variable that is not a vector.\n"); + cvm::error_static("Error: trying to get an element from a variable that is not a vector.\n"); return colvarvalue(type_notset); } } @@ -321,7 +321,7 @@ void colvarvalue::set_elem(int const i_begin, int const i_end, colvarvalue const if (vector1d_value.size() > 0) { vector1d_value.sliceassign(i_begin, i_end, x.as_vector()); } else { - cvm::error("Error: trying to set an element for a variable that is not a vector.\n"); + cvm::error_static("Error: trying to set an element for a variable that is not a vector.\n"); } } @@ -332,7 +332,7 @@ colvarvalue const colvarvalue::get_elem(int const icv) const return get_elem(elem_indices[icv], elem_indices[icv] + elem_sizes[icv], elem_types[icv]); } else { - cvm::error("Error: trying to get a colvarvalue element from a vector colvarvalue that was initialized as a plain array.\n"); + cvm::error_static("Error: trying to get a colvarvalue element from a vector colvarvalue that was initialized as a plain array.\n"); return colvarvalue(type_notset); } } @@ -344,7 +344,7 @@ void colvarvalue::set_elem(int const icv, colvarvalue const &x) check_types_assign(elem_types[icv], x.value_type); set_elem(elem_indices[icv], elem_indices[icv] + elem_sizes[icv], x); } else { - cvm::error("Error: trying to set a colvarvalue element for a colvarvalue that was initialized as a plain array.\n"); + cvm::error_static("Error: trying to set a colvarvalue element for a colvarvalue that was initialized as a plain array.\n"); } } @@ -354,25 +354,25 @@ void colvarvalue::set_random() size_t ic; switch (this->type()) { case colvarvalue::type_scalar: - this->real_value = cvm::rand_gaussian(); + this->real_value = cvm::main()->rand_gaussian(); break; case colvarvalue::type_3vector: case colvarvalue::type_unit3vector: case colvarvalue::type_unit3vectorderiv: - this->rvector_value.x = cvm::rand_gaussian(); - this->rvector_value.y = cvm::rand_gaussian(); - this->rvector_value.z = cvm::rand_gaussian(); + this->rvector_value.x = cvm::main()->rand_gaussian(); + this->rvector_value.y = cvm::main()->rand_gaussian(); + this->rvector_value.z = cvm::main()->rand_gaussian(); break; case colvarvalue::type_quaternion: case colvarvalue::type_quaternionderiv: - this->quaternion_value.q0 = cvm::rand_gaussian(); - this->quaternion_value.q1 = cvm::rand_gaussian(); - this->quaternion_value.q2 = cvm::rand_gaussian(); - this->quaternion_value.q3 = cvm::rand_gaussian(); + this->quaternion_value.q0 = cvm::main()->rand_gaussian(); + this->quaternion_value.q1 = cvm::main()->rand_gaussian(); + this->quaternion_value.q2 = cvm::main()->rand_gaussian(); + this->quaternion_value.q3 = cvm::main()->rand_gaussian(); break; case colvarvalue::type_vector: for (ic = 0; ic < this->vector1d_value.size(); ic++) { - this->vector1d_value[ic] = cvm::rand_gaussian(); + this->vector1d_value[ic] = cvm::main()->rand_gaussian(); } break; case colvarvalue::type_notset: @@ -419,7 +419,7 @@ void colvarvalue::set_ones(cvm::real assigned_value) void colvarvalue::undef_op() const { - cvm::error("Error: Undefined operation on a colvar of type \""+ + cvm::error_static("Error: Undefined operation on a colvar of type \""+ type_desc(this->type())+"\".\n"); } @@ -646,7 +646,7 @@ cvm::real colvarvalue::dist2(colvarvalue const &x2) const return (this->vector1d_value - x2.vector1d_value).norm2(); case colvarvalue::type_unit3vectorderiv: case colvarvalue::type_quaternionderiv: - cvm::error("Error: computing a squared-distance between two variables of type \"" + + cvm::error_static("Error: computing a squared-distance between two variables of type \"" + type_desc(this->type()) + "\", for which it is not defined.\n", COLVARS_BUG_ERROR); case colvarvalue::type_notset: @@ -684,7 +684,7 @@ colvarvalue colvarvalue::dist2_grad(colvarvalue const &x2) const break; case colvarvalue::type_unit3vectorderiv: case colvarvalue::type_quaternionderiv: - cvm::error("Error: computing a squared-distance gradient between two variables of type \"" + + cvm::error_static("Error: computing a squared-distance gradient between two variables of type \"" + type_desc(this->type()) + "\", for which it is not defined.\n", COLVARS_BUG_ERROR); case colvarvalue::type_notset: @@ -706,7 +706,7 @@ colvarvalue const colvarvalue::interpolate(colvarvalue const &x1, colvarvalue::check_types(x1, x2); if ((lambda < 0.0) || (lambda > 1.0)) { - cvm::error("Error: trying to interpolate between two colvarvalues with a " + cvm::error_static("Error: trying to interpolate between two colvarvalues with a " "lamdba outside [0:1].\n", COLVARS_BUG_ERROR); } @@ -724,7 +724,7 @@ colvarvalue const colvarvalue::interpolate(colvarvalue const &x1, case colvarvalue::type_unit3vector: case colvarvalue::type_quaternion: if (interp.norm()/cvm::sqrt(d2) < 1.0e-6) { - cvm::error("Error: interpolation between "+cvm::to_str(x1)+" and "+ + cvm::error_static("Error: interpolation between "+cvm::to_str(x1)+" and "+ cvm::to_str(x2)+" with lambda = "+cvm::to_str(lambda)+ " is undefined: result = "+cvm::to_str(interp)+"\n", COLVARS_INPUT_ERROR); @@ -745,7 +745,7 @@ std::string colvarvalue::to_simple_string() const { switch (type()) { case colvarvalue::type_scalar: - return cvm::to_str(real_value, 0, cvm::cv_prec); + return cvm::to_str(real_value, 0, cvm::main()->cv_prec); break; case colvarvalue::type_3vector: case colvarvalue::type_unit3vector: @@ -849,7 +849,7 @@ std::ostream & operator << (std::ostream &os, std::vector const &v) template void colvarvalue::read_from_stream_template_(IST &is) { if (type() == colvarvalue::type_notset) { - cvm::error("Trying to read from a stream a colvarvalue, " + cvm::error_static("Trying to read from a stream a colvarvalue, " "which has not yet been assigned a data type.\n"); } @@ -1012,7 +1012,7 @@ void colvarvalue::p2leg_opt(colvarvalue const &x, switch (x.value_type) { case colvarvalue::type_scalar: - cvm::error("Error: cannot calculate Legendre polynomials " + cvm::error_static("Error: cannot calculate Legendre polynomials " "for scalar variables.\n"); return; break; @@ -1067,7 +1067,7 @@ void colvarvalue::p2leg_opt(colvarvalue const &x, switch (x.value_type) { case colvarvalue::type_scalar: - cvm::error("Error: cannot calculate Legendre polynomials " + cvm::error_static("Error: cannot calculate Legendre polynomials " "for scalar variables.\n"); break; case colvarvalue::type_3vector: diff --git a/src/colvarvalue.h b/src/colvarvalue.h index 61f1bf718..bea7199a8 100644 --- a/src/colvarvalue.h +++ b/src/colvarvalue.h @@ -215,7 +215,7 @@ class colvarvalue { inline operator cvm::real() const { if (value_type != type_scalar) { - cvm::error("Error: trying to use a variable of type \""+ + cvm::error_static("Error: trying to use a variable of type \""+ type_desc(value_type)+"\" as one of type \""+ type_desc(type_scalar)+"\".\n"); } @@ -228,7 +228,7 @@ class colvarvalue { if ((value_type != type_3vector) && (value_type != type_unit3vector) && (value_type != type_unit3vectorderiv)) { - cvm::error("Error: trying to use a variable of type \""+ + cvm::error_static("Error: trying to use a variable of type \""+ type_desc(value_type)+"\" as one of type \""+ type_desc(type_3vector)+"\".\n"); } @@ -240,7 +240,7 @@ class colvarvalue { { if ((value_type != type_quaternion) && (value_type != type_quaternionderiv)) { - cvm::error("Error: trying to use a variable of type \""+ + cvm::error_static("Error: trying to use a variable of type \""+ type_desc(value_type)+"\" as one of type \""+ type_desc(type_quaternion)+"\".\n"); } @@ -396,7 +396,7 @@ inline cvm::real colvarvalue::operator [] (int const i) const switch (value_type) { case colvarvalue::type_notset: default: - cvm::error("Error: trying to access a colvar value " + cvm::error_static("Error: trying to access a colvar value " "that is not initialized.\n", COLVARS_BUG_ERROR); return 0.0; break; case colvarvalue::type_scalar: @@ -419,7 +419,7 @@ inline cvm::real & colvarvalue::operator [] (int const i) switch (value_type) { case colvarvalue::type_notset: default: - cvm::error("Error: trying to access a colvar value " + cvm::error_static("Error: trying to access a colvar value " "that is not initialized.\n", COLVARS_BUG_ERROR); return real_value; break; case colvarvalue::type_scalar: @@ -455,7 +455,7 @@ inline int colvarvalue::check_types(colvarvalue const &x1, (x1.type() == type_quaternionderiv))) { return COLVARS_OK; } else { - cvm::error("Trying to perform an operation between two colvar " + cvm::error_static("Trying to perform an operation between two colvar " "values with different types, \""+ colvarvalue::type_desc(x1.type())+ "\" and \""+ @@ -467,7 +467,7 @@ inline int colvarvalue::check_types(colvarvalue const &x1, if (x1.type() == type_vector) { if (x1.vector1d_value.size() != x2.vector1d_value.size()) { - cvm::error("Trying to perform an operation between two vector colvar " + cvm::error_static("Trying to perform an operation between two vector colvar " "values with different sizes, "+ cvm::to_str(x1.vector1d_value.size())+ " and "+ @@ -499,7 +499,7 @@ inline int colvarvalue::check_types_assign(colvarvalue::Type const &vt1, return COLVARS_OK; } else { if (vt1 != vt2) { - cvm::error("Trying to assign a colvar value with type \""+ + cvm::error_static("Trying to assign a colvar value with type \""+ type_desc(vt2)+"\" to one with type \""+ type_desc(vt1)+"\".\n"); return COLVARS_ERROR; diff --git a/src/cuda/colvar_rotation_derivative_kernel.cu b/src/cuda/colvar_rotation_derivative_kernel.cu index f09529ef0..7d275a52b 100644 --- a/src/cuda/colvar_rotation_derivative_kernel.cu +++ b/src/cuda/colvar_rotation_derivative_kernel.cu @@ -92,7 +92,7 @@ int prepare_derivative( kernelNodeParams.kernelParams = args; kernelNodeParams.extra = NULL; if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); } return checkGPUError(cudaGraphAddKernelNode( &node, graph, dependencies.data(), diff --git a/src/cuda/colvaratoms_kernel.cu b/src/cuda/colvaratoms_kernel.cu index 5a3d3981a..0e73a3641 100644 --- a/src/cuda/colvaratoms_kernel.cu +++ b/src/cuda/colvaratoms_kernel.cu @@ -64,7 +64,7 @@ int atoms_pos_from_proxy( kernelNodeParams.kernelParams = args; kernelNodeParams.extra = NULL; if (cvm::debug()) { - cvm::log("Add atoms_pos_from_proxy node.\n"); + cvm::log_static("Add atoms_pos_from_proxy node.\n"); } return checkGPUError(cudaGraphAddKernelNode( &node, graph, dependencies.data(), @@ -96,7 +96,7 @@ int atoms_pos_from_proxy( &atoms_pos_z_ag, &num_atoms}; if (cvm::debug()) { - cvm::log("Run atoms_pos_from_proxy.\n"); + cvm::log_static("Run atoms_pos_from_proxy.\n"); } return checkGPUError(cudaLaunchKernel((void*)atoms_pos_from_proxy_kernel, num_blocks, block_size, args, 0, stream)); @@ -119,7 +119,7 @@ int change_one_coordinate( size_t array_id = num_atoms * xyz + atom_id_in_group; void* args[] = {&atoms_pos_ag, &array_id, &step_size}; if (cvm::debug()) { - cvm::log("Run change_one_coordinate.\n"); + cvm::log_static("Run change_one_coordinate.\n"); } error_code |= checkGPUError(cudaLaunchKernel( (void*)change_one_coordinate_kernel, @@ -290,7 +290,7 @@ int atoms_calc_cog_com( kernelNodeParams.kernelParams = args; kernelNodeParams.extra = NULL; if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); } return checkGPUError(cudaGraphAddKernelNode( &node, graph, dependencies.data(), @@ -346,7 +346,7 @@ int atoms_calc_cog( kernelNodeParams.kernelParams = args; kernelNodeParams.extra = NULL; if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); } return checkGPUError(cudaGraphAddKernelNode( &node, graph, dependencies.data(), @@ -415,7 +415,7 @@ int atoms_total_force_from_proxy( &q, &num_atoms}; if (cvm::debug()) { - cvm::log("Run " + cvm::to_str(__func__) + " kernel.\n"); + cvm::log_static("Run " + cvm::to_str(__func__) + " kernel.\n"); } if (rotate) { return checkGPUError(cudaLaunchKernel( @@ -506,7 +506,7 @@ int apply_main_colvar_force_to_proxy( kernelNodeParams.kernelParams = args; kernelNodeParams.extra = NULL; if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); } if (rotate) { kernelNodeParams.func = (void*)apply_colvar_force_to_proxy_kernel; @@ -555,7 +555,7 @@ int apply_fitting_colvar_force_to_proxy( kernelNodeParams.kernelParams = args; kernelNodeParams.extra = NULL; if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); } kernelNodeParams.func = (void*)apply_colvar_force_to_proxy_kernel; return checkGPUError(cudaGraphAddKernelNode( @@ -770,7 +770,7 @@ int calc_fit_gradients_impl_loop1( return COLVARS_OK; } if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); } return checkGPUError(cudaGraphAddKernelNode( &node, graph, dependencies.data(), @@ -870,7 +870,7 @@ int calc_fit_gradients_impl_loop2( return COLVARS_OK; } if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); } return checkGPUError(cudaGraphAddKernelNode( &node, graph, dependencies.data(), @@ -920,13 +920,13 @@ int apply_translation( kernelNodeParams.kernelParams = args; kernelNodeParams.extra = NULL; if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); - cvm::log("x_ptr = " + cvm::to_str((void*)atoms_pos_x_ag) + "\n"); - cvm::log("y_ptr = " + cvm::to_str((void*)atoms_pos_y_ag) + "\n"); - cvm::log("z_ptr = " + cvm::to_str((void*)atoms_pos_z_ag) + "\n"); - cvm::log("pos = " + cvm::to_str((void*)translation_vector) + "\n"); - cvm::log("factor = " + cvm::to_str(translation_vector_factor) + "\n"); - cvm::log("num_atoms = " + cvm::to_str((int)num_atoms) + "\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("x_ptr = " + cvm::to_str((void*)atoms_pos_x_ag) + "\n"); + cvm::log_static("y_ptr = " + cvm::to_str((void*)atoms_pos_y_ag) + "\n"); + cvm::log_static("z_ptr = " + cvm::to_str((void*)atoms_pos_z_ag) + "\n"); + cvm::log_static("pos = " + cvm::to_str((void*)translation_vector) + "\n"); + cvm::log_static("factor = " + cvm::to_str(translation_vector_factor) + "\n"); + cvm::log_static("num_atoms = " + cvm::to_str((int)num_atoms) + "\n"); } return checkGPUError(cudaGraphAddKernelNode( &node, graph, dependencies.data(), @@ -984,7 +984,7 @@ int rotate_with_quaternion( kernelNodeParams.kernelParams = args; kernelNodeParams.extra = NULL; if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); } return checkGPUError(cudaGraphAddKernelNode( &node, graph, dependencies.data(), @@ -1038,7 +1038,7 @@ int accumulate_cpu_force( kernelNodeParams.kernelParams = args; kernelNodeParams.extra = NULL; if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); } return checkGPUError(cudaGraphAddKernelNode( &node, graph, dependencies.data(), @@ -1112,7 +1112,7 @@ int apply_force_with_inverse_rotation( kernelNodeParams.kernelParams = args; kernelNodeParams.extra = NULL; if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); } return checkGPUError(cudaGraphAddKernelNode( &node, graph, dependencies.data(), @@ -1171,7 +1171,7 @@ int apply_force( kernelNodeParams.kernelParams = args; kernelNodeParams.extra = NULL; if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); } return checkGPUError(cudaGraphAddKernelNode( &node, graph, dependencies.data(), @@ -1194,7 +1194,7 @@ int calc_fit_forces_impl_loop1( cudaGraph_t& graph, const std::vector& dependencies) { if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); } return calc_fit_gradients_impl_loop1( pos_unrotated, main_force, rot_deriv, q, num_atoms_main, @@ -1252,7 +1252,7 @@ int calc_fit_forces_impl_loop2( return COLVARS_OK; } // if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); // } return checkGPUError(cudaGraphAddKernelNode( &node, graph, dependencies.data(), diff --git a/src/cuda/colvartypes_kernel.cu b/src/cuda/colvartypes_kernel.cu index 7304e9dd8..e5b477e40 100644 --- a/src/cuda/colvartypes_kernel.cu +++ b/src/cuda/colvartypes_kernel.cu @@ -157,7 +157,7 @@ int build_overlapping_matrix( kernelNodeParams.kernelParams = args; kernelNodeParams.extra = NULL; if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); } return checkGPUError(cudaGraphAddKernelNode( &node, graph, dependencies.data(), @@ -670,7 +670,7 @@ int jacobi_4x4( kernelNodeParams.kernelParams = args; kernelNodeParams.extra = NULL; if (cvm::debug()) { - cvm::log("Add " + cvm::to_str(__func__) + " node.\n"); + cvm::log_static("Add " + cvm::to_str(__func__) + " node.\n"); } return checkGPUError(cudaGraphAddKernelNode( &node, graph, dependencies.data(), diff --git a/tests/functional/run_colvars_test.cpp b/tests/functional/run_colvars_test.cpp index 6150ab61e..dc08ffb0f 100644 --- a/tests/functional/run_colvars_test.cpp +++ b/tests/functional/run_colvars_test.cpp @@ -26,15 +26,16 @@ int main(int argc, char *argv[]) { int err = 0; colvarproxy_stub *proxy = new colvarproxy_stub(); + colvarmodule *cvmodule = proxy->cvmodule; // Initialize simple unit system to test file input err |= proxy->set_unit_system("real", false); if (argc > 3) { err |= proxy->set_output_prefix(output_prefix); } - err |= proxy->colvars->setup_input(); - err |= proxy->colvars->setup_output(); - err |= proxy->colvars->read_config_file(configuration_file.c_str()); + err |= cvmodule->setup_input(); + err |= cvmodule->setup_output(); + err |= cvmodule->read_config_file(configuration_file.c_str()); if (argc > 2) { // Read number of atoms from XYZ header @@ -42,7 +43,7 @@ int main(int argc, char *argv[]) { int natoms; ifs >> natoms; ifs.close(); - cvm::log("Reading trajectory for " + cvm::to_str(natoms) + cvmodule->log("Reading trajectory for " + cvm::to_str(natoms) + " atoms from XYZ file " + trajectory_file); for (int ai = 0; ai < natoms; ai++) { proxy->init_atom(ai+1); @@ -50,27 +51,27 @@ int main(int argc, char *argv[]) { int io_err = 0; while (!io_err) { io_err = proxy->read_frame_xyz(trajectory_file.c_str(), output_force); - if (!io_err) cvm::log("Frame " + cvm::to_str(cvm::step_absolute())); + if (!io_err) cvmodule->log("Frame " + cvm::to_str(cvmodule->step_absolute())); } proxy->post_run(); - cvm::log("Done"); + cvmodule->log("Done"); } - cvm::log("Input files read during this test:"); + cvmodule->log("Input files read during this test:"); unsigned char * args[2] = { (unsigned char *) "cv", (unsigned char *) "listinputfiles" }; - err |= run_colvarscript_command(2, args); - cvm::log(" " + std::string(get_colvarscript_result())); + err |= run_colvarscript_command(proxy->script, 2, args); + cvmodule->log(" " + std::string(get_colvarscript_result())); - double const max_gradient_error = proxy->colvars->get_max_gradient_error(); + double const max_gradient_error = proxy->cvmodule->get_max_gradient_error(); if (max_gradient_error > 0.) { - cvm::log("Max gradient error (debugGradients): " + cvm::to_str(max_gradient_error)); + cvmodule->log("Max gradient error (debugGradients): " + cvm::to_str(max_gradient_error)); double threshold = 1e-3; // Fail test if error is above threshold if (max_gradient_error > threshold) { - cvm::log("Error: gradient inaccuracy is above threshold (" + cvm::to_str(threshold) + ")"); + cvmodule->log("Error: gradient inaccuracy is above threshold (" + cvm::to_str(threshold) + ")"); err = 1; } } diff --git a/tests/functional_gpu/run_colvars_test_cuda.cpp b/tests/functional_gpu/run_colvars_test_cuda.cpp index 008db244c..6e3f3defe 100644 --- a/tests/functional_gpu/run_colvars_test_cuda.cpp +++ b/tests/functional_gpu/run_colvars_test_cuda.cpp @@ -55,15 +55,15 @@ class colvarproxy_stub_gpu : public colvarproxy { return COLVARS_NOT_IMPLEMENTED; } void init_cvm() { - colvars = new colvarmodule(this); - cvm::log("Using minimal CUDA testing interface.\n"); + cvmodule = new colvarmodule(this); + cvmodule->log("Using minimal CUDA testing interface.\n"); - colvars->cv_traj_freq = 0; // I/O will be handled explicitly - colvars->restart_out_freq = 0; + cvmodule->cv_traj_freq = 0; // I/O will be handled explicitly + cvmodule->restart_out_freq = 0; cvm::rotation::monitor_crossings = false; // Avoid unnecessary error messages - colvars->setup_input(); - colvars->setup_output(); + cvmodule->setup_input(); + cvmodule->setup_output(); colvarproxy_stub_gpu::setup(); } @@ -109,9 +109,9 @@ colvarproxy_stub_gpu::~colvarproxy_stub_gpu() { int colvarproxy_stub_gpu::setup() { boundaries_type = boundaries_non_periodic; reset_pbc_lattice(); - colvars->it = colvars->it_restart = 0; - if (colvars) { - return colvars->update_engine_parameters(); + cvmodule->it = cvmodule->it_restart = 0; + if (cvmodule) { + return cvmodule->update_engine_parameters(); } return COLVARS_OK; } @@ -139,7 +139,7 @@ int colvarproxy_stub_gpu::set_unit_system(std::string const &units_in, // colvarmodule sets this flag if new units are requested while colvars are already defined if (check_only) { if ((units != "" && units_in != units) || (units == "" && units_in != "real")) { - cvm::error("Specified unit system \"" + units_in + "\" is incompatible with previous setting \"" + cvmodule->error("Specified unit system \"" + units_in + "\" is incompatible with previous setting \"" + units + "\".\nReset the Colvars Module or delete all variables to change the unit.\n"); return COLVARS_ERROR; } else { @@ -161,7 +161,7 @@ int colvarproxy_stub_gpu::set_unit_system(std::string const &units_in, angstrom_value_ = 0.1; // nm kcal_mol_value_ = 4.184; // kJ/mol } else { - cvm::error("Unknown unit system specified: \"" + units_in + "\". Supported are real, metal, electron, and gromacs.\n"); + cvmodule->error("Unknown unit system specified: \"" + units_in + "\". Supported are real, metal, electron, and gromacs.\n"); return COLVARS_ERROR; } @@ -223,18 +223,18 @@ void colvarproxy_stub_gpu::clear_atom(int index) { int colvarproxy_stub_gpu::read_frame_xyz(const char *filename, const bool write_force_file) { std::vector positions(atoms_ids.size()); - int err = colvars->load_coords_xyz(filename, &positions, nullptr, true); + int err = cvmodule->load_coords_xyz(filename, &positions, nullptr, true); // Convert to SOA and copy to GPU colvarproxy_atoms::atom_buffer_real_t positions_soa; const size_t numAtoms = positions.size(); // if (numAtoms != positions.size()) { - // return cvm::error("Number of atoms mismatch!\n", COLVARS_ERROR); + // return cvmodule->error("Number of atoms mismatch!\n", COLVARS_ERROR); // } if (mAtomsChanged) { this->reallocate(); - if (colvars->gpu_calc) { + if (cvmodule->gpu_calc) { // Need to rebuild the graph in case of reallocation - colvars->gpu_calc->init(); + cvmodule->gpu_calc->init(); } } positions_soa.resize(3 * numAtoms); @@ -248,11 +248,11 @@ int colvarproxy_stub_gpu::read_frame_xyz(const char *filename, const bool write_ clear_device_array(d_mTotalForces, 3 * numAtoms); std::string force_filename; if (write_force_file) { - force_filename = colvars->output_prefix() + "_forces_" + cvm::to_str(colvars->it) + ".dat"; + force_filename = cvmodule->output_prefix() + "_forces_" + cvm::to_str(cvmodule->it) + ".dat"; } if ( !err ) { - colvars->calc(); - colvars->it++; + cvmodule->calc(); + cvmodule->it++; colvarproxy_atoms::atom_buffer_real_t h_applied_forces(3 * numAtoms); copy_DtoH(d_mAppliedForces, h_applied_forces.data(), 3 * numAtoms); if (write_force_file) { @@ -291,6 +291,7 @@ int main(int argc, char *argv[]) { int err = COLVARS_OK; colvarproxy_stub_gpu *proxy = new colvarproxy_stub_gpu(); proxy->init_cvm(); + colvarmodule* const cvmodule = proxy->cvmodule; // Initialize simple unit system to test file input err |= proxy->set_unit_system("real", false); // Initialize simple unit system to test file input @@ -299,11 +300,11 @@ int main(int argc, char *argv[]) { if (argc > 3) { err |= proxy->set_output_prefix(output_prefix); } - err |= proxy->colvars->setup_input(); - err |= proxy->colvars->setup_output(); - err |= proxy->colvars->read_config_file(configuration_file.c_str()); + err |= proxy->cvmodule->setup_input(); + err |= proxy->cvmodule->setup_output(); + err |= proxy->cvmodule->read_config_file(configuration_file.c_str()); if (err != COLVARS_OK) { - cvm::log("Error occurred!\n"); + cvmodule->log("Error occurred!\n"); } if (argc > 2) { @@ -312,47 +313,47 @@ int main(int argc, char *argv[]) { int natoms; ifs >> natoms; ifs.close(); - cvm::log("Reading trajectory for " + cvm::to_str(natoms) + cvmodule->log("Reading trajectory for " + cvm::to_str(natoms) + " atoms from XYZ file " + trajectory_file); for (int ai = 0; ai < natoms; ai++) { proxy->init_atom(ai+1); } - err = cvm::get_error(); + err = cvmodule->get_error(); if (err != COLVARS_OK) { - cvm::log("Error occurred!\n"); + cvmodule->log("Error occurred!\n"); } int io_err = 0; while (!io_err) { io_err = proxy->read_frame_xyz(trajectory_file.c_str(), output_force); - err = cvm::get_error(); + err = cvmodule->get_error(); if (err != COLVARS_OK) { - cvm::log("Error occurred!\n"); + cvmodule->log("Error occurred!\n"); } - if (!io_err) cvm::log("Frame " + cvm::to_str(cvm::step_absolute())); + if (!io_err) cvmodule->log("Frame " + cvm::to_str(cvmodule->step_absolute())); } proxy->post_run(); - cvm::log("Done"); - err = cvm::get_error(); + cvmodule->log("Done"); + err = cvmodule->get_error(); if (err != COLVARS_OK) { - cvm::log("Error occurred!\n"); + cvmodule->log("Error occurred!\n"); } } - cvm::log("Input files read during this test:"); + cvmodule->log("Input files read during this test:"); unsigned char * args[2] = { (unsigned char *) "cv", (unsigned char *) "listinputfiles" }; - err |= run_colvarscript_command(2, args); - cvm::log(" " + std::string(get_colvarscript_result())); + err |= run_colvarscript_command(proxy->script, 2, args); + cvmodule->log(" " + std::string(get_colvarscript_result())); - double const max_gradient_error = proxy->colvars->get_max_gradient_error(); + double const max_gradient_error = proxy->cvmodule->get_max_gradient_error(); if (max_gradient_error > 0.) { - cvm::log("Max gradient error (debugGradients): " + cvm::to_str(max_gradient_error)); + cvmodule->log("Max gradient error (debugGradients): " + cvm::to_str(max_gradient_error)); double threshold = 1e-3; // Fail test if error is above threshold if (max_gradient_error > threshold) { - cvm::log("Error: gradient inaccuracy is above threshold (" + cvm::to_str(threshold) + ")"); + cvmodule->log("Error: gradient inaccuracy is above threshold (" + cvm::to_str(threshold) + ")"); err = 1; } } diff --git a/tests/unittests/colvarvalue_unit3vector.cpp b/tests/unittests/colvarvalue_unit3vector.cpp index c8f4b6d4e..6a04bdc02 100644 --- a/tests/unittests/colvarvalue_unit3vector.cpp +++ b/tests/unittests/colvarvalue_unit3vector.cpp @@ -10,8 +10,13 @@ int main(int argc, char *argv[]) { x.rvector_value = cvm::rvector(1.0, 0.1, 0.0); x.apply_constraints(); + /// Number of digits to represent a collective variables value(s) + size_t const cv_prec = 14; + /// Number of characters to represent a collective variables value(s) + size_t const cv_width = 21; + std::cout << "x = " - << cvm::to_str(x, cvm::cv_width, cvm::cv_prec) << std::endl; + << cvm::to_str(x, cv_width, cv_prec) << std::endl; { colvarvalue y(colvarvalue::type_unit3vector); @@ -21,12 +26,12 @@ int main(int argc, char *argv[]) { colvarvalue const xtoy = 0.5*x.dist2_grad(y); colvarvalue const ytox = 0.5*y.dist2_grad(x); std::cout << "y = " - << cvm::to_str(y, cvm::cv_width, cvm::cv_prec) << std::endl; + << cvm::to_str(y, cv_width, cv_prec) << std::endl; std::cout << "x.dist2_grad(y) = " - << cvm::to_str(xtoy, cvm::cv_width, cvm::cv_prec) << std::endl; + << cvm::to_str(xtoy, cv_width, cv_prec) << std::endl; std::cout << "y.dist2_grad(x) = " - << cvm::to_str(ytox, cvm::cv_width, cvm::cv_prec) << std::endl; + << cvm::to_str(ytox, cv_width, cv_prec) << std::endl; } { @@ -37,12 +42,12 @@ int main(int argc, char *argv[]) { colvarvalue const xtoy = 0.5*x.dist2_grad(y); colvarvalue const ytox = 0.5*y.dist2_grad(x); std::cout << "y = " - << cvm::to_str(y, cvm::cv_width, cvm::cv_prec) << std::endl; + << cvm::to_str(y, cv_width, cv_prec) << std::endl; std::cout << "x.dist2_grad(y) = " - << cvm::to_str(xtoy, cvm::cv_width, cvm::cv_prec) << std::endl; + << cvm::to_str(xtoy, cv_width, cv_prec) << std::endl; std::cout << "y.dist2_grad(x) = " - << cvm::to_str(ytox, cvm::cv_width, cvm::cv_prec) << std::endl; + << cvm::to_str(ytox, cv_width, cv_prec) << std::endl; } // Below 10^-8, (1 - cos^2) = 1 in dist2_grad() @@ -54,21 +59,21 @@ int main(int argc, char *argv[]) { std::cout << std::endl; std::cout << "Epsilon = " << eps << std::endl; std::cout << "y = " - << cvm::to_str(y, cvm::cv_width, cvm::cv_prec) << std::endl; + << cvm::to_str(y, cv_width, cv_prec) << std::endl; colvarvalue xtoy = 0.5*x.dist2_grad(y); colvarvalue xminusy = x - y; std::cout << "dist2_grad = " - << cvm::to_str(xtoy, cvm::cv_width, cvm::cv_prec) << std::endl; + << cvm::to_str(xtoy, cv_width, cv_prec) << std::endl; std::cout << "difference = " - << cvm::to_str(xminusy, cvm::cv_width, cvm::cv_prec) << std::endl; + << cvm::to_str(xminusy, cv_width, cv_prec) << std::endl; for (size_t c = 0; c < 3; c++) { xtoy[c] /= xminusy[c]; } std::cout << "ratio = " - << cvm::to_str(xtoy, cvm::cv_width, cvm::cv_prec) << std::endl; + << cvm::to_str(xtoy, cv_width, cv_prec) << std::endl; } return 0; diff --git a/tests/unittests/embedded_tcl.cpp b/tests/unittests/embedded_tcl.cpp index 3e8c19d87..afb2f4eda 100644 --- a/tests/unittests/embedded_tcl.cpp +++ b/tests/unittests/embedded_tcl.cpp @@ -8,7 +8,7 @@ int main(int argc, char *argv[]) { colvarproxy *proxy = new colvarproxy(); - proxy->colvars = new colvarmodule(proxy); + proxy->cvmodule = new colvarmodule(proxy); int res = proxy->tcl_run_script("puts \"\n(Tcl) Tcl script running successfully using embedded interpreter.\""); diff --git a/tests/unittests/file_io.cpp b/tests/unittests/file_io.cpp index 1bd929607..e4ca0915a 100644 --- a/tests/unittests/file_io.cpp +++ b/tests/unittests/file_io.cpp @@ -8,14 +8,14 @@ int main(int argc, char *argv[]) { colvarproxy *proxy = new colvarproxy(); - proxy->colvars = new colvarmodule(proxy); + proxy->cvmodule = new colvarmodule(proxy); proxy->backup_file("nonexistent.txt"); proxy->remove_file("nonexistent.txt"); // Produce an (almost) empty state file, twice (uses proxy->backup_file()) - proxy->colvars->write_restart_file("test.colvars.state"); - proxy->colvars->write_restart_file("test.colvars.state"); + proxy->cvmodule->write_restart_file("test.colvars.state"); + proxy->cvmodule->write_restart_file("test.colvars.state"); proxy->backup_file("test.colvars.state.old"); diff --git a/tests/unittests/parse_error.cpp b/tests/unittests/parse_error.cpp index 971d48243..1a7edd9af 100644 --- a/tests/unittests/parse_error.cpp +++ b/tests/unittests/parse_error.cpp @@ -11,8 +11,8 @@ int main(int argc, char *argv[]) { colvarproxy_stub *proxy = new colvarproxy_stub(); proxy->set_unit_system("real", false); proxy->set_output_prefix("test.out"); - proxy->colvars->setup_input(); - proxy->colvars->setup_output(); + proxy->cvmodule->setup_input(); + proxy->cvmodule->setup_output(); // Hard-coded for decaalanine system const int natoms = 104; @@ -20,7 +20,7 @@ int main(int argc, char *argv[]) { proxy->init_atom(ai+1); } - int err = proxy->colvars->read_config_file("test_error.in"); + int err = proxy->cvmodule->read_config_file("test_error.in"); delete proxy; diff --git a/tests/unittests/read_xyz_traj.cpp b/tests/unittests/read_xyz_traj.cpp index b5d4bb2a6..da4d01837 100644 --- a/tests/unittests/read_xyz_traj.cpp +++ b/tests/unittests/read_xyz_traj.cpp @@ -11,8 +11,10 @@ int main(int argc, char *argv[]) { colvarproxy_stub *proxy = new colvarproxy_stub(); proxy->set_unit_system("real", false); proxy->set_output_prefix("test.out"); - proxy->colvars->setup_input(); - proxy->colvars->setup_output(); + colvarmodule *cvmodule = proxy->cvmodule; + + cvmodule->setup_input(); + cvmodule->setup_output(); // Hard-coded for decaalanine system const int natoms = 104; @@ -20,15 +22,15 @@ int main(int argc, char *argv[]) { proxy->init_atom(ai+1); } - proxy->colvars->read_config_file("test.in"); + cvmodule->read_config_file("test.in"); int err = 0; while (!err) { - cvm::log("Frame " + cvm::to_str(cvm::step_absolute())); + cvmodule->log("Frame " + cvm::to_str(cvmodule->step_absolute())); err = proxy->read_frame_xyz("da-traj.xyz"); } proxy->post_run(); - cvm::log("Done"); + cvmodule->log("Done"); delete proxy; diff --git a/vmd/src/colvarproxy_vmd.C b/vmd/src/colvarproxy_vmd.C index ff2644dae..9f14bf866 100644 --- a/vmd/src/colvarproxy_vmd.C +++ b/vmd/src/colvarproxy_vmd.C @@ -28,6 +28,8 @@ namespace { // Keep pointers to relevant runtime objects + // These global variables may include a registry of colvarmodule + // (or proxy) instances associated with each molecule VMDApp *colvars_vmd_ptr = NULL; colvarproxy_vmd *colvarproxy_vmd_ptr = NULL; } @@ -50,7 +52,8 @@ int tcl_colvars(ClientData clientData, Tcl_Interp *interp, if (colvars_vmd_ptr == NULL) { colvars_vmd_ptr = (VMDApp *) clientData; } - return tcl_run_colvarscript_command(clientData, interp, objc, objv); + colvarscript *script = colvarproxy_vmd_ptr ? colvarproxy_vmd_ptr->script : nullptr; + return tcl_run_colvarscript_command(script, interp, objc, objv); } @@ -59,8 +62,8 @@ int tcl_colvars_vmd_init(Tcl_Interp *interp, int molid_input) VMDApp *const vmd = colvars_vmd_ptr; int molid = molid_input == -(1<<16) ? vmd->molecule_top() : molid_input; if (vmd->molecule_valid_id(molid)) { - colvarproxy_vmd_ptr = new colvarproxy_vmd(interp, vmd, molid); - return (cvm::get_error() == COLVARS_OK) ? TCL_OK : TCL_ERROR; + colvarproxy_vmd_ptr = new colvarproxy_vmd(interp, vmd, molid); // also constructs colvarmodule + return (colvarproxy_vmd_ptr->cvmodule->get_error() == COLVARS_OK) ? TCL_OK : TCL_ERROR; } else { Tcl_SetResult(interp, (char *) "Error: molecule not found.", TCL_STATIC); @@ -96,15 +99,15 @@ colvarproxy_vmd::colvarproxy_vmd(Tcl_Interp *interp, VMDApp *v, int molid) have_scripts = false; #endif - colvars = new colvarmodule(this); - cvm::log("Using VMD interface, version "+ + cvmodule = new colvarmodule(this); + cvmodule->log("Using VMD interface, version "+ cvm::to_str(COLVARPROXY_VERSION)+".\n"); - colvars->cite_feature("VMD engine"); - colvars->cite_feature("Colvars-VMD interface (command line)"); + cvmodule->cite_feature("VMD engine"); + cvmodule->cite_feature("Colvars-VMD interface (command line)"); - colvars->cv_traj_freq = 0; // I/O will be handled explicitly - colvars->restart_out_freq = 0; + cvmodule->cv_traj_freq = 0; // I/O will be handled explicitly + cvmodule->restart_out_freq = 0; cvm::rotation::monitor_crossings = false; // Avoid unnecessary error messages // Default to VMD's native unit system, but do not set the units string @@ -112,8 +115,8 @@ colvarproxy_vmd::colvarproxy_vmd(Tcl_Interp *interp, VMDApp *v, int molid) angstrom_value_ = 1.; kcal_mol_value_ = 1.; - colvars->setup_input(); - colvars->setup_output(); + cvmodule->setup_input(); + cvmodule->setup_output(); // set the same seed as in Measure.C vmd_srandom(38572111); @@ -146,7 +149,7 @@ int colvarproxy_vmd::setup() return COLVARS_ERROR; } - return colvars->update_engine_parameters(); + return cvmodule->update_engine_parameters(); } @@ -162,7 +165,7 @@ int colvarproxy_vmd::set_unit_system(std::string const &units_in, bool check_onl // colvarmodule sets this flag if new units are requested while colvars are already defined if (check_only) { if ((units != "" && units_in != units) || (units == "" && units_in != "real")) { - cvm::error("Specified unit system \"" + units_in + "\" is incompatible with previous setting \"" + cvmodule->error("Specified unit system \"" + units_in + "\" is incompatible with previous setting \"" + units + "\".\nReset the Colvars Module or delete all variables to change the unit.\n"); return COLVARS_ERROR; } else { @@ -184,7 +187,7 @@ int colvarproxy_vmd::set_unit_system(std::string const &units_in, bool check_onl angstrom_value_ = 0.1; // nm kcal_mol_value_ = 4.184; // kJ/mol } else { - cvm::error("Unknown unit system specified: \"" + units_in + "\". Supported are real, metal, electron, and gromacs.\n"); + cvmodule->error("Unknown unit system specified: \"" + units_in + "\". Supported are real, metal, electron, and gromacs.\n"); return COLVARS_ERROR; } @@ -299,7 +302,7 @@ int colvarproxy_vmd::update_atomic_properties() void colvarproxy_vmd::request_total_force(bool yesno) { if ((yesno == true) && (total_force_requested == false)) { - cvm::log("Warning: a bias requested total forces, which are undefined in VMD. " + cvmodule->log("Warning: a bias requested total forces, which are undefined in VMD. " "This is only meaningful when analyzing a simulation where these were used, " "provided that a state file is loaded.\n"); } @@ -343,7 +346,7 @@ int colvarproxy_vmd::set_frame(long int f) if (vmdmol->get_frame(f) != NULL) { vmdmol_frame = f; - colvars->it = f; + cvmodule->it = f; update_input(); @@ -392,17 +395,7 @@ int colvarproxy_vmd::run_colvar_gradient_callback( #endif -enum e_pdb_field { - e_pdb_none, - e_pdb_occ, - e_pdb_beta, - e_pdb_x, - e_pdb_y, - e_pdb_z, - e_pdb_ntot -}; - -e_pdb_field pdb_field_str2enum(std::string const &pdb_field_str) +colvarproxy_vmd::e_pdb_field colvarproxy_vmd::pdb_field_str2enum(std::string const &pdb_field_str) { e_pdb_field pdb_field = e_pdb_none; @@ -432,7 +425,7 @@ e_pdb_field pdb_field_str2enum(std::string const &pdb_field_str) } if (pdb_field == e_pdb_none) { - cvm::error("Error: unsupported PDB field, \""+ + cvmodule->error("Error: unsupported PDB field, \""+ pdb_field_str+"\".\n"); } @@ -447,7 +440,7 @@ int colvarproxy_vmd::load_coords_pdb(char const *pdb_filename, double const pdb_field_value) { if (pdb_field_str.size() == 0 && indices.size() == 0) { - cvm::error("Bug alert: either PDB field should be defined or list of " + cvmodule->error("Bug alert: either PDB field should be defined or list of " "atom IDs should be available when loading atom coordinates!\n", COLVARS_BUG_ERROR); return COLVARS_ERROR; @@ -467,7 +460,7 @@ int colvarproxy_vmd::load_coords_pdb(char const *pdb_filename, int tmpmolid = vmd->molecule_load(-1, pdb_filename, "pdb", tmpspec); delete tmpspec; if (tmpmolid < 0) { - cvm::error("Error: VMD could not read file \""+std::string(pdb_filename)+"\".\n", + cvmodule->error("Error: VMD could not read file \""+std::string(pdb_filename)+"\".\n", COLVARS_FILE_ERROR); return COLVARS_ERROR; } @@ -527,7 +520,7 @@ int colvarproxy_vmd::load_coords_pdb(char const *pdb_filename, if (!pos_allocated) { pos.push_back(cvm::atom_pos(0.0, 0.0, 0.0)); } else if (ipos >= pos.size()) { - cvm::error("Error: the PDB file \""+ + cvmodule->error("Error: the PDB file \""+ std::string(pdb_filename)+ "\" contains coordinates for " "more atoms than needed.\n", COLVARS_INPUT_ERROR); @@ -544,7 +537,7 @@ int colvarproxy_vmd::load_coords_pdb(char const *pdb_filename, if (ipos < pos.size() || (!use_pdb_field && current_index != indices.end())) { size_t n_requested = use_pdb_field ? pos.size() : indices.size(); - cvm::error("Error: number of matching records in the PDB file \""+ + cvmodule->error("Error: number of matching records in the PDB file \""+ std::string(pdb_filename)+"\" ("+cvm::to_str(ipos)+ ") does not match the number of requested coordinates ("+ cvm::to_str(n_requested)+").\n", COLVARS_INPUT_ERROR); @@ -562,7 +555,7 @@ int colvarproxy_vmd::load_coords_pdb(char const *pdb_filename, } vmd->molecule_delete(tmpmolid); - return (cvm::get_error() ? COLVARS_ERROR : COLVARS_OK); + return (cvmodule->get_error() ? COLVARS_ERROR : COLVARS_OK); } @@ -572,9 +565,9 @@ int colvarproxy_vmd::load_atoms_pdb(char const *pdb_filename, double const pdb_field_value) { if (pdb_field_str.size() == 0) { - cvm::log("Error: must define which PDB field to use " + cvmodule->log("Error: must define which PDB field to use " "in order to define atoms from a PDB file.\n"); - cvm::set_error_bits(COLVARS_INPUT_ERROR); + cvmodule->set_error_bits(COLVARS_INPUT_ERROR); return COLVARS_ERROR; } @@ -584,7 +577,7 @@ int colvarproxy_vmd::load_atoms_pdb(char const *pdb_filename, delete tmpspec; if (tmpmolid < 0) { - cvm::error("Error: VMD could not read file \""+std::string(pdb_filename)+"\".\n", + cvmodule->error("Error: VMD could not read file \""+std::string(pdb_filename)+"\".\n", COLVARS_FILE_ERROR); return COLVARS_ERROR; } @@ -629,7 +622,7 @@ int colvarproxy_vmd::load_atoms_pdb(char const *pdb_filename, } vmd->molecule_delete(tmpmolid); - return (cvm::get_error() ? COLVARS_ERROR : COLVARS_OK); + return (cvmodule->get_error() ? COLVARS_ERROR : COLVARS_OK); } @@ -640,11 +633,11 @@ int colvarproxy_vmd::check_atom_id(int atom_number) int const aid(atom_number-1); if (cvm::debug()) - cvm::log("Adding atom "+cvm::to_str(aid+1)+ + cvmodule->log("Adding atom "+cvm::to_str(aid+1)+ " for collective variables calculation.\n"); if ( (aid < 0) || (aid >= vmdmol->nAtoms) ) { - cvm::error("Error: invalid atom number specified, "+ + cvmodule->error("Error: invalid atom number specified, "+ cvm::to_str(atom_number)+"\n"); return COLVARS_INPUT_ERROR; } @@ -714,7 +707,7 @@ int colvarproxy_vmd::check_atom_id(cvm::residue_id const &resid, if (aid < 0) { - cvm::error("Error: could not find atom \""+ + cvmodule->error("Error: could not find atom \""+ atom_name+"\" in residue "+ cvm::to_str(resid)+ ( (segment_id.size()) ? @@ -743,7 +736,7 @@ int colvarproxy_vmd::init_atom(cvm::residue_id const &resid, } if (cvm::debug()) - cvm::log("Adding atom \""+ + cvmodule->log("Adding atom \""+ atom_name+"\" in residue "+ cvm::to_str(resid)+ " (index "+cvm::to_str(aid)+ @@ -790,7 +783,7 @@ int colvarproxy_vmd::init_volmap_by_id(int volmap_id) int colvarproxy_vmd::check_volmap_by_id(int volmap_id) { if ((volmap_id < 0) || (volmap_id >= vmdmol->num_volume_data())) { - return cvm::error("Error: invalid numeric ID ("+cvm::to_str(volmap_id)+ + return cvmodule->error("Error: invalid numeric ID ("+cvm::to_str(volmap_id)+ ") for map.\n", COLVARS_INPUT_ERROR); } return COLVARS_OK; @@ -809,7 +802,7 @@ void colvarproxy_vmd::compute_voldata(VolumetricData const *voldata, cvm::real *value, cvm::real *atom_field) { - int i = 0; + size_t i = 0; float coord[3], voxcoord[3], grad[3]; cvm::rvector dV(0.0); cvm::atom_pos const origin(0.0, 0.0, 0.0); diff --git a/vmd/src/colvarproxy_vmd.h b/vmd/src/colvarproxy_vmd.h index c557acd45..10cd522bb 100644 --- a/vmd/src/colvarproxy_vmd.h +++ b/vmd/src/colvarproxy_vmd.h @@ -78,6 +78,18 @@ class colvarproxy_vmd : public colvarproxy { std::vector const &cvc_values, std::vector > &gradient); + enum e_pdb_field { + e_pdb_none, + e_pdb_occ, + e_pdb_beta, + e_pdb_x, + e_pdb_y, + e_pdb_z, + e_pdb_ntot + }; + + e_pdb_field pdb_field_str2enum(std::string const &pdb_field_str); + virtual int load_atoms_pdb(char const *filename, cvm::atom_group &atoms, std::string const &pdb_field,