├── misc └── logo.png ├── CHANGELOG.md ├── descriptors ├── runcrystalnets.jl └── gen_pers_homology.py ├── duplicates ├── pdd_matrix_compare.py ├── group_by_chemel.sh ├── pdd_matrix_elform.sh ├── README.md ├── multiple_chemform.py └── analyze_pdd_csv.py ├── zenodo ├── get_subset.py ├── get_unchanged_mofs.py ├── README.md ├── write_pac_cif.py └── clean_csd_mofs.py ├── FAQ.md ├── structure_validation ├── chk_overlap.py └── chk_hypervalent.py ├── README.md └── LICENSE /misc/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uowoolab/MOSAEC-DB/HEAD/misc/logo.png -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Current MOSAEC-DB version 2 | ## v1.0.0 Release 3 | Total Structure Count (*including unchanged*): 124.4k 4 | 5 | Latest CSD Data Update processed: v5.4.5 (March 2024) 6 | 7 | # Changelog 8 | - 9 | -------------------------------------------------------------------------------- /descriptors/runcrystalnets.jl: -------------------------------------------------------------------------------- 1 | using CrystalNets 2 | 3 | function main(args) 4 | show(determine_topology_dataset(args, true, true, true, CrystalNets.Options(export_subnets=false, export_net=false, export_clusters=false, export_input=false, export_trimmed=false, structure=StructureType.MOF, bonding=Bonding.Input, detect_organiccycles=false, clusterings=[Clustering.Auto, Clustering.Standard]))) 5 | end 6 | 7 | main(ARGS[1]) 8 | 9 | -------------------------------------------------------------------------------- /duplicates/pdd_matrix_compare.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | import amd 3 | import pandas as pd 4 | 5 | structure_list = argv[1] 6 | struc_base = structure_list.split(".cif")[0] 7 | 8 | pdd_df = amd.compare(structure_list, by="PDD", k=100) 9 | 10 | col_list = [] 11 | for col in pdd_df.columns: 12 | col_list.append(col) 13 | for idx in pdd_df.index: 14 | if col != idx and idx not in col_list: 15 | print(col, idx, pdd_df.loc[idx, col]) 16 | 17 | 18 | pdd_df.to_csv(f"{struc_base}.csv") 19 | -------------------------------------------------------------------------------- /duplicates/group_by_chemel.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "Extracting empirical formulas ..." 4 | 5 | for i in *.cif 6 | do 7 | cf=$(grep '_chemical_formula_sum' $i | sed 's/_chemical_formula_sum//') 8 | echo "$i $cf" >> all_formulae.txt 9 | done 10 | cut -d ' ' -f2- all_formulae.txt | sort | uniq -c | sort -gr | sed 's/^[ ]*//;s/[ ]*$//' > numX_chemform.txt 11 | cut -d ' ' -f2- numX_chemform.txt | sed 's/ //g' | sed "s/'//g" > unique_empform.txt 12 | 13 | 14 | echo "Making lists of structures with the same chemical formula ..." 15 | n=1 16 | for line in $(awk '{print$1}' numX_chemform.txt) 17 | do 18 | i=$(sed -n "${n}p" numX_chemform.txt | cut -d ' ' -f2- ) 19 | ii=$(sed -n "${n}p" unique_empform.txt) 20 | grep "$i" all_formulae.txt | awk '{print$1}' > $ii.lst 21 | ((n++)) 22 | done 23 | 24 | echo "Checking for empirical formula multiples ..." 25 | 26 | python multiple_chemform.py unique_empform.txt 27 | 28 | echo "Completed" 29 | -------------------------------------------------------------------------------- /duplicates/pdd_matrix_elform.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | for i in $(wc -l *.lst | awk '$1 > 1 {print$2}' | grep -v total ) 4 | do 5 | echo "running $i comparisons ..." 6 | for ii in $(cat $i) 7 | do 8 | cat $ii >> ${i%.lst}_pdd.cif 9 | done 10 | 11 | cat > pdd_matrix_compare.py << EOF 12 | from sys import argv 13 | import amd 14 | import pandas as pd 15 | 16 | structure_list = argv[1] 17 | struc_base = structure_list.split('.cif')[0] 18 | 19 | pdd_df = amd.compare(structure_list, by='PDD', k=100) 20 | 21 | col_list = [] 22 | for col in pdd_df.columns: 23 | col_list.append(col) 24 | for idx in pdd_df.index: 25 | if col != idx and idx not in col_list: 26 | print(col, idx, pdd_df.loc[idx, col]) 27 | 28 | 29 | pdd_df.to_csv(f'{struc_base}.csv') 30 | 31 | EOF 32 | ## load necessary environment with amd package installed 33 | . ~/.venvs/XXXX/bin/activate 34 | echo "Running PDD for all ${i%.lst} structures ..." 35 | python pdd_matrix_compare.py ${i%.lst}_pdd.cif > ${i%.lst}_pdd.pyout 36 | 37 | done 38 | -------------------------------------------------------------------------------- /duplicates/README.md: -------------------------------------------------------------------------------- 1 | # Structure Duplication Analysis using Pointwise Distance Distributions 2 | Identification of duplicated crystal structure based on similarity of their pointwise distance distribution (PDD) scores. 3 | 4 | # Workflow 5 | Warning: Scripts contain relative paths that will require editing to work on each system. 6 | 7 | 1. Normalize the crystal structure file (cif) formats using your preferred method (e.g., pymatgen, critic23, etc.) 8 | 2. Run group_by_chemel.sh to create *.lst files by each empirical formula that contains the filenames possessing the same empirical formula. 9 | 3. Run pdd_matrix_elform.sh to run pairwise PDD comparisons for all *.lst files -- writes separate *_pdd.pyout & *_pdd.csv for each empirical formula. 10 | 4. Combine PDD results from *_pdd.pyout files e.g., `cat *_pdd.pyout | sed 's/ /.cif,/g' | awk '{print$1,$2,$3}' > pdd_scores.txt` 11 | 5. Use analyze_pdd_csv.py on the pdd_scores.txt to identify duplicate crystal structures based on a defined PDD score threshold (default:) 12 | 13 | # Output 14 | A summary of the duplicate structures is stored as a csv file (default: **duplicate_pdd.csv**). 15 | 16 | Description of Columns: 17 | | Column Header | Description | 18 | | -------------- | -------------- | 19 | | `cif` | structure filename | 20 | | `unique` | whether the structure was identified as unique (True/False) | 21 | | `no_duplicates` | number of structure duplicates identified within PDD threshold | 22 | | `duplicate_ids` | structure filenames of those identified as duplicates | -------------------------------------------------------------------------------- /zenodo/get_subset.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import os 3 | import shutil 4 | import argparse 5 | 6 | CODE_PATH = os.path.dirname(os.path.realpath(__file__)) 7 | print(CODE_PATH) 8 | DB_PATH = CODE_PATH.replace("scripts", "") 9 | print(DB_PATH) 10 | 11 | 12 | def subset(txt_file, dest_dir): 13 | # define cif paths 14 | if "-neutral-" in dest_dir: 15 | fpath = os.path.join(DB_PATH, "database/full/neutral") 16 | ppath = os.path.join(DB_PATH, "database/partial/neutral") 17 | else: 18 | fpath = os.path.join(DB_PATH, "database/full/charged") 19 | ppath = os.path.join(DB_PATH, "database/partial/charged") 20 | 21 | with open(txt_file, "r") as rf: 22 | cifs = rf.read().split("\n") 23 | 24 | # separate cifs by origin directory 25 | fcifs = [os.path.join(fpath, x) for x in cifs if "_full" in x] 26 | pcifs = [os.path.join(ppath, x) for x in cifs if "_partial" in x] 27 | 28 | # move files 29 | print(f"Copying {len(fcifs + pcifs)} .cif files ... ") 30 | for cif in fcifs + pcifs: 31 | shutil.copy(cif, dest_dir) 32 | return 0 33 | 34 | 35 | if __name__ == "__main__": 36 | code_desc = "Retrieve MOSAEC-DB cifs from a specific subset (.txt)." 37 | parser = argparse.ArgumentParser(description=code_desc) 38 | parser.add_argument( 39 | "subset", 40 | type=str, 41 | help="path to .txt file with MOSAEC-DB cif names.", 42 | ) 43 | args = parser.parse_args() 44 | # create subset dir 45 | subset_dir = os.path.basename(args.subset)[:-4] 46 | print("Making subset directory ... ", subset_dir) 47 | os.makedirs(subset_dir, exist_ok=True) 48 | # find & move files 49 | subset(args.subset, subset_dir) 50 | -------------------------------------------------------------------------------- /duplicates/multiple_chemform.py: -------------------------------------------------------------------------------- 1 | import re 2 | from sys import argv 3 | 4 | 5 | def parse_formula(formula): 6 | """Parse a chemical formula into its constituent elements and their counts.""" 7 | elements = re.findall(r"([A-Z][a-z]*)(\d*)", formula) 8 | return {element: int(count) if count else 1 for element, count in elements} 9 | 10 | 11 | def find_multiples_of_formula(formula, formulas): 12 | """Find multiples of a given chemical formula within a list of formulas.""" 13 | parsed_formula = parse_formula(formula) 14 | multiples = [] 15 | 16 | for other_formula in formulas: 17 | if formula == other_formula: 18 | continue # Skip the same formula 19 | 20 | parsed_other_formula = parse_formula(other_formula) 21 | 22 | # Check if both formulas contain the same elements 23 | if set(parsed_formula.keys()) != set(parsed_other_formula.keys()): 24 | continue # Skip if the sets of elements are different 25 | 26 | # Check if all elements in the other formula are multiples of the elements in the original formula 27 | is_multiple = True 28 | for element, count in parsed_other_formula.items(): 29 | if count % parsed_formula[element] != 0: 30 | is_multiple = False 31 | break # Not a multiple if ratio is not integer 32 | if ( 33 | count // parsed_formula[element] 34 | != parsed_other_formula[list(parsed_other_formula.keys())[0]] 35 | // parsed_formula[list(parsed_formula.keys())[0]] 36 | ): 37 | is_multiple = False 38 | break # Not a multiple if ratios between corresponding elements differ 39 | 40 | if is_multiple: 41 | multiples.append(other_formula) 42 | 43 | return multiples 44 | 45 | 46 | # Read chemical formulas from a file 47 | def read_chemical_formulas_from_file(filename): 48 | with open(filename, "r") as file: 49 | chemical_formulas = [line.strip() for line in file if line.strip()] 50 | return chemical_formulas 51 | 52 | 53 | # run 54 | # input file should be tmp.txt from group_by_chemel.sh 55 | filename = argv[1] 56 | chemical_formulas = read_chemical_formulas_from_file(filename) 57 | for formula_to_check in chemical_formulas: 58 | multiples = find_multiples_of_formula(formula_to_check, chemical_formulas) 59 | if multiples: 60 | print(f"Multiples of {formula_to_check}: {multiples}") 61 | -------------------------------------------------------------------------------- /FAQ.md: -------------------------------------------------------------------------------- 1 | ## Frequently Asked Questions 2 | - [Crystal structure (CIF) count doesn't match the publication?](#crystal-structure-cif-count-doesnt-match-the-publication) 3 | - [Failed to find REFCODEs when retrieving unchanged structure?](#failed-to-find-refcodes-when-retrieving-unchanged-structures) 4 | - [Structure XX missing descriptors?](#structure-xx-missing-descriptors) 5 | - [Found a suspected erroneous crystal structure?](#found-a-suspected-erroneous-crystal-structure) 6 | 7 | ## Crystal structure (CIF) count doesn't match the publication? 8 | 9 | Structures which were unchanged during the solvent removal step could not be included publicly due to concerns relating to the Cambridge Structural Database (CSD) licensing agreements. 10 | 11 | **This amounted to an approximate total of 45k files being omitted from the public database provided on zenodo.** 12 | 13 | Scripts to regenerate those structures are available to individuals with an active CSD license. 14 | 15 | ## Failed to find REFCODEs when retrieving unchanged structures? 16 | 17 | The release version of MOSAEC-DB was constructed using several CSD data updates up to the version 5.4.5 (March 2024). 18 | 19 | The crystal structure REFCODEs can change during these CSD data updates, and as a result some REFCODEs reported in MOSAEC-DB may no longer exist in current or future CSD data updates. 20 | 21 | **Mismatch of the CSD database versions is the most likely cause of any mismatch**, though future additions to MOSAEC-DB should capture any new or updated REFCODEs included in the CSD. 22 | 23 | ## Structure XX missing descriptors? 24 | 25 | Any structures missing from the provided descriptors (e.g. RAC, RDF, etc.) csv files **failed during the calculation process**. The same principle applies to any of the data in the primary csv file (i.e. topology, dimensionality, etc.), and the partial atomic charge (REPEAT) structure files. 26 | 27 | Future MOSAEC-DB updates may address these missing values with newer version of the descriptor calculation codes/packages. 28 | 29 | ## Found a suspected erroneous crystal structure? 30 | 31 | Though the MOSAEC-DB construction protocol eliminated a majority of the structure errors, we expect that erroneous structures will remain due to practical limitations in the employed structure validation approach. The MOSAEC algorithm was estimated to be **ca. 95% accurate in flagging erroneous structures and ca. 85% accurate in flagging error-free structures** during manual validation. 32 | 33 | Feel free to contact the [authors](README.md#contact) with any structure error inquiries so that we may address them in future database versions. 34 | 35 | ## 36 | 37 | -------------------------------------------------------------------------------- /duplicates/analyze_pdd_csv.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import os 3 | import glob 4 | import argparse 5 | 6 | import pandas as pd 7 | 8 | 9 | code_desc = "Analyze csv containing all PDD scores calculated for a given database." 10 | parser = argparse.ArgumentParser(description=code_desc) 11 | parser.add_argument( 12 | "pdd_csv", 13 | type=str, 14 | help="path to csv containing all structure pairs' precomputed pdd scores.", 15 | ) 16 | parser.add_argument( 17 | "cif_path", 18 | type=str, 19 | help="path to directory containing all the structures to be considered.", 20 | ) 21 | parser.add_argument( 22 | "-output_csv", 23 | type=str, 24 | default="duplicate_pdd.csv", 25 | help="path to csv containing all structure pairs' precomputed pdd scores.", 26 | ) 27 | parser.add_argument( 28 | "-pdd_threshold", 29 | type=float, 30 | default=0.15, 31 | help="path to csv containing all structure pairs' precomputed pdd scores.", 32 | ) 33 | args = parser.parse_args() 34 | 35 | pdd_threshold = args.pdd_threshold 36 | 37 | cpath = args.cif_path 38 | cifs = glob.glob(f"{cpath}/*.cif", recursive=False) 39 | cifs = [os.path.basename(x) for x in cifs if x[-8:] != "_pdd.cif"] 40 | print(f"Total cifs from db to compare ... {len(cifs)}") 41 | duplicates = {x: [] for x in cifs} 42 | 43 | # read scores 44 | ignore_lines = ["", "s1,s2,pdd_score"] 45 | with open(args.pdd_csv, "r") as rf: 46 | dlines = [x for x in rf.read().split("\n") if x not in ignore_lines] 47 | 48 | # go over files from duplicate analysis 49 | # s1, s2, pdd_score 50 | print("Total no. PDD scores to compare ... ", len(dlines) - 1) 51 | for line in dlines: 52 | spl = line.split(",") 53 | cif1 = spl[0] 54 | cif2 = spl[1] 55 | pdd = float(spl[2]) 56 | if pdd < pdd_threshold: 57 | duplicates[cif1].append(cif2) 58 | duplicates[cif2].append(cif1) 59 | else: 60 | continue 61 | 62 | 63 | # get duplicate dictionary 64 | unique = [] 65 | dupl = [] 66 | rows = [] 67 | for cif, dupes in duplicates.items(): 68 | dupes = sorted(list(set(dupes))) 69 | if len(dupes) != 0: 70 | intersect = list(set(dupes) & set(unique)) 71 | if len(intersect) == 0: 72 | unique.append(cif) 73 | else: 74 | dupl.append(cif) 75 | else: 76 | unique.append(cif) 77 | 78 | rows.append( 79 | { 80 | "cif": cif, 81 | "unique": True if cif in unique else False, 82 | "no_duplicates": len(dupes), 83 | "duplicate_ids": "/".join(dupes), 84 | } 85 | ) 86 | 87 | 88 | print(f"Total unique MOFs ... {len(unique)}") 89 | print(f"Total duplicate MOFs ... {len(dupl)}") 90 | 91 | df = pd.DataFrame(rows) 92 | df.to_csv(args.output_csv, index=False) 93 | -------------------------------------------------------------------------------- /descriptors/gen_pers_homology.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import os 3 | import glob 4 | import time 5 | import argparse 6 | 7 | import numpy as np 8 | import pandas as pd 9 | 10 | from multiprocessing import Pool 11 | from subprocess import PIPE, Popen 12 | from pymatgen.core import Structure 13 | from mofdscribe.featurizers.topology import AtomCenteredPH 14 | 15 | 16 | def run_bash(cmd): 17 | p = Popen([cmd], shell=True, stdout=PIPE, stderr=PIPE) 18 | out, err = p.communicate() 19 | return out.decode("utf-8").strip().split() 20 | 21 | 22 | dest_path = f"{args.search_path}/homology_vectors" 23 | run_bash(f"mkdir -p {dest_path}") 24 | 25 | 26 | def gen_descriptors(file): 27 | stime = time.time() 28 | try: 29 | # read into pymatgen.Structure 30 | struct = Structure.from_file(file) 31 | # select mofdscribe featurizers 32 | new_types = ( 33 | "H", 34 | "C", 35 | "N-P", 36 | "O-S-Se", 37 | "F-Cl-Br-I", 38 | "Li-Be-Na-Mg-K-Ca-Rb-Sr-Cs-Ba-Fr-Ra", 39 | "Al-Si-Ga-Ge-As-In-Sn-Sb-Te-Tl-Pb-Bi-Po-At", 40 | "Sc-Ti-V-Cr-Mn-Fe-Co-Ni-Cu-Zn-Y-Zr-Nb-Mo-Tc-Ru-Rh-" 41 | "Pd-Ag-Cd-Hf-Ta-W-Re-Os-Ir-Pt-Au-Hg", 42 | "La-Ce-Pr-Nd-Pm-Sm-Eu-Gd-Tb-Dy-Ho-Er-Tm-Yb-Lu-Ac-" 43 | "Th-Pa-U-Np-Pu-Am-Cm-Bk-Cf-Es-Fm-Md-No-Lr", 44 | ) 45 | new_dimens = (0, 1, 2) 46 | featurizer = AtomCenteredPH(atom_types=new_types, dimensions=new_dimens) 47 | # calculate features 48 | feats = featurizer.featurize(struct) 49 | labels = featurizer.feature_labels() 50 | # output features 51 | bname = os.path.basename(file).replace(".cif", "") 52 | np.save(f"{dest_path}/{bname}.npy", feats) 53 | elapsedtime = time.time() - stime 54 | print(file, elapsedtime, "s") 55 | except Exception as e: 56 | print(f"{file} >> FEATURE CALCULATION Failed {e}\n") 57 | return None 58 | else: 59 | row = {"cif": [bname]} 60 | row.update({f"{label}": feats[i] for i, label in enumerate(labels)}) 61 | return pd.DataFrame(row) 62 | 63 | 64 | if __name__ == "__main__": 65 | code_desc = "Calculate Atom-specific Persistent Homology features as implemented in mofdscribe." 66 | parser = argparse.ArgumentParser(description=code_desc) 67 | parser.add_argument( 68 | "search_path", help="path where the structure files (cif) are located." 69 | ) 70 | parser.add_argument("num_cpus", help="no. cpus available for multiprocessing.") 71 | args = parser.parse_args() 72 | # 73 | files = glob.glob(f"{args.search_path}/*.cif", recursive=False) 74 | pool = Pool(processes=int(args.num_cpus)) 75 | df_path = f"{dest_path}/homology.csv" 76 | for results in pool.imap_unordered(gen_descriptors, files): 77 | if results is not None: 78 | if os.path.exists(df_path): 79 | results.to_csv(df_path, mode="a", header=False, index=False) 80 | else: 81 | results.to_csv(df_path, index=False) 82 | -------------------------------------------------------------------------------- /structure_validation/chk_overlap.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import argparse 3 | 4 | from pymatgen.io.cif import CifParser 5 | 6 | # Covalent radii revisited -- DOI:10.1039/B801115J 7 | COVALENT_RADII = { 8 | "H": 0.31, 9 | "He": 0.28, 10 | "Li": 1.28, 11 | "Be": 0.96, 12 | "B": 0.84, 13 | "C": 0.76, # for sp3; sp2 = 0.73; sp = 0.69 14 | "C_1": 0.69, 15 | "C_2": 0.73, 16 | "C_R": 0.73, 17 | "C_3": 0.76, 18 | "N": 0.71, 19 | "O": 0.66, 20 | "F": 0.57, 21 | "Ne": 0.58, 22 | "Na": 1.66, 23 | "Mg": 1.41, 24 | "Al": 1.21, 25 | "Si": 1.11, 26 | "P": 1.07, 27 | "S": 1.05, 28 | "Cl": 1.02, 29 | "Ar": 1.06, 30 | "K": 2.03, 31 | "Ca": 1.76, 32 | "Sc": 1.7, 33 | "Ti": 1.6, 34 | "V": 1.53, 35 | "Cr": 1.39, 36 | "Mn": 1.61, # low spin = 1.39 37 | "Fe": 1.52, # low spin = 1.32 38 | "Co": 1.5, # low spin = 1.26 39 | "Ni": 1.24, 40 | "Cu": 1.32, 41 | "Zn": 1.22, 42 | "Ga": 1.22, 43 | "Ge": 1.2, 44 | "As": 1.19, 45 | "Se": 1.2, 46 | "Br": 1.2, 47 | "Kr": 1.16, 48 | "Rb": 2.2, 49 | "Sr": 1.95, 50 | "Y": 1.9, 51 | "Zr": 1.75, 52 | "Nb": 1.64, 53 | "Mo": 1.54, 54 | "Tc": 1.47, 55 | "Ru": 1.46, 56 | "Rh": 1.42, 57 | "Pd": 1.39, 58 | "Ag": 1.45, 59 | "Cd": 1.44, 60 | "In": 1.42, 61 | "Sn": 1.39, 62 | "Sb": 1.39, 63 | "Te": 1.38, 64 | "I": 1.39, 65 | "Xe": 1.4, 66 | "Cs": 2.44, 67 | "Ba": 2.15, 68 | "La": 2.07, 69 | "Ce": 2.04, 70 | "Pr": 2.03, 71 | "Nd": 2.01, 72 | "Pm": 1.99, 73 | "Sm": 1.98, 74 | "Eu": 1.98, 75 | "Gd": 1.96, 76 | "Tb": 1.94, 77 | "Dy": 1.92, 78 | "Ho": 1.92, 79 | "Er": 1.89, 80 | "Tm": 1.9, 81 | "Yb": 1.87, 82 | "Lu": 1.87, 83 | "Hf": 1.75, 84 | "Ta": 1.7, 85 | "W": 1.62, 86 | "Re": 1.51, 87 | "Os": 1.44, 88 | "Ir": 1.41, 89 | "Pt": 1.36, 90 | "Au": 1.36, 91 | "Hg": 1.32, 92 | "Tl": 1.45, 93 | "Pb": 1.46, 94 | "Bi": 1.48, 95 | "Po": 1.4, 96 | "At": 1.5, 97 | "Rn": 1.5, 98 | "Fr": 2.6, 99 | "Ra": 2.21, 100 | "Ac": 2.15, 101 | "Th": 2.06, 102 | "Pa": 2, 103 | "U": 1.96, 104 | "Np": 1.9, 105 | "Pu": 1.87, 106 | "Am": 1.8, 107 | "Cm": 1.69, 108 | } 109 | 110 | 111 | if __name__ == "__main__": 112 | code_desc = ( 113 | "Check structure for overlapping atomic sites using Cordero Covalent radii." 114 | ) 115 | parser = argparse.ArgumentParser(description=code_desc) 116 | parser.add_argument( 117 | "filename", 118 | type=str, 119 | required=True, 120 | help="path to structure file (cif)", 121 | ) 122 | args = parser.parse_args() 123 | 124 | try: 125 | filename = args.filename 126 | parser = CifParser(filename) 127 | structure = parser.get_structures(primitive=False)[0] 128 | 129 | num_atoms = len(structure.frac_coords) 130 | 131 | criteria = 0.7 132 | num_problem = 0 133 | for i in range(num_atoms - 1): 134 | for j in range(i + 1, num_atoms): 135 | 136 | distance = structure.get_distance(i, j) 137 | if distance > 3.65: 138 | continue 139 | else: 140 | sum_radii = ( 141 | COVALENT_RADII[str(structure.species[i])] 142 | + COVALENT_RADII[str(structure.species[j])] 143 | ) 144 | if distance < criteria * sum_radii: 145 | num_problem += 1 146 | except: 147 | print("CTEST %s Error %i" % (filename, num_atoms)) 148 | exit(1) 149 | if num_problem == 0: 150 | print("CTEST %s Good %i" % (filename, num_atoms)) 151 | elif num_problem > 0: 152 | print("CTEST %s Bad %i %i" % (filename, num_atoms, num_problem)) 153 | -------------------------------------------------------------------------------- /structure_validation/chk_hypervalent.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import re 3 | import argparse 4 | import warnings 5 | 6 | 7 | from pymatgen.core import Structure 8 | 9 | from pymatgen.analysis.graphs import StructureGraph 10 | 11 | # from pymatgen.analysis.graphs import MoleculeGraph 12 | import pymatgen.analysis.local_env as env 13 | 14 | from pymatgen.io.babel import BabelMolAdaptor 15 | 16 | # from pymatgen.io.cif import CifWriter 17 | 18 | import openbabel 19 | from openbabel import pybel as pb 20 | 21 | 22 | def read_cif(file_path): 23 | return Structure.from_file(file_path, sort=False) 24 | 25 | 26 | def get_metal_indices(struct_): 27 | """This function returns metal site indices from a pymatgen Structure object""" 28 | metal_indices = [] 29 | 30 | for i, site in enumerate(struct_.sites): 31 | if site.species.contains_element_type("metal"): 32 | metal_indices.append(i) 33 | 34 | return metal_indices 35 | 36 | 37 | def get_graph(struct_): 38 | return StructureGraph.with_local_env_strategy(struct_, env.IsayevNN()) 39 | 40 | 41 | def get_smiles(mol): 42 | """This function returns a SMILES string from a pymatgen molecular graph""" 43 | babel_mol = BabelMolAdaptor(mol) 44 | pybel_mol = pb.Molecule(babel_mol.openbabel_mol) 45 | return pybel_mol.write("can").split()[0] 46 | 47 | 48 | def get_subgraphs(graph_): 49 | smiles_list = [] 50 | subgraphs = graph_.get_subgraphs_as_molecules(use_weights=False) 51 | for mol in subgraphs: 52 | if len(mol.sites) > 0: 53 | smiles = get_smiles(mol) 54 | smiles_list.append(smiles) 55 | 56 | return smiles_list 57 | 58 | 59 | def check_atoms(graph_, struct_): 60 | graph_dict = graph_.as_dict() 61 | atom_dict = {} 62 | connection_dict = {} 63 | bad_atom_list = [] 64 | counter = 0 65 | counter_2 = 2 66 | 67 | for atom in struct_: 68 | 69 | atom_id = "{}{}".format(atom.specie, 1) 70 | 71 | while atom_id in atom_dict.values(): 72 | atom_id = "{}{}".format(atom.specie, counter_2) 73 | counter_2 += 1 74 | 75 | atom_dict["{}".format(counter)] = atom_id 76 | 77 | counter += 1 78 | counter_2 = 2 79 | 80 | for atom, connections in zip( 81 | graph_dict["graphs"]["nodes"], graph_dict["graphs"]["adjacency"] 82 | ): 83 | for connection in connections: 84 | atom1 = atom_dict["{}".format(atom["id"])] 85 | atom2 = atom_dict["{}".format(connection["id"])] 86 | bond_length = round(struct_.get_distance(atom["id"], connection["id"]), 4) 87 | if atom1 not in connection_dict.keys(): 88 | connection_dict[atom1] = [atom2] 89 | if atom2 not in connection_dict.keys(): 90 | connection_dict[atom2] = [atom1] 91 | else: 92 | connection_dict[atom2].append(atom1) 93 | else: 94 | connection_dict[atom1].append(atom2) 95 | if atom2 not in connection_dict.keys(): 96 | connection_dict[atom2] = [atom1] 97 | else: 98 | connection_dict[atom2].append(atom1) 99 | for atom in connection_dict.keys(): 100 | if re.sub(r"\d+", "", atom) == "H" and len(connection_dict[atom]) > 1: 101 | print("BAD ATOM: {}".format(atom)) 102 | bad_atom_list.append(atom) 103 | elif re.sub(r"\d+", "", atom) == "C" and len(connection_dict[atom]) > 4: 104 | print("BAD ATOM: {}".format(atom)) 105 | bad_atom_list.append(atom) 106 | elif re.sub(r"\d+", "", atom) == "O" and len(connection_dict[atom]) > 2: 107 | print("BAD ATOM: {}".format(atom)) 108 | bad_atom_list.append(atom) 109 | elif ( 110 | re.sub(r"\d+", "", atom) in ["F", "Cl", "Br", "I"] 111 | and len(connection_dict[atom]) > 1 112 | ): 113 | print("BAD ATOM: {}".format(atom)) 114 | bad_atom_list.append(atom) 115 | return bad_atom_list 116 | 117 | 118 | def main(filename): 119 | 120 | struct = read_cif(filename) 121 | # atom_dict = struct.as_dict() 122 | metals = get_metal_indices(struct) 123 | graph = get_graph(struct) 124 | graph.remove_nodes(indices=metals) 125 | 126 | bad_atoms = check_atoms(graph, struct) 127 | 128 | if len(bad_atoms) > 0: 129 | print(f" {filename} | BAD STRUCTURE") 130 | elif len(bad_atoms) == 0: 131 | print(f" {filename} | GOOD STRUCTURE") 132 | 133 | 134 | if __name__ == "__main__": 135 | code_desc = "Checks structure for hypervalent H, C, O, and halogens atomic sites." 136 | parser = argparse.ArgumentParser(description=code_desc) 137 | parser.add_argument( 138 | "filename", 139 | type=str, 140 | required=True, 141 | help="path to structure file (cif)", 142 | ) 143 | args = parser.parse_args() 144 | with warnings.catch_warnings(): 145 | warnings.simplefilter("ignore") 146 | input_cif = args.filename 147 | main(input_cif) 148 | -------------------------------------------------------------------------------- /zenodo/get_unchanged_mofs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import os 3 | import shutil 4 | import argparse 5 | 6 | from ccdc import io 7 | from ccdc.io import EntryReader 8 | 9 | from clean_csd_mofs import clean_structure 10 | from write_pac_cif import assign_partial_atomic_charge 11 | 12 | CODE_PATH = os.path.dirname(os.path.realpath(__file__)) 13 | 14 | 15 | # text editing to remove disordered/partially occupied sites 16 | def filter_disorder(cif): 17 | filtered_lines = [] 18 | if isinstance(cif, str): 19 | lines = cif.split("\n") 20 | else: 21 | with open(cif, "r") as rf: 22 | lines = rf.read().split("\n") 23 | 24 | for line in lines: 25 | try: 26 | spl = line.split() 27 | if (spl[0][-1] != "*") and (spl[0][-1] != "?"): 28 | filtered_lines.append(line) 29 | except IndexError as ie: 30 | filtered_lines.append(line) 31 | continue 32 | except Exception as e: 33 | print(cif, " | error removing disordered sites") 34 | print(e) 35 | else: 36 | continue 37 | return "\n".join(filtered_lines) 38 | 39 | 40 | # get cifs from csd 41 | def print_cifs(gcd_file, write_path, rm_disordered_sites): 42 | with open(gcd_file, "r") as rf: 43 | refcode_list = [_ for _ in rf.read().split("\n") if _ != ""] 44 | 45 | reader = EntryReader("CSD") 46 | for refcode in refcode_list: 47 | try: 48 | entry = reader.entry(refcode) 49 | mol = entry.disordered_molecule 50 | cif_str = mol.to_string("cif") 51 | if rm_disordered_sites: 52 | cif_str = filter_disorder(cif_str) 53 | cif_path = os.path.join(write_path, f"{entry.identifier}.cif") 54 | with open(cif_path, "w") as wf: 55 | wf.write(cif_str) 56 | except Exception as e: 57 | print(refcode, " | failed to print cif") 58 | continue 59 | return refcode_list 60 | 61 | 62 | # convert cifs to P1 symmetry 63 | def convert2P1(refs, out_dir, rename=None): 64 | for ref in refs: 65 | try: 66 | clean_structure( 67 | f"{out_dir}/{ref}_P1.cif", 68 | read_path=f"tmp_cifs/{ref}", 69 | input_is_cif=True, 70 | ) 71 | if rename: 72 | p1_name = ref + "_P1.cif" 73 | mdb_name = p1_name.replace("_P1.cif", rename) 74 | shutil.move(f"{out_dir}/{p1_name} ", f"{out_dir}/{mdb_name}") 75 | except Exception as e: 76 | print(ref, " | failed to convert2P1 cif") 77 | print(e) 78 | continue 79 | return 0 80 | 81 | 82 | if __name__ == "__main__": 83 | code_desc = "Retrieve MOSAEC-DB cifs for refcodes which were unchanged." 84 | parser = argparse.ArgumentParser(description=code_desc) 85 | # full > os.path.join(CODE_PATH, "../database/full/unchanged_refcodes_full.gcd") 86 | # partial > os.path.join(CODE_PATH, "../database/partial/unchanged_refcodes_partial.gcd") 87 | parser.add_argument( 88 | "--gcd_files", 89 | nargs="+", 90 | default=[ 91 | os.path.join(CODE_PATH, "../database/full/unchanged_refcodes_full.gcd"), 92 | os.path.join( 93 | CODE_PATH, "../database/partial/unchanged_refcodes_partial.gcd" 94 | ), 95 | ], 96 | help="path(s) to .gcd file with desired refcodes.", 97 | ) 98 | parser.add_argument( 99 | "--remove_disorder", 100 | action="store_true", 101 | help="whether to remove disordered atom sites via simple text editing", 102 | ) 103 | parser.add_argument( 104 | "--write_repeat", 105 | action="store_true", 106 | help="whether to also write files containing REPEAT charges.", 107 | ) 108 | parser.add_argument( 109 | "--write_mepoml", 110 | action="store_true", 111 | help="whether to also write files containing MEPOML charges.", 112 | ) 113 | args = parser.parse_args() 114 | 115 | print("Writing MOSAEC-DB cifs ...\n") 116 | for gcd in args.gcd_files: 117 | # print tmp cifs 118 | cif_dir = "tmp_cifs" 119 | os.makedirs(cif_dir, exist_ok=True) 120 | refs = print_cifs(gcd, cif_dir, args.remove_disorder) 121 | 122 | # convert cifs to P1 & rename 123 | p1_dir = "MOSAEC-DB_unchanged" 124 | os.makedirs(p1_dir, exist_ok=True) 125 | os.makedirs("./tmp", exist_ok=True) 126 | f_end = "_full.cif" if "full" in gcd else "_partial.cif" 127 | convert2P1(refs, p1_dir, rename=f_end) 128 | 129 | shutil.rmtree(cif_dir) 130 | shutil.rmtree("./tmp") 131 | 132 | if args.write_repeat: 133 | print("\nWriting MOSAEC-DB REPEAT cifs ...\n") 134 | repeat_dir = "MOSAEC-DB_unchanged_REPEAT" 135 | os.makedirs(repeat_dir, exist_ok=True) 136 | rpt_json = os.path.join(CODE_PATH, "../misc_data/unchanged_repeat.json") 137 | assign_partial_atomic_charge(p1_dir, rpt_json, repeat_dir, pac_type="REPEAT") 138 | 139 | if args.write_mepoml: 140 | print("\nWriting MOSAEC-DB MEPO-ML cifs ...\n") 141 | mepoml_dir = "MOSAEC-DB_unchanged_MEPOML" 142 | os.makedirs(mepoml_dir, exist_ok=True) 143 | mpml_json = os.path.join(CODE_PATH, "../misc_data/unchanged_mepoml.json") 144 | assign_partial_atomic_charge(p1_dir, mpml_json, mepoml_dir, pac_type="MEPOML") 145 | 146 | -------------------------------------------------------------------------------- /zenodo/README.md: -------------------------------------------------------------------------------- 1 | # MOSAEC Database (v1.0.0-release) 2 | 3 | > [!WARNING] 4 | > ** The Database Zenodo record(s) will be taken down pending confirmation/amendments to the licensing agreement pertaining to the enclosed crystallographic data** 5 | 6 | [![Article](https://flat.badgen.net/static/Article/10.1039%2FD4SC07438F/nblue/)](https://doi.org/10.1039/D4SC07438F) 7 | 8 |

