def sele_exists(sele):
    sess = cmd.get_session()
    for i in sess["names"]:
        if type(i) is ListType:
            if sele==i[0]:
                return 1
    return 0
Example #2
0
 def testGetSession(self):
     cmd.fragment('ala')
     x = cmd.count_atoms()
     s = cmd.get_session()
     cmd.reinitialize()
     cmd.set_session(s)
     self.assertEqual(['ala'], cmd.get_names())
     self.assertEqual(x, cmd.count_atoms())
Example #3
0
 def testGetSession(self):
     cmd.fragment('ala')
     x = cmd.count_atoms()
     s = cmd.get_session()
     cmd.reinitialize()
     cmd.set_session(s)
     self.assertEqual(['ala'], cmd.get_names())
     self.assertEqual(x, cmd.count_atoms())
def dump_rep(name):
    if 'PYMOL_GIT_MOD' in os.environ:
        import shutil
        try:
            shutil.copytree(
                os.path.join(os.environ['PYMOL_GIT_MOD'], 'pymol2glmol', 'js'),
                os.path.join(os.getcwd(), 'js'))
        except OSError:
            pass

    names = cmd.get_session()['names']
    cmd.set('pdb_retain_ids', 1)

    ret = ''
    for obj in names:
        if (obj == None):
            continue
        if (obj[2] == 0):  # not visible
            continue
        if (obj[1] == 0 and obj[4] == 1 and obj[0] == name):
            ret += parseObjMol(obj)
        if (obj[1] == 0
                and obj[4] == 4):  # currently all dist objects are exported
            ret += parseDistObj(obj)

    cmd.turn('z', 180)
    view = cmd.get_view()
    cmd.turn('z', 180)
    cx = -view[12]
    cy = -view[13]
    cz = -view[14]
    cameraZ = -view[11] - 150
    fov = float(cmd.get("field_of_view"))
    fogStart = float(cmd.get("fog_start"))
    slabNear = view[15] + view[11]
    slabFar = view[16] + view[11]
    ret += "\nview:%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f" % \
        (cx, cy, cz, cameraZ, slabNear, slabFar, fogStart, fov)
    for i in range(9):
        ret += ",%.3f" % view[i]

    bgcolor = cmd.get_setting_tuple('bg_rgb')[1]
    ret += "\nbgcolor:%02x%02x%02x" % (int(255 * float(bgcolor[0])), \
                                       int(255 * float(bgcolor[1])), int(255 * float(bgcolor[2])))
    if 'PYMOL_GIT_MOD' in os.environ:
        template = open(os.path.join(os.environ['PYMOL_GIT_MOD'], 'pymol2glmol', 'imported.html')).read().\
            replace("###INCLUDE_PDB_FILE_HERE###", cmd.get_pdbstr(name)).\
            replace('###INCLUDE_REPRESENTATION_HERE###', ret)
    else:
        template = open('imported.html').read().\
            replace("###INCLUDE_PDB_FILE_HERE###", cmd.get_pdbstr(name)).\
            replace('###INCLUDE_REPRESENTATION_HERE###', ret)

    f = open(name + '.html', 'w')
    f.write(template)
    f.close()
Example #5
0
 def testGetMovieLocked(self):
     self.assertEqual(cmd.get_movie_locked(), 0)
     cmd.mset('1x1')
     cmd.mdo(1, 'cmd.color("blue")')
     s = cmd.get_session()
     cmd.set_session(s)
     self.assertEqual(cmd.get_movie_locked(), 1)
     cmd.set('security', 0)
     cmd.set_session(s)
     self.assertEqual(cmd.get_movie_locked(), 0)
