Difference between revisions of "Recycling Corner"

From Jmol
Jump to navigation Jump to search
(Rendering protein chain according to B-factor)
m (Visually transfer a hydrogen from a donor to an acceptor)
 
(3 intermediate revisions by the same user not shown)
Line 3: Line 3:
 
Feel free to add your material!
 
Feel free to add your material!
  
For example:
+
<big>
 +
* [[Recycling_Corner/Logos_Banners_Icons|Jmol logos, banners, icons]]
 +
* [[Recycling_Corner/Templates|Templates for creating Jmol webpages]]
 +
* [[Recycling_Corner/Menus|Custom pop-up menus]]
 +
* Reusable scripts: keep reading below
 +
</big>
  
== Jmol logos, banners, icons ==
+
<div style="font-size:2em;"> Reusable scripts </div>
  
=== New 2013 Jmol icon and logos ===
+
== Color picker ==
  
Icon, png:
 
 
[[Image:Jmol_icon13.png]]
 
 
[[Image:Jmol_icon_13.ico.zip|Windows icon]]; .ico files cannot be shown on this webpage, but you can download this one zipped.
 
 
for more icon formats, visit [http://biomodel.uah.es/Jmol/logos/ Angel's webpage]
 
 
Logos and banners:
 
 
[[Image:Jmol_logo13.png]]
 
[[Image:JSmol_logo13.png]]
 
 
'Made with Jmol' banners, in several languages: [[Jmol_Images]]
 
 
=== Older versions ===
 
 
[[Jmol_Images|Old logos and icons]]
 
 
 
== Templates for creating Jmol webpages ==
 
 
=== Jmol_Web_Page_Maker ===
 
Jonathan Gutow has written a Java program that automates generation of webpages that include Jmol.  The two templates below are among the types of web pages that can be generated. When using Jmol_Web_Page_Maker for the templates below, you can choose the view(s) to be displayed inside the Jmol application and have the necessary scripts, images plus .html code generated and saved automatically. Visit [http://www.uwosh.edu/faculty_staff/gutow/Jmol_Web_Page_Maker/Jmol_Web_Page_Maker.shtml his website].
 
 
'''This is now superceeded by the "export to web page" ability included within recent versions of Jmol application (11.3.x).'''
 
 
''Easy assignments for students or quick building of a simple page!''
 
 
=== SChiSM2 ===
 
SChiSM2 is a program running in a web server that lets you easily create a web page that includes interactive molecular models using JmolApplet.
 
* [http://ci.vbi.vt.edu/cammer/schism2.html SChiSM2 home page]
 
* A description has been published:
 
: S. Cammer (2007) SChiSM2: creating interactive web page annotations of molecular structure models using Jmol. ''Bioinformatics'' '''23''':383-384. doi:10.1093/bioinformatics/btl603 [http://bioinformatics.oxfordjournals.org/cgi/content/abstract/23/3/383]
 
 
=== Jmol "pop-up" and "pop-in" ===
 
Delays the appearance of Jmol panel until the user requests it. An image or caption is shown and upon user's choice it is replaced by the applet.
 
 
''No more waiting for Java and Jmol to load if you are not interested in the 3D model!''
 
 
Two methods have been developed:
 
* Method A - versatile: The user clicks to see the 3D model, and chooses whether it will be opened inline within the page (“pop-in”), or in a common pop-up window, or in separate pop-up windows for each model. (Uses &lt;iframe&gt;.)
 
* Method B - simpler: The user clicks to see the 3D model, always inline within the page (“pop-in”). (Uses &lt;div&gt;.) (A similar method is used on [http://www.jmol.org/ Jmol home webpage].)
 
 
You can find more details, demo pages and downloadable templates for both methods at [http://biomodel.uah.es/Jmol/pop-in/ Biomodel website].
 
 
For an alternative method, see [http://www.cem.msu.edu/~reusch/VirtTxtJml/strcopen.htm Bill Reusch's page] that uses innerHTML.
 
 
For other pop-up solutions, see also [[#Opening_a_duplicate_of_the_model_in_a_resizable_pop-up_window|below]].
 
 
=== Dynamically resized panels layout ===
 
Six templates for dividing the screen into two or more panels, either for Jmol or for content, all sized in percent relative to window size, using the whole window space, and automatically resized when the window is resized; no scrollbars in Jmol section, scrollbars in content if needed, no duplicate parallel scrollbars.
 
 
''No more guessing the user's screen resolution, browser chrome, default font size!''
 
 
[[Image:Resizable-panels.png]]
 
 
You can find more details, demo pages and downloadable templates at [http://biomodel.uah.es/Jmol/resizable/ Biomodel website].
 
 
== Reusable scripts ==
 
 
=== Molecule color picker ===
 
 
[[Image:molcolpicker.gif]] [[Image:appcolpicker.gif]]
 
[[Image:molcolpicker.gif]] [[Image:appcolpicker.gif]]
  
The code below was used to create the palettes shown above. It's a pure javascript color picker that can be used for changing color of selected part of molecule, applet background, or any feature of the model (cartoons, surfaces, etc.).
+
The code below was used to create the palettes shown above. It's a pure javascript color picker that can be used for changing color of selected part of molecule, JSmol background, or any feature of the model (cartoons, surfaces, etc.).
  
 
Sample of use, JavaScript code needed, example page: [[Recycling_Corner/Molecule_color_picker]]
 
Sample of use, JavaScript code needed, example page: [[Recycling_Corner/Molecule_color_picker]]
 +
 +
== Spin controls ==
  
 
=== "Basic" spin toggle ===
 
=== "Basic" spin toggle ===
Line 92: Line 37:
  
 
=== "Foolproof" spin toggle ===
 
=== "Foolproof" spin toggle ===
Reads the current spin status from the applet and changes it, so it can cope with any other previous change via script, popup menu, page controls, etc.
+
Reads the current spin status from JSmol and changes it, so it can cope with any other previous change via script, popup menu, page controls, etc.
 
 
==== The best and simplest trick: ====
 
  
 +
=== The best and simplest trick: ===
 
Valid for recent versions of Jmol:
 
Valid for recent versions of Jmol:
 
<pre>
 
<pre>
Line 109: Line 53:
 
(''The words "toggle spin" above can be changed to any other text you like.'')
 
(''The words "toggle spin" above can be changed to any other text you like.'')
  
==== The old trick: ====
+
=== The old trick: ===
  
 
Only compatible with '''Jmol 11.x''' (as long as <code>Jmol.js</code> is being used in the web page).
 
Only compatible with '''Jmol 11.x''' (as long as <code>Jmol.js</code> is being used in the web page).
Line 143: Line 87:
 
(''The word "messageProcess" above can be changed to any other text you like, as long as it is the same in the above two sections of code.'')
 
(''The word "messageProcess" above can be changed to any other text you like, as long as it is the same in the above two sections of code.'')
  
=== Slider controls for Jmol ===
+
== Slider controls for Jmol ==
 
See [[Recycling_Corner/Slider controls]]
 
See [[Recycling_Corner/Slider controls]]
  
=== Echoing PDB "Title" to the applet window ===
+
== Echoing PDB "Title" to the JSmol panel ==
The following JavaScript code snippet will report the title of a PDB entry to the applet window when a PDB file is loaded.  This should be included within a JavaScript portion of the html file that loads the applet and the PDB file.  One caveat: the "TITLE" in a PDB file is depositor-generated and may or may not be "useful" to the end user!  :)
+
The following JavaScript code snippet will report the title of a PDB entry to the JSmol panel when a PDB file is loaded.  This should be included within a JavaScript portion of the html file that loads both JSmol and the PDB file.  One caveat: the "TITLE" in a PDB file is depositor-generated and may or may not be "useful" to the end user!  :)
  
 
  var headerInfo = jmolGetPropertyAsString("fileHeader");
 
  var headerInfo = jmolGetPropertyAsString("fileHeader");
Line 178: Line 122:
 
  echo @{getheader()}
 
  echo @{getheader()}
  
=== Providing a 'please wait' notice while the applet loads ===
+
== Providing a 'please wait' notice while JSmol loads ==
 
in a [[Loading_Notice|separate page]]
 
in a [[Loading_Notice|separate page]]
  
=== Exporting an image from the applet ===
+
== Exporting an image from JSmol ==
An image of the current view may be exported from the Jmol applet, either
+
An image of the current view may be exported from JSmol, either
* [http://biomodel.uah.es/Jmol/export-image/ in a pop-up window], also compatible with '''JSO''' and '''JSmol'''.
+
* [https://biomodel.uah.es/Jmol/export-image/ in a pop-up window], also compatible with '''JSO''' and '''JSmol'''.
 
* [http://www.marietta.edu/%7Espilatrs/MnQuiry/JmolDemo/jmolImgCopy-test.html inserted into the same web page]
 
* [http://www.marietta.edu/%7Espilatrs/MnQuiry/JmolDemo/jmolImgCopy-test.html inserted into the same web page]
  
 
+
== Opening a duplicate of the model in a resizable pop-up window ==
=== Opening a duplicate of the model in a resizable pop-up window ===
 
 
The model, with is current state, is duplicated or cloned into a new (pop-up) window so it may be displayed at a larger size (and the user may resize that window at will).
 
The model, with is current state, is duplicated or cloned into a new (pop-up) window so it may be displayed at a larger size (and the user may resize that window at will).
  
 
See [[Recycling_Corner/Duplicate_Pop-up]]
 
See [[Recycling_Corner/Duplicate_Pop-up]]
  
 
+
== Style transitions ==
=== Style transitions ===
 
 
Smooth transitions from one rendering style to another.
 
Smooth transitions from one rendering style to another.
  
==== Spacefill to ball & stick ====
+
=== Spacefill to ball & stick ===
 
<pre>for (var i=0;i<=9;i++) {
 
<pre>for (var i=0;i<=9;i++) {
 
  s=100-80*i/9;
 
  s=100-80*i/9;
Line 207: Line 149:
 
  for(var i=0;i<=9;i++){s=100-80*i/9;spacefill @s%;w=0.9-0.75*i/9;wireframe @w;delay 0.2;}
 
  for(var i=0;i<=9;i++){s=100-80*i/9;spacefill @s%;w=0.9-0.75*i/9;wireframe @w;delay 0.2;}
  
 +
== Replacing applet with signed applet upon demand ==
 +
''Note: this is legacy code for the Jmol Java applet, but it may be adapted for a change between JSmol modalities (HTML5 and WebGL)''
  
=== Replacing applet with signed applet upon demand ===
 
 
The signed applet has [[Jmol_Applet#Unsigned_vs._Signed_Applet_.26_Data_Access|certain capabilities]] that the unsigned applet lacks, but using the signed applet will raise some dialogs with security warnings that the general user may find scary and, if permission is denied, the expanded features will not be available and hence the page will fail to do what is expected.
 
The signed applet has [[Jmol_Applet#Unsigned_vs._Signed_Applet_.26_Data_Access|certain capabilities]] that the unsigned applet lacks, but using the signed applet will raise some dialogs with security warnings that the general user may find scary and, if permission is denied, the expanded features will not be available and hence the page will fail to do what is expected.
  
Line 236: Line 179:
  
  
=== Including special characters in echo ===
+
== Including special characters in echo ==
 
Non-keyboard characters may be included in echo texts using their Unicode character number, like this:
 
Non-keyboard characters may be included in echo texts using their Unicode character number, like this:
 
  echo "\u03B1 is the alpha letter";
 
  echo "\u03B1 is the alpha letter";
Line 259: Line 202:
 
[[File:Unicode triangle arrows.png]]
 
[[File:Unicode triangle arrows.png]]
  
=== Center of mass ===
+
== Center of mass ==
 
Jmol centers the model around its geometric center, i.e. the center of the boundbox. If you are interested in the mass center of the molecule:
 
Jmol centers the model around its geometric center, i.e. the center of the boundbox. If you are interested in the mass center of the molecule:
  
 
See [[Recycling_Corner/Center_Of_Mass]]
 
See [[Recycling_Corner/Center_Of_Mass]]
  
 +
== Building helical molecules==
  
 
=== RIBOZOME - an Alpha Helix Generator script ===
 
=== RIBOZOME - an Alpha Helix Generator script ===
Line 278: Line 222:
  
  
=== Drawing objects ===
+
== Drawing objects ==
==== Cylinder ====
+
=== Cylinder ===
 
To draw a cylinder, you need this information:
 
To draw a cylinder, you need this information:
 
* two points that define the axis of the cylinder and its length
 
* two points that define the axis of the cylinder and its length
Line 294: Line 238:
 
For options, see documentation for the [{{ScriptingDoc}}#draw draw] command.
 
For options, see documentation for the [{{ScriptingDoc}}#draw draw] command.
  
==== Ellipsoid ====
+
=== Ellipsoid ===
 
Starting from these:
 
Starting from these:
 
* two points that define the main axis of the ellipsoid and its length
 
* two points that define the main axis of the ellipsoid and its length
Line 312: Line 256:
 
  isosurface myEllipB color translucent 0.7 lime scale @dL resolution @dR center @dC ellipsoid {@dx @dy @dz @dE} fill;
 
  isosurface myEllipB color translucent 0.7 lime scale @dL resolution @dR center @dC ellipsoid {@dx @dy @dz @dE} fill;
 
Resolution and eccentricity will need to be adjusted depending on your case.
 
Resolution and eccentricity will need to be adjusted depending on your case.
 +
 +
 +
== Legends inside J(S)mol panel ==
  
 
=== Element legend ===
 
=== Element legend ===
Line 332: Line 279:
 
  }
 
  }
 
  createElementKey;
 
  createElementKey;
 
  
 
=== Rainbow color key (legend) ===
 
=== Rainbow color key (legend) ===
Line 361: Line 307:
  
  
=== Test if a file exists before displaying it ===
+
== Test if a file exists before displaying it ==
==== Using HTML, Javascript and Jmol scripting: ====
+
=== Using HTML, Javascript and Jmol scripting: ===
 
A Javascript function:
 
A Javascript function:
 
<pre>function loadFile(x) {
 
<pre>function loadFile(x) {
Line 377: Line 323:
 
</pre>
 
</pre>
  
==== Using Jmol callbacks to Javascript: ====
+
=== Using Jmol callbacks to Javascript: ===
 
Another possibility is to use [[Jmol_JavaScript_Object/Info#Callbacks|loadStructCallback]] to detect the failure in loading the file. For instance:
 
Another possibility is to use [[Jmol_JavaScript_Object/Info#Callbacks|loadStructCallback]] to detect the failure in loading the file. For instance:
  
Line 393: Line 339:
 
</pre>
 
</pre>
  
==== Using only Jmol scripting: ====
+
=== Using only Jmol scripting: ===
 
Javascript:
 
Javascript:
 
<pre>Info.script = 'function loadFile(x) { filedat=load(x); exists=true; '+
 
<pre>Info.script = 'function loadFile(x) { filedat=load(x); exists=true; '+
Line 408: Line 354:
 
</pre>
 
</pre>
  
==== Using an AJAX call: ====
+
=== Using an AJAX call: ===
 
Javascript:
 
Javascript:
 
<pre>function loadFile(pathFilenameExt) {
 
<pre>function loadFile(pathFilenameExt) {
Line 432: Line 378:
 
''(Based on a contribution by Bilal Nizami)''
 
''(Based on a contribution by Bilal Nizami)''
  
=== Improved lighting ===
+
 
 +
== Improved lighting ==
 +
 
 
The lighting of atoms, bonds and ribbons and the thickness of ribbons may be customized to provide a nicer look, by adjusting several settings. Here is an example:
 
The lighting of atoms, bonds and ribbons and the thickness of ribbons may be customized to provide a nicer look, by adjusting several settings. Here is an example:
  
Line 498: Line 446:
 
[{{ScriptingDoc}}#setlighting Scripting Documentation].
 
[{{ScriptingDoc}}#setlighting Scripting Documentation].
  
=== Extract phi and psi values ===
+
== Extract phi and psi values ==
 +
 
 
The dihedral angles phi and psi are known in Jmol, as properties of each amino acid residue in a protein, which are copied to properties of each atom in that residue.
 
The dihedral angles phi and psi are known in Jmol, as properties of each amino acid residue in a protein, which are copied to properties of each atom in that residue.
  
Line 561: Line 510:
 
</table>
 
</table>
  
=== Front of the molecule, selecting (by percentage) ===
+
== Front of the molecule, selecting (by percentage) ==
  
 
The Jmol function at [[Recycling_Corner/Front_Selection]] selects a specified percentage of the front of the molecule, according to the orientation of the molecule when the function is executed.
 
The Jmol function at [[Recycling_Corner/Front_Selection]] selects a specified percentage of the front of the molecule, according to the orientation of the molecule when the function is executed.
  
=== Exchange of data between JmolScript and JavaScript ===
+
 
 +
== Exchange of data between JmolScript and JavaScript ==
  
 
# Passing a variable from JavaScript to a JSmol variable:
 
# Passing a variable from JavaScript to a JSmol variable:
Line 573: Line 523:
 
#: <code>myJSvar = Jmol.evaluateVar(myJSmol, myJSmolVar) </code>. Instead of the name of the variable, in the position of myJSmolVar you may use a Jmol math expression or some information from the molecule. <code>myJSmol</code> is the id/name of the JSmol object in the webpage (e.g. myJmol or jmolApplet0). [[Jmol_JavaScript_Object/Functions#evaluateVar|More details about evaluateVar()]].
 
#: <code>myJSvar = Jmol.evaluateVar(myJSmol, myJSmolVar) </code>. Instead of the name of the variable, in the position of myJSmolVar you may use a Jmol math expression or some information from the molecule. <code>myJSmol</code> is the id/name of the JSmol object in the webpage (e.g. myJmol or jmolApplet0). [[Jmol_JavaScript_Object/Functions#evaluateVar|More details about evaluateVar()]].
  
=== Visually transfer a hydrogen from a donor to an acceptor ===
+
== Visually transfer a hydrogen from a donor to an acceptor ==
Script authored by [[User:Karsten Theis|Karsten W. Theis]].
+
Script authored by [[User:Karsten Theis|Karsten Theis]].
  
 
[[File:Grotthuss fast hires.gif|500px]] ''click to see animated''
 
[[File:Grotthuss fast hires.gif|500px]] ''click to see animated''
Line 611: Line 561:
  
 
== Rendering protein chain according to B-factor ==
 
== Rendering protein chain according to B-factor ==
This function will color protein trace according to the B-factor (temperature factor) of each alpha carbon and, at the same time, display ticker trace for the portions of highest B-factor. It was inspired by the "sausage" or "putty" rendering in Pymol.
+
This function will color protein trace according to the B-factor (temperature factor) of each alpha carbon and, at the same time, display thicker trace for the portions of highest B-factor. It was inspired by the "sausage" or "putty" rendering in Pymol.
  
 
First, apply the script that defines the function:
 
First, apply the script that defines the function:
 
<pre>
 
<pre>
function putty(s, grad) {
+
function putty(s, grad) { // v.2
 
  define temp selected;
 
  define temp selected;
 
  select s and alpha;
 
  select s and alpha;
  
  bMin = {selected}.temperature.min;
+
  var bMin = {selected}.temperature.min;
  bMax = {selected}.temperature.max;
+
  var bMax = {selected}.temperature.max;
  wMin = 0.2; // trace thickness for lowest B-factor
+
  var wMin = 0.2; // trace thickness for lowest B-factor (Angstroms)
  wMax = 1.5; // trace thickness for highest B-factor
+
  var wMax = 1.5; // trace thickness for highest B-factor
  for (a in {selected}) {
+
  for (var a in {selected}) {
   a.trace = wMin + (a.temperature - bMin) * (wMax - wMin) / (bMax - bMin);
+
   a.trace = wMin + (a.temperature - bMin) * (wMax - wMin) / (bMax - bMin)
 
  }
 
  }
  
  if (grad=="wr") { // low B = white, high B = red
+
var c = "";
  set userColorScheme [xFFFFFF] [xFFE0E0] [xFFD0D0] [xFFC0C0] [xFFB0B0] [xFFA0A0] [xFF9090] [xFF8080] [xFF7070] [xFF6060] [xFF5050] [xFF4040] [xFF3030] [xFF2020] [xFF1010] [xFF0000];
+
  if (grad=="wr") { // gradient white > red (low to high B)
   color trace property temperature "user" range @bMin @bMax;
+
   c = color("white", "red", 32, false);
  } else { // standard blue - white - red gradient (low to high B-factor)
+
  } else { // standard gradient blue > white > red (low to high B)
  color trace property temperature "bwr" range @bMin @bMax;
+
  c = color("blue", "white", 16, false) + color("white", "red", 16, false);
 
  }
 
  }
 +
color trace property temperature @c range @bMin @bMax;
 
 
 
  select temp;
 
  select temp;
 +
print "B-factor range: " + @bMin + " to " + @bMax; // tip in console
 
}
 
}
 
</pre>
 
</pre>
Line 641: Line 593:
 
  putty( {protein} );
 
  putty( {protein} );
 
  putty( {*:A}, "wr" );
 
  putty( {*:A}, "wr" );
  putty( {*:B}, "" );
+
  putty( {*:B} );
 
 
== Custom pop-up menus ==
 
Jmol (both application and applet) allows a customized pop-up menu instead of the standard default menu.
 
Their definition and use are explained in [[Custom Menus]].
 
 
 
Examples:
 
* Default menu is built using this: [{{SVN Trunk}}Jmol/jmol.mnu jmol.mnu]
 
* An example of custom menu: [[test.mnu]]
 
 
 
Users, if you design a new menu, please, share it here.
 
 
 
=== SimpleBio ===
 
[[image:SimpleBio_menu.jpg|right]]This is devised to ease the handling of the menu by inexperienced users with only basic tasks, in tutorial pages of simple biomolecules.
 
 
 
It includes just these entries:
 
* Style - with simplified contents.
 
* Color - compacted to have less submenu nesting.
 
* Spin - just with on/off, no axes or speed options.
 
* Select - a bit simplified.
 
* Advanced <sup>(*)</sup> - a new entry including:
 
** Choose menu <sup>(*)</sup> - that allows to revert to the standard full menu.
 
** Language
 
** Console
 
* About
 
 
 
''(*) These are new entries, and so will not be localized; you may wish to edit them for your intended language.''
 
 
 
You can get this custom menu [[SimpleBio.mnu | here]].
 
 
 
=== SimpleChem ===
 
[[image:SimpleChem_menu.jpg|right]]This is devised to ease the handling of the menu by inexperienced users with only basic tasks, in tutorial pages of organic/inorganic molecules (no crystallography, symmetry, vibration or animation, no pdb-related options).
 
 
 
It includes just these entries:
 
* Style - with simplified contents.
 
* Color - simplified.
 
* Spin - just with on/off, no axes or speed options.
 
* Select - a bit simplified.
 
* Measurements
 
* Advanced <sup>(*)</sup> - a new entry including:
 
** Choose menu <sup>(*)</sup> - that allows to revert to the standard full menu.
 
** Language
 
** Console
 
* About
 
 
 
''(*) These are new entries, and so will not be localized; you may wish to edit them for your intended language.''
 
 
 
You can get this custom menu [[SimpleChem.mnu | here]].
 
 
 
=== SimpleCryst ===
 
[[image:SimpleCryst_menu.jpg|right]]This is devised to ease the handling of the menu by inexperienced users with only basic tasks, in tutorial pages of crystallographic structures.
 
 
 
It includes just these entries:
 
* Style - with simplified contents.
 
* Color - simplified.
 
* Spin - just with on/off, no axes or speed options.
 
* Select - a bit simplified.
 
* Show -  space group, current state, symmetry, unit cell
 
* Symmetry
 
* Measurements
 
* Console
 
* Use full menu <sup>(*)</sup> - that allows to revert to the standard full menu.
 
* Language
 
* About
 
 
 
''(*) These are new entries, and so will not be localized; you may wish to edit them for your intended language.''
 
 
 
You can get this custom menu [[SimpleCryst.mnu | here]].
 

Latest revision as of 18:26, 10 August 2025

This section intends to collect material by some users that may be useful to other users.

Feel free to add your material!

Reusable scripts

Color picker

Molcolpicker.gif Appcolpicker.gif

The code below was used to create the palettes shown above. It's a pure javascript color picker that can be used for changing color of selected part of molecule, JSmol background, or any feature of the model (cartoons, surfaces, etc.).

Sample of use, JavaScript code needed, example page: Recycling_Corner/Molecule_color_picker

Spin controls

"Basic" spin toggle

Quite trivial, but compact and useful. However, if other scripts, controls, or the user change the spin status, the checkbox will need to be reset accordingly using javascript. (To avoid this limitation, see the "foolproof" solution below)

It will work with any version of Jmol (as long as Jmol.js is being used in the web page).

jmolCheckbox("spin on", "spin off", "spin", false)

if the model is initially not spinning (the default);

or

jmolCheckbox("spin on", "spin off", "spin", true)

if the model is initially spinning (due to another script).

(The word "spin" above can be changed to any other text you like.)

"Foolproof" spin toggle

Reads the current spin status from JSmol and changes it, so it can cope with any other previous change via script, popup menu, page controls, etc.

The best and simplest trick:

Valid for recent versions of Jmol:

jmolButton("if(_spinning);spin off;else;spin on;endif","toggle spin")

Or even more compact:

jmolButton("spin @{!_spinning}","toggle spin")

(If you prefer jmolLink, it can be used in the same manner. If you don't use Jmol.js, and you have a good reason for not using it, you will know how to modify this code.)

(The words "toggle spin" above can be changed to any other text you like.)

The old trick:

Only compatible with Jmol 11.x (as long as Jmol.js is being used in the web page).

jmolButton("show spin", "toggle spin")

(If you prefer jmolLink, it can be used in the same manner.)

(The words "toggle spin" above can be changed to any other text you like.)

You must include these additional pieces of code:

Somewhere between <script> tags (recommended: within the head section):

function messageProcess(a_,b_)
{	// Convert both parameters from Java strings to JavaScript strings:
        var a = (""+a_).substring("jmolApplet".length)	
        var b = ""+b_
        // a_ will start with "jmolApplet": strip and leave just the ID part
	/*  SPIN DETECTION AND TOGGLE */
	if ( b.indexOf("set spin") != -1 )
	{	if ( b.indexOf("spin on") != -1 ) //was spinning
		{	jmolScript("spin off", a) 
		}
		else //was not spinning
		{ 	jmolScript("spin on", a) 
		}
	}
	/*  END of SPIN DETECTION AND TOGGLE  */
}

and somewhere between <script> tags, after the call to jmolInitialize() and before the call to jmolApplet():

jmolSetCallback("messageCallback", "messageProcess")

(The word "messageProcess" above can be changed to any other text you like, as long as it is the same in the above two sections of code.)

Slider controls for Jmol

See Recycling_Corner/Slider controls

Echoing PDB "Title" to the JSmol panel

The following JavaScript code snippet will report the title of a PDB entry to the JSmol panel when a PDB file is loaded. This should be included within a JavaScript portion of the html file that loads both JSmol and the PDB file. One caveat: the "TITLE" in a PDB file is depositor-generated and may or may not be "useful" to the end user! :)

var headerInfo = jmolGetPropertyAsString("fileHeader");
var cutUp = headerInfo.split("\n");
var headerstring="";
for (l=0;l<cutUp.length;l++) {
  var regexp = new RegExp("TITLE.{5}(.*)\s*");
  var temp = cutUp[l];           
  if (temp.search(regexp) == 0) {
    temp2 = RegExp.$1;
    temp2.replace(/^\s+|\s+$/g, "").replace(/\s+/g, " ");
    temp2 = temp2 + "|";
    headerstring += temp2;                          }
  }
}
headerstring.replace(/TITLE/, "");
jmolScript("set echo depth 0; set echo headerecho 2% 2%; font echo 12 sanserif bolditalic; color echo green");
jmolScript('echo "' + headerstring + '"');

Bob Hanson has also contributed this much more elegant way to accomplish the same thing all within JmolScript:

function getHeader()
  var titleLines = getProperty("fileHeader").split().find("TITLE").split()
  for (var i = 1; i <= titleLines.size;i = i + 1)
    titleLines[i] = (titleLines[i])[11][0].trim()
  end for
  return titleLines.join("|")
end function
set echo bottom left
echo @{getheader()}

Providing a 'please wait' notice while JSmol loads

in a separate page

Exporting an image from JSmol

An image of the current view may be exported from JSmol, either

Opening a duplicate of the model in a resizable pop-up window

The model, with is current state, is duplicated or cloned into a new (pop-up) window so it may be displayed at a larger size (and the user may resize that window at will).

See Recycling_Corner/Duplicate_Pop-up

Style transitions

Smooth transitions from one rendering style to another.

Spacefill to ball & stick

for (var i=0;i<=9;i++) {
 s=100-80*i/9;
 spacefill @s%;
 w=0.9-0.75*i/9;
 wireframe @w;
 delay 0.2;
}

Can be given in a single line:

for(var i=0;i<=9;i++){s=100-80*i/9;spacefill @s%;w=0.9-0.75*i/9;wireframe @w;delay 0.2;}

Replacing applet with signed applet upon demand

Note: this is legacy code for the Jmol Java applet, but it may be adapted for a change between JSmol modalities (HTML5 and WebGL)

The signed applet has certain capabilities that the unsigned applet lacks, but using the signed applet will raise some dialogs with security warnings that the general user may find scary and, if permission is denied, the expanded features will not be available and hence the page will fail to do what is expected.

This may lead to a situation where webpage authors wish to use the unsigned applet by default and make the switch to the signed applet if and when the users requests a certain capability (like saving a model to disk). The code here will do that.

The rationale is:

  1. Store the current state of the model in the applet so that it can be restored after the applet switch.
  2. Destroy the applet object.
  3. Insert the signed applet in the same place.
  4. Load back the model and state.

Latest Jmol.js (post-26 Sep 2011, Jmol_12.2.RC8 or later) includes a new jmolSwitchToSignedApplet() function to do this replacement easier:

The code (html + JavaScript, relying on Jmol.js):

<script type="text/javascript">
  jmolInitialize(".");
  jmolApplet(400, 'load example.mol;', 'ABC');
</script>
<br>
<input type="button" value="make the switch" onClick="jmolSwitchToSignedApplet('ABC')">

That's all! Note that 'ABC' is an example of an applet suffix ID, and if omitted will default to '0' (zero) in both jmolApplet() and jmolSwitchToSignedApplet().

Warning!

  • This method has not been thoroughly tested and might fail or break the page; particularly, testing under different browsers and OS's is needed.


Including special characters in echo

Non-keyboard characters may be included in echo texts using their Unicode character number, like this:

echo "\u03B1 is the alpha letter";
echo "\u2192 is an arrow pointing right";
echo "\u00B2 is the superscript two, or square power";

Note that, in these cases, the use of quotes surrounding the echoed text is compulsory.

Some Unicode characters may not be display in all operating systems (depending on font support). For example, try these triangles and arrows:

Rendered characters Jmol script
◄ ► ⏴ ⏵ ◀ ▶ echo "\u25C4 \u25BA \u23F4 \u23F5 \u25C0 \u25B6"
⇤ ← → ⇥ echo "\u21E4 \u2190 \u2192 \u21E5"
⏮ ⏭ ⏪ ⏩ ⏸ ⏯ ■ ⏹ echo "\u23EE \u23ED \u23EA \u23E9 \u23F8 \u23EF \u25A0 \u23F9"

which may look like this, or different depending on OS and web browser: Unicode triangle arrows.png

Center of mass

Jmol centers the model around its geometric center, i.e. the center of the boundbox. If you are interested in the mass center of the molecule:

See Recycling_Corner/Center_Of_Mass

Building helical molecules

RIBOZOME - an Alpha Helix Generator script

Creates an alpha helix from a user input string.

A script for the Jmol Application and also applied to a webpage with a J(S)mol object.

See Recycling_Corner/Alpha_Helix_Generator

POLYMERAZE - an DNA Double Helix Generator script

Creates a DNA or RNA single or double helix from a user input string.

See Recycling_Corner/DNA_Generator


Drawing objects

Cylinder

To draw a cylinder, you need this information:

  • two points that define the axis of the cylinder and its length
    • each of these may be an XYZ coordinate, an atom, the center of an atom set, or a reference to another previously drawn object
  • the diameter of the cylinder (in Angstroms)

Examples (with two XYZ points):

// open cylinder (tube):
draw myCyl diameter 6.0 color translucent cyan cylinder {13 1.58 9.3} {15 1.21 15} mesh nofill;
// closed at both ends:
draw myCyl diameter 6.0 color translucent cyan cylinder {13 1.58 9.3} {15 1.21 15} fill;
// closed at one end:
draw myCyl diameter 6.0 color translucent cyan cylinder {13 1.58 9.3} {15 1.21 15} fill;
draw myCap diameter 6.0 color opaque cyan circle {13 1.58 9.3} {15 1.21 15};

For options, see documentation for the draw command.

Ellipsoid

Starting from these:

  • two points that define the main axis of the ellipsoid and its length
    • each of these may be an XYZ coordinate, an atom, the center of an atom set

Example, with two atoms (numbers 3 and 7) at the ends of the ellipsoid:

atA = {atomNo=3};
atB = {atomNo=7};
dC = {(atA,atB)}; // defines the center, midpoint between both atoms
dE = 0.5; // eccentricity (<1 for cigar-shaped, 1 for a sphere, >1 for disk-shaped)
dR = 7; // resolution of the mesh or surface
dX = {atA}.x - {atB}.x; // for defining the orientation
dY = {atA}.y - {atB}.y;
dZ = {atA}.z - {atB}.z;
dL = {atA}.xyz.distance({atB}.xyz) /2; // length of the main ellipsoid axis
isosurface myEllipA color blueTint scale @dL resolution @dR center @dC ellipsoid {@dX @dY @dZ @dE} mesh nofill;
isosurface myEllipB color translucent 0.7 lime scale @dL resolution @dR center @dC ellipsoid {@dx @dy @dz @dE} fill;

Resolution and eccentricity will need to be adjusted depending on your case.


Legends inside J(S)mol panel

Element legend

This will work with any loaded molecule (it automatically reads the list of elements present).

It requires Jmol 14.6.0 or later.

Use either with color echo black; background white; or with color echo white; background black;

function createElementKey() {
  var y = 90;
  for (var e in {*}.element.pivot) {
    var c = {element=@e}.color;
    draw id @{"d_"+ e} diameter 2 [90 @y %] color @c;
    set echo id @{"e_" + e} [91 @{y-1} %];
    echo @e;
    font echo 24 bold sans;
    y -= 5;
  }
}
createElementKey;

Rainbow color key (legend)

This shows (inside J(S)mol) the actual colors used by Jmol in the "roygb" scheme. (there are other ways to achieve this)

function rainbowKey(minValue,maxValue,fontSize) {
  rainbowColors = ['[x0000FF]','[x0020FF]','[x0040FF]','[x0060FF]','[x0080FF]',
  '[x00A0FF]','[x00C0FF]','[x00E0FF]','[x00FFFF]','[x00FFE0]','[x00FFC0]',
  '[x00FFA0]','[x00FF80]','[x00FF60]','[x00FF40]','[x00FF20]','[x00FF00]',
  '[x20FF00]','[x40FF00]','[x60FF00]','[x80FF00]','[xA0FF00]','[xC0FF00]',
  '[xE0FF00]','[xFFFF00]','[xFFE000]','[xFFC000]','[xFFA000]','[xFF8000]',
  '[xFF6000]','[xFF4000]','[xFF2000]','[xFF0000]'];
  background echo darkgray;
  font echo @fontSize sans;
  for (i=1;i<=rainbowColors.length;i++) {
   n = "k"+i; // each echo needs a unique ID
   y = 99 - 2*i;
   set echo id @n [1 @y %];
   color echo @{rainbowColors[i]};
   v = (minValue + (maxValue-minValue) * i / rainbowColors.length) % 1;
   if (v.size<4) {v = "  " + v;}
   t = "\u2B24 " + v; // circle; \u25A0 square
   echo @t;
  }
}
rainbowKey(5.0,25.0,18);


Test if a file exists before displaying it

Using HTML, Javascript and Jmol scripting:

A Javascript function:

function loadFile(x) {
  var s = 'filedat = load("' + x  + '"); exists = true; '+
   'if ( filedat.find("NetworkError") != 0 ) { exists = false; } '+
   'elseif ( filedat.find("Not Found") != 0 ) { exists = false; } '+
   'if ( exists ) { load var filedat; } else { zap; set echo e0 50% 50%; set echo e0 center; echo "This file cannot be found"; }';
  Jmol.script(myJmol, s);
}

And the HTML element calling it:

<input type="button" onClick="loadFile('test.mol')" value="load it">

Using Jmol callbacks to Javascript:

Another possibility is to use loadStructCallback to detect the failure in loading the file. For instance:

In Javascript:

Info.loadstructcallback = 'loadCB';
function loadCB() {
 if (arguments[5]==0 && !window['noFile']) { //avoid repeated callbacks by zap
  Jmol.script(myJmol, 'zap; set echo e0 50% 50%; set echo e0 center; echo "This file cannot be found";'); 
  window['noFile'] = true;
 } else {
  window['noFile'] = false;
 }
}

Using only Jmol scripting:

Javascript:

Info.script = 'function loadFile(x) { filedat=load(x); exists=true; '+
 'if (filedat.find("NetworkError")!=0) {exists=false;} elseif (filedat.find("Not Found")!=0) {exists=false;}; '+
 'if (exists) {load var filedat;} else {zap; set echo e0 50% 50%; set echo e0 center; echo "This file cannot be found";} }; ';

And HTML:

<p>This file exists in the same folder 
 <script type="text/javascript">Jmol.jmolButton(myJmol, "loadFile('test.mol')", "load it");</script></p>
<p>This file  does not exist 
 <script type="text/javascript">Jmol.jmolButton(myJmol, "loadFile('test2.mol')", "load it");</script></p>

Using an AJAX call:

Javascript:

function loadFile(pathFilenameExt) {
 var req = new XMLHttpRequest();
 req.onreadystatechange = function() {
  if (this.readyState != 4) { return; } /*not finished yet*/
  if (this.status == 200) {
    Jmol.script(myJmol, 'load "' + pathFilenameExt + '";');
  } else {
    Jmol.script(myJmol, 'zap; set echo e0 50% 50%; set echo e0 center; echo "This file cannot be found";');
  }
 };
 req.open('GET', pathFilenameExt, false);
 req.send();
}

And the HTML:

<p>This file exists in the same folder <input type="button" onClick="loadFile('test.mol')" value="load it"></p>
<p>This file does not exist <input type="button" onClick="loadFile('test2.mol')" value="load it"></p>

(Based on a contribution by Bilal Nizami)


Improved lighting

The lighting of atoms, bonds and ribbons and the thickness of ribbons may be customized to provide a nicer look, by adjusting several settings. Here is an example:

Fast, fancy, shiny.png

Fast, fancy, shiny ball-and-stick.png

Default:

reset lighting; set cartoonsFancy off; set hermiteLevel 0; set antialiasDisplay off;

"Fast": (quick rendering, same as default except antialias is applied for a better comparison with the other two)

reset lighting; set cartoonsFancy off; set hermiteLevel 0; set antialiasDisplay on;

"Fancy": (relevant only for cartoons, without effect on atoms and bonds)

reset lighting; set cartoonsFancy on; set hermiteLevel 20; set antialiasDisplay on;

"Shiny": (adds light and shadow effects) (more similar to rendering in other software like e.g. Chimera)

set ambientPercent 25; set specularPower 100; set specularPercent 22; set specularExponent 4; set cartoonsFancy on; set antialiasDisplay on; set hermiteLevel 20;

Shiny-rendering-spacefill.png

Note: Jmol defaults may be restored using reset lighting which applies these values:

set ambientPercent diffusePercent specular specularPercent specularPower specularExponent
default value: 45 84 on 22 40 6
set zDepth zSlab zShade zShadePower celShading celShadingPower
default value: 0 50 off 3 off 10

For more details about each of these settings, see the Scripting Documentation.

Extract phi and psi values

The dihedral angles phi and psi are known in Jmol, as properties of each amino acid residue in a protein, which are copied to properties of each atom in that residue.

These scripts may be used to extract their values into an array:

For the first polymer in the first model in the loaded file:
p = getProperty("polymerinfo.models[1].polymers[1].monomers").select("psi,phi")

p will be an associative array, one element per residue, each one with keys "phi" and "psi" and their values.

Result for the first 2 and last 2 residues:
print p
 {
   "psi"  :  135.30487
  }
 {
   "phi"  :  -103.61969
   "psi"  :  110.173744
  }
...
 {
   "phi"  :  -81.423874
   "psi"  :  131.89566
  }
 {
   "phi"  :  -166.42226
  }
Another way, which will read all protein chains present:
ph = [];
ps = [];
n1 = {protein}.resno.min;
n2 = {protein}.resno.max;
for (r=n1; r<=n2; r++) {
 ph.push({resno=r}.phi);
 ps.push({resno=r}.psi);
}
Result:
print ph.join("\n")
NaN
-34.539898
...
-81.423874
-166.42226
print ps.join("\n")
135.30487
36.724583
...
131.89566
NaN

Front of the molecule, selecting (by percentage)

The Jmol function at Recycling_Corner/Front_Selection selects a specified percentage of the front of the molecule, according to the orientation of the molecule when the function is executed.


Exchange of data between JmolScript and JavaScript

  1. Passing a variable from JavaScript to a JSmol variable:
    • If the JS variable is e.g. myJSvar = 55, doing this will assign its value to a variable in JSmol:
    myJSmolVar = javascript("myJSvar"); print myJSmolVar; // prints 55
  2. Passing a variable from JSmol to a JavaScript variable:
    myJSvar = Jmol.evaluateVar(myJSmol, myJSmolVar) . Instead of the name of the variable, in the position of myJSmolVar you may use a Jmol math expression or some information from the molecule. myJSmol is the id/name of the JSmol object in the webpage (e.g. myJmol or jmolApplet0). More details about evaluateVar().

Visually transfer a hydrogen from a donor to an acceptor

Script authored by Karsten Theis.

Grotthuss fast hires.gif click to see animated

function htransfer(O1, O2, H12, q1, q2) {
  // H12 is moved from O1 to O2
 define temp selected;
 var x = distance(O1,O2);
 var y = distance(O1,H12);
 var ratio = y/x;
 var oldH = H12.xyz;
 var newH = O2.xyz + (O1.xyz - O2.xyz) * ratio; // beware order of operation
 var midH = (oldH + newH) * 0.5;
 H12.xyz = midH;
 delay 0.5;
 H12.xyz = newH;
 q1 = q1 - 1;
 q2 = q2 + 1;
 var mylabel = ['+', '-', ' '][q1];
  // arrays are 1-based, with 0 indicating the last and -1 the next to last
 select @O1;
 label @mylabel;
 set labeloffset 0 0;
 color label black;
 font label 32;
 mylabel = ['+', '-', ' '][q2];
 select @O2;
 label @mylabel;
 set labeloffset 0 0;
 color label black;
 font label 32;
 connect;
 select temp;
}

Rendering protein chain according to B-factor

This function will color protein trace according to the B-factor (temperature factor) of each alpha carbon and, at the same time, display thicker trace for the portions of highest B-factor. It was inspired by the "sausage" or "putty" rendering in Pymol.

First, apply the script that defines the function:

function putty(s, grad) { // v.2
 define temp selected;
 select s and alpha;

 var bMin = {selected}.temperature.min;
 var bMax = {selected}.temperature.max;
 var wMin = 0.2; // trace thickness for lowest B-factor (Angstroms)
 var wMax = 1.5; // trace thickness for highest B-factor
 for (var a in {selected}) {
  a.trace = wMin + (a.temperature - bMin) * (wMax - wMin) / (bMax - bMin)
 }

 var c = "";
 if (grad=="wr") { // gradient white > red (low to high B)
  c = color("white", "red", 32, false);
 } else { // standard gradient blue > white > red (low to high B)
  c = color("blue", "white", 16, false) + color("white", "red", 16, false);
 }
 color trace property temperature @c range @bMin @bMax;
	
 select temp;
 print "B-factor range: " + @bMin + " to " + @bMax; // tip in console
}

Second, invoke the function for the part you wish to render in this style, such as:

putty( {protein} );
putty( {*:A}, "wr" );
putty( {*:B} );