Commit 0655cbe1 authored by VIGNESHinZONE's avatar VIGNESHinZONE
Browse files

Test function for LCNN featurizer and few other typo's

parent ffcc8f01
Loading
Loading
Loading
Loading
+35 −7
Original line number Diff line number Diff line
import numpy as np
from deepchem.feat import Featurizer
from collections import defaultdict
from pymatgen import Element, Structure, Molecule, Lattice
from pymatgen.symmetry.analyzer import PointGroupAnalyzer
import networkx as nx
import networkx.algorithms.isomorphism as iso
from scipy.spatial.distance import cdist, pdist, squareform


class LCNNFeaturizer(Featurizer):
@@ -24,8 +19,7 @@ class LCNNFeaturizer(Featurizer):
  for featurization.
  
  [1] The Primitive Template file must be passed as raw text string or path file
  [2] The datapoint must be passed as raw text string. If a text file is present use
  >>> open(input_file_path).read() 
  [2] The datapoint must be passed as raw text string. 
  
  References
  ----------
@@ -216,6 +210,15 @@ class SiteEnvironment(object):
        environment are the same
    grtol : tolerance for deciding symmetric nodes
    """
    try:
        import networkx.algorithms.isomorphism as iso
    except:
        raise ImportError("This class requires networkx to be installed.")
    try:
        from scipy.spatial.distance import pdist, squareform
    except:
        raise ImportError("This class requires scipy to be installed.")
    
    self.pos = pos
    self.sitetypes = sitetypes
    self.activesiteidx = [i for i, s in enumerate(self.sitetypes) if 'A' in s]
@@ -270,6 +273,16 @@ class SiteEnvironment(object):
    networkx graph used for matching site positions in
    datum. 
    """
    try:
        import networkx as nx
    except:
        raise ImportError("This class requires networkx to be installed.")

    try:
        from scipy.spatial.distance import cdist, pdist
    except:
        raise ImportError("This class requires scipy to be installed.")

    # construct graph
    G = nx.Graph()
    dists = cdist([[0, 0, 0]], pos - np.mean(pos, 0))[0]
@@ -335,6 +348,10 @@ class SiteEnvironment(object):
    -------
    dict : atom mapping. None if there is no mapping
    """
    try:
        import networkx.algorithms.isomorphism as iso
    except:
        raise ImportError("This class requires networkx to be installed.")
    # construct graph
    G = self._ConstructGraph(env['pos'], env['sitetypes'])
    if len(self.G.nodes) != len(G.nodes):
@@ -582,6 +599,17 @@ class SiteEnvironments(object):
    ------
    list of local_env : list of local_env class
    """
    try:
        from pymatgen import Element, Structure, Molecule, Lattice
        from pymatgen.symmetry.analyzer import PointGroupAnalyzer

    except:
        raise ImportError("This class requires pymatgen to be installed.")

    try:
        from scipy.spatial.distance import cdist
    except:
        raise ImportError("This class requires scipy to be installed.")
    # %% Check error
    assert isinstance(coord, (list, np.ndarray))
    assert isinstance(cell, (list, np.ndarray))
+56 −0
Original line number Diff line number Diff line
import numpy as np
from deepchem.feat.material_featurizers.lcnn_featurizer import LCNNFeaturizer

template = """#primitive strucutre
2.81852800e+00  0.00000000e+00  0.00000000e+00 T
-1.40926400e+00  2.44091700e+00  0.00000000e+00 T
0.00000000e+00  0.00000000e+00  2.55082550e+01 F
1 1
1 0 2
6
0.666670000000  0.333330000000  0.090220999986 S1
0.333330000000  0.666670000000  0.180439359180 S1
0.000000000000  0.000000000000  0.270657718374 S1
0.666670000000  0.333330000000  0.360876077568 S1
0.333330000000  0.666670000000  0.451094436762 S1
0.000000000000  0.000000000000  0.496569911270 A1
"""


structure = """-4.22779200e+00 -2.44091700e+00  0.00000000e+00
 2.81852800e+00 -4.88183400e+00  0.00000000e+00
 0.00000000e+00  0.00000000e+00  2.31755900e+01
24
 0.333330000000  0.500000000000  0.099298999982 S1
 0.000000000000  0.500000000000  0.198598000008 S1
 0.166670000000  0.250000000000  0.297897000033 S1
 0.333330000000  0.500000000000  0.397196000059 S1
 0.000000000000  0.500000000000  0.496495000084 S1
 0.333330000000  0.000000000000  0.099298999982 S1
 0.000000000000  0.000000000000  0.198598000008 S1
 0.166670000000  0.750000000000  0.297897000033 S1
 0.333330000000  0.000000000000  0.397196000059 S1
 0.000000000000  0.000000000000  0.496495000084 S1
 0.833330000000  0.250000000000  0.099298999982 S1
 0.500000000000  0.250000000000  0.198598000008 S1
 0.666670000000  0.000000000000  0.297897000033 S1
 0.833330000000  0.250000000000  0.397196000059 S1
 0.500000000000  0.250000000000  0.496495000084 S1
 0.833330000000  0.750000000000  0.099298999982 S1
 0.500000000000  0.750000000000  0.198598000008 S1
 0.666670000000  0.500000000000  0.297897000033 S1
 0.833330000000  0.750000000000  0.397196000059 S1
 0.500000000000  0.750000000000  0.496495000084 S1
 0.666670000000  0.500000000000  0.546547663253 A1 0
 0.666670000000  0.000000000000  0.546547663253 A1 0
 0.166670000000  0.750000000000  0.546547663253 A1 2
 0.166670000000  0.250000000000  0.546547663253 A1 1
"""