Example #6
0
 	def sele2Color_deprecated(self):
 		globalShader = self.optionMenu_shader.getvalue()

 		# (color:shader) dictionary
 		# be used in shaderFactory.SCString()
 		#self.spColorShaderDict = {}
 		# get all the selection name
		sess = cmd.get_session()['names']
		for i in sess:
			if type(i) is ListType:
				# for each selection in the scene
				# also should exist in seleShaderDict
				if i[0] in self.seleShaderDict:
					newShader =  self.seleShaderDict[i[0]]
					if newShader != globalShader: # should be different from global shader, otherwise do nothing
						newColorInc = ShaderFactory.seleSlot[newShader]
						# pymol api routine
						# get the color for all the atoms in current selection
						stored.idcolor_list = []
						cmd.iterate(i[0], 'stored.idcolor_list.append((ID, int(color)))')

						# for a set of atoms have the same new color
						# apply color all at once for better performance
						# cmd.color is slow
						# example result: (color_index: [atom ids])
						# {25: [2, 3, 6], 6: [1], 9: [4, 5]}
						colorSetDict = {}
						for (atom_id, color) in stored.idcolor_list:
							colorSetDict.setdefault(color, []).append(str(atom_id))
						#print repr(colorSetDict)

						# for each color
						#for (atom_id, color) in stored.idcolor_list:
						for color in colorSetDict:
							atom_set = colorSetDict[color]
							rgb_color = cmd.get_color_tuple(color)
							#newColorInc = 0.001
							if rgb_color[2] >= 0.990:
								color_id = '%s %s %s' % (str(rgb_color[0])[0:5].ljust(5, '0'), str(rgb_color[1])[0:5].ljust(5, '0'), str(rgb_color[2]-newColorInc)[0:5])
							else:
								color_id = '%s %s %s' % (str(rgb_color[0])[0:5].ljust(5, '0'), str(rgb_color[1])[0:5].ljust(5, '0'), str(rgb_color[2]+newColorInc)[0:5])
							#print atom_id, color, color_id, repr(rgb_color)

							# color_id from all the sele:shader dictionary
							# determine color_id:shader pair
							if color_id not in self.spColorShaderDict:
								self.spColorShaderDict[color_id] = [newShader, i[0]]

							# apply new color to atom set
							newRGB = color_id.split(' ')
							newColor = [float(newRGB[0]), float(newRGB[1]), float(newRGB[2])]
							cmd.set_color(color_id, newColor)
							cmd.color(color_id, ('ID %s' % '+'.join(atom_set)))
						print 'apply shader [%s] to selection [%s].' % (newShader, i[0])
	def setNative(self, base=""):

		# --- get last structure --- #
		if base == "":
			sess = cmd.get_session()
			for i in sess["names"]:
				if type(i) is ListType:
					base = i[0]

		cmd.set_name(base, "native")
		file = base + ".pdb"
		self.viewer.setNative(file)
		self.viewer.displayNative()
def stereo_ray(output='', width='', height=''):

   if output == '':
      print 'no output filename defined\n'
      print 'try: \'stereo_ray filename\''
      return -1
      # abort if no output file name given
 
   if width == '':
      width,height = cmd.get_session()['main'][0:2]
      # get dimensions from viewer if not given
 
   elif height == '':
      oldWidth,oldHeight = cmd.get_session()['main'][0:2]
      height = int(width)*oldHeight/oldWidth
      # calculate height from proportions of viewer if
      # only width is given
 
   cmd.ray(width, height, angle=-3)
   cmd.png(output+"_r")
   cmd.ray(width, height, angle=3)
   cmd.png(output+"_l")
def stereo_ray(output="", width="", height=""):
    """
DESCRIPTION
   "stereo_ray" ray-traces the current scene twice (separated by 
   a six-degree rotation around the y axis)
   and saves a pair of images that can be combined in any image
   manipulation software to form a stereoimage.
   The first argument, the output file name, is mandatory.
   The second and third arguments, the size of the image, are not.
   If the width is given, the height will be calculated.
 
USAGE
   stereo_ray filename [, width [, height]]
 
EXAMPLE
   stereo_ray output, 1000, 600
   stereo_ray secondImage.png
   """

    if output == "":
        print "no output filename defined\n"
        print "try: 'stereo_ray filename'"
        return -1
        # abort if no output file name given

    if width == "":
        width, height = cmd.get_session()["main"][0:2]
        # get dimensions from viewer if not given

    elif height == "":
        oldWidth, oldHeight = cmd.get_session()["main"][0:2]
        height = int(width) * oldHeight / oldWidth
        # calculate height from proportions of viewer if
        # only width is given

    cmd.ray(width, height, angle=-3)
    cmd.png(output + "_r")
    cmd.ray(width, height, angle=3)
    cmd.png(output + "_l")
