Answers.Body: <p>PyMOL in itself can be used as python package.
  The GUI app has its own Python, but in a conda environment you can install it as a package.
  Any PyMOL app command can be used as a cmd command. In PyMOL Wiki you see both. They follow a similar pattern and actually have more functionality.</p>
  <pre><code>import pymol2
  with pymol2.PYMOL() as pymol:
      pymol.cmd.load('foo.pdb', 'foo')
      pymol.cmd.load('bar.pdb', 'bar')
      pymol.cmd.align('foo', 'bar')
      pymol.cmd.save('foobar.aln')
  </code></pre>
  <p>For more discussion of how the alignment output object is used see <a href="https://bioinformatics.stackexchange.com/questions/14919/assessing-pymol-sequence-alignment-object/14936#14936">Assessing PyMol sequence alignment object</a></p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-06-27T10:40:24.913Z
Answers.Text: Hi! Thanks so much for your answer. Sorry it took me so long to say anything, I was testing all the options. Also, I'm sorry I don't have enough reputation to upvote your answer. Is there any way I could save the alignment in a Python text stream, as in an io.StringIO() stream? So that I don't save any file in the process. I made some attempts but I couldn't hack it and I didn't see anything related in your previous answer that you linked. Thanks in advance!
Answers.UserDisplayName: Francho Nerín Fonz
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-06-27T14:21:29.477Z
Answers.Text: Nah, the important thing is that marked as solved, thus helping the healthiness of the site, which struggled to leave beta because of high unsolved cases —so thanks!
  I don't know off the top of my head, but https://docs.python.org/3/library/tempfile.html may be of use. There is likely a function that is not imported by the top of cmd module, but is present in one of the submodules. Maybe one of the searches in the open-source PyMOL repo might help https://github.com/schrodinger/pymol-open-source/search?q=.aln (sorry I'm tight for time atm)
