"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "modules/pymol/importing.py" between
pymol-v1.8.6.0.tar.bz2 and pymol-v2.1.0.tar.bz2

About: PyMOL is a Python-enhanced molecular graphics tool. It excels at 3D visualization of proteins, small molecules, density, surfaces, and trajectories. It also includes molecular editing, ray tracing, and movies. Open Source version.

importing.py  (pymol-v1.8.6.0.tar.bz2):importing.py  (pymol-v2.1.0.tar.bz2)
skipping to change at line 28 skipping to change at line 28
import re import re
import os import os
import sys import sys
import copy import copy
import traceback import traceback
import pymol import pymol
cmd = sys.modules["pymol.cmd"] cmd = sys.modules["pymol.cmd"]
from . import setting from . import setting
from . import selector from . import selector
from . import colorprinting
from .cmd import _cmd,lock,unlock,Shortcut, \ from .cmd import _cmd,lock,unlock,Shortcut, \
_feedback,fb_module,fb_mask, \ _feedback,fb_module,fb_mask, \
DEFAULT_ERROR, DEFAULT_SUCCESS, _raising, is_ok, is_error, \ DEFAULT_ERROR, DEFAULT_SUCCESS, _raising, is_ok, is_error, \
_load, is_list, space_sc, safe_list_eval, is_string, loadable _load, is_list, space_sc, safe_list_eval, is_string, loadable
from .constants import _loadable from .constants import _loadable
from pymol.creating import unquote
def incentive_format_not_available_func(format=''): def incentive_format_not_available_func(format=''):
raise pymol.IncentiveOnlyException( raise pymol.IncentiveOnlyException(
"'%s' format not supported by this PyMOL build" % format) "'%s' format not supported by this PyMOL build" % format)
try:
from pymol.m4x import readcex
except ImportError:
def readcex():
raise pymol.CmdException("CEX format not currently supported")
from chempy import io,PseudoFile from chempy import io,PseudoFile
# TODO remove (keep for now for eventual legacy uses in scripts) # TODO remove (keep for now for eventual legacy uses in scripts)
loadable_sc = Shortcut(loadable.__dict__.keys()) loadable_sc = Shortcut(loadable.__dict__.keys())
def filename_to_objectname(fname, _self=cmd): def filename_to_objectname(fname, _self=cmd):
oname, _, _, _ = filename_to_format(fname) oname, _, _, _ = filename_to_format(fname)
return _self.get_legal_name(oname) return _self.get_legal_name(oname)
def filename_to_format(filename): def filename_to_format(filename):
skipping to change at line 284 skipping to change at line 280
cmd.space(string space, float gamma) cmd.space(string space, float gamma)
SEE ALSO SEE ALSO
color color
''' '''
r = DEFAULT_ERROR r = DEFAULT_ERROR
tables = { 'cmyk' : "$PYMOL_PATH/data/pymol/cmyk.png", tables = { 'cmyk' : "$PYMOL_DATA/pymol/cmyk.png",
'pymol' : 'pymol', 'pymol' : 'pymol',
'rgb' : 'rgb', 'rgb' : 'rgb',
'greyscale': 'greyscale' } 'greyscale': 'greyscale' }
space_auto = space_sc.interpret(space) space_auto = space_sc.interpret(space)
if (space_auto != None) and not is_list(space_auto): if (space_auto != None) and not is_list(space_auto):
space = space_auto space = space_auto
if space=="": if space=="":
filename = "" filename = ""
skipping to change at line 423 skipping to change at line 419
shift = safe_list_eval(str(shift)) # dangerous shift = safe_list_eval(str(shift)) # dangerous
if is_list(shift): if is_list(shift):
shift = [float(shift[0]),float(shift[1]),float(shift[2])] shift = [float(shift[0]),float(shift[1]),float(shift[2])]
else: else:
shift = [float(shift),float(shift),float(shift)] shift = [float(shift),float(shift),float(shift)]
# preprocess selection # preprocess selection
selection = selector.process(selection) selection = selector.process(selection)
# #
filename = unquote(filename)
noext, ext, format_guessed, zipped = filename_to_format(filename) noext, ext, format_guessed, zipped = filename_to_format(filename)
fname = _self.exp_path(filename) fname = _self.exp_path(filename)
if zipped: if zipped:
raise pymol.CmdException('zipped (%s) trajectories not supported ' % (zipped)) raise pymol.CmdException('zipped (%s) trajectories not supported ' % (zipped))
if not format: if not format:
format = format_guessed format = format_guessed
if not plugin: if not plugin:
skipping to change at line 519 skipping to change at line 517
def _processPWG(fname,_self=cmd): def _processPWG(fname,_self=cmd):
r = DEFAULT_ERROR r = DEFAULT_ERROR
if sys.version_info[0] < 3: if sys.version_info[0] < 3:
import urllib import urllib
else: else:
import urllib.request as urllib import urllib.request as urllib
try: try:
from web.pymolhttpd import PymolHttpd from .pymolhttpd import PymolHttpd
browser_flag = 0 browser_flag = 0
launch_flag = 0 launch_flag = 0
report_url = None report_url = None
logging = 1 logging = 1
root = None root = None
port = 0 port = 0
wrap_native = 0 wrap_native = 0
if ':' in fname: if '://' in fname:
lines = urllib.urlopen(fname).readlines() lines = urllib.urlopen(fname).readlines()
else: else:
lines = open(fname).readlines() lines = open(fname).readlines()
for line in lines: for line in lines:
line = line.strip() line = line.strip()
if len(line) and line[0:1] != '#': if len(line) and line[0:1] != '#':
input = line.split(None,1) input = line.split(None,1)
if len(input) and input[0]!='#': if len(input) and input[0]!='#':
keyword = input[0].lower() keyword = input[0].lower()
if keyword == 'port': # will be assigned dynamically if not specified if keyword == 'port': # will be assigned dynamically if not specified
skipping to change at line 615 skipping to change at line 613
def _magic_check_cor_charmm(filename): def _magic_check_cor_charmm(filename):
# http://www.ks.uiuc.edu/Research/vmd/plugins/molfile/corplugin.html # http://www.ks.uiuc.edu/Research/vmd/plugins/molfile/corplugin.html
# assume at least 2 title/comment lines, starting with * # assume at least 2 title/comment lines, starting with *
with open(filename) as handle: with open(filename) as handle:
if (handle.readline().startswith('*') and if (handle.readline().startswith('*') and
handle.readline().startswith('*')): handle.readline().startswith('*')):
return True return True
return False return False
def _epymol_get_load_func(format): def _eval_func(func):
func = None '''
Evaluate a "module:callable" signature, e.g. "os.path:dirname".
'''
if not isinstance(func, str):
return func
try: try:
if format == 'vis': m = __import__(func.split(':')[0])
from epymol.vis import load_vis as func except ImportError as e:
elif format == 'moe': print(' Warning: ' + str(e))
from epymol.moe import read_moestr as func return incentive_format_not_available_func
elif format == 'phypo':
from epymol.ph4 import load_phypo as func return eval(func.replace(':', '.'), {m.__name__: m}, {})
except ImportError:
func = incentive_format_not_available_func
return func
def load(filename, object='', state=0, format='', finish=1, def load(filename, object='', state=0, format='', finish=1,
discrete=-1, quiet=1, multiplex=None, zoom=-1, partial=0, discrete=-1, quiet=1, multiplex=None, zoom=-1, partial=0,
mimic=1, object_props=None, atom_props=None, _self=cmd): mimic=1, object_props=None, atom_props=None, _self=cmd):
''' '''
DESCRIPTION DESCRIPTION
"load" can by used to read molecules, crystallographic maps and "load" can by used to read molecules, crystallographic maps and
other volumetric data, PyMOL sessions, and some other types of other volumetric data, PyMOL sessions, and some other types of
content. content.
skipping to change at line 707 skipping to change at line 707
try: try:
_self.lock(_self) _self.lock(_self)
plugin = '' plugin = ''
state = int(state) state = int(state)
finish = int(finish) finish = int(finish)
zoom = int(zoom) zoom = int(zoom)
discrete = int(discrete) discrete = int(discrete)
if multiplex==None: if multiplex==None:
multiplex=-2 multiplex=-2
filename = unquote(filename)
# analyze filename # analyze filename
noext, ext, format_guessed, zipped = filename_to_format(filename) noext, ext, format_guessed, zipped = filename_to_format(filename)
filename = _self.exp_path(filename)
# file format # file format
try: try:
# user specified the type as an int # user specified the type as an int
ftype = int(format) ftype = int(format)
format = loadable._reverse_lookup(format) format = loadable._reverse_lookup(format)
except ValueError: except ValueError:
format = str(format) format = str(format)
if not format: if not format:
format = format_guessed format = format_guessed
elif format.startswith('plugin'): elif format.startswith('plugin'):
format, _, plugin = format.partition(':') format, _, plugin = format.partition(':')
else: else:
ext = format ext = format
if format == 'pkl': if format == 'pkl':
format = 'model' # legacy format = 'model' # legacy
ftype = getattr(_loadable, format, -1) ftype = getattr(_loadable, format, -1)
if ftype not in _self._load2str.values():
filename = _self.exp_path(filename)
# object name # object name
object = str(object).strip() object = str(object).strip()
if not object: if not object:
object = noext if noext else _self.get_unused_name('obj') object = noext if noext else _self.get_unused_name('obj')
if format in ['dcd', 'dtr']: if format in ['dcd', 'dtr']:
# for trajectories, use most recently added structure # for trajectories, use most recently added structure
object = _guess_trajectory_object(object, _self) object = _guess_trajectory_object(object, _self)
# deferred (circular imports)
if format not in loadfunctions:
func = _epymol_get_load_func(format)
if func is not None:
loadfunctions[format] = func
# molfile plugins # molfile plugins
if (ftype < 0 and format not in loadfunctions or if (ftype < 0 and format not in loadfunctions or
format == 'plugin' and not plugin): format == 'plugin' and not plugin):
plugin = _cmd.find_molfile_plugin(_self._COb, ext) plugin = _cmd.find_molfile_plugin(_self._COb, ext)
if not plugin: if not plugin:
raise pymol.CmdException('unsupported file type: ' + ext) raise pymol.CmdException('unsupported file type: ' + ext)
ftype = loadable.plugin ftype = loadable.plugin
# special handling for trj files (autodetect AMBER versus GROMACS) # special handling for trj files (autodetect AMBER versus GROMACS)
if ftype == loadable.trj and check_gromacs_trj_magic(filename): if ftype == loadable.trj and check_gromacs_trj_magic(filename):
ftype = loadable.trj2 ftype = loadable.trj2
# special handling for cdr files (autodetect AMBER versus CHARMM) # special handling for cdr files (autodetect AMBER versus CHARMM)
if ftype == loadable.crd and _magic_check_cor_charmm(filename): if ftype == loadable.crd and _magic_check_cor_charmm(filename):
ftype = loadable.plugin ftype = loadable.plugin
plugin = 'cor' plugin = 'cor'
# generic forwarding to format specific load functions # generic forwarding to format specific load functions
func = loadfunctions.get(format, _load) func = loadfunctions.get(format, _load)
func = _eval_func(func)
kw = { kw = {
'filename': filename, 'filename': filename,
'fname': filename, # alt 'fname': filename, # alt
'object': object, 'object': object,
'prefix': object, # alt 'prefix': object, # alt
'state': state, 'state': state,
'format': format, 'format': format,
'finish': finish, 'finish': finish,
'discrete': discrete, 'discrete': discrete,
'quiet': quiet, 'quiet': quiet,
skipping to change at line 809 skipping to change at line 808
finally: finally:
_self.unlock(r,_self) _self.unlock(r,_self)
if _self._raising(r,_self): raise pymol.CmdException if _self._raising(r,_self): raise pymol.CmdException
return r return r
def load_pse(filename, partial=0, quiet=1, format='pse', _self=cmd): def load_pse(filename, partial=0, quiet=1, format='pse', _self=cmd):
try: try:
contents = _self.file_read(filename) contents = _self.file_read(filename)
session = io.pkl.fromString(contents) session = io.pkl.fromString(contents)
except AttributeError as e: except AttributeError as e:
raise pymol.CmdException('PSE contains objects which cannot be unpic kled (%s)' % e.message) raise pymol.CmdException('PSE contains objects which cannot be unpic kled (%s)' % str(e))
r = _self.set_session(session, quiet=quiet, partial=partial, steal=1) r = _self.set_session(session, quiet=quiet, partial=partial, steal=1)
if not partial: if not partial:
_self.set("session_file", _self.set("session_file",
# always use unix-like path separators # always use unix-like path separators
filename.replace("\\", "/"), quiet=1) filename.replace("\\", "/"), quiet=1)
if ((format == 'psw' or if ((format == 'psw' or
_self.get_setting_boolean("presentation")) and _self.get_setting_boolean("presentation")) and
skipping to change at line 1140 skipping to change at line 1139
"http://files.rcsb.org/download/{code}.{type}.gz", "http://files.rcsb.org/download/{code}.{type}.gz",
"/data/biounit/coordinates/divided/{mid}/{code}.{type}.gz", "/data/biounit/coordinates/divided/{mid}/{code}.{type}.gz",
], ],
"pdb" : [ "pdb" : [
"http://files.rcsb.org/download/{code}.{type}.gz", "http://files.rcsb.org/download/{code}.{type}.gz",
"/data/structures/divided/pdb/{mid}/pdb{code}.ent.gz", "/data/structures/divided/pdb/{mid}/pdb{code}.ent.gz",
], ],
"cif" : [ "cif" : [
"http://files.rcsb.org/download/{code}.{type}.gz", "http://files.rcsb.org/download/{code}.{type}.gz",
"/data/structures/divided/mmCIF/{mid}/{code}.cif.gz", "/data/structures/divided/mmCIF/{mid}/{code}.cif.gz",
"http://ftp-versioned.wwpdb.org/pdb_versioned/views/latest/coordinat es/mmcif/{mid}/pdb_{code:0>8}/pdb_{code:0>8}_xyz.cif.gz",
], ],
"2fofc" : "http://www.ebi.ac.uk/pdbe/coordinates/files/{code}.ccp4", "2fofc" : "https://www.ebi.ac.uk/pdbe/coordinates/files/{code}.ccp4",
"fofc" : "http://www.ebi.ac.uk/pdbe/coordinates/files/{code}_diff.ccp4", "fofc" : "https://www.ebi.ac.uk/pdbe/coordinates/files/{code}_diff.ccp4"
,
"pubchem": [ "pubchem": [
"http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?{type}={code}&d isopt=3DSaveSDF", "http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?{type}={code}&d isopt=3DSaveSDF",
"http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?{type}={code}&d isopt=SaveSDF", "http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?{type}={code}&d isopt=SaveSDF",
], ],
"emd": "ftp://ftp.wwpdb.org/pub/emdb/structures/EMD-{code}/map/emd_{code }.map.gz", "emd": "ftp://ftp.wwpdb.org/pub/emdb/structures/EMD-{code}/map/emd_{code }.map.gz",
"cc": [ "cc": [
"http://files.rcsb.org/ligands/download/{code}.cif", "http://files.rcsb.org/ligands/download/{code}.cif",
"ftp://ftp.ebi.ac.uk/pub/databases/msd/pdbechem/files/mmcif/{code}.c if", "ftp://ftp.ebi.ac.uk/pub/databases/msd/pdbechem/files/mmcif/{code}.c if",
], ],
} }
skipping to change at line 1171 skipping to change at line 1171
discrete = bool: make discrete multi-state object discrete = bool: make discrete multi-state object
multiplex = bool: split states into objects (like split_states) multiplex = bool: split states into objects (like split_states)
zoom = int: zoom to new loaded object zoom = int: zoom to new loaded object
type = str: fofc, 2fofc, pdb, pdb1, ... type = str: fofc, 2fofc, pdb, pdb1, ...
path = str: fetch_path path = str: fetch_path
file = str or file: file name or open file handle file = str or file: file name or open file handle
''' '''
r = DEFAULT_ERROR r = DEFAULT_ERROR
fetch_host_list = [x if '://' in x else fetchHosts[x] fetch_host_list = [x if '://' in x else fetchHosts[x]
for x in _self.get("fetch_host", _self=_self).split()] for x in _self.get("fetch_host").split()]
# file types can be: fofc, 2fofc, pdb, pdb1, pdb2, pdb3, etc... # file types can be: fofc, 2fofc, pdb, pdb1, pdb2, pdb3, etc...
# bioType is the string representation of the type # bioType is the string representation of the type
# nameFmt is the file name pattern after download # nameFmt is the file name pattern after download
bioType = type bioType = type
nameFmt = '{code}.{type}' nameFmt = '{code}.{type}'
if type == 'pdb': if type == 'pdb':
pass pass
elif type in ('fofc', '2fofc'): elif type in ('fofc', '2fofc'):
nameFmt = '{code}_{type}.ccp4' nameFmt = '{code}_{type}.ccp4'
skipping to change at line 1221 skipping to change at line 1221
file = os.path.join(path, nameFmt.format(code=code, type=type)) file = os.path.join(path, nameFmt.format(code=code, type=type))
if not is_string(file): if not is_string(file):
fobj = file fobj = file
file = None file = None
elif os.path.exists(file): elif os.path.exists(file):
# skip downloading # skip downloading
url_list = [] url_list = []
for url in url_list: for url in url_list:
url = url.format(mid=code[1:3], code=code, type=type) url = url.format(mid=code[-3:-1], code=code, type=type)
try: try:
contents = _self.file_read(url) contents = _self.file_read(url)
# assume HTML content means error on server side without error H TTP code # assume HTML content means error on server side without error H TTP code
if b'<html' in contents[:500].lower(): if b'<html' in contents[:500].lower():
raise pymol.CmdException raise pymol.CmdException
except pymol.CmdException: except pymol.CmdException:
if not quiet: if not quiet:
print(" Warning: failed to fetch from", url) colorprinting.warning(" Warning: failed to fetch from %s" % (url,))
continue continue
if file: if file:
try: try:
fobj = open(file, 'wb') fobj = open(file, 'wb')
except IOError: except IOError:
print(' Warning: Cannot write to "%s"' % file) colorprinting.warning(' Warning: Cannot write to "%s"' % fil e)
if fobj: if fobj:
fobj.write(contents) fobj.write(contents)
fobj.flush() fobj.flush()
if file: if file:
fobj.close() fobj.close()
if not file: if not file:
return DEFAULT_SUCCESS return DEFAULT_SUCCESS
skipping to change at line 1268 skipping to change at line 1268
elif contents and bioType in ('cif', 'cc'): elif contents and bioType in ('cif', 'cc'):
r = _self.load(contents, name, state, loadable.cifstr, r = _self.load(contents, name, state, loadable.cifstr,
finish, discrete, quiet, multiplex, zoom) finish, discrete, quiet, multiplex, zoom)
elif contents and bioType in ('mmtf',): elif contents and bioType in ('mmtf',):
r = _self.load(contents, name, state, loadable.mmtfstr, r = _self.load(contents, name, state, loadable.mmtfstr,
finish, discrete, quiet, multiplex, zoom) finish, discrete, quiet, multiplex, zoom)
if not _self.is_error(r): if not _self.is_error(r):
return name return name
print(" Error-fetch: unable to load '%s'." % code) colorprinting.error(" Error-fetch: unable to load '%s'." % code)
return DEFAULT_ERROR return DEFAULT_ERROR
def _multifetch(code,name,state,finish,discrete,multiplex,zoom,type,path,fil e,quiet,_self): def _multifetch(code,name,state,finish,discrete,multiplex,zoom,type,path,fil e,quiet,_self):
import string import string
r = DEFAULT_SUCCESS r = DEFAULT_SUCCESS
code_list = code.split() code_list = code.split()
name = name.strip() name = name.strip()
if (name!='') and (len(code_list)>1) and (discrete<0): if (name!='') and (len(code_list)>1) and (discrete<0):
discrete = 1 # by default, select discrete when loading discrete = 1 # by default, select discrete when loading
# multiple PDB entries into a single object # multiple PDB entries into a single object
all_type = type all_type = type
for obj_code in code_list: for obj_code in code_list:
obj_name = name obj_name = name
type = all_type type = all_type
if not type:
if 1 < len(obj_code) < 4:
type = 'cc'
else:
type = _self.get('fetch_type_default')
# allow fetching codes like EMD-3489 or emd_3489 # allow fetching codes like EMD-3489 or emd_3489
if obj_code[3:4] in ('_', '-') and \ if obj_code[3:4] in ('_', '-') and \
obj_code[:3].upper() in ('CID', 'SID', 'EMD'): obj_code[:3].upper() in ('CID', 'SID', 'EMD'):
if not obj_name: if not obj_name:
obj_name = obj_code obj_name = obj_code
type = obj_code[:3].lower() type = obj_code[:3].lower()
obj_code = obj_code[4:] obj_code = obj_code[4:]
if not obj_name: if not obj_name:
obj_name = obj_code obj_name = obj_code
skipping to change at line 1318 skipping to change at line 1324
if chain and isinstance(r, str): if chain and isinstance(r, str):
if _self.count_atoms(r'?%s & c. \%s' % (r, chain)) == 0: if _self.count_atoms(r'?%s & c. \%s' % (r, chain)) == 0:
_self.delete(r) _self.delete(r)
raise pymol.CmdException('no such chain: ' + chain) raise pymol.CmdException('no such chain: ' + chain)
_self.remove(r'?%s & ! c. \%s' % (r, chain)) _self.remove(r'?%s & ! c. \%s' % (r, chain))
return r return r
def fetch(code, name='', state=0, finish=1, discrete=-1, def fetch(code, name='', state=0, finish=1, discrete=-1,
multiplex=-2, zoom=-1, type='', async=-1, path='', multiplex=-2, zoom=-1, type='', async_=-1, path='',
file=None, quiet=1, _self=cmd): file=None, quiet=1, _self=cmd, **kwargs):
''' '''
DESCRIPTION DESCRIPTION
"fetch" downloads a file from the internet (if possible) "fetch" downloads a file from the internet (if possible)
USAGE USAGE
fetch code [, name [, state [, finish [, discrete [, multiplex fetch code [, name [, state [, finish [, discrete [, multiplex
[, zoom [, type [, async [, path ]]]]]]]]] [, zoom [, type [, async [, path ]]]]]]]]]
skipping to change at line 1364 skipping to change at line 1370
need synchronous behavior in order to insure that all structures need synchronous behavior in order to insure that all structures
are loaded before the next command is executed, please provide the are loaded before the next command is executed, please provide the
optional argument "async=0". optional argument "async=0".
Fetch requires a direct connection to the internet and thus may Fetch requires a direct connection to the internet and thus may
not work behind certain types of network firewalls. not work behind certain types of network firewalls.
''' '''
state, finish, discrete = int(state), int(finish), int(discrete) state, finish, discrete = int(state), int(finish), int(discrete)
multiplex, zoom = int(multiplex), int(zoom) multiplex, zoom = int(multiplex), int(zoom)
async, quiet = int(async), int(quiet) async_, quiet = int(kwargs.pop('async', async_)), int(quiet)
if not type: if kwargs:
if len(code) == 3: raise pymol.CmdException('unknown argument: ' + ', '.join(kwargs))
type = 'cc'
else:
type = _self.get('fetch_type_default')
r = DEFAULT_SUCCESS r = DEFAULT_SUCCESS
if not path: if not path:
# blank paths need to be reset to '.' # blank paths need to be reset to '.'
path = setting.get('fetch_path',_self=_self) or '.' path = _self.get('fetch_path') or '.'
if async<0: # by default, run asynch when interactive, sync when not if async_ < 0: # by default, run asynch when interactive, sync when not
async = not quiet async_ = not quiet
args = (code, name, state, finish, discrete, multiplex, zoom, type, path , file, quiet, _self) args = (code, name, state, finish, discrete, multiplex, zoom, type, path , file, quiet, _self)
kwargs = { '_self' : _self } kwargs = { '_self' : _self }
if async: if async_:
_self.async(_multifetch, *args, **kwargs) _self.async_(_multifetch, *args, **kwargs)
else: else:
try: try:
_self.block_flush(_self) _self.block_flush(_self)
r = _multifetch(*args) r = _multifetch(*args)
finally: finally:
_self.unblock_flush(_self) _self.unblock_flush(_self)
return r return r
def load_coordset(coords, object, state=0, quiet=1, _self=cmd): def load_coordset(coords, object, state=0, quiet=1, _self=cmd):
''' '''
skipping to change at line 1532 skipping to change at line 1535
_self.load(filename, **kwargs) _self.load(filename, **kwargs)
if group: if group:
if kwargs.get('object', '') != '': if kwargs.get('object', '') != '':
print(' Warning: group and object arguments given') print(' Warning: group and object arguments given')
members = [kwargs['object']] members = [kwargs['object']]
else: else:
members = map(filename_to_objectname, filenames) members = map(filename_to_objectname, filenames)
_self.group(group, ' '.join(members)) _self.group(group, ' '.join(members))
def _import_etree():
try:
from lxml import etree
except ImportError:
import xml.etree.ElementTree as etree
return etree
def load_pdbml(filename, object='', discrete=0, multiplex=1, zoom=-1, quiet=
1, _self=cmd):
'''
DESCRIPTION
Load a PDBML formatted structure file
'''
etree = _import_etree()
from chempy import Atom, models
from collections import defaultdict
multiplex, discrete = int(multiplex), int(discrete)
PDBxNS = '{http://pdbml.pdb.org/schema/pdbx-v40.xsd}'
try:
root = etree.fromstring(_self.file_read(filename))
atom_site_list = root.findall('.'
'/' + PDBxNS + 'atom_siteCategory'
'/' + PDBxNS + 'atom_site')
except etree.XMLSyntaxError:
raise pymol.CmdException("File doesn't look like XML")
except etree.XPathEvalError:
raise pymol.CmdException("XML file doesn't look like a PDBML file")
if not atom_site_list:
raise pymol.CmdException("no PDBx:atom_site nodes found in XML file"
)
# state -> model dictionary
model_dict = defaultdict(models.Indexed)
# atoms
for atom_site in atom_site_list:
atom = Atom()
atom.coord = [None, None, None]
model_num = 1
for child in atom_site:
tag = child.tag
if tag == PDBxNS + 'Cartn_x':
atom.coord[0] = float(child.text)
elif tag == PDBxNS + 'Cartn_y':
atom.coord[1] = float(child.text)
elif tag == PDBxNS + 'Cartn_z':
atom.coord[2] = float(child.text)
elif tag == PDBxNS + 'B_iso_or_equiv':
atom.b = float(child.text)
elif tag == PDBxNS + 'auth_asym_id':
atom.chain = child.text or ''
elif tag == PDBxNS + 'auth_atom_id':
atom.name = child.text or ''
elif tag == PDBxNS + 'auth_comp_id':
atom.resn = child.text or ''
elif tag == PDBxNS + 'auth_seq_id':
atom.resi = child.text or ''
elif tag == PDBxNS + 'label_alt_id':
atom.resi = child.text or ''
elif tag == PDBxNS + 'label_asym_id':
atom.segi = child.text or ''
elif tag == PDBxNS + 'label_atom_id':
if not atom.name:
atom.name = child.text or ''
elif tag == PDBxNS + 'label_comp_id':
if not atom.resn:
atom.resn = child.text or ''
elif tag == PDBxNS + 'label_seq_id':
if not atom.resi:
atom.resi = child.text or ''
elif tag == PDBxNS + 'label_entity_id':
atom.custom = child.text or ''
elif tag == PDBxNS + 'occupancy':
atom.q = float(child.text)
elif tag == PDBxNS + 'pdbx_PDB_model_num':
model_num = int(child.text)
elif tag == PDBxNS + 'type_symbol':
atom.symbol = child.text or ''
elif tag == PDBxNS + 'group_PDB':
atom.hetatm = (child.text == 'HETATM')
if None not in atom.coord:
model_dict[model_num].add_atom(atom)
# symmetry and cell
try:
node = root.findall('.'
'/' + PDBxNS + 'cellCategory'
'/' + PDBxNS + 'cell')[0]
cell = [float(node.findall('./' + PDBxNS + a)[0].text)
for a in ['length_a', 'length_b', 'length_c',
'angle_alpha', 'angle_beta', 'angle_gamma']]
spacegroup = root.findall('.'
'/' + PDBxNS + 'symmetryCategory'
'/' + PDBxNS + 'symmetry'
'/' + PDBxNS + 'space_group_name_H-M')[0].text
except IndexError:
cell = None
spacegroup = ''
# object name
if not object:
object = os.path.basename(filename).split('.', 1)[0]
# only multiplex if more than one model/state
multiplex = multiplex and len(model_dict) > 1
# load models as objects or states
for model_num in sorted(model_dict):
if model_num < 1:
print(" Error: model_num < 1 not supported")
continue
model = model_dict[model_num]
model.connect_mode = 3
if cell:
model.cell = cell
model.spacegroup = spacegroup
if multiplex:
oname = '%s_%04d' % (object , model_num)
model_num = 1
else:
oname = object
_self.load_model(model, oname,
state=model_num, zoom=zoom,
discrete=discrete)
def load_cml(filename, object='', discrete=0, multiplex=1, zoom=-1, quiet=1,
_self=cmd):
'''
DESCRIPTION
Load a CML formatted structure file
'''
etree = _import_etree()
from chempy import Atom, Bond, models
multiplex, discrete = int(multiplex), int(discrete)
try:
root = etree.fromstring(_self.file_read(filename))
except etree.XMLSyntaxError:
raise pymol.CmdException("File doesn't look like XML")
if root.tag != 'cml':
raise pymol.CmdException('not a CML file')
molecule_list = root.findall('./molecule')
if len(molecule_list) < 2:
multiplex = 0
elif not multiplex:
discrete = 1
for model_num, molecule_node in enumerate(molecule_list, 1):
model = models.Indexed()
atom_idx = {}
for atom_node in molecule_node.findall('./atomArray/atom'):
atom = Atom()
atom.name = atom_node.get('id', '')
if 'x3' in atom_node.attrib:
atom.coord = [float(atom_node.get(a)) for a in ['x3', 'y3',
'z3']]
elif 'x2' in atom_node.attrib:
atom.coord = [float(atom_node.get(a)) for a in ['x2', 'y2']]
+ [0.0]
else:
print(' Warning: no coordinates for atom', atom.name)
continue
atom.symbol = atom_node.get('elementType', '')
atom.formal_charge = int(atom_node.get('formalCharge', 0))
atom_idx[atom.name] = len(model.atom)
model.add_atom(atom)
for bond_node in molecule_node.findall('./bondArray/bond'):
refs = bond_node.get('atomsRefs2', '').split()
if len(refs) == 2:
bnd = Bond()
bnd.index = [int(atom_idx[ref]) for ref in refs]
bnd.order = int(bond_node.get('order', 1))
model.add_bond(bnd)
# object name
if not object:
object = os.path.basename(filename).split('.', 1)[0]
# load models as objects or states
if multiplex:
oname = molecule_node.get('id') or _self.get_unused_name('unname
d')
model_num = 1
else:
oname = object
_self.load_model(model, oname, state=model_num, zoom=zoom, discrete=
discrete)
def load_mmtf(filename, object='', discrete=0, multiplex=0, zoom=-1, quiet=1 , _self=cmd): def load_mmtf(filename, object='', discrete=0, multiplex=0, zoom=-1, quiet=1 , _self=cmd):
''' '''
DESCRIPTION DESCRIPTION
Load an MMTF file or URL. Load an MMTF file or URL.
''' '''
from chempy.mmtf import MmtfReader from chempy.mmtf import MmtfReader
if not object: if not object:
object = filename_to_objectname(filename) object = filename_to_objectname(filename)
skipping to change at line 1811 skipping to change at line 1609
def load_r3d(filename, object, state=0, zoom=-1, _self=cmd): def load_r3d(filename, object, state=0, zoom=-1, _self=cmd):
from . import cgo from . import cgo
obj = cgo.from_r3d(filename) obj = cgo.from_r3d(filename)
return _self.load_cgo(obj, object, state, zoom=zoom) return _self.load_cgo(obj, object, state, zoom=zoom)
def load_cc1(filename, object, state=0, _self=cmd): def load_cc1(filename, object, state=0, _self=cmd):
obj = io.cc1.fromFile(filename) obj = io.cc1.fromFile(filename)
return _self.load_model(obj, object, state) return _self.load_model(obj, object, state)
from pymol.viewing import load_png
loadfunctions = { loadfunctions = {
'mae': incentive_format_not_available_func, 'mae': incentive_format_not_available_func,
'pdbml': load_pdbml, 'pdbml': 'pymol.lazyio:load_pdbml',
'cml': load_cml, 'cml': 'pymol.lazyio:load_cml',
'mtz': load_mtz, 'mtz': load_mtz,
'py': lambda filename, _self: _self.do("_ run %s" % filename), 'py': lambda filename, _self: _self.do("_ run %s" % filename),
'pml': lambda filename, _self: _self.do("_ @%s" % filename), 'pml': lambda filename, _self: _self.do("_ @%s" % filename),
'pwg': _processPWG, 'pwg': _processPWG,
'aln': _processALN, 'aln': _processALN,
'fasta': _processFASTA, 'fasta': _processFASTA,
'png': load_png, 'png': 'pymol.viewing:load_png',
'idx': load_idx, 'idx': load_idx,
'pse': load_pse, 'pse': load_pse,
'psw': load_pse, 'psw': load_pse,
'cex': readcex, 'cex': 'pymol.m4x:readcex',
'ply': load_ply, 'ply': load_ply,
'r3d': load_r3d, 'r3d': load_r3d,
'cc1': load_cc1, 'cc1': load_cc1,
'pdb': read_pdbstr, 'pdb': read_pdbstr,
# Incentive
'vis': incentive_format_not_available_func,
'moe': incentive_format_not_available_func,
'phypo': incentive_format_not_available_func,
} }
 End of changes. 34 change blocks. 
266 lines changed or deleted 61 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)