NGL@1.0.0-beta.7 Home Manual Reference Source Gallery

NGL is an on-line viewer for proteins and other molecular structures. It is intended for users of the web application including a graphical interface and for developers who want to use NGL in their own projects.

Users

NGL provides a web application with an efficient graphical user interface (GUI) for performing common visualization tasks. A comprehensive set of molecular representations is available to create complex molecular views. Based on the WebGL technology, NGL requires only a modern web-browser.

Developers

The NGL viewer can be embedded within other web-pages and controlled via a JavaScript API.

Coloring

Representations

stage.loadFile("rcsb://1crn").then(function (o) {
  o.addRepresentation("ball+stick", {colorScheme: "bfactor"});
  o.autoView();
});

Available schemes

Selection-based coloring

Create and a selection-based coloring scheme. Supply a list with pairs of colorname and selection for coloring by selections. Use the last entry as a default (catch all) coloring definition.

var schemeId = NGL.ColormakerRegistry.addSelectionScheme([
  ["red", "64-74 or 134-154 or 222-254 or 310-310 or 322-326"],
  ["green", "311-322"],
  ["yellow", "40-63 or 75-95 or 112-133 or 155-173 or 202-221 or 255-277 or 289-309"],
  ["blue", "1-39 or 96-112 or 174-201 or 278-288"],
  ["white", "*"]
], "Transmembrane 3dqb");

stage.loadFile("rcsb://3dqb.pdb").then(function (o) {
  o.addRepresentation("cartoon", {color: schemeId });  // pass schemeId here
  o.autoView();
});

Custom coloring

Create a class with a atomColor method that returns a hex color:

var schemeId = NGL.ColormakerRegistry.addScheme(function (params) {
  this.atomColor = function (atom) {
    if (atom.serial < 1000) {
      return 0x0000FF;  // blue
    } else if (atom.serial > 2000) {
      return 0xFF0000;  // red
    } else {
      return 0x00FF00;  // green
    }
  };
});

stage.loadFile("rcsb://3dqb.pdb").then(function (o) {
  o.addRepresentation("cartoon", {color: schemeId});  // pass schemeId  here
  o.autoView();
});

Custom geometries

Shape

Convenience API

Render a variety of geometry primitives using a Shape object:

var shape = new NGL.Shape( "shape" );
shape.addMesh(
    [ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1 ],
    [ 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0 ],
    undefined, undefined, "My mesh"
);
shape.addSphere( [ 0, 0, 9 ], [ 1, 0, 0 ], 1.5 );
shape.addSphere( [ 12, 5, 15 ], [ 1, 0.5, 0 ], 1 );
shape.addEllipsoid( [ 6, 0, 0 ], [ 1, 0, 0 ], 1.5, [ 3, 0, 0 ], [ 0, 2, 0 ] );
shape.addCylinder( [ 0, 2, 7 ], [ 0, 0, 9 ], [ 1, 1, 0 ], 0.5 );
shape.addCone( [ 0, 2, 7 ], [ 0, 3, 3 ], [ 1, 1, 0 ], 1.5 );
shape.addArrow( [ 1, 2, 7 ], [ 30, 3, 3 ], [ 1, 0, 1 ], 1.0 );
shape.addArrow( [ 2, 2, 7 ], [ 30, -3, -3 ], [ 1, 0.5, 1 ], 1.0 );
shape.addLabel( [ 15, -4, 4 ], [ 0.2, 0.5, 0.8 ], 2.5, "Hello" );

var shapeComp = stage.addComponentFromObject( shape );
shapeComp.addRepresentation( "buffer" );
shapeComp.autoView();

Buffer

Low level approach, more scalable

Render two spheres (sscales to many more) a SphereBuffer object:

var shape = new NGL.Shape( "shape" );
var sphereBuffer = new NGL.SphereBuffer( {
    position: new Float32Array( [ 0, 0, 0, 4, 0, 0 ] ),
    color: new Float32Array( [ 1, 0, 0, 1, 1, 0 ] ),
    radius: new Float32Array( [ 1, 1.2 ] )
} );
shape.addBuffer( sphereBuffer );
var shapeComp = stage.addComponentFromObject( shape );
shapeComp.addRepresentation( "buffer" );
shapeComp.autoView();

Embedding

For embedding the viewer into other websites a single JavaScript file is available ngl.js. See below for CDNs to provide this file.

Example

The following code creates a viewer and loads the structure of PDB entry 1CRN from the RCSB PDB. The result can be seen and edited online here. For more information on how to control the viewer see the API reference, starting with the Stage class.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
</head>
<body>
  <script src="path/to/ngl.js"></script>
  <script>
    document.addEventListener("DOMContentLoaded", function () {
      var stage = new NGL.Stage("viewport");
      stage.loadFile("rcsb://1crn", {defaultRepresentation: true});
    });
  </script>
  <div id="viewport" style="width:400px; height:300px;"></div>
</body>
</html>

Concept

The main object in NGL is the stage. By using the stage.loadFile method, component objects, containing structur or volume data, can be added to the stage. Finally representation objects, like "cartoon" or "surface", are added to the component for showing the data.

// create a `stage` object
var stage = new NGL.Stage("viewport");
// load a PDB structure and consume the returned `Promise`
stage.loadFile("rcsb://1CRN").then(function (component) {
  // add a "cartoon" representation to the structure component
  component.addRepresentation("cartoon");
  // provide a "good" view of the structure
  component.autoView();
});

Element

If the size of your DOM element (here "viewport") is not know upon calling the Stage constructor make sure that you call stage.handleResize() when the size is known or has changed.