Answers.UserDisplayName: Matteo Ferla
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-06-27T14:41:07.387Z
Answers.Text: Thanks for the pointers! I finally found out how to retrieve the alignment string, I'm going to edit my question to put the final answer in it.
Answers.UserDisplayName: Francho Nerín Fonz
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-06-27T15:34:06.040Z
Answers.Text: @MatteoFerla any way to use it in python without anaconda enviroment ? https://stackoverflow.com/questions/63958085/how-to-embed-the-pymol-module-into-python
Answers.UserDisplayName: pippo1980
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-06-27T16:16:10.027Z
Answers.Text: Hi @pippo1980 maybe a separate question? Generally not advised, you could use `venv` and `pip`, but historically there were compatibility issues between `conda` and `pip` (probably resolved)
Answers.UserDisplayName: M__
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-06-27T16:19:08.933Z
Answers.Text: Anyway thanks @FranchoNerínFonz for finalising the post. Very interesting (and useful) question and answer indeed.
Answers.UserDisplayName: M__
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-06-27T16:29:05.543Z
Answers.Text: @pippo1980 The classic solution was installing the OS pymol —which is not installed via conda but with wizardry and  the deprecated `python setup.py install` (not `pip install .`) https://github.com/schrodinger/pymol-open-source/blob/master/INSTALL —alternatively, there's always the nightmarish über-hack of copypasting of site-packages folders from a conda installation to a vanilla Python... But that's a big no no due to irreproducibility.
Answers.UserDisplayName: Matteo Ferla
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-05-24T09:11:47.763Z
Answers.LastActivityDate: 2022-05-24T09:11:47.763Z
Answers.UserDisplayName: Matteo Ferla
Body: <p>I am looking for a Python package that performs pairwise structural alignment of protein structures (i.e., PDB files) and returns a sequence alignment. PyMOL is able to do this through the GUI, for example:</p>
  <p><a href="https://i.sstatic.net/mtLMF.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/mtLMF.png" alt="PyMOL GUI showing two protein structures and their sequences" /></a></p>
  <p>For two protein PDBs, one can be aligned to the other with the &quot;align&quot; menu or <code>align</code> command:</p>
  <p><a href="https://i.sstatic.net/weICw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/weICw.png" alt="PyMOL GUI showing the two protein structures superimposed and their sequences aligned position by position (and with gaps)" /></a></p>
  <p>With it, the sequences appear aligned in the sequence viewer according to the structural alignment, and an &quot;alignment&quot; object is created, which can be saved with the command:</p>
  <p><code>save A_aligned_with_B.aln, aln_structure_1_to_structure_0</code></p>
  <p>which produces the <code>A_aligned_with_B.aln</code> alignment file in Clustal format (nevermind the ?s, which correspond to special HIS resnames):</p>
  <pre><code>CLUSTAL
  
  structure_0  YIYQDSISLPWKVLLVMLLALITLATTLSNAFVIATVYRTRKL?TPANYLIASLAVTDLLVSI
  structure_1  EEQGNKL?WAALLILMVIIPTIG-----GNTLVILAVSLEKKLQYATNYFLMSLAVADLLVGL
                                           .*..**..*....**....**...****.****..
  
  structure_0  LVMPISTMYTVT-GRWTLGQVVCDFWLSSDITCCTASIL?LCVIALDRYWAITDAVEYSAKRT
  structure_1  FVMPIALLTIMFEAMWPLPLVLCPAWLFLDVLFSTASIM?LCAISVDRYIAIKKPIQANQYNS
               .****......  ..*.*..*.*..**..*....****.***.*..***.**........ ..
  
  structure_0  PKRAAVMIALVWVFSISISLPP-FFWRQAKAEEEVSE-CVVNTD?IL-YTVYSTVGAFYFPTL
  structure_1  RATAFIKITVVWLISIGIAIPVPIKGIETDVDNPNNITCVLTKERFGDFMLFGSLAAFFTPLA
               ...*...*..**..**.*..*  .              **....    ........**..*..
  
  structure_0  LLIALYGRIYVEARSRILKQTPNRTGKLLEKKKLMAAR--ERKATKTLGIILGAFIVCWLPFF
  structure_1  IMIVTYFLTI?ALQKKAYLVKNKPPQRLTIGKKSVQTISNEQRASKVLGIVFFLFLLMWCPFF
               ..*..*....                              * .*.*.***....*...*.***
  
  structure_0  IISLVMPICKDACW--F?LAIFDFFTWLGYLNSLINPIIYTMSNEDFKQAF?KLIRFK--   
  structure_1  ITNITLVLCDS-CNQTTLQMLLEIFVWIGYVSSGVNPLVYTLFNKTFRDAFGRYITCNYR   
               *.......*   *   .  .....*.*.**..*..**..**..*..*..**         
  </code></pre>
  <p>I need a Python package that is easily installable/distributable that accepts two PDBs or protein structures and returns the structural alignment of the sequences somehow. All within a Python script, and not creating intermediate files, e.g. for the alignment.</p>
  <p>There are plenty of Python tools that allow structural superimposition and RMSD calculation (e.g., Biopython), but I haven't found any that are able to return a sequence alignment from the structural alignment.</p>
  <p><strong>Edit:</strong></p>
  <p>Possible answer, thanks to the answer and comments from <a href="https://bioinformatics.stackexchange.com/a/19109/15529">Matteo Ferla</a>.</p>
  <pre class="lang-py prettyprint-override"><code>import pymol2
  with pymol2.PyMOL() as pymol:
      pymol.cmd.load('foo.pdb', 'foo')
      pymol.cmd.load('bar.pdb', 'bar')
      pymol.cmd.align('foo', 'bar', object='aln')
      aln = pymol2.cmd2.pymol.exporting.get_alnstr('aln', _self=pymol.cmd) # I don't know if this line could be cleaner
      # aln is itself a string
  </code></pre>
  
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2022-05-23T17:56:27.010Z
Comments.Text: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comments.UserDisplayName: Community
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2022-05-24T03:58:03.420Z
Comments.Text: Please provide more details to help us in answering your question. For example, showing the alignment that you would like to see from Chimera or PyMOL. Showing the first few lines of any input files is also helpful (or, at least, providing two demonstrative PDB IDs that you are interested in).
Comments.UserDisplayName: gringer
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2022-05-24T09:06:39.760Z
Comments.Text: This was asked before here —I know because I answered it. You want the primary sequence alignment based on PyMOL's superimposition of tertiary structure.
Comments.UserDisplayName: Matteo Ferla
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2022-05-24T09:07:50.063Z
Comments.Text: Ignore my comment. I saw your Q was just updated...
Comments.UserDisplayName: Matteo Ferla
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2023-06-26T09:48:03.463Z
Comments.Text: "align" performs a sequence alignment followed by a structural
      superposition, and then carries out zero or more cycles of
      refinement in order to reject structural outliers found during
      the fit. "align" does a good job on proteins with decent sequence
      similarity (identity >30%). For comparing proteins with lower
      sequence identity, the "super" and "cealign" commands perform
      better.
