Пример #1
0
def depict_smile(genecluster, structuresfolder):
    indigo = Indigo()
    renderer = IndigoRenderer(indigo)
    query = indigo.loadMoleculeFromFile("genecluster" + str(genecluster) +
                                        ".smi")
    indigo.setOption("render-coloring", True)
    renderer.renderToFile(query, "genecluster" + str(genecluster) + ".png")

    indigo.setOption("render-image-size", 200, 150)
    renderer.renderToFile(query,
                          "genecluster" + str(genecluster) + "_icon.png")
    dircontents = os.listdir(os.getcwd())
    geneclusterstring = "genecluster" + str(genecluster) + ".png"
    if geneclusterstring in dircontents:
        shutil.copy("genecluster" + str(genecluster) + ".png",
                    structuresfolder)
        shutil.copy("genecluster" + str(genecluster) + "_icon.png",
                    structuresfolder)
        shutil.copy("genecluster" + str(genecluster) + ".smi",
                    structuresfolder)
        os.remove("genecluster" + str(genecluster) + ".png")
        os.remove("genecluster" + str(genecluster) + "_icon.png")
        os.remove("genecluster" + str(genecluster) + ".smi")
        smiles_input = path.join('SMILES', 'input')
        if path.exists(smiles_input):
            os.remove(smiles_input)
        return "success"
    else:
        return "failed"
Пример #2
0
    def filter(
        self,
        similarity: Union[BaseMatch] = None,
        exact: IndigoRecord = None,
        substructure: IndigoRecord = None,
        limit=10,
        **kwargs,
    ) -> Generator[IndigoRecord, None, None]:

        # actions needed to be called on elastic_search result
        postprocess_actions: PostprocessType = []

        query = self.__compile(
            similarity=similarity,
            exact=exact,
            substructure=substructure,
            limit=limit,
            postprocess_actions=postprocess_actions,
            **kwargs,
        )
        res = self.el_client.search(index=self.index_name, body=query)
        indigo_session = Indigo()
        for el_response in res.get("hits", {}).get("hits", []):
            record = get_record_by_index(el_response, self.index_name)
            for action_fn in postprocess_actions:
                record = action_fn(record, indigo_session)
                if not record:
                    continue
            yield record
class CompoundFaker(BaseProvider):
    compounds = COMPOUNDS
    indigo = Indigo()

    def molecule(self):
        smiles_str = self.random_element(self.compounds)
        return self.indigo.loadMolecule(smiles_str)

    def cid(self):
        return build_cid(self.random_int(2000000, 3000000))

    def molfile(self, v2000=False):
        if v2000:
            self.indigo.setOption("molfile-saving-mode", "2000")
        else:
            self.indigo.setOption("molfile-saving-mode", "3000")
        return self.molecule().molfile()

    def mrvfile(self):
        return format_mrvfile(self.molecule().cml())

    def molfile_v2000(self):
        smiles_str = self.random_element(self.compounds)
        self.indigo.setOption("molfile-saving-mode", "2000")
        return self.indigo.loadMolecule(smiles_str).molfile()

    def smile(self):
        return self.random_element(self.compounds)
Пример #4
0
def push(data):
    indigo = Indigo()
    compound = indigo.loadMolecule(data)
    indigo_record = IndigoRecordMolecule(indigo_object=compound)

    elasticRepository = elastic_repository_molecule()
    elasticRepository.index_record(record=indigo_record)
Пример #5
0
def search(data):
    indigo = Indigo()
    compound = indigo.loadMolecule(data)
    indigo_record = IndigoRecordMolecule(indigo_object=compound)

    elasticRepository = elastic_repository_molecule()
    return elasticRepository.filter(exact=indigo_record)
