Design and development of an interactive visualization tools for molecular dynamics simulation data
Abstract
The research on molecular dynamics produces thousands of datasets pertaining the behavior of molecular compounds. The work aims to be a contribution toward the identification of effective ways to visualize the outcome of molecular simulations by the development of interactive visualization tool.
Full text
Design and Development of an Interactive Visualization Tools for Molecular Dynamics Simulation Data Giacomo Garbin 29 January 2019 Supervised by Pere-Pau Vázquez MOVING Group - UPC Marco Tarini Department of Computer Science University of Milan MASTER IN INNOVATION AND RESEARCH IN INFORMATICS FACULTAT D’INFORMÀTICA DE BARCELONA (FIB) UNIVERSITAT POLITÈCNICA DE CATALUNYA (UPC) BarcelonaTech
Index Abstract 3 1 Introduction 4 1.1 Motivation 5 1.2 Addressed Problem and Contribution 5 Root Mean Square Deviation 6 Root Mean Square Fluctuation 7 3D Visualization of RMSD and RMSF 7 1.3 Biomolecular Background 7 Our Case Study 9 1.4 Starting from Scratch 10 2 Space-Filling & Impostors 11 2.1 Space-Filling 11 2.2 Real Sphere 12 Subdivision Process 12 Normalization Process 13 Sphere Mesh 15 2.3 Impostor Sphere 17 2.3.1 Ray Tracing 17 2.3.2 Impostor Generation 18 Vertex Shader 18 Geometry Shader 19 Fragment Shader 20 2.3.3 First View 22 3 Lighting 24 3.1 Blinn-Phong Lighting Model 24 3.1.1 Light Components 25 Ambient Light 25 Diffuse Light 26 Specular Highlight 26 3.1.2 Turning on the Light 27 3.2 Screen-Space Ambient Occlusion (SSAO) 31 3.2.1 Geometry Step 32 3.2.2 Occlusion Step 33 3.2.3 Blur Step 38 3.2.4 Lighting Step 39 4 Object Outlining 42 4.1 Silhouette & Outline 42 4.1.1 Silhouette Step 42 1
4.1.2 Outline Step 44 4.2 Multi-Outline for Atoms & Residues 46 4.2.1 Silhouette Step 47 4.2.2 Outline Step 48 4.3 Outline Color Mapping 50 4.3.1 Color Palettes 50 4.3.2 Color Scheme 51 5 RMSD & RMSF 54 5.1 Deviations & Fluctuations 54 5.2 Comparing Conformations 55 5.2.1 Proper Rigid Transformation 55 5.2.2 Optimal Alignment & Kabsch Algorithm 56 5.2.3 Minimum RMSD & RMSF 58 5.3 Code Implementation 59 5.3.1 Class Definitions 59 5.3.2 Method Definitions 61 5.3.3 Data Storage 66 6 User Interface 67 6.1 Central Area 67 6.1.1 Model Rotating 68 6.1.2 Model Panning 69 6.1.3 Camera Orbiting 70 6.1.4 Atom Selection 71 6.1.5 Camera Zooming 74 6.2 Right Panel 74 6.2.1 Atom and Residue Data Tab Widget 74 6.2.2 Trajectory Data Widget 75 6.2.3 Object Outlining Widget 75 6.2.4 Lighting Tab Widget 76 6.3 Bottom Bar 77 6.4 Shneiderman’s Mantra 77 7 Conclusions 78 7.1 Addressed Problem and Contribution 78 7.2 Accomplished Results 78 7.3 Application Improvements 79 Bibliography 81 2
Abstract The research on molecular dynamics produces thousands of datasets pertaining the dynamic behavior of complex molecular compounds (including protein to protein docking, protein folding, and others), often by means of simulations, measurement. The work aims to be a contribution toward the identification of effective ways to visualize the outcome of molecular simulations. This involves the design, development, and testing (including user studies) of interactive visualization tools, which conveys the inspected spatiotemporal data by means of dashboards, charts and 3D rendering of relevant protein-ligand configurations. The tools must be complete with a GUI and can potentially leverage clustering algorithms, rendering algorithms (implemented via OpenGL or WebGL), and display devices such as power-walls. 3
1 Introduction Visualization is a discipline whose goal is to communicate information through images and it has a vast number of application areas. One of these areas is scientific visualization, which is focused on the visualization and inspection of scientific data in order to help scientists with understanding, knowledge discovery and hypothesis testing processes. The work presented in this report belongs to the field of molecular visualization, a branch of scientific visualization that aims to visually represent molecules and their properties, and to help understand their behavior over time. In many areas such as pharmacology or biotechnology, researchers use computers to perform molecular simulations (or MS) of the physical movements of atoms and molecules, and the interactions between molecules. In the context of drug design, MS aim at predicting the binding of a small molecule, called ligand (the drug), with a larger biomolecule, the protein. Such a binding may inhibit or activate certain function of the biomolecule, which results in a therapeutic benefit for the patient. Figure 1.1 : docking process of a drug into a protein The figure above shows the drug, highlighted in green, which attempts to enter an opening of the protein. 4
The result of a MS is a trajectory with the information of the positions of the atoms of both molecules in each step, together with associated data such as the temporal interactions that are established between the protein and the ligand and that guide the ligand towards the bound conformation, which they also help to stabilize. 1.1 Motivation Computing molecular simulations (or MS) is a complex and time-consuming process, and analyzing the results generated can take days or weeks. Therefore providing new tools and techniques to visualize and interact with these simulations is crucial to understanding them. The iterative loop in drug design typically involves simulations requiring long computation times, followed by a data analysis conducted by domain experts using also visualization tools. To help these experts during comprehension and decision making, it is of great importance to provide effective visualization tools. Two of the key aspects required to make informed decisions in the drug design process are estimating the interaction energy between the protein and the ligand, and understanding which parts of the molecule influence their binding. This information enables the domain expert to hypothesize which residues can be altered in the subsequent design process in order to improve the ligand’s affinity. Communication of this information is a challenge. 1.2 Addressed Problem and Contribution In contrast with the large efforts carried out in the field of molecular structural analysis, with a number of software packages providing all sorts of geometric information on the molecules, much less effort has been devoted to the development of efficient tools for the visual analysis of other variables such as the interaction forces. In nowadays molecular visualization packages the methods available to visualize the interaction forces that drive these simulations are limited. Most of the software packages use simple 2D plots or a 2D visualization of the molecule of interest (the ligand) with the nearest interacting atoms, making difficult to understand the real 3D arrangement of these atoms. Moreover, most of them have limited (or null) interaction and only allow the analysis of a single step of the simulation. The following figure shows two examples of 2D visualization of the root mean square fluctuation (or RMSF). 5
Figure 1.2 : two different 2D-methods to visualize RMSF (right side from [02]) The left side of the figure shows a screenshot of Schrödinger Maestro, where the RMSF is represented as a simple 2D plot. The right side of the figure shows the circular design proposed by P. Vázquez et al., which provides a link to the 3D structure of the molecule by maintaining the spatial order of the secondary structures, and, instead of visualizing this information as charts, they display the RMSF next to the protein backbone to facilitate relating the fluctuations with the residues involved. But still a 2D representation of the RMSF. Our goal with the work presented in this report is to display directly on the 3D models of a molecular simulation the information useful in understanding the interactions between protein and ligand. In particular we will focus on two quantities: the root mean square deviation (or RMSD) and the root mean square fluctuation (or RMSF) of both atoms and residues. Root Mean Square Deviation The RMSD of atomic positions is the measure of the average distance between the atoms of superimposed molecules. More generally, it is a measure of the average distance between two different conformations of a set of points in the three-dimensional space. In other words, the RMSD expresses how different two conformations are from each other. When a dynamical system fluctuates about some well-defined reference position, the RMSD from the average over time can be referred to as the root mean square fluctuation (or RMSF). 6
Root Mean Square Fluctuation The RMSF is a measure of the deviation of the position of a particle with respect to a reference position over time. Therefore this quantity can measure the average fluctuation of an atom around a reference position. The knowledge and visualization of both these quantities during an molecular simulation is a key element used by domain experts to detect important properties on the molecules involved and to better understand the interactions occurring during the simulation. These are some examples. ● RMSD is used as a quantitative measure of similarity between two or more molecular structures. ● In the study of protein folding, RMSD is used as a reaction coordinate to quantify where the protein is between the folded state and the unfolded state. ● RMSD is commonly used in the context of docking to study the configuration of ligands when bound to macromolecules. ● RMSF is used to reveal movements both in the protein and the ligand derived from the (potential) energies. High values of this quantity may indicate that some parts of the protein move to interact with the ligand guiding it towards the binding site, to make room for the ligand, or to establish stabilizing interactions with the ligand. ● RMSF is used to reveal which are the most flexible parts of the molecule. 3D Visualization of RMSD and RMSF The approach we proposed to visualize RMSD and RMSF directly on the molecule's 3D model is to outline the parts of the molecule involved into the study (which can be either individual atoms and residues) and map the values of RMSD and RMSF on a color scheme, which is then applied to the outline. 1.3 Biomolecular Background Amolecule is an electrically neutral group of two or more atoms held together by chemical bonds, while a biomolecule (or biological molecule) is a loosely used term for molecules that are present in organisms, essential to some typically biological process. The term biomolecules include also large macromolecules such as proteins. 7
In the following, we will mainly use the term molecule to refer to both concepts, it should be clear from the context to which we are actually referring. Cells are made of molecules, they communicate through molecules, and they respond to signals by changing existing molecules or making new ones. Molecules form the structures of cells and carry out cellular functions. Chemical bonds within and between biological molecules are important to their structure. Most jobs in the cell are done by proteins, which form one of the groups of large molecules most important for cells. To do their jobs, proteins must interact in a specific way with other molecules. The specific relationship between proteins and other molecules is based on the shape of the protein. Protein shape is complex and is essential to protein function. Proteins are polymers of amino acids (amino acids joined together by peptide bonds). 1 Figure 1.3 : amino acid structure (right side from Wikipedia) The central carbon atom is flanked by an amino group and a carboxyl group. The characteristic N-C-C sequence is called the backbone of the amino acids. The name of the amino acid (or residue) depends on which one of the 20 side-chain groups is at R. The side-chain can be as simple as a hydrogen atom (as in the amino acid glycine) or more complicated. Aresidue is a specific monomer within the protein, that is a molecule which can undergo polymerization, thereby contributing constitutional units to the essential structure of the macromolecule. 1polymer : a substance that has a molecular structure consisting chiefly or entirely of a large number of similar units bonded together 8
Figure 2.4 : a 3D example of the normalization process The figure above illustrates a three-dimensional example of the normalization process applied to the vertices of a triangle, which has been subjected to different iterations of the subdivision process. The left side of the figure shows the vertices before being normalized while the right side of the figure shows the vertices after being normalized. The normalization process is made with respect to a point placed along the line parallel to the normal direction of the triangle face and passing through its center. Sphere Mesh Applying the subdivision and normalization processes to an octahedron is possible to obtain the approximation mesh of a sphere. The following figure illustrates the normalization process applied to the vertices of an octahedron, whose triangular faces are subjected to successive iterations of the subdivision process. 15
Figure 2.5 : subdivision and normalization processes applied to an octahedron 16
Iterating the subdivision process further, it is possible to obtain an arbitrary approximation of a sphere, but obviously the number of vertices of the mesh increases accordingly. Therefore, with this approach we must choose between performance and image quality, both defined by the number of triangles used to approximate the spheres. 2.3 Impostor Sphere To overcome the problems inherent in the use of sphere meshes outlined in the previous section, it is de facto the standard nowadays in molecular visualization the use of impostors to render spheres. An impostor sphere is a square or quad, in the jargon of the computer graphics called billboard, placed in the position where the sphere should be and which is always oriented towards the camera. In the fragment shader a circle is drawn procedurally on the billboard in order to map each point on the square to a point on the sphere we are trying to render. There are two advantages compared to using sphere meshes. With impostors, only four vertices are needed to render each sphere and the spheres will always have the highest quality possible, limited only by the screen resolution. 2.3.1 Ray Tracing In the fragment shader, we compute the position and normal of each point along the sphere's surface by using a technique called ray tracing. For each fragment, we create a ray from the camera position in the direction towards that point on the impostor square and we detect the point on the sphere that the ray hits, if there is any. We can mathematically describe a ray with a pair of vectors, that is, the position from O which the ray is fired and the direction towards which the ray extends. The points on the D ︿ ray can be expressed as the following equation. (t) Dt OP = ︿ + Equation 2.1 : ray equation The points on a sphere of center and radius can be expressed as the following S R equation. R P S | || |− | || | = We can substitute with the ray equation. The ray is shot from the position of the camera, P which in view-space is always , so . With simple algebra, we obtain the following 0 0O= quadratic equation with respect to .t 17
D (︿ ·D ︿)t2− 2 D (︿ ·S)t+S (·S)−R2= 0 If the discriminant is negative, then the equation has no solution. In terms of our ray test, this means the ray misses the sphere. If the discriminant is positive, then the equation has two solution. The ray hits the sphere in two places: once going in, and once coming out. We're interested in the smallest solution, the one in front of the camera. Once we find a solution for , we can use the ray equation to compute the position. With the t position and the center of the sphere, we can also compute the normal. 2.3.2 Impostor Generation The generation of each impostor sphere follows the steps shown in Figure 2.6. Figure 2.6 : overview on impostor sphere generation The vertex shader receives the data of the sphere, the geometry shader builds the quad and the fragment shader calculates the position and normal of each point of the sphere. Vertex Shader The vertex shader is invoked only once for each sphere and generates a single point. Listing 2.1 : impostor vertex shader #version 450 core layout (location = 0) in vec3 center; layout (location = 1) in float radius; layout (location = 2) in vec3 albedo; out Vertex { vec3 center; float radius; vec3 albedo; } vert; void main() 18
{ vert.center = center; vert.radius = radius; vert.albedo = albedo; } The vertex shader is straightforward. It receives the information of the sphere as input, namely the position of the center, the radius and the color of the sphere. In our case, each sphere represents an atom of a molecule and the values of radius and albedo will be those that distinguish the chemical element of the atom. Geometry Shader The geometry shader receives the point generated by the vertex shader as input. For each received point, it generates four new vertices, each deviated so as to form the vertices of the billboard, which is returned as a triangle strip. Listing 2.2 : impostor geometry shader #version 450 core layout (points) in; layout (triangle_strip, max_vertices = 4) out; in Vertex { vec3 center; float radius; vec3 albedo; } vert[]; uniform mat4 model; uniform mat4 view; uniform mat4 projection; out Fragment { flat vec3 center; flat float radius; flat vec3 albedo; smooth vec2 offset; } frag; void main() { vec2 offsets[4]; offsets[0] = vec2(-1.0f, -1.0f); offsets[1] = vec2(-1.0f, +1.0f); offsets[2] = vec2(+1.0f, -1.0f); offsets[3] = vec2(+1.0f, +1.0f); float BoxCorrection = 1.5f; for (int i = 0; i < 4; i++) 19
{ gl_Position = view * model * vec4(vert[0].center, 1.0f); frag.center = vec3(gl_Position); frag.radius = vert[0].radius; frag.albedo = vert[0].albedo; frag.offset = offsets[i] * BoxCorrection; gl_Position.xy += (frag.offset * frag.radius); gl_Position = projection * gl_Position; EmitVertex(); } EndPrimitive(); } The geometry shader also expands the size of the square, in order to avoid the problem illustrated in Figure 2.7. Figure 2.7 : billboard size correction If the square were the same size as the sphere, in certain configurations, such as with large spheres or after a large zoom-in, some parts of the impostor would be cut off. Fragment Shader The fragment shader applies the ray tracing algorithm described in Section 2.3.1 and returns the position, normal vector and color of each pixel in three different color buffers. Note that the exported positions and normals are in view-space. 20
Listing 2.3 : impostor fragment shader #version 450 layout (location = 0) out vec3 center; layout (location = 1) out vec3 normal; layout (location = 2) out vec3 albedo; struct Impostor { vec3 center; vec3 normal; }; void SetImpostor(out Impostor impostor); in Fragment { flat vec3 center; flat float radius; flat vec3 albedo; smooth vec2 offset; } frag; uniform mat4 projection; void main() { Impostor impostor; SetImpostor(impostor); // frag depth vec4 clip = projection * vec4(impostor.center, 1.0f); float depth = clip.z / clip.w; float near = gl_DepthRange.near; float far = gl_DepthRange.far; float diff = gl_DepthRange.diff; gl_FragDepth = ((diff * depth) + near + far) * 0.5f; center = impostor.center; normal = impostor.normal; albedo = frag.albedo; } void SetImpostor(out Impostor impostor) { vec3 ray = normalize(frag.center + vec3(frag.offset * frag.radius, 0.0f)); float b = 2.0f * dot(ray, -frag.center); float c = dot(frag.center, frag.center) - (frag.radius * frag.radius); float delta = (b * b) - (4.0f * c); if(delta < 0.0f) { discard; 21
} delta = sqrt(delta); float t1 = (-b + delta) * 0.5f; float t2 = (-b - delta) * 0.5f; float t = min(t1, t2); impostor.center = ray * t; impostor.normal = normalize(impostor.center - frag.center); } The impostor sphere has no depth, it's just a circle on the billboard. We have to write the depth value ourselves going through the process OpenGL normally goes through to compute the depth. The view-space position is transformed to clip-space through the projection matrix. The perspective division happens, transforming to normalized device coordinate (NDC) space. The depth range function is applied, forcing the [-1, +1] range in the fragment shader to the range provided with glDepthRange. We write the final depth to a built-in output variable gl_FragDepth. 2.3.3 First View We can finally take a look to the model of our case study. Figure 2.8 : a first look at the model of our case study In the figure above, each fragment of the model is assigned the corresponding albedo value attenuated with a grayscale factor based on the normal vector of the fragment. 22
Although the rendered image in Figure 2.8 allows us to perceive the atoms configuration of the molecules, does not return a great feeling of realism. In the next chapter we will use the information generated by the sphere impostor fragment shader to improve the realism of the image by integrating a lighting model into the project. 23
3 Lighting In the previous chapter we illustrated an approach, called impostors, which allows us to visualize a scene with a large quantity of spherical models (which will represent the atoms of our molecules), rendered with the highest quality possible and with a small computational cost. Moreover, the impostor's strategy returns for each sphere two precious geometrical information, namely the position and normal vectors of each fragment, which we will use in this chapter for lighting calculations. At the end of the previous chapter we tried to render the model of our case study using only the information available to us, without further calculations (see Figure 2.8). Although the resulted image allows us to perceive the atoms configuration of the molecules, does not return a great feeling of realism. In this chapter we will integrate a lighting model into the application, improving the realism transmitted by the generated images, which in turn facilitates the understanding of the configuration of molecular models. 3.1 Blinn-Phong Lighting Model The simulation of light in computer graphics is a huge topic. Many approaches have been proposed, some of them very complex and expensive in terms of computational resources, and therefore not suitable for real-time applications, while other models try to find a good compromise between the realism of the simulation and its performance. To this second category belongs also the lighting model that we will integrate in the project, which is known as the blinn-phong lighting model. The process of lighting in our application consists of two phases or steps. Figure 3.1 : steps of lighting process ●Geometry Step : in this step the geometry of the scene is calculated and then "exported" to be used in the next stage 24
The introduction of a lighting model greatly increases the sense of realism perceivable in the images generated by the application, compare Figure 3.5 with Figure 2.8 of the previous chapter. However, when a sphere is illuminated, the current model does not take into account the neighboring spheres. All objects receive the same lighting, based exclusively on the direction between light and object, regardless of the surrounding environment. This is the issue we will tackle in the next section with the use of a technique for the dynamic computation of the ambient light component. 3.2 Screen-Space Ambient Occlusion (SSAO) In the Blinn-Phong lighting model, illustrated in the previous section, the ambient component is simply a constant. In reality, it depends on the geometry of the scene to which the lighting model is applied. A widespread technique that approximates indirect light in real-time is called screen-space ambient occlusion (or SSAO). SSAO generates an occlusion factor for each fragment based on the depth value of the surrounding fragments, which is then used to attenuate the ambient component of the lighting model. As the name suggests, SSAO works in screen-space, and is part of a family of techniques, called deferred rendering, in which the lighting calculation is separated by and postponed to (deferred to) the calculation of the scene geometry. SSAO consists of four phases or steps. Figure 3.6 : steps of screen-space ambient occlusion ●Geometry Step : in this step the geometry of the scene is calculated and then "exported" to be used in the following stages ●Occlusion Step : in this step the occlusion factor of each fragment is calculated ●Blur Step : in this step a blur effect is applied to the result of the previous stage to obtain a smooth occlusion factor ●Lighting Step : in this step the lighting model is applied and its ambient component is attenuated using the occlusion factor generated in the previous stages 31
3.2.1 Geometry Step SSAO calculates the occlusion factor in view-space. In this step the scene geometry, that is, positions and normals of the vertices, are transformed into view-space and stored in two textures: center and normal. This fits well with the approach used to generate the impostor spheres described in the previous chapter, since it also works in view-space. Moreover, another texture called albedo is filled with the colors of the vertices. Listing 3.2 : geometry fragment shader #version 450 layout (location = 0) out vec3 center; layout (location = 1) out vec3 normal; layout (location = 2) out vec3 albedo; struct Impostor { vec3 center; vec3 normal; }; void SetImpostor(out Impostor impostor); in Fragment { flat vec3 center; flat float radius; flat vec3 albedo; smooth vec2 offset; } frag; uniform mat4 projection; void main() { Impostor impostor; SetImpostor(impostor); // ... center = impostor.center; normal = impostor.normal; albedo = frag.albedo; } The fragment shader of the geometry step calculates the scene geometry and exports the results in three different color buffers, attached respectively to the center, normal and albedo textures. 32
center texture normal texture albedo texture Figure 3.7 : result of the geometry step applied to our case study The figure above shows the result of the geometry step applied to our case study. 3.2.2 Occlusion Step SSAO generates an occlusion factor for each fragment based on the depth value of the surrounding fragments. The samples that make up the sample kernel are distributed within a hemisphere tangent to the fragment, with the normal vector pointing in the positive z direction. Listing 3.3 : SSAO kernel definition void SetKernel() { QRandomGenerator generator = QRandomGenerator::securelySeeded(); kernel.clear(); auto lerp = [] (float a, float b, float f) { return a + f * (b - a); }; float size = KernelSize * KernelSize; for (int i = 0; i < size; i++) { QVector3D sample; sample.setX(generator.generateDouble() * 2.0f - 1.0f); sample.setY(generator.generateDouble() * 2.0f - 1.0f); sample.setZ(generator.generateDouble()); sample.normalize(); sample *= generator.generateDouble(); float scale = i / size; sample *= lerp(0.1f, 1.0f, scale * scale); kernel.append(sample); } } 33
In order for the kernel samples to fall within a hemisphere, the x and y components of each sample are randomly generated in the range -1.0 and +1.0, while the z component is randomly selected in the range 0.0 and 1.0. Furthermore, the length of each sample is scaled with a quadratic interpolation factor, in order to distribute a greater number of samples near the origin of the hemisphere, ie the current fragment. Generating a sample kernel for each fragment is computationally too heavy. To overcome this problem, a single sample kernel is generated that is randomly rotated around the normal of each fragment. But similarly, generating a rotation vector for each fragment is too expensive. The solution to this problem is to create a small array of rotation vectors and then distribute this pattern of rotations along the entire screen-space. Listing 3.4 : SSAO noise definition void SetNoise(int w, int h) { QRandomGenerator generator = QRandomGenerator::securelySeeded(); noise.clear(); for (int i = 0; i < NoiseSize * NoiseSize; i++) { float x = generator.generateDouble() * 2.0f - 1.0f; float y = generator.generateDouble() * 2.0f - 1.0f; noise.append({x, y, 0}); } SetNoiseScale(w, h); } void SetNoiseScale(int w, int h) { NoiseScale.setX(w); NoiseScale.setY(h); NoiseScale /= NoiseSize; } In order for the sample kernel rotations to be around the z axis (tangent space), the x and y components of each rotation vector are randomly generated in the range -1.0 and +1.0, while the z component is set to 0. The scale factor of the rotation pattern is also updated to adapt it to the current screen size. This scale factor will be used later in the fragment shader for the calculation of the sampling offsets of the rotation vectors. The sample kernel and the rotation pattern are both transferred to the GPU through the use of textures, and together with the center and normal textures generated in the geometry step, they are the input of the occlusion step fragment shader. 34
Listing 3.5 : occlusion fragment shader #version 450 core struct FragData { vec3 center; vec3 normal; vec3 noise; }; smooth in vec2 offset; uniform mat4 projection; uniform sampler2D center; uniform sampler2D normal; uniform sampler2D kernel; uniform sampler2D noise; uniform int size; // kernel size uniform vec2 scale; // noise scale uniform float radius; uniform float bias; out float occlusion; void main() { FragData frag; frag.center = texture(center, offset).xyz; frag.normal = normalize(texture(normal, offset).xyz); frag.noise = normalize(texture(noise, offset * scale).xyz); // TBN matrix vec3 tangent = normalize(frag.noise - frag.normal * dot(frag.noise, frag.normal)); vec3 bitangent = cross(frag.normal, tangent); mat3 TBN = mat3(tangent, bitangent, frag.normal); occlusion = 0.0f; for(int i = 0; i < size; i++) { float x = float(i) / float(size); for(int j = 0; j < size; j++) { float y = float(j) / float(size); vec3 KernelSample = TBN * texture(kernel, vec2(x, y)).xyz; KernelSample = frag.center + KernelSample * radius; vec4 offset = vec4(KernelSample, 1.0f); offset = projection * offset; offset.xyz /= offset.w; offset.xyz = offset.xyz * 0.5f + 0.5f; 35
float depth = texture(center, offset.xy).z; float range = smoothstep(0.0f, 1.0f, radius / abs(frag.center.z - depth)); occlusion += ((depth >= KernelSample.z + bias) ? 1.0f : 0.0f) * range; } } occlusion = 1.0f - (occlusion / float(size * size)); } The data of each fragment is extracted from the textures passed in input to the fragment shader. With the normal and the rotation vector, a TBN (tangent, bitangent and normal) matrix is constructed by means of the Gram-Schmidt orthogonalization process to transform the samples (slightly inclined with respect to the rotation vector) from tanget-space to view-space. Each kernel sample is then transformed into view-space, translated with respect to the fragment position and modulated by the uniform radius, which parameterizes the range of the SSAO. The next step transforms the sample from view-space to screen-space (using the projection matrix, also passed to the fragment shader as uniform) and retrieve from the texture center (which contains the position in view-space of each fragment) the depth of the texel associated with the current sample. This sample contributes to the occlusion factor if its depth is greater than or equal to the z component of the sample. In other words, the sample contributes to the occlusion factor, if it is "inside" some geometry near the fragment. Vice versa, if the depth is less than the z component of the sample, it means that in that particular position there are no elements of occlusion for the fragment. occlusion += (depth >= KernelSample.z) ? 1.0f : 0.0f; Without further precautions, this approach suffers from a problem when the fragment under examination is on the edge of a surface. In this case the depth values of surfaces that do not contribute to the occlusion factor are also taken into consideration, as the following image shows. 36
Figure 3.8 : bad occlusion factor This problem can be prevented by checking if the sample depth is within the sampling radius. Moreover, instead of a brusque "on/off", the contribution of each sample is interpolated between 0 and 1 to ensure a smooth effect near the radius limit. Finally, the fragment shader returns the normalized occlusion factor with respect to the sample kernel size. Figure 3.9 : good occlusion factor 37
As can be seen from the figure above, the occlusion factor generated by the fragment shader allows us to perceive the depth of the model. 3.2.3 Blur Step To get around the problem of having to generate a rotation vector for the sample kernel for each fragment, we created a small array of rotation vectors and used its values repeatedly along the whole screen-space. This strategy has a price, observable in the Figure 3.9. The repeated pattern of the rotation vectors is distinctly recognizable. For this reason, before attenuating the ambient component in the lighting step with the occlusion factor, a blur effect should be applied to the latter. Listing 3.6 : blur fragment shader #version 450 core smooth in vec2 coords; uniform sampler2D occlusion; uniform int NoiseSize; out float blur; void main() { int HalfNoiseSize = int(NoiseSize * 0.5f); vec2 size = 1.0f / vec2(textureSize(occlusion, 0)); blur = 0.0f; for (int x = -HalfNoiseSize; x < +HalfNoiseSize; x++) { for (int y = -HalfNoiseSize; y < +HalfNoiseSize; y++) { vec2 offset = vec2(x, y) * size; blur += texture(occlusion, coords + offset).r; } } blur *= 1.0f / (NoiseSize * NoiseSize); } The fragment shader receives the texture with the values of the occlusion factor generated by the previous step and uses the randomness pattern of the rotation vectors to generate a simple but effective blur effect. 38
Figure 3.9 : occlusion factor with blur effect The figure above shows the occlusion factor with the blur effect applied and that will be used in the next step. 3.2.4 Lighting Step To integrate the occlusion factor into the lighting model, it is sufficient to attenuate the ambient component of the lighting model with the occlusion factor generated in the previous steps. Listing 3.7 : lighting fragment shader #version 450 core struct Fragment { vec3 center; vec3 normal; vec3 albedo; float SSAO; }; struct Light { // ... }; void SetFragment(out Fragment frag); vec3 GetLighting(Fragment frag, Light light, vec3 eye); smooth in vec2 offset; 39
uniform sampler2D center; uniform sampler2D normal; uniform sampler2D albedo; uniform sampler2D occlusion; uniform float shininess; uniform Light light; out vec4 PixelColor; void main() { Fragment frag; SetFragment(frag); PixelColor = vec4(GetLighting(frag, light, vec3(0.0f)), 1.0f); } void SetFragment(out FragData frag) { frag.center = texture(center, offset).xyz; frag.normal = texture(normal, offset).xyz; frag.albedo = texture(albedo, offset).rgb; frag.SSAO = texture(occlusion, offset).r; } vec3 GetLighting(Fragment frag, Light light, vec3 eye) { float factor; // ambient component factor = frag.SSAO; vec3 ambient = factor * light.ambient; // diffuse component // ... // specular component // ... vec3 lighting = (ambient + diffuse + specular) * frag.albedo; return lighting; } The fragment shader of the lighting step receives the geometry and the colors of the scene as input through the textures generated in the geometry step, together with the values of the occlusion factor generated in the previous stages. Ambient occlusion is applied to each fragment simply by multiplying the ambient component of the lighting model by the occlusion factor extracted from the occlusion texture. 40
4.2.1 Silhouette Step To achieve the multi-outline effect, we first need to assign to the silhouette of each object (in our case atoms or residues) a unique color, so we can then associate the desired outline color to each object in the outline step. A unique color for each object can be obtained by converting the serial number of atoms and residues into a triplet of bytes and use these values to define the red, green and blue channels of the object's color outline. We can also take advantage of the fact that serial numbers of atoms and residuals are always positive values. This means that the byte triplet (0, 0, 0) is not associated with any object and therefore the black color can be used as clear color for the silhouette. Listing 4.5 : multi-silhouette vertex shader #version 450 core layout (location = 0) in vec3 center; layout (location = 1) in float radius; layout (location = 2) in vec3 albedo; layout (location = 3) in vec2 number; uniform int OutlineMode; out VertData { vec3 center; float radius; vec3 colour; } vert; void main() { uvec3 mask = uvec3(0x00FF0000, 0x0000FF00, 0x000000FF); uvec3 shift = uvec3(16, 8, 0); vec3 colour; switch (OutlineMode) { // residue number case 0: case 1: { colour = ((uvec3(number[1]) & mask) >> shift) / 255.0f; break; } // atom number case 2: case 3: { 47
colour = ((uvec3(number[0]) & mask) >> shift) / 255.0f; break; } } vert.center = center; vert.radius = radius; vert.colour = colour; } The new silhouette vertex shader receives two additional information, namely the pair of atom and residue serial numbers and the OutlineMode uniform to determine which of the two serials should be used to define the color of the object's silhouette. The conversion between serial number and byte triplet is computed with a sequence of bitwise operations. The result is then divided by 255 to obtain a triplet of values in the range 0 - 1, that is to say the color to be assigned to the object's silhouette in the silhouette fragment shader. Figure 4.3 : silhouette colored based on the residue numbers The figure above shows the colored silhouette based on the residue numbers. It should not be surprising to observe dark blue gradations. The number of residues in our case study is 121 and the first 255 values are mapped to the blue channel. 4.2.2 Outline Step Before drawing the outline, we pass to the multi-outline fragment shader a 1D texture with the outline colors of all atoms or residues, depending on the outline mode. The colors in the 48
texture are ordered based on the serial numbers of atoms or residues. We can therefore access the outline color of an object by indexing the texture directly with its serial. Listing 4.6 : multi-outline fragment shader #version 450 struct Outline { int thickness; sampler1D color; }; in smooth vec2 texcoord; uniform sampler2D silhouette; uniform Outline outline; out vec4 PixelColor; void main() { vec3 texel = texture(silhouette, texcoord).rgb; // if the texel is NOT black (we are on the silhouette) if (texel != vec3(0.0f)) { vec2 size = 1.0f / textureSize(silhouette, 0); for (int i = -outline.thickness; i <= +outline.thickness; i++) { for (int j = -outline.thickness; j <= +outline.thickness; j++) { if (i == 0 && j == 0) { continue; } vec2 offset = vec2(i, j) * size; // and if one of the texel-neighbors has a different color // (we are on the border or on another atom/residue) if (texture(silhouette, texcoord + offset).rgb != texel) { // retrieve atom/residue number uvec3 shift = uvec3(16, 8, 0); uvec3 rgb = uvec3(texel * 255.0f); uint number = 0; for (int j = 0; j < 3; j++) { number += rgb[j] << shift[j]; } // retrieve outline color float size = 1.0f / textureSize(outline.color, 0); 49
float offset = number * size + size * 0.5f; vec3 color = texture(outline.color, offset).rgb; PixelColor = vec4(color, 1.0f); return; } } } } discard; } The multi-outline fragment shader is mostly the same as Listing 4.4. We first sample the silhouette texture and check if the texel color is black. If it is, we are not on the silhouette and we can directly discard the fragment. Otherwise, as before, we explore the neighboring texels in a radius equal to the desired outline thickness in search of a texel whose color is different from that of the current texel. If the search fails, we discard the fragment. Otherwise, if there is any, it means that we have reached the edge of the object or the silhouette of another object. In both cases, we retrieve the serial number reconverting the texel color and use it to offset the outline texture color. We can then return the desired outline color. 4.3 Outline Color Mapping Choose the best coloring for the outline is a matter of tweaking and experimentation. 4.3.1 Color Palettes The application gives the user the possibility to choose between different color brewer palettes. Listing 4.7 : outline color palettes enum ColorPaletteType { sequential, diverging, qualitative }; struct ColorPalette { QString name; ColorPaletteType type; QMap<int, QString> colors; }; QVector<ColorPalette> ColorPalettes { { "RdPu", sequential, { {3, "#fde0dd #fa9fb5 #c51b8a"}, {4, "#feebe2 #fbb4b9 #f768a1 #ae017e"}, {5, "#feebe2 #fbb4b9 #f768a1 #c51b8a #7a0177"}, 50
{6, "#feebe2 #fcc5c0 #fa9fb5 #f768a1 #c51b8a #7a0177"}, {7, "#feebe2 #fcc5c0 #fa9fb5 #f768a1 #dd3497 #ae017e #7a0177"} } }, { "BrBG", diverging, { {3, "#d8b365 #f5f5f5 #5ab4ac"}, {4, "#a6611a #dfc27d #80cdc1 #018571"}, {5, "#a6611a #dfc27d #f5f5f5 #80cdc1 #018571"}, {6, "#8c510a #d8b365 #f6e8c3 #c7eae5 #5ab4ac #01665e"}, {7, "#8c510a #d8b365 #f6e8c3 #f5f5f5 #c7eae5 #5ab4ac #01665e"} } }, { "RdYlBu", diverging, { {3, "#fc8d59 #ffffbf #91bfdb"}, {4, "#d7191c #fdae61 #abd9e9 #2c7bb6"}, {5, "#d7191c #fdae61 #ffffbf #abd9e9 #2c7bb6"}, {6, "#d73027 #fc8d59 #fee090 #e0f3f8 #91bfdb #4575b4"}, {7, "#d73027 #fc8d59 #fee090 #ffffbf #e0f3f8 #91bfdb #4575b4"} } }, }; By filling the ColorPalettes array with additional ColorPalette structures, the new palettes will be automatically integrated into the application and made available to the user. 4.3.2 Color Scheme The outline colors are organized in color schemes, which are a collection of color steps. Each color spet defines a values range (minimum and maximum values) and a color associated with that range. When a value falls within the range defined by the color step, the color of the step is assigned to the outline. Listing 4.8 : outline color scheme struct ColorStep { int number; float min; float max; QColor color; }; typedef QVector<ColorStep> ColorScheme; ColorScheme GetColorScheme(float min, float max, ColorPalette palette, int size) 51
{ ColorScheme scheme; QStringList colors = palette.colors[size].split(" "); float span = (max - min) / size; for (int i = 0; i < size; i++) { ColorStep step; step.number = i; step.min = min + span * i; step.max = min + span * (i+1); step.color = colors[i]; scheme += step; } scheme.first().min = 0; scheme.last().max = FLT_MAX; return scheme; } static ColorStep GetColorStep(ColorScheme scheme, float value) { for (auto step : scheme) { if (step.min <= value && value < step.max) { return step; } } ColorStep InvalidStep; InvalidStep.number = -1; InvalidStep.min = NAN; InvalidStep.max = NAN; InvalidStep.color = QColor::Invalid; return InvalidStep; } The GetColorScheme() method takes the minimum and maximum values of the range to be partitioned and the number of desired partitions (size). It constructs a color scheme by partitioning the range of values in the specified number of partitions and associating the corresponding colors extracted from the selected palette. The GetColorStep() method receives a color scheme and a value to be tested. It checks if the value falls into one of the color scheme partitions and if so, returns the corresponding color step, from which the outline color can be extracted. 52
Figure 4.4 : multi-outlining with color brewer palette The figure above shows the multi-outlining effect achieved by mapping a color brewer palette. In the next chapter we will calculate the values of RMSD and RMSF with which we will define the outline color schemes for atoms and residues. 53
5 RMSD & RMSF In Chapters 2 and 3 we built a 3D viewer to display molecular models. We have chosen space-filling as method of representation. This means that each atom of the molecule is represented by a sphere and, using a technique called impostors, we did not have to compromise between performance and image quality. Moreover, in order to increase the sense of realism of the model, we have integrated a lighting model into the application. In the previous chapter we implemented the multi-outlining for atoms and residues. This feature allows us to outline each atom or residue of the molecule and assign a different outline color to each of them. This chapter illustrates how the values of root mean square deviation (RMSD) and root mean square fluctuation (RMSF) have been computed, both at atom and residue level, and how they are mapped to the outline color of the objects in the scene. 5.1 Deviations & Fluctuations The root mean square deviation (or RMSD) of atomic positions is the measure of the average distance between the atoms of superimposed molecules, or, more generally, it is a measure of the average distance between two different conformations of a set of points in three-dimensional space. In other words, the RMSD expresses how different two conformations are from each other. We can express the RMSD with the following equation. Equation 5.1 : root mean square deviation In Equation 5.1, is the number of points in the set and represents the position of the N xi, t point at the time . The set of positions of all the points in the set at a given time is called i t t conformation at the time . The conformation at the time is called reference t tref conformation and is used as a reference value to measure the deviation of another conformation. When a dynamical system (like a molecule) fluctuates about some well-defined reference position, the RMSD from the average over time can be referred to as the root mean square fluctuation (or RMSF). 54
The RMSF is then a measure of the deviation of the position of a particle with respect to a reference position over time. Therefore this quantity can measure the average fluctuation of an atom around a reference position. We can express the RMSF with the following equation. Equation 5.2 : root mean square fluctuation In Equation 5.2, is the samples number of the positions of the points in the set (or the time T instants) along which the fluctuation is calculated. As before, represents the position of xi, t the point at the time and represents its reference position.i t xi, tref When used to measure the deviation or fluctuation of atomic positions, RMSD and RMSF are typically expressed in angstroms, where 1 Å is equal to 10-10 m. 5.2 Comparing Conformations When we compare the conformations of a dynamic system, such as the molecular conformations sampled from a molecular simulation, before applying Equation 5.1 and Equation 5.2 on a conformation to calculate its RMSD and RMSF, a roto-translation on the conformation should be carried out to align it as best as possible to the reference conformation. We apply this transformation on the conformation in order to compensate the fact that a molecule can (and probably will) drift away from its origin and rotate in an arbitrary way during its trajectory. The result will be the minimum (or least) RMSD and RMSF over all the possible relative positions and orientations of the two conformations under consideration. In this way we obtain a measure of the deviations and fluctuations mostly due to the interactions between the molecules and that tries to filter out other possible turbulences due to the independent movement of the structures. 5.2.1 Proper Rigid Transformation Before calculating the RMSD and RMSF of a conformation, we will apply a roto-translation to align it as best as possible to the reference configuration. 55
Each roto-translation (or proper rigid transformation) can be decomposed into two operations: a translation and a rotation. This class of transformations has an important property: any object will keep the same shape and size after a proper rigid transformation. It is a subclass of the class transformations that also includes the operation of reflection and whose elements are called rigid transformations. Any rigid transformation preserves the of the objects size (the euclidean distance between every pair of points), but in general does not preserve the objects shape (due to the possible reflections). A rigid transformation is formally defined as a transformation that, when acting on any vector , produces a transformed vector of the following form. Equation 5.3 : rigid transformation Where is an orthogonal transformation (i.e., ), and is a vector giving the R RRT= −1 translation of the origin. A proper rigid transformation also satisfies the following property. et 1d(R) = Equation 5.4 : proper rigid transformation Which means that does not produce a reflection, and hence it represents a rotation (an R orientation-preserving orthogonal transformation). Indeed, when an orthogonal transformation matrix produces a reflection, its determinant is equal to –1. 5.2.2 Optimal Alignment & Kabsch Algorithm As stated in the previous paragraph, the optimal alignment requires both a translation and a rotation. We can resolve the translation part if we first move the conformation so that its centroid coincides with the centroid of the reference conformation. The centroid of a set of points is the average position of all its points. 56
MaxResiduesRMSD = MaxInitValue; // initialize residues Min and Max RMSF MinResiduesRMSF = MinInitValue; MaxResiduesRMSF = MaxInitValue; for (auto &residue : residues) { // reference conformation : 1st model QVector<QVector3D> x; QVector<Vector3f> a; // get conformation atoms positions for (auto AtomNumber : residue.atoms) { x += FirstModel[AtomNumber]; } // get conformation centroid QVector3D c = GetCentroid(x); for (auto &v : x) { // move centroid to reference system origin v = v - c; // from QVector3D to Vector3f a += FromQVector3DToVector3f(v); } ConformationLookupTable[residue.number] += a; // get conformation rotate matrix Matrix3f R = GetRotateMatrix(a, a); OptimalRotationMatrixLookupTable[residue.number] += R; // get conformation RMSD residue.RMSDs += GetRMSD(a, a, R); // initialize residue Min and Max RMSD residue.MinRMSD = MinInitValue; residue.MaxRMSD = MaxInitValue; for (auto model : models.mid(1)) { // movement conformation QVector<QVector3D> y; QVector<Vector3f> b; // get conformation atoms positions for (auto AtomNumber : residue.atoms) { y += model[AtomNumber]; } // get conformation centroid QVector3D c = GetCentroid(y); for (auto &v : y) 63
{ // move centroid to reference system origin v = v - c; // from QVector3D to Vector3f b += FromQVector3DToVector3f(v); } ConformationLookupTable[residue.number] += b; // get conformation rotate matrix Matrix3f R = GetRotateMatrix(a, b); OptimalRotationMatrixLookupTable[residue.number] += R; // get conformation RMSD float RMSD = GetRMSD(a, b, R); residue.RMSDs += RMSD; // update residue Min and Max RMSD residue.MinRMSD = (RMSD < residue.MinRMSD) ? RMSD : residue.MinRMSD; residue.MaxRMSD = (RMSD > residue.MaxRMSD) ? RMSD : residue.MaxRMSD; } // get residue RMSF residue.RMSF = GetAverage(residue.RMSDs); // update residues Min and Max RMSD MinResiduesRMSD = (residue.MinRMSD < MinResiduesRMSD) ? residue.MinRMSD : MinResiduesRMSD; MaxResiduesRMSD = (residue.MaxRMSD > MaxResiduesRMSD) ? residue.MaxRMSD : MaxResiduesRMSD; // update residues Min and Max RMSF MinResiduesRMSF = (residue.RMSF < MinResiduesRMSF) ? residue.RMSF : MinResiduesRMSF; MaxResiduesRMSF = (residue.RMSF > MaxResiduesRMSF) ? residue.RMSF : MaxResiduesRMSF; } } The method CookResidues() calculates the RMSD of each residue at each step of the simulation. The first step of the simulation is chosen as the reference conformation. For each residue the minimum and maximum RMSD values are saved. The RMSF of each residuel is calculated as an average on all RMSD values. Finally, the minimum and maximum RMSD values of all residues on the entire simulation are saved. Listing 5.7 : CookAtoms() trajectory method void Trajectory::CookAtoms() { // initialize atoms Min and Max RMSD MinAtomsRMSD = MinInitValue; MaxAtomsRMSD = MaxInitValue; // initialize atoms Min and Max RMSF MinAtomsRMSF = MinInitValue; 64
MaxAtomsRMSF = MaxInitValue; for (auto &atom : atoms) { // atom conformation index int AtomIndex = residues[atom.residue].atoms.indexOf(atom.number); // reference conformation : 1st model auto x = ConformationLookupTable[atom.residue].first(); // get atom position Vector3f a = x[AtomIndex]; // get rotate matrix Matrix3f R = OptimalRotationMatrixLookupTable[atom.residue][0]; // get atom RMSD atom.RMSDs += (R * a - a).norm(); // initialize atom Min and Max RMSD atom.MinRMSD = MinInitValue; atom.MaxRMSD = MaxInitValue; for (int i = 1; i < models.size(); i++) { // movement conformation auto y = ConformationLookupTable[atom.residue][i]; // get atom position Vector3f b = y[AtomIndex]; // get rotate matrix Matrix3f R = OptimalRotationMatrixLookupTable[atom.residue][i]; // get atom RMSD float RMSD = (R * b - a).norm(); atom.RMSDs += RMSD; // update atom Min and Max RMSD atom.MinRMSD = (RMSD < atom.MinRMSD) ? RMSD : atom.MinRMSD; atom.MaxRMSD = (RMSD > atom.MaxRMSD) ? RMSD : atom.MaxRMSD; } // get atom RMSF atom.RMSF = GetAverage(atom.RMSDs); // update atoms Min and Max RMSD MinAtomsRMSD = (atom.MinRMSD < MinAtomsRMSD) ? atom.MinRMSD : MinAtomsRMSD; MaxAtomsRMSD = (atom.MaxRMSD > MaxAtomsRMSD) ? atom.MaxRMSD : MaxAtomsRMSD; // update atoms Min and Max RMSF MinAtomsRMSF = (atom.RMSF < MinAtomsRMSF) ? atom.RMSF : MinAtomsRMSF; MaxAtomsRMSF = (atom.RMSF > MaxAtomsRMSF) ? atom.RMSF : MaxAtomsRMSF; } } 65
The method CookAtoms() calculates the RMSD of each atom at each step of the simulation. The first step of the simulation is chosen as the reference conformation. For each atom the minimum and maximum RMSD values are saved. The RMSF of each atom is calculated as an average on all RMSD values. Finally, the minimum and maximum RMSD values of all atoms on the entire simulation are saved. 5.3.3 Data Storage Computing all RMSD and RMSF values for each atom and residual at each step of the trajectory takes time, even for a relatively small simulation such as our case study. It could be argued that the sequential strategy adopted here is not the most efficient way. Certainly more performing results could be obtained by parallelizing the RMSD calculation, given the intrinsic independence of the computation. However, it was preferred to perform the calculation “offline” only once and to store the results in an external file, from which data is loaded when the application is started. We can now use the calculated RMSD and RMSF values to define the outline color of atoms and residues. 66
6 User Interface In this chapter we will describe the components of the graphical user interface (or UI) of our application and the features that it offers to the user. The UI is implemented with the Qt framework and consists of three main components. Figure 6.1 : user interface components ●central area : this is the OpenGL widget in which the molecular 3D models are rendered ●right panel : this widget is made up of different parts, some of which return information on the molecular simulation and others allow to configure the scene ●bottom bar : with this widget the user can move between the steps of the molecular simulation In the following sections we will analyze each component of the UI in detail. 6.1 Central Area As you can see in Figure 6.1, the area dedicated to rendering the scene takes up most of the application window. 67
This part of the UI consists of an OpenGL widget and, in addition to rendering the 3D molecular model of the current step in the simulation, allows the user to interact with the model through the use of the mouse. Using the mouse on the OpenGL widget, the user can perform the following actions. ●model rotating : moving the mouse when the left button is pressed, the user can rotate the molecular model in object-space, that is around its axes ●model panning : moving the mouse when the middle button is pressed, the user can move the molecular model around the scene in view-space ●camera orbiting : moving the mouse when the right button is pressed, the user can rotate the camera around the origin of the world-space ●camera zooming : scrolling the mouse wheel, the user can move the camera closer or further away from the origin of the world-space ●atom selection : hovering the mouse cursor over an atom of the molecular model, the user can retrieve its data We will take a look at how each of these actions is implemented in the application. The status of each mouse button is stored with a flag. When the user presses a mouse button, the respective flag is activated and the coordinates of the current mouse cursor are stored. When the user releases a previously pressed mouse button, the respective flag is deactivated. 6.1.1 Model Rotating The rotation of the molecular model, which is activated by moving the mouse when the left button is pressed, takes place in object-space, which means that the model is rotated around its own axes by updating the model matrix. Listing 6.1 : mouse move handler - model rotating void OpenGLWidget::mouseMoveEvent(QMouseEvent *event) { int x = event->pos().x(); int y = event->pos().y(); float factor = 0.005f; // model rotating if (mouse.MouseLeftButton) { float dx = factor * (x - mouse.lastX); float dy = factor * (y - mouse.lastY); QMatrix4x4 rotation; 68
rotation.rotate(qRadiansToDegrees(dx), camera.up); rotation.rotate(qRadiansToDegrees(dy), camera.right); QVector4D column = model.column(3); model.setColumn(3, {0.0f, 0.0f, 0.0f, 1.0f}); model = rotation * model; model.setColumn(3, column); mouse.lastX = x; mouse.lastY = y; } } Before applying the rotation, the molecular model is positioned at the center of the scene, zeroing (with the exception of the last element, which is set to one) the fourth column of the model matrix, which defines the translation of the model in world-space. 6.1.2 Model Panning The panning of the molecular model, which is activated by moving the mouse when the middle button is pressed, takes place in view-space on the plane facing the user. Applying the translation in view-space rather than in world-space, gives a more natural result for the user. The new position of the model will be the one that the user instinctively associates to the relative movement of the mouse. Listing 6.2 : mouse move handler - model panning void OpenGLWidget::mouseMoveEvent(QMouseEvent *event) { int x = event->pos().x(); int y = event->pos().y(); float factor = 0.005f; // model rotating // ... // model panning if (mouse.MouseMiddleButton) { factor *= 10.0f; float dx = factor * (x - mouse.lastX); float dy = factor * (mouse.lastY - y); QMatrix4x4 translation; translation.translate(dx * camera.right); translation.translate(dy * camera.up); model = translation * model; mouse.lastX = x; mouse.lastY = y; 69
factor *= 0.1f; } } Note how the translations are applied with respect to the up and right axes of the camera, which together with the front axis define the view-space coordinate system. 6.1.3 Camera Orbiting By moving the mouse when the right button is pressed, the user can move the camera on a circumference arc while it is still facing the center point of the scene. This means that the camera can not be moved freely, but it can only orbit around the origin of the world-space. Listing 6.3 : mouse move handler - camera orbiting void OpenGLWidget::mouseMoveEvent(QMouseEvent *event) { int x = event->pos().x(); int y = event->pos().y(); float factor = 0.005f; // model rotating // ... // model panning // ... // camera orbiting if (mouse.MouseRightButton) { float dx = factor * (x - mouse.lastX); float dy = factor * (y - mouse.lastY); camera.yaw += qRadiansToDegrees(dx); camera.pitch = qBound(-MAX_PITCH, camera.pitch + qRadiansToDegrees(dy), +MAX_PITCH); camera.eye = { cos(qDegreesToRadians(camera.yaw)) * cos(qDegreesToRadians(camera.pitch)), sin(qDegreesToRadians(camera.pitch)), sin(qDegreesToRadians(camera.yaw)) * cos(qDegreesToRadians(camera.pitch)), }; camera.eye = camera.radius * camera.eye.normalized(); camera.front = (camera.center - camera.eye).normalized(); camera.right = QVector3D::crossProduct(camera.front, {0.0f, 1.0f, 0.0f}).normalized(); camera.up = QVector3D::crossProduct(camera.right, camera.front).normalized(); mouse.lastX = x; mouse.lastY = y; 70
} } eye and center represent respectively the position of the camera and the center of the scene, both in world-space. Note how the camera rotations are applied around the up and right axes. The rotation angle around the right axis (also known as the pitch angle) is limited to values below 90 degrees to avoid to overturn the camera. After the camera's orbiting movement is calculated, the up, right and front axes that define the view-space are orthonormalized using the Gram-Schmidt process, so as to form once again an orthonormal triplet of vectors. 6.1.4 Atom Selection By hovering the mouse cursor over an atom of the molecular model, the user can retrieve its data, which are displayed in the right panel of the application window. In order to correctly detect the atom under the mouse cursor, we first add another color buffer output to the geometry step and connect it to a texture we called colour. The following listing update the previous impostor fragment shader, see Listing 2.3. Here we simply add the new color buffer named colour to the outputs and write it with the value received from the previous shader. Listing 6.4 : impostor fragment shader #version 450 layout (location = 0) out vec3 center; layout (location = 1) out vec3 normal; layout (location = 2) out vec3 albedo; layout (location = 3) out vec3 colour; struct Impostor { vec3 center; vec3 normal; }; void SetImpostor(out Impostor impostor); in Fragment { flat vec3 center; flat float radius; flat vec3 albedo; flat vec3 colour; smooth vec2 offset; } frag; uniform mat4 projection; 71
void main() { Impostor impostor; SetImpostor(impostor); // frag depth // ... center = impostor.center; normal = impostor.normal; albedo = frag.albedo; colour = frag.colour; } colour is calculated in the new impostor vertex shader, which replaces the version in Listing 2.1, and reaches unchanged the fragment shader above. The way we calculate colour is the same as seen in Listing 4.5 for the multi-silhouette colors. Listing 6.5 : impostor vertex shader #version 450 core layout (location = 0) in vec3 center; layout (location = 1) in float radius; layout (location = 2) in vec3 albedo; layout (location = 3) in vec2 number; out Vertex { vec3 center; float radius; vec3 albedo; vec3 colour; } vert; void main() { float AtomNumber = number[0]; uvec3 mask = uvec3(0x00FF0000, 0x0000FF00, 0x000000FF); uvec3 shift = uvec3(16, 8, 0); vec3 colour = ((uvec3(AtomNumber) & mask) >> shift) / 255.0f; vert.center = center; vert.radius = radius; vert.albedo = albedo; vert.colour = colour; } Therefore the texture colour contains the silhouette of the molecular model with each atom drawn with a unique color calculated based on its serial number. Let's now go back to the mouse move handler to see how atom selection is implemented. 72
Moreover, by observing how the values of RMSD and RMSF vary during the simulation, the user can understand or formulate hypotheses about the interactions between the molecules (or between parts of them). 7.3 Application Improvements The work presented in this report shows how a quantity that is typically represented with a dedicated 2D plot can be inserted and displayed in another context, allowing to aggregate different classes of information in a single image (in our case the spatial information given from the 3D model and the values of RMSD and RMSF), and at the same time preserving an easy understanding of each information class. We hope that our work will inspire future research in the field of molecular visualization and more generally in scientific and non-scientific visualization. We conclude this report with a list of possible ideas to improve and expand our application, many of which have remained out of the version presented here for timing reasons. ● We calculated RMSD and RMSF taking as reference conformation the first step of the simulation. It would be interesting to compare the values obtained with those calculated from other reference conformations, such as the average conformation of the trajectory or the native conformation of a protein. ● The RMSD for a single atom expresses the distance (in angstroms) from its reference position in its residue. Since for a conformation of a single element , the Equation 5.1 can be simplified in the following equation. This quantity represents the length of the atom displacement vector relative to its reference position. If we normalize this vector, we get the direction of the displacement. It would be interesting and graphically challenged to also display this information directly on a 3D molecular model. An idea could be to use a 2D or 3D glyph, for example in the shape of an arrow, positioned near the atom. ● It is mandatory to give the user the ability to "access" the hidden parts of a molecule, that is those atoms and residues occluded from other parts of the molecule itself or from other molecules. ● It would be useful to add another outline filter based on the distance of atoms and residues from the ligand, to recognize its interactions with the protein. 79
● It would definitely be better to show the atoms and residues information in a pop-up box next to the mouse cursor, making sure not to hide the selected object. 80
Bibliography [01] Pedro Hermosilla Casajús. Advanced Inspection Techniques for Molecular Simulations. 2017. [02] P. Vázquez, P. Hermosilla, V. Guallar, J. Estrada, A. Vinacua. Visual Analysis of Protein-Ligand Interactions. 2018. [03] René Fester Kratz. Molecular & Cell Biology For Dummies. 2009. [04] Rajendra Kumar Singh, A.S. Ethayathulla, Talat Jabeen, Sujata Sharma, Punit Kaur & Tej P. Singh. Aspirin induces its anti-inflammatory effects through its specific binding to phospholipase A2: Crystal structure of the complex formed between phospholipase A2 and aspirin at 1.9 Å resolution. 2005. [05] John Kessenich, Graham Sellers, Dave Shreiner. OpenGL Programming Guide: The Official Guide to Learning OpenGL (ninth edition). 2016. [06] Kouichi Matsuda, Rodger Lea. WebGL Programming Guide: Interactive 3D Graphics Programming with WebGL. 2013. [07] Joey de Vries. Learn OpenGL. 2017. [08] Jason L. McKesson. Learning Modern 3D Graphics Programming. 2012. [09] Eric Haines, Naty Hoffman, Tomas Möller. Real-Time Rendering (fourth edition). 2018. [10] Guillaume Lazar, Robin Penea. Mastering Qt 5. 2016. 81