### Install Benchmark Dependencies Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Installs necessary packages for LaTeX rendering and SELFIES benchmarking, including dvipng, texlive-latex-extra, texlive-fonts-recommended, cm-super, pandas, rdkit, and matplotlib. ```bash !sudo apt-get -qq install dvipng texlive-latex-extra texlive-fonts-recommended cm-super ``` ```bash !pip install -qq selfies==2.1.1 pandas rdkit matplotlib SciencePlots ``` -------------------------------- ### Install SELFIES Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/index.md Install the SELFIES library using pip. This is the primary method for adding SELFIES to your project. ```bash pip install selfies ``` -------------------------------- ### Derivation Example Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/derivation.md Illustrates the step-by-step derivation of a SELFIES string from an initial state. ```text X_0 \to \texttt{F}X_1 \to \texttt{FC}X_3 \to \texttt{FC=C}X_2 \to \texttt{FC=C=N} ``` -------------------------------- ### Build Documentation with Sphinx Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/README.md Run this command in the project directory after installing the required Sphinx extensions to build the documentation. ```bash python -m sphinx source ``` -------------------------------- ### SELFIES to SMILES Examples Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/derivation.md Provides examples of SELFIES strings and their corresponding SMILES representations. ```text [C][=C][C][#C][13Cexpl] | C=CC#C[13C] ``` ```text [C][F][C][C][C][C] | CF ``` ```text [C][O][=C][#O][C][F] | COC=O ``` -------------------------------- ### Run SELFIES Test Suite Source: https://github.com/aspuru-guzik-group/selfies/blob/master/README.md Install tox and run the SELFIES test suite. You can specify the number of trials and dataset samples for testing. ```bash tox -- --trials=10000 --dataset_samples=10000 ``` -------------------------------- ### Show selfies Package Version Source: https://github.com/aspuru-guzik-group/selfies/blob/master/README.md Run this pip command to check the currently installed version of the selfies package. ```bash pip show selfies ``` -------------------------------- ### Get Current Semantic Constraints Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Retrieves and displays the currently active semantic constraints after a custom update. ```python sf.get_semantic_constraints() ``` -------------------------------- ### Time Individual Roundtrip Translation and Plot Sizes vs. Time Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb This snippet times the roundtrip translation of a subset of compounds and plots the resulting sizes against the translation times. It requires prior setup of the subset and random seed. ```python random.seed(100) subset = random.sample(nci_open_compound, k=1000) sizes, times = time_individual_roundtrip_translation(subset) plot_translation_sizes_vs_time(sizes, times) ``` -------------------------------- ### Get Default Semantic Constraints Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Retrieves the default semantic constraints used by the selfies library, which map atoms to their bonding capacities. ```python sf.get_preset_constraints("default") ``` -------------------------------- ### Basic Ring Bond Derivation Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/derivation.md Represents a simple carbon ring using the [Ring1] symbol. This example demonstrates the creation of a 6-membered carbon ring. ```SEFLIES [C][=C][C][=C][C][=C][Ring1][Branch1_2] ``` -------------------------------- ### Get and Print Standard SELFIS Alphabet Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Retrieves the standard robust alphabet used by SELFIS and prints it, along with its length. This is typically done to inspect the available symbols. ```python alphabet = list(sf.get_semantic_robust_alphabet()) print(alphabet) len(alphabet) ``` -------------------------------- ### Time Random SELFIS Decoding and Get Atom Sizes Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb This function generates random SELFIS strings, times the decoding process for a batch, and calculates the number of atoms for each decoded molecule. It's used to measure decoding performance and analyze molecule complexity. ```python def time_random_selfies(n, length): rand_selfies = ["".join(random.choices(alphabet, k=length)) for _ in range(n)] def batch_decode(): for s in rand_selfies: sf.decoder(s) n_trials = 20 decode_time = timeit.timeit(stmt=batch_decode, number=n_trials) / n_trials sizes = [Chem.MolFromSmiles(sf.decoder(s)).GetNumAtoms() for s in rand_selfies] return decode_time, sizes ``` -------------------------------- ### Display CPU Information Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb This command displays detailed information about the CPU(s) available in the environment. It is useful for understanding the hardware resources being used for the benchmark. ```bash !cat /proc/cpuinfo ``` -------------------------------- ### Import selfies library Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Import the selfies library to begin using its functionalities. ```python import selfies as sf ``` -------------------------------- ### Import Libraries for Benchmarking Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Imports essential Python libraries for plotting, numerical operations, data manipulation, random number generation, SELFIES encoding/decoding, timing, and RDKit molecule handling. ```python import matplotlib.pyplot as plt import numpy as np import pandas as pd import random import selfies as sf import timeit from rdkit import Chem plt.style.use("science") ``` -------------------------------- ### Execute and Print SELFIES Translation Benchmark Results Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Runs the roundtrip translation benchmark using the loaded NCI open compound dataset and prints the average encode time, decode time, and total roundtrip time. ```python encode_time, decode_time = time_roundtrip_translation(nci_open_compound) print("Encode time:", encode_time) print("Decode time:", decode_time) print("Total time: ", encode_time + decode_time) ``` -------------------------------- ### Upgrade selfies Package Source: https://github.com/aspuru-guzik-group/selfies/blob/master/README.md Use this pip command to upgrade to the latest release of the selfies package. Review the CHANGELOG before upgrading. ```bash pip install selfies --upgrade ``` -------------------------------- ### Customize SELFIES Semantic Constraints (Hypervalence) Source: https://github.com/aspuru-guzik-group/selfies/blob/master/README.md Illustrates how to relax semantic constraints to allow for hypervalent atoms, demonstrating the effect on decoding a SELFIES string for orthoperiodic acid. ```python import selfies as sf hypervalent_sf = sf.encoder('O=I(O)(O)(O)(O)O', strict=False) # orthoperiodic acid standard_derived_smi = sf.decoder(hypervalent_sf) # OI (the default constraints for I allows for only 1 bond) sf.set_semantic_constraints("hypervalent") relaxed_derived_smi = sf.decoder(hypervalent_sf) # O=I(O)(O)(O)(O)O (the hypervalent constraints for I allows for 7 bonds) ``` -------------------------------- ### Create Vocabulary Mappings Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Generates mappings between SELFIES symbols and their corresponding integer indices (stoi) and vice versa (itos). This is essential for numerical encoding and decoding. ```python vocab_stoi = {symbol: idx for idx, symbol in enumerate(alphabet)} vocab_itos = {idx: symbol for idx, symbol in vocab_stoi.items()} vocab_stoi ``` -------------------------------- ### Integer and One-Hot Encoding of SELFIES Source: https://github.com/aspuru-guzik-group/selfies/blob/master/README.md Demonstrates building an alphabet from a dataset, padding SELFIES strings using a special '[nop]' symbol, and converting to integer and one-hot encodings. ```python import selfies as sf dataset = ["[C][O][C]", "[F][C][F]", "[O][=O]", "[C][C][O][C][C]"] alphabet = sf.get_alphabet_from_selfies(dataset) alphabet.add("[nop]") # [nop] is a special padding symbol alphabet = list(sorted(alphabet)) # ['[=O]', '[C]', '[F]', '[O]', '[nop]'] pad_to_len = max(sf.len_selfies(s) for s in dataset) # 5 symbol_to_idx = {s: i for i, s in enumerate(alphabet)} dimethyl_ether = dataset[0] # [C][O][C] label, one_hot = sf.selfies_to_encoding( selfies=dimethyl_ether, vocab_stoi=symbol_to_idx, pad_to_len=pad_to_len, enc_type="both" ) # label = [1, 3, 1, 4, 4] # one_hot = [[0, 1, 0, 0, 0], [0, 0, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 0, 1]] ``` -------------------------------- ### Generate Random Valid Molecules with SELFIES Source: https://github.com/aspuru-guzik-group/selfies/blob/master/README.md Shows how to generate random, valid SELFIES strings and decode them into SMILES, useful for machine learning or initial filtering. ```python import selfies as sf import random alphabet=sf.get_semantic_robust_alphabet() # Gets the alphabet of robust symbols rnd_selfies=''.join(random.sample(list(alphabet), 9)) rnd_smiles=sf.decoder(rnd_selfies) print(rnd_smiles) ``` -------------------------------- ### SMILES Strings for 1st Mutation Source: https://github.com/aspuru-guzik-group/selfies/blob/master/original_code_from_paper/bitflips_in_paper_Fig3.txt Lists the SMILES strings corresponding to the first mutation set, as presented in the source. ```smiles CNC(C)CC1=CC=C2C(C1)OCO2 CNC(C)CC=CC=CC(=C=NN)OCO CNC(C)CC1=CN=C2C(=C1)OCO2 ``` -------------------------------- ### Decode SELFIES with Default Constraints Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Decodes a SELFIES string using the current semantic constraints, demonstrating how atoms adhere to their specified bonding capacities. ```python sf.decoder("[Li][=C][C][S][=C][C][#S]") ``` -------------------------------- ### SMILES Strings for 2nd Mutation Source: https://github.com/aspuru-guzik-group/selfies/blob/master/original_code_from_paper/bitflips_in_paper_Fig3.txt Lists the SMILES strings corresponding to the second mutation set, as presented in the source. ```smiles CNC(C)CC=CC=C1C(=NOCO1) CNC(C)C=NCC1=C2C(=C1)OCO2 C1NC(C)CC=CC=C1O ``` -------------------------------- ### Display Label Encoding Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Shows the resulting label (integer) encoding for a SELFIES string after conversion. ```python label ``` -------------------------------- ### Multiple Explicit Ring Bonds with Multiplicity Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/derivation.md Shows the derivation of a molecule with multiple explicit ring bonds, including handling of bond multiplicities when existing bonds are involved. ```SEFLIES [C][C][C][C][Expl=Ring1][Ring2][Expl#Ring1][Ring2] ``` -------------------------------- ### Compare SMILES using RDKit Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Compares two SMILES strings for molecular equivalence using RDKit's Chem.CanonSmiles, as direct string comparison can be misleading. ```python from rdkit import Chem Chem.CanonSmiles(original_smiles) == Chem.CanonSmiles(decoded_smiles) ``` -------------------------------- ### Explain SELFIES to SMILES Translation Attribution Source: https://github.com/aspuru-guzik-group/selfies/blob/master/README.md Shows how to obtain attribution information that traces which SELFIES tokens are responsible for specific SMILES tokens during decoding. ```python selfies = "[C][N][C][Branch1][C][P][C][C][Ring1][=Branch1]" smiles, attr = sf.decoder( selfies, attribute=True) print('SELFIES', selfies) print('SMILES', smiles) print('Attribution:') for smiles_token in attr: print(smiles_token) # output SELFIES [C][N][C][Branch1][C][P][C][C][Ring1][=Branch1] SMILES C1NC(P)CC1 Attribution: AttributionMap(index=0, token='C', attribution=[Attribution(index=0, token='[C]')]) AttributionMap(index=2, token='N', attribution=[Attribution(index=1, token='[N]')]) AttributionMap(index=3, token='C', attribution=[Attribution(index=2, token='[C]')]) AttributionMap(index=5, token='P', attribution=[Attribution(index=3, token='[Branch1]'), Attribution(index=5, token='[P]')]) AttributionMap(index=7, token='C', attribution=[Attribution(index=6, token='[C]')]) AttributionMap(index=8, token='C', attribution=[Attribution(index=7, token='[C]')]) ``` -------------------------------- ### Selfies and SMILES for 1st Mutation Source: https://github.com/aspuru-guzik-group/selfies/blob/master/original_code_from_paper/bitflips_in_paper_Fig3.txt Compares Selfies and SMILES notations for the first set of molecular mutations. The 'yes' indicates a successful representation. ```text [C][N][C][Branch1_3][epsilon][C][C][C][=C][C][=C][C][Branch1_2][=O][=C][Ring1][#N][O][C][O][Ring1][#N] - CNC(C)CC1=CC=C2C(C1)OCO2 : yes [C][N][C][Branch1_3][epsilon][C][C][C][=C][C][=C][C][Branch1_3][=O][=C][=N][#N][O][C][O][Ring1][#N] - CNC(C)CC=CC=CC(=C=NN)OCO : yes [C][N][C][Branch1_3][epsilon][C][C][C][=C][N][=C][C][Branch1_3][=O][=C][Ring1][#N][O][C][O][Ring1][#N] - CNC(C)CC1=CN=C2C(=C1)OCO2 : yes ``` -------------------------------- ### Ring Bond with Explicit Triple Bond Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/derivation.md Shows the use of 'Expl=Ring1' to create a triple bond within a ring structure, followed by a carbon atom. ```SEFLIES [C][C][Expl=Ring1][C] ``` -------------------------------- ### Convert SELFIES to Label and One-Hot Encoding Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Converts a single SELFIES string to its label (integer) and one-hot encoded representations using `sf.selfies_to_encoding`. Padding is applied up to `max_len`. ```python dimethyl_ether = selfies_dataset[0] label, one_hot = sf.selfies_to_encoding(dimethyl_ether, vocab_stoi, pad_to_len=max_len) ``` -------------------------------- ### Tokenize SELFIES String Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Splits a SELFIES string into its individual symbols using `sf.split_selfies`. This is useful for processing SELFIES at the symbol level. ```python list(sf.split_selfies("[C][O][C]")) ``` -------------------------------- ### Translate SELFIES to SMILES and back Source: https://github.com/aspuru-guzik-group/selfies/blob/master/README.md Demonstrates the core translation functionality between SELFIES and SMILES representations, including error handling for invalid inputs. ```python import selfies as sf benzene = "c1ccccc1" # SMILES -> SELFIES -> SMILES translation try: benzene_sf = sf.encoder(benzene) # [C][=C][C][=C][C][=C][Ring1][=Branch1] benzene_smi = sf.decoder(benzene_sf) # C1=CC=CC=C1 except sf.EncoderError: pass # sf.encoder error! except sf.DecoderError: pass # sf.decoder error! len_benzene = sf.len_selfies(benzene_sf) # 8 symbols_benzene = list(sf.split_selfies(benzene_sf)) # ['[C]', '[=C]', '[C]', '[=C]', '[C]', '[=C]', '[Ring1]', '[=Branch1]'] ``` -------------------------------- ### Ring Bond with Explicit Bond Type Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/derivation.md Illustrates using an explicit bond type with a ring symbol, specifically an 'Expl=Ring1' for a double bond in a carbon ring. ```SEFLIES [C][C][=C][C][=C][C][Expl=Ring1][Branch1_2] ``` -------------------------------- ### Complex Ring Derivation with Branches Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/derivation.md Illustrates a complex ring formation involving multiple ring symbols and branches, resulting in a specific branched cyclic structure. ```SEFLIES [C][C][C][C][Branch1_1][C][C][Ring1][Ring2][C][C] ``` -------------------------------- ### SMILES Strings for 3rd Mutation Source: https://github.com/aspuru-guzik-group/selfies/blob/master/original_code_from_paper/bitflips_in_paper_Fig3.txt Lists the SMILES strings corresponding to the third mutation set, as presented in the source. ```smiles CNC(CCC1=CC=C2(O))C1=NCO2 CN=C(C)C#N CN=NC1CC=NC(=C1)OCO ``` -------------------------------- ### Selfies and SMILES for 2nd Mutation Source: https://github.com/aspuru-guzik-group/selfies/blob/master/original_code_from_paper/bitflips_in_paper_Fig3.txt Compares Selfies and SMILES notations for the second set of molecular mutations. The 'yes' indicates a successful representation. ```text [C][N][C][Branch1_3][epsilon][C][C][C][=C][C][=C][C][Branch1_3][Branch1_2][Branch1_3][Ring1][#N][O][C][O][Ring1][#N] - CNC(C)CC=CC=C1C(=NOCO1) : yes [C][N][C][Branch1_3][epsilon][C][C][=N][=C][C][=C][C][Branch1_3][=O][=C][Ring1][F][O][C][O][Ring1][#N] - CNC(C)C=NCC1=C2C(=C1)OCO2 : yes [C][N][C][Branch1_3][epsilon][C][C][C][=C][C][=C][Ring1][Branch1_3][=O][=C][Ring1][#N][O][C][O][Ring1][#N] - C1NC(C)CC=CC=C1O : yes ``` -------------------------------- ### Time Individual SELFIES Translation and Plot Results Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Measures the time for individual SMILES-to-SELFIES-to-SMILES roundtrips and plots the translation time against the number of atoms in the molecule. Requires RDKit for atom count. ```python def time_individual_roundtrip_translation(smiles): sizes = [] times = [] for s in smiles: n_trials = 3 time = timeit.timeit(stmt=lambda: sf.decoder(sf.encoder(s)), number=n_trials) / n_trials mol = Chem.MolFromSmiles(s) if mol is not None: sizes.append(mol.GetNumAtoms()) times.append(time) return sizes, times def plot_translation_sizes_vs_time(sizes, times): times = np.array(times) * 1000 plt.scatter(sizes, times, s=2) plt.xlabel("Number of Atoms") plt.ylabel("Roundtrip Time (ms)") plt.xlim((0, 60)) plt.tight_layout() plt.savefig("nci_open_compound_translation.pdf") plt.show() ``` -------------------------------- ### Revert to Default Constraints Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Resets the semantic constraints back to the library's default settings by calling sf.set_semantic_constraints without arguments. ```python sf.set_semantic_constraints() ``` -------------------------------- ### Display One-Hot Encoding Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Shows the resulting one-hot encoded representation for a SELFIES string after conversion. ```python one_hot ``` -------------------------------- ### Time Random SELFIS Decoding with Standard Alphabet Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Measures the decoding time for random SELFIS strings generated using the standard alphabet across different symbol lengths. The results are stored and printed for analysis. ```python lengths = [10, 100, 250] sizes_log_stnd = dict() for l in lengths: decode_time, sizes_log_stnd[l] = time_random_selfies(n=1000, length=l) print(f"Decode time (length={l:4}):", decode_time) ``` -------------------------------- ### Reset Semantic Constraints and Random Seed Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Resets the semantic constraints for SELFIS to their default values and sets the random seed for reproducibility. ```python sf.set_semantic_constraints() # reset to defaults random.seed(100) ``` -------------------------------- ### Convert One-Hot Encoding back to SELFIES Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Converts a one-hot encoded representation back into a SELFIES string using `sf.encoding_to_selfies`. The `[nop]` padding symbols are included in the output. ```python dimethyl_ether = sf.encoding_to_selfies(one_hot, vocab_itos, enc_type="one_hot") dimethyl_ether ``` -------------------------------- ### Set Custom SELFIES Semantic Constraints Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Configures SELFIES with custom semantic constraints, specifically setting the maximum valency for Phosphorus (P-1) to 6. This ensures generated SELFIES adhere to these specific chemical rules. ```python constraints = sf.get_preset_constraints(name="hypervalent") constraints["P-1"] = 6 sf.set_semantic_constraints(constraints) ``` -------------------------------- ### Selfies and SMILES for 3rd Mutation Source: https://github.com/aspuru-guzik-group/selfies/blob/master/original_code_from_paper/bitflips_in_paper_Fig3.txt Compares Selfies and SMILES notations for the third set of molecular mutations. The 'yes' indicates a successful representation. ```text [C][N][C][Branch1_3][=C][C][C][C][=C][C][=C][Branch1_3][Branch1_3][=O][=C][Ring1][#N][=N][C][O][Ring1][#N] - CNC(CCC1=CC=C2(O))C1=NCO2 : yes [C][N][#C][Branch1_3][epsilon][C][C][#N][=C][C][=C][C][Branch1_3][=O][=C][Ring1][#N][O][C][O][Ring1][#N] - CN=C(C)C#N : yes [C][N][=N][Branch1_3][epsilon][C][C][C][=N][Branch1_3][=C][C][Branch1_3][=O][=C][Ring1][#N][O][C][O][Ring1][#N] - CN=NC1CC=NC(=C1)OCO : yes ``` -------------------------------- ### Encode and Decode SMILES to SELFIES Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Translate a SMILES string to SELFIES using sf.encoder and back to SMILES using sf.decoder. Handles potential EncoderError and DecoderError. ```python original_smiles = "O=Cc1ccccc1" # benzaldehyde try: encoded_selfies = sf.encoder(original_smiles) # SMILES -> SELFIES decoded_smiles = sf.decoder(encoded_selfies) # SELFIES -> SMILES except sf.EncoderError as err: pass # sf.encoder error... except sf.DecoderError as err: pass # sf.decoder error... ``` -------------------------------- ### Load and Preprocess SMILES Data Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Reads SMILES strings from a CSV file, converts them to a list, and corrects escaped backslashes that may have been introduced during CSV writing. Displays the total number of SMILES strings loaded. ```python nci_open_compound = pd.read_csv("PubChem_compound_text_DTP_NCI.csv") nci_open_compound = nci_open_compound["isosmiles"].tolist() # csv file saves backslashes as \\, so we replace nci_open_compound = [s.replace("\\\\", "\\") for s in nci_open_compound] len(nci_open_compound) ``` -------------------------------- ### Set Custom Semantic Constraints Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Modifies the semantic constraints for specific atoms (e.g., Li and S) and applies them using sf.set_semantic_constraints. ```python new_constraints = sf.get_preset_constraints("default") new_constraints['Li'] = 1 new_constraints['S'] = 2 sf.set_semantic_constraints(new_constraints) ``` -------------------------------- ### Encode SMILES to SELFIES Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Converts a list of SMILES strings to their SELFIES representations using `sf.encoder`. This is the first step in using SELFIES for molecular data. ```python smiles_dataset = ["COC", "FCF", "O=O", "O=Cc1ccccc1"] selfies_dataset = list(map(sf.encoder, smiles_dataset)) selfies_dataset ``` -------------------------------- ### Extract SELFIES Alphabet and Add Padding Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Extracts unique SELFIES symbols from a dataset using `sf.get_alphabet_from_selfies` and adds a special padding symbol `[nop]`. The resulting alphabet is then sorted. ```python alphabet = sf.get_alphabet_from_selfies(selfies_dataset) alphabet.add("[nop]") alphabet = list(sorted(alphabet)) alphabet ``` -------------------------------- ### Plot SMILES Size Distributions for Standard and Filtered Alphabets Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Generates a figure with two subplots, each displaying the distribution of molecule sizes. The left subplot shows the distribution for the standard alphabet, and the right subplot shows the distribution for the filtered alphabet. The plots are configured for shared axes and saved to a PDF file. ```python fig, axes = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(6.7, 2.8)) plot_smiles_size_distribution(axes[0], sizes_log_stnd) plot_smiles_size_distribution(axes[1], sizes_log_filt) axes[1].yaxis.set_tick_params(labelbottom=True) plt.tight_layout() plt.savefig("n=1000_length=50_size_hist.pdf") plt.show() ``` -------------------------------- ### Decode SELFIES with Padding to SMILES Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Decodes a SELFIES string, including padding symbols like `[nop]`, back into its original SMILES representation using `sf.decoder`. Padding symbols are ignored during decoding. ```python sf.decoder(dimethyl_ether) # sf.decoder ignores [nop] ``` -------------------------------- ### Large Carbon Ring Derivation Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/derivation.md Demonstrates the creation of a large, 22-membered carbon ring using repeated carbon symbols and ring connection symbols. ```SEFLIES [C][C][C][C][C][C][C][C][C][C][C] [C][C][C][C][C][C][C][C][C][C][C] [Ring2][Ring1][Branch1_2] ``` -------------------------------- ### Calculate Maximum SELFIES Symbol Length Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Computes the maximum symbol length of SELFIES strings in a dataset using `sf.len_selfies`. This is useful for determining padding lengths for numerical encoding. ```python max_len = max(sf.len_selfies(s) for s in selfies_dataset) max_len ``` -------------------------------- ### Display Decoded SMILES Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Shows the resulting SMILES string after decoding a SELFIES string. ```python decoded_smiles ``` -------------------------------- ### Time Batch SELFIES Roundtrip Translation Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Measures the time taken to encode a list of SMILES strings to SELFIES and decode them back. It performs multiple trials for accuracy and returns the average encode and decode times. ```python def time_roundtrip_translation(smiles): selfies = [sf.encoder(s) for s in smiles] def batch_encode(): for s in smiles: sf.encoder(s) def batch_decode(): for s in selfies: sf.decoder(s) n_trials = 3 encode_time = timeit.timeit(stmt=batch_encode, number=n_trials) / n_trials decode_time = timeit.timeit(stmt=batch_decode, number=n_trials) / n_trials return encode_time, decode_time ``` -------------------------------- ### Configure Matplotlib for SVG Output Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Sets the default figure format for Matplotlib plots to SVG, which is a scalable vector graphics format suitable for high-quality visualizations. ```python %config InlineBackend.figure_formats = ['svg'] ``` -------------------------------- ### Display Encoded SELFIES Source: https://github.com/aspuru-guzik-group/selfies/blob/master/docs/source/tutorial.ipynb Shows the resulting SELFIES string after encoding a SMILES string. ```python encoded_selfies ``` -------------------------------- ### Plot SMILES Size Distribution Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Plots the distribution of molecule sizes (number of atoms) for different SELFIS symbol lengths. It uses a logarithmic scale for the y-axis and allows for overlaying distributions from different symbol lengths. ```python def plot_smiles_size_distribution(ax, sizes_log): bins = list(range(0, 251, 10)) for l, sizes in sizes_log.items(): ax.hist(sizes, bins=bins, density=True, label=str(l), alpha=0.5, zorder=(250 - l)) ax.set_xlabel("Number of Atoms") ax.set_ylabel("Normalized Counts") ax.set_yscale("log") ax.legend(title="Symbol Length") ``` -------------------------------- ### Time Random SELFIS Decoding with Filtered Alphabet Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Measures the decoding time for random SELFIS strings generated using a filtered alphabet across different symbol lengths. The results are stored and printed, allowing comparison with the standard alphabet. ```python lengths = [10, 100, 250] sizes_log_filt = dict() for l in lengths: decode_time, sizes_log_filt[l] = time_random_selfies(n=1000, length=l) print(f"Decode time (length={l:4}):", decode_time) ``` -------------------------------- ### Filter and Extend SELFIS Alphabet Source: https://github.com/aspuru-guzik-group/selfies/blob/master/examples/benchmark_v2_1_1.ipynb Filters the standard SELFIS alphabet to exclude certain symbols (e.g., those with '=', '#', or specific elements) and then extends it with specific branch and ring symbols. This creates a custom alphabet for benchmarking. ```python def f(symbol): return all((s not in symbol) for s in ("=", "#", "[F]", "[Cl]", "[Br]", "[I]", "[H]", "[O-1]", "Branch", "Ring")) alphabet = list(filter(f, sf.get_semantic_robust_alphabet())) alphabet.extend(["[Branch1]", "[Ring1]"]) print(alphabet) len(alphabet) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.