CDN

Instead of hosting the ngl.js file yourself you can point to the Unpkg or RawGit CDN.

Latest stable/untagged version released on NPM:

Latest development version released on NPM:

Specific Version

File Formats

The following file formats are supported. Files can be compressed with gzip. Format detection is based on the file extension.

Structures

Structure data is saved into Structure instances.

Loading flags (in the GUI available from the File menu):

  • asTrajectory: load the topology from first model and add the coordinates from it and the remaining models as trajectory frames. Note that this assumes that all models share the same topology.
  • firstModelOnly: load only the first model.
  • cAlphaOnly: load only C-alpha atoms.

Atom data added to all structures:

  • index: running atom index that is unique within the structure
  • modelindex: running model index that is unique within the structure
  • globalindex: globally unique running atom index

mmCIF

Extension: .mmcif, .cif, .mcif

Specification: http://mmcif.wwpdb.org/

Supported features:

  • Title: read from "_struct.title" item
  • Box coordinates: read from "_cell" item
  • Space group: read from "_symmetry.space_group_name_H-M" item
  • Secondary structure: read from "_struct_conf" and "_struct_sheet_range" items
  • Assemblies
    • Biological assemblies: read from "_pdbx_struct_oper_list" and "_pdbx_struct_assembly_gen" items
    • Non-crystallographic symmetry: read from "_struct_ncs_oper" item
    • Crystallographic symmetry: determined from space group
  • Atom data: read from the "_atom_site" items
    • resname: read from "label_comp_id" field
    • x, y, z: read from "Cartn_x", "Cartn_y", "Cartn_z" fields
    • resno: read from "auth_seq_id" field
    • serial: read from "id" field
    • atomname: read from "label_atom_id" field
    • chainname: read from "auth_asym_id" field
    • element: read from "type_symbol" field or deduced from atomname if not available
    • vdw: deduced from element
    • covalent: deduced from element
    • bfactor: read from "B_iso_or_equiv" field
    • altloc: read from "label_alt_id" field
    • inscode: read from "pdbx_PDB_ins_code" field
    • hetero: determined from "group_PDB" field, which is "ATOM" or "HETATM"
    • occupancy: read from "occupancy" field
  • Connectivity: read from the "_struct_conn" item, which generally contains data on hetero atom connectivity. Entries with "_conn_type_id" equal to "hydrog" are currently ignored. Connectivity for non-hetero atoms is calculated during post-processing.
  • The cif dictionary is added to the structure.extraData property, with key cif, excluding "_atom_site" items

PDB/PQR

Extension: .pdb, .ent, .pqr

Specification: http://www.wwpdb.org/documentation/file-format.php

Supported features:

  • Title: read from "TITLE" record
  • Box coordinates: read from "CRYST1" record
  • Space group: read from "CRYST1" record
  • Secondary structure: read from "HELIX" and "SHEET" records
  • Assemblies
    • Biological assemblies: read from "REMARK 350" record
    • Non-crystallographic symmetry: read from "MTRIX" record
    • Crystallographic symmetry: determined from space group
  • Atom data: read from the "ATOM" and "HETATM" records
    • resname: read from "resName" field
    • x, y, z: read from "x", "y", "z" fields
    • resno: read from "resSeq" field
    • serial: read from "serial" field
    • atomname: read from "name" field
    • chainname: read from "chainID" field
    • element: read from "element" field or deduced from atomname if not available
    • vdw: deduced from element
    • covalent: deduced from element
    • bfactor: read from "tempFactor" field
    • altloc: read from "altLoc" field
    • inscode: read from "insCode" field
    • hetero: determined from record type, which is "ATOM" or "HETATM"
    • occupancy: read from "occupancy" field
  • Connectivity: read from the "CONNECT" record, which generally contains data on hetero atom connectivity. Connectivity for non-hetero atoms is calculated during post-processing.

GRO

Extension: .gro

Specification: http://manual.gromacs.org/current/online/gro.html

Supported features:

  • Title: read from "title string" field
  • Box coordinates: read from "box vectors" field
  • Secondary structure: not available in the format, automatically calculated during post-processing
  • Atom data:
    • resname: read from "residue name" field
    • x, y, z: read from "position" fields
    • resno: read from "residue number" field
    • serial: read from "atom number" field
    • atomname: read from "atom name" field
    • chainname: not available, automatically assigned during post-processing
    • element: deduced from atomname
    • vdw: deduced from element
    • covalent: deduced from element
    • altloc: not available, left empty
    • inscode: not available, left empty
  • Connectivity: not available in the format, automatically calculated during post-processing

TODO:

  • Read velocity data from GRO files that includes it (and create a new Representation to display it).

SDF

Extension: .sdf, .sd

Specification: http://download.accelrys.com/freeware/ctfile-formats/

Supported features:

  • Title: read from the second line of the header block
  • Box coordinates: not available in the format
  • Secondary structure: not available in the format, automatically calculated during post-processing
  • Atom data:
    • resname: not available, set as "HET"
    • x, y, z: read from "position" fields
    • resno: read from "residue number" field
    • serial: not available, set from running index
    • atomname: not available set as "element + index"
    • chainname: not available, automatically assigned during post-processing
    • element: read from "element" field
    • vdw: deduced from element
    • covalent: deduced from element
    • altloc: not available, left empty
    • inscode: not available, left empty
  • Connectivity: read from bond block, includes bond order
  • Associated data items are added to the structure.extraData property with key sdf

MOL2

Extension: .mol2

Specification: http://www.tripos.com/data/support/mol2.pdf

