Unix C-Shell Programming Notes: Part II

This is the second part of this series of notes on the advanced use of the Unix shell. The first part can be accessed by following the link. In this second part, I will show some advanced examples I wrote for my research activity.

1. CHANGE FILE NAMES SCRIPT

I wrote this script to change the default names of the files generated during a molecular dynamics simulation by the program mdrun in the early version of the GROMACS package for MD simulation. GROMACS is a widely used software package for simulating the behavior of molecules and molecular systems. Although it is now possible to define the root name of the files upon running the simulation program, this script can still be helpful. The script is written in the C Shell (csh) .

 #! /bin/csh -ef
#
# Change the names of the default  output Files
# generated by the program GROMACS mdrun program
#
# (c) Danilo Roccatano
#######
#
#Define the radix of the files name
#
setenv RADIX  'EH_min'

if (-e md.log) then
   if (  -e $RADIX'.log')  then 
     echo Warning $RADIX'.log' exist
   else
     mv md.log            $RADIX'.log'
   endif
else
   echo The md.log file does not exist!
endif

if (-e ener.ene) then
  if (  -e 'e'$RADIX'.ene') then 
   echo Warning 'e'$RADIX'.ene' exist
  else
    mv ener.ene       'e'$RADIX'.ene'
  endif
else
  echo The energy file does not exist
endif

if (-e ctraj.xtc ) then
  if ( -e 'r'$RADIX'.xtc') then 
    echo Warning 'r'$RADIX'.xtc' exist
  else
    mv ctraj.xtc      'r'$RADIX'.xtc'
  endif
else
  echo The compressed trajectory file does not exist
endif

if (-e confout.gro) then
  if ( -e 'x'$RADIX'.gro') then 
    echo Warning 'x'$RADIX'.gro' exist
  else
    mv confout.gro    'x'$RADIX'.gro'
  endif
else
  echo The final configuration file does not exit.
  echo Probably your simulation crashed before the end 
endif
 
exit
Continue reading

The shell of a snail and its 3D Digitization with the Structure-from-Motion algorithm

To grass, or leaf, or fruit, or wall,
The snail sticks close, nor fears to fall,
As if he grew there, house and all
                                                 Together.
Within that house secure he hides,
When danger imminent betides
Of storm, or other harm besides
                                                Of weather.
Give but his horns the slightest touch,
His self-collecting power is such,
He shrinks into his house, with much
                                                Displeasure.
Where’er he dwells, he dwells alone,
Except himself has chattels none,
Well satisfied to be his own
                                             Whole treasure.
Thus, hermit-like, his life he leads,
Nor partner of his banquet needs,
And if he meets one, only feeds
                                                The faster.
Who seeks him must be worse than blind,
(He and his house are so combin’d)
If, finding it, he fails to find
                                                Its master.

The Snail by William Cowper (1731-1800)

Introduzione

The beautiful poetry of Cowper expresses the pleasant charm that this small inhabitant of our gardens instills. I have always been fascinated by this gastropod, to the point that it was one of my favorite invertebrates for my amateur naturalistic observations. Furthermore, I still recall with pleasure and nostalgia the collection of those called ‘ciammaruchelle‘ in the Ciociaro dialect, which are small snails. These were gathered by the handful in the wheat fields after the harvest. It was one of the various culinary traditions that involved my entire family every year and were carried out with constant devotion. The collection was organized with careful timing, locations, and weather conditions to increase the likelihood of success. Usually, we would return home with a rich and tasty haul, but not without difficulties, as the little snails would climb onto the thistle plants (Cynara cardunculus L., 1753) where they would hide among the thorns to protect themselves from predators. Unfortunately for them, the predator Homo Sapiens Sapiens Frusinenses, equipped with keen eyesight and great tenacity, did not easily give up its prey!

The collected species was a variety of the snail Eobania vermiculata, commonly known as “rigatella,” which is very common in Mediterranean regions. The snails were gathered in woven baskets and, once back home, they were enclosed in circular cages with fine mesh walls for several days to purge their intestines. They were then cooked for a few hours in a tomato base spiced with mint (Clinopodium nepeta), following an ancient recipe. The dish was consumed with fresh or, even better, baked bread to make it crispy. It was a vibrant celebration of scents, flavors, and colors, with the sound of slurping as they tried to empty the succulent contents of their shells. A delicate feast of aromas and flavors: the scent of tomato infused with snail meat and mint, combined with the red color of the snails’ shells adorned with white-brown stripes.