Example #10
0
def get_mdo_commands(quiet=1):
    '''
DESCRIPTION

    Get the list of mdo commands.
    '''
    s = cmd.get_session("none")
    commands = s["movie"][5] or []
    if not int(quiet):
        for frame, command in enumerate(commands, 1):
            if command:
                print('mdo {}: {}'.format(frame, command.strip(';')))
    return commands
def stereo_ray(output='', width='', height=''):

    if output == '':
        print 'no output filename defined\n'
        print 'try: \'stereo_ray filename\''
        return -1
        # abort if no output file name given

    if width == '':
        width, height = cmd.get_session()['main'][0:2]
        # get dimensions from viewer if not given

    elif height == '':
        oldWidth, oldHeight = cmd.get_session()['main'][0:2]
        height = int(width) * oldHeight / oldWidth
        # calculate height from proportions of viewer if
        # only width is given

    cmd.ray(width, height, angle=-3)
    cmd.png(output + "_r")
    cmd.ray(width, height, angle=3)
    cmd.png(output + "_l")
Example #12
0
def get_keyframes(quiet=1):
    '''
DESCRIPTION

    Get the list of camera keyframes for the current movie.
    '''
    s = cmd.get_session("none")
    viewelem_list = s["movie"][6]
    if not viewelem_list:
        return []
    r = [i for (i,v) in enumerate(viewelem_list, 1) if v[12] == 2]
    if not int(quiet):
        print(r)
    return r
	def setDesigned(self, base=""):
		
		# --- get last structure --- #
		if base == "":
			sess = cmd.get_session()
			for i in sess["names"]:
				if type(i) is ListType:
					base = i[0]

		file = base + ".pdb"
		cmd.set_name(base, "designed")
		self.viewer.setDesign(file)
		self.viewer.selectCatalytic()
		self.viewer.displayDesigned()
Example #14
0
def get_keyframes(quiet=1):
    '''
DESCRIPTION

    Get the list of camera keyframes for the current movie.
    '''
    s = cmd.get_session("none")
    viewelem_list = s["movie"][6]
    if not viewelem_list:
        return []
    r = [i for (i, v) in enumerate(viewelem_list, 1) if v[12] == 2]
    if not int(quiet):
        print(r)
    return r
	def __init__(self):

		Wizard.__init__(self)
		self.viewer = design_viewer()
		self.resfile = Resfile()

		sess = cmd.get_session()
		base = ""
		for i in sess["names"]:
			if type(i) is ListType:
				base = i[0]

		if base != "":
			self.setDesigned(base)

		self.wiz_ros = wizard_rosetta()
Example #16
0
	def applyShader_deprecated(self):
		sele = self.varSelectionName.get()
		shader = self.optionMenu_selectionShader.getvalue()
		sess = cmd.get_session()['names']
		match_flag = False
		for i in sess:
			if type(i) is ListType:
				match = re.search(sele, i[0])
				#print 'sele: %s, i[0]: %s, match: %s' % (sele, i[0], repr(match))

				# exact word match
				# pattern s1, string: 1t3r
				# match == None
				if match is None:
					continue
				# when using regular expression like 's*'
				# match is always not None
				# match.group(0) == '' if not matching
				if match is not None: 
					#print repr(match.group(0))
					if match.group(0) == '':
						continue

				match_flag = True
				#if match.group(0):
				#if sele == i[0]:
				# user clicked apply for a selection more than once
				if i[0] in self.seleShaderDict:
					for key in self.spColorShaderDict:
						sele_in_dict = self.spColorShaderDict[key][1]
						if i[0] == sele_in_dict:
							self.selectionConsole.set('Shader for [%s] is not empty. \n Click [Unset all] if scene has been changed.' % i[0])
							return
								#self.spColorShaderDict.pop(key, 0)

				self.seleShaderDict[i[0]] = shader
	 			self.selectionConsole.set('Set [%s] with [%s] shader' % (sele, self.seleShaderDict[i[0]]))
	 			# add into dictionary
	 			self.sele2Color()

	 	if match_flag == False:
 			self.selectionConsole.set('Error: Selection [%s] does not exist.' % sele)
