Mathematica in Examples – Replace all Elements in an Array that satisfy a Condition

Here is a short but useful code snippet, that replaces all elements in an array that satisfy a condition. Mathematica has many ways to do such things, but provides remarkable shortcuts.

Specifically,  I want all elements in the array

array={0.601, 0.9, 1.553, 2.588}

that are larger 1 to be set to 1 (thus clipping of all elements larger 1).

Download Mathematica Notebook: ReplaceElementsinanArray.nb

The fastest way to do that is to use the ReplaceAll function combined with the Condition function. First is highlighted in blue and latter in red.

In:=

array/.x_/;>1->1

The ReplaceAll function is given by /. a->b , where a is our condition x_/;>1 (number greater “1″) and b (“1″ here) our replacement. The output gives than

Out:=

{0.601, 0.9, 1, 1}

Pretty simple, huh?

Alternatively, the same result is achieved by using the Table function together with the If function:

In:=

Table[If[array[[i]] > 1, 1, array[[i]]], {i, 1, Length[array]}]

The code is not as compact as the one above, but has the same output.

Latex in Inkscape

Textext is an excellent Plugin to render Latex formulas in Inkscape. Features are editing of formulas after they have been rendered and loading of latex packages in advance. Latter is especially useful for customizing latex fonts. The installation is straight forward:

Editing Latex formulas in Inkscape works like a charm using Textext.

Installation

1. You need to install Pdflatex and Pdf2Svg at first: Direct Install or

sudo apt-get install texlive-latex-extra pdf2svg

2. Download Textext Plugin for Inkscape from the Textext Side

Direct Download: textext-0.4.4.tar.gz

3. Unzip the file into the Inkscape Plugin folder

Inkscape 0.47:    ~/.config/inkscape/extensions/

Inkscape > 0.47:  ~/.inkscape/extensions/

4. After restarting Inkscape you find the Textex Plugin  in the Extensions menu:

Mathematica in Examples – Fit Lorentz distribution with Constraints

Mathematica’s NonLinearModelFit function is useful to fit an arbitrary function to a set of data. In this example code a Lorentz function with constraints for the parameters is fit to some example data. Initial fit parameters are guessed.

Download Mathematica Notebook : nonlinearfit_lorentz_osfight.nb

1. We define the Lorentz function with linear background in Mathematica as

Lor[{A_,μ_,Γ,C0_,m_},ν_]:= (A Γ)/((ν-μ)^2+(Γ/2)^2) + m ν + C0;

where 4A/Γ is the peak height, μ the center, Γ the linewidth of the of the Lorentzian (the code can be copied to Mathematica). mν + C0 is the linear background and can be set to zero if not needed.

2. Lets take some random data and try to guess the initial parameters by plotting the guess function and the data together. The guessed initial values are colored in red

Input=

data = {{0.`, 0.0007568602316023421`}, {0.4`,
   0.0006077641663579275`}, {0.8`,
   0.0010957089335075778`}, {1.2000000000000002`,
   0.0014422342777222481`}, {1.6`, 0.0021026269660642818`}, {2.`,
   0.002035918694285509`}, {2.4000000000000004`,
   0.0019560986865232773`}, {2.8000000000000003`,
   0.002807918106577903`}, {3.2`, 0.0032891006273276686`}, {3.6`,
   0.009439170796893468`}, {4.`, 0.012570566138374808`}, {4.4`,
   0.01820541122261653`}, {4.800000000000001`,
   0.01555451311477995`}, {5.2`,
   0.022197008830661266`}, {5.6000000000000005`,
   0.013782511728324743`}, {6.`, 0.013581988241044292`}, {6.4`,
   0.0090081109450604`}, {6.800000000000001`,
   0.003354272775540456`}, {7.2`,
   0.0021712171237978674`}, {7.6000000000000005`,
   0.0030934291572321778`}, {8.`, 0.0019866310063820377`}, {8.4`,
   0.0010959725673603206`}, {8.8`,
   0.0012691490482224404`}, {9.200000000000001`,
   0.0006927858593134837`}, {9.600000000000001`,
   0.0011999520986368984`}, {10.`, 0.0007696824792981429`}};