Continue reading

Exploring Photoelasticity of Plastic Materials with the MLT

In the recent Instructable project Introducing the Mini LED Table: Compact, Affordable, and Enhanced With Computer Vision, we presented an inexpensive, compact, and easy-to-build Mini LED Table (MLT) that is a simple and cost-effective project for a STEM activity and a tool for educational purposes. Among other applications, The device can open doors for students and educators to explore the fascinating world of material science and engineering by providing an affordable and compact solution.

In a new project on the Instructables website, I have extended the capability of the MLT by adding a device that uses polarizer filters in front of the Picamera, which will provide the capability to visualize the internal stress distribution within transparent materials. These stress patterns due to the birefringence of some materials are paramount for engineering analysis. They are significant in determining various substances’ mechanical behavior and structural integrity. 

To address this possible application, we will explain how to add a polarizer to the MLT, which is already equipped with computer vision capabilities. In short, the accessory consists in adding a removable polarizer filter onto the Mini LED Table and incorporating another polarizer near the Picamera mounted on a rotatable 3D support enabling the visualization and analysis of colorful stress patterns that arise in transparent plastic and other materials exhibiting photoelastic effects.

By harnessing the capabilities of MLT, polarized light, and computer vision integration, we want to provide educators and students with a powerful tool for visualizing and understanding the intricate stress patterns present in transparent plastics and other photoelastic materials.

Before delving into the details of the project, let us provide a brief overview of photoelasticity and its significance in engineering. Photoelasticity is a powerful technique used to analyze the stress distribution in materials. It is based on the principle that the refractive index of a photoelastic material changes with applied stress. By passing polarized light through a stressed material and analyzing the resulting fringe patterns, engineers can gain valuable insights into the stress distribution and behavior of the material under various loading conditions.

Photoelasticity finds extensive applications in engineering. It aids in designing and analyzing components subjected to complex stress states, such as structural components, machine parts, and even optical devices. By visualizing stress concentrations, engineers can optimize designs, identify potential failure points, and enhance various systems’ overall reliability and performance. Additionally, photoelasticity plays a crucial role in material testing, prototype validation, and quality control processes, enabling engineers to ensure the integrity and safety of critical components.

Unveiling Stardust on Your Rooftop: a Magnetic Microparticle Sorter and Spotter

With the help of my lovely assistant, we have just published on Instructables another STEM project. This time, it was inspired by the reading of the classic Comets by Carl Sagan and the upcoming period of significant meteor shower events of the year:

  1. Perseids: The Perseids is one of the most popular and reliable meteor showers, occurring annually in mid-August. It is associated with the comet Swift-Tuttle and gets its name from the constellation Perseus, from where the meteors appear to radiate. The Perseids are known for their fast and bright meteors, often leaving long-lasting trails in the sky. They are visible from both hemispheres, but the best viewing opportunities are typically in the northern hemisphere. During its peak, the Perseids can produce up to 60 to 100 meteors per hour.
  2. Geminids: The Geminids meteor shower takes place every December and is considered one of the most reliable and prolific meteor showers of the year. The Geminids are associated with the asteroid 3200 Phaethon and appear to radiate from the constellation Gemini, hence their name. Unlike many other meteor showers, the Geminids can be observed from both the northern and southern hemispheres. They are known for producing bright, colorful meteors and can reach a peak rate of 120 to 160 meteors per hour, making them a spectacular astronomical event.
  3. Quadrantids: The Quadrantids meteor shower occurs annually in early January and is known for its brief but intense display of meteors. The radiant point of the Quadrantids lies in the defunct constellation Quadrans Muralis, which is no longer recognized as a constellation. However, the meteors can be seen anywhere in the sky. The Quadrantids are associated with the asteroid 2003 EH1, which is believed to be an extinct comet. The peak of the Quadrantids is relatively short, usually lasting only a few hours, but it can produce a high meteor rate of around 60 to 200 meteors per hour.