Comments.UserDisplayName: pippo1980
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2023-06-26T10:02:56.567Z
Comments.Text: cealign aligns two proteins using the CE algorithm. It is very robust for proteins with little to no sequence similarity (twilight zone). For proteins with decent structural similarity, the super command is preferred and with decent sequence similarity, the align command is preferred, because these commands are much faster than cealign.
Comments.UserDisplayName: pippo1980
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2023-06-26T10:04:17.907Z
Comments.Text: yoiu can save a clustal object as a result of cealign, cealign target, mobile [, target_state [, mobile_state
      [, quiet [, guide [, d0 [, d1 [, window [, gap_max
      [, transform [, object ]]]]]]]]]]   --> object = string: name of alignment object to create {default: (no alignment object)}  https://pymolwiki.org/index.php/Cealign
Comments.UserDisplayName: pippo1980
Tags: <phylogenetics><proteins><protein-structure>
Title: Perform protein structure-based sequence alignment in Python
ThreadText: # Perform protein structure-based sequence alignment in Python
  
  (Asked by: username_0 on 2022-05-23)
  
  I am looking for a Python package that performs pairwise structural alignment of protein structures (i.e., PDB files) and returns a sequence alignment. PyMOL is able to do this through the GUI, for example:
  
  [![PyMOL GUI showing two protein structures and their sequences](https://i.sstatic.net/mtLMF.png)](https://i.sstatic.net/mtLMF.png)
  
  For two protein PDBs, one can be aligned to the other with the "align" menu or `align` command:
  
  [![PyMOL GUI showing the two protein structures superimposed and their sequences aligned position by position (and with gaps)](https://i.sstatic.net/weICw.png)](https://i.sstatic.net/weICw.png)
  
  With it, the sequences appear aligned in the sequence viewer according to the structural alignment, and an "alignment" object is created, which can be saved with the command:
  
  `save A_aligned_with_B.aln, aln_structure_1_to_structure_0`
  
  which produces the `A_aligned_with_B.aln` alignment file in Clustal format (nevermind the ?s, which correspond to special HIS resnames):
  
  ```
  CLUSTAL
  
  structure_0  YIYQDSISLPWKVLLVMLLALITLATTLSNAFVIATVYRTRKL?TPANYLIASLAVTDLLVSI
  structure_1  EEQGNKL?WAALLILMVIIPTIG-----GNTLVILAVSLEKKLQYATNYFLMSLAVADLLVGL
                                           .*..**..*....**....**...****.****..
  
  structure_0  LVMPISTMYTVT-GRWTLGQVVCDFWLSSDITCCTASIL?LCVIALDRYWAITDAVEYSAKRT
  structure_1  FVMPIALLTIMFEAMWPLPLVLCPAWLFLDVLFSTASIM?LCAISVDRYIAIKKPIQANQYNS
               .****......  ..*.*..*.*..**..*....****.***.*..***.**........ ..
  
  structure_0  PKRAAVMIALVWVFSISISLPP-FFWRQAKAEEEVSE-CVVNTD?IL-YTVYSTVGAFYFPTL
  structure_1  RATAFIKITVVWLISIGIAIPVPIKGIETDVDNPNNITCVLTKERFGDFMLFGSLAAFFTPLA
               ...*...*..**..**.*..*  .              **....    ........**..*..
  
  structure_0  LLIALYGRIYVEARSRILKQTPNRTGKLLEKKKLMAAR--ERKATKTLGIILGAFIVCWLPFF
  structure_1  IMIVTYFLTI?ALQKKAYLVKNKPPQRLTIGKKSVQTISNEQRASKVLGIVFFLFLLMWCPFF
               ..*..*....                              * .*.*.***....*...*.***
  
  structure_0  IISLVMPICKDACW--F?LAIFDFFTWLGYLNSLINPIIYTMSNEDFKQAF?KLIRFK--   
  structure_1  ITNITLVLCDS-CNQTTLQMLLEIFVWIGYVSSGVNPLVYTLFNKTFRDAFGRYITCNYR   
               *.......*   *   .  .....*.*.**..*..**..**..*..*..**         
  
  ```
  
  I need a Python package that is easily installable/distributable that accepts two PDBs or protein structures and returns the structural alignment of the sequences somehow. All within a Python script, and not creating intermediate files, e.g. for the alignment.
  
  There are plenty of Python tools that allow structural superimposition and RMSD calculation (e.g., Biopython), but I haven't found any that are able to return a sequence alignment from the structural alignment.
  
  **Edit:**
  
  Possible answer, thanks to the answer and comments from [username_3 username_3](https://bioinformatics.stackexchange.com/a/19109/15529).
  
  ```py
  import pymol2
  with pymol2.PyMOL() as pymol:
      pymol.cmd.load('foo.pdb', 'foo')
      pymol.cmd.load('bar.pdb', 'bar')
      pymol.cmd.align('foo', 'bar', object='aln')
      aln = pymol2.cmd2.pymol.exporting.get_alnstr('aln', _self=pymol.cmd) # I don't know if this line could be cleaner
      # aln is itself a string
  
  ```
  
  **Tags:** phylogenetics, proteins, protein-structure
  
  > **Comments:**
  > **username_1**: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.  
  > **username_2**: Please provide more details to help us in answering your question. For example, showing the alignment that you would like to see from Chimera or PyMOL. Showing the first few lines of any input files is also helpful (or, at least, providing two demonstrative PDB IDs that you are interested in).  
  > **username_3**: This was asked before here —I know because I answered it. You want the primary sequence alignment based on PyMOL's superimposition of tertiary structure.  
  > **username_3**: Ignore my comment. I saw your Q was just updated...  
  > **username_4**: "align" performs a sequence alignment followed by a structural     superposition, and then carries out zero or more cycles of     refinement in order to reject structural outliers found during     the fit. "align" does a good job on proteins with decent sequence     similarity (identity >30%). For comparing proteins with lower     sequence identity, the "super" and "cealign" commands perform     better.  
  > **username_4**: cealign aligns two proteins using the CE algorithm. It is very robust for proteins with little to no sequence similarity (twilight zone). For proteins with decent structural similarity, the super command is preferred and with decent sequence similarity, the align command is preferred, because these commands are much faster than cealign.  
  > **username_4**: yoiu can save a clustal object as a result of cealign, cealign target, mobile [, target_state [, mobile_state     [, quiet [, guide [, d0 [, d1 [, window [, gap_max     [, transform [, object ]]]]]]]]]]   --> object = string: name of alignment object to create {default: (no alignment object)}  https://pymolwiki.org/index.php/Cealign  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_3 on 2022-05-24. Score: 2 | Accepted answer
  
  PyMOL in itself can be used as python package.
  The GUI app has its own Python, but in a conda environment you can install it as a package.
  Any PyMOL app command can be used as a cmd command. In PyMOL Wiki you see both. They follow a similar pattern and actually have more functionality.
  
  ```
  import pymol2
  with pymol2.PYMOL() as pymol:
      pymol.cmd.load('foo.pdb', 'foo')
      pymol.cmd.load('bar.pdb', 'bar')
      pymol.cmd.align('foo', 'bar')
      pymol.cmd.save('foobar.aln')
  
  ```
  
  For more discussion of how the alignment output object is used see [Assessing PyMol sequence alignment object](https://bioinformatics.stackexchange.com/questions/14919/assessing-pymol-sequence-alignment-object/14936#14936)
  
  > **Comments:**
  > **username_0**: Hi! Thanks so much for your answer. Sorry it took me so long to say anything, I was testing all the options. Also, I'm sorry I don't have enough reputation to upvote your answer. Is there any way I could save the alignment in a Python text stream, as in an io.StringIO() stream? So that I don't save any file in the process. I made some attempts but I couldn't hack it and I didn't see anything related in your previous answer that you linked. Thanks in advance!  
  > **username_3**: Nah, the important thing is that marked as solved, thus helping the healthiness of the site, which struggled to leave beta because of high unsolved cases —so thanks! I don't know off the top of my head, but https://docs.python.org/3/library/tempfile.html may be of use. There is likely a function that is not imported by the top of cmd module, but is present in one of the submodules. Maybe one of the searches in the open-source PyMOL repo might help https://github.com/schrodinger/pymol-open-source/search?q=.aln (sorry I'm tight for time atm)  
  > **username_0**: Thanks for the pointers! I finally found out how to retrieve the alignment string, I'm going to edit my question to put the final answer in it.  
  > **username_4**: @username_3 any way to use it in python without anaconda enviroment ? https://stackoverflow.com/questions/63958085/how-to-embed-the-pymol-module-into-python  
  > **username_5**: Hi @username_4 maybe a separate question? Generally not advised, you could use `venv` and `pip`, but historically there were compatibility issues between `conda` and `pip` (probably resolved)  
  > **username_5**: Anyway thanks @username_0 for finalising the post. Very interesting (and useful) question and answer indeed.  
  > **username_3**: @username_4 The classic solution was installing the OS pymol —which is not installed via conda but with wizardry and  the deprecated `python setup.py install` (not `pip install .`) https://github.com/schrodinger/pymol-open-source/blob/master/INSTALL —alternatively, there's always the nightmarish über-hack of copypasting of site-packages folders from a conda installation to a vanilla Python... But that's a big no no due to irreproducibility.  
  
  ---
  
  