Package: selfies
SELFIESSelf-Referencing Embedded Strings (SELFIES): A 100% robust molecular string representationMario Krenn, Florian Haese, AkshatKumar Nigam, Pascal Friederich, Alan Aspuru-GuzikMachine Learning: Science and Technology1, 045024 (2020),extensive blog post January 2021.Talk on youtube about SELFIES.A community paper with 31 authors on SELFIES and the future of molecular string representations.Blog explaining SELFIES in Japanese languageMajor contributors of v1.0.n:Alston LoandSeyone ChithranandaMain developer of v2.0.0:Alston LoChemistry Advisor:Robert PolliceA main objective is to use SELFIES as direct input into machine learning models,
in particular in generative models, for the generation of molecular graphs
which are syntactically and semantically valid.InstallationUse pip to installselfies.pipinstallselfiesTo check if the correct version ofselfiesis installed, use
the following pip command.pipshowselfiesTo upgrade to the latest release ofselfiesif you are using an
older version, use the following pip command. Please see theCHANGELOGto review the changes between versions ofselfies, before upgrading:pipinstallselfies--upgradeUsageOverviewPlease refer to thedocumentation,
which contains a thorough tutorial  for getting started withselfiesand detailed descriptions of the functions
thatselfiesprovides. We summarize some key functions below.FunctionDescriptionselfies.encoderTranslates a SMILES string into its corresponding SELFIES string.selfies.decoderTranslates a SELFIES string into its corresponding SMILES string.selfies.set_semantic_constraintsConfigures the semantic constraints thatselfiesoperates on.selfies.len_selfiesReturns the number of symbols in a SELFIES string.selfies.split_selfiesTokenizes a SELFIES string into its individual symbols.selfies.get_alphabet_from_selfiesConstructs an alphabet from an iterable of SELFIES strings.selfies.selfies_to_encodingConverts a SELFIES string into its label and/or one-hot encoding.selfies.encoding_to_selfiesConverts a label or one-hot encoding into a SELFIES string.ExamplesTranslation between SELFIES and SMILES representations:importselfiesassfbenzene="c1ccccc1"# SMILES -> SELFIES -> SMILES translationtry:benzene_sf=sf.encoder(benzene)# [C][=C][C][=C][C][=C][Ring1][=Branch1]benzene_smi=sf.decoder(benzene_sf)# C1=CC=CC=C1exceptsf.EncoderError:pass# sf.encoder error!exceptsf.DecoderError:pass# sf.decoder error!len_benzene=sf.len_selfies(benzene_sf)# 8symbols_benzene=list(sf.split_selfies(benzene_sf))# ['[C]', '[=C]', '[C]', '[=C]', '[C]', '[=C]', '[Ring1]', '[=Branch1]']Very simple creation of random valid molecules:A key property of SELFIES is the possibility to create valid random molecules in a very simple way -- inspired by a tweet byRajarshi Guha:importselfiesassfimportrandomalphabet=sf.get_semantic_robust_alphabet()# Gets the alphabet of robust symbolsrnd_selfies=''.join(random.sample(list(alphabet),9))rnd_smiles=sf.decoder(rnd_selfies)print(rnd_smiles)These simple lines gives crazy molecules, but all are valid. Can be used as a start for more advanced filtering techniques or for machine learning models.Integer and one-hot encoding SELFIES:In this example, we first build an alphabet from a dataset of SELFIES strings,
and then convert a SELFIES string into its padded encoding. Note that we use the[nop](no operation)
symbol to pad our SELFIES, which is a special SELFIES symbol that is always
ignored and skipped over byselfies.decoder, making it a useful
padding character.importselfiesassfdataset=["[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 symbolalphabet=list(sorted(alphabet))# ['[=O]', '[C]', '[F]', '[O]', '[nop]']pad_to_len=max(sf.len_selfies(s)forsindataset)# 5symbol_to_idx={s:ifori,sinenumerate(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]]Customizing SELFIES:In this example, we relax the semantic constraints ofselfiesto allow
for hypervalences (caution: hypervalence rules are much less understood
than octet rules. Some molecules containing hypervalences are important,
but generally, it is not known which molecules are stable and reasonable).importselfiesassfhypervalent_sf=sf.encoder('O=I(O)(O)(O)(O)O',strict=False)# orthoperiodic acidstandard_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)Explaining Translation:You can get an "attribution" list that traces the connection between input and output tokens. For example let's see which tokens in the SELFIES string[C][N][C][Branch1][C][P][C][C][Ring1][=Branch1]are responsible for the output SMILES tokens.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:')forsmiles_tokeninattr:print(smiles_token)# outputSELFIES[C][N][C][Branch1][C][P][C][C][Ring1][=Branch1]SMILESC1NC(P)CC1Attribution: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]')])attris a list ofAttributionMaps containing the output token, its index, and input tokens that led to it. For example, thePappearing in the output SMILES at that location is a result of both the[Branch1]token at position 3 and the[P]token at index 5. This works for both encoding and decoding. For finer control of tracking the translation (like tracking rings), you can access attributions in the underlying molecular graph withget_attribution.More Usages and ExamplesMore examples can be found in theexamples/directory, including avariational autoencoder that runs on the SELFIESlanguage.ThisICLR2020 paperused SELFIES in a
genetic algorithm to achieve state-of-the-art performance for inverse design,
with thecode here.SELFIES allows forhighly efficient exploration and interpolation of the chemical space, with adeterministic algorithms, see code.We use SELFIES forDeep Molecular dreaming, a new generative model inspired by interpretable neural networks in computational vision. See thecode of PASITHEA here.Kohulan Rajan, Achim Zielesny, Christoph Steinbeck show in two papers that SELFIES outperforms other representations inimg2stringandstring2stringtranslation tasks, see the codes ofDECIMERandSTOUT.Nathan Frey, Vijay Gadepally, and Bharath Ramsundar used SELFIES with normalizing flows to develop theFastFlowsframework for deep chemical generative modeling.An improvement to the old genetic algorithm, the authors have also releasedJANUS, which allows for more efficient optimization in the chemical space. JANUS makes use ofSTONED-SELFIESand a neural network for efficient sampling.Testsselfiesusespytestwithtoxas its testing framework.
All tests can be found in  thetests/directory. To run the test suite for
SELFIES, installtoxand run:tox----trials=10000--dataset_samples=10000By default,selfiesis tested against a random subset
(of sizedataset_samples=10000) on various datasets:130K molecules fromQM9250K molecules fromZINC50K molecules from a dataset ofnon-fullerene acceptors for organic solar cells160K+ molecules from variousMoleculeNetdatasets36M+ molecules from theeMolecules Database.
Due to its large size, this dataset is not included on the repository. To run tests
on it, please download the dataset into thetests/test_setsdirectory
and run thetests/run_on_large_dataset.pyscript.Version HistorySeeCHANGELOG.CreditsWe thank Jacques Boitreaud, Andrew Brereton, Nessa Carson (supersciencegrl), Matthew Carbone (x94carbone),  Vladimir Chupakhin (chupvl), Nathan Frey (ncfrey), Theophile Gaudin,
HelloJocelynLu, Hyunmin Kim (hmkim), Minjie Li, Vincent Mallet, Alexander Minidis (DocMinus), Kohulan Rajan (Kohulan),
Kevin Ryan (LeanAndMean), Benjamin Sanchez-Lengeling, Andrew White, Zhenpeng Yao and Adamo Young for their suggestions and bug reports,
and Robert Pollice for chemistry advices.LicenseApache License 2.0