9 | mosaecdb 10 |

11 | 12 | MOSAEC-DB consists of 124k+ metal-organic framework (MOF) and coordination polymer crystallographic information files (.cif) processed for atomistic simulations. This database contains solely experimental crystal structures derived from the Cambridge Structural Database (CSD) which have been processed by novel solvent removal (SAMOSA) and error analysis (MOSAEC) tools. 13 | 14 | ## Download 15 | The MOSAEC-DB files, including all publicly-available crystal structures, file management scripts, and supplemental data, can be downloaded from the [zenodo](https://doi.org/10.5281/zenodo.14780807) record. 16 | 17 | Additional scripts used in the construction and analysis of MOSAEC-DB, as well as general database use information, are available in a [GitHub](https://github.com/uowoolab/MOSAEC-DB) repository. 18 | 19 | ## Details 20 | 21 | All structures have been converted to 'P1' symmetry, and undergone solvent removal and structure validity verification using in-house codes. Check the [GitHub](https://github.com/uowoolab/MOSAEC-DB) for the links to these codes when they become available. 22 | 23 | Broadly, the solvent removal and structure validity codes employ concept of metal oxidation states and ligand formal charges to establish proper solvent removal decision-making and identify potentially problematic crystal structures. 24 | 25 | ### Directory Structure 26 | 27 | ``` 28 | . 29 | ├── database 30 | │  ├── full 31 | │      ├── charged 32 | │      ├── neutral 33 | │      └── unchanged_refcodes_full.gcd 34 | │  └── partial 35 | │      ├── charged 36 | │      ├── neutral 37 | │      └── unchanged_refcodes_partial.gcd 38 | ├── database_MEPOML 39 | ├── database_REPEAT 40 | ├── descriptors 41 | │      ├── APRDF_mosaec-db.csv 42 | │      ├── GEOM_mosaec-db.csv 43 | │      ├── PHOM_mosaec-db.csv 44 | │      └── RAC_mosaec-db.csv 45 | ├── misc_data 46 | | ├── PDD_duplicate_thresh0.15.csv 47 | │      ├── unchanged_mepoml.json 48 | │      └── unchanged_repeat.json 49 | ├── scripts 50 | ├── subsets 51 | │      ├── details_sampling 52 | │      ├── diverse-neutral-*-20k.txt 53 | │      ├── diverse-charged-*-3k.txt 54 | │      ├── uniq-neutral-porous-2.4pld.txt 55 | │      └── uniq-neutral-porous-0.10vf.txt 56 | ├── mosaec-db.xlsx 57 | ├── mosaec-db.csv 58 | └── README.md 59 | ``` 60 | 61 | Primary directories containing the crystal structures (.cif) are organized according to activation (i.e. full vs. partial activation) and framework charge (i.e. neutral vs. charged) states.Separate directories are provided for files containing precomputed partial atomic charges, namely those calculated via the DFT-derived REPEAT charges and the ML-predicted MEPO-ML charges. 62 | 63 | Calculated properties and information related to the structure processing can be found in the attached, identical excel worksheet (mosaec-db.xlsx) and csv (mosaec-db.csv). Additional properties will be found in the `misc_data` directory, such as a full record of the structure duplicate data. 64 | 65 | ### Scripts 66 | 67 | Subsets of MOSAEC-DB are arranged according to common conventions of porosity in prior databases, as well as a diverse sampling of several chemical and geometric descriptors (denoted as * in the directory structure). Sampling was achieved using [farthest point sampling](https://github.com/uowoolab/MOF-Diversity-Analysis/blob/main/farthest_point_sampling.py) of the desired descriptor vector. Details regarding the order in which the crystal structures are sampled are provided (subsets/sampling_details) if further sub-sampling is required. 68 | 69 | ``` 70 | python get_subset.py ../subsets/______.txt 71 | ``` 72 | 73 | Crystal structures that were unchanged by the database construction protocol due to their lack of solvent are outlined in corresponding text files (.gcd). Access to these structures is subject to the users' CSD license status, however the computation ready structure can be regenerated by applying the provided structure processing codes to the relevant CSD REFCODES. This script makes use of a [CSD-Cleaner](https://github.com/uowoolab/CSD-cleaner) code that requires the CSD Python API and pymatgen packages. 74 | 75 | ``` 76 | python get_unchanged_mofs.py --remove_disorder 77 | ``` 78 | 79 | Additionally, **experimental** functionality to regenerate the structure files containing partial atomic charges (REPEAT/MEPO-ML) is provided in these scripts. Consistency of these functions is subject to change with various versions of pymatgen and the CSD Python API, thus we cannot guarantee accuracy to the original, computed partial atomic charges. Testing was performed using Python 3.9.x, csd-python-api 3.1.0, and pymatgen 2024.5.31. Check the GitHub repository before using these scripts to ensure you are using the most up-to-date versions possible. 80 | 81 | ``` 82 | python get_unchanged_mofs.py --remove_disorder --write_repeat --write_mepoml 83 | ``` 84 | 85 | ## Updates 86 | Information regarding future updates and additions to the database will be outlined in the [GitHub](https://github.com/uowoolab/MOSAEC-DB/blob/main/CHANGELOG.md) repository established at the time of publication. 87 | 88 | ## Licensing 89 | The [CC BY 4.0 license](https://creativecommons.org/licenses/by/4.0/) applies to the utilization of the MOSAEC database. Follow the license guidelines regarding the use, sharing, adaptation, and attribution of this data. 90 | 91 | ## Citation 92 | Please cite the following [article](https://doi.org/10.1039/D4SC07438F) when using MOSAEC-DB. 93 | 94 | ## Contact 95 | Reach out to any of the following authors with any questions: 96 | 97 | Marco Gibaldi: marco.gibaldi@uottawa.ca 98 | 99 | Tom Woo: tom.woo@uottawa.ca 100 | 101 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MOSAEC Database (v1.0.0-release) 2 | 3 | > [!WARNING] 4 | > ** The Database Zenodo record(s) will be taken down pending confirmation/amendments to the licensing agreement pertaining to the enclosed crystallographic data** 5 | 6 | [![Article](https://flat.badgen.net/static/Article/10.1039%2FD4SC07438F/nblue/)](https://doi.org/10.1039/D4SC07438F) 7 | ![Python](https://flat.badgen.net/static/Python/3.9%20|%203.11/green/) 8 | [![Formatter](https://flat.badgen.net/static/Code%20Format/black/black)](https://black.readthedocs.io/en/stable/) 9 | 10 |