guessPlot = Plot[Lor[{0.005, 5, 1, 0, 0}, x], {x, 0, 10}, {PlotStyle -> Red}, PlotRange -> All];
dataPlot = ListPlot[data];
Show[{guessPlot, dataPlot}, PlotRange -> All]

Output=

The guessed Lorentz curve (red) is shown next to the data points.

3. Our inital values look decent, so we can try to fit a curve to the data. The initial values from above are labeled in red and constraints in blue.

Input=

nlmLor=NonlinearModelFit[data,{Lor[{A,μ,Γ,m,C0},x],{Γ>0,A>0}},{{A,0.005},{μ,5},{Γ,1},{m,0},{C0,0}},x]; 
nlmPar=nlmLor["BestFitParameters"]

Output=

{A->0.00987806,μ->5.05304,Γ->2.18077,m->0.000195088,C0->-0.0000407613}

4. Now we can fit the result and check the fit quality
Input=

fitPlot = Plot[Lor[{A, μ, Γ, m, C0}, x] /. nlmPar, {x, 0,10}, PlotStyle -> {Blue, Thick}, PlotRange -> All];
Show[dataPlot, fitPlot]

Output=

The fit Lorentz curve (blue) is shown with the data points.

Tips

  • the “quality” of the initial parameters are quite important for the convergence of the fit
  • using constraints requires more computation effort and is not recommended with the NonLinearModelFit
  • detailed fit errors are given using for example nlmLor["ParameterTable"] or nlmLor["ParameterTableEntries"]

This article is part of a series explaining how to use Mathematica for experimental data analysis. In this series:

Part 1 – Fit Lorentz distribution with Constraints

Part 2 – Fit a triplet Gaussian (coming soon)

Mathematica 7.02 on Linux – Direct Download

Wolfram provided an updated version of Mathematica 7  with the filename M-LINUX-L-7.0.2-1376260 that works much better on Ubuntu and removes among others things the annoying Java bug that caused Mathematica to take 15% of the CPU in idle.

Wolfram Mathematica 7.02 Download Page (Direct Download)

(It does not get rid though of well-known issues, for example the tremendous slowdown of the user interface for large notebooks.)

Revtex4 for Latex on Lucid

To use Revtex 4.1 in Latex for (american) scientific papers install the package texlive-publishers (direct install) and use in your document

\documentclass[11pt]{revtex4-1}
\begin{document}
\end{document}

For older Revtex versions check the package revtex.

Ubuntu 10.4.1 – Released !

Latex in Examples – Greek Unicode Letters / Hypperref

An example how to use greek utf enconded text letters, like τ,Γ,π,ω…, as direct input method in latex instead of $\tau$, $\Gamma$, $\pi$,$\omega$… . Each letter requires a newcommand in the preface.

PDF: greek_unicode.pdf

Files: greek_unicode.zip

Latex Code

\documentclass[10pt,a4paper]{article}
\usepackage[utf8x]{inputenc}

%small letters
\newcommand\textalpha{\ensuremath{\alpha}}
\newcommand\textgamma{\ensuremath{\gamma}}
\newcommand\textpi{\ensuremath{\pi}}
%capital letters
\newcommand\textGamma{\ensuremath{\Gamma}}
\newcommand\textPi{\ensuremath{\Pi}}
\begin{document}

Formula using Latex standard math environments versus unicode:

\begin{eqnarray*}
\mathrm{latex input} &  & \mathrm{unicode} \\
\alpha & \Leftrightarrow & α\\
\gamma \Gamma & \Leftrightarrow & γ Γ \\
\pi \Pi & \Leftrightarrow & π Π
\end{eqnarray*}

\end{document}

Hypperref Problem

When the hypperref package is used additionally  some greek letters cannot be defined via the \newcommand anymore, such as \textmu and \textbeta.  The error looks something like that

! LaTeX Error: Command \textmu unavailable in encoding OT1.
! LaTeX Error: Command \textbeta unavailable in encoding OT1.