Supported features:

  • Title: read from the first line of the molecule record
  • Box coordinates: not available in the format
  • Secondary structure: not available in the format, automatically calculated during post-processing
  • Atom data:
    • resname: read from "residue name" field
    • x, y, z: read from "coordinate" fields
    • resno: read from "residue number" field
    • serial: read from "atom number" field
    • atomname: read from "atom name" field
    • chainname: not available, automatically assigned during post-processing
    • element: read from "atom type" field
    • vdw: deduced from element
    • covalent: deduced from element
    • altloc: not available, left empty
    • inscode: not available, left empty
    • bfactor: read from the "partial charge" field (i.e. not a bfactor)
  • Connectivity: read from bond record, includes bond order

MMTF

Extension: .mmtf

Specification: https://github.com/rcsb/mmtf

Supported features:

  • Title: read from "title"
  • Box coordinates: read from "unitCell" field
  • Secondary structure: read from "secStructList" field
  • Atom data:
    • resname: read from "groupTypeList[].groupName" field
    • x, y, z: read from "x/y/zCoordList" fields
    • resno: read from "groupIdList" field
    • serial: read from "atomIdList" field
    • atomname: read from "groupTypeList[].atomNameList" field
    • chainname: read from "chainNameList" field
    • element: read from "groupTypeList[].elementList" field
    • vdw: deduced from element
    • covalent: deduced from element
    • altloc: read from "altLocList" field
    • inscode: read from "insCodeList" field
    • bfactor: read from "bFactorList" field
    • occupancy: read from "occupancyList" field
  • Connectivity: read from "bondAtomList", "bondOrderList" fields and their "groupTypeList[]" counterparts

Topologies

Topology are different from structure files as they not contain coordinate data.

PRMTOP

Topology format used by Amber.

Extensions: .prmtop, .parm7

PSF

Topology format used by Charmm.

Extension: .psf

TOP

Topology format used by Gromacs.

Extension: .top

Trajectories

Structure files in mmCIF, PDB, GRO, SDF, MOL2 or MMTF format can also be loaded as trajectories by setting the asTrajectory flag. Trajectory files in DCD, NCTRAJ, TRR or XTC format are added to a Structure.

DCD

Uncompressed, binary trajectory format used by Charmm.

Extension: .dcd

TRR

Uncompressed, binary trajectory format used by Gromacs.

Extension: .trr

NCTRAJ

Uncompressed, binary trajectory format used by Amber.

Extensions: .nctraj, .ncdf, .nc

XTC

Compressed, binary trajectory format used by Gromacs.

Extension: .xtc

Densities

Density data is saved into Volume instances.

MRC/MAP/CCP4

Extensions: .mrc, .map, .ccp4

Specification: http://www.ccp4.ac.uk/html/maplib.html, http://ami.scripps.edu/software/mrctools/mrc_specification.php

Supported features:

  • Header data
  • Density data

CUBE

Extensions: .cube, .cub

Specification: http://paulbourke.net/dataformats/cube/

Supported features:

  • Header data
  • Density data

TODO:

  • Read structure embedded in the header.

DSN6/BRIX

Extensions: .dsn6, .brix

Supported features:

  • Header data
  • Density data

DX/DXBIN

Extensions: .dx, .dxbin

Specification: http://www.poissonboltzmann.org/docs/file-format-info/

Supported features:

  • Header data
  • Density data

XPLOR/CNS

Extensions: .xplor, .cns

Supported features:

  • Header data
  • Density data

Surfaces

The surface geometry is saved into Surface instances.

OBJ

Extension: .obj

The PyMOL molecular visualization system can export surfaces in the OBJ format.

PLY

Extension: .ply

The EDTsurf program outputs surfaces in the PLY format.

Annotation

wwPDB Validation Report

Extension: .xml

Load PDB entry 3PQR and its validation report. Add the validation object to the structure object. Then show clashes and color by geometry quality using the ValidationRepresentation to show the clash data. There are two validation dta-based colorschemes available: densityfit and geoquality.

Promise.all( [
    stage.loadFile( "rcsb://3PQR" ),
    NGL.autoLoad( "http://ftp.wwpdb.org/pub/pdb/validation_reports/pq/3pqr/3pqr_validation.xml.gz", { ext: "validation" } )
] ).then( function( ol ){
    ol[ 0 ].structure.validation = ol[ 1 ];
    ol[ 0 ].addRepresentation( "cartoon", { color: "geoquality" } );
    ol[ 0 ].addRepresentation( "validation" );
    ol[ 0 ].addRepresentation( "ball+stick", {
        sele: ol[ 1 ].clashSele,
        color: "geoquality"
    } );
    ol[ 0 ].addRepresentation( "licorice", {
        sele: "hetero",
        color: "geoquality"
    } );
    stage.autoView();
} );

General

JSON

Extension: .json

CSV

Extension: .csv

MSGPACK

Extension: .msgpack

NETCDF

Extension: .netcdf

TXT

Extensions: .txt, .text

XML

Extension: .xml

Interaction controls

Camera

Viewer

The translation, zoom and rotation of the scene can be set via the ViewerControls class which is available as a property of the stage: Stage.viewerControls.

Getting and setting the orientation for the whole scene:

var orientationMatrix = stage.viewerControls.getOrientation();
stage.viewerControls.orient(orientationMatrix);

Animation

The scene can be smoothly rotated, moved and zoomed via the AnimationControls class which is available as a property of the stage: Stage.animationControls.

Automatic view

For the whole stage (see Stage.autoView):

