Package pipe_control :: Module pymol_control
[hide private]
[frames] | no frames]

Source Code for Module pipe_control.pymol_control

  1  ############################################################################### 
  2  #                                                                             # 
  3  # Copyright (C) 2006-2013 Edward d'Auvergne                                   # 
  4  #                                                                             # 
  5  # This file is part of the program relax (http://www.nmr-relax.com).          # 
  6  #                                                                             # 
  7  # This program is free software: you can redistribute it and/or modify        # 
  8  # it under the terms of the GNU General Public License as published by        # 
  9  # the Free Software Foundation, either version 3 of the License, or           # 
 10  # (at your option) any later version.                                         # 
 11  #                                                                             # 
 12  # This program is distributed in the hope that it will be useful,             # 
 13  # but WITHOUT ANY WARRANTY; without even the implied warranty of              # 
 14  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               # 
 15  # GNU General Public License for more details.                                # 
 16  #                                                                             # 
 17  # You should have received a copy of the GNU General Public License           # 
 18  # along with this program.  If not, see <http://www.gnu.org/licenses/>.       # 
 19  #                                                                             # 
 20  ############################################################################### 
 21   
 22  # Module docstring. 
 23  """Module for interfacing with PyMOL.""" 
 24   
 25  # Dependency check module. 
 26  import dep_check 
 27   
 28  # Python module imports. 
 29  if dep_check.pymol_module: 
 30      import pymol 
 31  from math import pi 
 32  from numpy import float64, transpose, zeros 
 33  from os import F_OK, access, pardir, sep 
 34  PIPE, Popen = None, None 
 35  if dep_check.subprocess_module: 
 36      from subprocess import PIPE, Popen 
 37  from tempfile import mktemp 
 38  from time import sleep 
 39   
 40  # relax module imports. 
 41  from lib.errors import RelaxError, RelaxNoPdbError, RelaxNoSequenceError 
 42  from lib.geometry.rotations import euler_to_R_zyz, R_to_axis_angle 
 43  from lib.io import delete, file_root, get_file_path, open_read_file, open_write_file, test_binary 
 44  from pipe_control import pipes 
 45  from pipe_control.mol_res_spin import exists_mol_res_spin_data 
 46  from pipe_control.result_files import add_result_file 
 47  from specific_analyses.setup import get_specific_fn 
 48  from status import Status; status = Status() 
 49   
 50   
