votca 2026-dev
Loading...
Searching...
No Matches
jobtopology.cc
Go to the documentation of this file.
1/*
2 * Copyright 2009-2023 The VOTCA Development Team
3 * (http://www.votca.org)
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License")
6 *
7 * You may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 */
19
20// Standard includes
21#include <algorithm>
22#include <numeric>
23#include <stdexcept>
24#include <string>
25
26// Local VOTCA includes
28#include "votca/tools/version.h"
33#include "votca/xtp/qmregion.h"
36
37namespace votca {
38namespace xtp {
39
40namespace {
41// Unweighted mean of a mapped molecule's own atom positions, matching
42// EwaldRegion's own Centroid (and legacy's PolarSeg::CalcPos). Only the
43// lattice image is taken from it there, so staying consistent with the
44// background's convention matters more than the choice itself.
45template <class T>
46Eigen::Vector3d UnweightedCentroid(const T& mol) {
47 Eigen::Vector3d pos = Eigen::Vector3d::Zero();
48 Index n = 0;
49 for (const auto& atom : mol) {
50 pos += atom.getPos();
51 ++n;
52 }
53 return (n > 0) ? Eigen::Vector3d(pos / double(n)) : pos;
54}
55} // namespace
56
57std::vector<const tools::Property*> JobTopology::SortRegionsDefbyId(
58 const tools::Property& regions_def) const {
59 std::vector<const tools::Property*> view;
60 for (const auto& child : regions_def) {
61 view.push_back(&child);
62 }
63 std::sort(view.begin(), view.end(),
64 [](const tools::Property* A, const tools::Property* B) {
65 return (A->get("id").as<Index>()) < (B->get("id").as<Index>());
66 });
67 return view;
68}
69
70std::vector<std::string> ModifyRegionOptionsFromJobFileRegion(
71 tools::Property& opt, const tools::Property& job_opt) {
72 std::vector<std::string> modified_options;
73 for (auto& child : opt) {
74 if (child.as<std::string>() == "jobfile") {
75 if (job_opt.exists(child.name())) {
76 const tools::Property& job_opt_child = job_opt.get(child.name());
77 modified_options.push_back(child.path() + "." + child.name());
78 if (job_opt_child.HasChildren()) {
79 child.value() = "";
80 for (const auto& job_childchild : job_opt_child) {
81 child.add(job_childchild);
82 }
83 } else {
84 child.value() = job_opt_child.value();
85 }
86 } else {
87 throw std::runtime_error("Requested to replace:" + child.path() + "." +
88 child.name() +
89 " but no option in jobfile found");
90 }
91 } else if (job_opt.exists(child.name())) {
92 std::vector<std::string> child_modified_options =
94 job_opt.get(child.name()));
95 modified_options.insert(modified_options.end(),
96 child_modified_options.begin(),
97 child_modified_options.end());
98 }
99 }
100 return modified_options;
101}
102
104
105 const tools::Property& prop = job_.getInput();
106 std::vector<const tools::Property*> regions_def_job =
107 prop.Select("regions.*region");
108
109 for (const auto& job_region : regions_def_job) {
110
111 Index job_region_id = job_region->get("id").as<Index>();
112
113 auto found_prop =
114 std::find_if(regions_def.begin(), regions_def.end(),
115 [job_region_id](const tools::Property& p) {
116 return p.get("id").as<Index>() == job_region_id;
117 });
118 if (found_prop == regions_def.end()) {
119 throw std::runtime_error(
120 "Your jobfile options want to modify a region with id " +
121 std::to_string(job_region_id) +
122 " it does not exist in your region specifications.");
123 }
124
125 tools::Property& region = *found_prop;
126 if (region.name() != job_region->name()) {
127 throw std::runtime_error("Types of region with id" +
128 std::to_string(job_region_id) +
129 " do not agree jobfile:" + job_region->name() +
130 " options:" + region.name());
131 }
132
133 std::vector<std::string> changed_options =
134 ModifyRegionOptionsFromJobFileRegion(region, *job_region);
135
136 if (!changed_options.empty()) {
137 XTP_LOG(Log::info, log_) << " Region " << job_region_id
138 << " is modified by jobfile" << std::flush;
140 << " Replacing the following paths with jobfile entries"
141 << std::flush;
142 for (const std::string& path : changed_options) {
143 XTP_LOG(Log::info, log_) << " - " << path << std::flush;
144 }
145 }
146 }
147}
148
150 const Topology& top, std::pair<std::string, tools::Property> options) {
151
152 CheckEnumerationOfRegions(options.second);
153 ModifyOptionsByJobFile(options.second);
154
155 std::vector<std::vector<SegId>> region_seg_ids =
156 PartitionRegions(options.second, top);
157
158 // // around this point the whole jobtopology will be centered
159 CreateRegions(options, top, region_seg_ids);
160 XTP_LOG(Log::error, log_) << " Regions created" << std::flush;
161 for (const auto& region : regions_) {
162 XTP_LOG(Log::error, log_) << *region << std::flush;
163 }
164
165 return;
166}
167
168template <class T>
169void JobTopology::ShiftPBC(const Topology& top, const Eigen::Vector3d& center,
170 T& mol) const {
171 Eigen::Vector3d r_pbc = top.PbShortestConnect(center, mol.getPos());
172 Eigen::Vector3d r = mol.getPos() - center;
173 Eigen::Vector3d shift = r_pbc - r;
174 if (shift.norm() > 1e-9) {
175 mol.Translate(shift);
176 }
177}
178
180 const std::pair<std::string, tools::Property>& options, const Topology& top,
181 const std::vector<std::vector<SegId>>& region_seg_ids) {
182 std::string mapfile = options.first;
183 // around this point the whole jobtopology will be centered for removing pbc
184 Eigen::Vector3d center = top.getSegment(region_seg_ids[0][0].Id()).getPos();
185
186 // The union of every segment carved out of the periodic cell, collected
187 // as each molecule is mapped and shifted. An EwaldRegion needs the whole
188 // union to know which background copies to suppress, and no single
189 // client region knows it (see EwaldRegion::RegisterForeground). All
190 // region types contribute, not only qm and polar: every region takes its
191 // segments from the Topology the background was converged on.
192 std::vector<std::pair<Index, Eigen::Vector3d>> foreground_union;
193
194 for (const tools::Property& region_def : options.second) {
195 Index id = region_def.get("id").as<Index>();
196 const std::vector<SegId>& seg_ids = region_seg_ids[id];
197 std::string type = region_def.name();
198 std::unique_ptr<Region> region;
199 QMRegion QMdummy(0, log_, "");
200 StaticRegion Staticdummy(0, log_);
201 PolarRegion Polardummy(0, log_);
202 EwaldRegion Ewalddummy(0, log_);
203 if (type == QMdummy.identify()) {
204 std::unique_ptr<QMRegion> qmregion =
205 std::make_unique<QMRegion>(id, log_, workdir_);
206 QMMapper qmmapper(log_);
207 qmmapper.LoadMappingFile(mapfile);
208 for (const SegId& seg_index : seg_ids) {
209 const Segment& segment = top.getSegment(seg_index.Id());
210 QMMolecule mol = qmmapper.map(segment, seg_index);
211 mol.setType("qm" + std::to_string(id));
212 ShiftPBC(top, center, mol);
213 foreground_union.push_back({seg_index.Id(), UnweightedCentroid(mol)});
214 qmregion->push_back(mol);
215 }
216 region = std::move(qmregion);
217 } else if (type == Polardummy.identify()) {
218 std::unique_ptr<PolarRegion> polarregion =
219 std::make_unique<PolarRegion>(id, log_);
220 PolarMapper polmap(log_);
221 polmap.LoadMappingFile(mapfile);
222 for (const SegId& seg_index : seg_ids) {
223 const Segment& segment = top.getSegment(seg_index.Id());
224
225 PolarSegment mol = polmap.map(segment, seg_index);
226
227 ShiftPBC(top, center, mol);
228 mol.setType("mm" + std::to_string(id));
229 foreground_union.push_back({seg_index.Id(), UnweightedCentroid(mol)});
230 polarregion->push_back(mol);
231 }
232 region = std::move(polarregion);
233 } else if (type == Staticdummy.identify()) {
234 std::unique_ptr<StaticRegion> staticregion =
235 std::make_unique<StaticRegion>(id, log_);
236 StaticMapper staticmap(log_);
237 staticmap.LoadMappingFile(mapfile);
238 for (const SegId& seg_index : seg_ids) {
239 const Segment& segment = top.getSegment(seg_index.Id());
240 StaticSegment mol = staticmap.map(segment, seg_index);
241 mol.setType("mm" + std::to_string(id));
242 ShiftPBC(top, center, mol);
243 foreground_union.push_back({seg_index.Id(), UnweightedCentroid(mol)});
244 staticregion->push_back(mol);
245 }
246 region = std::move(staticregion);
247
248 } else if (type == Ewalddummy.identify()) {
249 // Owns no segments of the job's topology: it represents the whole
250 // periodic cell, loaded from the background calculator's own
251 // checkpoint by its Initialize below. seg_ids is empty for it by
252 // construction (see CreateRegionSegIds).
253 region = std::make_unique<EwaldRegion>(id, log_);
254 } else {
255 throw std::runtime_error("Region type not known!");
256 }
257 region->Initialize(region_def);
258 regions_.push_back(std::move(region));
259 }
260
261 // After every region exists, so the declaration covers the complete
262 // union, and before any of them is evaluated.
263 for (std::unique_ptr<Region>& reg : regions_) {
264 EwaldRegion* ewald = dynamic_cast<EwaldRegion*>(reg.get());
265 if (ewald != nullptr) {
266 ewald->RegisterForeground(foreground_union);
267 }
268 }
269}
270
271void JobTopology::WriteToPdb(std::string filename) const {
272
273 csg::PDBWriter writer;
274 writer.Open(filename, false);
275 writer.WriteHeader("Job:" + std::to_string(this->job_.getId()));
276 for (const std::unique_ptr<Region>& reg : regions_) {
277 reg->WritePDB(writer);
278 }
279 writer.Close();
280}
281
282std::vector<std::vector<SegId>> JobTopology::PartitionRegions(
283 const tools::Property& regions_def, const Topology& top) const {
284
285 std::vector<const tools::Property*> sorted_regions =
286 SortRegionsDefbyId(regions_def);
287
288 std::vector<Index> explicitly_named_segs_per_region;
289 std::vector<std::vector<SegId>> segids_per_region;
290 std::vector<bool> processed_segments =
291 std::vector<bool>(top.Segments().size(), false);
292 for (const tools::Property* region_def : sorted_regions) {
293
294 // An ewaldregion takes no segments from this topology: it loads the
295 // periodic background written by the ewaldbackground calculator from a
296 // checkpoint, so it needs neither segments nor a cutoff.
297 EwaldRegion Ewalddummy(0, log_);
298 const bool is_ewald = region_def->name() == Ewalddummy.identify();
299 if (!is_ewald && !region_def->exists("segments") &&
300 !region_def->exists("cutoff")) {
301 throw std::runtime_error(
302 "Region definition needs either segments or a cutoff to find "
303 "segments");
304 }
305 if (is_ewald) {
306 segids_per_region.push_back(std::vector<SegId>());
307 continue;
308 }
309 std::vector<SegId> seg_ids;
310 if (region_def->exists("segments")) {
311 seg_ids = region_def->get("segments").as<std::vector<SegId>>();
312 for (const SegId& seg_id : seg_ids) {
313 if (seg_id.Id() > Index(top.Segments().size() - 1)) {
314 throw std::runtime_error("Segment id is not in topology");
315 }
316 processed_segments[seg_id.Id()] = true;
317 }
318 }
319 explicitly_named_segs_per_region.push_back(Index(seg_ids.size()));
320
321 if (region_def->exists("cutoff")) {
322 double cutoff =
323 tools::conv::nm2bohr * region_def->get("cutoff.radius").as<double>();
324
325 std::string seg_geometry =
326 region_def->get("cutoff.geometry").as<std::string>();
327 double min = top.getBox().diagonal().minCoeff();
328 if (cutoff > 0.5 * min) {
329 throw std::runtime_error(
330 (boost::format("Cutoff is larger than half the box size. Maximum "
331 "allowed cutoff is %1$1.1f") %
332 (tools::conv::bohr2nm * 0.5 * min))
333 .str());
334 }
335 std::vector<SegId> center = seg_ids;
336
337 Index id = region_def->get("cutoff.region").as<Index>();
338 bool only_explicit = region_def->get("cutoff.explicit_segs").as<bool>();
339 if (id < Index(segids_per_region.size())) {
340 center = segids_per_region[id];
341 if (only_explicit) {
342 Index no_of_segs = explicitly_named_segs_per_region[id];
343 if (no_of_segs == 0) {
344 throw std::runtime_error(
345 "Region with id '" + std::to_string(id) +
346 "' does not have explicitly named segments");
347 }
348 center.resize(no_of_segs, SegId(0, "n"));
349 // need the second argument because resize can also increase
350 // capacity of vector and then needs a constructor,
351 // here we shrink, so should not happen
352 }
353 } else if (id != region_def->get("id").as<Index>()) {
354 throw std::runtime_error("Region with id '" + std::to_string(id) +
355 "' used for cutoff does not exist");
356 }
357
358 if (center.empty()) {
359 throw std::runtime_error(
360 "Region needs either a segment or another region to which to "
361 "apply "
362 "the cutoff");
363 }
364 for (const SegId& segid : center) {
365 const Segment& center_seg = top.getSegment(segid.Id());
366 for (const Segment& otherseg : top.Segments()) {
367 if (center_seg.getId() == otherseg.getId() ||
368 processed_segments[otherseg.getId()]) {
369 continue;
370 }
371 if (top.PbShortestConnect(center_seg.getPos(), otherseg.getPos())
372 .norm() < cutoff) {
373 seg_ids.push_back(SegId(otherseg.getId(), seg_geometry));
374 processed_segments[otherseg.getId()] = true;
375 }
376 }
377 }
378 }
379 segids_per_region.push_back(seg_ids);
380 }
381 return segids_per_region;
382}
383
385 const tools::Property& regions_def) const {
386 std::vector<Index> reg_ids;
387 for (const tools::Property& region_def : regions_def) {
388 reg_ids.push_back(region_def.get("id").as<Index>());
389 }
390
391 std::vector<Index> v(reg_ids.size());
392 std::iota(v.begin(), v.end(), 0);
393 if (!std::is_permutation(reg_ids.begin(), reg_ids.end(), v.begin())) {
394 throw std::runtime_error(
395 "Region id definitions are not clear. You must start at id 0 and "
396 "then "
397 "ascending order. i.e. 0 1 2 3.");
398 }
399
400 // The whole job topology is centred on region 0's FIRST segment, and an
401 // ewaldregion owns none -- its entry in region_seg_ids is empty by
402 // construction. Reading element zero of it is undefined behaviour, so
403 // the rule is stated here rather than left to a crash far downstream.
404 EwaldRegion Ewalddummy(0, log_);
405 for (const tools::Property& region_def : regions_def) {
406 if (region_def.name() == Ewalddummy.identify() &&
407 region_def.get("id").as<Index>() == 0) {
408 throw std::runtime_error(
409 "An ewaldregion cannot be region 0: it owns no segments of the "
410 "job's topology, and the job is centred on region 0's first "
411 "segment.");
412 }
413 }
414}
415
416void JobTopology::WriteToHdf5(std::string filename) const {
417 std::lock_guard<std::recursive_mutex> lock(
420 CheckpointWriter a = cpf.getWriter();
421 a(job_.getId(), "jobid");
422 a(votca::tools::ToolsVersionStr(), "XTPVersion");
423 a(jobtopology_version(), "version");
424 for (const auto& region : regions_) {
426 cpf.getWriter("region_" + std::to_string(region->getId()));
427 region->WriteToCpt(w);
428 }
429}
430
431void JobTopology::ReadFromHdf5(std::string filename) {
432 std::lock_guard<std::recursive_mutex> lock(
435 CheckpointReader a = cpf.getReader();
436 Index id = -1;
437 a(id, "jobid");
438 if (id != job_.getId()) {
439 throw std::runtime_error(
440 "Jobid from checkpoint file does not agree with jobid" +
441 std::to_string(id) + ":" + std::to_string(job_.getId()));
442 }
443 regions_.clear();
444 Index no_regions = a.getNumDataSets();
445 regions_.reserve(no_regions);
446
447 QMRegion QMdummy(0, log_, "");
448 StaticRegion Staticdummy(0, log_);
449 PolarRegion Polardummy(0, log_);
450
451 for (Index i = 0; i < no_regions; i++) {
452 CheckpointReader r = cpf.getReader("region_" + std::to_string(i));
453 std::string type;
454 r(type, "type");
455
456 std::unique_ptr<Region> region = nullptr;
457 if (type == QMdummy.identify()) {
458 region = std::make_unique<QMRegion>(i, log_, workdir_);
459 } else if (type == Polardummy.identify()) {
460 region = std::make_unique<PolarRegion>(i, log_);
461 } else if (type == Staticdummy.identify()) {
462 region = std::make_unique<StaticRegion>(i, log_);
463 } else {
464 throw std::runtime_error("Region type:" + type + " not known!");
465 }
466 region->ReadFromCpt(r);
467 if (id != region->getId()) {
468 throw std::runtime_error("read in the wrong region, ids are mismatched.");
469 }
470 regions_.push_back(std::move(region));
471 }
472}
473
474} // namespace xtp
475} // namespace votca
void WriteHeader(std::string header)
Definition pdbwriter.cc:41
void Close() override
Definition pdbwriter.cc:51
void Open(std::string file, bool bAppend=false) override
Definition pdbwriter.cc:33
class to manage program options with xml serialization functionality
Definition property.h:55
Property & get(const std::string &key)
get existing property
Definition property.cc:79
std::string & value()
reference to value of property
Definition property.h:153
iterator end()
end iterator for child properties
Definition property.h:191
bool exists(const std::string &key) const
check whether property exists
Definition property.cc:122
T as() const
return value as type
Definition property.h:283
iterator begin()
iterator to first child property
Definition property.h:188
bool HasChildren() const
does the property have children?
Definition property.h:182
std::string & name()
name of property
Definition property.h:159
std::vector< Property * > Select(const std::string &filter)
select property based on a filter
Definition property.cc:185
void setType(std::string type)
const Eigen::Vector3d & getPos() const
CheckpointReader getReader()
CheckpointWriter getWriter()
The periodic Ewald background, as a Region.
Definition ewaldregion.h:74
std::string identify() const override
Definition ewaldregion.h:79
void RegisterForeground(const std::vector< std::pair< Index, Eigen::Vector3d > > &foreground)
std::vector< std::unique_ptr< Region > > regions_
void ShiftPBC(const Topology &top, const Eigen::Vector3d &center, T &mol) const
std::vector< const tools::Property * > SortRegionsDefbyId(const tools::Property &regions_def) const
void ReadFromHdf5(std::string filename)
static constexpr int jobtopology_version()
void CreateRegions(const std::pair< std::string, tools::Property > &options, const Topology &top, const std::vector< std::vector< SegId > > &region_seg_ids)
std::vector< std::vector< SegId > > PartitionRegions(const tools::Property &regions_def, const Topology &top) const
void WriteToPdb(std::string filename) const
void CheckEnumerationOfRegions(const tools::Property &regions_def) const
void BuildRegions(const Topology &top, std::pair< std::string, tools::Property > options)
void WriteToHdf5(std::string filename) const
void ModifyOptionsByJobFile(tools::Property &regions_def) const
std::string identify() const override
Definition polarregion.h:52
std::string identify() const override
Definition qmregion.h:83
void LoadMappingFile(const std::string &mapfile)
AtomContainer map(const Segment &seg, const SegId &segid) const
std::string identify() const override
Container for segments and box and atoms.
Definition topology.h:41
Eigen::Vector3d PbShortestConnect(const Eigen::Vector3d &r1, const Eigen::Vector3d &r2) const
Definition topology.cc:140
std::vector< Segment > & Segments()
Definition topology.h:58
const Eigen::Matrix3d & getBox() const
Definition topology.h:64
Segment & getSegment(Index id)
Definition topology.h:55
#define XTP_LOG(level, log)
Definition logger.h:40
const double bohr2nm
Definition constants.h:46
const double nm2bohr
Definition constants.h:47
const std::string & ToolsVersionStr()
Definition version.cc:33
std::recursive_mutex & Hdf5Mutex()
Charge transport classes.
Definition ERIs.h:28
ClassicalSegment< PolarSite > PolarSegment
SegmentMapper< PolarSegment > PolarMapper
SegmentMapper< QMMolecule > QMMapper
ClassicalSegment< StaticSite > StaticSegment
SegmentMapper< StaticSegment > StaticMapper
std::vector< std::string > ModifyRegionOptionsFromJobFileRegion(tools::Property &opt, const tools::Property &job_opt)
Provides a means for comparing floating point numbers.
Definition basebead.h:33
Eigen::Index Index
Definition types.h:26