Example #17
0
    def test_pse(self):
        self.ambientOnly()

        viewport = (50, 50)
        cmd.viewport(*viewport)

        objname = 'simpletri'
        obj = []
        obj.extend([
            cgo.BEGIN, cgo.TRIANGLES, cgo.COLOR, 1.0, 0., 0., cgo.VERTEX, 0.0,
            0.0, 1.0, cgo.VERTEX, 1.0, 0.0, 0.0, cgo.VERTEX, 0.0, 1.0, 0.0,
            cgo.END
        ])
        cmd.load_cgo(obj, objname, 1)

        s = cmd.get_session()
        cmd.set_session(s)

        self.assertEqual([objname], cmd.get_names())
        self.assertImageHasColor('red')
Example #18
0
def ramp_levels(name, levels, quiet=1):
    '''
DESCRIPTION

    Changes the slot levels of a ramp.

SEE ALSO

    ramp_new, isolevel
    '''
    quiet = int(quiet)
    if cmd.is_string(levels):
        levels = cmd.safe_list_eval(levels)

    try:
        position = cmd.get_names('all').index(name)

        odata = cmd.get_session(name, 1, 1, 0, 0)['names'][0]
        if odata[4] != 8:
            raise TypeError('not a ramp')
        data = odata[5]
    except:
        print(' Error: Get session data for ramp "%s" failed' % (name))
        raise CmdException

    if len(levels) != len(data[3]):
        print(' Error: number of levels must agree with existing object')
        raise CmdException

    map_name = data[6]
    colors = [data[4][i:i+3] for i in range(0, len(data[4]), 3)]
    cmd.ramp_new(name, map_name, levels, colors, quiet=quiet)

    # restore original position
    if position == 0:
        cmd.order(name, location='top')
    else:
        cmd.order(cmd.get_names('all')[position-1] + ' ' + name)
Example #19
0
def ramp_levels(name, levels, quiet=1):
    '''
DESCRIPTION

    Changes the slot levels of a ramp.

SEE ALSO

    ramp_new, isolevel
    '''
    quiet = int(quiet)
    if cmd.is_string(levels):
        levels = cmd.safe_list_eval(levels)

    try:
        position = cmd.get_names('all').index(name)

        odata = cmd.get_session(name, 1, 1, 0, 0)['names'][0]
        if odata[4] != 8:
            raise TypeError('not a ramp')
        data = odata[5]
    except:
        print(' Error: Get session data for ramp "%s" failed' % (name))
        raise CmdException

    if len(levels) != len(data[3]):
        print(' Error: number of levels must agree with existing object')
        raise CmdException

    map_name = data[6]
    colors = [data[4][i:i + 3] for i in range(0, len(data[4]), 3)]
    cmd.ramp_new(name, map_name, levels, colors, quiet=quiet)

    # restore original position
    if position == 0:
        cmd.order(name, location='top')
    else:
        cmd.order(cmd.get_names('all')[position - 1] + ' ' + name)
Example #20
0
    def testDistanceMode4(self):
        # create two 2-state objects
        cmd.fragment('gly', 'm1', origin=0)
        cmd.create('m1', 'm1', 1, 2)
        cmd.create('m2', 'm1', 1, 1)
        cmd.create('m2', 'm1', 1, 2)

        # shift one state by 5 and the other by 9 angstrom
        cs = cmd.get_coordset('m1', state=1, copy=0)
        cs += [5., 0., 0.]
        cs = cmd.get_coordset('m2', state=2, copy=0)
        cs += [9., 0., 0.]

        # creates one distance measure per state
        d = cmd.distance('d1', '?m1', '?m2', mode=4)

        # expecting 7 = (5 + 9) / 2
        self.assertAlmostEqual(d, 7.0, delta=1e-4)

        # one distance measurement has 2 * 3 coordinates
        d1states = cmd.get_session('d1', 1, 1, 0, 0)['names'][0][5][2]
        self.assertEqual(len(d1states[0][1]), 6)
        self.assertEqual(len(d1states[1][1]), 6)