def test_LCNNFeaturizer():
    featuriser = LCNNFeaturizer(np.around(6.00), template)
    data = featuriser._featurize(structure)
    assert data['X_Sites'].shape == (4, 3)
    assert data['X_NSs'].shape == (1, 4, 6, 19)
    
 No newline at end of file
+37 −36
Original line number Diff line number Diff line
@@ -55,53 +55,54 @@ def load_Platinum_Adsorption(
    **kwargs
) -> Tuple[List[str], Tuple[Dataset, ...], List[dc.trans.Transformer]]:
  """
    Load mydataset.
    Contains 
    Load Platinum Adsorption Dataset

    The dataset consist of diffrent configurations of Adsorbates (i.e N and NO)
    on Platinum surface represented as Lattice and their formation energy. There
    are 648 diffrent adsorbate configuration in this datasets given in this format
    
    [ax][ay][az]
    [bx][by][bz]
    [cx][cy][cz]
    [number sites]
    [site1a][site1b][site1c][site type][occupation state if active site]
    [site2a][site2b][site2c][site type][occupation state if active site]

    - ax,ay, ... are cell basis vector
    - site1a,site1b,site1c are the scaled coordinates of site 1

     
    Parameters
    ----------
    featurizer : Featurizer (default LCNNFeaturizer)
        A featurizer that inherits from deepchem.feat.Featurizer.
    transformers : List[]
    Does'nt require any transformation
        the featurizer to use for processing the data. Reccomended to use
        the LCNNFeaturiser.
    splitter : Splitter (default RandomSplitter)
        A splitter that inherits from deepchem.splits.splitters.Splitter.
    reload : bool (default True)
        Try to reload dataset from disk if already downloaded. Save to disk
        after featurizing.
    data_dir : str, optional (default None)
        Path to datasets.
        the splitter to use for splitting the data into training, validation, and
        test sets.  Alternatively you can pass one of the names from
        dc.molnet.splitters as a shortcut.  If this is None, all the data will 
        be included in a single dataset.
    transformers : list of TransformerGenerators or strings. the Transformers to
        apply to the data and appropritate featuriser. Does'nt require any
        transformation for LCNN_featuriser    
    reload : bool
        if True, the first call for a particular featurizer and splitter will cache
        the datasets to disk, and subsequent calls will reload the cached datasets.    
    data_dir : str
        a directory to save the raw data in
    save_dir : str, optional (default None)
        Path to featurized datasets.
    featurizer_kwargs : dict
        Specify parameters to featurizer, e.g. {"cutoff": 6.00}
    splitter_kwargs : dict
        Specify parameters to splitter, e.g. {"seed": 42}
    transformer_kwargs : dict
        Maps transformer names to constructor arguments, e.g.
        {"BalancingTransformer": {"transform_x":True, "transform_y":False}}
    **kwargs : additional optional arguments.
    Returns
    -------
    tasks, datasets, transformers : tuple
        tasks : list
        Column names corresponding to machine learning target variables.
        datasets : tuple
        train, validation, test splits of data as
        ``deepchem.data.datasets.Dataset`` instances.
        transformers : list
        ``deepchem.trans.transformers.Transformer`` instances applied
        to dataset.
        a directory to save the dataset in

    References
    ----------
    MLA style references for this dataset. The example is like this.
    Last, First et al. "Article title." Journal name, vol. #, no. #, year, pp. page range, DOI.
    ...[1] Lym, J et al. "Lattice Convolutional Neural Network Modeling of Adsorbate
    .. [1] Jonathan Lym, Geun Ho G. "Lattice Convolutional Neural Network Modeling of Adsorbate
       Coverage Effects"J. Phys. Chem. C 2019, 123, 18951−18959
    
    Examples
    --------
    >>>
    >> import deepchem as dc
    >> feat_args = {"cutoff": np.around(6.00, 2), "input_file_path": os.path.join(data_path,'input.in') }

    >> tasks, datasets, transformers = load_Platinum_Adsorption(
        reload=True,
        data_dir=data_path,
+0 −27
Original line number Diff line number Diff line
import os
from deepchem.molnet import load_Platinum_Adsorption


def test_Platinum_Adsorption_loader():

  current_dir = os.path.dirname(os.path.abspath(__file__))
  kwargs = {"log_every_n": 100}
  tasks, datasets, transformers = load_Platinum_Adsorption(
      reload=False, data_dir=current_dir, save_dir=current_dir, **kwargs)
  assert tasks[0] == "Formation Energy"
  assert datasets[0].X[0]['X_Sites'].shape[1] == 3
  assert datasets[0].X[0]['X_NSs'].shape[3] == 19
  assert datasets[0].X[0]['X_NSs'].shape[2] == 6
  assert datasets[0].X[0]['X_NSs'].shape[1] == datasets[0].X[0][
      'X_Sites'].shape[0]

  if os.path.exists(os.path.join(current_dir, 'Platinum_Adsorption.json')):
    os.remove(os.path.join(current_dir, 'Platinum_Adsorption.json'))

  if os.path.exists(os.path.join(current_dir, 'input.in')):
    os.remove(os.path.join(current_dir, 'input.in'))

  if os.path.exists(os.path.join(current_dir, 'platinum_adsorption.tar.gz')):
    os.remove(os.path.join(current_dir, 'platinum_adsorption.tar.gz'))