A workaround is to remove the error causing commands and load additionally the tipa package and the textcomp package, that will do the trick.

\documentclass[10pt,a4paper]{article}
\usepackage[utf8x]{inputenc}
\usepackage{hyperref}
\usepackage{tipa,textcomp}

%small letters
\newcommand\textalpha{\ensuremath{\alpha}}
\newcommand\textgamma{\ensuremath{\gamma}}
\newcommand\textpi{\ensuremath{\pi}}
%capital letters
\newcommand\textGamma{\ensuremath{\Gamma}}
\newcommand\textPi{\ensuremath{\Pi}}

\begin{document}

μ, β, α, γ, π, Γ, Π

\end{document}

Latex in Examples – figure, subfloat & minipage

An example how to arrange three pictures  in columns and rows.

Files:  subfloat_1

PDF: examples

Latex Code

\documentclass[10pt,a4paper,draft]{article}
\usepackage[utf8x]{inputenc}

\usepackage{graphicx}%
\usepackage{subfig}%

\begin{document}

\begin{figure}[ht]
\begin{minipage}{0.62\textwidth}
\subfloat[]{\label{subfig:a}\includegraphics[width=1\textwidth]{fcc}}%
\end{minipage}\quad %
\begin{minipage}{0.33\textwidth}%
\subfloat[]{\label{subfig:b}\includegraphics[width=1\textwidth]{fcc}}\\%
\subfloat[]{\label{subfig:c}\includegraphics[width=1\textwidth]{fcc}}%
\end{minipage}%

 \label{fig:diamond_lattice}
 \caption{Face-Center-Cubic - \ref{subfig:a}  \ref{subfig:b} \ref{subfig:c} }

\end{figure}

Caveats for a Karmic Koala Upgrade

