FORTRAN Programming: A Basic Introduction (PART I)

In college, before video games, we would amuse our- selves by posing programming exercises. One of the favorites was to write the shortest self-reproducing pro- gram. Since this is an exercise divorced from reality, the usual vehicle was FORTRAN. Actually, FORTRAN was the language of choice for the same reason that three-legged races are popular.

Ken Thompson, Communications of the ACM. 27 (8), 761–763, 1984.

In December of last year, I celebrated the 30th anniversary of my Laurea in Chemistry dissertation. The starting of my thesis dissertation also signed my acquaintance to one of the grannies of the scientific programming languages, FORTRAN. Since then, I have used and (continue to) this language for my research activity by writing several thousands of lines of code. Therefore, I want to share some of my modest programming achievements using this language.

I will concisely introduce this captivating programming language in a series of articles. This is a primer on a programming language with much more to offer, especially in the new versions starting from the FORTRAN 90. Readers interested in deepening their knowledge in FORTRAN can find online many excellent tutorials and discussion groups, as well as plenty of excellent textbooks that have been written.

The FORTRAN language 

Fortran (FORmula TRANslation) language was introduced in 1957 and remains the language of choice for most scientific programming. The language was constantly restyled and updated (e.g. Fortran IV, Fortran 77). Recent improvements, recently introduced with the Fortran 90 and 95/2003, include several extensions in more modern languages (e.g. in the C language). Some of the most important features of Fortran 90/95 include recursive subroutines, dynamic storage allocation and pointers, user-defined data structures, modules, and the ability to manipulate entire arrays. Fortran 90 is compatible with Fortran 77 but not the other way around. However, the new Fortran language has evolved in a modern computer language by incorporating constructs from other languages.  

Continue reading

A Practical Introduction to the C Language for Computational Chemistry. Part 4

Controlling complexity is the essence of computer programming.

Brian W. Kernighan. in Software Tools (with PJ Plauger), 1976.

THE FUNCTIONS