Пример #6
0
def iterate_file(
    file: Path,
    iterator: str = None,
    error_handler: Optional[Callable[[object, BaseException], None]] = None,
) -> Generator[IndigoRecordMolecule, None, None]:
    """
    :param file:
    :param iterator: supported iterators sdf, smiles, smi, cml.
                     If iterator is not set, trying to determine
                     iterator by file extension
    :type iterator: str
    :param error_handler: lambda for catching exceptions
    :type error_handler: Optional[Callable[[object, BaseException], None]]
    :return:
    """
    iterators = {
        "sdf": "iterateSDFile",
        "smiles": "iterateSmilesFile",
        "smi": "iterateSmilesFile",
        "cml": "iterateCMLFile",
    }
    if not iterator:
        iterator = file.suffix[1:]
    iterator_fn = iterators.get(iterator)
    if not iterator_fn:
        raise AttributeError(f"Unsupported iterator {iterator}")

    indigo_object: IndigoObject
    for indigo_object in getattr(Indigo(), iterator_fn)(str(file)):
        yield IndigoRecordMolecule(
            indigo_object=indigo_object, error_handler=error_handler
        )
Пример #7
0
def iterate_file(file: Path,
                 iterator: str = None) -> Generator[IndigoRecord, None, None]:
    """
    :param file:
    :param iterator: supported iterators sdf, smiles, smi, cml.
                     If iterator is not set, trying to determine
                     iterator by file extension
    :type iterator: str
    :return:
    """
    iterators = {
        "sdf": "iterateSDFile",
        "smiles": "iterateSmilesFile",
        "smi": "iterateSmilesFile",
        "cml": "iterateCMLFile",
    }
    if not iterator:
        iterator = file.suffix[1:]
    iterator_fn = iterators.get(iterator)
    if not iterator_fn:
        raise AttributeError(f"Unsupported iterator {iterator}")

    indigo_object: IndigoObject
    for indigo_object in getattr(Indigo(), iterator_fn)(str(file)):
        yield IndigoRecord(indigo_object=indigo_object)
Пример #8
0
def resetIndigo():
    global indigo, indigoRenderer, indigoInchi

    indigo = Indigo()
    indigoRenderer = IndigoRenderer(indigo)
    indigoInchi = IndigoInchi(indigo)

    # Set default options
    indigo.setOption('render-bond-length', '30')
    indigo.setOption('render-relative-thickness', '1.3')
    indigo.setOption('render-coloring', False)
    indigo.setOption('render-comment-font-size', 14.0)
    indigo.setOption('render-comment-offset', '10')
def get_molfile_v3000(compound: str) -> str:
    """Computes the molfile v3000 from a compound string.

    Args:
        compound: A molfile (either v2000 or v3000), MRV file, etc.

    Returns:
        The molfile v3000.

    """
    indigo = Indigo()
    indigo.setOption("molfile-saving-mode", "3000")
    molecule = indigo.loadMolecule(compound)
    return molecule.molfile()
Пример #10
0
 def wrapper():
     indigo = Indigo()
     opts = request.json.get('options', {})
     for key, value in opts.items():
         try:
             indigo.setOption(key, value)
         except IndigoException as e:
             pass
     mol_text = request.json.get("struct")
     try:
         mol = indigo.loadMolecule(mol_text)
     except IndigoException as e:
         return jsonify({'msg': str(e)})
     return func(mol)
Пример #11
0
def get_inchikey(compound: str) -> str:
    """Computes the InChIKey from a compound string.

    Args:
        compound: A molfile (either v2000 or v3000), MRV file, SMILES, etc.

    Returns:
        The InChIKey for the compound.

    """
    indigo = Indigo()
    indigo_inchi = IndigoInchi(indigo)
    molecule = indigo.loadMolecule(compound)
    inchi = indigo_inchi.getInchi(molecule)
    return indigo_inchi.getInchiKey(inchi)
Пример #12
0
def indigo_init(options={}):
    try:
        tls.indigo = Indigo()
        tls.indigo.inchi = IndigoInchi(tls.indigo)
        tls.indigo.renderer = IndigoRenderer(tls.indigo)
        for option, value in indigo_api.indigo_defaults.items():
            tls.indigo.setOption(option, value)
        for option, value in options.items():
            # TODO: Remove this when Indigo API supports smiles type option
            if option in {'smiles', }:
                continue
            tls.indigo.setOption(option, value)
        return tls.indigo
    except Exception as e:
        indigo_api_logger.error('indigo-init: {0}'.format(e))
        return None