I was just into upgrading to the newest Ubuntu 9.10 release, Karmic Koala, launched on Oct. 30th. However, there are some issues which should be considered:

  • Ipods are not recognized by Banshee & Co anymore due to the change from HAL to Device-Kit, but some people work already on a fix for this problem (Bug #382941 -high priority) and a not too pretty workaround is explained at bugzilla
  • the window list application crash for vertical gnome panels is still existing, an upcoming fix is still unknown, but a workaround is easy and should work for Karmic Koala (not tested yet)
  • more?

Quick and Dirty CVS

CVS is an easy way to manage programming projects. It keeps track of who changed what and when, as well as saving old versions. I’ll explain how to get a CVS server up and running in 5-10 minutes.

1. Install the server/repo

For Debian/Ubuntu this is fairly straight forward. “apt-get install cvs” should do the trick. Those on other distribuitions should use whatever package manager their distribution uses. Install from source if you like to complicate things, or are running gentoo.

2. Set up the server/repo

Decide on a directory that you want to hold all your CVS modules (i.e. your projects). Typically this is /cvs or /usr/local/cvsroot but it doesnt matter.

Export this directory as the CVSROOT environment variable, this is done with the simple command
$ export CVSROOT=/path/to/cvs/root

(NOTE: this works for bash/csh/ksh, zsh should use the setenv command) You should also add this export statement either to your user init script (~/.bashrc) or the global init script (/etc/profile). So you don’t have to export the variable every time you use cvs on the server.

Run the command
$ cvs init
in order to initialize your cvs repository.

3. Configure the server/repo

CVS does not like having its files edited in the repo, in order to avoid conflicts, its a good idea to checkout the CVSROOT package (this holds all the configuration files) and then comit those changes rather than just editing the files in the package directly. So lets do this (and at the same time we can test if the repo is set up properly.

$ chvs checkout CVSROOT

should display an output like the following

U CVSROOT/checkoutlist
U CVSROOT/commitlist

Try editing some file, (add a space in a comment), save the file and type

$ cvs commit -m "first commit"

The -m is to indicate a short comment for the commit, otherwise cvs would open up the editor specified by the $EDITOR environmental variable to edit the comment.

If it doesnt work. Make sure that your user has write access to the cvs directory. The easiest way to set this up is to create a group (cvs) and to change the cvsroot directory to that groups ownership and to add your user to the group.

4.  Setting up remote access

Set up the proper permissions and users to allow remote reading and writing of the files.

Create a user named cvs-admin in the group cvs (or something along those lines). Go over to the cvs root directory and run the following 2 commands

$ chown -R :cvs .
$ chmod -R g+s .

The first one changes the owning group of the directory (and all of its files) to the cvs group. The second one makes it so that any newly created files will maintain the cvs group ownership (that way if many different users add files they will all still be readable and checkoutable by everyone

In order to get the server runing we need to edit some system config files. Make sure that the following line is in /etc/services

cvspserver       2401/tcp   #CVS network server

Then add the following line to /etc/inet.conf

cvspserver      stream  tcp     nowait  cvs-admin    /usr/bin/cvs cvs --allow-root=/cvs pserver

Also make sure to edit any firewall scripts to allow traffic on port 2401. Restart the inet service and everything should be runnning

5. Adding users

cvs does let you remotely log-in via a local user, but this is insecure, and doesnt work too well when you have a non root owner for the server process. If you don’t mind the security problem (i.e. on a local network), you can simply change the inet.conf to start the service as root instead of cvs-admin and add the names of the users you want to edit to the “writers” files and those who are read only to the “readers” file. (more on this in a second)

If you want the extra security OR you want to add users who don’t have a local account (i.e. windows users logging in remotely) you need to make a passwd file for the repository.

Checkout CVSROOT again (if you have deleted the previous checkout). Create a file named  passwd, a file named readers, and a file named “writers” and add the names of those users that you want to have write access to your repository (either local or remote) to writers.  If a writer/reader doesnt have a local account associated with them, or you decided to run the service from non-root account (which is recomended) you need to add an entry to the passwd file.

The passwd file has entries in the following format

username:password:systemuser

If the proccess is running as non-root then it has no rights to change the user of the attempted read, therefore any user other than the cvs-admin user in the systemuser field will cause the attempted checkout/commit to fail. If you are running a non-root cvs server all the entries should have the following format

john:43eEPdlpnUmb6:cvs-admin

The first field is the user name, the second is the encrypted password. The easiest way to generate this field is to use the htpasswd utility that is installed if you have apache installed on your server, otherwise you can use this utility that can generate the entry for you.

After creating and editing the readers/writers/passwd files we need to tell the cvs repository to include those files in the configuration, edit the checkoutlist file and add 3 lines to it, “passwd”, “readers”, “writers” with no quotes.

Now we just need to add those files and commit to the module with the following command:

$ cvs add writers
$ cvs add readers
$ cvs add passwd
$ cvs commit -m "Added passwd and users"

6. Client Configuration

The last thing left is to configure your client to access the cvs repo. luckily this is fairly straight forward.

For one off checkouts you can use the following commands

$ cvs -d :pserver:username@server:/path/to/cvs/root login
$ cvs -d :pserver:username@server:/path/to/cvs/root checkout MODULE
$ cvs -d :pserver:username@server:/path/to/cvs/root logout

For a regular cvs repository it would be easier to set the CVSROOT variable to point to the server/user that you need.

$ export CVSROOT=:pserver:username@server:/path/to/cvs/root

After which you can simply use the commands without specifying the server everytime

$ cvs login
$ cvs checkout MODULE
$ cvs logout

Remember to save the export either to /etc/profile or ~/.bashrc to save the exported variable next time you log in.

7. Anonymous CVS

There are two ways of doing this, depending on which way your server is configured. If you have it running as root, then you have to create an anonymous user

$ useradd anonymous -s /bin/false
$ adduser anonymous cvs

The reason I add anonymous to the cvs group is because even a read-only user needs to have write permissions to create a lockfile. There are ways around it but I havent figured them out.

In the passwd file add the following line  – anonymous:

If you are running the server as non-root, then you should add the following line to the passwd file

anonymous::cvs-admin

In either case, make sure to add the anonymous user to the readers file.
To make sure its working properly, log in as anonymous and try commiting a change, it should fail.

Return top
 
This website uses a Hackadelic PlugIn, Hackadelic SEO Table Of Contents 1.7.3.