File: MolImage.py

package info (click to toggle)
rdkit 202503.6-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 222,000 kB
  • sloc: cpp: 411,111; python: 78,482; ansic: 26,181; java: 8,285; javascript: 4,404; sql: 2,393; yacc: 1,626; lex: 1,267; cs: 1,090; makefile: 581; xml: 229; fortran: 183; sh: 121
file content (74 lines) | stat: -rw-r--r-- 1,947 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# $Id$
#
#  Copyright (C) 2004, 2005 Rational Discovery LLC
#  All Rights Reserved
#
import os
import sys
import tempfile

import Chem
from Chem import TemplateAlign
from Chem.Draw.MolDrawing import MolDrawing
from mod_python import apache
from sping.SVG.pidSVG import SVGCanvas as Canvas
from utils import cactvs


def gif(req, smiles, width=100, height=100, highlight='[]', frame=0, dblSize=0, **kwargs):
  req.content_type = 'image/gif'
  width = int(width)
  height = int(height)
  frame = int(frame)
  dblSize = int(dblSize)

  # FIX: unsafe:
  highlight = eval(highlight)
  imgD = ''
  if smiles:
    fName = tempfile.NamedTemporaryFile(suffix='.gif', delete=False).name
    cactvs.SmilesToGif(smiles, fName, (width, height), dblSize=dblSize, frame=frame)
    if os.path.exists(fName):
      imgD = open(fName, 'rb').read()
      try:
        os.unlink(fName)
      except OSError:
        pass
  return imgD


def svg(req, smiles, width=100, height=100, highlight='[]', frame=0, template='', numbers=0,
        **kwargs):
  req.content_type = 'image/svg+xml'
  width = int(width)
  height = int(height)
  frame = int(frame)
  # FIX: unsafe:
  highlight = eval(highlight)
  imgD = ''
  mol = None
  if smiles:
    mol = Chem.MolFromSmiles(smiles)
  if mol:
    if kwargs.get('kekulize', True):
      Chem.Kekulize(mol)
    if template and highlight:
      try:
        patt = Chem.MolFromSmiles(template)
        Chem.Compute2DCoords(patt)
        TemplateAlign.AlignMolToTemplate2D(mol, patt, highlight)
      except Exception:
        Chem.Compute2DCoords(mol)
    else:
      Chem.Compute2DCoords(mol)
    canvas = Canvas(size=(width, height))
    drawer = MolDrawing(canvas=canvas)
    if numbers and numbers != '0':
      drawer.includeAtomNumbers = True
      drawer.atomNumberOffset = 1
    drawer.noCarbonSymbols = 1
    drawer.AddMol(mol, highlightAtoms=highlight)
    svg = canvas._txt + '</svg>'
  else:
    svg = ''
  return svg