scope-sco 0.9.3__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.
scope_sco/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ from scope_sco import sco_classes, sco_structure, sco_functions
2
+ from scope_sco.sco_classes import *
3
+ from scope_sco.sco_structure import *
4
+ from scope_sco.sco_functions import *
5
+
File without changes
@@ -0,0 +1,68 @@
1
+ import os
2
+ from argparse import ArgumentParser
3
+ from scope.read_write import load_binary, clear_screen
4
+ from scope_sco.sco_classes import System_sco
5
+
6
+ def env_exists(path):
7
+ if not os.path.isfile(path):
8
+ raise ValueError(f'Path {path} does not exist!')
9
+ env = load_binary(path)
10
+ if env.object_type == "environment":
11
+ return path
12
+ else:
13
+ raise ValueError(f'Path {path} is not an Environment binary file!')
14
+
15
+ def create_many_parser(subparsers):
16
+ parser = subparsers.add_parser("create_many",help="Creates many SCO systems from cell2mol data",description="Creates many SCO systems from cell2mol data")
17
+ parser.add_argument("-n", "--env",type=env_exists, help='Path to the Environment. Script will load all sources in env.sources_path')
18
+ parser.add_argument('-f', '--force', action='store_true')
19
+ parser.add_argument('-v', '--verbose', action='store_true')
20
+ parser.set_defaults(func=create_many)
21
+
22
+ def create_many(args):
23
+ clear_screen()
24
+
25
+ #########################
26
+ # Loads the Environment #
27
+ #########################
28
+ env = load_binary(args.env)
29
+ print(f"\tEnviroment {env.name} Loaded. ")
30
+ print(f"\tLoading All Sources From Path {env.sources_path}: ")
31
+
32
+ print(f"\t------------------------------------------------")
33
+ print(f"\tThe script expects the following folder structure")
34
+ print(f"\t\t{env.sources_path}/")
35
+ print(f"\t\t\t...Systems/")
36
+ print(f"\t\t\t\t...*/*.cif")
37
+ print(f"\t\t\t\t...*/*.gmol")
38
+ print(f"\t------------------------------------------------")
39
+
40
+ ###############################
41
+ # Defines Overwrite and Debug #
42
+ ###############################
43
+ if args.verbose: debug = 1
44
+ else: debug = 0
45
+ if args.force: overwrite = 1
46
+ else: overwrite = 0
47
+ ###############################
48
+
49
+ if debug > 0: print(f"Arguments_parsed: {args}")
50
+
51
+ for name in sorted(os.listdir(env.sources_path)):
52
+ sys_path = env.sources_path+name
53
+ sys_name = name
54
+ ## In sources_path, I expect a folder for each system.
55
+ if os.path.isdir(sys_path):
56
+ ## Inside, each system's folder, I expect a folder for each crystal structure
57
+ new_sys = System_sco(sys_name)
58
+ new_sys.set_paths_from_environment(env, create_folders=True, debug=debug)
59
+ new_sys.load_multiple_cell2mol_folders(new_sys.sources_path, debug=debug)
60
+ worked1 = new_sys.set_reference_cells(overwrite=overwrite, debug=debug)
61
+ worked2 = new_sys.set_reference_molecs(overwrite=overwrite, debug=debug)
62
+ if worked1 and worked2:
63
+ print(f"\tCreation of system {new_sys.name} worked. Saving sys_file here: {new_sys.system_file}. Folders will be created if necessary")
64
+ new_sys.create_folders()
65
+ new_sys.save()
66
+
67
+ if __name__ == "__main__":
68
+ create_many()
@@ -0,0 +1,69 @@
1
+ import os
2
+ import sys
3
+ from argparse import ArgumentParser
4
+ from scope.read_write import load_binary, clear_screen
5
+ from scope_sco.sco_classes import System_sco
6
+
7
+ def path_exists(path):
8
+ if not os.path.exists(path):
9
+ raise ValueError(f'Path {path} does not exist!')
10
+ return path
11
+
12
+ def env_exists(path):
13
+ if not os.path.isfile(path):
14
+ raise ValueError(f'Path {path} does not exist!')
15
+ env = load_binary(path)
16
+ if env.object_type == "environment":
17
+ return path
18
+ else:
19
+ raise ValueError(f'Path {path} is not an Environment binary file!')
20
+
21
+ def create_single_parser(subparsers):
22
+ parser = subparsers.add_parser("create_single",help="Creates a SCO system from a cell2mol Cell object",description="Creates a SCO system from a cell2mol Cell object")
23
+ parser.add_argument("-n", "--env", type=env_exists, help='Path to the Environment. Script will load Source data in env.sources_path')
24
+ parser.add_argument('-s', '--source', type=str, help='Name of the Source Folder Inside env.sources_path')
25
+ parser.add_argument('-f', '--force', action='store_true')
26
+ parser.add_argument('-v', '--verbose', action='store_true')
27
+ parser.set_defaults(func=create_single)
28
+
29
+ def create_single(args):
30
+ clear_screen()
31
+
32
+ #########################
33
+ # Loads the Environment #
34
+ #########################
35
+ env = load_binary(args.env)
36
+ print(f"\tEnviroment {env.name} Loaded. ")
37
+
38
+ ###############################
39
+ # Defines Overwrite and Debug #
40
+ ###############################
41
+ if args.verbose: debug = 1
42
+ else: debug = 0
43
+ if args.force: overwrite = 1
44
+ else: overwrite = 0
45
+ ###############################
46
+
47
+ if debug > 0: print(f"\tArguments_parsed: {args}")
48
+
49
+ source_path = env.sources_path+args.source
50
+ system_name = args.source
51
+ exists = path_exists(source_path)
52
+
53
+ if not exists:
54
+ print(f"\t{source_path} does not exist: ")
55
+ sys.exit()
56
+
57
+ print(f"\tLoading Source From Path {source_path}: ")
58
+ new_sys = System_sco(system_name)
59
+ new_sys.set_paths_from_environment(env)
60
+ new_sys.load_multiple_cell2mol_folders(new_sys.sources_path, debug=debug)
61
+ worked1 = new_sys.set_reference_cells(overwrite=overwrite, debug=debug)
62
+ worked2 = new_sys.set_reference_molecs(overwrite=overwrite, debug=debug)
63
+ if worked1 and worked2:
64
+ print(f"\tCreation of system {new_sys.name} worked. Saving sys_file here: {new_sys.system_file}. Folders will be created if necessary")
65
+ new_sys.create_folders()
66
+ new_sys.save()
67
+
68
+ if __name__ == "__main__":
69
+ create_single()
@@ -0,0 +1,56 @@
1
+ #import os
2
+ #from argparse import ArgumentParser
3
+ #from Scope.Read_Write import load_binary
4
+ #from Scope.Spin_Crossover.SCO_Classes import sco_system
5
+ #
6
+ #def env_exists(path):
7
+ # if not os.path.isfile(path):
8
+ # raise ValueError(f'Path {path} does not exist!')
9
+ # env = load_binary(path)
10
+ # if env.type == "environment":
11
+ # return path
12
+ # else:
13
+ # raise ValueError(f'Path {path} is not an Environment binary file!')
14
+ #
15
+ #def parse_args():
16
+ # parser = ArgumentParser(prog="get_t12", description="Computes the transition temperature T12 for a given branch of a SCO system")
17
+ # parser.add_argument('-n', '--env', type=env_exists, help='Path to the Environment. Script will load all sources in env.sources_path')
18
+ # parser.add_argument('-b', '--branch', type=str)
19
+ # parser.add_argument('-f', '--force', action='store_true')
20
+ # parser.add_argument('-v', '--verbose', action='store_true')
21
+ # return parser.parse_args()
22
+ #
23
+ #def main():
24
+ #
25
+ # args = parse_args()
26
+ #
27
+ # #########################
28
+ # # Loads the Environment #
29
+ # #########################
30
+ # env = load_binary(args.env)
31
+ # print(f"\tEnviroment {env.name} Loaded. ")
32
+ #
33
+ # ###############################
34
+ # # Defines Overwrite and Debug #
35
+ # ###############################
36
+ # if args.verbose: debug = 1
37
+ # else: debug = 0
38
+ # if args.force: overwrite = 1
39
+ # else: overwrite = 0
40
+ # ###############################
41
+ #
42
+ # if debug > 0: print(f"\tArguments_parsed: {args}")
43
+ #
44
+ # source_path = env.sources_path+args.source
45
+ # system_name = args.source
46
+ # exists = path_exists(source_path)
47
+ #
48
+ # if not exists:
49
+ # print(f"\t{source_path} does not exist: ")
50
+ # sys.exit()
51
+ #
52
+ # new_sys.save()
53
+ #
54
+ #if __name__ == "__main__":
55
+ # main()
56
+ #
scope_sco/cli/main.py ADDED
@@ -0,0 +1,15 @@
1
+ import argparse
2
+ from scope_sco.cli.create_many import create_many_parser
3
+ from scope_sco.cli.create_single import create_single_parser
4
+ #from scope_sco.cli.get_t12 import get_t12_parser
5
+
6
+ def main():
7
+ parser = argparse.ArgumentParser(prog="scope_sco")
8
+ subparsers = parser.add_subparsers(dest="command", required=True)
9
+
10
+ create_many_parser(subparsers)
11
+ create_single_parser(subparsers)
12
+ #get_t12_parser(subparsers)
13
+
14
+ args = parser.parse_args()
15
+ args.func(args)
@@ -0,0 +1,348 @@
1
+ ################################################
2
+ ##### SYSTEM & CELL Classes Adapted to SCO #####
3
+ ################################################
4
+ import os
5
+ from copy import deepcopy
6
+
7
+ from scope.classes_cell import *
8
+ from scope.classes_cif import Cif
9
+ from scope.classes_state import State
10
+ from scope.classes_specie import *
11
+ from scope.classes_system import System
12
+ from scope.read_write import load_binary, print_xyz
13
+ from scope_sco.sco_structure import *
14
+
15
+ ########################################
16
+ ##### SYSTEM Object Adapted to SCO #####
17
+ ########################################
18
+ class System_sco(System):
19
+ """
20
+ Represent a spin-crossover system built from crystal references.
21
+
22
+ Attributes:
23
+ object_subtype (str): System subtype (`"sco_system"`).
24
+ refcode (str): Reference code for the system.
25
+ refcode_wo_digits (str): Reference code stripped of digits.
26
+
27
+ Methods:
28
+ load_single_cell2mol_folder(): Import one cell2mol folder.
29
+ load_multiple_cell2mol_folders(): Import several cell2mol folders.
30
+ set_reference_molecs(): Build HS/LS molecular references.
31
+ set_reference_cells(): Build HS/LS crystal references.
32
+ """
33
+ def __init__(self, refcode: str) -> None:
34
+ System.__init__(self, refcode)
35
+ self.object_subtype = "sco_system"
36
+ self.refcode = refcode
37
+ self.refcode_wo_digits = ''.join([i for i in refcode if not i.isdigit()])
38
+
39
+ def __repr__(self):
40
+ to_print = ''
41
+ to_print += '-------------------------------------\n'
42
+ to_print += '-- >>> SCOPE System_sco Object >>> --\n'
43
+ to_print += '-------------------------------------\n'
44
+ to_print += System.__repr__(self, indirect=True)
45
+ to_print += '\n'
46
+ return to_print
47
+
48
+ ######
49
+ ## Load Cells from paths
50
+ ######
51
+ def load_single_cell2mol_folder(self, folder: str, overwrite: bool=False, debug: int=0):
52
+ """
53
+ Import one cell2mol folder into the current SCO system.
54
+
55
+ Parameters:
56
+ folder (str): Folder containing `.gmol` and `.cif` files.
57
+ overwrite (bool): Whether to overwrite an existing source.
58
+ debug (int): Verbosity level.
59
+
60
+ Returns:
61
+ object | None: Updated system, or `None` if the folder is invalid.
62
+ """
63
+ from cell2mol.tmcharge_common import Cell, atom, molecule, ligand, metal
64
+ if folder[-1] != '/': folder += '/'
65
+ if not os.path.isdir(folder): return None
66
+ cell_loaded = False
67
+ cif_loaded = False
68
+
69
+ # A first loop over the list of files, to ensure that all necessary data is there
70
+ for fil in sorted(os.listdir(folder)):
71
+ if fil.endswith(".gmol") and fil.startswith("Cell"):
72
+ if debug > 0: print("IMPORT_cell2mol_FOLDER: Trying to load cell2mol CELL file from", folder+fil)
73
+ new_cell = import_cell(load_binary(folder+fil)) ## Imports to the generic Cell class
74
+ if new_cell is None: continue
75
+ new_cell = convert_to_sco_cell(new_cell) ## Converts to the SCO adapted Cell class
76
+ if new_cell is None: continue
77
+ cell_loaded = True
78
+ cell_path = folder+fil
79
+ if debug > 0: print("IMPORT_cell2mol_FOLDER: File loaded successfully")
80
+ elif fil.endswith(".cif"):
81
+ if debug > 0: print("IMPORT_cell2mol_FOLDER: Trying to load CIF file from", folder+fil)
82
+ new_cif = Cif(fil, folder+fil)
83
+ cif_loaded = True
84
+ if debug > 0: print("IMPORT_cell2mol_FOLDER: File loaded successfully")
85
+ if debug > 0: print(f"IMPORT_cell2mol_FOLDER: Path={folder}, {cell_loaded=} {cif_loaded=}")
86
+
87
+ ## In SCO projects reading from cell2mol, I set that both the Cell and the cif have to be there.
88
+ ## If the information could be properly retrieved, then it keeps the cell
89
+ if cif_loaded and cell_loaded:
90
+ ## Prepare the cell object
91
+ if debug > 0: print(f"IMPORT_cell2mol_FOLDER: Preparing the cell object in {cell_path}")
92
+ new_cell.get_FeN6_molecules()
93
+ new_cell.get_spin_and_phase_data()
94
+ ## Link Cell and Cif objects
95
+ new_cell.associate_cif(new_cif)
96
+ new_cif.associate_cell(new_cell)
97
+ ## Stores Path
98
+ new_cell.set_path(cell_path)
99
+ ## Create System_SCO, and incorporate the cell
100
+ if hasattr(new_cell,"name"): source_name = new_cell.name.lower()
101
+ else: source_name = folder.split('/')[-2].lower()
102
+ self.add_source(source_name, new_cell, overwrite=overwrite, debug=debug)
103
+ return self
104
+
105
+ ###### Same for multiple folders
106
+ def load_multiple_cell2mol_folders(self, path: str, overwrite: bool=False, debug: int=0):
107
+ if path[-1] != '/': path += '/'
108
+ if not os.path.isdir(path): return None
109
+ for folder in sorted(os.listdir(path)):
110
+ if os.path.isdir(path+folder):
111
+ if debug > 0: print(f"Loading cell2mol folder {folder}")
112
+ self.load_single_cell2mol_folder(path+folder, overwrite=overwrite, debug=debug)
113
+ return self
114
+
115
+ ######
116
+ def set_reference_molecs(self, overwrite: bool=False, debug: int=0):
117
+ found_hs, hs = self.find_source("ref_hs_mol")
118
+ found_ls, ls = self.find_source("ref_ls_mol")
119
+ if not overwrite and (found_hs or found_ls):
120
+ if debug > 0: print(f"SET_REF_MOLEC: reference molecules already present. Use overwrite=True to reset them")
121
+ return True
122
+
123
+ ## Collect all FeN6 molecules in the cells of the system
124
+ pool = []
125
+ for source in self.sources:
126
+ if source.object_type == "cell": pool.extend(source.get_FeN6_molecules(overwrite=overwrite, debug=0))
127
+ if debug > 0: print(f"SET_REF_MOLEC: {len(pool)} FeN6 molecules in pool")
128
+ if len(pool) == 0: print(f"SET_REF_MOLEC: Empty pool of reference molecules"); return False
129
+
130
+ ## Evaluates
131
+ for mol in pool:
132
+ mol.scope_FeNdist, mol.scope_FeNangle, mol.scope_epsylon = geom_sco_from_xyz(mol.labels, mol.coord, debug=0)
133
+ mol.scope_guess_spin = guess_spin_state(int(mol.metals[0].charge), mol.scope_FeNdist[0], debug=0)
134
+
135
+ ## Evaluates in pairs to make sure we get the 'same' molecule (same charge and chemical composition) for both spin states
136
+ found_refs = False
137
+ for idx, mol1 in enumerate(pool):
138
+ for jdx, mol2 in enumerate(pool):
139
+ if jdx != idx and not found_refs:
140
+ if mol1.scope_guess_spin == 'HS' and mol2.scope_guess_spin == 'LS' and mol1.charge == mol2.charge and mol1 == mol2:
141
+ found_refs = True
142
+ hs = deepcopy(mol1) #I'm making a deepcopy to avoid issues with references
143
+ ls = deepcopy(mol2)
144
+ if not found_refs:
145
+ hs = deepcopy(pool[0])
146
+ ls = deepcopy(pool[0])
147
+
148
+ ## Prepares the species:
149
+ hs.name = "ref_hs_mol"
150
+ hs.set_bonds()
151
+ hs.set_spin_metals(4, debug=debug)
152
+ hs.fix_ligands_rdkit_obj()
153
+ self.add_source(hs.name, hs)
154
+
155
+ ls.name = "ref_ls_mol"
156
+ ls.set_bonds()
157
+ ls.set_spin_metals(0, debug=debug) # Not strictly necessary, but for clarity
158
+ ls.fix_ligands_rdkit_obj()
159
+ self.add_source(ls.name, ls)
160
+
161
+ # Creates 'initial' States:
162
+ hs.set_initial_state(debug=debug)
163
+ ls.set_initial_state(debug=debug)
164
+ return True
165
+
166
+ ######
167
+ def set_reference_cells(self, overwrite: bool=False, debug: int=0):
168
+ found_hs, hs = self.find_source("ref_hs_cell")
169
+ found_ls, ls = self.find_source("ref_ls_cell")
170
+ if not overwrite and (found_hs or found_ls):
171
+ if debug > 0: print(f"SET_REF_CELLS: reference HS of LS cells already present. Use overwrite=True to reset them")
172
+ return True
173
+
174
+ hs_ref_temp = 1000 ## Initial high value to find the lowest temperature
175
+ ls_ref_temp = 1000 ## Initial high value to find the lowest temperature
176
+ found_hs = False
177
+ found_ls = False
178
+ for source in self.sources:
179
+ if source.object_type == "cell":
180
+ cell = source
181
+ if hasattr(cell,"warning_list"): ## In cell2mol cells, this variable contains any warning found during the interpretation
182
+ if not any(cell.warning_list): ## For a cell to be valid, no error is allowed
183
+ cell.get_spin_and_phase_data(debug=debug)
184
+
185
+ ## This try/except block is to skip cases in which the diffraction temperature is not known
186
+ if hasattr(cell,"cif"):
187
+ if hasattr(cell.cif,"diff_temp"):
188
+ try: cell.cif.diff_temp = float(cell.cif.diff_temp)
189
+ except: continue
190
+ else: continue
191
+ else: continue
192
+
193
+ ## Locate reference HS and LS crystals based on their diffraction temperature
194
+ if cell.phase == "HS" and cell.cif.diff_temp < hs_ref_temp:
195
+ hs_ref_temp = cell.cif.diff_temp
196
+ hs = deepcopy(cell)
197
+ found_hs = True
198
+ elif cell.phase == "LS" and cell.cif.diff_temp < ls_ref_temp:
199
+ ls = deepcopy(cell)
200
+ found_ls = True
201
+ elif cell.phase == "IS":
202
+ if debug > 0: print(f"SET_REF_CELLS: IS phase found but not implemented")
203
+
204
+ if not found_hs:
205
+ for source in self.sources:
206
+ if source.object_type == "cell":
207
+ cell = source
208
+ if hasattr(cell,"warning_list"):
209
+ if not any(cell.warning_list):
210
+ hs = deepcopy(cell)
211
+ if not found_ls:
212
+ for source in self.sources:
213
+ if source.object_type == "cell":
214
+ cell = source
215
+ if hasattr(cell,"warning_list"):
216
+ if not any(cell.warning_list):
217
+ ls = deepcopy(cell)
218
+
219
+ if ls is None or hs is None: # Then something went wrong
220
+ return False
221
+
222
+ ## Prepares the cells:
223
+ hs.name = "ref_hs_cell"
224
+ hs.set_spin_metals(4, debug=debug)
225
+ for mol in hs.molecules:
226
+ mol.set_bonds()
227
+ if mol.iscomplex: mol.fix_ligands_rdkit_obj()
228
+ self.add_source(hs.name, hs, overwrite=overwrite)
229
+
230
+ ls.name = "ref_ls_cell"
231
+ ls.set_spin_metals(0, debug=debug) # Not strictly necessary, but for clarity
232
+ for mol in ls.molecules:
233
+ mol.set_bonds()
234
+ if mol.iscomplex: mol.fix_ligands_rdkit_obj()
235
+ self.add_source(ls.name, ls, overwrite=overwrite)
236
+
237
+ if hs.natoms != ls.natoms: print(f"Warning: different number of atoms in crystal; HS: {hs.natoms} vs. LS: {ls.natoms}")
238
+
239
+ # Creates "initial" states:
240
+ hs.set_initial_state(debug=debug)
241
+ ls.set_initial_state(debug=debug)
242
+ return True
243
+
244
+ ######################################
245
+ ##### CELL Object Adapted to SCO #####
246
+ ######################################
247
+ class Cell_sco(Cell):
248
+ """
249
+ Represent a crystal cell specialized for spin-crossover analysis.
250
+
251
+ Attributes:
252
+ object_subtype (str): Cell subtype (`"sco_cell"`).
253
+ FeN6s (list): FeN6 coordination environments.
254
+ phase (str): Assigned spin-crossover phase.
255
+ hs_molar_fraction (float): High-spin molar fraction.
256
+
257
+ Methods:
258
+ get_FeN6_molecules(): Extract FeN6 molecular environments.
259
+ get_spin_and_phase_data(): Assign phase and HS fraction.
260
+ get_sco_geom(): Print SCO geometric descriptors.
261
+ """
262
+ def __init__(self, name: str, labels: list, pos: list, cell_vector: list=None, cell_param: list=None) -> None:
263
+ Cell.__init__(self, name, labels, pos, cell_vector, cell_param)
264
+ self.object_subtype = "sco_cell"
265
+
266
+ def __repr__(self) -> None:
267
+ to_print = ''
268
+ to_print += '-----------------------------------\n'
269
+ to_print += '-- >>> SCOPE Cell_sco Object >>> --\n'
270
+ to_print += '-----------------------------------\n'
271
+ to_print += Cell.__repr__(self, indirect=True)
272
+ if hasattr(self,"phase"): to_print += f' Phase = {self.phase}\n'
273
+ if hasattr(self,"hs_molar_fraction"): to_print += f' HS Molar Fraction = {self.hs_molar_fraction}\n'
274
+ to_print += '\n'
275
+ return to_print
276
+
277
+ ######
278
+ def get_sco_geom(self, debug: int=0):
279
+ from scope_sco.sco_structure import geom_sco_from_xyz
280
+ if not hasattr(self,"fragmented"): self.check_fragmentation(reconstruct=True, debug=debug)
281
+ assert not self.fragmented, f"Found Fragmented molecules in the geometry of self: {self.name}"
282
+ if not hasattr(self,"molecules"): self.get_molecules(debug=debug)
283
+ for mol in self.molecules:
284
+ if mol.iscomplex: print(geom_sco_from_xyz(self.labels, self.coord, debug=debug))
285
+
286
+ ######
287
+ def get_FeN6_molecules(self, overwrite: bool=False, debug: int=0):
288
+ if not hasattr(self,"molecules"): self.get_molecules()
289
+
290
+ ## If already computed, returns them
291
+ if not overwrite and hasattr(self,"FeN6s"):
292
+ if len(self.FeN6s) > 0: return self.FeN6s
293
+
294
+ self.FeN6s = []
295
+ for mol in self.molecules:
296
+ if mol.iscomplex:
297
+ keepit = False
298
+ for met in mol.metals:
299
+ if hasattr(met,"charge"):
300
+ if debug > 0: print(f" GET_FeN6s: Evaluating metal: {met}")
301
+ coord_sphere = met.get_coord_sphere_formula(debug=debug)
302
+ if debug > 0: print(f" GET_FeN6s: Received {coord_sphere=}")
303
+ if coord_sphere == "N6": keepit = True
304
+ else: print(f" GET_FeN6s: Metal does not have charge variable")
305
+ if keepit:
306
+ if debug > 1: print(f" GET_FeN6s: Entering geom_sco with:")
307
+ if debug > 1: print_xyz(mol.labels, mol.coord)
308
+ mol.scope_FeNdist, mol.scope_FeNangle, mol.scope_epsylon = geom_sco_from_xyz(mol.labels, mol.coord, debug=0)
309
+ mol.scope_guess_spin = guess_spin_state(int(mol.metals[0].charge), mol.scope_FeNdist[0], debug=debug)
310
+ self.FeN6s.append(mol)
311
+ if debug > 0: print(f" GET_FeN6s: found {mol.scope_guess_spin} molecule with oxidation state: {mol.metals[0].charge=}")
312
+ return self.FeN6s
313
+
314
+ ######
315
+ def get_spin_and_phase_data(self, debug: int=0):
316
+ if not hasattr(self,"FeN6s"): self.get_FeN6_molecules()
317
+ guess_spins = []
318
+ self.phase = ''
319
+ self.hs_molar_fraction = 0.0
320
+ for mol in self.FeN6s:
321
+ guess_spins.append(mol.scope_guess_spin)
322
+
323
+ if all(sp == "HS" for sp in guess_spins):
324
+ self.phase = "HS"
325
+ self.hs_molar_fraction = 1.0
326
+ elif all(sp == "LS" for sp in guess_spins):
327
+ self.phase = "LS"
328
+ self.hs_molar_fraction = 0.0
329
+ elif "HS" in guess_spins and "LS" in guess_spins:
330
+ self.phase = "IS"
331
+ self.hs_molar_fraction = float(guess_spins.count("HS")/len(guess_spins))
332
+ if debug > 0: print(f"Get_Spin&Phase: phase:{self.phase} and molar_frac: {self.hs_molar_fraction}")
333
+
334
+ #############################################
335
+ ##### CONVERSION TO SCO-Adapted Classes #####
336
+ #############################################
337
+ def convert_to_sco_cell(generic_cell):
338
+ if not isinstance(generic_cell, Cell):
339
+ print(f"CONVERT_TO_SCO_CELL: Input is not a 'cell' object")
340
+ return None
341
+ if isinstance(generic_cell, Cell_sco):
342
+ if debug > 0: print(f"CONVERT_TO_SCO_CELL: Input is already a 'sco_cell' object")
343
+ return generic_cell
344
+ new_cell = Cell_sco(generic_cell.name, generic_cell.labels, generic_cell.coord, generic_cell.cell_vector, generic_cell.cell_param)
345
+ for attr in generic_cell.__dict__.keys():
346
+ if not hasattr(new_cell,attr):
347
+ setattr(new_cell, attr, getattr(generic_cell,attr))
348
+ return new_cell
@@ -0,0 +1,103 @@
1
+ ######################################################
2
+ #### Function that are Specific to Spin Crossover ####
3
+ ######################################################
4
+ from scope.classes_data import *
5
+ from scope.thermodynamics import *
6
+
7
+ ######
8
+ def get_sco_geom(state: object, debug: int=0):
9
+ from scope_sco.sco_structure import geom_sco_from_xyz
10
+ from scope.classes_state import State
11
+ if not hasattr(state,"fragmented"): state.check_fragmentation(reconstruct=True, debug=debug)
12
+ assert not state.fragmented, f"Found Fragmented molecules in the geometry of state: {state.name}"
13
+ if not hasattr(state,"molecules"): state.get_molecules(debug=debug)
14
+ for mol in state.molecules:
15
+ if mol.iscomplex: print(geom_sco_from_xyz(state.labels, state.coord, debug=debug))
16
+
17
+ ######
18
+ def get_T12(branch: object, High_E_state: object, Low_E_state: object, Trange: range=range(10,501,1), ignore_not_minima: bool=False, flexible: bool=True, overwrite: bool=False, debug: int=0):
19
+
20
+ if not ignore_not_minima:
21
+ ## Checks that both states exist and are minima
22
+ if not hasattr(High_E_state,"isminimum") or not hasattr(Low_E_state,"isminimum"):
23
+ if debug > 0: print(f"{High_E_state.name} and/or {Low_E_state.name} have not been evaluated as minima")
24
+ return False, None
25
+
26
+ ## If not, it evaluates if the states could be considered minima for the sake of T12 evaluation
27
+ if not High_E_state.isminimum and (not High_E_state.almost_minimum or not flexible):
28
+ if debug > 0: print(f"{High_E_state.name} cannot be used for Thermochemistry")
29
+ return False, None
30
+
31
+ if not Low_E_state.isminimum and (not Low_E_state.almost_minimum or not flexible):
32
+ if debug > 0: print(f"{High_E_state.name} cannot be used for Thermochemistry")
33
+ return False, None
34
+
35
+ assert "Helec" in High_E_state.results
36
+ assert "Helec" in Low_E_state.results
37
+
38
+ ## dHelec
39
+ if overwrite or not "dHelec" in branch.results.keys():
40
+ assert High_E_state.results["Helec"].units == Low_E_state.results["Helec"].units
41
+ key = "dHelec"
42
+ value = High_E_state.results["Helec"].value - Low_E_state.results["Helec"].value
43
+ units = High_E_state.results["Helec"].units
44
+ function = "scope_sco.sco_functions.get_T12"
45
+ branch.add_result(Data(key,value,units,function), overwrite=overwrite)
46
+
47
+ ## dSelec
48
+ if overwrite or not "dSelec" in branch.results.keys():
49
+ assert High_E_state.results["Selec"].units == Low_E_state.results["Selec"].units
50
+ key = "dSelec"
51
+ value = High_E_state.results["Selec"].value - Low_E_state.results["Selec"].value
52
+ units = High_E_state.results["Selec"].units
53
+ function = "scope_sco.sco_functions.get_T12"
54
+ branch.add_result(Data(key,value,units,function), overwrite=overwrite)
55
+
56
+ ## dHvib
57
+ if overwrite or not "dHvib" in branch.results.keys():
58
+ assert High_E_state.results["Hvib"].units == Low_E_state.results["Hvib"].units
59
+ #dHvib_collection = substract_collections("dHvib", High_E_state.results["Hvib"], Low_E_state.results["Hvib"], prop="temperature")
60
+ dHvib_collection = High_E_state.results["Hvib"]-Low_E_state.results["Hvib"]
61
+ dHvib_collection.key = "dHvib"
62
+ branch.add_result(dHvib_collection, overwrite=overwrite)
63
+
64
+ ## dSvib
65
+ if overwrite or not "dSvib" in branch.results.keys():
66
+ assert High_E_state.results["Svib"].units == Low_E_state.results["Svib"].units
67
+ #dSvib_collection = substract_collections("dSvib", High_E_state.results["Svib"], Low_E_state.results["Svib"], prop="temperature")
68
+ dSvib_collection = High_E_state.results["Svib"]-Low_E_state.results["Svib"]
69
+ dSvib_collection.key = "dSvib"
70
+ branch.add_result(dSvib_collection, overwrite=overwrite)
71
+
72
+ ## dGtot
73
+ if overwrite or not "dGtot" in branch.results.keys():
74
+ assert High_E_state.results["Gtot"].units == Low_E_state.results["Gtot"].units
75
+ #dGtot_collection = substract_collections("dGtot", High_E_state.results["Gtot"], Low_E_state.results["Gtot"], prop="temperature")
76
+ dGtot_collection = High_E_state.results["Gtot"]-Low_E_state.results["Gtot"]
77
+ dGtot_collection.key = "dGtot"
78
+ branch.add_result(dGtot_collection, overwrite=overwrite)
79
+
80
+ ## T12
81
+ if overwrite or not "T12" in branch.results.keys():
82
+ dGdata = dGtot_collection.get_values()
83
+ key = "T12"
84
+ value = find_t12(Trange, dGdata)
85
+ units = "K"
86
+ function = "scope_sco.sco_functions.get_T12"
87
+ branch.add_result(Data(key, value, units, function), overwrite=overwrite)
88
+
89
+ if debug > 0:
90
+ print("Printing RESULTS for branch")
91
+ branch.results["dHelec"].print_in_units('kj')
92
+ print(branch.results["dSelec"])
93
+ print(branch.results["dHvib"])
94
+ print(branch.results["dSvib"])
95
+ print(branch.results["dGtot"])
96
+ print(branch.results["T12"])
97
+
98
+ ## Set branch_status_finished
99
+ #if "T12" in branch.results.keys():
100
+ # branch.set_status("finished", debug=debug)
101
+ # branch.remove_output_lines()
102
+
103
+ return True, branch.results["T12"]
@@ -0,0 +1,94 @@
1
+ import numpy as np
2
+ from scope.geometry import *
3
+
4
+ ######
5
+ def geom_sco_from_xyz(labels, pos, debug=0):
6
+ #Computes Structural Variables for all Fe atoms of a given structure
7
+ #Returns two lists, one for FeN and another for NFeN, with all values.
8
+ # Epsylon is eq. 1 of Halcrow's Chem. Soc. Rev., 2011,40, 4119-4142
9
+ # Angle is the average of cis angles, without the deviation from 90º
10
+
11
+ alldist = []
12
+ allangle = []
13
+ allepsylon = []
14
+
15
+ #Computes Fe-N distances and vectors
16
+ NFe = labels.count("Fe")
17
+ for idx, p1 in enumerate(pos):
18
+ if labels[idx] == 'Fe':
19
+
20
+ if debug >= 2: print(f"Atom {idx} is an Iron: {p1}")
21
+ dist_FeX = []
22
+ vec_FeX = []
23
+ for jdx, p2 in enumerate(pos):
24
+ if labels[jdx] == 'N':
25
+ if debug >= 2: print(f"Atom {jdx} is a Nitrogen: {p2}")
26
+ dist_FeX.append(np.linalg.norm(np.subtract(p1,p2)))
27
+ vec_FeX.append(np.subtract(p1,p2))
28
+
29
+ if debug >= 2: print("dist_FeX", dist_FeX)
30
+
31
+ # Checks that it detected 6 N atoms
32
+ if len(vec_FeX) < 6:
33
+ print("less than 6 N atoms in the Fe coord sphere. Found", len(vec_FeX))
34
+ print("printing coordinates to debug:")
35
+ for idx, at in enumerate(labels):
36
+ print("%s %.6f %.6f %.6f" % (labels[idx], pos[idx][0], pos[idx][1], pos[idx][2]))
37
+
38
+ # Computes average FeN distance for the closest 6 N atoms, and prepares their vectors (vec_FeN)
39
+ dist_FeN = []
40
+ vec_FeN = []
41
+ for idx in range(0,6):
42
+ targ = sorted(range(len(dist_FeX)), key=lambda k: dist_FeX[k])[idx]
43
+ #targ = np.argpartition(dist_FeX, idx)[idx]
44
+ dist_FeN.append(dist_FeX[targ])
45
+ vec_FeN.append(vec_FeX[targ])
46
+ if debug >= 1: print(f"Target: {targ=} {dist_FeX[targ]=} {vec_FeX[targ]}")
47
+
48
+ if debug >= 1: print(f"dist_FeN=", dist_FeN)
49
+ AvFeN = np.round(np.mean(dist_FeN),3)
50
+
51
+ # Takes vec_FeN vectors and computes angles
52
+ all_NFeN_angles = []
53
+ for idx, v1 in enumerate(vec_FeN):
54
+ for jdx, v2 in enumerate(vec_FeN):
55
+ if jdx > idx:
56
+ angle = get_angle_vectors(v1, v2)*180.0/3.141592
57
+ all_NFeN_angles.append(angle)
58
+ if debug >= 2: print(f"GEOM_SCO: {all_NFeN_angles=}")
59
+
60
+ # Stores the 12th angles closest to 90 degrees
61
+ all_NFeN_angles = np.array(all_NFeN_angles) - 90
62
+ if debug >= 2: print(f"GEOM_SCO: {all_NFeN_angles=} - 90")
63
+
64
+ NFeN_angles = []
65
+ epsylon = 0
66
+ for idx in range(0,12):
67
+ targ = sorted(range(len(all_NFeN_angles)), key=lambda k: all_NFeN_angles[k])[idx]
68
+ NFeN_angles.append(all_NFeN_angles[targ] + 90)
69
+ epsylon += np.abs(all_NFeN_angles[targ])
70
+ if debug >= 1: print(f"Target: {targ=} {all_NFeN_angles[targ]=} {epsylon=}")
71
+ epsylon = np.round(epsylon,3)
72
+ if debug >= 2: print(f"GEOM_SCO: {NFeN_angles=}")
73
+
74
+ AvNFeN_angle = np.round(np.mean(NFeN_angles),3)
75
+ if debug >= 2: print(f"{NFeN_angles=}")
76
+
77
+ alldist.append(AvFeN)
78
+ allangle.append(AvNFeN_angle)
79
+ allepsylon.append(epsylon)
80
+
81
+ return alldist, allangle, allepsylon
82
+
83
+ ######
84
+ def guess_spin_state(ox_state: str, dist: float, debug: int=0):
85
+ if debug > 0: print(f"Received Ox_state={ox_state} and dist={dist}")
86
+ if ox_state == 2 or ox_state == '2':
87
+ if float(dist) >= 1.8 and float(dist) <= 2.04: guess_spin = 'LS'
88
+ elif float(dist) > 2.04 and float(dist) <= 2.10: guess_spin = 'Unk'
89
+ elif float(dist) > 2.10 and float(dist) <= 2.23: guess_spin = 'HS'
90
+ elif float(dist) > 2.23 : guess_spin = 'Unk'
91
+ else: guess_spin = 'Unk'
92
+ else: guess_spin = 'Unk'
93
+ if debug > 0: print(f"Guess_spin={guess_spin}")
94
+ return guess_spin
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: scope-sco
3
+ Version: 0.9.3
4
+ Summary: Spin-crossover add-on for SCOPE
5
+ Author-email: Sergi Vela <sergi.vela@iqac.csic.es>
6
+ Requires-Python: <3.13,>=3.12
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: scope-qc
9
+
10
+ # scope-sco
11
+
12
+ `scope-sco` is the spin-crossover add-on for SCOPE. It extends the core `scope` package with utilities for building, running, and analysing spin-crossover workflows.
13
+
14
+ This add-on is intended for users who already work with SCOPE's core chemistry and workflow abstractions and need spin-crossover-specific functionality on top of them.
15
+
16
+ ## Documentation
17
+
18
+ - Repository and source code: <https://github.com/QTC-IQAC/Scope>
19
+ - Preprint: <https://doi.org/10.26434/chemrxiv.15001415/v1>
20
+ - Tutorials: <https://github.com/QTC-IQAC/Scope_Tutorials>
21
+
22
+ ## Installation
23
+
24
+ create and activate conda environment and install pip:
25
+
26
+ ```bash
27
+ conda create --name scope python=3.12
28
+ conda activate scope
29
+ conda install pip
30
+ ```
31
+
32
+ ### Option 1: from PyPI
33
+ ```bash
34
+ pip install scope-sco
35
+ ```
36
+
37
+ ### Option 2: from repository
38
+ ```bash
39
+ git clone https://github.com/QTC-IQAC/Scope.git
40
+ cd Scope
41
+ pip install -e sco
42
+ ```
43
+
44
+ ### Option 3: from TestPyPi
45
+ ```bash
46
+ pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ scope-sco
47
+ ```
48
+
49
+ ## Command Line Interface
50
+
51
+ The package provides the `scope_sco` command. For help:
52
+
53
+ ```bash
54
+ scope_sco -h
55
+ ```
56
+
57
+ ## Usage
58
+
59
+ `scope-sco` complements the main `scope` package and is meant to be used together with the core SCOPE workflow and data model.
60
+
61
+ ## License
62
+
63
+ See the repository-level [LICENSE](../LICENSE) file for licensing information.
@@ -0,0 +1,14 @@
1
+ scope_sco/__init__.py,sha256=ZsJrphHliPXf5fdA-Qi21K7xszOqv8Y-d05YjAFKTsc,179
2
+ scope_sco/sco_classes.py,sha256=NOoTcTbH6j5qjH_9mcwVsY3jTXyxGmMMVnOeDdT4jXo,16713
3
+ scope_sco/sco_functions.py,sha256=RzIZ_POwOOBtJacBFbuVT3lHE6155q_5KpnQ2IFbnMk,5184
4
+ scope_sco/sco_structure.py,sha256=gA4tazI9jXas0mQ67QkhYfhm5Sat-7N_oW3C-9ppx6k,4176
5
+ scope_sco/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ scope_sco/cli/create_many.py,sha256=vPE4N7j3LnVqIOVSY-wFa2uGi3eK7jsRvWeblOvxDuk,2884
7
+ scope_sco/cli/create_single.py,sha256=Q9XaOEvCUs1SIPgPDzPJkddnXvcFrjGSI7Pd7wvgT98,2626
8
+ scope_sco/cli/get_t12.py,sha256=Cxupvs1D1-R3S2G5Ib41As_F75DJIRSaIiLpiTzInpo,1803
9
+ scope_sco/cli/main.py,sha256=DwfmyeHjOhhYM6Oh8cgbA6DwSUvUT9SIxtyDDTYehaA,487
10
+ scope_sco-0.9.3.dist-info/METADATA,sha256=f6kbQ7hp8RcQibClVWeH4fxVBi8qFcOHmzcM1rELl8g,1621
11
+ scope_sco-0.9.3.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
12
+ scope_sco-0.9.3.dist-info/entry_points.txt,sha256=EII6k1yiIw61B05uMdA8bO_1y07wCXApnQ5XQ-ImsPc,54
13
+ scope_sco-0.9.3.dist-info/top_level.txt,sha256=orfiIxYU5dSssYkSO__s06q56VUBqcRJwVeIqUHMftg,10
14
+ scope_sco-0.9.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ scope_sco = scope_sco.cli.main:main
@@ -0,0 +1 @@
1
+ scope_sco