structure-clustering 1.2.0__tar.gz → 1.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/.github/workflows/wheels.yml +2 -1
  2. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/PKG-INFO +13 -7
  3. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/README.md +12 -6
  4. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/pyproject.toml +1 -1
  5. structure_clustering-1.2.2/src/Result.cpp +156 -0
  6. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/src/Structure.cpp +3 -0
  7. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/src/Structure.hpp +5 -0
  8. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/src/main.cpp +2 -1
  9. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/src/structure_clustering/__main__.py +63 -30
  10. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/src/structure_clustering/import_multi_xyz.py +17 -3
  11. structure_clustering-1.2.0/src/Result.cpp +0 -99
  12. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/.gitignore +0 -0
  13. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/CMakeLists.txt +0 -0
  14. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/LICENSE +0 -0
  15. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/src/Atom.hpp +0 -0
  16. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/src/ChemcraftWriter.cpp +0 -0
  17. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/src/ChemcraftWriter.hpp +0 -0
  18. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/src/Machine.cpp +0 -0
  19. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/src/Machine.hpp +0 -0
  20. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/src/Result.hpp +0 -0
  21. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/src/constants.hpp +0 -0
  22. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/src/hash.hpp +0 -0
  23. {structure_clustering-1.2.0 → structure_clustering-1.2.2}/src/structure_clustering/__init__.py +0 -0
@@ -62,10 +62,11 @@ jobs:
62
62
  wget 'https://sourceforge.net/projects/boost/files/boost/1.86.0/boost_1_86_0.tar.bz2' &&
63
63
  tar xf boost_1_86_0.tar.bz2 &&
64
64
  mv boost_1_86_0 boost
65
+ # it seems that the old tar command does no longer work
65
66
  CIBW_BEFORE_ALL_WINDOWS: >
66
67
  mkdir boost && cd boost &&
67
68
  curl -L -o boost_1_86_0.zip https://sourceforge.net/projects/boost/files/boost/1.86.0/boost_1_86_0.zip/download &&
68
- tar xf boost_1_86_0.zip &&
69
+ pwsh -Command "Expand-Archive -Path boost_1_86_0.zip -DestinationPath . -Force" &&
69
70
  ren boost_1_86_0 boost
70
71
 
71
72
  - name: Verify clean directory
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: structure_clustering
3
- Version: 1.2.0
3
+ Version: 1.2.2
4
4
  Summary: Python package for fast exact clustering of similar molecular structures through parameterized connectivity graphs.
5
5
  Author: Michael Gatt, Gabriel Schöpfer, Milan Ončák
6
6
  Maintainer: Michael Gatt
@@ -68,12 +68,18 @@ To choose another Chemcraft output path:
68
68
  structure_clustering structures.xyz -ec results.chemcraft.chd
69
69
  ```
70
70
 
71
- To write only a deduplicated set of structures, use `--representatives-only`:
71
+ To limit the number of exported structures per cluster, use `--export-limit`:
72
72
  ```bash
73
- structure_clustering structures.xyz --representatives-only
73
+ structure_clustering structures.xyz --export-limit
74
74
  ```
75
75
 
76
- This keeps the first structure from each cluster and all unique singles in the exported file. Clustering itself is unchanged; the option only filters the written output. If native output is requested with `-e`, the same filtering is applied there as well.
76
+ Without an integer, the limit defaults to 10 structures per cluster. To choose another limit, provide it explicitly, for example:
77
+ ```bash
78
+ structure_clustering structures.xyz --export-limit 3
79
+ ```
80
+
81
+ If `--export-limit` is omitted, all structures are exported as usual. Unique singles are always exported, and clustering itself is unchanged. The same limit is applied to both Chemcraft and optional native output. `--export-limit 1` therefore exports one representative from each non-singleton cluster plus all unique singles.
82
+
77
83
 
78
84
  The native clustering format is optional and can be written in addition:
79
85
  ```bash