Who won’t be thrilled by capturing a piece of outer space right in your hands? However, you might think, “But I don’t have the necessary equipment!” Fear not, as luck would have it, you’ve stumbled upon this instructable that will guide you in creating your own Micrometeorite Separator and Spotter (MSS).

Sure, it’s true that if a magnificent carbonaceous chondrite were to gracefully land right in front of your doorstep, you wouldn’t need any equipment. However, chances are high that tiny fragments of meteorites, resembling specks of falling stars, are scattered on your rooftop, waiting to be discovered. Countless websites and YouTube videos share fascinating tales of those who have embarked on this labor of love, showcasing the patience and dedication required to uncover these elusive cosmic treasures. The meteorites you’re after are microscopic, so your search will focus on distinguishing them from the terrestrial dust and debris that pervade our surroundings.

Fortunately, a small and mighty Neodymium magnet proves invaluable in this pursuit, especially for isolating metallic meteorites. Yet, be prepared for a challenging quest, as finding these little celestial gems is no easy task. However, the rewards of discovering even a single meteorite are genuinely remarkable.

We have recently published an Instructable project presenting a simple yet effective device to aid you in your meteorite discovery journey. This device remains compact and portable that can be used with a digital microscope or fitted under a stereomicroscope and the wonders they reveal.

So, get ready to embark on an extraordinary adventure and immerse yourself in the captivating world of meteorite hunting. With the Micrometeorite Separator and Spotter (MSS) at your disposal, you’ll be equipped to explore the heavens and unveil the hidden secrets within the depths of our vast universe.

Happy hunting, and do not forget to like this post and the Instructable !

Introducing the Mini LED Table: Compact, Affordable, and Enhanced With Computer Vision

How many times have you found yourself looking at your cake decorations, wondering how many pearls are left in the box? Have you ever tried to count how many mustard, basil or pepper plants you can grow with the seeds you have in stock? And what about the urge to know the exact number of millimeter stainless steel balls you recently purchased at your favorite DIY store?
For this purpose, some scrap cardboard, a strip of LEDs, and a Raspberry Pi Zero with its tiny chamber might help satisfy your mathematical desire to enumerate these tiny objects.
In a recent article on Instructables, we detailed the eye-opening experience with all the construction details of a compact, battery-powered, easy-to-use, and affordable mini LED table (MTL). In addition to the hardware, an open source software based on OpenCv is also strengthened for the acquisition and simple processing of the images of the objects on the MTL for possible applications.

Continue reading

Il Mini Tavolo LED: Illumina l’Universo dei Dettagli Nascosti!

Quante volte ti sei trovato a guardare le tue decorazioni per i dolci, chiedendoti quante perle rimangono nella scatola? Hai mai provato a contare quante piante di senape, basilico o pepe puoi coltivare con i semi che hai in magazzino? E cosa dire dell’urgenza di conoscere il numero esatto delle sfere in acciaio inossidabile da un millimetro che hai recentemente acquistato nel tuo negozio di fai-da-te preferito?
Per questo scopo, un po’ di cartone di recupero, una striscia di LED e un Raspberry Pi Zero con la sua piccola camera potrebbero aiutare a soddisfare il tuo desiderio matematico di enumerare questi oggetti minuscoli.
In un recente articolo su Instructables, abbiamo descritto l’ illuminante esperienza con tutti i dettagli costruttivi di un mini tavolo LED (MTL) compatto, alimentato a batteria, facile da usare e conveniente. Oltre all’hardware viene fortito anche un software opensource basato su OpenCv per l’acquisizione e la semplice elaborazione delle immagini degli oggetti sul MTL per possibili applicazioni.

Caratteristiche principali del progetto:

  • Un tavolo a LED compatto, portatile ed economico realizzato con un foglio di cartone di imballaggio e una striscia di LED bianchi.
  • Può essere alimentato alimentato da una batteria elettrica e ha un dimmer per regolare l’intensità della luce.
  • È dotato di una camera Raspberry Pi per acquisire le immagini (con la distanza focale modificata per mettere a fuoco oggetti vicini).
  • Il software in Python fornito come OpenSource consente di controllare la camera e di elaborare le immagini per contare gli oggetti sul tavolo.

L’articolo originale (in inglese) del MTL si trova sul mio sito Instructables.