51 -class Pymol:
52 """The PyMOL execution object.""" 53
54 - def __init__(self, exec_mode=None):
55 """Set up the PyMOL execution object. 56 57 @keyword exec_mode: The execution mode which can be either 'module' or 'external'. 58 @type exec_mode: None or str 59 """ 60 61 # Variable for storing the pymol command history. 62 self.command_history = "" 63 64 # The pymol mode of operation. 65 self.exec_mode = exec_mode 66 if not exec_mode: 67 if dep_check.pymol_module: 68 self.exec_mode = 'module' 69 self.open = False 70 else: 71 self.exec_mode = 'external'
72 73
74 - def clear_history(self):
75 """Clear the PyMOL command history.""" 76 77 self.command_history = ""
78 79
80 - def exec_cmd(self, command=None, store_command=True):
81 """Execute a PyMOL command. 82 83 @param command: The PyMOL command to send into the program. 84 @type command: str 85 @param store_command: A flag specifying if the command should be stored in the history 86 variable. 87 @type store_command: bool 88 """ 89 90 # Reopen the GUI if needed. 91 if not self.running(): 92 self.open_gui() 93 94 # Execute the command. 95 if self.exec_mode == 'module': 96 pymol.cmd.do(command) 97 else: 98 self.pymol.write(command + '\n') 99 100 # Place the command in the command history. 101 if store_command: 102 self.command_history = self.command_history + command + "\n"
103 104
105 - def open_gui(self):
106 """Open the PyMOL GUI.""" 107 108 # Use the PyMOL python modules. 109 if self.exec_mode == 'module': 110 # Open the GUI. 111 pymol.finish_launching() 112 self.open = True 113 114 # Otherwise execute PyMOL on the command line. 115 if self.exec_mode == 'external': 116 # Test that the PyMOL binary exists. 117 test_binary('pymol') 118 119 # Python 2.3 and earlier. 120 if Popen == None: 121 raise RelaxError("The subprocess module is not available in this version of Python.") 122 123 # Open PyMOL as a pipe. 124 self.pymol = Popen(['pymol', '-qpK'], stdin=PIPE).stdin 125 126 # Execute the command history. 127 if len(self.command_history) > 0: 128 self.exec_cmd(self.command_history, store_command=0) 129 return 130 131 # Test if the PDB file has been loaded. 132 if hasattr(cdp, 'structure'): 133 self.open_pdb()
134 135
136 - def open_pdb(self):
137 """Open the PDB file in PyMOL.""" 138 139 # Test if PyMOL is running. 140 if not self.running(): 141 return 142 143 # Reinitialise PyMOL. 144 self.exec_cmd("reinitialize") 145 146 # Open the PDB files. 147 open_files = [] 148 for model in cdp.structure.structural_data: 149 for mol in model.mol: 150 # The file path as the current directory. 151 file_path = None 152 if access(mol.file_name, F_OK): 153 file_path = mol.file_name 154 155 # The file path using the relative path. 156 if file_path == None and hasattr(mol, 'file_path') and mol.file_path != None: 157 file_path = mol.file_path + sep + mol.file_name 158 if not access(file_path, F_OK): 159 file_path = None 160 161 # The file path using the absolute path. 162 if file_path == None and hasattr(mol, 'file_path_abs') and mol.file_path_abs != None: 163 file_path = mol.file_path_abs + sep + mol.file_name 164 if not access(file_path, F_OK): 165 file_path = None 166 167 # Hmmm, maybe the absolute path no longer exists and we are in a results subdirectory? 168 if file_path == None and hasattr(mol, 'file_path') and mol.file_path != None: 169 file_path = pardir + sep + mol.file_path + sep + mol.file_name 170 if not access(file_path, F_OK): 171 file_path = None 172 173 # Fall back to the current directory. 174 if file_path == None: 175 file_path = mol.file_name 176 177 # Already loaded. 178 if file_path in open_files: 179 continue 180 181 # Already loaded. 182 if file_path in open_files: 183 continue 184 185 # Open the file in PyMOL. 186 self.exec_cmd("load " + file_path) 187 188 # Add to the open file list. 189 open_files.append(file_path)
190 191
192 - def running(self):
193 """Test if PyMOL is running. 194 195 @return: Whether the Molmol pipe is open or not. 196 @rtype: bool 197 """ 198 199 # Test if PyMOL module interface is already running. 200 if self.exec_mode == 'module': 201 return self.open 202 203 # Test if command line PyMOL is already running. 204 if self.exec_mode == 'external': 205 # Pipe exists. 206 if not hasattr(self, 'pymol'): 207 return False 208 209 # Test if the pipe has been broken. 210 try: 211 self.pymol.write('\n') 212 except IOError: 213 return False 214 215 # PyMOL is running. 216 return True
217 218 219 220 # Initialise the Pymol executable object. 221 pymol_obj = Pymol('external') 222 """Pymol data container instance.""" 223 224 225
226 -def cartoon():
227 """Apply the PyMOL cartoon style and colour by secondary structure.""" 228 229 # Test if the current data pipe exists. 230 pipes.test() 231 232 # Test for the structure. 233 if not hasattr(cdp, 'structure'): 234 raise RelaxNoPdbError 235 236 # Loop over the PDB files. 237 open_files = [] 238 for model in cdp.structure.structural_data: 239 for mol in model.mol: 240 # Identifier. 241 pdb_file = mol.file_name 242 if mol.file_path: 243 pdb_file = mol.file_path + sep + pdb_file 244 id = file_root(pdb_file) 245 246 # Already loaded. 247 if pdb_file in open_files: 248 continue 249 250 # Add to the open file list. 251 open_files.append(pdb_file) 252 253 # Hide everything. 254 pymol_obj.exec_cmd("cmd.hide('everything'," + repr(id) + ")") 255 256 # Show the cartoon style. 257 pymol_obj.exec_cmd("cmd.show('cartoon'," + repr(id) + ")") 258 259 # Colour by secondary structure. 260 pymol_obj.exec_cmd("util.cbss(" + repr(id) + ", 'red', 'yellow', 'green')")
261 262
263 -def command(command):
264 """Function for sending PyMOL commands to the program pipe. 265 266 @param command: The command to send into the program. 267 @type command: str 268 """ 269 270 # Pass the command to PyMOL. 271 pymol_obj.exec_cmd(command)
272 273
274 -def cone_pdb(file=None):
275 """Display the cone geometric object. 276 277 @keyword file: The name of the file containing the cone geometric object. 278 @type file: str 279 """ 280 281 # Read in the cone PDB file. 282 pymol_obj.exec_cmd("load " + file) 283 284 285 # The cone axes. 286 ################ 287 288 # Select the AVE, AXE, and SIM residues. 289 pymol_obj.exec_cmd("select (resn AVE,AXE,SIM)") 290 291 # Show the vector as a stick. 292 pymol_obj.exec_cmd("show stick, 'sele'") 293 294 # Colour it blue. 295 pymol_obj.exec_cmd("color cyan, 'sele'") 296 297 # Select the atom used for labelling. 298 pymol_obj.exec_cmd("select (resn AVE,AXE,SIM and symbol N)") 299 300 # Hide the atom. 301 pymol_obj.exec_cmd("hide ('sele')") 302 303 # Label using the atom name. 304 pymol_obj.exec_cmd("cmd.label(\"sele\",\"name\")") 305 306 307 # The cone object. 308 ################## 309 310 # Select the CON residue. 311 pymol_obj.exec_cmd("select (resn CON,EDG)") 312 313 # Hide everything. 314 pymol_obj.exec_cmd("hide ('sele')") 315 316 # Show as 'sticks'. 317 pymol_obj.exec_cmd("show sticks, 'sele'") 318 319 # Colour it white. 320 pymol_obj.exec_cmd("color white, 'sele'") 321 322 # Shorten the stick width from 0.25 to 0.15. 323 pymol_obj.exec_cmd("set stick_radius,0.15000") 324 325 # Set a bit of transparency. 326 pymol_obj.exec_cmd("set stick_transparency, 0.3") 327 328 329 # Clean up. 330 ########### 331 332 # Remove the selection. 333 pymol_obj.exec_cmd("cmd.delete('sele')") 334 335 336 # Rotate to the average position. 337 ################################# 338 339 # Check if there is an average position. 340 if hasattr(cdp, 'ave_pos_beta'): 341 # The average position rotation. 342 ave_pos_R = zeros((3, 3), float64) 343 ave_pos_alpha = 0.0 344 if hasattr(cdp, 'ave_pos_alpha') and cdp.ave_pos_alpha != None: 345 ave_pos_alpha = cdp.ave_pos_alpha 346 euler_to_R_zyz(ave_pos_alpha, cdp.ave_pos_beta, cdp.ave_pos_gamma, ave_pos_R) 347 348 # The rotation is passive (need to rotated the moving domain back into the average position defined in the non-moving domain PDB frame). 349 R = transpose(ave_pos_R) 350 351 # Convert to axis-angle notation. 352 axis, angle = R_to_axis_angle(R) 353 354 # The PDB file to rotate. 355 for i in range(len(cdp.domain_to_pdb)): 356 if cdp.domain_to_pdb[i][0] != cdp.ref_domain: 357 pdb = cdp.domain_to_pdb[i][1] 358 359 # Execute the pymol command to rotate. 360 pymol_obj.exec_cmd("cmd.rotate([%s, %s, %s], %s, '%s', origin=[%s, %s, %s])" % (axis[0], axis[1], axis[2], angle/pi*180.0, pdb, cdp.pivot[0], cdp.pivot[1], cdp.pivot[2]))
361 362
363 -def create_macro(data_type=None, style="classic", colour_start=None, colour_end=None, colour_list=None):
364 """Create an array of PyMOL commands. 365 366 @keyword data_type: The data type to map to the structure. 367 @type data_type: str 368 @keyword style: The style of the macro. 369 @type style: str 370 @keyword colour_start: The starting colour of the linear gradient. 371 @type colour_start: str or RBG colour array (len 3 with vals from 0 to 1) 372 @keyword colour_end: The ending colour of the linear gradient. 373 @type colour_end: str or RBG colour array (len 3 with vals from 0 to 1) 374 @keyword colour_list: The colour list to search for the colour names. Can be either 'molmol' or 'x11'. 375 @type colour_list: str or None 376 @return: The list of PyMOL commands. 377 @rtype: list of str 378 """ 379 380 # Specific PyMOL macro creation function. 381 macro = get_specific_fn('pymol_macro', cdp.pipe_type) 382 383 # Get the macro. 384 commands = macro(data_type, style, colour_start, colour_end, colour_list) 385 386 # Return the macro commands. 387 return commands
388 389
390 -def macro_apply(data_type=None, style="classic", colour_start_name=None, colour_start_rgb=None, colour_end_name=None, colour_end_rgb=None, colour_list=None):
391 """Execute a PyMOL macro. 392 393 @keyword data_type: The data type to map to the structure. 394 @type data_type: str 395 @keyword style: The style of the macro. 396 @type style: str 397 @keyword colour_start_name: The name of the starting colour of the linear gradient. 398 @type colour_start_name: str 399 @keyword colour_start_rgb: The RGB array starting colour of the linear gradient. 400 @type colour_start_rgb: RBG colour array (len 3 with vals from 0 to 1) 401 @keyword colour_end_name: The name of the ending colour of the linear gradient. 402 @type colour_end_name: str 403 @keyword colour_end_rgb: The RGB array ending colour of the linear gradient. 404 @type colour_end_rgb: RBG colour array (len 3 with vals from 0 to 1) 405 @keyword colour_list: The colour list to search for the colour names. Can be either 'molmol' or 'x11'. 406 @type colour_list: str or None 407 """ 408 409 # Test if the current data pipe exists. 410 pipes.test() 411 412 # Test if sequence data exists. 413 if not exists_mol_res_spin_data(): 414 raise RelaxNoSequenceError 415 416 # Check the arguments. 417 if colour_start_name != None and colour_start_rgb != None: 418 raise RelaxError("The starting colour name and RGB colour array cannot both be supplied.") 419 if colour_end_name != None and colour_end_rgb != None: 420 raise RelaxError("The ending colour name and RGB colour array cannot both be supplied.") 421 422 # Merge the colour args. 423 if colour_start_name != None: 424 colour_start = colour_start_name 425 else: 426 colour_start = colour_start_rgb 427 if colour_end_name != None: 428 colour_end = colour_end_name 429 else: 430 colour_end = colour_end_rgb 431 432 # Clear the PyMOL history first. 433 pymol_obj.clear_history() 434 435 # Create the macro. 436 commands = create_macro(data_type=data_type, style=style, colour_start=colour_start, colour_end=colour_end, colour_list=colour_list) 437 438 # Save the commands as a temporary file, execute it, then delete it. 439 try: 440 # Temp file name. 441 tmpfile = "%s.pml" % mktemp() 442 443 # Open the file. 444 file = open(tmpfile, 'w') 445 446 # Loop over the commands and write them. 447 for command in commands: 448 file.write("%s\n" % command) 449 file.close() 450 451 # Execute the macro. 452 pymol_obj.exec_cmd("@%s" % tmpfile) 453 454 # Wait a bit for PyMOL to catch up (it takes time for PyMOL to start and the macro to execute). 455 sleep(3) 456 457 # Delete the temporary file (no matter what). 458 finally: 459 # Delete the file. 460 delete(tmpfile, fail=False)
461 462
463 -def macro_run(file=None, dir=None):
464 """Execute the PyMOL macro from the given text file. 465 466 @keyword file: The name of the macro file to execute. 467 @type file: str 468 @keyword dir: The name of the directory where the macro file is located. 469 @type dir: str 470 """ 471 472 # Open the file for reading. 473 file_path = get_file_path(file, dir) 474 file = open_read_file(file, dir) 475 476 # Loop over the commands and apply them. 477 for command in file.readlines(): 478 pymol_obj.exec_cmd(command)
479 480
481 -def macro_write(data_type=None, style="classic", colour_start_name=None, colour_start_rgb=None, colour_end_name=None, colour_end_rgb=None, colour_list=None, file=None, dir=None, force=False):
482 """Create a PyMOL macro file. 483 484 @keyword data_type: The data type to map to the structure. 485 @type data_type: str 486 @keyword style: The style of the macro. 487 @type style: str 488 @keyword colour_start_name: The name of the starting colour of the linear gradient. 489 @type colour_start_name: str 490 @keyword colour_start_rgb: The RGB array starting colour of the linear gradient. 491 @type colour_start_rgb: RBG colour array (len 3 with vals from 0 to 1) 492 @keyword colour_end_name: The name of the ending colour of the linear gradient. 493 @type colour_end_name: str 494 @keyword colour_end_rgb: The RGB array ending colour of the linear gradient. 495 @type colour_end_rgb: RBG colour array (len 3 with vals from 0 to 1) 496 @keyword colour_list: The colour list to search for the colour names. Can be either 'molmol' or 'x11'. 497 @type colour_list: str or None 498 @keyword file: The name of the macro file to create. 499 @type file: str 500 @keyword dir: The name of the directory to place the macro file into. 501 @type dir: str 502 @keyword force: Flag which if set to True will cause any pre-existing file to be overwritten. 503 @type force: bool 504 """ 505 506 # Test if the current data pipe exists. 507 pipes.test() 508 509 # Test if sequence data exists. 510 if not exists_mol_res_spin_data(): 511 raise RelaxNoSequenceError 512 513 # Check the arguments. 514 if colour_start_name != None and colour_start_rgb != None: 515 raise RelaxError("The starting colour name and RGB colour array cannot both be supplied.") 516 if colour_end_name != None and colour_end_rgb != None: 517 raise RelaxError("The ending colour name and RGB colour array cannot both be supplied.") 518 519 # Merge the colour args. 520 if colour_start_name != None: 521 colour_start = colour_start_name 522 else: 523 colour_start = colour_start_rgb 524 if colour_end_name != None: 525 colour_end = colour_end_name 526 else: 527 colour_end = colour_end_rgb 528 529 # Create the macro. 530 commands = create_macro(data_type=data_type, style=style, colour_start=colour_start, colour_end=colour_end, colour_list=colour_list) 531 532 # File name. 533 if file == None: 534 file = data_type + '.pml' 535 536 # Open the file for writing. 537 file_path = get_file_path(file, dir) 538 file = open_write_file(file, dir, force) 539 540 # Loop over the commands and write them. 541 for command in commands: 542 file.write(command + "\n") 543 544 # Close the file. 545 file.close() 546 547 # Add the file to the results file list. 548 add_result_file(type='pymol', label='PyMOL', file=file_path)
549 550
551 -def tensor_pdb(file=None):
552 """Display the diffusion tensor geometric structure. 553 554 @keyword file: The name of the file containing the diffusion tensor geometric object. 555 @type file: str 556 """ 557 558 # Test if the current data pipe exists. 559 pipes.test() 560 561 # Read in the tensor PDB file. 562 pymol_obj.exec_cmd("load " + file) 563 564 565 # The tensor object. 566 #################### 567 568 # Select the TNS residue. 569 pymol_obj.exec_cmd("select resn TNS") 570 571 # Hide everything. 572 pymol_obj.exec_cmd("hide ('sele')") 573 574 # Show as 'sticks'. 575 pymol_obj.exec_cmd("show sticks, 'sele'") 576 577 578 # Centre of mass. 579 ################# 580 581 # Select the COM residue. 582 pymol_obj.exec_cmd("select resn COM") 583 584 # Show the centre of mass as the dots representation. 585 pymol_obj.exec_cmd("show dots, 'sele'") 586 587 # Colour it blue. 588 pymol_obj.exec_cmd("color blue, 'sele'") 589 590 591 # The diffusion tensor axes. 592 ############################ 593 594 # Select the AXS residue. 595 pymol_obj.exec_cmd("select resn AXS") 596 597 # Hide everything. 598 pymol_obj.exec_cmd("hide ('sele')") 599 600 # Show as 'sticks'. 601 pymol_obj.exec_cmd("show sticks, 'sele'") 602 603 # Colour it cyan. 604 pymol_obj.exec_cmd("color cyan, 'sele'") 605 606 # Select the N atoms of the AXS residue (used to display the axis labels). 607 pymol_obj.exec_cmd("select (resn AXS and elem N)") 608 609 # Label the atoms. 610 pymol_obj.exec_cmd("label 'sele', name") 611 612 613 614 # Monte Carlo simulations. 615 ########################## 616 617 # Select the SIM residue. 618 pymol_obj.exec_cmd("select resn SIM") 619 620 # Colour it. 621 pymol_obj.exec_cmd("colour cyan, 'sele'") 622 623 624 # Clean up. 625 ########### 626 627 # Remove the selection. 628 pymol_obj.exec_cmd("cmd.delete('sele')")
629 630
631 -def vector_dist(file=None):
632 """Display the XH bond vector distribution. 633 634 @keyword file: The vector distribution PDB file. 635 @type file: str 636 """ 637 638 # Test if the current data pipe exists. 639 pipes.test() 640 641 # The file root. 642 id = file_root(file) 643 644 # Read in the vector distribution PDB file. 645 pymol_obj.exec_cmd("load " + file) 646 647 648 # Create a surface. 649 ################### 650 651 # Select the vector distribution. 652 pymol_obj.exec_cmd("cmd.show('surface', " + repr(id) + ")")
653 654
655 -def view():
656 """Start PyMOL.""" 657 658 # Open PyMOL. 659 if pymol_obj.running(): 660 raise RelaxError("PyMOL is already running.") 661 else: 662 pymol_obj.open_gui()
663