stage.loadFile("rcsb://3pqr").then(function (o) {
  o.addRepresentation("cartoon");
  stage.autoView();  // focus on all representations in all components
});

For individual components (see Component.autoView):

stage.loadFile("rcsb://3pqr").then(function (o) {
  o.addRepresentation("cartoon");
  var duration = 1000;  // optional duration for animation, defaults to zero
  o.autoView(duration);  // focus on the whole structure
});

For structure components using a selection string (see StructureComponent.autoView):

stage.loadFile("rcsb://3pqr").then(function (o) {
  o.addRepresentation("cartoon");
  o.autoView("RET");  // focus on retinal
});

Principal axes

Animate structure to align with principal axes:

stage.loadFile("rcsb://3pqr").then(function (o) {
  o.addRepresentation("cartoon");
  var pa = o.structure.getPrincipalAxes();
  stage.animationControls.rotate(pa.getRotationQuaternion(), 1500);
});

Spin

Spin the whole scene around the y-axis (see Stage.setSpin):

stage.setSpin(true);

Picking

Whenever the user clicks or hovers over the viewer canvas the appropriate StageSignal is dispatched from Stage.signals. Any function added to those those signals is then called with a PickingProxy instance that provides access to what was picked.

Note that the MouseControls class (see below) provides more convenient means to bind picking events to custom actions.

Clicked

stage.signals.clicked.add(function (pickingProxy) {...});

Hovered

Basis usage:

stage.signals.hovered.add(function (pickingProxy) {...});

Example for showing a tooltip when hovering over atoms or bonds:

// create tooltip element and add to the viewer canvas
var tooltip = document.createElement("div");
Object.assign(tooltip.style, {
  display: "none",
  position: "absolute",
  zIndex: 10,
  pointerEvents: "none",
  backgroundColor: "rgba(0, 0, 0, 0.6)",
  color: "lightgrey",
  padding: "0.5em",
  fontFamily: "sans-serif"
});
stage.viewer.container.appendChild(tooltip);

// load a structure file
stage.loadFile( "rcsb://1blu", { defaultRepresentation: true } );

// listen to `hovered` signal to move tooltip around and change its text
stage.signals.hovered.add(function (pickingProxy) {
  if (pickingProxy && (pickingProxy.atom || pickingProxy.bond)){
    var atom = pickingProxy.atom || pickingProxy.closestBondAtom;
    var cp = pickingProxy.canvasPosition;
    tooltip.innerText = "ATOM: " + atom.qualifiedName();
    tooltip.style.bottom = cp.y + 3 + "px";
    tooltip.style.left = cp.x + 3 + "px";
    tooltip.style.display = "block";
  }else{
    tooltip.style.display = "none";
  }
});

Mouse

Controls

For convenience, there is a MouseControls class which is available as a property of the stage: Stage.mouseControls and can be used to bind actions (any user-defined function or predefined methods from the MouseActions class) to mouse events with keyboard modifiers.

stage.mouseControls.add("drag-left+right", NGL.MouseActions.zoomDrag);

The default controls are as follows:

  • scroll zoom scene
  • scroll-ctrl move near clipping plane
  • scroll-shift move near clipping plane and far fog
  • scroll-alt change isolevel of isosurfaces
  • drag-right pan/translate scene
  • drag-left rotate scene
  • drag-middle zoom scene
  • drag-shift-right zoom scene
  • drag-left+right zoom scene
  • drag-ctrl-right pan/translate hovered component
  • drag-ctrl-left rotate hovered component
  • clickPick-middle auto view picked component element
  • hoverPick show tooltip for hovered component element

Observer

For low-level control, there is a MouseObserver class which is available as a property of the stage: Stage.mouseObserver and dispatches MouseSignals originating from the viewer canvas.

stage.mouseObserver.signals.scroll.add(function (delta) {...});

Keyboard

Controls

For convenience, there is a KeyControls class which is available as a property of the stage: Stage.keyControls and can be used to bind actions (any user-defined function or predefined methods from the KeyActions class) to key events.

stage.keyControls.add("r", NGL.KeyActions.autoView);

The default controls are as follows:

  • i toggle stage spinning
  • k toggle stage rocking
  • p pause all stage animations
  • r reset stage auto view

Component

Each Component (wrapping a Structure, Surface, Volume or Shape object) can be moved independently from the camera using the .setPosition, .setRotation, .setScale methods.

// Load a protein
stage.loadFile("rcsb://1crn").then(function (o) {
  o.addRepresentation("cartoon");
  stage.autoView();
});

// Load the same protein and move it
stage.loadFile("rcsb://1crn").then(function (o) {
  o.setPosition([20, 0, 0]);
  o.setRotation([ 2, 0, 0 ]);
  o.setScale(0.5);
  o.addRepresentation("cartoon", {color: "orange"});
  stage.autoView();
});

In addition, a transformation matrix can be set with .setTransform which is applied before the set position, rotation and scale. Such a matrix can be supplied by external superposition tools to align two structures.

Promise.all([

  stage.loadFile("rcsb://1u19"),
  stage.loadFile("rcsb://3pqr")

]).then(function(ol) {

  ol[0].addRepresentation("cartoon", {color: "skyblue", sele: ":A"});
  ol[1].addRepresentation("cartoon", {color: "tomato"});

  var m = new NGL.Matrix4().fromArray([
    -0.674, 0.131, -0.727, -7.528,
    0.283, 0.955, -0.090, -30.266,
    0.682, -0.267, -0.681, 24.816,
    0, 0, 0, 1
  ]).transpose();

  ol[0].setTransform(m);

  stage.autoView();

});

