MATLAB figures, part 2

Here is a quick update on the comments I have previously given to obtain nice figures in MATLAB. As you probably know, two of the most common plagues during export are font inconsistency (usually microscopic ticks and labels) and bad export quality for raster (PNG, JPG) formats. I will also give a small tip at the end to improve readability and general aesthetics for markers. Continue reading →

Moving to London !

My contract in Lyon has ended on January 31st. Therefore, I am really excited to join the Garbin Lab at Imperial College in London ! We will study here the non-linear properties of soft materials through bubble excitation.

And quite soon, we will submit (with the people from Lyon) our experimental paper on peculiar spatio-temporal patterns observed in shear-thickening, cornstarch suspensions.

Spatio-temporal plot of the tangential velocity field (averaged in the gradient direction), plotted as a function of the vorticity direction (z) and time in a 41% cornstarch suspension solicited above the critical (DST) stress.

 

Shear-thickening

Soft materials and liquids

Soft materials (gels, elastomers, pastes, foams, suspensions, liquids ...) are generally from a particular point of view - the material is more liquid, or more solid - chosen by the physicist. In this article, we will focus on the "liquid" aspects of a very specific class of soft materials.

The simplest liquids are Newtonian; this means that they are fully characterized by a scalar quantity called viscosity  \eta . This viscosity opposes the shear of the fluid, which is defined as a progressive transformation of the elementary fluid elements (bricks) in rhomboedral shapes (parallelograms in three dimensions, say):

Shearing a slab of fluid (of thickness e ) at a shear rate  \dot\gamma

Shearing the fluid at a specific rate  \dot \gamma necessitates to apply forces (purple arrows above) on the boundaries of the elementary surface. The applied, normalized force  \tau , is proportional to  \dot\gamma, providing a definition for  \eta :

 \eta = \displaystyle{\frac{\tau}{\dot\gamma}}

The class of Newtonian fluid is rather small  (water, ethanol, glycerol, honey, silicon oil, decane, ...) and generally work for (chemically) pure solvents of small molecules.


Non-Newtonian fluids

A wide array of soft materials (foams, shampoo, hair gel, muds, peanut butter, spreads in general) exhibit a non-constant viscosity when  \dot\gamma varies, requiring fluid models that go beyond the Newtonian case. Such non-Newtonian fluids exhibit numerous curious effects. One of them is the Weissenberg effect, associated to the elastic behaviour of such materials in addition of a purely viscous nature.

Non-Newtonian fluids can be sub-divided into two classes. Shear-thinning fluids (most common case) have a decreasing  \eta when the shear rate increases. In constrast, shear-thickening fluids get more viscous when we try to shear them faster or harder.  A well-known example of this is cornstarch suspensions when highly concentrated in water. Its viscosity is low at low shear rate, but it is clearly not the case when you try to impose a large force to it !

We can examine with the right apparatus (a rheometer) the response of a 41 % vol. cornstarch suspension as a function of   \dot\gamma . The viscosity is clearly not constant (notice the log scale):

Cornstarch shear-thickening. The viscosity is NOT constant.

Around a specific shear rate (4-5 s^{-1} ), the viscosity dramatically increases: the cornstarch suspension seems to get stuck. What can happen in the fluid to produce such a striking effect ? A part of the answer lies in the shape of the cornstarch particles, which look like small rocks under the microscope.


Two models for shear thickening

Until recently, the rheologists postulated that grains suspended in a liquid were never in contact with another, since a (sometimes extremely thin) liquid layer was always present between them [1]. When this layer is very thin, moving the particles relative to one another induces extreme shear rates for the fluid suspending the particles, requiring a lot of energy or a long time to separate them.  Shear-thickening was therefore explained saying that packs of particles very close to each other are formed in the liquid and act as effective solids (called hydroclusters) which hinder the movement of the rest of the suspension. This increases the global suspension viscosity.

This idealized model has recently been challenged. A new model including solid friction and therefore contacts between grains has been developed, when sufficiently compressed one onto another [2]. The authors of this frictional model claim that the thin fluid film can break if the particles are not perfect spheres, which is experimentally always the case.

