Commit f1ded1be authored by nd-02110114's avatar nd-02110114
Browse files

🚧 wip commit

parent ca579061
Loading
Loading
Loading
Loading
+51 −57
Original line number Diff line number Diff line
import numpy as np
from typing import List

from deepchem.utils.typing import RDKitMol
from deepchem.feat.base_classes import MolecularFeaturizer

ZINC_CHARSET = [
zinc_charset = [
    ' ', '#', ')', '(', '+', '-', '/', '1', '3', '2', '5', '4', '7', '6', '8',
    '=', '@', 'C', 'B', 'F', 'I', 'H', 'O', 'N', 'S', '[', ']', '\\', 'c', 'l',
    'o', 'n', 'p', 's', 'r'
@@ -14,52 +11,52 @@ ZINC_CHARSET = [
class OneHotFeaturizer(MolecularFeaturizer):
  """Encodes a molecule as a one-hot array.

  This featurizer takes a molecule and encodes its SMILES string
  as a one-hot array.
  This featurizer takes a molecule and encodes its Smiles string as a one-hot
  array.

  Notes
  -----
  This class requires RDKit to be installed.
  Note that this featurizer is not thread safe in initialization of charset.
  Note
  ----
  This class requires RDKit to be installed. Note that this featurizer is not
  Thread Safe in initialization of charset
  """

  def __init__(self, charset: List[str] = ZINC_CHARSET, padlength: int = 120):
  def __init__(self, charset=None, padlength=120):
    """Initialize featurizer.

    Parameters
    ----------
    charset: List[str]
    charset: list of str, optional (default None)
      A list of strings, where each string is length 1.
    padlength: int, optional (default 120)
      length to pad the smile strings to.
    """
    try:
      from rdkit import Chem
    except ModuleNotFoundError:
      raise ValueError("This class requires RDKit to be installed.")
    self.charset = charset
    self.pad_length = padlength

  def _featurize(self, mol: RDKitMol) -> np.ndarray:
  def _featurize(self, mol):
    """Compute one-hot featurization of this molecule.

    Parameters
    ----------
    mol: rdkit.Chem.rdchem.Mol
      RDKit Mol object
    mol : RDKit Mol
        Molecule.

    Returns
    -------
    np.ndarray
      The one hot encoded arrays for each character in SMILES
    rval: np.ndarray
      Vector of RDKit descriptors for `mol`
    """
    try:
    from rdkit import Chem
    except ModuleNotFoundError:
      raise ValueError("This class requires RDKit to be installed.")

    smiles = Chem.MolToSmiles(mol)
    if self.charset is None:
      self.charset = self._create_charset(smiles)
    return np.array([self.one_hot_encoded(smile) for smile in smiles])

  def one_hot_array(self, i: int) -> List[int]:
  def one_hot_array(self, i):
    """Create a one hot array with bit i set to 1

    Parameters
@@ -69,93 +66,90 @@ class OneHotFeaturizer(MolecularFeaturizer):

    Returns
    -------
    List[int]
      The one hot list of bit i. The length is len(self.charset)
    obj:`list` of obj:`int`
      length len(self.charset)
    """
    return [int(x) for x in [ix == i for ix in range(len(self.charset))]]

  def one_hot_index(self, c: str) -> int:
  def one_hot_index(self, c):
    """Compute one-hot index of charater.

    Parameters
    ----------
    c: str
    c: char
      character whose index we want

    Returns
    -------
    int
    index of c in self.charset
    """
    return self.charset.index(c)

  def pad_smile(self, smile: str) -> str:
    """Pad a SMILES string to `self.pad_length`
  def pad_smile(self, smile):
    """Pad a smile string to `self.pad_length`

    Parameters
    ----------
    smile: str
      The SMILES string to be padded.
      The smiles string to be padded.

    Returns
    -------
    str
      SMILES string padded to self.pad_length
      smile string space padded to self.pad_length
    """

    return smile.ljust(self.pad_length)

  def one_hot_encoded(self, smile: str) -> np.ndarray:
    """One Hot Encode an entire SMILES string
  def one_hot_encoded(self, smile):
    """One Hot Encode an entire SMILE string
    
    Parameters
    ----------
    smile: str
      SMILES string to encode
      smile string to encode

    Returns
    -------
    np.ndarray
      The one hot encoded arrays for each character in SMILES
    np.array of one hot encoded arrays for each character in smile
    """
    return np.array([
        self.one_hot_array(self.one_hot_index(x)) for x in self.pad_smile(smile)
    ])

  def untransform(self, one_hot: np.ndarray) -> List[str]:
    """Convert from one hot representation back to SMILES
  def untransform(self, z):
    """Convert from one hot representation back to SMILE

    Parameters
    ----------
    one_hot: np.ndarray
      A numpy array of one hot encoded features
    z: obj:`list`
      list of one hot encoded features

    Returns
    -------
    List[str]
      The List SMILES strings picking MAX for each one hot encoded array
    Smile Strings picking MAX for each one hot encoded array
    """
    smiles_list = []
    for i in range(len(one_hot)):
      smiles = ""
      for j in range(len(one_hot[i])):
        char_bit = np.argmax(one_hot[i][j])
        smiles += self.charset[char_bit]
      smiles_list.append(smiles.strip())
    return smiles_list

  def _create_charset(self, smiles: List[str]) -> List[str]:
    """Create the charset from SMILES
    z1 = []
    for i in range(len(z)):
      s = ""
      for j in range(len(z[i])):
        oh = np.argmax(z[i][j])
        s += self.charset[oh]
      z1.append([s.strip()])
    return z1

  def _create_charset(self, smiles):
    """Create the charset from smiles

    Parameters
    ----------
    smiles: List[str]
      List of SMILES strings
    smiles: obj:`list` of obj:`str`
      list of smile strings

    Returns
    -------
    List[str]
      List of length one strings that are characters in SMILES. No duplicates
    obj:`list` of obj:`str`
      List of length one strings that are characters in smiles.  No duplicates
    """
    s = set()
    for smile in smiles:
+11 −0
Original line number Diff line number Diff line
from collections import deque

import sys
import tensorflow as tf
import pickle

import os
import fnmatch
import numpy as np
from scipy.spatial.distance import pdist, squareform
import pandas as pd

from deepchem.feat.base_classes import Featurizer
from deepchem.feat.graph_features import atom_features
from scipy.sparse import csr_matrix


def get_atom_type(atom):
+0 −2
Original line number Diff line number Diff line
@@ -20,11 +20,9 @@ from deepchem.feat.atomic_coordinates import NeighborListComplexAtomicCoordinate

# molecule featurizers
from deepchem.feat.molecule_featurizers import MolGraphConvFeaturizer
from deepchem.feat.molecule_featurizers import AdjacencyFingerprint
from deepchem.feat.molecule_featurizers import CircularFingerprint
from deepchem.feat.molecule_featurizers import CoulombMatrix
from deepchem.feat.molecule_featurizers import CoulombMatrixEig
from deepchem.feat.molecule_featurizers import OneHotFeaturizer
from deepchem.feat.molecule_featurizers import RawFeaturizer
from deepchem.feat.molecule_featurizers import RDKitDescriptors
from deepchem.feat.molecule_featurizers import SmilesToImage
+4 −4
Original line number Diff line number Diff line
@@ -5,7 +5,7 @@ import inspect
import logging
import numpy as np
import multiprocessing
from typing import Any, Dict, List, Iterable, Sequence, Tuple
from typing import Any, Dict, List, Iterable, Sequence, Tuple, Union

from deepchem.utils.typing import PymatgenStructure

@@ -214,7 +214,7 @@ class MolecularFeaturizer(Featurizer):
  The subclasses of this class require RDKit to be installed.
  """

  def featurize(self, molecules, log_every_n=1000, canonical=False):
  def featurize(self, molecules, log_every_n=1000):
    """Calculate features for molecules.

    Parameters
@@ -224,8 +224,6 @@ class MolecularFeaturizer(Featurizer):
      strings.
    log_every_n: int, default 1000
      Logging messages reported every `log_every_n` samples.
    canonical: bool, default False
      Whether to use a canonical order of atoms returned by RDKit

    Returns
    -------
@@ -235,6 +233,8 @@ class MolecularFeaturizer(Featurizer):
    try:
      from rdkit import Chem
      from rdkit.Chem.rdchem import Mol
      from rdkit.Chem import rdmolfiles
      from rdkit.Chem import rdmolops
    except ModuleNotFoundError:
      raise ValueError("This class requires RDKit to be installed.")

+0 −2
Original line number Diff line number Diff line
# flake8: noqa
from deepchem.feat.molecule_featurizers.adjacency_fingerprint import AdjacencyFingerprint
from deepchem.feat.molecule_featurizers.bp_symmetry_function_input import BPSymmetryFunctionInput
from deepchem.feat.molecule_featurizers.circular_fingerprint import CircularFingerprint
from deepchem.feat.molecule_featurizers.coulomb_matrices import CoulombMatrix
from deepchem.feat.molecule_featurizers.coulomb_matrices import CoulombMatrixEig
from deepchem.feat.molecule_featurizers.one_hot_featurizer import OneHotFeaturizer
from deepchem.feat.molecule_featurizers.raw_featurizer import RawFeaturizer
from deepchem.feat.molecule_featurizers.rdkit_descriptors import RDKitDescriptors
from deepchem.feat.molecule_featurizers.smiles_to_image import SmilesToImage
Loading