@@ -92,7 +98,7 @@ The native `.dat` output can be visualized with [cluster-vis](https://photophys.
92
98
  ```text
93
99
  usage: structure_clustering [-h] [--disconnected] [--config CONFIG]
94
100
  [-e [FILE]] [-ec [FILE]]
95
- [--representatives-only]
101
+ [--export-limit [N]]
96
102
  xyz_file
97
103
  ```
98
104
 
@@ -103,7 +109,7 @@ Options:
103
109
  - `--disconnected`: include disconnected graphs in clustering. By default, disconnected structures are sorted out. An explicit CLI flag overrides `options.only_connected_graphs` from the TOML file.
104
110
  - `-e [FILE]`, `--export [FILE]`: additionally write the native clustering output. Without a filename, uses `sc.dat`.
105
111
  - `-ec [FILE]`, `--export-chemcraft [FILE]`: set the Chemcraft-compatible output path. Chemcraft output is written by default to `sc.chemcraft.chd`. Note that the file extension needs to be **`.chd`**, otherwise Chemcraft will not read it properly.
106
- - `--representatives-only`: export only the first structure from each cluster, plus all unique single structures. This affects both Chemcraft and native output and does not change clustering itself.
112
+ - `--export-limit [N]`: limit output of each luster to maximum `N` exported structures. Without `N`, defaults to 10. If the option is omitted, all structures are exported. Unique singles are always included. This affects both Chemcraft and native output and does not change clustering itself.
107
113
  - `-h`, `--help`: show the command-line help.
108
114
 
109
115
  If the installed `structure_clustering` command is not on your `PATH`, use:
@@ -115,7 +121,7 @@ python -m structure_clustering structures.xyz
115
121
  ### Example
116
122
 
117
123
  ```bash
118
- structure_clustering structures.xyz -ec clusters.chd --representatives-only
124
+ structure_clustering structures.xyz -ec clusters.chd --export-limit
119
125
  ```
120
126
 
121
127
  A typical run reports the number of clusters and singles, the number of structures sorted out, cluster-size statistics, and connectivity statistics. In the default connected-only mode, the sorted-out count includes disconnected structures as well as redundant members removed when one representative per cluster is retained.
@@ -38,12 +38,18 @@ To choose another Chemcraft output path:
38
38
  structure_clustering structures.xyz -ec results.chemcraft.chd
39
39
  ```
40
40
 
41
- To write only a deduplicated set of structures, use `--representatives-only`:
41
+ To limit the number of exported structures per cluster, use `--export-limit`:
42
42
  ```bash
43
- structure_clustering structures.xyz --representatives-only
43
+ structure_clustering structures.xyz --export-limit
44
44
  ```
45
45
 
46
- This keeps the first structure from each cluster and all unique singles in the exported file. Clustering itself is unchanged; the option only filters the written output. If native output is requested with `-e`, the same filtering is applied there as well.
46
+ Without an integer, the limit defaults to 10 structures per cluster. To choose another limit, provide it explicitly, for example:
47
+ ```bash
48
+ structure_clustering structures.xyz --export-limit 3
49
+ ```
50
+
51
+ If `--export-limit` is omitted, all structures are exported as usual. Unique singles are always exported, and clustering itself is unchanged. The same limit is applied to both Chemcraft and optional native output. `--export-limit 1` therefore exports one representative from each non-singleton cluster plus all unique singles.
52
+
47
53
 
48
54
  The native clustering format is optional and can be written in addition:
49
55
  ```bash
@@ -62,7 +68,7 @@ The native `.dat` output can be visualized with [cluster-vis](https://photophys.
62
68
  ```text
63
69
  usage: structure_clustering [-h] [--disconnected] [--config CONFIG]
64
70
  [-e [FILE]] [-ec [FILE]]
65
- [--representatives-only]
71
+ [--export-limit [N]]
66
72
  xyz_file
67
73
  ```
68
74
 
@@ -73,7 +79,7 @@ Options:
73
79
  - `--disconnected`: include disconnected graphs in clustering. By default, disconnected structures are sorted out. An explicit CLI flag overrides `options.only_connected_graphs` from the TOML file.
74
80
  - `-e [FILE]`, `--export [FILE]`: additionally write the native clustering output. Without a filename, uses `sc.dat`.
75
81
  - `-ec [FILE]`, `--export-chemcraft [FILE]`: set the Chemcraft-compatible output path. Chemcraft output is written by default to `sc.chemcraft.chd`. Note that the file extension needs to be **`.chd`**, otherwise Chemcraft will not read it properly.
76
- - `--representatives-only`: export only the first structure from each cluster, plus all unique single structures. This affects both Chemcraft and native output and does not change clustering itself.
82
+ - `--export-limit [N]`: limit output of each luster to maximum `N` exported structures. Without `N`, defaults to 10. If the option is omitted, all structures are exported. Unique singles are always included. This affects both Chemcraft and native output and does not change clustering itself.
77
83
  - `-h`, `--help`: show the command-line help.
78
84
 
79
85
  If the installed `structure_clustering` command is not on your `PATH`, use:
@@ -85,7 +91,7 @@ python -m structure_clustering structures.xyz
85
91
  ### Example
86
92
 
87
93
  ```bash
88
- structure_clustering structures.xyz -ec clusters.chd --representatives-only
94
+ structure_clustering structures.xyz -ec clusters.chd --export-limit
89
95
  ```
90
96
 
91
97
  A typical run reports the number of clusters and singles, the number of structures sorted out, cluster-size statistics, and connectivity statistics. In the default connected-only mode, the sorted-out count includes disconnected structures as well as redundant members removed when one representative per cluster is retained.
@@ -4,7 +4,7 @@ build-backend = "scikit_build_core.build"
4
4
 
5
5
  [project]
6
6
  name = "structure_clustering"
7
- version = "1.2.0"
7
+ version = "1.2.2"
8
8
  description = "Python package for fast exact clustering of similar molecular structures through parameterized connectivity graphs."
9
9
  readme = "README.md"
10
10
  authors = [
@@ -0,0 +1,156 @@
1
+ #include <algorithm>
2
+ #include <fstream>
3
+ #include <string>
4
+ #include <vector>
5
+ #include <stdexcept>
6
+ #include <iomanip>
7
+ #include <iostream>
8
+ #include <cmath>
9
+ #include <limits>
10
+ #include <sstream>
11
+
12
+ #include "Result.hpp"
13
+ #include "constants.hpp"
14
+ #include "ChemcraftWriter.hpp"
15
+
16
+ Result::Result(std::vector<Structure> &structures)
17
+ : _clusters({}), _singles({}), _structures(structures) {};
18
+
19
+ void Result::addSingle(const int structureIdx) { _singles.push_back(structureIdx); }
20
+
21
+ void Result::addCluster(const std::vector<int> structureIdxs) {
22
+ _clusters.push_back(structureIdxs);
23
+ }
24
+
25
+ std::string getElementSymbol(int atomicNumber) {
26
+ const auto &elements = CHEMICAL_ELEMENTS;
27
+
28
+ if (atomicNumber < 1 || atomicNumber > elements.size()) {
29
+ throw std::out_of_range("Invalid atomic number");
30
+ }
31
+
32
+ return elements[atomicNumber - 1];
33
+ }
34
+
35
+ void Result::exportDat(const std::string filepath) const {
36
+ std::ofstream file;
37
+ file.open(filepath);
38
+
39
+ // write groups
40
+ file << "@GROUPS" << std::endl;
41
+ for (auto &cluster : _clusters) {
42
+ for (auto &id : cluster) {
43
+ file << id + 1 << " ";
44
+ }
45
+ file << std::endl;
46
+ }
47
+
48
+ // write singles
49
+ file << "@UNIQUES" << std::endl;
50
+ for (auto &id : _singles) {
51
+ file << id + 1 << " ";
52
+ }
53
+ file << std::endl;
54
+
55
+ // write graphs
56
+ typedef boost::graph_traits<Graph>::edge_iterator edge_iterator;
57
+ for (size_t i = 0; i < _structures.size(); i++) {
58
+ auto &graph = _structures[i].getGraph();
59
+ file << "@GRAPH-" << i + 1 << std::endl;
60
+ std::pair<edge_iterator, edge_iterator> ei = edges(graph);
61
+ for (edge_iterator it = ei.first; it != ei.second; ++it) {
62
+ file << source(*it, graph) + 1 << " " << target(*it, graph) + 1 << std::endl;
63
+ }
64
+ }
65
+
66
+ // write geometries
67
+ for (size_t i = 0; i < _structures.size(); i++) {
68
+ file << "@STRUCTURE-" << i + 1 << std::endl;
69
+ auto &structure = _structures[i];
70
+ for (int j = 0; j < structure.numAtoms(); j++) {
71
+ auto &atom = structure.getAtom(j);
72
+ file << getElementSymbol(atom.atomicNumber()) << " " << atom.position().x() << " "
73
+ << atom.position().y() << " " << atom.position().z() << std::endl;
74
+ }
75
+ }
76
+
77
+ file.close();
78
+ }
79
+
80
+ void Result::exportChemcraft(const std::string filepath) const {
81
+ const bool hasEnergies = std::any_of(
82
+ _structures.begin(), _structures.end(),
83
+ [](const Structure &structure) { return structure.getEnergyEV().has_value(); });
84
+
85
+ // Preserve the original export when the XYZ input has no energies.
86
+ if (!hasEnergies) {
87
+ auto chemcraftFile = ChemcraftWriter(filepath);
88
+ for (auto &cluster : _clusters) {
89
+ chemcraftFile.startCluster(_structures[cluster[0]].getHash());
90
+ for (auto &id : cluster) {
91
+ chemcraftFile.writeStructure(_structures[id]);
92
+ }
93
+ }
94
+ for (auto &id : _singles) {
95
+ chemcraftFile.startSingle(_structures[id].getHash());
96
+ chemcraftFile.writeStructure(_structures[id]);
97
+ }
98
+ chemcraftFile.close();
99
+ return;
100
+ }
101
+
102
+ double minimumEnergy = std::numeric_limits<double>::infinity();
103
+ for (const auto &structure : _structures) {
104
+ const auto energy = structure.getEnergyEV();
105
+ if (!energy.has_value() || !std::isfinite(*energy)) {
106
+ throw std::runtime_error(
107
+ "All XYZ structures must have valid energies for energy-sorted Chemcraft output.");
108
+ }
109
+ minimumEnergy = std::min(minimumEnergy, *energy);
110
+ }
111
+
112
+ struct Job {
113
+ bool isCluster;
114
+ std::size_t index;
115
+ double energy;
116
+ };
117
+ std::vector<Job> jobs;
118
+ jobs.reserve(_clusters.size() + _singles.size());
119
+
120
+ for (std::size_t i = 0; i < _clusters.size(); ++i) {
121
+ const auto &cluster = _clusters[i];
122
+ if (cluster.empty()) continue;
123
+ double clusterEnergy = std::numeric_limits<double>::infinity();
124
+ for (int id : cluster) {
125
+ clusterEnergy = std::min(clusterEnergy, *_structures[id].getEnergyEV());
126
+ }
127
+ jobs.push_back({true, i, clusterEnergy});
128
+ }
129
+ for (std::size_t i = 0; i < _singles.size(); ++i) {
130
+ jobs.push_back({false, i, *_structures[_singles[i]].getEnergyEV()});
131
+ }
132
+
133
+ std::stable_sort(jobs.begin(), jobs.end(),
134
+ [](const Job &a, const Job &b) { return a.energy < b.energy; });
135
+
136
+ auto chemcraftFile = ChemcraftWriter(filepath);
137
+ for (const auto &job : jobs) {
138
+ std::ostringstream label;
139
+ label << std::fixed << std::setprecision(4)
140
+ << (job.energy - minimumEnergy) << " eV";
141
+ if (job.isCluster) {
142
+ chemcraftFile.startCluster(label.str());
143
+ for (int id : _clusters[job.index]) {
144
+ chemcraftFile.writeStructure(_structures[id]);
145
+ }
146
+ } else {
147
+ chemcraftFile.startSingle(label.str());
148
+ chemcraftFile.writeStructure(_structures[_singles[job.index]]);
149
+ }
150
+ }
151
+ chemcraftFile.close();
152
+ };
153
+
154
+ std::vector<std::vector<int>> Result::getClusters() const { return _clusters; };
155
+ std::vector<int> Result::getSingles() const { return _singles; };
156
+ std::vector<Structure> Result::getStructures() const { return _structures; };
@@ -27,6 +27,9 @@ bool isConnected(const double &r_a, const double &r_b, const double &distance_ab
27
27
 
28
28
  Structure::Structure(const int id) : _id(id), _graph({}) {}
29
29
 
30
+ void Structure::setEnergyEV(double energy_eV) { _energy_eV = energy_eV; }
31
+ std::optional<double> Structure::getEnergyEV() const { return _energy_eV; }
32
+
30
33
  void Structure::addAtom(const Atom &atom) { _atoms.push_back(atom); }
31
34
 
32
35
  int Structure::numAtoms() const { return _atoms.size(); }
@@ -2,6 +2,7 @@
2
2
  #define __STRUCTURE__
3
3
 
4
4
  #include <iostream>
5
+ #include <optional>
5
6
  #include <string>
6
7
  #include <vector>
7
8
 
@@ -21,6 +22,7 @@ class Structure {
21
22
  int _id;
22
23
  std::vector<Atom> _atoms;
23
24
  Graph _graph;
25
+ std::optional<double> _energy_eV;
24
26
 
25
27
  public:
26
28
  Structure(const int id);
@@ -41,6 +43,9 @@ public:
41
43
  const int getNumFragments() const;
42
44
  const std::vector<int> getFragmentAtomIndices(int fragmentIndex) const;
43
45
 
46
+ void setEnergyEV(double energy_eV);
47
+ std::optional<double> getEnergyEV() const;
48
+
44
49
  int getId() const;
45
50
  };
46
51
 
@@ -25,13 +25,14 @@ PYBIND11_MODULE(_core, m) {
25
25
  py::class_<Structure>(m, "Structure")
26
26
  .def(py::init<int>())
27
27
  .def("addAtom", &Structure::addAtom)
28
+ .def("setEnergyEV", &Structure::setEnergyEV)
28
29
  .def_property_readonly("numConnections", &Structure::getNumConnections)
29
30
  .def_property_readonly("numAtoms", &Structure::numAtoms)
30
31
  .def_property_readonly("numFragments", &Structure::getNumFragments)
31
32
  .def("getHash", &Structure::getHash)
32
33
  .def("getFragmentAtomIndices", &Structure::getFragmentAtomIndices)
33
34
  .def("getAtom", &Structure::getAtom);
34
-
35
+
35
36
  py::class_<Atom>(m, "Atom")
36
37
  .def(py::init<const int, const double, const double, const double>())
37
38
  .def_property_readonly("atomic_number", &Atom::atomicNumber)
@@ -14,6 +14,7 @@ from structure_clustering import element_to_atomic_number
14
14
  DEFAULT_OH_MAX_DISTANCE = 2.3
15
15
  DEFAULT_NATIVE_OUTPUT = Path("sc.dat")
16
16
  DEFAULT_CHEMCRAFT_OUTPUT = Path("sc.chemcraft.chd")
17
+ DEFAULT_OUTPUT_LIMIT = 10
17
18
 
18
19
 
19
20
  def build_parser() -> argparse.ArgumentParser:
@@ -76,11 +77,15 @@ def build_parser() -> argparse.ArgumentParser:
76
77
  )
77
78
 
78
79
  parser.add_argument(
79
- "--representatives-only",
80
- action="store_true",
80
+ "--export-limit",
81
+ nargs="?",
82
+ const=DEFAULT_OUTPUT_LIMIT,
83
+ default=None,
84
+ type=int,
85
+ metavar="N",
81
86
  help=(
82
- "Export only one representative from each cluster, "
83
- "plus all unique single structures."
87
+ "Limit each cluster to at most N structures in exported files. Without N,"
88
+ f"defaults to {DEFAULT_OUTPUT_LIMIT}. If omitted, exports all structures."
84
89
  ),
85
90
  )
86
91
 
@@ -223,9 +228,10 @@ def validate_output_paths(
223
228
  )
224
229
 
225
230
 
226
- def export_representative_chemcraft(
231
+ def export_limited_chemcraft(
227
232
  result,
228
233
  output_path: Path,
234
+ limit: int,
229
235
  ) -> None:
230
236
  with tempfile.TemporaryDirectory() as temporary_directory:
231
237
  temporary_path = Path(temporary_directory) / "full.chemcraft.xyz"
@@ -253,25 +259,27 @@ def export_representative_chemcraft(
253
259
  filtered_lines.extend(block)
254
260
  continue
255
261
 
256
- first_geometry_end = next(
257
- (
258
- line_index
259
- for line_index, line in enumerate(block)
260
- if line.strip() == "[/geometry]"
261
- ),
262
- None,
263
- )
264
- if first_geometry_end is None:
262
+ geometry_ends = [
263
+ line_index
264
+ for line_index, line in enumerate(block)
265
+ if line.strip() == "[/geometry]"
266
+ ]
267
+ if not geometry_ends:
265
268
  raise RuntimeError(
266
- "Could not identify the first geometry in Chemcraft cluster output."
269
+ "Could not identify geometries in Chemcraft cluster output."
267
270
  )
268
271
 
269
- filtered_lines.extend(block[: first_geometry_end + 1])
272
+ if len(geometry_ends) <= limit:
273
+ filtered_lines.extend(block)
274
+ continue
275
+
276
+ last_geometry_end = geometry_ends[limit - 1]
277
+ filtered_lines.extend(block[: last_geometry_end + 1])
270
278
 
271
279
  trailing_geometry = next(
272
280
  (
273
281
  line
274
- for line in block[first_geometry_end + 1 :]
282
+ for line in block[last_geometry_end + 1 :]
275
283
  if line.strip() == "[Geometry]"
276
284
  ),
277
285
  None,
@@ -280,19 +288,19 @@ def export_representative_chemcraft(
280
288
  filtered_lines.append(trailing_geometry)
281
289
 
282
290
  filtered_lines.extend(
283
- line for line in block[first_geometry_end + 1 :]
291
+ line for line in block[last_geometry_end + 1 :]
284
292
  if line.strip() == "[/Job]"
285
293
  )
286
294
 
287
295
  output_path.write_text("".join(filtered_lines))
288
296
 
289
297
 
290
- def export_representative_native(
298
+ def export_limited_native(
291
299
  result,
292
300
  output_path: Path,
293
301
  clusters: Sequence[Sequence[int]],
294
302
  singles: Sequence[int],
295
- representative_indices: Sequence[int],
303
+ export_indices: Sequence[int],
296
304
  ) -> None:
297
305
  with tempfile.TemporaryDirectory() as temporary_directory:
298
306
  temporary_path = Path(temporary_directory) / "full.dat"
@@ -319,13 +327,15 @@ def export_representative_native(
319
327
 
320
328
  old_to_new = {
321
329
  old_index: new_index
322
- for new_index, old_index in enumerate(representative_indices, start=1)
330
+ for new_index, old_index in enumerate(export_indices, start=1)
323
331
  }
324
332
 
325
333
  output_lines = ["@GROUPS\n"]
326
334
  for cluster in clusters:
327
335
  if cluster:
328
- output_lines.append(f"{old_to_new[cluster[0]]}\n")
336
+ output_lines.append(
337
+ " ".join(str(old_to_new[index]) for index in cluster) + "\n"
338
+ )
329
339
 
330
340
  output_lines.append("@UNIQUES\n")
331
341
  output_lines.append(
@@ -333,7 +343,7 @@ def export_representative_native(
333
343
  )
334
344
 
335
345
  for section_type in ("GRAPH", "STRUCTURE"):
336
- for new_index, old_index in enumerate(representative_indices, start=1):
346
+ for new_index, old_index in enumerate(export_indices, start=1):
337
347
  if old_index not in sections[section_type]:
338
348
  raise RuntimeError(
339
349
  f"Could not find @{section_type}-{old_index + 1} in native output."
@@ -354,6 +364,9 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
354
364
  if args.config is not None and not args.config.is_file():
355
365
  parser.error(f"Configuration file does not exist: {args.config}")
356
366
 
367
+ if args.export_limit is not None and args.export_limit < 1:
368
+ parser.error("--export-limit must be a positive integer.")
369
+
357
370
  validate_output_paths(
358
371
  parser,
359
372
  native_output=args.export,
@@ -451,7 +464,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
451
464
  print("\nClustering finished")
452
465
  print(
453
466
  f" {len(clusters)} clusters "
454
- f"({num_clustered_structures} structures in non-singleton clusters)"
467
+ f"({num_clustered_structures} structures in non-single clusters)"
455
468
  )
456
469
  print(f" {len(singles)} unique single structures")
457
470
  print(
@@ -468,15 +481,31 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
468
481
  f"(remaining {num_remaining_structures})"
469
482
  )
470
483
 
484
+ limited_clusters = None
485
+ limited_export_indices = None
486
+ if args.export_limit is not None:
487
+ limited_clusters = [
488
+ cluster[: args.export_limit]
489
+ for cluster in clusters
490
+ ]
491
+ limited_export_indices = sorted(
492
+ singles
493
+ + [
494
+ structure_index
495
+ for cluster in limited_clusters
496
+ for structure_index in cluster
497
+ ]
498
+ )
499
+
471
500
  if args.export is not None:
472
501
  print(f"\nWriting native output file to {args.export} ...")
473
- if args.representatives_only:
474
- export_representative_native(
502
+ if args.export_limit is not None:
503
+ export_limited_native(
475
504
  result,
476
505
  args.export,
477
- clusters,
506
+ limited_clusters,
478
507
  singles,
479
- remaining_indices,
508
+ limited_export_indices,
480
509
  )
481
510
  else:
482
511
  result.export(str(args.export))
@@ -486,8 +515,12 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
486
515
  f"\nWriting Chemcraft output file to "
487
516
  f"{args.export_chemcraft} ..."
488
517
  )
489
- if args.representatives_only:
490
- export_representative_chemcraft(result, args.export_chemcraft)
518
+ if args.export_limit is not None:
519
+ export_limited_chemcraft(
520
+ result,
521
+ args.export_chemcraft,
522
+ args.export_limit,
523
+ )
491
524
  else:
492
525
  result.exportChemcraft(str(args.export_chemcraft))
493
526
 
@@ -1,5 +1,13 @@
1
+ import re
2
+
1
3
  from structure_clustering import Atom, Structure
2
4
 
5
+ HARTREE_TO_EV = 27.211386245988
6
+ _ENERGY_NUMBER = r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?"
7
+ _NAMED_ENERGY = re.compile(rf"\b(?:energy|E)\s*[:=]\s*({_ENERGY_NUMBER})", re.I)
8
+ _LEADING_ENERGY = re.compile(rf"^\s*({_ENERGY_NUMBER})(?=\s|$)")
9
+ _EV_UNIT = re.compile(r"\beV\b", re.I)
10
+
3
11
 
4
12
  def element_to_atomic_number(symbol):
5
13
  # fmt:off
@@ -27,7 +35,7 @@ def import_multi_xyz(file_path):
27
35
 
28
36
  Per frame:
29
37
  1) atom count (int)
30
- 2) comment line (ignored)
38
+ 2) comment line (energy, when present)
31
39
  3) N coordinate lines: "Element x y z" (extra trailing tokens ignored)
32
40
  4) next frame begins only after at least one blank line
33
41
  """
@@ -55,12 +63,18 @@ def import_multi_xyz(file_path):
55
63
  atom_count = int(count_line)
56
64
  start_idx = i
57
65
  i += 1 # move past atom count
58
-
59
- # skip the comment line (also if empty)
66
+ # read the comment line (also if empty)
67
+ comment = lines[i] if i < n else ""
60
68
  if i < n:
61
69
  i += 1
62
70
 
63
71
  s = Structure(start_idx)
72
+ match = _NAMED_ENERGY.search(comment) or _LEADING_ENERGY.match(comment)
73
+ if match is not None:
74
+ energy_eV = float(match.group(1))
75
+ if _EV_UNIT.search(comment) is None:
76
+ energy_eV *= HARTREE_TO_EV
77
+ s.setEnergyEV(energy_eV)
64
78
 
65
79
  # read exactly atom_count atom lines (skipping blank lines if they appear)
66
80
  atoms_read = 0
@@ -1,99 +0,0 @@
1
- #include <fstream>
2
- #include <string>
3
- #include <vector>
4
- #include <stdexcept>
5
- #include <iomanip>
6
- #include <iostream>
7
-
8
- #include "Result.hpp"
9
- #include "constants.hpp"
10
- #include "ChemcraftWriter.hpp"
11
-
12
- Result::Result(std::vector<Structure> &structures)
13
- : _clusters({}), _singles({}), _structures(structures) {};
14
-
15
- void Result::addSingle(const int structureIdx) { _singles.push_back(structureIdx); }
16
-
17
- void Result::addCluster(const std::vector<int> structureIdxs) {
18
- _clusters.push_back(structureIdxs);
19
- }
20
-
21
- std::string getElementSymbol(int atomicNumber) {
22
- const auto &elements = CHEMICAL_ELEMENTS;
23
-
24
- if (atomicNumber < 1 || atomicNumber > elements.size()) {
25
- throw std::out_of_range("Invalid atomic number");
26
- }
27
-
28
- return elements[atomicNumber - 1];
29
- }
30
-
31
- void Result::exportDat(const std::string filepath) const {
32
- std::ofstream file;
33
- file.open(filepath);
34
-
35
- // write groups
36
- file << "@GROUPS" << std::endl;
37
- for (auto &cluster : _clusters) {
38
- for (auto &id : cluster) {
39
- file << id + 1 << " ";
40
- }
41
- file << std::endl;
42
- }
43
-
44
- // write singles
45
- file << "@UNIQUES" << std::endl;
46
- for (auto &id : _singles) {
47
- file << id + 1 << " ";
48
- }
49
- file << std::endl;
50
-
51
- // write graphs
52
- typedef boost::graph_traits<Graph>::edge_iterator edge_iterator;
53
- for (size_t i = 0; i < _structures.size(); i++) {
54
- auto &graph = _structures[i].getGraph();
55
- file << "@GRAPH-" << i + 1 << std::endl;
56
- std::pair<edge_iterator, edge_iterator> ei = edges(graph);
57
- for (edge_iterator it = ei.first; it != ei.second; ++it) {
58
- file << source(*it, graph) + 1 << " " << target(*it, graph) + 1 << std::endl;
59
- }
60
- }
61
-
62
- // write geometries
63
- for (size_t i = 0; i < _structures.size(); i++) {
64
- file << "@STRUCTURE-" << i + 1 << std::endl;
65
- auto &structure = _structures[i];
66
- for (int j = 0; j < structure.numAtoms(); j++) {
67
- auto &atom = structure.getAtom(j);
68
- file << getElementSymbol(atom.atomicNumber()) << " " << atom.position().x() << " "
69
- << atom.position().y() << " " << atom.position().z() << std::endl;
70
- }
71
- }
72
-
73
- file.close();
74
- }
75
-
76
- void Result::exportChemcraft(const std::string filepath) const {
77
- auto chemcraftFile = ChemcraftWriter(filepath);
78
- // write groups
79
- for (auto &cluster : _clusters) {
80
- chemcraftFile.startCluster(_structures[cluster[0]].getHash());
81
- for (auto &id : cluster) {
82
- auto &structure = _structures[id];
83
- chemcraftFile.writeStructure(structure);
84
- }
85
- }
86
-
87
- // write singles
88
- for (auto &id : _singles) {
89
- auto &structure = _structures[id];
90
- chemcraftFile.startSingle(structure.getHash());
91
- chemcraftFile.writeStructure(structure);
92
- }
93
-
94
- chemcraftFile.close();
95
- };
96
-
97
- std::vector<std::vector<int>> Result::getClusters() const { return _clusters; };
98
- std::vector<int> Result::getSingles() const { return _singles; };
99
- std::vector<Structure> Result::getStructures() const { return _structures; };