Molecular Representations

Each loaded structure can be displayed using a variety of representations that can be combined to create complex molecular views. Multiple representation types are supported, including space-filling spheres for atoms (spacefill), cylinders and spheres for bonds and atoms (ball+stick), simple lines for bonds (line), secondary structure abstraction (cartoon), backbone atom trace (backbone). The appearance of the representations can be fine-tuned by parameters, for example, to change the quality. Most representations have a color and a radius parameter that can use data from the underlying structure. For instance, a representation can be colored uniformly or according to the element, residue or secondary structure type of the atoms from which the representation is derived. The size of representation objects, for example sphere and cylinder radii in a ball+stick representation, can be set similarly.

Common parameters are described in the {@link StructureRepresentationParameters} type definition.

axes

backbone

Cylinders connect successive residues of unbroken chains by their main backbone atoms, which are .CA atoms in case of proteins and C4'/C3' atoms for RNA/DNA, respectively. The main backbone atoms are displayed as spheres.

  • aspectRatio: ...
  • radiusSegments: ...
  • sphereDetail: ...

ball+stick

Atoms are displayed as spheres (balls) and bonds as cylinders (sticks).

  • aspectRatio: A number between 1.0 and 10.0, defining how much bigger the sphere radius is compared to the cylinder radius.
  • radiusSegments: An integer between 3 and 25, defining the number of segments used to create a cylinder. Only has an effect when ray-casting of geometric primitives is unavailable or switched of via the impostor preference.
  • sphereDetail: See spacefill representation

base

Simplified display of RNA/DNA nucleotides, best used in conjunction with a cartoon representation. Here, a stick is drawn connecting the sugar backbone with a nitrogen in the base (.N1 in case of adenine or guanine, .N3 in case of thymine or cytosine).

  • aspectRatio: ...
  • radiusSegments: ...
  • sphereDetail: ...

cartoon

The main backbone atoms (see backbone) of successive residues in unbroken chains are connected by a smooth trace. The trace is expanded perpendicular to its tangent with an elliptical cross-section. The major axis points from .CA in the direction of the .O in case of proteins and from the C1'/C3' to C2'/O4' for RNA/DNA, respectively.

  • aspectRatio: ...
  • subdiv: ...
  • radialSegments: ...
  • tension: ...
  • capped: ...
  • wireframe: ...
  • arrows: ... (in development)

contact

CAUTION This feature is only for preview. It is still under development and has not been thoroughly tested. Bugs and other surprises are likely.

Works currently only for proteins. The angle criterion has currently little meaning.

Displays cylinders between supposedly contacting atoms.

  • contactType
    • polar: ...
    • polar backbone: ...
  • maxDistance: ...
  • maxAngle: ...

distance

Displays the distance between pairs of atoms.

helixorient

Displays various helix-related values...

hyperball

A derivate of the ball+stick representation (pioneered by HyperBalls project) in which atoms are smoothly connected by an elliptic hyperboloid.

label

Displays a label near the corresponding atom.

  • labelType: atom name, residue name, residue name + no or residue no
  • font: ...
  • antialias: ...

licorice

A variant of the ball+stick representation where balls and sticks have the same radius, that is the aspectRatio parameter is fixed to 1.0.

line

Bonds are displayed by a flat, unshaded line.

point

Atoms are displayed by textured points.

ribbon

A thin ribbon is displayed along the main backbone trace.

rocket

rope

A rope-like protein fold abstraction well suited for coarse-grained structures. In this representation a tube follows the center points of local axes as defined by helixorient. The result is similar to what is shown by the Bendix tool.

  • subdiv: ...
  • radialSegments: ...
  • tension: ...
  • capped: ...
  • wireframe: ...
  • smooth: ...

spacefill

Atoms are displayed as a set of space-filling spheres.

  • sphereDetail: An integer between 0 and 3, where 0 means low and 3 very high geometric detail. Only has an effect when ray-casting of geometric primitives is unavailable or switched of via the impostor preference.

surface

Displays the molecular surface and its variants.

  • surfaceType
    • vws: van der Waals surface
    • sas: solvent accessible surface
    • ms: molecular surface
    • ses: solvent excluded surface
    • av: high quality molecular surface
  • probeRadius:
  • scaleFactor: (just for debugging)

trace

A flat, unshaded line is displayed along the main backbone trace.

tube

Essentially like cartoon but with the aspectRatio fixed at a value of 1.0.

unitcell

Draws the corners and edges of a crystallographic unitcell.

validation

Draws clashes given in a wwPDB validation report.

Scripting

Scripts are written in JavaScript and can be loaded as files that have the extension .ngl or .js.

Example

Load the structure of PDB entry 1CRN from RCSB, add a cartoon representation and center the view on the structure.

stage.loadFile("rcsb://1CRN").then(function (o) {
  o.addRepresentation("cartoon");
  o.autoView();
});

Here, o is a StructureComponent instance.

Variables

The following variables are available in a scripting context.

stage  // the stage object
__name__  // the name of the script file
__path__  // the full path of the script file
__dir__  // the directory to the script file

Selection Language

Selections (or 'Sele' for short) strings can be input at various places in the user interface or when scripting. They are used to limit which atoms/residues are shown in a [molecular representation]{@tutorial molecular-representations} or what atoms are loaded from a trajectory.

Example

Select the side-chain and C-alpha atoms plus the backbone nitrogen in case of proline. not backbone or .CA or (PRO and .N) This selection is useful to display the sidechains together with a backbone trace. Hence there is also the keyword sidechainAttached for it.

Language