Numerical simulations performed at the Levich Institute (in New York) [3] have shown that taking into account particle friction between grains provides a satisfactory description of the spectacular and discontinuous viscosity increase in cornstarch suspensions, especially since at the onset of shear-thickening, the number of inter-grain contacts jumps and forms a network spanning the whole sample.


Additional proof

A last experiment validates the frictional model hypothesis versus the hydrocluster model [4]. Shear cycles are performed, shearing in one direction, then reversing (instantaneously) the shear (hence, from  +\dot\gamma to  - \dot\gamma ). If we consider the hydrocluster model, changing the rotation sense will not change much to the suspension material properties (it will have the same "instantaneous viscosity" without showing any discontinuity at the time of reversal) since the thin films separating the particles will take a long time to grow. Changes in global material properties will only be noticed after a long time.

When such experiments are performed, a sharp change in the material properties is observed at the time of reversal. If we now consider the frictional model, just after the reversal, the previously compressed grains can now release their compressive forces and therefore their friction between each another. The fluid grains will then be redistributed in the fluid, which will ultimately generate new network of particles bearing compressive forces and friction, and reach a viscosity similar to the one measured before shear reversal. The paper from Gadala Maria and Acrivos and more recent numerical simulations [5]) agree on such a subject.

Here, at ENS de Lyon, we focus our research on the complex dynamics of cornstarch in the shear-thickened state. At imposed stresses, the measured response is very irregular and may exhibit interesting statistical properties. The actual shape of the shear-thickening curve (shown above) is still not perfectly understood, even though it looks very similar to the characteristic lines of first-order phase transitions.


Bibliography

[1] N.J. Wagner, J.F. Brady,  "Shear thickening in colloidal dispersions", Physics Today, (2009)
[2] M. Wyart, M. Cates, "Discontinuous shear thickening without inertia in dense non-Brownian suspensions", Physical Review Letters (2014)
[3] R. Seto, R. Mari, J. Morris, M. Denn, "Discontinuous Shear Thickening of Frictional Hard-Sphere Suspensions", Physical Review Letters (2013)
[4] F. Gadala Maria, A. Acrivos, "Shear‐Induced Structure in a Concentrated Suspension of Solid Spheres", Journal of Rheology (1980)
[5] F. Peters, G. Ghigliotti, S. Gallier, F. Blanc, E. Lemaire, and L. Lobry, "Rheology of non-Brownian suspensions of rough frictional particles under shear reversal: A numerical study", Journal of Rheolgy (2016)

Videos for scientific presentations

Videos provide a great way to display rather large and complex set of data in a clear and concise fashion. However, video encoding and embedding is generally a painful process for most of the scientific community when in a hurry before a conference. The vast array of codecs, container file types and hazardous symbolic links in files are probably to blame for this. Tackling such issues is however not impossible, and may increase your video quality and your compression ratio, while maintaining compatibility with the two slideshow softwares I use (Microsoft Powerpoint ® and Adobe Reader CC ®).


Encode a video from a set of images

ImageJ and MATLAB natively provide solutions to create movie files, respectively from image stacks and movie objects (based on a figure). Unfortunately, customization options are scarce and output quality is often not up to our (my) expectations. Worse, the output file size is not always reasonable.

A free, multi-platform, command line austere alternative is called ffmpeg. One of the many features of ffmpeg compiles an image sequence into a video file using efficient codecs. It also provides tools to re-encode your video files if their exotic format does not allow playback on your favourite presentation software. The global ffmpeg syntax reads :

./ffmpeg -i image_%03d.png [options] mavideo.mp4

Windows users will drop the  ./, and will think about adding the ffmpeg binary folder to the environment variables (PATH). The -i command specifies the input file or files to be converted to video. An image sequence will classically be called using regular expressions ; in the example case, files of name image_001.png, image_002.png, etc. Let us now take a look at the encoding options that may prove useful :

Slow motion is achieved with a video filter, called by inserting the following expression where the [options] are located in the original code. Here, the video will be three times slower than the input nominal "speed" :

-filter:v "setpts=3*PTS"

You can change the video size (in our case, force a size of 572x946 pixels)

-s 572x946

Video quality can be set changing the crf option (from 1, best quality, to 31, worst quality, 18 being already excellent quality) :

-crf 18