Example #21
0
    def testDistanceMode4(self):
        # create two 2-state objects
        cmd.fragment('gly', 'm1', origin=0)
        cmd.create('m1', 'm1', 1, 2)
        cmd.create('m2', 'm1', 1, 1)
        cmd.create('m2', 'm1', 1, 2)

        # shift one state by 5 and the other by 9 angstrom
        cs = cmd.get_coordset('m1', state=1, copy=0)
        cs += [5., 0., 0.]
        cs = cmd.get_coordset('m2', state=2, copy=0)
        cs += [9., 0., 0.]

        # creates one distance measure per state
        d = cmd.distance('d1', '?m1', '?m2', mode=4)

        # expecting 7 = (5 + 9) / 2
        self.assertAlmostEqual(d, 7.0, delta=1e-4)

        # one distance measurement has 2 * 3 coordinates
        d1states = cmd.get_session('d1', 1, 1, 0, 0)['names'][0][5][2]
        self.assertEqual(len(d1states[0][1]), 6)
        self.assertEqual(len(d1states[1][1]), 6)
Example #22
0
    def test_pse(self):
        self.ambientOnly()

        viewport = (50, 50)
        cmd.viewport(*viewport)

        objname = 'simpletri'
        obj = []
        obj.extend([
            cgo.BEGIN, cgo.TRIANGLES,
            cgo.COLOR, 1.0, 0., 0.,
            cgo.VERTEX, 0.0, 0.0, 1.0,
            cgo.VERTEX, 1.0, 0.0, 0.0,
            cgo.VERTEX, 0.0, 1.0, 0.0,
            cgo.END
            ])
        cmd.load_cgo(obj, objname, 1)

        s = cmd.get_session()
        cmd.set_session(s)

        self.assertEqual([objname], cmd.get_names())
        self.assertImageHasColor('red')
Example #23
0
def get_raw_distances(names='', state=1, selection='all', quiet=1):
    '''
DESCRIPTION

    Get the list of pair items from distance objects. Each list item is a
    tuple of (index1, index2, distance).

    Based on a script from Takanori Nakane, posted on pymol-users mailing list.
    http://www.mail-archive.com/[email protected]/msg10143.html

ARGUMENTS

    names = string: names of distance objects (no wildcards!) {default: all
    measurement objects}

    state = integer: object state {default: 1}

    selection = string: atom selection {default: all}

SEE ALSO

    select_distances, cmd.find_pairs, cmd.get_raw_alignment
    '''
    from chempy import cpv

    state, quiet = int(state), int(quiet)
    if state < 1:
        state = cmd.get_state()

    valid_names = cmd.get_names_of_type('object:measurement')
    if names == '':
        names = ' '.join(valid_names)
    else:
        for name in names.split():
            if name not in valid_names:
                print(' Error: no such distance object: ' + name)
                raise CmdException

    raw_objects = cmd.get_session(names, 1, 1, 0, 0)['names']

    xyz2idx = {}
    cmd.iterate_state(state, selection, 'xyz2idx[x,y,z] = (model,index)',
            space=locals())

    r = []
    for obj in raw_objects:
        try:
            points = obj[5][2][state-1][1]
            if points is None:
                raise ValueError
        except (KeyError, ValueError):
            continue
        for i in range(0, len(points), 6):
            xyz1 = tuple(points[i:i+3])
            xyz2 = tuple(points[i+3:i+6])
            try:
                r.append((xyz2idx[xyz1], xyz2idx[xyz2], cpv.distance(xyz1, xyz2)))
                if not quiet:
                    print(' get_raw_distances: ' + str(r[-1]))
            except KeyError:
                if quiet < 0:
                    print(' Debug: no index for %s %s' % (xyz1, xyz2))
    return r