Keywords

  • all, *
  • sidechain
  • sidechainAttached (not backbone or .CA or (PRO and .N))
  • backbone
  • protein
  • nucleic
  • rna
  • dna
  • hetero
  • ligand (( not polymer or hetero ) and not ( water or ion ))
  • ion
  • saccharide/sugar
  • polymer
  • water
  • hydrogen
  • helix
  • sheet
  • turn (not helix and not sheet)
  • small (Gly or Ala or Ser)
  • nucleophilic (Ser or Thr or Cys)
  • hydrophobic (Ala or Val or Leu or Ile or Met or Pro or Phe or Trp)
  • aromatic (Phe or Tyr or Trp or His)
  • amid (Asn or Gln)
  • acidic (Asp or Glu)
  • basic (His or Lys or Arg)
  • charged (Asp or Glu or His or Lys or Arg)
  • polar (Asp or Cys or Gly or Glu or His or Lys or Arg or Asn or Gln or Ser or Thr or Tyr)
  • nonpolar (Ala or Ile or Leu or Met or Phe or Pro or Val or Trp)
  • cyclic (His or Phe or Pro or Trp or Tyr)
  • aliphatic (Ala or Gly or Ile or Leu or Val)
  • bonded (all atoms with at least one bond)
  • ring (all atoms within rings)

Expressions

  • residue number: 1, 2, 100
  • residue number range: 3-40 (Note that around the dash - no spaces are allowed)
  • chain name: :A
  • atom name: .CA, .C, .N, ...
  • model: /0, /1, ...
  • residue name: ALA, GLU, SOL, DMPC, ...
  • numeric residue name: [032], [1AB], ...
  • list of residue names: [ALA,GLU,MET], [ARG,LYS], ...
  • element name: _H, _C, _O, ...
  • alternate location: %A, %B, ... or % for non-alternate location atoms
  • insertion code: ^A, ^B, ... or ^ for residues with no insertion code

Some of these expressions can be combined (in this order) - residue numer (range), insertion code, chain name, atom name, alternate location, model - like this

// select C-alpha atoms of residue 10 with insertion code A
// from chain F in model 0 at alternate location C
10^A:F.CA%C/0

which is the same as

10 and ^A and :F and .CA and %C and /0

Single expressions may be left out as long as the order (see above) is kept, for example:

:A/0 # select chain A from model 0

Atomindex

A list of atom indices can be given as a comma seperated list (no spaces in between) prefixed with the @ character.

@0,1,4,5,11,23,42

Logical operators (in order of binding strength)

  • NOT
  • AND
  • OR

Additionally, parentheses () can be used for grouping: :A and ( 1 or 10 or 100 ) # select residues 1, 10 and 100 from chain A

Structure data

Molecular data is stored in objects of the Structure class. Structure objects provide the common model/chain/residue/atom hierarchy.

Proxies

The data in each level of the hierarchy can be efficiently and conveniently accessed through proxy objects.

// Get an AtomProxy object for atom with index 10
stage.loadFile("rcsb://1crn").then(function(component) {
  var atomProxy = component.structure.getAtomProxy(10)
  console.log(atomProxy.qualifiedName())
});

Iterators

For each level of the hierarchy an iterator is available.

// Calculate B-factor statistics
stage.loadFile("rcsb://1crn").then(function(component) {
  var bfactorSum = 0
  var bfactorMin = +Infinity
  var bfactorMax = -Infinity
  component.structure.eachAtom(function(atom) {
    bfactorSum += atom.bfactor;
    if (bfactorMin > atom.bfactor) bfactorMin = atom.bfactor
    if (bfactorMax < atom.bfactor) bfactorMax = atom.bfactor
  });
  var bfactorAvg = bfactorSum / component.structure.atomCount
  console.log(bfactorSum, bfactorMin, bfactorMax, bfactorAvg)
});

Volume Representations

For volumetric data and (when applicable) for surface data

Surface

Show triangulation of volume data at a given isolevel or direct display of a surface mesh.

Dot

Render each cell of a volume (optionally filtered given threshold values) as a dot or show the vertices of a surface mesh.

Slice

Render a slice of a volume colored by the value of each cell closest to each point on the slice.

Usage

A collection of NGL snippets

Implementing custom default representations

Start by creating a function that adds the wanted representations to a component. See also {@ StructureComponent.addRepresentation}.

function defaultStructureRepresentation( component ){
    // bail out if the component does not contain a structure
    if( component.type !== "structure" ) return;
    // add three representations
    component.addRepresentation( "cartoon", {
        aspectRatio: 3.0,
        scale: 1.5
    } );
    component.addRepresentation( "licorice", {
        sele: "hetero and not ( water or ion )",
        multipleBond: true
    } );
    component.addRepresentation( "spacefill", {
        sele: "water or ion",
        scale: 0.5
    } );
}