L’articolo contiene le istruzioni dettagliate e i file STL per la stampa 3D dei componenti necessari. Il progetto è stato realizzato in collaborazione con i miei due cari collaboratori, in particolare Leonardo. È un progetto semplice e accessibile che può essere utilizzato anche a scopo educativo per imparare concetti di costruzione, elettronica, ottica e programmazione.

Introduzione alla programmazione in Python (III)

Puntate precedenti:

  1. Introduzione alla programmazione in Python (I)
  2. Introduzione alla programmazione in Python (II)

Siamo giunti alla terza parte di questa serie dove vedremo come usare le istruzion condizionali per il controllo del flusso del programma.

DIAGRAMMI DI FLUSSO

Per una descrizione più semplice e intuitiva dei commandi per il controllo del programma, verranno utilizzati diagrammi di flusso. Un diagramma di flusso è un tipo di diagramma (grafico o simbolico) che rappresenta un algoritmo o un processo. Ogni passo nel processo è rappresentato da un simbolo diverso e contiene una breve descrizione del passo del processo. I simboli del diagramma di flusso sono collegati tra loro con frecce che mostrano la direzione del flusso del processo. Un diagramma di flusso mostra tipicamente il flusso dei dati in un processo, dettagliando le operazioni/passi in un formato pittorico che è più facile da capire rispetto alla lettura di un formato testuale.

Continue reading

Retro programming Nostalgia IV: Acid/Base Equilibrium and Titration (Part I)

The motivation for this article stems from my interest in retro-computing connected, on the one hand, to the re-evaluation of my youthful explorations of scientific computing in the BASIC language and, on the other, to the popularity they are having in the amateur sector in recent years and of teaching, single-board microcomputers (single-board computers, such as, for example, the Raspberry Pi). These small computers have considerably more power at a much lower cost than the microcomputers of the 80s. This made it possible to emulate the operating systems of the legendary Commodore home computer models and the MSX extension on these computers.

Therefore, a renewed interest in the BASIC programming language is also occurring. This interest in retro-computing reflects the nostalgia for the great emotions that the development of consumer information technology brought to my generation in the 1970s and 1980s. I remember being so struck by the creativity in using and programming these microcomputers that it redirected my scientific interests and academic career. I have written in other articles about my first programming adventures with Commodore home computers and MSX systems in the late 80s and early 90s and my rediscoveries in computer archaeology. Among the exhibits, I found a small program I used to study acid/base titrations developed in MSX BASIC. Therefore, I took the opportunity to write notes on acid-base balance and titration and thus provide a restored and improved version of my program to students passionate about programming and grappling with this important concept of analytical chemistry.

Continue reading

Easter 2023: Superquadric and Squared-Eggs

First there was the Great Cosmic Egg.

Huai-nan Tzu, China 100 BCE 

Another Easter is arriving, and here I am for a new article on old friends: the Eggs. In my blog for Easter 2021, I mentioned squared eggs paraphrasing a sentence attributed to the extraordinary jeweler Peter Carl Fabergé:” This year, your Highness, we will be featuring square eggs.” A hen is unlikely to make a cubic-shaped egg, but we can still transform a cooked egg to get the cuboid shape. If you look for squared eggs on the internet, you will find a tool called the egg cuber that does the magic. Unfortunately, I could not yet try one, but it seems to be doing an excellent job from the reviews. The shape of the egg is not a perfect cube but a cuboid, namely a cube with rounded corners. In my previous article, I anticipated that this shape could be obtained using the superquadric function. Curiouser and curiouser! In this article, I will give a bit of mathematical background and even a source code to play with such a function as my Easter Bunny gift.

Continue reading

FORTRAN Programming (PART III): NUMERICAL DIFFERENTIATION

In the fall of 1972 President Nixon announced that the rate of increase of inflation was decreasing. This was the first time a sitting president used the third derivative to advance his case for reelection.

Hugo Rossi. Mathematics Is an Edifice, Not a Toolbox, Notices of the AMS, v. 43, no. 10, October 1996.

Welcome to the third part is the third part of the essential introduction to the FORTRAN programming series. In this part, we will introduce the use of functions and subroutines to structure the programs. Then we use them to make a program to calculate numerical derivatives of mathematical functions.

Continue reading