A ton of other options to rotate, crop, change the luminosity, etc. of your videos is available at the excellent ffmpeg Wiki page.


Powerpoint compatibility

Microsoft Powerpoint ®, for versions after 2013, is perfectly compatible with the standard output of ffmpeg. Video integration and embedding is therefore seamless. If you want your video to be Powerpoint 2010 compatible, the xvid codec is recommended. The new ffmpeg call syntax is now :

./ffmpeg -i image_%03d.png -c:v libxvid -q:v 4 video.avi

An .avi file is output. Xvid is know to be a lot less efficient than what ffmpeg can natively do, so expect either a decrease in video quality, or a increase in size. By the way, the video quality is now set using -q:v.


Adobe Reader / Beamer

You can directly include videos in PDF files for Adobe Reader versions above 9 (and Adobe Reader CC) to avoid any stress-related "did I copy my videos along with my PDF file" situation. The solution requires the use of the media9 Beamer package for LaTeX.

\documentclass[...]{beamer} 
[...]
\includepackage{media9}
[...]
\begin{document}

Media9 allows multimedia file inclusion in presentations (e.g. : 3d animations, links to Youtube streams, etc.) in addition to videos. I regularly use one simple macro :

\newcommand{\addvideo}[3]{
% Macro to add video : 
% Argument 1 : video source location
% Argument 2 : image preview file location
% Argument 3 : width of video
\begin{center}
    \includemedia
    [
        width  = {#3}, addresource = {#1},               %Inclut le fichier source dans le fichier pdf
        flashvars = {src=#1 & scaleMode = letterbox}     % Appelle le fichier source dans le lecteur 
    ]
    {\includegraphics[width = {#3}]{#2}}{StrobeMediaPlayback.swf} % Arg #2 is used as preview image        
\end{center}
}

Including a video called video.mp4 using a cover image called image_example.png for a video width of 8cm will be done with this command line:

\addvideo{video.mp4}{image_exemple.png}{8cm}

The video file is now included in the PDF file. Copying the video file along the PDF file to read the video is, after this step, unnecessary.

Last point : a small compatibility issue with the video player of Adobe Reader will impose a pixel format for your video output. You can set it when calling ffmpeg with the -pix_fmt command:

./ffmpeg -i image_%03d.png -pix_fmt yuv420p video.mp4

Please note that in this case, only even video sizes (472x276, 800x600, etc.) are accepted.

Boundary effects in directional freezing

Directional freezing applies a temperature gradient on a fluid or a solid and moves this gradient with respect to the sample. We can either move the sample in a fixed gradient (our case), or the opposite, which occurs in industry (zone melting) and in geology (freeze/thaw cycles in soils, pingos). Both cases are physically identical.

In the case where the solidified medium is a suspension (biphasic), particles will enter the ice in the steady state ; their location and potential structuration will depend on the shape of the liquid/solid interface. For high solidification velocities V, this interface forms characteristic needles, whose shape can be modified using anti-freezing agents or an imposed liquid flow. This ice-templating, concept provides useful tools to structure materials after sublimation of the solid (ice) matrix.

Below the critical solidification velocity, the solid/liquid (hereafter water/ice) front is plane. In this case, the particle arrangement in the solid phase is not well-known. To address this question, our experiment relies on this setup:

setup_freezing
Experimental setup. From top to bottom : intial state, steady state where the sample has significantly moved, and zoom in between the glass sheets near the 0°C isotherm.

The motor (left) pushes a sample holder (two glass sheets separated by spacers) in a large temperature gradient. A digital camera observes the sample from above the 1 cm window between the hot and cold ovens, providing frames where the 0°C isotherm is always visible. The camera setup works in (simple) light scattering mode.


Volume models

We have observed a strong particle rejection when ice forms, generating a dense particle strip. This strip can exist beyond the 0°C line. In this situation, and in the reference frame of the glass sheets, fluid muse be continuously provided to the solid phase at a rate proportional to V for a steady state to exist (otherwise, the ice phase will recede). This water muse cross the strip, modelled as a porous medium, in which a Darcy flow sets in. The strip stops growing when the pressure difference induced by this flow equals the chemical potential difference linked to the temperature gradient.

With this simple model, the strip is much larger than what is reported. Another way to tell this is that the Darcy micro-channels are too large (experiments used 300 nm particles). A refined model suggested that these micro-channels present at temperatures below 0°C may be partially frozen, reducing the effective size of the micro-channels and limiting the size of the strip. An adjustable-parameter model then recovers the experimentally measured sub-cooling T_f - T_0 where T_0 = 0^\circ {\rm C}.

We use larger particles (d = 3μm) that leave very large micro-channels which should eventually be almost frozen. Since this model is only one-dimensional, it does not include any dependence of the strip width with the sample height, e. Our experimental observations showed no structural or aspect modification of the strip during freeze/thaw cycles, and a dependence of the strip width with e. Something in the model is therefore lacking.


Boundary effects

The pressure gradient applied on the strip may be transmitted to the glass plates through an isotropisation of the particle (solid) stresses (this is the Janssen model). The stress balance of a slice of strip then shows a fast (exponential) increase of the friction at the system boundary. A common life example of this happens when too much coffee grains are put in a French press machine. Dimensional analysis shows that the exponential law characteristic length is

\xi = \frac{e}{2 \mu K},

\mu being the Coulomb solid friction ratio and, K is the stress isotropisation constant (of order 1 in our case), e being the height of the sample. We should therefore observe a significant change in the stripe width with e, which is observed experimentally.

Strip length h as a function of sample height e

We are now working on a microscopic description of the particle admission process in the solid phase along with models to explain the patterns observed in the stripe..

Nice figures using MATLAB

MATLAB (or, conversely, Octave) is pretty great at processing data and quickly plotting them, but its default plot possibilities (better now after Release > 2014b) are definitely not perfect.

Four plots, using MATLAB default properties
Four plots, using MATLAB default properties. Not great, but not bad.

Image and font sizes ...

Imposing the font size and the total size of an image (or PDF export) can be tricky. It requires to know the final size of the image you will use. For this, you can cheat and determine what the line size is using TeX commands:

\the\columnwidth
\the\textwidth

This will output something like 510.0pt. We then have to recast the 510 directly in MATLAB for both raster (position option) and vector (paperposition, paperwidth, paperunits options) formats:

set(gca, 'fontsize', 12);
set(gcf, 'paperunits'   , 'points',          'position', [100 100 510 300], ...
         'paperposition', [100 100 510 300], 'papersize', [510 300]);

which will impose a font size of 12 points on a 510 point wide image. Beware of the argument order for the figure (paperunits before papersize) or otherwise everything will blow up.


Typeface consistency

MATLAB (> R2014b) can now handle LaTeX tick labels. Hurray !

set(gca, 'TickLabelInterpreter', 'latex');

Markers

I don't really like MATLAB markers since the new versions. Let's plot a basic line :

plot([1 2 3 4 5 6], [1.1 1.0 1.05 0.95 1.0 0.98], 'o')

then export it to .pdf. Zooming on the markers will result in this :

Not really a circle
Not really a circle

I don't know any workaround for the moment.


An alternative : qTikZ / matlab2TikZ

If you want perfectly clean .pdf files compatible with LaTeX based on MATLAB graphs, you can use qTikZ coupled with matlab2TikZ.

  • matlab2TikZ converts your .fig into a .tex file for further modification.
  • qTikZ allows to edit the resulting .tex file and watch the resulting figure (with correct cropping) in real time.

It provides really great results. And you do not have to worry about font size relative to figure size, since in .tex, the two parameters are set separately. Sample figure becomes:

QTikZ default output
QTikZ default output

This image has a major advantage compared to MATLAB output : it does not create unwanted white padding (i.e. the axis size is exactly what you requested), the default font is LaTeX, and the circle marker issue is gone. You may have some trouble with colorbars, but nothing too worrisome.


Color maps

The venerable Jet colormap is now widely hated around the world for its strange light gradients at specific places and its poor lisibility in black and white. The parula colormap does a great job since MATLAB R2014b. A free alternative compatible with color-blindedness is viridis. Other useful candidates like cbrewer may be useful.

One last thing: if you want to change the default color order in MATLAB (when using the hold on command), you can use this (> R2014b):

set(groot, 'defaultAxesColorOrder', cmap(nplots));

where your colormap (cmap) has nplots lines.

Von Kármán flows

The von Kármán swirling flow (generally mistaken for the vortex street named after the same Theodore von Kármán) is produced by the rotation of two face-to-face discs in a cylinder filled with fluid. For bladed discs and a low-viscosity fluid, the inertial stirring produces a high-intensity, large Reynolds number flow.

von Karman flow, seeded with bubbles. The two impellers (in black) are visible.
von Kármán flow seeded with air bubbles. The two impellers (in black) are visible.

This flow has been studied to answer a few fundamental open questions on turbulence. One of them is the symmetry restoration in turbulent flows. Despite their highly random instantaneous aspect, turbulent flows recover – statistically, and at small scales – the symmetries of the (forcing) boundary conditions. This flow proposes to answer the following question :

Is the small-scalle statistical symmetry restoration mechanism in turbulent flows valid at larger scales ?

One important result on this topic has been evidenced by Florent Ravelet, Louis Marié, Arnaud Chiffaudel et François Daviaud. They showed that the von Kármán flow kept a memory allowing to statistically remain in an asymmetric statistical state despite imposing back a symmetrical forcing. The flow exhibits a statistical hysteresis.

Hence, when the two impellers rotating at imposed frequencies f_1 (bottom) and f_2 (top), we can impose f_1 = f_2 and have a symmetrical forcing with respect to impeller exchange, but to obtain a flow that will indefinitely remain oriented towards one of the impellers. An analogy with ferromagnetic systems provides insights to plot the aspect the the hysteresis cycle when f_1 et f_2 are varied.

For large Reynolds number, the relevant dimensionless variables are :

\theta = \frac{f_1-f_2}{f_1 + f_2}

and the reduced torque difference :

\gamma = \frac{T_1-T_2}{T_1 + T_2}

The cycle has therefore this aspect :

VK_gth
Hysteresis cycle of the mean statistical states of the von Kármán flow. Black squares, states at imposed impeller frequency. Circles, states reached at imposed torques.

The frequency imposed cycle shows indeed how at well-chosen values of \theta, especially 0, more than one statistically steady state may coexist. The full cycle is obtained scanning \theta from -1 to 1 and 1 to -1 and shows three branches, the central one being metastable. Between the central and the external branches, a \gamma range is ``forbidden''.

During my PhD thesis, I focused my studies on torque imposed experiments, in which C_1 and C_2 are imposed. For well-chosen values of C_1 and C_2, we can impose \gamma in the forbidden region. We expect no statistical steady state to survive in this region. This result is confirmed by the experiments.

Evolution of the impeller frequency for various gamma values
Temporal series of the impeller rotation frequencies f_1 (dark) and f_2 (light) for several normalized torque differences \gamma. The color scale refers to the colors of the circles in the hysteresis cycle figure.

The study of the large-scale statistical properties of the multi-stable flow for (moderately) long times has yielded several scientific articles. Other statistical properties induced when changing the rotation sense of the impellers have also been published (see Pierre-Philippe Cortet et al., New Journal of Physics, 2011).

One PhD thesis (by Denis Kuzzay) has followed such work to investigate the dissipative structures down to the Kolmogorov (or below) scales. The SHREK collaboration investigates whether quantum turbulence dissipates energy in a similar fashion.

Caseinate sodium gels

Our collaboration with G. H. McKinley focuses on the rheological response of caseinate sodium gels under an imposed oscillatory stress (Lyon) and strain (Cambridge). The local displacement analysis of the gel provides local Lissajous-Bowditch curves highlighting ... a homogeneous response !

Lissajous-Bowditch curves (local Lissajous-Bowditch, thin coloured lines obtained using LORE) of a 6% caseinate gel under an oscillatory stress of 180 Pa.
Lissajous-Bowditch  curves (local curves obtained through echographic analysis, thin coloured line) of a 6% sodium caseinate gel under an oscillatory stress \sigma_{\rm pp} = 180 Pa and a typical strain of 60 %.

The Lissajous-Bowditch curve analysis yields interesting information on the nature (strain-hardening or softening) of these gels. We are currently looking for ways to predict gel failure from the weakly non-linear response of the gels. A publication about this is under way !