Pass that function as a callback whenever you load a structure file via {@link Stage#loadFile}.

stage.loadFile( "rcsb://1crn" ).then( defaultStructureRepresentation );
stage.loadFile( "rcsb://4hhb" ).then( defaultStructureRepresentation );

Note that the same strategy works for surface and volume files loaded into a {@link SurfaceComponent}.

Distance-based selection

Get a selection of atoms that are within a certain distance of another selection.

stage.loadFile( "rcsb://3pqr" ).then( function( o ){
    // get all atoms within 5 Angstrom of retinal
    var selection = new NGL.Selection( "RET" );
    var radius = 5;
    var atomSet = o.structure.getAtomSetWithinSelection( selection, radius );
    // expand selection to complete groups
    var atomSet2 = o.structure.getAtomSetWithinGroup( atomSet );
    o.addRepresentation( "licorice", { sele: atomSet2.toSeleString() } );
    o.addRepresentation( "cartoon" );
    o.autoView();
} );

Change Log

All notable changes to this project will be documented in this file, following the suggestions of Keep a CHANGELOG. This project adheres to Semantic Versioning.

Unreleased

Added

  • contour option for volume surfaces (electron density maps)
  • buble, for transpiling some ES2015 features (e.g. classes, arrow functions, ...)
  • volume slice representation including interpolation support
  • xplor/cns volume file parser
  • colorVolume parameter for surface representation of volume data
  • voxelSize parameter for volume file parser
  • support for non orthogonal cell in cube file parser
  • dsn6/brix volume file parser
  • psf topology/structure file parser
  • wwPDB validation report xml parser, representation and colorschemes
  • support for picking Shape objects, Volume slices, Contact bonds
  • scroll mouse behavior to change far/near clipping and fog
  • label primitive for Shape class
  • support for reversing color schemes with colorReverse parameter
  • independent component movement via .setPosition, .setRotation, .setScale, .setTransform
  • bonded and ring selection language keywords
  • resname list to selection language, [ALA,GLU]

Changed

  • renamed volume parameter in molecular surface representation to colorVolume
  • renamed colormaker classes from colorMaker to colormaker, i.e. removed camel case
  • renamed ColormakerRegistry.getTypes to .getSchemes
  • colormaker subclasses now auto-register with ColormakerRegistry
  • refactored buffer classes to use a data object as input
  • refactored picking to be more general
  • replaced PickingData with PickingProxy
  • updated three.js to r85
  • updated chroma.js to 1.3.3
  • replaced utils/bitset with utils/bitarray
  • tweaked aminoacid keywords in selection language to follow rasmol/jmol, vmd

Removed

  • stage/component.centerView method, use .autoView instead
  • GidPool, picking handled by Picker objects
  • deprecated use of # for element selection, use _ instead

v0.9.3 - 2016-10-14

Changed

  • increased light distance from camera, to fix unlit rendering
  • remove double quotes from atomnames in chemComp cif parser

v0.9.2 - 2016-10-06

Changed

  • fix, moved polyfills back inside the bundle

v0.9.1 - 2016-10-06

Changed

  • removed (wrongly added) ngl2.js from dist folder
  • fixed chemComp cif parser not passing chainid

v0.9.0 - 2016-10-05

Added

  • lazy representation parameter that only builds & updates the representation when visible
  • chainname based color scheme
  • BondHash class to quickly get atoms connected to an atom
  • SpatialHash class to quickly get neighboring atoms/points
  • XmlParser parameter to use the browser's DOMParser
  • attachment (top, middle, bottom; left, center, right) for LabelRepresentation/TextBuffer
  • border color and width for LabelRepresentation/TextBuffer
  • colored background rectangle for LabelRepresentation/TextBuffer
  • "offset" style rendering of double/triple bonds (@fredludlow)
  • PubchemDatasource to load cid as sdf, pubchem://16490
  • basic entity support (type, description, chain mapping; mmcif, mmtf)
  • entitytype, moleculetype, chainid, polymer color schemes
  • ShaderRegistry, DecompressorRegistry
  • box display for "axes" representation

Changed

  • ResidueindexColorMaker colorscale domain on a per chain basis
  • ChainindexColorMaker colorscale domain on a per model basis
  • Fixed, initial parameters for a Buffer not taken into account
  • ignore bonds that are defined multiple times in PDB parser
  • updated mmtf lib to v1.0
  • use npm as the build system
  • complete list of ion and saccharide group names

Removed

  • gulp as the build system

v0.8 - 2016-07-22

Added

  • gulp build scripts
  • mmtf v0.2 support
  • support for rendering double/triple bonds, enable via multipleBond Representation parameter (@fredludlow, @arose)
  • stage.clicked signal (renamed from .onPicking)
  • stage.hovered signal
  • parsing of "chem comp" cif files
  • experimental "axes" representation showing the principal axes of an atom selection
  • added cone, arrow & ellipsoid buffers
  • added Shape class as a simple way to add custom shapes to the scene

Changed

  • reorganized everything to use es6 modules
  • read bondOrder from 'pdbx_value_order' in mmcif files
  • interpret 'CONECT 1529 1528 1528' as double bond in pdb files
  • side Buffer/Representation parameter changed: THREE.FrontSide => "front", THREE.BackSide => "back", THREE.DoubleSide => "double"
  • support for negative resno values in selections: "-5:A", "-12--8", "-12-0"
  • use chemical component type (available in mmtf) for determining molecule type
  • .get/setOrientation return/argument changed
  • enable SDF font as the default TextBuffer class only on Chrome
  • support for building using three-jsnext
  • renamed radiusSegments parameter to radialSegments
  • WebWorkers (for building surfaces) no longer need to load the main script file
  • NGL.GET renamed to NGL.getQuery

Removed

  • python-based build scripts
  • closure-compiler
  • stage.signals.onPicking (renamed to .clicked)
  • stage.signals.atom/bond/volume/nothingPicked, use .clicked instead
  • NGL.mainScriptFilePath no longer needed
  • NGL.useWorker, use "useWorker" representation parameter

v0.7.1a - 2016-06-02

Changed

  • fixed version in builds

v0.7.1 - 2016-06-02

Added

  • orthographic camera mode
  • backgroundColor parameter for Stage
  • x/y/z offset parameters for labels (TextBuffer)
  • OX1 atoms are recognized as part of the protein backbone
  • stage.makeImage now increments the task counter
  • added .isIdentity method to test if an Assembly is an identity transformation over all chains
  • embedded-dev build target (@sbliven)
  • support for responseType = "json" to efficiently load json data

Changed

  • there is no longer a fake unitcell created when no space group information is available
  • the query string is removed from urls before the determining file info (e.g. name, extension)
  • fixed labelText param not working in LabelRepresentation
  • enable SDF font as the default only on Chrome (fixes labels not shown on some OS/Browser)
  • ignore 'given' ncs operators
  • ensure that resname is upper case

Removed

  • stage.setTheme removed (use new backgroundColor parameter), themes now part of GUI code
  • NGL.Preferences is now part of the GUI code and removed from NGL.Stage. Setting overwritePreferences: true when instantiating an NGL.Stage object is not necessary anymore.
  • removed .requestVisibility method and signal (too GUI specific, if needed, should be handled there)

v0.7 - 2016-05-08

Added

  • Store and Proxy classes for memory efficiency
  • MMTF, DXBIN, DCD files format parsers
  • 'unitcell' representation
  • stage.makeImage (returns Promise)
  • take NCS operations into account when creating unitcell & supercell assemblies
  • added multi sample antialias rendering
  • added support for spinning around an axis
  • use bitsets for storing selections of atoms
  • Assembly and AssemblyPart classes
  • stage.toggleFullscreen method
  • read occupancy data when available (mmCIF, pdb, mmtf)
  • occupancy color scheme
  • alternate location support in selections, e.g. %B
  • read insertion codes when available (mmCIF, pdb, mmtf)
  • insertion code support in selections, e.g. ^A
  • numeric residue name support in selections, e.g. [032]
  • Queue class to handle async tasks

Changed

  • fixed transformation matrix in mrc/ccp4 parser
  • optimized near clipping
  • Fiber class remanamed to Polymer
  • more consistent fog
  • use workers more sparsely due to the large overhead of creating them
  • create font SDF on demand, remove asset dependency
  • integrated three.js lighting into custom shaders
  • MIGRATION: chainname read from auth_asym_id instead of from label_asym_id field
  • DOC: clarified apache configuration for deployment
  • FIX: cif parser, ignore non-displayable bonds between symmetry mates
  • FIX: cif parser, struct_conn bonds not added for multiple altloc atoms
  • LIB: updated signals.js
  • LIB: updated promise.js
  • LIB: updated three.js
  • LIB: updated pako.js to pako_inflate.js (no deflation support needed)
  • CODE: support loading of Blob objects in addition to File objects
  • CODE: tweaked DistanceRepresentation visibility params

Removed

  • zip, lzma, bzip2 decompression
  • removed async.js
  • mdsrv related code and documentation
  • stage.exportImage (makes image and triggers download), use stage.makeImage

v0.6 - 2015-10-12

Added

  • MIGRATION: Stage.loadFile signature changed, now returns a Promise and does not accept callbacks
  • MIGRATION: moved trajectory server into its own repository: MDSrv
  • ADD: Support for MOL2 and SDF files
  • ADD: Support for DX files
  • ADD: Support for PQR files
  • ADD: ExampleRegistry singleton
  • ADD: PluginRegistry singleton
  • ADD: Datasource class to use instead of hard-coded paths
  • ADD: GidPool
  • ADD: simple xml parser
  • ADD: APBS plugin to load PQR and DX file, simple GUI
  • ADD: bond and surface picking
  • ADD: User-defined color schemes (API)
  • GUI: VirtualList and VirtualTable
  • GUI: re-sizable sidebar (contents still need to be made responsive)
  • WIP: scripting API

Changed

  • EXAMPLES: general fixes and enhancements
  • DOC: moved installation and development information into the README
  • GUI/DOC: Higher color contrast for GUI and documentation pages
  • CODE: qunit updated
  • CODE: moved logical units of code into their own files
  • CODE: speeded up secondary structure assignment from PDB/mmCIF files; fixed bugs leading to wrong assignment
  • CODE: element color scheme now uses colorValue parameter to color carbon elements
  • CODE: script and assets paths are now configurable
  • CODE: more forgiving pdb parsing wrt to model records
  • CODE: helper function for re-ordering atoms
  • CODE: enhancements to handling Web Workers (WorkerPool, lazy Worker creation)
  • CODE: enhancements to volume triangulation (limit to given box, skip empty parts)
  • CODE: all *Buffer classes now inherit from Buffer and share common code
  • CODE: BufferAttributes can be re-used or grown
  • CODE: moved Buffer-specific code out of Representation class
  • CODE: molecular surface enhancements (color by atom, filter by atom)
  • CODE: nicer clipping of meshes and impostors (unlit interior to make them appear solid)
  • CODE: optimized kdtree building
  • CODE: clearer atomnames handling for fiber creation
  • CODE: Color handling code refactored exposing more parameters
  • CODE: Basic support for async creation of representations (so far used for molecular surfaces and volume triangulation)
  • CODE: chunked data loading and parsing via streamer class
  • CODE: faster autobonding of large residues (e.g. hydrated lipids)
  • CODE: WebWorker support while using development and build files
  • CODE: WebWorker used for decompression, parsing and surface generation
  • FIX: Issue #7
  • FIX: residues at the end of fibers may not require all backbone atoms
  • FIX: standard compatible atom names when writing pdb files
  • FIX: origin coordinates not used/read from mrc header

Removed

  • DEL: removed FragFit plugins

v0.5 - 2015-30-04

Added

  • Initial release