Example #24
0
def get_raw_distances(names='', state=1, selection='all', quiet=1):
    '''
DESCRIPTION

    Get the list of pair items from distance objects. Each list item is a
    tuple of (index1, index2, distance).

    Based on a script from Takanori Nakane, posted on pymol-users mailing list.
    http://www.mail-archive.com/[email protected]/msg10143.html

ARGUMENTS

    names = string: names of distance objects (no wildcards!) {default: all
    measurement objects}

    state = integer: object state {default: 1}

    selection = string: atom selection {default: all}

SEE ALSO

    select_distances, cmd.find_pairs, cmd.get_raw_alignment
    '''
    from chempy import cpv

    state, quiet = int(state), int(quiet)
    if state < 1:
        state = cmd.get_state()

    valid_names = cmd.get_names_of_type('object:measurement')
    if names == '':
        names = ' '.join(valid_names)
    else:
        for name in names.split():
            if name not in valid_names:
                print((' Error: no such distance object:', name))
                raise CmdException

    raw_objects = cmd.get_session(names, 1, 1, 0, 0)['names']

    xyz2idx = {}
    cmd.iterate_state(state,
                      selection,
                      'xyz2idx[x,y,z] = (model,index)',
                      space=locals())

    r = []
    for obj in raw_objects:
        try:
            points = obj[5][2][state - 1][1]
            if points is None:
                raise ValueError
        except (KeyError, ValueError):
            continue
        for i in range(0, len(points), 6):
            xyz1 = tuple(points[i:i + 3])
            xyz2 = tuple(points[i + 3:i + 6])
            try:
                r.append(
                    (xyz2idx[xyz1], xyz2idx[xyz2], cpv.distance(xyz1, xyz2)))
                if not quiet:
                    print((' get_raw_distances:', r[-1]))
            except KeyError:
                if quiet < 0:
                    print((' Debug: no index for', xyz1, xyz2))
    return r
Example #25
0
def get_raw_distances(names='',
                      state=1,
                      selection='all',
                      fc=2.0,
                      amber=0,
                      gro=0,
                      label='ID',
                      quiet=1):
    '''
DESCRIPTION

    Get the list of pair items from distance objects. Each list item is a
    tuple of (ID1, ID2, distance).

    Based on a script from Takanori Nakane, posted on pymol-users mailing list.
    http://www.mail-archive.com/[email protected]/msg10143.html

ARGUMENTS

    names = string: names of distance objects (no wildcards!) {default: all
    measurement objects}

    state = integer: object state {default: 1}

    selection = string: atom selection {default: all}

    amber = integer: generate AMBER rst file {default: 0}

    gro = integer: generate GROMACS rst file {default: 0}

    label = string: label type ('ID' or 'index') {default: ID}

SEE ALSO

    select_distances, cmd.find_pairs, cmd.get_raw_alignment
    '''
    from chempy import cpv

    state, quiet, fc = int(state), int(quiet), float(fc)
    if state < 1:
        state = cmd.get_state()

    valid_names = cmd.get_names_of_type('object:measurement')
    if names == '':
        names = ' '.join(valid_names)
    else:
        for name in names.split():
            if name not in valid_names:
                print(' Error: no such distance object: ' + name)
                raise CmdException

    raw_objects = cmd.get_session(names, 1, 1, 0, 0)['names']

    xyz2idx = {}
    cmd.iterate_state(state,
                      selection,
                      'xyz2idx[x,y,z] = (model, resi, resn, name, ' + label +
                      ')',
                      space=locals())

    r = []
    for obj in raw_objects:
        try:
            points = obj[5][2][state - 1][1]
            if points is None:
                raise ValueError
        except (KeyError, ValueError):
            continue
        for i in range(0, len(points), 6):
            xyz1 = tuple(points[i:i + 3])
            xyz2 = tuple(points[i + 3:i + 6])
            try:
                r.append(
                    (xyz2idx[xyz1], xyz2idx[xyz2], cpv.distance(xyz1, xyz2)))
                if not quiet:
                    print(' get_raw_distances: ' + str(r[-1]))
            except KeyError:
                if quiet < 0:
                    print(' Debug: no index for %s %s' % (xyz1, xyz2))
    # print(r)
    # for generate amber MD restraint file.
    if (int(amber)):
        for i in r:
            print("""# {0}{1}  {2} - {3}{4}  {5}
&rst
   iat={6}, {7},
   r1=0, r2=0.5,
   r3={8:.2f}, r4=8,
   rk2={9}, rk3={9},
/""".format(str(i[0][1]), str(i[0][2]), str(i[0][3]), str(i[1][1]),
            str(i[1][2]), str(i[1][3]), str(i[0][4]), str(i[1][4]),
            float(i[2]), float(fc)))

    # for generate GROMACS MD restraint file.
    if (int(gro)):
        for i in r:
            print(
                "{6} {7} 10 0.00 {8:.3f} 0.800 800 ; {0}{1} {2} - {3}{4} {5} 2kcal/mol/A2"
                .format(str(i[0][1]), str(i[0][2]), str(i[0][3]), str(i[1][1]),
                        str(i[1][2]), str(i[1][3]), str(i[0][4]), str(i[1][4]),
                        float(i[2]) / 10))

    return r
