structure-step 2024.8.4__py2.py3-none-any.whl

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.
@@ -0,0 +1,754 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ """Non-graphical part of the Structure step in a SEAMM flowchart
4
+ """
5
+
6
+ from datetime import datetime
7
+ import json
8
+ import logging
9
+ from pathlib import Path
10
+ import pkg_resources
11
+ import pprint # noqa: F401
12
+ import shutil
13
+ import sys
14
+ import time
15
+ import traceback
16
+
17
+ from ase import Atoms as ASE_Atoms
18
+ import ase.optimize as ASE_Optimize
19
+ from ase.calculators.calculator import all_changes as ASE_all_changes
20
+ import numpy as np
21
+ from tabulate import tabulate
22
+
23
+ import structure_step
24
+ import molsystem
25
+ import seamm
26
+ from seamm_ase import SEAMM_Calculator
27
+ from seamm_util import Q_, units_class, getParser
28
+ import seamm_util.printing as printing
29
+ from seamm_util.printing import FormattedText as __
30
+
31
+ # In addition to the normal logger, two logger-like printing facilities are
32
+ # defined: "job" and "printer". "job" send output to the main job.out file for
33
+ # the job, and should be used very sparingly, typically to echo what this step
34
+ # will do in the initial summary of the job.
35
+ #
36
+ # "printer" sends output to the file "step.out" in this steps working
37
+ # directory, and is used for all normal output from this step.
38
+
39
+ logger = logging.getLogger(__name__)
40
+ job = printing.getPrinter()
41
+ printer = printing.getPrinter("Structure")
42
+
43
+ # Add this module's properties to the standard properties
44
+ path = Path(pkg_resources.resource_filename(__name__, "data/"))
45
+ csv_file = path / "properties.csv"
46
+ if path.exists():
47
+ molsystem.add_properties_from_file(csv_file)
48
+
49
+
50
+ class Structure(seamm.Node):
51
+ """
52
+ The non-graphical part of a Structure step in a flowchart.
53
+
54
+ Attributes
55
+ ----------
56
+ parser : configargparse.ArgParser
57
+ The parser object.
58
+
59
+ options : tuple
60
+ It contains a two item tuple containing the populated namespace and the
61
+ list of remaining argument strings.
62
+
63
+ subflowchart : seamm.Flowchart
64
+ A SEAMM Flowchart object that represents a subflowchart, if needed.
65
+
66
+ parameters : StructureParameters
67
+ The control parameters for Structure.
68
+
69
+ See Also
70
+ --------
71
+ TkStructure,
72
+ Structure, StructureParameters
73
+ """
74
+
75
+ def __init__(
76
+ self,
77
+ flowchart=None,
78
+ title="Structure",
79
+ namespace="org.molssi.seamm",
80
+ extension=None,
81
+ logger=logger,
82
+ ):
83
+ """A step for optimizing structure in a SEAMM flowchart.
84
+
85
+ Parameters
86
+ ----------
87
+ flowchart: seamm.Flowchart
88
+ The non-graphical flowchart that contains this step.
89
+
90
+ title: str
91
+ The name displayed in the flowchart.
92
+ namespace : str
93
+ The namespace for the plug-ins of the subflowchart
94
+ extension: None
95
+ Not yet implemented
96
+ logger : Logger = logger
97
+ The logger to use and pass to parent classes
98
+
99
+ Returns
100
+ -------
101
+ None
102
+ """
103
+ logger.setLevel(logging.DEBUG)
104
+ logger.debug(f"Creating Structure {self}")
105
+ self.subflowchart = seamm.Flowchart(
106
+ parent=self, name="Structure", namespace=namespace
107
+ )
108
+
109
+ super().__init__(
110
+ flowchart=flowchart,
111
+ title="Structure",
112
+ extension=extension,
113
+ module=__name__,
114
+ logger=logger,
115
+ )
116
+
117
+ self._metadata = structure_step.metadata
118
+ self.parameters = structure_step.StructureParameters()
119
+ self._step = 0
120
+ self._file_handler = None
121
+ self._working_configuration = None
122
+ self._data = {}
123
+ self._results = {}
124
+ self._logfile = None
125
+
126
+ @property
127
+ def version(self):
128
+ """The semantic version of this module."""
129
+ return structure_step.__version__
130
+
131
+ @property
132
+ def git_revision(self):
133
+ """The git version of this module."""
134
+ return structure_step.__git_revision__
135
+
136
+ def analyze(self, indent="", **kwargs):
137
+ """Do any analysis of the output from this step.
138
+
139
+ Also print important results to the local step.out file using
140
+ "printer".
141
+
142
+ Parameters
143
+ ----------
144
+ indent: str
145
+ An extra indentation for the output
146
+ """
147
+ table = {
148
+ "": [
149
+ "Converged?",
150
+ "Energy",
151
+ "# steps",
152
+ "Max Force",
153
+ "RMS Force",
154
+ "Max Step",
155
+ ],
156
+ "Value": [
157
+ "Yes" if self._results["converged"] else "**NO**",
158
+ f"{self._results['energy']:.2f}",
159
+ self._results["nsteps"],
160
+ f"{self._results['maximum_gradient']:.6f}",
161
+ f"{self._results['rms_gradient']:.6f}",
162
+ f"{self._results['maximum_step']:.6f}",
163
+ ],
164
+ "Units": [
165
+ "",
166
+ "kJ/mol",
167
+ "",
168
+ "kJ/mol/Å",
169
+ "kJ/mol/Å",
170
+ "Å",
171
+ ],
172
+ }
173
+
174
+ tmp = tabulate(
175
+ table,
176
+ headers="keys",
177
+ tablefmt="rounded_outline",
178
+ )
179
+ length = len(tmp.splitlines()[0])
180
+ text = "\n"
181
+ text += "Optimization".center(length)
182
+ text += "\n"
183
+ text += tmp
184
+ text += "\n"
185
+ printer.important(__(text, indent=8 * " ", wrap=False, dedent=False))
186
+
187
+ def calculator(
188
+ self,
189
+ calculator,
190
+ properties=["energy"],
191
+ system_changes=ASE_all_changes,
192
+ ):
193
+ """Create a calculator for the structure step.
194
+
195
+ Parameters
196
+ ----------
197
+ ase : ase.calculators.calculator.Calculator
198
+ The ASE calculator we are working for
199
+ properties : list of str
200
+ The properties to calculate.
201
+ system_changes : int
202
+ The changes to the system.
203
+
204
+ Returns
205
+ -------
206
+ results : dict
207
+ The dictionary of results from the calculation.
208
+ """
209
+ wd = Path(self.directory)
210
+ wd.mkdir(parents=True, exist_ok=True)
211
+
212
+ self._step += 1
213
+ self._results["nsteps"] = self._step
214
+ self._data["step"].append(self._step)
215
+ fmt = "05d"
216
+
217
+ calculator.results = {}
218
+
219
+ n_atoms = len(calculator.atoms)
220
+ self.logger.debug(f"{n_atoms} atoms in the structure")
221
+ positions = calculator.atoms.positions
222
+ self.logger.debug(f"Positions: {positions}")
223
+ cell = calculator.atoms.cell
224
+ self.logger.debug(f"Cell: {cell}")
225
+
226
+ # Set the coordinates in the configuration
227
+ self._working_configuration.atoms.set_coordinates(positions, fractionals=False)
228
+
229
+ # Find the handler for job.out and set the level up
230
+ job_handler = None
231
+ out_handler = None
232
+ for handler in job.handlers:
233
+ if (
234
+ isinstance(handler, logging.FileHandler)
235
+ and "job.out" in handler.baseFilename
236
+ ):
237
+ job_handler = handler
238
+ job_level = job_handler.level
239
+ job_handler.setLevel(printing.JOB)
240
+ elif isinstance(handler, logging.StreamHandler):
241
+ out_handler = handler
242
+ out_level = out_handler.level
243
+ out_handler.setLevel(printing.JOB)
244
+
245
+ # Get the first real node
246
+ first_node = self.subflowchart.get_node("1").next()
247
+
248
+ # Ensure the nodes have their options
249
+ node = first_node
250
+ while node is not None:
251
+ node.all_options = self.all_options
252
+ node = node.next()
253
+
254
+ # And the subflowchart has the executor
255
+ self.subflowchart.executor = self.flowchart.executor
256
+
257
+ # Direct most output to iteration.out
258
+ step_id = f"step_{self._step:{fmt}}"
259
+ step_dir = Path(self.directory) / step_id
260
+ step_dir.mkdir(parents=True, exist_ok=True)
261
+
262
+ # A handler for the file
263
+ if self._file_handler is not None:
264
+ self._file_handler.close()
265
+ job.removeHandler(self._file_handler)
266
+ path = step_dir / "Step.out"
267
+ path.unlink(missing_ok=True)
268
+ self._file_handler = logging.FileHandler(path)
269
+ self._file_handler.setLevel(printing.NORMAL)
270
+ formatter = logging.Formatter(fmt="{message:s}", style="{")
271
+ self._file_handler.setFormatter(formatter)
272
+ job.addHandler(self._file_handler)
273
+
274
+ # Add the step to the ids so the directory structure is reasonable
275
+ self.subflowchart.reset_visited()
276
+ self.set_subids((*self._id, step_id))
277
+
278
+ # Run through the steps in the loop body
279
+ node = first_node
280
+ try:
281
+ while node is not None:
282
+ node = node.run()
283
+ except DeprecationWarning as e:
284
+ printer.normal("\nDeprecation warning: " + str(e))
285
+ traceback.print_exc(file=sys.stderr)
286
+ traceback.print_exc(file=sys.stdout)
287
+ except Exception as e:
288
+ printer.job(f"Caught exception in step {self.step}: {str(e)}")
289
+ with open(step_dir / "stderr.out", "a") as fd:
290
+ traceback.print_exc(file=fd)
291
+ raise
292
+ self.logger.debug(f"End of step {self._step}")
293
+
294
+ # Remove any redirection of printing.
295
+ if self._file_handler is not None:
296
+ self._file_handler.close()
297
+ job.removeHandler(self._file_handler)
298
+ self._file_handler = None
299
+ if job_handler is not None:
300
+ job_handler.setLevel(job_level)
301
+ if out_handler is not None:
302
+ out_handler.setLevel(out_level)
303
+
304
+ # Get the energy and derivatives
305
+ paths = sorted(step_dir.glob("**/Results.json"))
306
+
307
+ if len(paths) == 0:
308
+ raise RuntimeError(
309
+ "There are no energy and gradients in properties.json for step "
310
+ f"{self._step} in {step_dir}."
311
+ )
312
+ else:
313
+ # Find the most recent and assume that is the one wanted
314
+ newest_time = None
315
+ for path in paths:
316
+ with path.open() as fd:
317
+ data = json.load(fd)
318
+ time = datetime.fromisoformat(data["iso time"])
319
+ if newest_time is None:
320
+ newest = path
321
+ newest_time = time
322
+ elif time > newest_time:
323
+ newest_time = time
324
+ newest = path
325
+ with newest.open() as fd:
326
+ data = json.load(fd)
327
+
328
+ energy = data["energy"]
329
+ if "energy,units" in data:
330
+ units = data["energy,units"]
331
+ else:
332
+ units = "kJ/mol"
333
+ self._data["energy"].append(energy)
334
+
335
+ energy *= Q_(1.0, units).to("eV").magnitude
336
+ self._results["energy"] = Q_(energy, "eV").m_as("kJ/mol")
337
+
338
+ gradients = data["gradients"]
339
+
340
+ if self.logger.isEnabledFor(logging.DEBUG):
341
+ self.logger.debug("\ngradients")
342
+ for i in range(n_atoms):
343
+ self.logger.debug(
344
+ f" {gradients[i][0]:8.3f} {gradients[i][1]:8.3f} "
345
+ f"{gradients[i][2]:8.3f}"
346
+ )
347
+
348
+ if "gradients,units" in data:
349
+ funits = data["gradients,units"]
350
+ else:
351
+ funits = "kJ/mol/Å"
352
+
353
+ # Get the measures of convergence
354
+ max_force = np.max(np.linalg.norm(gradients, axis=1))
355
+ self._data["max_force"].append(max_force)
356
+ self._results["maximum_gradient"] = Q_(max_force, funits).m_as("kJ/mol/Å")
357
+ rms_force = np.sqrt(np.mean(np.linalg.norm(gradients, axis=1) ** 2))
358
+ self._data["rms_force"].append(rms_force)
359
+ self._results["rms_gradient"] = Q_(rms_force, funits).m_as("kJ/mol/Å")
360
+
361
+ if self._step > 1:
362
+ step = positions - self._last_coordinates
363
+ max_step = np.max(np.linalg.norm(step, axis=1))
364
+ else:
365
+ max_step = 0.0
366
+ self._data["max_step"].append(max_step)
367
+ self._results["maximum_step"] = max_step
368
+ self._last_coordinates = np.array(positions)
369
+
370
+ # Units!
371
+ gradients = np.array(gradients) * Q_(1.0, funits).to("eV/Å").magnitude
372
+
373
+ calculator.results["energy"] = energy
374
+ calculator.results["forces"] = -gradients
375
+
376
+ # Log the results
377
+ if self._logfile is not None:
378
+ headers = [
379
+ "Step",
380
+ f"E ({units})",
381
+ f"Fmax ({funits})",
382
+ f"Frms ({funits})",
383
+ "max step (Å)",
384
+ ]
385
+ tmp = tabulate(
386
+ self._data,
387
+ headers=headers,
388
+ tablefmt="rounded_outline",
389
+ disable_numparse=False,
390
+ floatfmt=".3f",
391
+ )
392
+ with open(self._logfile, "w") as fd:
393
+ fd.write(tmp)
394
+ fd.write("\n")
395
+
396
+ # and plot the results
397
+ self.plot(E_units=units, F_units=funits)
398
+
399
+ def create_parser(self):
400
+ """Setup the command-line / config file parser"""
401
+ parser_name = "structure-step"
402
+ parser = getParser()
403
+
404
+ # Remember if the parser exists ... this type of step may have been
405
+ # found before
406
+ parser_exists = parser.exists(parser_name)
407
+
408
+ # Create the standard options, e.g. log-level
409
+ super().create_parser(name=parser_name)
410
+
411
+ if not parser_exists:
412
+ # Any options for diffusivity itself
413
+ parser.add_argument(
414
+ parser_name,
415
+ "--html",
416
+ action="store_true",
417
+ help="whether to write out html files for graphs, etc.",
418
+ )
419
+
420
+ # Now need to walk through the steps in the subflowchart...
421
+ self.subflowchart.reset_visited()
422
+ node = self.subflowchart.get_node("1").next()
423
+ while node is not None:
424
+ node = node.create_parser()
425
+
426
+ return self.next()
427
+
428
+ def description_text(self, P=None, short=False, natoms=None):
429
+ """Create the text description of what this step will do.
430
+ The dictionary of control values is passed in as P so that
431
+ the code can test values, etc.
432
+
433
+ Parameters
434
+ ----------
435
+ P: dict
436
+ An optional dictionary of the current values of the control
437
+ parameters.
438
+ Returns
439
+ -------
440
+ str
441
+ A description of the current step.
442
+ """
443
+ if P is None:
444
+ P = self.parameters.values_to_dict()
445
+
446
+ if P["approach"] == "Optimization":
447
+ text = "The structure will be optimization using the "
448
+ text += "{optimizer} optimizer, converging to {convergence} "
449
+
450
+ max_steps = P["max steps"]
451
+ if natoms is not None and "natoms" in max_steps:
452
+ tmp = max_steps.split()
453
+ if "natoms" in tmp[0]:
454
+ max_steps = int(tmp[1]) * natoms
455
+ else:
456
+ max_steps = int(tmp[0]) * natoms
457
+ text += f"with a maximum of {max_steps} steps."
458
+
459
+ stop = P["continue if not converged"]
460
+ if isinstance(stop, bool) and not stop or stop == "no":
461
+ text += " The workflow will continue if the structure "
462
+ text += "does not converge."
463
+
464
+ # Make sure the subflowchart has the data from the parent flowchart
465
+ self.subflowchart.root_directory = self.flowchart.root_directory
466
+ self.subflowchart.executor = self.flowchart.executor
467
+ self.subflowchart.in_jobserver = self.subflowchart.in_jobserver
468
+
469
+ if not short:
470
+ # Get the first real node
471
+ node = self.subflowchart.get_node("1").next()
472
+ text += "\n\n"
473
+
474
+ # Now walk through the steps in the subflowchart...
475
+ while node is not None:
476
+ try:
477
+ text += __(node.description_text(), indent=3 * " ").__str__()
478
+ except Exception as e:
479
+ print(f"Error describing structure flowchart: {e} in {node}")
480
+ self.logger.critical(
481
+ f"Error describing structure flowchart: {e} in {node}"
482
+ )
483
+ raise
484
+ except: # noqa: E722
485
+ print(
486
+ "Unexpected error describing structure flowchart: "
487
+ f"{sys.exc_info()[0]} in {str(node)}"
488
+ )
489
+ self.logger.critical(
490
+ "Unexpected error describing structure flowchart: "
491
+ f"{sys.exc_info()[0]} in {str(node)}"
492
+ )
493
+ raise
494
+ text += "\n"
495
+ node = node.next()
496
+
497
+ return self.header + "\n" + __(text, **P, indent=4 * " ").__str__()
498
+
499
+ def plot(self, E_units="", F_units=""):
500
+ """Generate a plot of the convergence of the geometry optimization."""
501
+ figure = self.create_figure(
502
+ module_path=("seamm",),
503
+ template="line.graph_template",
504
+ title="Geometry optimization convergence",
505
+ )
506
+ plot = figure.add_plot("convergence")
507
+
508
+ x_axis = plot.add_axis("x", label="Step", start=0, stop=0.8)
509
+ y_axis = plot.add_axis("y", label=f"Energy ({E_units})")
510
+ y2_axis = plot.add_axis(
511
+ "y",
512
+ anchor=x_axis,
513
+ label=f"Force ({F_units})",
514
+ overlaying="y",
515
+ side="right",
516
+ tickmode="sync",
517
+ )
518
+ y3_axis = plot.add_axis(
519
+ "y",
520
+ anchor=None,
521
+ label="Distance (Å)",
522
+ overlaying="y",
523
+ position=0.9,
524
+ side="right",
525
+ tickmode="sync",
526
+ )
527
+ x_axis.anchor = y_axis
528
+
529
+ plot.add_trace(
530
+ color="red",
531
+ name="Energy",
532
+ width=3,
533
+ x=self._data["step"],
534
+ x_axis=x_axis,
535
+ xlabel="step",
536
+ y=self._data["energy"],
537
+ y_axis=y_axis,
538
+ ylabel="Energy",
539
+ yunits=E_units,
540
+ )
541
+
542
+ plot.add_trace(
543
+ color="black",
544
+ name="Max Force",
545
+ width=3,
546
+ x=self._data["step"],
547
+ x_axis=x_axis,
548
+ xlabel="step",
549
+ y=self._data["max_force"],
550
+ y_axis=y2_axis,
551
+ ylabel="Max Force",
552
+ yunits=F_units,
553
+ )
554
+
555
+ plot.add_trace(
556
+ color="green",
557
+ name="RMS Force",
558
+ width=3,
559
+ x=self._data["step"],
560
+ x_axis=x_axis,
561
+ xlabel="step",
562
+ y=self._data["rms_force"],
563
+ y_axis=y2_axis,
564
+ ylabel="RMS Force",
565
+ yunits=F_units,
566
+ )
567
+
568
+ plot.add_trace(
569
+ color="blue",
570
+ name="Max Step",
571
+ width=3,
572
+ x=self._data["step"],
573
+ x_axis=x_axis,
574
+ xlabel="step",
575
+ y=self._data["max_step"],
576
+ y_axis=y3_axis,
577
+ ylabel="Max Step",
578
+ yunits="Å",
579
+ )
580
+
581
+ figure.grid_plots("convergence")
582
+
583
+ # Write to disk
584
+ path = Path(self.directory) / "Convergence.graph"
585
+ figure.dump(path)
586
+
587
+ if "html" in self.options and self.options["html"]:
588
+ path = Path(self.directory) / "Convergence.html"
589
+ figure.template = "line.html_template"
590
+ figure.dump(path)
591
+
592
+ def run(self):
593
+ """Run a Structure step.
594
+
595
+ Parameters
596
+ ----------
597
+ None
598
+
599
+ Returns
600
+ -------
601
+ seamm.Node
602
+ The next node object in the flowchart.
603
+ """
604
+ self._data = {
605
+ "step": [],
606
+ "energy": [],
607
+ "max_force": [],
608
+ "rms_force": [],
609
+ "max_step": [],
610
+ }
611
+ self._last_coordinates = None
612
+ self._step = 0
613
+ next_node = super().run(printer)
614
+
615
+ # Get the values of the parameters, dereferencing any variables
616
+ P = self.parameters.current_values_to_dict(
617
+ context=seamm.flowchart_variables._data
618
+ )
619
+
620
+ _, starting_configuration = self.get_system_configuration()
621
+ _, self._working_configuration = self.get_system_configuration(P)
622
+ n_atoms = starting_configuration.n_atoms
623
+
624
+ # Have to fix formatting for printing...
625
+ PP = dict(P)
626
+ for key in PP:
627
+ if isinstance(PP[key], units_class):
628
+ PP[key] = "{:~P}".format(PP[key])
629
+
630
+ # Print what we are doing
631
+ printer.important(
632
+ __(self.description_text(P, short=True, natoms=n_atoms), indent=self.indent)
633
+ )
634
+
635
+ # Create the directory
636
+ wd = Path(self.directory)
637
+ wd.mkdir(parents=True, exist_ok=True)
638
+
639
+ # Setup the log file for the optimization
640
+ self._logfile = wd / "optimization.log"
641
+
642
+ symbols = starting_configuration.atoms.symbols
643
+ XYZ = starting_configuration.atoms.coordinates
644
+
645
+ calculator = SEAMM_Calculator(self)
646
+ atoms = ASE_Atoms("".join(symbols), positions=XYZ, calculator=calculator)
647
+
648
+ # The default maximum number of steps may vary depending on the optimizer
649
+ max_steps = P["max steps"]
650
+
651
+ # Optimize the structure
652
+ if P["optimizer"] == "BFGS":
653
+ optimizer = ASE_Optimize.BFGS(atoms, restart=wd / "bfgs.json", logfile=None)
654
+ elif P["optimizer"] == "LBFGS":
655
+ optimizer = ASE_Optimize.LBFGS(
656
+ atoms, restart=wd / "lbfgs.json", logfile=None
657
+ )
658
+ elif P["optimizer"] == "FIRE":
659
+ optimizer = ASE_Optimize.FIRE(atoms, restart=wd / "fire.json", logfile=None)
660
+ elif P["optimizer"] == "GPMin":
661
+ optimizer = ASE_Optimize.GPMin(
662
+ atoms, restart=wd / "gpmin.json", logfile=None
663
+ )
664
+ elif P["optimizer"] == "MDMin":
665
+ optimizer = ASE_Optimize.MDMin(
666
+ atoms, restart=wd / "mdmin.json", logfile=None
667
+ )
668
+ elif P["optimizer"] == "BFGSLineSearch":
669
+ optimizer = ASE_Optimize.BFGSLineSearch(
670
+ atoms, restart=wd / "bfgsline.json", logfile=None
671
+ )
672
+ elif P["optimizer"] == "LBFGSLineSearch":
673
+ optimizer = ASE_Optimize.LBFGSLineSearch(
674
+ atoms, restart=wd / "lbfgsline.json", logfile=None
675
+ )
676
+
677
+ convergence = P["convergence"].m_as("eV/Å")
678
+ if "natoms" in max_steps:
679
+ tmp = max_steps.split()
680
+ if "natoms" in tmp[0]:
681
+ max_steps = int(tmp[1]) * len(atoms)
682
+ else:
683
+ max_steps = int(tmp[0]) * len(atoms)
684
+
685
+ # Run the optimization
686
+ exception = None
687
+ tic = time.perf_counter_ns()
688
+ try:
689
+ converged = optimizer.run(fmax=convergence, steps=max_steps)
690
+ except Exception as exception: # noqa: F841
691
+ converged = False
692
+ finally:
693
+ toc = time.perf_counter_ns()
694
+ self._results["t_elapsed"] = round((toc - tic) * 1.0e-9, 3)
695
+ self._results["converged"] = converged
696
+
697
+ # Print the results
698
+ self.analyze()
699
+
700
+ # Store results to db, variables, tables, and json as requested
701
+ self.store_results(
702
+ configuration=self._working_configuration,
703
+ data=self._results,
704
+ )
705
+
706
+ # Clean up the subdirectories
707
+ if exception is not None or not converged:
708
+ keep = P["on error"]
709
+ if keep == "delete all subdirectories":
710
+ subdirectories = wd.glob("step_*")
711
+ for subdirectory in subdirectories:
712
+ shutil.rmtree(subdirectory)
713
+ elif keep == "keep last subdirectory":
714
+ subdirectories = wd.glob("step_*")
715
+ subdirectories = sorted(subdirectories)
716
+ for subdirectory in subdirectories[:-1]:
717
+ shutil.rmtree(subdirectory)
718
+ if not converged:
719
+ raise RuntimeError(
720
+ f"Optimization did not converge in {max_steps} steps"
721
+ )
722
+ raise exception from None
723
+ else:
724
+ keep = P["on success"]
725
+ if keep == "delete all subdirectories":
726
+ subdirectories = wd.glob("step_*")
727
+ for subdirectory in subdirectories:
728
+ shutil.rmtree(subdirectory)
729
+ elif keep == "keep last subdirectory":
730
+ subdirectories = wd.glob("step_*")
731
+ subdirectories = sorted(subdirectories)
732
+ for subdirectory in subdirectories[:-1]:
733
+ shutil.rmtree(subdirectory)
734
+
735
+ return next_node
736
+
737
+ def set_id(self, node_id=()):
738
+ """Sequentially number the subnodes"""
739
+ self.logger.debug("Setting ids for subflowchart {}".format(self))
740
+ if self.visited:
741
+ return None
742
+ else:
743
+ self.visited = True
744
+ self._id = node_id
745
+ self.set_subids(self._id)
746
+ return self.next()
747
+
748
+ def set_subids(self, node_id=()):
749
+ """Set the ids of the nodes in the subflowchart"""
750
+ node = self.subflowchart.get_node("1").next()
751
+ n = 1
752
+ while node is not None:
753
+ node = node.set_id((*node_id, str(n)))
754
+ n += 1