11 | mosaecdb 12 |

13 | 14 | MOSAEC-DB is a database of metal-organic framework (MOF) and coordination polymer crystallographic information files (.cif) processed for atomistic simulations. 15 | 16 | This repository collects the software applied during database construction, validation, and analysis. 17 | 18 | Additionally, this repository will provide further information regarding the use of the database and changes to the database: 19 | - [Frequently Asked Questions](FAQ.md) 20 | - [Updates](CHANGELOG.md) 21 | 22 | # Download 23 | The MOSAEC-DB files, including all publicly-available crystal structures, scripts, and supplemental data, can be downloaded from the [zenodo](https://doi.org/10.5281/zenodo.14780807) repository. 24 | 25 | # Database Construction 26 | 27 | ## Structure Retrieval & Symmetry Conversion 28 | 29 | Initial crystal structures may be retrieved directly from the Cambridge Structural Database (CSD) through the [ConQuest](https://www.ccdc.cam.ac.uk/solutions/software/conquest/) program or their provided [Python API](https://www.ccdc.cam.ac.uk/solutions/csd-core/components/csd-python-api/). 30 | 31 | Retrieved CSD crystal structures were converted to `P1` symmetry using our [CSD-Cleaner](https://github.com/uowoolab/CSD-cleaner) code. 32 | 33 | ## Solvent Removal 34 | 35 | The [SAMOSA](https://github.com/uowoolab/SAMOSA) solvent removal method was utilized in database construction. A [publication](https://doi.org/10.1021/acs.jcim.4c01897) outlining the details of this method is available. All `*_full` MOSAEC-DB structures were generated with default settings, while `*_partial` structures were generated with the `--keep_bound` option. 36 | 37 | ## Structure Error Analysis 38 | 39 | The results of the [MOSAEC](https://github.com/uowoolab/MOSAEC) error checking algorithm were used to determine whether to include a structure in MOSAEC-DB. A [preprint](https://doi.org/10.26434/chemrxiv-2024-ftsv3) article outlining the details of this method is available, and the GitHub repository will be available to the public shortly (following its publication). Only structures which passed the MOSAEC error flagging routine were included in the final database. 40 | 41 | ## Structure Validation 42 | 43 | Additional tools to check for problematic structures which may not have been caught by the structure error analyses are provided in [structure_validation](structure_validation/). This includes codes to search for overlapping and hypervalent atom sites. 44 | 45 | ## Duplicate Structure Analysis 46 | 47 | Criterion based on pointwise distance distribution (PDD) scores were applied to identify duplicated and/or highly similar crystal structures with shared empirical formulas. The codes used to complete this analysis are provided in [duplicates](duplicates/). 48 | 49 | # Descriptor Calculation 50 | 51 | ## Global Structure Features 52 | 53 | Descriptors characterizing the databases' geometric and chemical environments were generated using a number of standard libraries. 54 | 55 | The codes generating the atomic property-weighted radial distribution function ([AP-RDF](https://github.com/uowoolab/MOF-Descriptor-Codes/tree/main/AP-RDFs)) and revised autocorrelation function ([RAC](https://github.com/uowoolab/MOF-Descriptor-Codes/tree/main/RACs)) are identical to those used in the ARC-MOF database. 56 | 57 | Geometric properties were generated using the [Zeo++](http://www.zeoplusplus.org/) v0.3.0 software with default settings. 58 | 59 | Any code used to generate descriptors which were not previously made available are provided in [descriptors](descriptors/), including the atom-specific persistent homology descriptors included in the zenodo record. 60 | 61 | ## Partial Atomic Charges 62 | 63 | Electrostatic potential-derived partial atomic charges were computed for as many MOSAEC-DB structures as possible using the previously reported [REPEAT](https://doi.org/10.1021/ct9003405) method. The most recent version of this code is available at the following [repository](https://github.com/uowoolab/REPEAT). 64 | 65 | Additionally, a broader set of MOSAEC-DB were assigned ML-predicted partial atomic charges using the [MEPO-ML](https://github.com/uowoolab/MEPO-ML) models that we reported in a recent [publication](https://doi.org/10.1038/s41524-024-01413-4). 66 | 67 | ## Framework Dimensionality 68 | 69 | Each crystal structure's dimensionality was calculated using a previously reported [algorithm](https://github.com/ccdc-opensource/science-paper-mofs-2020/tree/main). 70 | 71 | ## Topology 72 | 73 | The [CrystalNets](https://github.com/coudertlab/CrystalNets.jl) package was applied to compute the net topology. A simple julia [script](descriptors/runcrystalnet.jl) was used to characterize MOSAEC-DB crystal structures. 74 | 75 | # File Management Utilities 76 | 77 | Additional utilities unrelated to the MOSAEC-DB database construction and characterization processes are also provided in the zenodo record to facilitate simple file manipulations. These tools are available in [zenodo](zenodo/) alongside descriptions of their functions below. 78 | 79 | ## Unchanged Crystal Structure Retrieval 80 | 81 | Crystal structures that were unchanged by the database construction protocol due to their lack of solvent are outlined in corresponding text files (.gcd). Access to these structures is subject to the users' CSD license status, however the computation ready structure can be regenerated by applying the provided structure processing codes to the relevant CSD REFCODES. This script makes use of a [CSD-Cleaner](https://github.com/uowoolab/CSD-cleaner) code that depends on the CSD Python API and pymatgen packages. 82 | 83 | ``` 84 | python get_unchanged_mofs.py --remove_disorder 85 | ``` 86 | 87 | Additionally, **experimental** functionality to regenerate the structure files containing partial atomic charges (REPEAT/MEPO-ML) is provided in these scripts. Consistency of these functions is subject to change with various versions of pymatgen and the CSD Python API, thus we cannot guarantee accuracy to the original, computed partial atomic charges. Testing was performed using Python 3.9.x, csd-python-api 3.1.0, and pymatgen 2024.5.31. 88 | 89 | ``` 90 | python get_unchanged_mofs.py --remove_disorder --write_repeat --write_mepoml 91 | ``` 92 | 93 | ## Subset Preparation 94 | 95 | Subsets of MOSAEC-DB are arranged according to common conventions of porosity in prior databases, as well as a diverse sampling of several chemical and geometric descriptors. Sampling was achieved using [farthest point sampling](https://github.com/uowoolab/MOF-Diversity-Analysis/blob/main/farthest_point_sampling.py) of the desired descriptor vector. 96 | 97 | ``` 98 | python get_subset.py ../subsets/______.txt 99 | ``` 100 | 101 | ## Updates 102 | Information regarding future updates and additions to the database will be outlined in the [GitHub](CHANGELOG.md) repository established at the time of publication. 103 | 104 | ## Licensing 105 | The [CC BY 4.0 license](https://creativecommons.org/licenses/by/4.0/) applies to the utilization of the MOSAEC database. Follow the license guidelines regarding the use, sharing, adaptation, and attribution of this data. 106 | 107 | ## Citation 108 | Please cite the following [article](https://doi.org/10.1039/D4SC07438F) when using MOSAEC-DB. 109 | 110 | ## Contact 111 | Reach out to any of the following authors with any questions: 112 | 113 | Marco Gibaldi: marco.gibaldi@uottawa.ca 114 | 115 | Tom Woo: tom.woo@uottawa.ca 116 | 117 | -------------------------------------------------------------------------------- /zenodo/write_pac_cif.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import os 3 | import glob 4 | import json 5 | import argparse 6 | import warnings 7 | 8 | import numpy as np 9 | 10 | from datetime import date 11 | from pathlib import Path 12 | from collections import defaultdict 13 | 14 | from pymatgen.io.cif import CifParser 15 | 16 | 17 | # compare floats within a certain tolerance 18 | def floats_equal(a, b, tol=0.01): 19 | a = float(a) 20 | b = float(b) 21 | return abs(a - b) <= (min(abs(a), abs(b)) * tol) 22 | 23 | 24 | # read in partial atomic charges stored in JSON file 25 | def read_pac_json(json_name): 26 | with open(json_name, "r") as jsonr: 27 | pac_dict = json.load(jsonr) 28 | return pac_dict 29 | 30 | 31 | # iterate 32 | def assign_partial_atomic_charge( 33 | cifs_path, repeat_json, dst_path=None, pac_type="REPEAT" 34 | ): 35 | # set defaults for arguments 36 | if dst_path is None: 37 | dst_path = cifs_path.parent 38 | else: 39 | dst_path = Path(dst_path) 40 | # get saved json charge dict 41 | charge_dict = read_pac_json(repeat_json) 42 | # find all cifs to be processed 43 | cifs = glob.glob(f"{cifs_path}/*.cif", recursive=False) 44 | # 45 | for cif_path in cifs: 46 | # check if charges available in stored json 47 | if os.path.basename(cif_path) in charge_dict.keys(): 48 | charge_dict_i = charge_dict[os.path.basename(cif_path)] 49 | else: 50 | print(f"{cif_path} | ERROR | {pac_type} not stored") 51 | continue 52 | # parse cif using pymatgen 53 | cif_path = Path(cif_path) 54 | with warnings.catch_warnings(): 55 | warnings.simplefilter("ignore") 56 | try: 57 | cif_struct = CifParser(cif_path).get_structures(primitive=False).pop() 58 | except ValueError: 59 | print(f"{cif_path} | ERROR | EMPTY cif") 60 | continue 61 | 62 | # compare number of atoms between CIF and saved JSON 63 | # if len(cif_struct) != len(charge_dict_i): 64 | json_num_atoms = sum( 65 | [len(v) for k, v in charge_dict_i.items() if k != "rand_key"] 66 | ) 67 | if len(cif_struct) != json_num_atoms: 68 | print( 69 | cif_path, 70 | " | ERROR | Different number of atoms in CIF (", 71 | len(cif_struct), 72 | ") and JSON (", 73 | json_num_atoms, 74 | ").", 75 | ) 76 | continue 77 | 78 | # Get atomic symbols and fractional coordinates for all atoms 79 | symbols = [atom.specie.symbol for atom in cif_struct] 80 | frac_xyz = np.around([atom.frac_coords for atom in cif_struct], decimals=6) 81 | frac_xyz[frac_xyz == 0.0] = 0.0 82 | 83 | # Reassign labels for all atoms 84 | labels = [] 85 | label_counter = {element: 0 for element in set(symbols)} 86 | for symbol in symbols: 87 | label_counter[symbol] += 1 88 | labels.append(f"{symbol}{label_counter[symbol]}") 89 | 90 | # Create preambles for the new CIF file 91 | if pac_type == "REPEAT": 92 | new_cif = "# Generated by REPEAT Assigner based on pymatgen\n" 93 | else: 94 | new_cif = "# Charges generated by MEPO-ML\n" 95 | # 96 | new_cif += f"data_{cif_path.name.replace('.cif', '')}\n" 97 | new_cif += "_audit_creation_date " 98 | new_cif += date.today().strftime("%Y-%m-%d") + "\n" 99 | # 100 | if pac_type == "REPEAT": 101 | new_cif += "_audit_creation_method REPEAT_Assigner\n" 102 | else: 103 | new_cif += "_audit_creation_method MEPO-ML\n" 104 | 105 | # Create cell info for the new CIF file 106 | new_cif += f"_cell_length_a {cif_struct.lattice.a:.6f}\n" 107 | new_cif += f"_cell_length_b {cif_struct.lattice.b:.6f}\n" 108 | new_cif += f"_cell_length_c {cif_struct.lattice.c:.6f}\n" 109 | new_cif += f"_cell_angle_alpha {cif_struct.lattice.alpha:.6f}\n" 110 | new_cif += f"_cell_angle_beta {cif_struct.lattice.beta:.6f}\n" 111 | new_cif += f"_cell_angle_gamma {cif_struct.lattice.gamma:.6f}\n" 112 | new_cif += ( 113 | f"_cell_volume {cif_struct.lattice.volume:.6f}\n" 114 | ) 115 | 116 | # [ASSUMED P1] Create symmetry info for the new CIF file 117 | new_cif += "_symmetry_space_group_name_H-M P1\n" 118 | new_cif += "_symmetry_Int_Tables_number 1\n" 119 | new_cif += "loop_\n" 120 | new_cif += " _symmetry_equiv_pos_site_id\n" 121 | new_cif += " _symmetry_equiv_pos_as_xyz\n" 122 | new_cif += " 1 x,y,z\n" 123 | 124 | # Create atom info for the new CIF file 125 | new_cif += "loop_\n" 126 | new_cif += " _atom_site_type_symbol\n" 127 | new_cif += " _atom_site_label\n" 128 | new_cif += " _atom_site_fract_x\n" 129 | new_cif += " _atom_site_fract_y\n" 130 | new_cif += " _atom_site_fract_z\n" 131 | new_cif += " _atom_type_partial_charge\n" 132 | 133 | # Adjust widths for the symbols and labels column 134 | symbol_width = len(max(symbols, key=len)) 135 | label_width = len(max(labels, key=len)) 136 | 137 | # flags to gauge if cif is consistent with prior entry 138 | # required for changes in atom ordering with different version of 139 | # dependencies e.g., pymatgen 140 | 141 | # block writing if error is encountered 142 | write_cif = True 143 | # whether the ordering of the sites/labels e.g., C1, C2, C3... 144 | # equals past ordering (potential for different CifParsing behaviour) 145 | label_order_issue = False 146 | # dict mapping the current:past cif atom labels 147 | label_mismatch = defaultdict(str) 148 | # Loop over all atoms and create info line for each of 149 | rand_num = np.array(charge_dict_i["rand_key"]) 150 | # track number of matches 151 | try: 152 | match_count = 0 153 | for j, (symbol, label, frac) in enumerate(zip(symbols, labels, frac_xyz)): 154 | # prev_line = charge_dict_i[str(j)] 155 | pac_list_Z = charge_dict_i[symbol] 156 | # iterate over all sites with shared atomic symbol to find match 157 | # match_ind = None 158 | # frac_sum = sum(frac) 159 | frac_sum = sum(frac * rand_num) 160 | for k, site_dict in enumerate(pac_list_Z): 161 | # check X 162 | if not floats_equal(frac[0], site_dict["x"]): 163 | continue 164 | # check sum 165 | # if not floats_equal(frac_sum, site_dict["sum"]): 166 | if not floats_equal(frac_sum, site_dict["sum_rand"]): 167 | continue 168 | # check label 169 | if label != site_dict["label"]: 170 | label_mismatch[label] = site_dict["label"] 171 | label_order_issue = True 172 | # select index that passes all checks 173 | match_ind = k 174 | break 175 | # cleanup 176 | if match_ind != None: 177 | match_count += 1 178 | charge = pac_list_Z[match_ind]["charge"] 179 | # write line 180 | new_cif += f" {symbol:{symbol_width}} {label:{label_width}} " 181 | new_cif += "{:.6f} {:.6f} {:.6f} ".format(*frac) + f"{charge}\n" 182 | else: 183 | print( 184 | f"{cif_path} | ERROR | Did not find a matching atom site ... \n", 185 | label, 186 | ) 187 | print(symbol, label, frac, frac_sum) 188 | print(pac_list_Z) 189 | write_cif = False 190 | break 191 | except Exception as e: 192 | print(f"{cif_path} | ERROR | Issue assigning Charge", e) 193 | continue 194 | 195 | if label_order_issue: 196 | print( 197 | f"{cif_path} | WARNING | Label mismatch ... \n", 198 | dict(label_mismatch), 199 | ) 200 | if write_cif & (match_count == len(cif_struct)): 201 | # Write the new CIF 202 | dst_path.joinpath( 203 | cif_path.name.replace(".cif", f"_{pac_type}.cif") 204 | ).write_text(new_cif) 205 | 206 | 207 | if __name__ == "__main__": 208 | code_desc = "Assigning partial atomic charges (PAC e.g., REPEAT, MEPO-ML) to a MOSAEC-DB CIF." 209 | ap = argparse.ArgumentParser(description=code_desc) 210 | ap.add_argument("cif_path", type=str, help="path to the structure files (cif).") 211 | ap.add_argument( 212 | "-o", 213 | "--outdir", 214 | type=str, 215 | metavar="OUTPUT_DIR", 216 | help="output directory for structure files with PACs included.", 217 | ) 218 | ap.add_argument( 219 | "-r", 220 | "--repeat_json", 221 | type=str, 222 | metavar="REPEAT_JSON", 223 | help="Explicitly provide the name of the REPEAT output file.", 224 | ) 225 | ap.add_argument( 226 | "--pac_type", 227 | type=str, 228 | default="REPEAT", 229 | metavar="PAC_TYPE", 230 | choices=["REPEAT", "MEPOML"], 231 | ) 232 | args = ap.parse_args() 233 | assign_partial_atomic_charge(args.cif, args.repeat_json, args.outdir, args.pac_type) 234 | 235 | -------------------------------------------------------------------------------- /zenodo/clean_csd_mofs.py: -------------------------------------------------------------------------------- 1 | from ccdc import io 2 | from ccdc.io import CrystalWriter 3 | from pymatgen.symmetry.groups import sg_symbol_from_int_number, SpaceGroup 4 | from pymatgen.core import Structure, Lattice 5 | from pymatgen.core.operations import SymmOp 6 | from pymatgen.io.cif import CifWriter 7 | import argparse 8 | import os 9 | import uuid 10 | import numpy as np 11 | import shutil 12 | 13 | script_path, script_name = os.path.split(os.path.realpath(__file__)) 14 | temp_cif_path = "/tmp/temp-{}.cif".format(uuid.uuid4().hex) 15 | 16 | 17 | def get_block(cif_lines, keyword, start): 18 | """ 19 | Separate a cif into blocks based on "loop_" sections. 20 | 21 | Parameters: 22 | cif_lines (list of str): list of lines in cif file 23 | keyword (str): keyword identifying block (e.g., "atom" for atoms 24 | "symmetry" for symmetry operations, "geom" for geometry 25 | (bonding) information, etc.) 26 | start (int): the line number of beginning of block (line after "loop_") 27 | 28 | Returns: 29 | block (list of str): list of lines in the "block" from the cif 30 | """ 31 | 32 | for num, line in enumerate(cif_lines[start:]): 33 | if ( 34 | line[0] == "_" 35 | and not line.strip("\n").split("_", maxsplit=1)[1].startswith(keyword) 36 | or "loop_" in line 37 | ): 38 | end = num + start 39 | break 40 | try: 41 | block = cif_lines[start:end] 42 | except UnboundLocalError: 43 | block = cif_lines[start:] 44 | # Remove any "loop_" lines 45 | block = [val for val in block if val != "loop_\n"] 46 | 47 | return block 48 | 49 | 50 | def get_dict(lst, good_atoms, label_key): 51 | """ 52 | Get a dictionary of structural attributes of a cif containing only certain 53 | atoms. For example, to get a dictionary of atoms and their coordinates for only 54 | a certain list of atoms. This works given a list of lines from a "block" in a cif 55 | (identified by the "loop_" sections) 56 | 57 | Parameters: 58 | lst (list of str): List of lines to consider for dictionary 59 | good_atoms (list of str): Atom labels to consider for dictionary 60 | label_key (str): the header which will be used as the keys of the dict 61 | (e.g., for atom labels use _atom_site_label) 62 | 63 | Returns: 64 | dict (dict): Dictionary of specified keys and attributes (properties) 65 | (properties are the remaining headers in the "loop_" section) 66 | """ 67 | 68 | dict = {} 69 | for num, line in enumerate(lst): 70 | if line[0] == "_": 71 | dict[line.strip().strip("\n")] = [] 72 | for num, line in enumerate(lst): 73 | if line[0] != "_": 74 | line = line.strip().replace("(", "").replace(")", "").split() 75 | if line[list(dict.keys()).index(label_key)] in good_atoms: 76 | for n, prop in enumerate(dict.keys()): 77 | dict[prop].append(line[n]) 78 | 79 | return dict 80 | 81 | 82 | def get_asymmetric_unit(ref, is_cif=False): 83 | """ 84 | Retrieve a cif from the CSD and return the 85 | asymmetric unit molecule atoms. Also, write the crystal to a 86 | temporary cif to get atomic coordinates of the crystal 87 | (no way to do this with CSD). If is_cif is True, do not 88 | retrieve the structure from CSD, just read the specified cif. 89 | 90 | Parameters: 91 | ref (str): the CSD refcode for the structure (or cif filename if 92 | is_cif is equal to True) 93 | Returns: 94 | atoms (list of str): the atom labels of the asymmetric unit molecule 95 | 96 | """ 97 | if is_cif: 98 | cryst = io.CrystalReader(ref)[0] 99 | else: 100 | csd_reader = io.EntryReader("CSD") 101 | cryst = csd_reader.entry(ref).crystal 102 | cryst.centre_molecule() 103 | mol = cryst.asymmetric_unit_molecule 104 | atoms = [str(atom).replace("Atom(", "").strip(")") for atom in mol.atoms] 105 | with CrystalWriter(temp_cif_path) as mol_writer: 106 | mol_writer.write(cryst) 107 | 108 | return atoms 109 | 110 | 111 | def convert_to_p1(ops, asym_unit_atoms, asym_unit_coords): 112 | """ 113 | From a list of symmetry operations in string format and a list of atoms and 114 | their coordinates, generate a full unit cell in P1 symmetry. 115 | 116 | Parameters: 117 | ops (list of str): list 118 | asym_unit_atoms (list of str): list of elements in asymmetric unit 119 | asym_unit_coords (list of float): list of fractional coordinates of 120 | atoms in asymmetric unit 121 | 122 | Returns: 123 | new_species (list of str): species in the full unit cell 124 | new_coords (numpy array): array of fractional coordinates 125 | of atoms in full unit cell 126 | 127 | """ 128 | 129 | op_matrices = [] 130 | unit_cell_atoms = [] 131 | unit_cell_coords = [] 132 | # Need to apply symmetry operations specified in cif manually, 133 | # space group isn't good enough 134 | a = np.zeros((4, 4), dtype=np.float32) 135 | # Need to instantiate SymmOp class with some 4x4 affine matrix to 136 | # use from_xyz_string function 137 | sym_op_obj = SymmOp(a) 138 | for op in ops: 139 | op_matrices.append(sym_op_obj.from_xyz_string(op).affine_matrix) 140 | 141 | for num, atom in enumerate(asym_unit_atoms): 142 | for op in op_matrices: 143 | unit_cell_coords.append(op @ asym_unit_coords[num]) 144 | unit_cell_atoms.append(atom) 145 | 146 | unit_cell_coords = np.asarray(unit_cell_coords) 147 | unit_cell_coords = unit_cell_coords[:, :-1] 148 | 149 | return unit_cell_atoms, unit_cell_coords 150 | 151 | 152 | def remove_duplicate_atoms(pm_struct): 153 | """ 154 | Remove atoms which have identical fractional coordinates. 155 | 156 | Parameters: 157 | pm_struct (Pymatgen Structure object): structure from which 158 | to remove duplicates 159 | Returns: 160 | pm_struct (Pymatgen Structure object): structure with duplicates 161 | removed 162 | """ 163 | 164 | coords_check = [] 165 | bad_indices = [] 166 | 167 | for atom in pm_struct: 168 | if any(np.round(atom.frac_coords, 2) == 1): 169 | for x in range(3): 170 | if round(atom.frac_coords[x], 2) == 1: 171 | atom.frac_coords[x] = 0 172 | 173 | for num, atom in enumerate(pm_struct): 174 | for coord in coords_check: 175 | if all(np.round(coord, 2) == np.round(atom.frac_coords, 2)): 176 | bad_indices.append(num) 177 | else: 178 | coords_check.append(atom.frac_coords) 179 | 180 | pm_struct.remove_sites(bad_indices) 181 | 182 | return pm_struct 183 | 184 | 185 | def csd_to_pymatgen(path, atoms): 186 | """ 187 | Manually parse a CSD cif to generate a pymatgen structure which contains 188 | only a list of atoms specified (in this case, the asymmetric unit). This 189 | function returns a Pymatgen structure which is in P1 symmetry by applying 190 | the symmetry operations found in the cif. 191 | 192 | Parameters: 193 | path (str): path to the cif file 194 | atoms (list): list of the atoms in the asymmetric unit 195 | 196 | Returns: 197 | struct (Pymatgen Structure object): Structure in P1 symmetry 198 | """ 199 | with open(path) as f: 200 | cif = f.readlines() 201 | f.close() 202 | 203 | blocks = {"symmetry": None, "atom_site": None, "geom": None} 204 | 205 | for num, line in enumerate(cif): 206 | if "loop_" in line: 207 | for block in blocks.keys(): 208 | test_header = cif[num + 1].strip().split("_", maxsplit=1)[1] 209 | # Found some cases with anisotropic info with same prefix 210 | # ignore these for now... 211 | if test_header.startswith(block): 212 | if block == "atom_site" and test_header.startswith( 213 | "atom_site_aniso" 214 | ): 215 | pass 216 | else: 217 | blocks[block] = get_block(cif, block, num + 1) 218 | elif "_symmetry_space_group_name_H-M" in line: 219 | space_group_name_HM = line.strip().split()[-1] 220 | elif "_symmetry_Int_Tables_number" in line: 221 | int_tables_num = line.strip().split()[-1] 222 | elif "_space_group_name_Hall" in line: 223 | space_group_name_hall = line.strip().split()[-1] 224 | elif "cell_length_a" in line: 225 | cell_length_a = float( 226 | line.strip().replace("(", "").replace(")", "").split()[-1] 227 | ) 228 | elif "cell_length_b" in line: 229 | cell_length_b = float( 230 | line.strip().replace("(", "").replace(")", "").split()[-1] 231 | ) 232 | elif "cell_length_c" in line: 233 | cell_length_c = float( 234 | line.strip().replace("(", "").replace(")", "").split()[-1] 235 | ) 236 | elif "cell_angle_alpha" in line: 237 | cell_angle_alpha = float( 238 | line.strip().replace("(", "").replace(")", "").split()[-1] 239 | ) 240 | elif "cell_angle_beta" in line: 241 | cell_angle_beta = float( 242 | line.strip().replace("(", "").replace(")", "").split()[-1] 243 | ) 244 | elif "cell_angle_gamma" in line: 245 | cell_angle_gamma = float( 246 | line.strip().replace("(", "").replace(")", "").split()[-1] 247 | ) 248 | num_cols = 0 249 | atom_dict = {} 250 | coords = [] 251 | 252 | atom_dict = get_dict(blocks["atom_site"], atoms, "_atom_site_label") 253 | # Need to have 4th dimension (value of 1) for matrix multiplication 254 | # when applying the symmetry operations. The extra dimension 255 | # is removed later by the covert_to_p1 function 256 | for x, y, z in zip( 257 | atom_dict["_atom_site_fract_x"], 258 | atom_dict["_atom_site_fract_y"], 259 | atom_dict["_atom_site_fract_z"], 260 | ): 261 | coords.append([float(x), float(y), float(z), 1]) 262 | 263 | species = atom_dict["_atom_site_type_symbol"] 264 | sg = SpaceGroup.from_int_number(int(int_tables_num)) 265 | # Get only the operations (not headers) from the Symmetry block 266 | sym_ops = [val for val in blocks["symmetry"] if val[0] != "_"] 267 | # Get rid of any numbering "e.g., 1 x,y,z" from the symmetry operations 268 | for i in range(len(sym_ops)): 269 | sym_ops[i] = ",".join( 270 | [val.split()[-1] for val in sym_ops[i].strip().split(",")] 271 | ) 272 | 273 | species, coords = convert_to_p1(sym_ops, species, coords) 274 | 275 | lattice = Lattice.from_parameters( 276 | a=cell_length_a, 277 | b=cell_length_b, 278 | c=cell_length_c, 279 | alpha=cell_angle_alpha, 280 | beta=cell_angle_beta, 281 | gamma=cell_angle_gamma, 282 | ) 283 | struct = Structure( 284 | lattice=lattice, species=species, coords=coords, to_unit_cell=True 285 | ) 286 | # Need to remove duplicates since some atoms lie on 287 | # boundaries when converted to P1 288 | struct = remove_duplicate_atoms(struct) 289 | 290 | return struct 291 | 292 | 293 | def main(write_path, read_path=None, tmp_path=None, input_is_cif=False): 294 | """ 295 | Get the asymmetric unit of a CSD structure and convert it to a Pymatgen 296 | Structure object in P1 symmetry. Then, write the cif to a specified path. 297 | 298 | Parameters: 299 | read_path (str): Path to read the cif from (used if inp_is_cif) 300 | write_path (str): Path to write the cif 301 | tmp_path (str): Path to write the temporary cif for debugging 302 | 303 | Returns: 304 | mof_p1 (Pymatgen Structure object): MOF in P1 symmetry 305 | """ 306 | 307 | if input_is_cif: 308 | ref = read_path.rsplit("_P1.cif", 1)[0] 309 | ref = f"{ref}.cif" 310 | else: 311 | ref = write_path.split("/")[-1].rsplit("_P1.cif", 1)[0] 312 | asymmetric_unit_atoms = get_asymmetric_unit(ref, input_is_cif) 313 | if tmp_path is not None: 314 | shutil.copyfile(temp_cif_path, tmp_path) 315 | mof_p1 = csd_to_pymatgen(temp_cif_path, asymmetric_unit_atoms) 316 | os.remove(temp_cif_path) 317 | CifWriter(mof_p1).write_file(write_path) 318 | 319 | return mof_p1 320 | 321 | 322 | if __name__ == "__main__": 323 | parser = argparse.ArgumentParser( 324 | description="Retrieve crystal structure from the CSD," 325 | + "and convert it to P1 symmetry." 326 | ) 327 | parser.add_argument("refcode", metavar="r", type=str, help="CSD Refcode of the MOF") 328 | parser.add_argument( 329 | "--write_dir", 330 | type=str, 331 | default=os.getcwd(), 332 | help="Directory to write the cif." + " Defaults to current working directory.", 333 | ) 334 | parser.add_argument( 335 | "--read_dir", 336 | type=str, 337 | default=os.getcwd(), 338 | help="Directory of where the cif is located", 339 | ) 340 | parser.add_argument( 341 | "-d", 342 | action="store_true", 343 | help="If this flag is present, " + " keep the temporary CSD cif.", 344 | ) 345 | parser.add_argument( 346 | "-inp_is_cif", 347 | action="store_true", 348 | help="If this flag is present, " + " the input is a cif file.", 349 | ) 350 | 351 | args = parser.parse_args() 352 | refcode = args.refcode 353 | write_dir = args.write_dir 354 | inp_is_cif = args.inp_is_cif 355 | if inp_is_cif: 356 | refcode = refcode.split(".cif")[0] 357 | read_path = "{}/{}".format(args.read_dir, refcode) 358 | final_cif_path = "{}/{}_P1.cif".format(write_dir, refcode) 359 | if args.d: 360 | main( 361 | final_cif_path, 362 | tmp_path="{}/{}_original.cif".format(write_dir, refcode), 363 | input_is_cif=inp_is_cif, 364 | ) 365 | else: 366 | if inp_is_cif: 367 | main(final_cif_path, read_path=read_path, input_is_cif=inp_is_cif) 368 | else: 369 | main(final_cif_path, input_is_cif=inp_is_cif) 370 | 371 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution 4.0 International Public License 58 | 59 | By exercising the Licensed Rights (defined below), You accept and agree 60 | to be bound by the terms and conditions of this Creative Commons 61 | Attribution 4.0 International Public License ("Public License"). To the 62 | extent this Public License may be interpreted as a contract, You are 63 | granted the Licensed Rights in consideration of Your acceptance of 64 | these terms and conditions, and the Licensor grants You such rights in 65 | consideration of benefits the Licensor receives from making the 66 | Licensed Material available under these terms and conditions. 67 | 68 | 69 | Section 1 -- Definitions. 70 | 71 | a. Adapted Material means material subject to Copyright and Similar 72 | Rights that is derived from or based upon the Licensed Material 73 | and in which the Licensed Material is translated, altered, 74 | arranged, transformed, or otherwise modified in a manner requiring 75 | permission under the Copyright and Similar Rights held by the 76 | Licensor. For purposes of this Public License, where the Licensed 77 | Material is a musical work, performance, or sound recording, 78 | Adapted Material is always produced where the Licensed Material is 79 | synched in timed relation with a moving image. 80 | 81 | b. Adapter's License means the license You apply to Your Copyright 82 | and Similar Rights in Your contributions to Adapted Material in 83 | accordance with the terms and conditions of this Public License. 84 | 85 | c. Copyright and Similar Rights means copyright and/or similar rights 86 | closely related to copyright including, without limitation, 87 | performance, broadcast, sound recording, and Sui Generis Database 88 | Rights, without regard to how the rights are labeled or 89 | categorized. For purposes of this Public License, the rights 90 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 91 | Rights. 92 | 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. Share means to provide material to the public by any means or 116 | process that requires permission under the Licensed Rights, such 117 | as reproduction, public display, public performance, distribution, 118 | dissemination, communication, or importation, and to make material 119 | available to the public including in ways that members of the 120 | public may access the material from a place and at a time 121 | individually chosen by them. 122 | 123 | j. Sui Generis Database Rights means rights other than copyright 124 | resulting from Directive 96/9/EC of the European Parliament and of 125 | the Council of 11 March 1996 on the legal protection of databases, 126 | as amended and/or succeeded, as well as other essentially 127 | equivalent rights anywhere in the world. 128 | 129 | k. You means the individual or entity exercising the Licensed Rights 130 | under this Public License. Your has a corresponding meaning. 131 | 132 | 133 | Section 2 -- Scope. 134 | 135 | a. License grant. 136 | 137 | 1. Subject to the terms and conditions of this Public License, 138 | the Licensor hereby grants You a worldwide, royalty-free, 139 | non-sublicensable, non-exclusive, irrevocable license to 140 | exercise the Licensed Rights in the Licensed Material to: 141 | 142 | a. reproduce and Share the Licensed Material, in whole or 143 | in part; and 144 | 145 | b. produce, reproduce, and Share Adapted Material. 146 | 147 | 2. Exceptions and Limitations. For the avoidance of doubt, where 148 | Exceptions and Limitations apply to Your use, this Public 149 | License does not apply, and You do not need to comply with 150 | its terms and conditions. 151 | 152 | 3. Term. The term of this Public License is specified in Section 153 | 6(a). 154 | 155 | 4. Media and formats; technical modifications allowed. The 156 | Licensor authorizes You to exercise the Licensed Rights in 157 | all media and formats whether now known or hereafter created, 158 | and to make technical modifications necessary to do so. The 159 | Licensor waives and/or agrees not to assert any right or 160 | authority to forbid You from making technical modifications 161 | necessary to exercise the Licensed Rights, including 162 | technical modifications necessary to circumvent Effective 163 | Technological Measures. For purposes of this Public License, 164 | simply making modifications authorized by this Section 2(a) 165 | (4) never produces Adapted Material. 166 | 167 | 5. Downstream recipients. 168 | 169 | a. Offer from the Licensor -- Licensed Material. Every 170 | recipient of the Licensed Material automatically 171 | receives an offer from the Licensor to exercise the 172 | Licensed Rights under the terms and conditions of this 173 | Public License. 174 | 175 | b. No downstream restrictions. You may not offer or impose 176 | any additional or different terms or conditions on, or 177 | apply any Effective Technological Measures to, the 178 | Licensed Material if doing so restricts exercise of the 179 | Licensed Rights by any recipient of the Licensed 180 | Material. 181 | 182 | 6. No endorsement. Nothing in this Public License constitutes or 183 | may be construed as permission to assert or imply that You 184 | are, or that Your use of the Licensed Material is, connected 185 | with, or sponsored, endorsed, or granted official status by, 186 | the Licensor or others designated to receive attribution as 187 | provided in Section 3(a)(1)(A)(i). 188 | 189 | b. Other rights. 190 | 191 | 1. Moral rights, such as the right of integrity, are not 192 | licensed under this Public License, nor are publicity, 193 | privacy, and/or other similar personality rights; however, to 194 | the extent possible, the Licensor waives and/or agrees not to 195 | assert any such rights held by the Licensor to the limited 196 | extent necessary to allow You to exercise the Licensed 197 | Rights, but not otherwise. 198 | 199 | 2. Patent and trademark rights are not licensed under this 200 | Public License. 201 | 202 | 3. To the extent possible, the Licensor waives any right to 203 | collect royalties from You for the exercise of the Licensed 204 | Rights, whether directly or through a collecting society 205 | under any voluntary or waivable statutory or compulsory 206 | licensing scheme. In all other cases the Licensor expressly 207 | reserves any right to collect such royalties. 208 | 209 | 210 | Section 3 -- License Conditions. 211 | 212 | Your exercise of the Licensed Rights is expressly made subject to the 213 | following conditions. 214 | 215 | a. Attribution. 216 | 217 | 1. If You Share the Licensed Material (including in modified 218 | form), You must: 219 | 220 | a. retain the following if it is supplied by the Licensor 221 | with the Licensed Material: 222 | 223 | i. identification of the creator(s) of the Licensed 224 | Material and any others designated to receive 225 | attribution, in any reasonable manner requested by 226 | the Licensor (including by pseudonym if 227 | designated); 228 | 229 | ii. a copyright notice; 230 | 231 | iii. a notice that refers to this Public License; 232 | 233 | iv. a notice that refers to the disclaimer of 234 | warranties; 235 | 236 | v. a URI or hyperlink to the Licensed Material to the 237 | extent reasonably practicable; 238 | 239 | b. indicate if You modified the Licensed Material and 240 | retain an indication of any previous modifications; and 241 | 242 | c. indicate the Licensed Material is licensed under this 243 | Public License, and include the text of, or the URI or 244 | hyperlink to, this Public License. 245 | 246 | 2. You may satisfy the conditions in Section 3(a)(1) in any 247 | reasonable manner based on the medium, means, and context in 248 | which You Share the Licensed Material. For example, it may be 249 | reasonable to satisfy the conditions by providing a URI or 250 | hyperlink to a resource that includes the required 251 | information. 252 | 253 | 3. If requested by the Licensor, You must remove any of the 254 | information required by Section 3(a)(1)(A) to the extent 255 | reasonably practicable. 256 | 257 | 4. If You Share Adapted Material You produce, the Adapter's 258 | License You apply must not prevent recipients of the Adapted 259 | Material from complying with this Public License. 260 | 261 | 262 | Section 4 -- Sui Generis Database Rights. 263 | 264 | Where the Licensed Rights include Sui Generis Database Rights that 265 | apply to Your use of the Licensed Material: 266 | 267 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 268 | to extract, reuse, reproduce, and Share all or a substantial 269 | portion of the contents of the database; 270 | 271 | b. if You include all or a substantial portion of the database 272 | contents in a database in which You have Sui Generis Database 273 | Rights, then the database in which You have Sui Generis Database 274 | Rights (but not its individual contents) is Adapted Material; and 275 | 276 | c. You must comply with the conditions in Section 3(a) if You Share 277 | all or a substantial portion of the contents of the database. 278 | 279 | For the avoidance of doubt, this Section 4 supplements and does not 280 | replace Your obligations under this Public License where the Licensed 281 | Rights include other Copyright and Similar Rights. 282 | 283 | 284 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 285 | 286 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 287 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 288 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 289 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 290 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 291 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 292 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 293 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 294 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 295 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 296 | 297 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 298 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 299 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 300 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 301 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 302 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 303 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 304 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 305 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 306 | 307 | c. The disclaimer of warranties and limitation of liability provided 308 | above shall be interpreted in a manner that, to the extent 309 | possible, most closely approximates an absolute disclaimer and 310 | waiver of all liability. 311 | 312 | 313 | Section 6 -- Term and Termination. 314 | 315 | a. This Public License applies for the term of the Copyright and 316 | Similar Rights licensed here. However, if You fail to comply with 317 | this Public License, then Your rights under this Public License 318 | terminate automatically. 319 | 320 | b. Where Your right to use the Licensed Material has terminated under 321 | Section 6(a), it reinstates: 322 | 323 | 1. automatically as of the date the violation is cured, provided 324 | it is cured within 30 days of Your discovery of the 325 | violation; or 326 | 327 | 2. upon express reinstatement by the Licensor. 328 | 329 | For the avoidance of doubt, this Section 6(b) does not affect any 330 | right the Licensor may have to seek remedies for Your violations 331 | of this Public License. 332 | 333 | c. For the avoidance of doubt, the Licensor may also offer the 334 | Licensed Material under separate terms or conditions or stop 335 | distributing the Licensed Material at any time; however, doing so 336 | will not terminate this Public License. 337 | 338 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 339 | License. 340 | 341 | 342 | Section 7 -- Other Terms and Conditions. 343 | 344 | a. The Licensor shall not be bound by any additional or different 345 | terms or conditions communicated by You unless expressly agreed. 346 | 347 | b. Any arrangements, understandings, or agreements regarding the 348 | Licensed Material not stated herein are separate from and 349 | independent of the terms and conditions of this Public License. 350 | 351 | 352 | Section 8 -- Interpretation. 353 | 354 | a. For the avoidance of doubt, this Public License does not, and 355 | shall not be interpreted to, reduce, limit, restrict, or impose 356 | conditions on any use of the Licensed Material that could lawfully 357 | be made without permission under this Public License. 358 | 359 | b. To the extent possible, if any provision of this Public License is 360 | deemed unenforceable, it shall be automatically reformed to the 361 | minimum extent necessary to make it enforceable. If the provision 362 | cannot be reformed, it shall be severed from this Public License 363 | without affecting the enforceability of the remaining terms and 364 | conditions. 365 | 366 | c. No term or condition of this Public License will be waived and no 367 | failure to comply consented to unless expressly agreed to by the 368 | Licensor. 369 | 370 | d. Nothing in this Public License constitutes or may be interpreted 371 | as a limitation upon, or waiver of, any privileges and immunities 372 | that apply to the Licensor or You, including from the legal 373 | processes of any jurisdiction or authority. 374 | 375 | 376 | ======================================================================= 377 | 378 | Creative Commons is not a party to its public 379 | licenses. Notwithstanding, Creative Commons may elect to apply one of 380 | its public licenses to material it publishes and in those instances 381 | will be considered the “Licensor.” The text of the Creative Commons 382 | public licenses is dedicated to the public domain under the CC0 Public 383 | Domain Dedication. Except for the limited purpose of indicating that 384 | material is shared under a Creative Commons public license or as 385 | otherwise permitted by the Creative Commons policies published at 386 | creativecommons.org/policies, Creative Commons does not authorize the 387 | use of the trademark "Creative Commons" or any other trademark or logo 388 | of Creative Commons without its prior written consent including, 389 | without limitation, in connection with any unauthorized modifications 390 | to any of its public licenses or any other arrangements, 391 | understandings, or agreements concerning use of licensed material. For 392 | the avoidance of doubt, this paragraph does not form part of the 393 | public licenses. 394 | 395 | Creative Commons may be contacted at creativecommons.org. 396 | 397 | --------------------------------------------------------------------------------