Пример #13
0
    def parseMolecule(self):
        '''
        turn the input into a toolkit molecule according to user settings

        indigo is supposed to read transparently, so we can do away with
        the format setting, basically. If it's numeric, we ask pubchem,
        if it isn't, we consider it a molecule.
        '''
        rawinput = self.data_string

        try:
            pubchemId = int(rawinput)
        except ValueError:
            pubchemId = None

        if pubchemId is not None:
            try:
                url = common.pubchem_url % pubchemId
                pubchemContent = urllib.urlopen(url).read()
            except IOError:
                raise common.MCFError, 'No connection to PubChem'

            self.data_string = pubchemContent

        #common.debug('rpc: %s' % self.rpc)
        #common.debug('data ---\n%s\n---' % self.data_string)

        try:
            tkmol = Indigo().loadMolecule(self.data_string)
        except IndigoException:
            raise common.MCFError, "Invalid input data"

        hydrogens = self.options['hydrogens']

        if hydrogens == 'add':
            tkmol.unfoldHydrogens()
            tkmol.layout()  # needed to give coordinates to added Hs

        elif hydrogens == 'delete':
            tkmol.foldHydrogens()

        if not tkmol.hasCoord() or self.options['recalculate_coordinates']:
            tkmol.layout()

        return tkmol
Пример #14
0
def smiles(smiles_string):
    # Render SMILES to PNG
    indigo = Indigo()
    renderer = IndigoRenderer(indigo)

    mol = indigo.loadMolecule(smiles_string)
    mol.layout()  # if not called, will be done automatically by the renderer
    indigo.setOption("render-output-format", "png")
    indigo.setOption("render-image-size", 250, 250)
    indigo.setOption("render-background-color", 1.0, 1.0, 1.0)
    indigo.setOption("render-coloring", True)

    indigo.setOption("aromaticity-model", "generic")
    mol.dearomatize()

    buf = renderer.renderToBuffer(mol)
    buf = io.BytesIO(buf)

    return send_file(
        buf,
        mimetype='image/png',
        as_attachment=False,
    )
def indigo_atom_map_reaction(rxn_smiles: str,
                             timeout_period: int,
                             existing_mapping="discard",
                             verbose=False):

    try:
        # Instantiate the Indigo class object and set the timeout period.
        indigo_mapper = Indigo()
        indigo_mapper.setOption("aam-timeout", timeout_period)

        # Return the atom mapping of the reaction SMILES string.
        rxn = indigo_mapper.loadReaction(rxn_smiles)
        rxn.automap(existing_mapping)

        return rxn.smiles()

    # If an exception occurs for any reason, print the message if indicated, and return None.
    except Exception as exception:
        if verbose:
            print(
                "Exception occured during atom mapping of the reaction SMILES. Detailed message: {}"
                .format(exception))

        return None
Пример #16
0
def indigo_fixture() -> Indigo:
    return Indigo()
Пример #17
0
 def wrapper():
     indigo = Indigo()
     opts = request.json.get('options', {})
     for key, value in opts.items():
         indigo.setOption(key, value)
     return func()
Пример #18
0
import traceback
import types

from indigo import Indigo
from indigo_renderer import IndigoRenderer
from indigo_inchi import IndigoInchi

from .celery_app import celery
import config

from .common.util import api_route

imago_api = Blueprint('imago', __name__)
imago_api_logger = logging.getLogger('imago')
imago_api.config = config.__dict__
imago_api.indigo = Indigo()
imago_api.renderer = IndigoRenderer(imago_api.indigo)
imago_api.indigo_inchi = IndigoInchi(imago_api.indigo)
imago_api_app = flask_restful.Api(imago_api)
imago_api_app.route = types.MethodType(api_route, imago_api_app)
allowed_types = imago_api.config['ALLOWED_TYPES']

