Selfies_converter added
Browse files- selfies_converter.py +46 -0
selfies_converter.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
import selfies as sf
|
| 4 |
+
from tqdm import tqdm
|
| 5 |
+
|
| 6 |
+
def convert_file(input_file, verbose=False):
|
| 7 |
+
base_name = os.path.splitext(input_file)[0]
|
| 8 |
+
selfies_file = f"{base_name}.selfies"
|
| 9 |
+
alphabet_file = f"{base_name}.alph"
|
| 10 |
+
|
| 11 |
+
alphabet = set()
|
| 12 |
+
|
| 13 |
+
with open(input_file, 'r') as fin, open(selfies_file, 'w') as fout:
|
| 14 |
+
lines = fin.readlines()
|
| 15 |
+
if verbose:
|
| 16 |
+
lines = tqdm(lines, desc=f"Converting {input_file}")
|
| 17 |
+
|
| 18 |
+
for line in lines:
|
| 19 |
+
smiles = line.strip()
|
| 20 |
+
try:
|
| 21 |
+
selfies = sf.encoder(smiles, strict=False)
|
| 22 |
+
fout.write(f"{selfies}\n")
|
| 23 |
+
alphabet.update(sf.split_selfies(selfies))
|
| 24 |
+
except sf.EncoderError as e:
|
| 25 |
+
if verbose:
|
| 26 |
+
print(f"Failed to encode: {smiles}, {e}")
|
| 27 |
+
continue
|
| 28 |
+
|
| 29 |
+
with open(alphabet_file, 'w') as f:
|
| 30 |
+
for symbol in sorted(alphabet):
|
| 31 |
+
f.write(f"{symbol}\n")
|
| 32 |
+
|
| 33 |
+
if verbose:
|
| 34 |
+
print(f"Conversion complete. SELFIES saved to {selfies_file}")
|
| 35 |
+
print(f"Alphabet saved to {alphabet_file}")
|
| 36 |
+
|
| 37 |
+
def main():
|
| 38 |
+
parser = argparse.ArgumentParser(description="SELFIES Converter")
|
| 39 |
+
parser.add_argument("input_file", help="Input SMILES file (.smi)")
|
| 40 |
+
parser.add_argument("-v", "--verbose", action="store_true", help="Increase output verbosity")
|
| 41 |
+
args = parser.parse_args()
|
| 42 |
+
|
| 43 |
+
convert_file(args.input_file, args.verbose)
|
| 44 |
+
|
| 45 |
+
if __name__ == "__main__":
|
| 46 |
+
main()
|