signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def get_substances(identifier, namespace='<STR_LIT>', as_dataframe=False, **kwargs):
results = get_json(identifier, namespace, '<STR_LIT>', **kwargs)<EOL>substances = [Substance(r) for r in results['<STR_LIT>']] if results else []<EOL>if as_dataframe:<EOL><INDENT>return substances_to_frame(substances)<EOL><DEDENT>return substances<EOL>
Retrieve the specified substance records from PubChem. :param identifier: The substance identifier to use as a search query. :param namespace: (optional) The identifier type, one of sid, name or sourceid/<source name>. :param as_dataframe: (optional) Automatically extract the :class:`~pubchempy.Substance` properties into a pandas :class:`~pandas.DataFrame` and return that.
f498:m5
def get_assays(identifier, namespace='<STR_LIT>', **kwargs):
results = get_json(identifier, namespace, '<STR_LIT>', '<STR_LIT:description>', **kwargs)<EOL>return [Assay(r) for r in results['<STR_LIT>']] if results else []<EOL>
Retrieve the specified assay records from PubChem. :param identifier: The assay identifier to use as a search query. :param namespace: (optional) The identifier type.
f498:m6
def get_properties(properties, identifier, namespace='<STR_LIT>', searchtype=None, as_dataframe=False, **kwargs):
if isinstance(properties, text_types):<EOL><INDENT>properties = properties.split('<STR_LIT:U+002C>')<EOL><DEDENT>properties = '<STR_LIT:U+002C>'.join([PROPERTY_MAP.get(p, p) for p in properties])<EOL>properties = '<STR_LIT>' % properties<EOL>results = get_json(identifier, namespace, '<STR_LIT>', properties, searchtype=searchtype, **kwargs)<EOL>results = results['<STR_LIT>']['<STR_LIT>'] if results else []<EOL>if as_dataframe:<EOL><INDENT>import pandas as pd<EOL>return pd.DataFrame.from_records(results, index='<STR_LIT>')<EOL><DEDENT>return results<EOL>
Retrieve the specified properties from PubChem. :param identifier: The compound, substance or assay identifier to use as a search query. :param namespace: (optional) The identifier type. :param searchtype: (optional) The advanced search type, one of substructure, superstructure or similarity. :param as_dataframe: (optional) Automatically extract the properties into a pandas :class:`~pandas.DataFrame`.
f498:m7
def get_all_sources(domain='<STR_LIT>'):
results = json.loads(get(domain, None, '<STR_LIT>').decode())<EOL>return results['<STR_LIT>']['<STR_LIT>']<EOL>
Return a list of all current depositors of substances or assays.
f498:m12
def download(outformat, path, identifier, namespace='<STR_LIT>', domain='<STR_LIT>', operation=None, searchtype=None,<EOL>overwrite=False, **kwargs):
response = get(identifier, namespace, domain, operation, outformat, searchtype, **kwargs)<EOL>if not overwrite and os.path.isfile(path):<EOL><INDENT>raise IOError("<STR_LIT>" % path)<EOL><DEDENT>with open(path, '<STR_LIT:wb>') as f:<EOL><INDENT>f.write(response)<EOL><DEDENT>
Format can be XML, ASNT/B, JSON, SDF, CSV, PNG, TXT.
f498:m13
def memoized_property(fget):
attr_name = '<STR_LIT>'.format(fget.__name__)<EOL>@functools.wraps(fget)<EOL>def fget_memoized(self):<EOL><INDENT>if not hasattr(self, attr_name):<EOL><INDENT>setattr(self, attr_name, fget(self))<EOL><DEDENT>return getattr(self, attr_name)<EOL><DEDENT>return property(fget_memoized)<EOL>
Decorator to create memoized properties. Used to cache :class:`~pubchempy.Compound` and :class:`~pubchempy.Substance` properties that require an additional request.
f498:m14
def deprecated(message=None):
def deco(func):<EOL><INDENT>@functools.wraps(func)<EOL>def wrapped(*args, **kwargs):<EOL><INDENT>warnings.warn(<EOL>message or '<STR_LIT>'.format(func.__name__),<EOL>category=PubChemPyDeprecationWarning,<EOL>stacklevel=<NUM_LIT:2><EOL>)<EOL>return func(*args, **kwargs)<EOL><DEDENT>return wrapped<EOL><DEDENT>return deco<EOL>
Decorator to mark functions as deprecated. A warning will be emitted when the function is used.
f498:m15
def _parse_prop(search, proplist):
props = [i for i in proplist if all(item in i['<STR_LIT>'].items() for item in search.items())]<EOL>if len(props) > <NUM_LIT:0>:<EOL><INDENT>return props[<NUM_LIT:0>]['<STR_LIT:value>'][list(props[<NUM_LIT:0>]['<STR_LIT:value>'].keys())[<NUM_LIT:0>]]<EOL><DEDENT>
Extract property value from record using the given urn search filter.
f498:m16
def compounds_to_frame(compounds, properties=None):
import pandas as pd<EOL>if isinstance(compounds, Compound):<EOL><INDENT>compounds = [compounds]<EOL><DEDENT>properties = set(properties) | set(['<STR_LIT>']) if properties else None<EOL>return pd.DataFrame.from_records([c.to_dict(properties) for c in compounds], index='<STR_LIT>')<EOL>
Construct a pandas :class:`~pandas.DataFrame` from a list of :class:`~pubchempy.Compound` objects. Optionally specify a list of the desired :class:`~pubchempy.Compound` properties.
f498:m17
def substances_to_frame(substances, properties=None):
import pandas as pd<EOL>if isinstance(substances, Substance):<EOL><INDENT>substances = [substances]<EOL><DEDENT>properties = set(properties) | set(['<STR_LIT>']) if properties else None<EOL>return pd.DataFrame.from_records([s.to_dict(properties) for s in substances], index='<STR_LIT>')<EOL>
Construct a pandas :class:`~pandas.DataFrame` from a list of :class:`~pubchempy.Substance` objects. Optionally specify a list of the desired :class:`~pubchempy.Substance` properties.
f498:m18
def __init__(self, aid, number, x=None, y=None, z=None, charge=<NUM_LIT:0>):
self.aid = aid<EOL>"""<STR_LIT>"""<EOL>self.number = number<EOL>"""<STR_LIT>"""<EOL>self.x = x<EOL>"""<STR_LIT>"""<EOL>self.y = y<EOL>"""<STR_LIT>"""<EOL>self.z = z<EOL>"""<STR_LIT>"""<EOL>self.charge = charge<EOL>"""<STR_LIT>"""<EOL>
Initialize with an atom ID, atomic number, coordinates and optional change. :param int aid: Atom ID :param int number: Atomic number :param float x: X coordinate. :param float y: Y coordinate. :param float z: (optional) Z coordinate. :param int charge: (optional) Formal charge on atom.
f498:c4:m0
@deprecated('<STR_LIT>')<EOL><INDENT>def __getitem__(self, prop):<DEDENT>
if prop in {'<STR_LIT>', '<STR_LIT:x>', '<STR_LIT:y>', '<STR_LIT:z>', '<STR_LIT>'}:<EOL><INDENT>return getattr(self, prop)<EOL><DEDENT>raise KeyError(prop)<EOL>
Allow dict-style access to attributes to ease transition from when atoms were dicts.
f498:c4:m3
@deprecated('<STR_LIT>')<EOL><INDENT>def __setitem__(self, prop, val):<DEDENT>
setattr(self, prop, val)<EOL>
Allow dict-style setting of attributes to ease transition from when atoms were dicts.
f498:c4:m4
@deprecated('<STR_LIT>')<EOL><INDENT>def __contains__(self, prop):<DEDENT>
if prop in {'<STR_LIT>', '<STR_LIT:x>', '<STR_LIT:y>', '<STR_LIT:z>', '<STR_LIT>'}:<EOL><INDENT>return getattr(self, prop) is not None<EOL><DEDENT>return False<EOL>
Allow dict-style checking of attributes to ease transition from when atoms were dicts.
f498:c4:m5
@property<EOL><INDENT>def element(self):<DEDENT>
return ELEMENTS.get(self.number, None)<EOL>
The element symbol for this atom.
f498:c4:m6
def to_dict(self):
data = {'<STR_LIT>': self.aid, '<STR_LIT>': self.number, '<STR_LIT>': self.element}<EOL>for coord in {'<STR_LIT:x>', '<STR_LIT:y>', '<STR_LIT:z>'}:<EOL><INDENT>if getattr(self, coord) is not None:<EOL><INDENT>data[coord] = getattr(self, coord)<EOL><DEDENT><DEDENT>if self.charge is not <NUM_LIT:0>:<EOL><INDENT>data['<STR_LIT>'] = self.charge<EOL><DEDENT>return data<EOL>
Return a dictionary containing Atom data.
f498:c4:m7
def set_coordinates(self, x, y, z=None):
self.x = x<EOL>self.y = y<EOL>self.z = z<EOL>
Set all coordinate dimensions at once.
f498:c4:m8
@property<EOL><INDENT>def coordinate_type(self):<DEDENT>
return '<STR_LIT>' if self.z is None else '<STR_LIT>'<EOL>
Whether this atom has 2D or 3D coordinates.
f498:c4:m9
def __init__(self, aid1, aid2, order=BondType.SINGLE, style=None):
self.aid1 = aid1<EOL>"""<STR_LIT>"""<EOL>self.aid2 = aid2<EOL>"""<STR_LIT>"""<EOL>self.order = order<EOL>"""<STR_LIT>"""<EOL>self.style = style<EOL>"""<STR_LIT>"""<EOL>
Initialize with begin and end atom IDs, bond order and bond style. :param int aid1: Begin atom ID. :param int aid2: End atom ID. :param int order: Bond order.
f498:c5:m0
@deprecated('<STR_LIT>')<EOL><INDENT>def __getitem__(self, prop):<DEDENT>
if prop in {'<STR_LIT>', '<STR_LIT>'}:<EOL><INDENT>return getattr(self, prop)<EOL><DEDENT>raise KeyError(prop)<EOL>
Allow dict-style access to attributes to ease transition from when bonds were dicts.
f498:c5:m3
@deprecated('<STR_LIT>')<EOL><INDENT>def __setitem__(self, prop, val):<DEDENT>
setattr(self, prop, val)<EOL>
Allow dict-style setting of attributes to ease transition from when bonds were dicts.
f498:c5:m4
@deprecated('<STR_LIT>')<EOL><INDENT>def __contains__(self, prop):<DEDENT>
if prop in {'<STR_LIT>', '<STR_LIT>'}:<EOL><INDENT>return getattr(self, prop) is not None<EOL><DEDENT>return False<EOL>
Allow dict-style checking of attributes to ease transition from when bonds were dicts.
f498:c5:m5
@deprecated('<STR_LIT>')<EOL><INDENT>def __delitem__(self, prop):<DEDENT>
if not hasattr(self.__wrapped, prop):<EOL><INDENT>raise KeyError(prop)<EOL><DEDENT>delattr(self.__wrapped, prop)<EOL>
Delete the property prop from the wrapped object.
f498:c5:m6
def to_dict(self):
data = {'<STR_LIT>': self.aid1, '<STR_LIT>': self.aid2, '<STR_LIT>': self.order}<EOL>if self.style is not None:<EOL><INDENT>data['<STR_LIT>'] = self.style<EOL><DEDENT>return data<EOL>
Return a dictionary containing Bond data.
f498:c5:m7
def __init__(self, record):
self._record = None<EOL>self._atoms = {}<EOL>self._bonds = {}<EOL>self.record = record<EOL>
Initialize with a record dict from the PubChem PUG REST service. For most users, the ``from_cid()`` class method is probably a better way of creating Compounds. :param dict record: A compound record returned by the PubChem PUG REST service.
f498:c6:m0
@property<EOL><INDENT>def record(self):<DEDENT>
return self._record<EOL>
The raw compound record returned by the PubChem PUG REST service.
f498:c6:m1
def _setup_atoms(self):
<EOL>self._atoms = {}<EOL>aids = self.record['<STR_LIT>']['<STR_LIT>']<EOL>elements = self.record['<STR_LIT>']['<STR_LIT>']<EOL>if not len(aids) == len(elements):<EOL><INDENT>raise ResponseParseError('<STR_LIT>')<EOL><DEDENT>for aid, element in zip(aids, elements):<EOL><INDENT>self._atoms[aid] = Atom(aid=aid, number=element)<EOL><DEDENT>if '<STR_LIT>' in self.record:<EOL><INDENT>coord_ids = self.record['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>']<EOL>xs = self.record['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:x>']<EOL>ys = self.record['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:y>']<EOL>zs = self.record['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>'][<NUM_LIT:0>].get('<STR_LIT:z>', [])<EOL>if not len(coord_ids) == len(xs) == len(ys) == len(self._atoms) or (zs and not len(zs) == len(coord_ids)):<EOL><INDENT>raise ResponseParseError('<STR_LIT>')<EOL><DEDENT>for aid, x, y, z in zip_longest(coord_ids, xs, ys, zs):<EOL><INDENT>self._atoms[aid].set_coordinates(x, y, z)<EOL><DEDENT><DEDENT>if '<STR_LIT>' in self.record['<STR_LIT>']:<EOL><INDENT>for charge in self.record['<STR_LIT>']['<STR_LIT>']:<EOL><INDENT>self._atoms[charge['<STR_LIT>']].charge = charge['<STR_LIT:value>']<EOL><DEDENT><DEDENT>
Derive Atom objects from the record.
f498:c6:m3
def _setup_bonds(self):
self._bonds = {}<EOL>if '<STR_LIT>' not in self.record:<EOL><INDENT>return<EOL><DEDENT>aid1s = self.record['<STR_LIT>']['<STR_LIT>']<EOL>aid2s = self.record['<STR_LIT>']['<STR_LIT>']<EOL>orders = self.record['<STR_LIT>']['<STR_LIT>']<EOL>if not len(aid1s) == len(aid2s) == len(orders):<EOL><INDENT>raise ResponseParseError('<STR_LIT>')<EOL><DEDENT>for aid1, aid2, order in zip(aid1s, aid2s, orders):<EOL><INDENT>self._bonds[frozenset((aid1, aid2))] = Bond(aid1=aid1, aid2=aid2, order=order)<EOL><DEDENT>if '<STR_LIT>' in self.record and '<STR_LIT>' in self.record['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>'][<NUM_LIT:0>]:<EOL><INDENT>aid1s = self.record['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>']['<STR_LIT>']<EOL>aid2s = self.record['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>']['<STR_LIT>']<EOL>styles = self.record['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>']['<STR_LIT>']<EOL>for aid1, aid2, style in zip(aid1s, aid2s, styles):<EOL><INDENT>self._bonds[frozenset((aid1, aid2))].style = style<EOL><DEDENT><DEDENT>
Derive Bond objects from the record.
f498:c6:m4
@classmethod<EOL><INDENT>def from_cid(cls, cid, **kwargs):<DEDENT>
record = json.loads(request(cid, **kwargs).read().decode())['<STR_LIT>'][<NUM_LIT:0>]<EOL>return cls(record)<EOL>
Retrieve the Compound record for the specified CID. Usage:: c = Compound.from_cid(6819) :param int cid: The PubChem Compound Identifier (CID).
f498:c6:m5
def to_dict(self, properties=None):
if not properties:<EOL><INDENT>skip = {'<STR_LIT>', '<STR_LIT>', '<STR_LIT>'}<EOL>properties = [p for p in dir(Compound) if isinstance(getattr(Compound, p), property) and p not in skip]<EOL><DEDENT>return {p: [i.to_dict() for i in getattr(self, p)] if p in {'<STR_LIT>', '<STR_LIT>'} else getattr(self, p) for p in properties}<EOL>
Return a dictionary containing Compound data. Optionally specify a list of the desired properties. synonyms, aids and sids are not included unless explicitly specified using the properties parameter. This is because they each require an extra request.
f498:c6:m8
def to_series(self, properties=None):
import pandas as pd<EOL>return pd.Series(self.to_dict(properties))<EOL>
Return a pandas :class:`~pandas.Series` containing Compound data. Optionally specify a list of the desired properties. synonyms, aids and sids are not included unless explicitly specified using the properties parameter. This is because they each require an extra request.
f498:c6:m9
@property<EOL><INDENT>def cid(self):<DEDENT>
if '<STR_LIT:id>' in self.record and '<STR_LIT:id>' in self.record['<STR_LIT:id>'] and '<STR_LIT>' in self.record['<STR_LIT:id>']['<STR_LIT:id>']:<EOL><INDENT>return self.record['<STR_LIT:id>']['<STR_LIT:id>']['<STR_LIT>']<EOL><DEDENT>
The PubChem Compound Identifier (CID). .. note:: When searching using a SMILES or InChI query that is not present in the PubChem Compound database, an automatically generated record may be returned that contains properties that have been calculated on the fly. These records will not have a CID property.
f498:c6:m10
@property<EOL><INDENT>def elements(self):<DEDENT>
return [a.element for a in self.atoms]<EOL>
List of element symbols for atoms in this Compound.
f498:c6:m11
@property<EOL><INDENT>def atoms(self):<DEDENT>
return sorted(self._atoms.values(), key=lambda x: x.aid)<EOL>
List of :class:`Atoms <pubchempy.Atom>` in this Compound.
f498:c6:m12
@property<EOL><INDENT>def bonds(self):<DEDENT>
return sorted(self._bonds.values(), key=lambda x: (x.aid1, x.aid2))<EOL>
List of :class:`Bonds <pubchempy.Bond>` between :class:`Atoms <pubchempy.Atom>` in this Compound.
f498:c6:m13
@memoized_property<EOL><INDENT>def synonyms(self):<DEDENT>
if self.cid:<EOL><INDENT>results = get_json(self.cid, operation='<STR_LIT>')<EOL>return results['<STR_LIT>']['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>'] if results else []<EOL><DEDENT>
A ranked list of all the names associated with this Compound. Requires an extra request. Result is cached.
f498:c6:m14
@memoized_property<EOL><INDENT>def sids(self):<DEDENT>
if self.cid:<EOL><INDENT>results = get_json(self.cid, operation='<STR_LIT>')<EOL>return results['<STR_LIT>']['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>'] if results else []<EOL><DEDENT>
Requires an extra request. Result is cached.
f498:c6:m15
@memoized_property<EOL><INDENT>def aids(self):<DEDENT>
if self.cid:<EOL><INDENT>results = get_json(self.cid, operation='<STR_LIT>')<EOL>return results['<STR_LIT>']['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>'] if results else []<EOL><DEDENT>
Requires an extra request. Result is cached.
f498:c6:m16
@property<EOL><INDENT>def charge(self):<DEDENT>
return self.record['<STR_LIT>'] if '<STR_LIT>' in self.record else <NUM_LIT:0><EOL>
Formal charge on this Compound.
f498:c6:m18
@property<EOL><INDENT>def molecular_formula(self):<DEDENT>
return _parse_prop({'<STR_LIT:label>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
Molecular formula.
f498:c6:m19
@property<EOL><INDENT>def molecular_weight(self):<DEDENT>
return _parse_prop({'<STR_LIT:label>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
Molecular Weight.
f498:c6:m20
@property<EOL><INDENT>def canonical_smiles(self):<DEDENT>
return _parse_prop({'<STR_LIT:label>': '<STR_LIT>', '<STR_LIT:name>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
Canonical SMILES, with no stereochemistry information.
f498:c6:m21
@property<EOL><INDENT>def isomeric_smiles(self):<DEDENT>
return _parse_prop({'<STR_LIT:label>': '<STR_LIT>', '<STR_LIT:name>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
Isomeric SMILES.
f498:c6:m22
@property<EOL><INDENT>def inchi(self):<DEDENT>
return _parse_prop({'<STR_LIT:label>': '<STR_LIT>', '<STR_LIT:name>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
InChI string.
f498:c6:m23
@property<EOL><INDENT>def inchikey(self):<DEDENT>
return _parse_prop({'<STR_LIT:label>': '<STR_LIT>', '<STR_LIT:name>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
InChIKey.
f498:c6:m24
@property<EOL><INDENT>def iupac_name(self):<DEDENT>
<EOL>return _parse_prop({'<STR_LIT:label>': '<STR_LIT>', '<STR_LIT:name>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
Preferred IUPAC name.
f498:c6:m25
@property<EOL><INDENT>def xlogp(self):<DEDENT>
return _parse_prop({'<STR_LIT:label>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
XLogP.
f498:c6:m26
@property<EOL><INDENT>def exact_mass(self):<DEDENT>
return _parse_prop({'<STR_LIT:label>': '<STR_LIT>', '<STR_LIT:name>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
Exact mass.
f498:c6:m27
@property<EOL><INDENT>def monoisotopic_mass(self):<DEDENT>
return _parse_prop({'<STR_LIT:label>': '<STR_LIT>', '<STR_LIT:name>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
Monoisotopic mass.
f498:c6:m28
@property<EOL><INDENT>def tpsa(self):<DEDENT>
return _parse_prop({'<STR_LIT>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
Topological Polar Surface Area.
f498:c6:m29
@property<EOL><INDENT>def complexity(self):<DEDENT>
return _parse_prop({'<STR_LIT>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
Complexity.
f498:c6:m30
@property<EOL><INDENT>def h_bond_donor_count(self):<DEDENT>
return _parse_prop({'<STR_LIT>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
Hydrogen bond donor count.
f498:c6:m31
@property<EOL><INDENT>def h_bond_acceptor_count(self):<DEDENT>
return _parse_prop({'<STR_LIT>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
Hydrogen bond acceptor count.
f498:c6:m32
@property<EOL><INDENT>def rotatable_bond_count(self):<DEDENT>
return _parse_prop({'<STR_LIT>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
Rotatable bond count.
f498:c6:m33
@property<EOL><INDENT>def fingerprint(self):<DEDENT>
return _parse_prop({'<STR_LIT>': '<STR_LIT>'}, self.record['<STR_LIT>'])<EOL>
Raw padded and hex-encoded fingerprint, as returned by the PUG REST API.
f498:c6:m34
@property<EOL><INDENT>def cactvs_fingerprint(self):<DEDENT>
<EOL>return '<STR_LIT>'.format(int(self.fingerprint[<NUM_LIT:8>:], <NUM_LIT:16>))[:-<NUM_LIT:7>].zfill(<NUM_LIT>)<EOL>
PubChem CACTVS fingerprint. Each bit in the fingerprint represents the presence or absence of one of 881 chemical substructures. More information at ftp://ftp.ncbi.nlm.nih.gov/pubchem/specifications/pubchem_fingerprints.txt
f498:c6:m35
@property<EOL><INDENT>def heavy_atom_count(self):<DEDENT>
if '<STR_LIT:count>' in self.record and '<STR_LIT>' in self.record['<STR_LIT:count>']:<EOL><INDENT>return self.record['<STR_LIT:count>']['<STR_LIT>']<EOL><DEDENT>
Heavy atom count.
f498:c6:m36
@property<EOL><INDENT>def isotope_atom_count(self):<DEDENT>
if '<STR_LIT:count>' in self.record and '<STR_LIT>' in self.record['<STR_LIT:count>']:<EOL><INDENT>return self.record['<STR_LIT:count>']['<STR_LIT>']<EOL><DEDENT>
Isotope atom count.
f498:c6:m37
@property<EOL><INDENT>def atom_stereo_count(self):<DEDENT>
if '<STR_LIT:count>' in self.record and '<STR_LIT>' in self.record['<STR_LIT:count>']:<EOL><INDENT>return self.record['<STR_LIT:count>']['<STR_LIT>']<EOL><DEDENT>
Atom stereocenter count.
f498:c6:m38
@property<EOL><INDENT>def defined_atom_stereo_count(self):<DEDENT>
if '<STR_LIT:count>' in self.record and '<STR_LIT>' in self.record['<STR_LIT:count>']:<EOL><INDENT>return self.record['<STR_LIT:count>']['<STR_LIT>']<EOL><DEDENT>
Defined atom stereocenter count.
f498:c6:m39
@property<EOL><INDENT>def undefined_atom_stereo_count(self):<DEDENT>
if '<STR_LIT:count>' in self.record and '<STR_LIT>' in self.record['<STR_LIT:count>']:<EOL><INDENT>return self.record['<STR_LIT:count>']['<STR_LIT>']<EOL><DEDENT>
Undefined atom stereocenter count.
f498:c6:m40
@property<EOL><INDENT>def bond_stereo_count(self):<DEDENT>
if '<STR_LIT:count>' in self.record and '<STR_LIT>' in self.record['<STR_LIT:count>']:<EOL><INDENT>return self.record['<STR_LIT:count>']['<STR_LIT>']<EOL><DEDENT>
Bond stereocenter count.
f498:c6:m41
@property<EOL><INDENT>def defined_bond_stereo_count(self):<DEDENT>
if '<STR_LIT:count>' in self.record and '<STR_LIT>' in self.record['<STR_LIT:count>']:<EOL><INDENT>return self.record['<STR_LIT:count>']['<STR_LIT>']<EOL><DEDENT>
Defined bond stereocenter count.
f498:c6:m42
@property<EOL><INDENT>def undefined_bond_stereo_count(self):<DEDENT>
if '<STR_LIT:count>' in self.record and '<STR_LIT>' in self.record['<STR_LIT:count>']:<EOL><INDENT>return self.record['<STR_LIT:count>']['<STR_LIT>']<EOL><DEDENT>
Undefined bond stereocenter count.
f498:c6:m43
@property<EOL><INDENT>def covalent_unit_count(self):<DEDENT>
if '<STR_LIT:count>' in self.record and '<STR_LIT>' in self.record['<STR_LIT:count>']:<EOL><INDENT>return self.record['<STR_LIT:count>']['<STR_LIT>']<EOL><DEDENT>
Covalently-bonded unit count.
f498:c6:m44
@classmethod<EOL><INDENT>def from_sid(cls, sid):<DEDENT>
record = json.loads(request(sid, '<STR_LIT>', '<STR_LIT>').read().decode())['<STR_LIT>'][<NUM_LIT:0>]<EOL>return cls(record)<EOL>
Retrieve the Substance record for the specified SID. :param int sid: The PubChem Substance Identifier (SID).
f498:c7:m0
def to_dict(self, properties=None):
if not properties:<EOL><INDENT>skip = {'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'}<EOL>properties = [p for p in dir(Substance) if isinstance(getattr(Substance, p), property) and p not in skip]<EOL><DEDENT>return {p: getattr(self, p) for p in properties}<EOL>
Return a dictionary containing Substance data. If the properties parameter is not specified, everything except cids and aids is included. This is because the aids and cids properties each require an extra request to retrieve. :param properties: (optional) A list of the desired properties.
f498:c7:m4
def to_series(self, properties=None):
import pandas as pd<EOL>return pd.Series(self.to_dict(properties))<EOL>
Return a pandas :class:`~pandas.Series` containing Substance data. If the properties parameter is not specified, everything except cids and aids is included. This is because the aids and cids properties each require an extra request to retrieve. :param properties: (optional) A list of the desired properties.
f498:c7:m5
@property<EOL><INDENT>def sid(self):<DEDENT>
return self.record['<STR_LIT>']['<STR_LIT:id>']<EOL>
The PubChem Substance Idenfitier (SID).
f498:c7:m6
@property<EOL><INDENT>def synonyms(self):<DEDENT>
if '<STR_LIT>' in self.record:<EOL><INDENT>return self.record['<STR_LIT>']<EOL><DEDENT>
A ranked list of all the names associated with this Substance.
f498:c7:m7
@property<EOL><INDENT>def source_name(self):<DEDENT>
return self.record['<STR_LIT:source>']['<STR_LIT>']['<STR_LIT:name>']<EOL>
The name of the PubChem depositor that was the source of this Substance.
f498:c7:m8
@property<EOL><INDENT>def source_id(self):<DEDENT>
return self.record['<STR_LIT:source>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT:str>']<EOL>
Unique ID for this Substance within those from the same PubChem depositor source.
f498:c7:m9
@property<EOL><INDENT>def standardized_cid(self):<DEDENT>
for c in self.record['<STR_LIT>']:<EOL><INDENT>if c['<STR_LIT:id>']['<STR_LIT:type>'] == CompoundIdType.STANDARDIZED:<EOL><INDENT>return c['<STR_LIT:id>']['<STR_LIT:id>']['<STR_LIT>']<EOL><DEDENT><DEDENT>
The CID of the Compound that was produced when this Substance was standardized. May not exist if this Substance was not standardizable.
f498:c7:m10
@memoized_property<EOL><INDENT>def standardized_compound(self):<DEDENT>
for c in self.record['<STR_LIT>']:<EOL><INDENT>if c['<STR_LIT:id>']['<STR_LIT:type>'] == CompoundIdType.STANDARDIZED:<EOL><INDENT>return Compound.from_cid(c['<STR_LIT:id>']['<STR_LIT:id>']['<STR_LIT>'])<EOL><DEDENT><DEDENT>
Return the :class:`~pubchempy.Compound` that was produced when this Substance was standardized. Requires an extra request. Result is cached.
f498:c7:m11
@property<EOL><INDENT>def deposited_compound(self):<DEDENT>
for c in self.record['<STR_LIT>']:<EOL><INDENT>if c['<STR_LIT:id>']['<STR_LIT:type>'] == CompoundIdType.DEPOSITED:<EOL><INDENT>return Compound(c)<EOL><DEDENT><DEDENT>
Return a :class:`~pubchempy.Compound` produced from the unstandardized Substance record as deposited. The resulting :class:`~pubchempy.Compound` will not have a ``cid`` and will be missing most properties.
f498:c7:m12
@memoized_property<EOL><INDENT>def cids(self):<DEDENT>
results = get_json(self.sid, '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>return results['<STR_LIT>']['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>'] if results else []<EOL>
A list of all CIDs for Compounds that were produced when this Substance was standardized. Requires an extra request. Result is cached.
f498:c7:m13
@memoized_property<EOL><INDENT>def aids(self):<DEDENT>
results = get_json(self.sid, '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>return results['<STR_LIT>']['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>'] if results else []<EOL>
A list of all AIDs for Assays associated with this Substance. Requires an extra request. Result is cached.
f498:c7:m14
@classmethod<EOL><INDENT>def from_aid(cls, aid):<DEDENT>
record = json.loads(request(aid, '<STR_LIT>', '<STR_LIT>', '<STR_LIT:description>').read().decode())['<STR_LIT>'][<NUM_LIT:0>]<EOL>return cls(record)<EOL>
Retrieve the Assay record for the specified AID. :param int aid: The PubChem Assay Identifier (AID).
f498:c8:m0
def to_dict(self, properties=None):
if not properties:<EOL><INDENT>properties = [p for p in dir(Assay) if isinstance(getattr(Assay, p), property)]<EOL><DEDENT>return {p: getattr(self, p) for p in properties}<EOL>
Return a dictionary containing Assay data. If the properties parameter is not specified, everything is included. :param properties: (optional) A list of the desired properties.
f498:c8:m4
@property<EOL><INDENT>def aid(self):<DEDENT>
return self.record['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT:id>']<EOL>
The PubChem Substance Idenfitier (SID).
f498:c8:m5
@property<EOL><INDENT>def name(self):<DEDENT>
return self.record['<STR_LIT>']['<STR_LIT>']['<STR_LIT:name>']<EOL>
The short assay name, used for display purposes.
f498:c8:m6
@property<EOL><INDENT>def description(self):<DEDENT>
return self.record['<STR_LIT>']['<STR_LIT>']['<STR_LIT:description>']<EOL>
Description
f498:c8:m7
@property<EOL><INDENT>def project_category(self):<DEDENT>
if '<STR_LIT>' in self.record['<STR_LIT>']['<STR_LIT>']:<EOL><INDENT>return self.record['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']<EOL><DEDENT>
A category to distinguish projects funded through MLSCN, MLPCN or from literature. Possible values include mlscn, mlpcn, mlscn-ap, mlpcn-ap, literature-extracted, literature-author, literature-publisher, rnaigi.
f498:c8:m8
@property<EOL><INDENT>def comments(self):<DEDENT>
return [comment for comment in self.record['<STR_LIT>']['<STR_LIT>']['<STR_LIT>'] if comment]<EOL>
Comments and additional information.
f498:c8:m9
@property<EOL><INDENT>def results(self):<DEDENT>
return self.record['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']<EOL>
A list of dictionaries containing details of the results from this Assay.
f498:c8:m10
@property<EOL><INDENT>def target(self):<DEDENT>
if '<STR_LIT:target>' in self.record['<STR_LIT>']['<STR_LIT>']:<EOL><INDENT>return self.record['<STR_LIT>']['<STR_LIT>']['<STR_LIT:target>']<EOL><DEDENT>
A list of dictionaries containing details of the Assay targets.
f498:c8:m11
@property<EOL><INDENT>def revision(self):<DEDENT>
return self.record['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']<EOL>
Revision identifier for textual description.
f498:c8:m12
@property<EOL><INDENT>def aid_version(self):<DEDENT>
return self.record['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']['<STR_LIT:version>']<EOL>
Incremented when the original depositor updates the record.
f498:c8:m13
def platform_detect():
<EOL>pi = pi_version()<EOL>if pi is not None:<EOL><INDENT>return RASPBERRY_PI<EOL><DEDENT>plat = platform.platform()<EOL>if plat.lower().find('<STR_LIT>') > -<NUM_LIT:1>:<EOL><INDENT>return BEAGLEBONE_BLACK<EOL><DEDENT>elif plat.lower().find('<STR_LIT>') > -<NUM_LIT:1>:<EOL><INDENT>return BEAGLEBONE_BLACK<EOL><DEDENT>elif plat.lower().find('<STR_LIT>') > -<NUM_LIT:1>:<EOL><INDENT>return BEAGLEBONE_BLACK<EOL><DEDENT>elif plat.lower().find('<STR_LIT>') > -<NUM_LIT:1>:<EOL><INDENT>return BEAGLEBONE_BLACK<EOL><DEDENT>return UNKNOWN<EOL>
Detect if running on the Raspberry Pi or Beaglebone Black and return the platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN.
f501:m0
def pi_revision():
<EOL>with open('<STR_LIT>', '<STR_LIT:r>') as infile:<EOL><INDENT>for line in infile:<EOL><INDENT>match = re.match('<STR_LIT>', line, flags=re.IGNORECASE)<EOL>if match and match.group(<NUM_LIT:1>) in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>elif match:<EOL><INDENT>return <NUM_LIT:2><EOL><DEDENT><DEDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>
Detect the revision number of a Raspberry Pi, useful for changing functionality like default I2C bus based on revision.
f501:m1
def pi_version():
<EOL>with open('<STR_LIT>', '<STR_LIT:r>') as infile:<EOL><INDENT>cpuinfo = infile.read()<EOL><DEDENT>match = re.search('<STR_LIT>', cpuinfo,<EOL>flags=re.MULTILINE | re.IGNORECASE)<EOL>if not match:<EOL><INDENT>return None<EOL><DEDENT>if match.group(<NUM_LIT:1>) == '<STR_LIT>':<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>elif match.group(<NUM_LIT:1>) == '<STR_LIT>':<EOL><INDENT>return <NUM_LIT:2><EOL><DEDENT>elif match.group(<NUM_LIT:1>) == '<STR_LIT>':<EOL><INDENT>return <NUM_LIT:3><EOL><DEDENT>elif match.group(<NUM_LIT:1>) == '<STR_LIT>':<EOL><INDENT>return <NUM_LIT:3><EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Detect the version of the Raspberry Pi. Returns either 1, 2, 3 or None depending on if it's a Raspberry Pi 1 (model A, B, A+, B+), Raspberry Pi 2 (model B+), Raspberry Pi 3,Raspberry Pi 3 (model B+) or not a Raspberry Pi.
f501:m2
def get_platform():
plat = platform_detect.platform_detect()<EOL>if plat == platform_detect.RASPBERRY_PI:<EOL><INDENT>version = platform_detect.pi_version()<EOL>if version == <NUM_LIT:1>:<EOL><INDENT>from . import Raspberry_Pi<EOL>return Raspberry_Pi<EOL><DEDENT>elif version == <NUM_LIT:2>:<EOL><INDENT>from . import Raspberry_Pi_2<EOL>return Raspberry_Pi_2<EOL><DEDENT>elif version == <NUM_LIT:3>:<EOL><INDENT>"""<STR_LIT>"""<EOL>from . import Raspberry_Pi_2<EOL>return Raspberry_Pi_2<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT><DEDENT>elif plat == platform_detect.BEAGLEBONE_BLACK:<EOL><INDENT>from . import Beaglebone_Black<EOL>return Beaglebone_Black<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>
Return a DHT platform interface for the currently detected platform.
f503:m0
def read(sensor, pin, platform=None):
if sensor not in SENSORS:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if platform is None:<EOL><INDENT>platform = get_platform()<EOL><DEDENT>return platform.read(sensor, pin)<EOL>
Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on specified pin and return a tuple of humidity (as a floating point value in percent) and temperature (as a floating point value in Celsius). Note that because the sensor requires strict timing to read and Linux is not a real time OS, a result is not guaranteed to be returned! In some cases this will return the tuple (None, None) which indicates the function should be retried. Also note the DHT sensor cannot be read faster than about once every 2 seconds. Platform is an optional parameter which allows you to override the detected platform interface--ignore this parameter unless you receive unknown platform errors and want to override the detection.
f503:m1
def read_retry(sensor, pin, retries=<NUM_LIT:15>, delay_seconds=<NUM_LIT:2>, platform=None):
for i in range(retries):<EOL><INDENT>humidity, temperature = read(sensor, pin, platform)<EOL>if humidity is not None and temperature is not None:<EOL><INDENT>return (humidity, temperature)<EOL><DEDENT>time.sleep(delay_seconds)<EOL><DEDENT>return (None, None)<EOL>
Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on specified pin and return a tuple of humidity (as a floating point value in percent) and temperature (as a floating point value in Celsius). Unlike the read function, this read_retry function will attempt to read multiple times (up to the specified max retries) until a good reading can be found. If a good reading cannot be found after the amount of retries, a tuple of (None, None) is returned. The delay between retries is by default 2 seconds, but can be overridden.
f503:m2
def login_open_sheet(oauth_key_file, spreadsheet):
try:<EOL><INDENT>scope = ['<STR_LIT>']<EOL>credentials = ServiceAccountCredentials.from_json_keyfile_name(oauth_key_file, scope)<EOL>gc = gspread.authorize(credentials)<EOL>worksheet = gc.open(spreadsheet).sheet1<EOL>return worksheet<EOL><DEDENT>except Exception as ex:<EOL><INDENT>print('<STR_LIT>')<EOL>print('<STR_LIT>', ex)<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>
Connect to Google Docs spreadsheet and return the first worksheet.
f508:m0
def read_prologs(filename):
results = {}<EOL>prolog = {}<EOL>heading_re = re.compile(r"<STR_LIT>")<EOL>heading = "<STR_LIT>"<EOL>content = "<STR_LIT>"<EOL>counter = <NUM_LIT:0><EOL>for line in open(filename):<EOL><INDENT>line = line.strip()<EOL>if line.startswith("<STR_LIT>"):<EOL><INDENT>if counter != <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>prolog = {}<EOL>heading = "<STR_LIT>"<EOL>content = "<STR_LIT>"<EOL>counter = counter + <NUM_LIT:1><EOL>continue<EOL><DEDENT>if line.startswith("<STR_LIT>"):<EOL><INDENT>counter = <NUM_LIT:0><EOL>if len(heading):<EOL><INDENT>prolog[heading] = content<EOL>content = "<STR_LIT>"<EOL><DEDENT>name = prolog['<STR_LIT:name>'].strip()<EOL>results[name] = prolog<EOL>prolog = None<EOL>continue<EOL><DEDENT>if counter == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>counter = counter + <NUM_LIT:1><EOL>if len(line) == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>match_head = heading_re.search(line)<EOL>if match_head is not None:<EOL><INDENT>if len(heading):<EOL><INDENT>prolog[heading] = content<EOL><DEDENT>heading = match_head.group(<NUM_LIT:1>).lower()<EOL>content = "<STR_LIT>"<EOL>continue<EOL><DEDENT>if line.startswith("<STR_LIT>"):<EOL><INDENT>content = content + line[<NUM_LIT:6>:] + "<STR_LIT:\n>"<EOL>continue<EOL><DEDENT>elif line == "<STR_LIT:*>":<EOL><INDENT>content = content + "<STR_LIT:\n>"<EOL>continue<EOL><DEDENT>if counter:<EOL><INDENT>raise ValueError("<STR_LIT>"+str(counter)+"<STR_LIT>" + line + "<STR_LIT:'>")<EOL><DEDENT><DEDENT>return results<EOL>
Given a filename, search for SST prologues and returns a dict where the keys are the name of the prolog (from the "Name" field) and the keys are another dict with keys correspding fo the SST labels in lowercase. prologs = read_prologs( filename ) Common SST labels are: name, purpose, lanugage, invocation, arguments, description, authors, notes etc.
f514:m0
def read_pal_version():
verfile = os.path.join("<STR_LIT>", "<STR_LIT>", "<STR_LIT>")<EOL>verstring = "<STR_LIT>"<EOL>for line in open(verfile):<EOL><INDENT>if line.startswith("<STR_LIT>"):<EOL><INDENT>match = re.search(r"<STR_LIT>", line)<EOL>if match:<EOL><INDENT>verstring = match.group(<NUM_LIT:1>)<EOL><DEDENT>break<EOL><DEDENT><DEDENT>(major, minor, patch) = verstring.split("<STR_LIT:.>")<EOL>return (verstring, major, minor, patch)<EOL>
Scans the PAL configure.ac looking for the version number. (vers, maj, min, patchlevel) = read_pal_version() Returns the version as a string and the major, minor and patchlevel version integers
f515:m0
def query(searchstr, outformat=FORMAT_BIBTEX, allresults=False):
logger.debug("<STR_LIT>".format(sstring=searchstr))<EOL>searchstr = '<STR_LIT>'+quote(searchstr)<EOL>url = GOOGLE_SCHOLAR_URL + searchstr<EOL>header = HEADERS<EOL>header['<STR_LIT>'] = "<STR_LIT>" % outformat<EOL>request = Request(url, headers=header)<EOL>response = urlopen(request)<EOL>html = response.read()<EOL>html = html.decode('<STR_LIT:utf8>')<EOL>tmp = get_links(html, outformat)<EOL>result = list()<EOL>if not allresults:<EOL><INDENT>tmp = tmp[:<NUM_LIT:1>]<EOL><DEDENT>for link in tmp:<EOL><INDENT>url = GOOGLE_SCHOLAR_URL+link<EOL>request = Request(url, headers=header)<EOL>response = urlopen(request)<EOL>bib = response.read()<EOL>bib = bib.decode('<STR_LIT:utf8>')<EOL>result.append(bib)<EOL><DEDENT>return result<EOL>
Query google scholar. This method queries google scholar and returns a list of citations. Parameters ---------- searchstr : str the query outformat : int, optional the output format of the citations. Default is bibtex. allresults : bool, optional return all results or only the first (i.e. best one) Returns ------- result : list of strings the list with citations
f517:m0
def get_links(html, outformat):
if outformat == FORMAT_BIBTEX:<EOL><INDENT>refre = re.compile(r'<STR_LIT>')<EOL><DEDENT>elif outformat == FORMAT_ENDNOTE:<EOL><INDENT>refre = re.compile(r'<STR_LIT>')<EOL><DEDENT>elif outformat == FORMAT_REFMAN:<EOL><INDENT>refre = re.compile(r'<STR_LIT>')<EOL><DEDENT>elif outformat == FORMAT_WENXIANWANG:<EOL><INDENT>refre = re.compile(r'<STR_LIT>')<EOL><DEDENT>reflist = refre.findall(html)<EOL>reflist = [re.sub('<STR_LIT>' % '<STR_LIT:|>'.join(name2codepoint), lambda m:<EOL>chr(name2codepoint[m.group(<NUM_LIT:1>)]), s) for s in reflist]<EOL>return reflist<EOL>
Return a list of reference links from the html. Parameters ---------- html : str outformat : int the output format of the citations Returns ------- List[str] the links to the references
f517:m1
def convert_pdf_to_txt(pdf, startpage=None):
if startpage is not None:<EOL><INDENT>startpageargs = ['<STR_LIT>', str(startpage)]<EOL><DEDENT>else:<EOL><INDENT>startpageargs = []<EOL><DEDENT>stdout = subprocess.Popen(["<STR_LIT>", "<STR_LIT>"] + startpageargs + [pdf, "<STR_LIT:->"],<EOL>stdout=subprocess.PIPE).communicate()[<NUM_LIT:0>]<EOL>if not isinstance(stdout, str):<EOL><INDENT>stdout = stdout.decode()<EOL><DEDENT>return stdout<EOL>
Convert a pdf file to text and return the text. This method requires pdftotext to be installed. Parameters ---------- pdf : str path to pdf file startpage : int, optional the first page we try to convert Returns ------- str the converted text
f517:m2