Example #26
0
def get_raw_distances(names='',
                      state=1,
                      selection='all',
                      quiet=1,
                      filename='intrs.txt'):
    '''
DESCRIPTION

    Get the list of pair items from distance objects. Each list item is a
    tuple of (index1, index2, distance).

    Based on a script from Takanori Nakane, posted on pymol-users mailing list.
    http://www.mail-archive.com/[email protected]/msg10143.html

ARGUMENTS

    names = string: names of distance objects (no wildcards!) {default: all
    measurement objects}

    state = integer: object state {default: 1}

    selection = string: atom selection {default: all}

    quiet = boolen

    filename

SEE ALSO

    select_distances, cmd.find_pairs, cmd.get_raw_alignment
    '''
    foo = cmd.do('l = [];')  ## ugly hack!
    from chempy import cpv

    state, quiet = int(state), int(quiet)
    if state < 1:
        state = cmd.get_state()

    valid_names = cmd.get_names_of_type('object:measurement')
    if names == '':
        names = ' '.join(valid_names)
    else:
        for name in names.split():
            if name not in valid_names:
                print(' Error: no such distance object: ' + name)
                raise CmdException

    raw_objects = cmd.get_session(names, 1, 1, 0, 0)['names']

    xyz2idx = {}
    cmd.iterate_state(state,
                      selection,
                      'xyz2idx[x,y,z] = (model,index)',
                      space=locals())

    r = []
    rresi = []
    for obj in raw_objects:
        try:
            points = obj[5][2][state - 1][1]
            if not quiet:
                print(points)
            if points is None:
                raise ValueError
        except (KeyError, ValueError):
            continue
        for i in range(0, len(points), 6):
            xyz1 = tuple(points[i:i + 3])
            xyz2 = tuple(points[i + 3:i + 6])
            try:
                r.append(
                    (xyz2idx[xyz1], xyz2idx[xyz2], cpv.distance(xyz1, xyz2)))
                # (('yC_5lj3_U6', 1183)
                if not quiet:
                    print(' get_raw_distances: ' + str(r[-1]))
                rresi.append([
                    unid(xyz2idx[xyz1][0], xyz2idx[xyz1][1]),
                    unid(xyz2idx[xyz2][0], xyz2idx[xyz2][1])
                ])
                if not quiet:
                    print('  ', unid(xyz2idx[xyz1][0], xyz2idx[xyz1][1]),
                          '<->', unid(xyz2idx[xyz2][0], xyz2idx[xyz2][1]))
            except KeyError:
                if quiet < 0:
                    print(' Debug: no index for %s %s' % (xyz1, xyz2))

    if rresi:
        with open(filename, 'w') as f:
            for r in rresi:
                # not fully correct
                # f.write('Prp8' +',' + r[0] + '\n')
                f.write(r[0] + ',' + r[1] + '\n')
        print('File saved:', filename)
    return r, rresi