A C program is a collection of functions. A C function is equivalent to the subroutine in FORTRAN or BASIC and procedures in PASCAL, PERL, or PYTHON programming languages. A portion of the program cannot be executed independently but only as part of another program. The function contains a specific algorithm or a stand-alone procedure. You have already used several library functions in your previous programs. Output commands for printing or reading files (such as printf(), openf()), mathematical functions (sqrt(), cos() are a library or intrinsic functions as well. Other library functions, we can classify as follows

  • Input/output functions. Input/output on the computer devices (e.g. output to the terminal, printer, hard disk, input from keyboard). It is usually used with #include <stdio.h>;
  • String manipulation functions. This library contains common operations on strings (e.g., concatenation, length, search, and extraction of substrings). It is usually used with #include <string.h>;
  • Mathematical functions. Mathematical calculations (e.g. trigonometrics functions, exponentiation, square root extraction). It is usually used with #include <math.h>;
  • Graphical functions. Function for graphics operations (open a graphical window and canvas) and drawing graphical primitives (e.g. points, line, curves).
  • Operative system control functions. Operation requiriing allocation of the computer resources or devices (e.g. date and time, allocation of memory). It is usually used with, for example, #include <time.h>;
  • Data conversion functions. Operation for data conversion (e.g. change characters type, ascii to integer). It is usually used with #include <ctype.h>;

To use these function, you need to use the precompiler instruction #include at the beginning of the program. The compiler use by deafult the standard library #include <stdlib.h>;

You can write your functions, and it is called user-defined functions. The use of function allows the program to structure and makes its organization and reading easier. C language is structured around the use of functions. The main() function is a function that contains calls to other functions, both intrinsic and user-defined functions.

Continue reading

NATALE 2022: Il Trigesimo Anniversario della mia Tesi di Laurea

Mais à l’instant même où la gorgée mêlée des miettes du gâteau toucha mon palais, je tressaillis, attentif à ce qui se passait d’extraordinaire en moi. Un plaisir délicieux m’avait envahi, isolé, sans la notion de sa cause.

PROUST Marcel, Du côté de chez Swann.

Ci sono ricordi del passato che rievocano nostalgicamente piacevoli momenti nella nostra vita. Questi preziosi tesori sono, a volte, sepolti nella nostra mente o, come nel mio caso, in quella di dimenticati cristalli di ferrite. Come per dolcetti di Proust, il ritrovamento di queste vestigie ci fa rivivere le emozioni di un passato lontano. I ricordi di cui parlo sono quelle della mia tesi di Laurea in Chimica che dopo essere stata scritta e discussa fu poi dimenticata nella memoria artificiale di obsoleti supporti magnetici degli albori della rivoluzione digitale.

Discussi la mia tesi di laurea il 23 dicembre dell’anno 1992, era l’ultima sessione di laurea di quell’anno. A quell’epoca, non esisteva ancora la laurea triennale che fu introdotta in conformità con il processo di Bologna dall’anno scolastico 2001/2002. Il corso di laurea in chimica era quinquennale e si entrava in tesi nell’ultimo anno. La tesi sperimentale comportava un lavoro originale che doveva essere discusso di fronte a una commissione di laurea composta dai professori del dipartimento, i relatori e i controrelatori (coloro che dovevano leggere la tesi e valutare il lavoro di ricerca e la sua presentazione). Pertanto, la tesi di Laurea (come del resto l’equivalente tesi magistrale) era un’esperienza molto importante nel condizionare la scelta dello studente nell’avviarsi o meno in una carriera accademica. Nel mio caso, la tesi segnò la scelta di intraprendere la carriera dello scienziato e educatore.  Scelta che, come gli academici goliardici delle prime università europee, mi ha portato a peregrinare lontano dalla mia alma mater nelle lontane Università del nord Europa. Di fatti, questa prefazione è stata abbozzata a Brema in Germania e completata a Lincoln nel Regno Unito, a pochi chilometri dalla città che diede i natali a Isacco Newton.

Continue reading

La Modellazione 3D della Forma delle Uova degli Uccelli per il Design di Oggetti Funzionali

La Pasqua di quest’anno è stata un’altra occasione per pubblicare il mio tradizionale articolo sulla matematica della forma delle uova degli uccelli. Quest’anno con l’aiuto dei miei figli, abbiamo creato il seguente Instructable educazionale:

https://www.instructables.com/Modelling-and-Designing-of-Bird-Eggs-for-3D-Printi/

Il progetto mira a mostrare come utilizzare un semplice modello matematico per generare la forma 3D di uova di uccelli reali aggiustandone i diversi parametri. I modelli di uova generati possono essere salvati come modello tridimensionale nel formato STL e poi stampati utilizzando una stampante ad estrusione di filamento plastico. L’uovo stampato può essere dipinto o modificato utilizzando un programma di modellistica 3D (per esempio MeshLab, sviluppato in Italy dal Visual Computing Lab of CNR-ISTI) per aggiungere funzionalità per gadget o giocattoli nella forma di uovo. Viene spiegato in dettaglio un esempio di come creare un uovo illuminato internamente con un LED multicolore.

Più recentemente, per divertimento, ho pubblicato sempre su sito Instrutables un altro esempio usando lo stesso approccio:

https://www.instructables.com/The-Eggyrint/

Inoltre, l’argomento della modellazione della forma delle uova è stato trattato in articoli precedenti e il lettore interessato può integrare le informazioni nel progetto Instructable con quelle fornite nei seguenti articoli:

https://wordpress.com/post/daniloroccatano.blog/3792

https://wordpress.com/post/daniloroccatano.blog/5171

https://wordpress.com/post/daniloroccatano.blog/6760

Nell’Instructable dviene fornito un programma in C++ che dà la possibilità di generare le forma 3D delle uova e salvarle in STL. Può essere utilizzato per la ricerca, l’insegnamento e il divertimento.

Spero che il nostro progetto vi piaccia e commenti e suggerimenti costruttivi sono sempre i benvenuti!

Exploring the Lotus Effect using Candle Soot

I recently published an new Instructable that is the results of some home experiments that I did some time ago (see also my previous article).

https://www.instructables.com/EXPLORING-THE-LOTUS-EFFECT-USING-CANDLE-SOOT/

It shows how to prepare these simple surfaces and make some interesting observations with them. Like the previous two Instructables, my family help me a lot in preparing it in the very short time of one day. So a big thank you to my wife, Francesco, and, in particular, to Leonardo.

Hydrophobic and super-hydrophobic surfaces are ubiquitous in the natural world. You do not need to search much to find good examples: just walk out in your garden after a light rain and look at the plenty of weed leaves pearly decorated by water droplets. If you have an ornamental pond, you may have even the chance to see floating better examples of plants having a super-hydrophobic surface. Notably, wettability in Nature is present in a different form that subtle differences in the function and effect on the water droplets. Plant leaves need to keep their surfaces clean for light-harvesting efficiency. A water repellent leaves let water drops roll over its surface and mechanically remove dust particles. This effect was first noted on leaves of the Lotus plant, and for that reason, it is also called the Lotus effect.

Several novel technological materials exploit the properties of super-hydrophobic. For example, in your kitchen, Teflon pans are used to avoid sticking food residuals and therefore easily cleaned. Your car windows are teated to let the water easily roll over the surface. 

Candle soot is an artificial material that is easy to produce and can be used to demonstrate some of the properties of the (super)-hydrophobic surface existing in nature.

The Mighty Roto-Microscope

I am happy to announce our second Instructable project. Like the first one, it was a long-standing idea that was rolling in my mind for a long time. The current limited travelling mobility due to the COVID offered more time to develop this idea during my vacation. In a joyful collaboration with my son Leonardo, we managed to realize this useful device in a very short time.

This project aimed to develop a device that integrated with a cheap USB microscope allows taking 3D pictures of small samples. The project is meant to be an education STEM activity to learn using Arduino, 3D image reconstruction, and 3D printing by creating a useful piece of equipment for doing some exciting science activity. Like my previous project, it is also a moment to share good and educative time with my family and in particular, my elder son Leonardo that helped me in creating this instructable and evaluating the device as an enthusiastic STEM student. This time, also my lovely wife helps me to make a video of the assembly of the equipment!

The roto-microscope allows controlling the position of a simple USB microscope around the sample. This allows to take accurate pictures from different angles and not just from the top as in the traditional microscopes. This is not a new idea as there are professional microscopes. However, this device means to be affordable for a student and still provides some similar results and a lot of fun in building it. Other similar and excellent OpenSource projects are available (see, for example, the Ladybug microscope, the Lego microscope, and the OpenScan project), our project adds an additional option and I hope that you enjoy making it as we did!

If you find it an interesting device then instructions on how to build it are on our Instructable.

The Magic Sand Slicer

We have published for the first time a project on Instructables: a website specialised in publishing interesting DIY projects by an effervescent community of makers and educators.

The project is called the Magic-Sand Slicer and it is an education project initially conceived as a STEM activity to learn using Arduino, a 3D printer, and some exciting science. It is also a collaboration with my son Leonardo who helped me in evaluating the device as a STEM student. We have learned a lot together, and we want to share the results of this long journey. This project aims to create a device that automatically makes sections of a cylinder of easy-to-cut coloured material. That can be used for practising 3D image reconstruction of the coloured blogs hidden in the column. The so-called Magic-Sand (c), also known with other trademarks names, becomes suitable for this experiment.
What is the point of making pictures of thin layers of sand and then reconstructing it digitally? Is it just for the fun of it? It varies on who is using it. However, students and teachers from different disciplines (e.g. geology, biology, medical) can find it a helpful education device to practice with image reconstruction from the serial sections. It could also be of interest to a geologist interested in sedimentary material plasticity to study rock and the secrets it beholds, or to a process, engineering to emulate the packing of fine granular materials. Finally, an artist can make a fantastic program of unravelling magic forms generated by packing coloured sand. 

I was surprised that the project got so much interest in a very short time and I thank the Instructable community for their nice welcome! If you like to know more about the project (and try it!) then you can read our instructable here.

I also just realized that the Instructable was reviewed on the Arduino blog site by the Arduino team!

Seminar Series: Molecular Dynamics Simulation of Biomolecules

In this new series, I will post slides of seminars or lessons that I have delivered in the past years. Some of the reported information is updated, but still helpful. In some cases, I have added descriptions of the slide contents or references to other articles or the original paper where I describe my research results.
I hope you like the presentation, and remember to add your feedback and subscribe to have email notifications about my new blog posts.

In 1648, Isaac Newton published his first edition of the Principia Mathematica, one of the greatest scientific masterpieces of all time. On page 12 of this magnum opus, the famous three laws that bear his name and from which classical mathematical physics evolved are enunciated. More than 350 years after that publication, the same laws formulated to explain the motion of stars and planets remain valuable for us when trying to simplify the description of the atomic world. In the first decades of the last century, the birth of quantum mechanics marked the beginning of the detailed description of atomic physics. The equation of Schrödinger, to the same extent as Newton’s equations, allowed for the mathematically elegant formulation of the shining theoretical intuitions and the experimental data accumulated in the previous decades. Although this equation could be used in principle to describe any molecular system’s physicochemical behaviour, it is impossible to resolve analytically when the number of electrons is more than two. The invention of electronic computers after World War II facilitated the numerical solution of this equation for polyatomic systems. However, despite the continuous and rapid development of computer performance, the ab-initio quantum-mechanical approach to describe static and dynamic properties of molecules containing hundreds or even thousands of atoms, as for biological macromolecules, is still far from becoming a standard computational tool. This approach requires many calculations that can be proportional to N^{3-5}, where N is the total number of electrons in the system. It was clear that a reduction, using ad hoc approximations, of the description of the dynamic behaviour of atoms using a classic physics model would be necessary to overcome this problem. In the classical representation, the electrons on the atoms are not explicitly considered, but their mean-field effect is taken into account. Alder and Wainwright performed the first simulation of an atomic fluid using this approximation approximately 63 years ago (1957). They developed and used the method to study simple fluids by means of a model representing atoms as discs and rigid spheres. These first pioneer studies mark the birth of the classical molecular dynamics (MD) simulation technique. The successive use of more realistic interaction potentials has allowed obtaining simulations comparable to experimental data, showing that MD can be a valuable tool for surveying the microscopical properties of physical systems. The first simulations of this type were carried out by Rahman and Verlet (1964): in these simulations, a Lennard-Jones-type potential was used to describe the atomic interactions of argon in the liquid state. Another significant hallmark in this field was the simulation of the first protein (the bovine pancreatic trypsin inhibitor) by McCammon and Karplus in 1977. In the following years, the success obtained in reproducing structural properties of proteins and other macromolecules led to a great spread of the MD within structural biology studies. The continuous increase of computer power and improvement of programming languages has concurred with further refinement of the technique. Its application was progressively expanded to more complex biological systems comprising large protein complexes in a membrane environment. In this way, MD is becoming a powerful and flexible tool with applications in disparate fields, from structural biology to material science.

Continue reading

1971-2021: The Molecular Dynamics of Liquid Water turns Fifty

This year signs a landmark in the history of the molecular dynamics (MD) simulation method. Half a century ago 1971, Aneesur Rhaman and Frank H. Stillinger [1] published a pioneering work on the MD simulation of liquid water in the Journal of Chemical Physics. The journal received the article on May the 6th, 1971, and accepted it in October. Just seven years before (1964), the physicist A. Rahman (24 August 1927 – 6 June 1987) pioneered the computational method of MD when he published the first MD simulation study of liquid Argon [2]. The 1971 article is also the first MD study of a molecule in a condensed phase. It signed an important milestones water models are the most studied and used molecular models in MD simulations.

However, despite its structural simplicity, after 50 years of intense study, a perfect model for MD simulation is not yet available. By a perfect model, I mean one capable of computationally conveniently reproducing all the properties of water molecules in the range of possible applications. A water model needs to balance its computational simplicity required to keep computational costs for the simulations of large macromolecules in solution limited, and the accuracy to reproduce the physical chemistry properties accurately. For the most used but still 40-year-old models, this compromise was the equivalent of the inconveniently short blanket: pulling on one side would fit some properties but leave others loose. However, the continuous availability of inexpensive computer power and the advancements in simulation algorithms have allowed for significant progress in developing more accurate and efficient water models. In fact, several excellent models have been proposed since the R&S publication that can reproduce very well properties at 298 K or in a limited range of temperatures. In an updated but comprehensive article written 30 years later in the R&S paper, Guillot reported more than 100 proposed classic models for MD or Monte Carlo simulations published up to then [3]. Nineteen years after the publication of Guillot’s review, new and more sophisticated models have been proposed; nevertheless, the most used ones continue to bring the legacy of the R&S model.

In the late 1970s and early 1980s, the first molecular dynamics simulations of water were conducted using simplified models. These models represented water molecules as spheres interacting via pairwise Lennard-Jones potentials, capturing the intermolecular forces between the molecules. These developments in modeling water from molecular dynamics simulations have contributed significantly to our understanding of water’s structure, thermodynamics, and dynamics at the molecular level. They have provided insights into a wide range of phenomena, including solvation, hydrophobic interactions, phase transitions, and biomolecular interactions involving water molecules. In the following list, there is a summary of commonly used models for simulating water in molecular dynamics simulations.

  1. The SPC (Simple Point Charge) and SPC/E (Extended) developed by Prof. HJC Berendsen and collaborators a the University of Groningen (The Netherlands) [4] are widely used water models in molecular dynamics simulations. These models consider three atoms per water molecule but have different parameters for the Lennard-Jones potential and partial charges. The SPC/E model, in particular, has successfully reproduced various water properties, including the density and structure of liquid water.
    • Lennard-Jones Potential: The SPC models also utilize the Lennard-Jones potential to describe the van der Waals interactions between water molecules. The parameters are adjusted to reproduce various properties of water, including the radial distribution function.
    • Charges: The SPC models assign partial charges to the oxygen and hydrogen atoms in a manner that reproduces the dipole moment and electric field properties of water. These charges are carefully chosen to ensure an accurate representation of the water molecule.
  2. The TIP3P (Transferable Intermolecular Potential 3 Points) model developed by Prof. W. Jorgensen and collaborators at Yale University (USA) [4] is another widely-used water model. As the SPC model, it represents water molecules as three atoms: two hydrogen atoms and one oxygen atom. The oxygen atom has a partial negative charge, while each hydrogen atom has a partial positive charge. The model also includes harmonic bond stretching and angle bending terms to describe the covalent bonds and bond angles within water molecules.
    • Bond Stretching: The TIP3P model assumes harmonic bond stretching between oxygen and hydrogen atoms. The equilibrium bond length is typically set to 0.9572 Å, and the force constant represents the stiffness of the bond.
    • Angle Bending: The TIP3P model employs harmonic angle bending terms to describe the HOH angle. The equilibrium angle is typically set to 104.52 degrees, corresponding to the tetrahedral geometry of water.
    • Lennard-Jones Potential: The model uses the Lennard-Jones potential to describe the van der Waals interactions between water molecules. The parameters for the potential are chosen to reproduce the experimentally observed properties of water, such as the density and vaporization enthalpy.
    • Charges: The oxygen atom in the TIP3P model carries a partial negative charge, while each hydrogen atom has a partial positive charge. The charges are usually chosen to reproduce the dipole moment and electric field properties of water.
  3. The TIP4P model extends the TIP3P model by explicitly including a virtual site, referred to as the “dummy” or “massless” site, in addition to the three atoms. This dummy site is located along the HOH angle bisector and represents the lone pair of electrons on the oxygen atom. The TIP4P model improves the description of water properties, particularly the hydrogen bonding behavior.
    • Dummy Sites: The TIP4P model introduces a virtual site, referred to as the dummy or massless site, to represent the lone pair of electrons on the oxygen atom. This allows for a more accurate representation of the hydrogen bonding behavior in water.
    • Electrostatics: The TIP4P model includes a positive charge located on the dummy site, which balances the negative charge on the oxygen atom. This ensures that the model reproduces the correct dipole moment of water.
  4. Flexible Models: While rigid water models, such as TIP3P and SPC/E, assume fixed bond lengths and bond angles, flexible models introduce additional degrees of freedom by allowing parameter variations. Flexible water models, such as TIP5P and TIP4P/2005, consider the anharmonicity of bond stretching and angle bending, providing a more accurate description of water’s vibrational behavior.
    • Anharmonicity: Flexible water models, such as TIP4P/2005 and TIP5P, introduce anharmonic terms to account for the deviations from the harmonic behavior of bond stretching and angle bending. This allows for a more accurate representation of water’s vibrational properties.
    • Improved Parameters: Flexible models often incorporate refined parameters to better reproduce experimental data, such as vibrational spectra and thermodynamic properties, beyond what can be achieved with rigid models.
  5. Polarizable Models: Classical force fields typically assume fixed atomic charges on water molecules. However, water is a polar molecule whose charge distribution changes in response to its local environment. Polarizable models have been developed to capture the dynamic nature of water’s charge distribution. Polarizable force fields, such as the AMOEBA (Atomic Multipole Optimized Energetics for Biomolecular Simulation) force field, allow the partial charges on water molecules to vary with the atomic positions and local electric fields.
    • Drude Oscillators: Polarizable models, such as the AMOEBA force field, employ Drude oscillators to represent the fluctuating charge distributions in water. A Drude oscillator consists of a heavy atom (representing the oxygen atom) and a lighter particle (representing the hydrogen atom) connected by a harmonic bond.
    • Atomic Multipole Moments: Polarizable models use atomic multipole moments, including dipoles, quadrupoles, and higher-order moments, to describe the charge distribution of water molecules. The moments are allowed to vary with the positions of the atoms, capturing the dynamic nature of water’s charge distribution.

These model are the most communely used water models used in molecular dynamics simulations an din particular in simulation of biomolecular systems. The choice of model depends on the research question and the desired level of accuracy required for the simulation.

REFERENCES

  1. Rahman, A. and Stillinger, F.H., 1971. Molecular dynamics study of liquid water. The Journal of Chemical Physics55(7), pp.3336-3359.
  2. A. Rahman (1964). “Correlations in the Motion of Atoms in Liquid Argon”. Physical Review136: A405-A411.
  3. Guillot, B., 2002. A reappraisal of what we have learnt during three decades of computer simulations on water. Journal of molecular liquids101(1-3), pp.219-260.
  4. H. J. C. Berendsen, J. R. Grigera and T. P. Straatsma, The missing term in effective pair potentials, Journal of Physical Chemistry 91 (1987) 6269-6271.
  5. Jorgensen, W.L., Chandrasekhar, J., Madura, J.D., Impey, R.W. and Klein, M.L., 1983. Comparison of simple potential functions for simulating liquid water. The Journal of chemical physics79(2), pp.926-935.

A Practical Introduction to the C Language for Computational Chemistry. Part 3

Sphere. From Space, from Space, Sir: whence else?

Square. Pardon me, my Lord, but is not your Lordship already in Space, your Lordship and his humble servant, even at this moment?

Sphere. Pooh! what do you know of Space? Define Space.

Square. Space, my Lord, is height and breadth indefinitely prolonged.

Sphere. Exactly: you see you do not even know what Space is. You think it is of Two Dimensions only; but I have come to announce to you a Third — height, breadth, and length.

Square. Your Lordship is pleased to be merry. We also speak of length and height, or breadth and thickness, thus denoting Two Dimensions by four names.

Sphere. But I mean not only three names, but Three Dimensions.

Adapted from: 
Flatland: A romance of many dimensions by Edwin A. Abbott

ADVENTURE IN SPACELAND

In part 2 of this tutorial, we have learned how to use arrays and how to read atomic coordinates from a file. In the appendix, you can find an example of the solution to the exercises given in the previous tutorial.

In this third part, we are going to learn how to generate three-dimensional coordination of atoms in a cubic crystal lattice and how to calculate non-bonded molecular potential and the force acting among them.

Continue reading