versions = []
with open('/srv/service_version', 'r') as ver:
    for line in ver.readlines():
        if line.startswith("imago-console-"):
            versions.append(re.search('imago-console-(.*)\..*', line).group(1))


@celery.task(bind=True)
def recognize_image(self, args):
Пример #19
0
 def indigo_structure(self):
     indigo = Indigo()
     indigo.setOption("molfile-saving-mode", "3000")
     return indigo.loadStructure(structureStr=self.molfile_v3000)
Пример #20
0
from marshmallow.exceptions import ValidationError

import config
from .db.BingoPostgresAdapter import BingoPostgresAdapter
from .db.models import LibraryMeta, User as Usermodel
from .db.database import db_session
from .common.util import item_to_sdf_chunk, merge_dicts, api_route
from .celery_app import celery

from .validation import LibrarySchema, SearcherSchema, UserSchema

libraries_api = Blueprint('libraries_api', __name__)

if not os.path.exists(config.__dict__['UPLOAD_FOLDER']):
    os.makedirs(config.__dict__['UPLOAD_FOLDER'])
libraries_api.indigo = Indigo()
libraries_api.renderer = IndigoRenderer(libraries_api.indigo)
libraries_api.indigo_inchi = IndigoInchi(libraries_api.indigo)
libraries_api.config = config.__dict__
libraries_api.adapter = BingoPostgresAdapter(libraries_api.config,
                                             libraries_api.indigo,
                                             libraries_api.indigo_inchi)
libraries_api.redis = redis.StrictRedis(host='localhost', port=6379, db=0)
libraries_api_app = flask_restful.Api(libraries_api)
libraries_api_logger = logging.getLogger('libraries')
#libraries_api_logger.addHandler(logging.FileHandler('/srv/api/app.log'))
auth = HTTPBasicAuth()
libraries_api_app.route = types.MethodType(api_route, libraries_api_app)


@auth.verify_password
Пример #21
0
"""
Categorize flavonoids according to the input molecule.
"""
import itertools
from indigo import Indigo
from itertools import combinations, product

from chalcone_class import Chalcone


idg = Indigo()
CHAIN = idg.CHAIN
RING = idg.RING


def getskidx(ringidx, sk):
    """ get the indices of atoms in identified skeletons """
    skix = []
    for ski in sk:
        tix = []
        for i in ski[0]:
            tix += ringidx[i]
        tix += ski[1:-1]
        skix.append(tix)
    return skix


# TO DO
def _checkXanthSK(molobj):
    """
    Get skeleton of Xanthones.
Пример #22
0
import time
from pathlib import Path

from bingo_elastic.model.record import IndigoRecord
from bingo_elastic.queries import SimilarityMatch
from bingo_elastic.elastic import ElasticRepository
from bingo_elastic.model import helpers
from indigo import Indigo

if __name__ == '__main__':
    indigo = Indigo()
    start_time = time.time()

    repository = ElasticRepository(host="127.0.0.1", port=9200)
    # try:
    #     sdf = helpers.iterate_sdf("../data/pubchem/Compound_000000001_000500000.sdf")
    #     repository.index_records(sdf)
    # except ValueError as e:
    #     print(e)
    #
    #
    # time.sleep(300)

    print(
        "--- {} seconds for reading and indexing data ---".format(time.time() -
                                                                  start_time))

    mol = indigo.loadMolecule(
        "Cc1ccc2nc(-c3ccc(NC(C4N(C(c5cccs5)=O)CCC4)=O)cc3)sc2c1")
    target = IndigoRecord(indigo_object=mol)
Пример #23
0
 def setUp(self) -> None:
     self.indigo = Indigo()
Пример #24
0
 def test_init(self):
     indigo = Indigo()
     indigo_render = IndigoRenderer(indigo)
     self.assertIsNotNone(indigo_render)