Archive for the ‘ math ’ Category

Ray tracing – matrix math

Today was my last day at Reson, and I’m finally getting around to writing the Python version of my ray tracing script.  What I want to do is take sound speed profiles as input, and compute the difference in depth that would result from using one versus the other at different multibeam launch angles.  It’s just a little tool that I’d like to have to figure out how much error I could expect given two profiles.

So far, I’ve read in the profile (from a text file), and parsed the data:

filename = 'ssp.txt'

ssp = []
depth = []

file1 = open(filename)
for line in file1.readlines():
#    print line
    splitup = line.split()
    ssp.append(float(splitup[1]))
    depth.append(float(splitup[0]))

After this, I defined an array of launch angles (relative to horizontal, so +/- 75 degrees was actually 15 – 165), and an array of sound speed values interpolated from the sound speed profile to a certain depth increment (1m), and down to a given water depth (10m).


LaunchAngle = r_[15.:166.:5.] # array of launch angles in degrees
LaunchAngleRadians = LaunchAngle*pi/180
nadirdepth = 100 # nadir depth in meters
DepthIncrement = 0.5 # depth increment in m

if nadirdepth > max(depth):
    ssp.append(0.016*(nadirdepth - max(depth)))
    depth.append(nadirdepth)

if min(depth)>0:
    ssp = insert(ssp,0,ssp[0])
    depth = insert(depth,0,0)

depthvector = r_[0:nadirdepth:DepthIncrement]
interpfun = interp1d(depth,ssp)
sspvector = interpfun(depthvector)

And as if that much wasn’t suspicious enough, I decided that I wanted to do all of the calcs using matrix math. I figured I’d ditch all the loops that were in my original Matlab script, and replace them with some nice streamlined matrices. So efficient. The problem is that there are some exceptions that I need to take care of, that are difficult to deal with when doing everything in a series of matrices. For example, when the sound speed in a certain layer is the same as the sound speed in the first layer – then the gradient is zero, and the radius of curvature is infinite. Here’s what I’ve hacked together so far. It’s not pretty.


thetaLaunch = tile(LaunchAngleRadians,(size(depthvector),1))
depthmat = transpose(tile(depthvector,(size(LaunchAngleRadians),1)))
sspmat = transpose(tile(sspvector,(size(LaunchAngleRadians),1)))

g = (sspmat - sspvector[0]) / DepthIncrement

Rc = -sspvector[0]/(g*cos(thetaLaunch))

thetamat = arccos( ((Rc*cos(thetaLaunch)) - DepthIncrement ) / Rc )

dx = (Rc*sin(thetamat) - Rc*sin(thetaLaunch))
dxnandex = isnan(dx)
dx[dxnandex] = DepthIncrement/tan(thetaLaunch[dxnandex])
dx[0,] = 0
dxsum = cumsum(dx,axis=0)

Yuck. But at least I managed to get some rays that made sense.

The next step is to convert the ray paths to two-way travel times, and then compare the depth that would be calculated if the ray tracing were done with a second sound speed profile.

Inkscape + Latex on Mac

I thought this was going to be trivial – it seemed so easy on Ubuntu.  But I getting Textex working with Inkscape on a Mac is a bit different.  I found these instructions on the mactex-wiki.  I’m not gonna lie.  It looks terrifying, and involves changing several lines of code in textext.py and textext.inx, and moving and deleting files from various folders in the inkscape package.

So before I embark on that journey, I’m going to try just blindly copying textext.py and textext.inx into the Inkscape extensions folder.  Oh hey, I got the textext item in the Extensions menu:

Next problem:  I click on the Textext option, and get this error:

Couldn’t find python-lxml in Fink, so I tried fink install lxml-py26…. and it didn’t work. :-(

It’s too late to be messing with this tonight. Maybe tomorrow. Or maybe Inkscape is not the answer – there’s got to be a better way!!

Maybe next time I’ll look into this blog post.

Diagrams in Mac

Here we go again… I was trying to draw a little diagram, and since I’m using a Mac, figured I’d look up OmniGraffle.  But OmniGraffle is now $100 for the basic package – and $200 for professional.  It wouldn’t be quite so painful except I got it for free back when I got my old Mac Powerbook back in 2006.

So it’s back to Inkscape.  I love open source!  It was an easy install – I decided to take a pass on compiling from source, and just grabbed the .dmg file from the downloads page. And of course, I already went through the whole Inkscape plus Latex thing a while ago.

And, for fun, here’s a screen shot of Inkscape in action:

… who needs OmniGraffle anyway… (sniffle)

Simple beam pattern in Python

It’s been a long time since I’ve

(a) used Python, numpy, scipy, or matplotlib

(b) done a beam pattern calculation of any kind

So I thought it would be a good chance to brush up on several things all at once, and maybe even have the satisfaction of making a pretty picture at the end of the night.

Well, here’s the (perhaps not so) pretty picture:

This was so simple, I’m almost embarrassed to post it, but it will probably be helpful for me later, so here it is.  What is it?  I pretended I had two little pingers spaced 5 wavelengths apart, sending out continuous sinusoidal waves.  I summed these signals at each of the elements in a 2-D grid, plotted the resulting magnitudes, and voila.

What I had to learn:

- How to use exp() using numpy – I had to load it separately for some reason, otherwise it would default to the exp() that comes with the basic math package, which doesn’t allow computations on arrays.

-How to plot an image, a la “imagesc” in Matlab.  This is accomplished using <code>imshow(datahere)</code>, and a colorbar can be added using <code>colorbar()</code>.

-How to do a screen capture of a certain area on a Mac computer:  command+shift+4 gives you crosshairs so you can pick what you like.

It would have been nice to add some attenuation, but I’m too tired now.  One more thing that I need to figure out though, what’s the best way to post my code?  I probably should figure out how to put it up on the bluehost server (where this blog lives), and link to it from here.

NYT Article – Square Dancing

Yeah – thanks, Val!

Square Dancing Article from The New York Times

This article made me smile – it gives a fun description of the Pythagorean theorem. Yay, geometry! My favorite is the part where the author tells where the word geometry comes from geo (earth) and metry (measurement) – geometry was originally used in solving problems of land measurement. This makes me happy to be a surveyor :-)

Still working on MB-System

Yeah, I really should’ve realized it was just too easy.  I just tried installing MB-System, and I am getting a ton of errors because my c compiler is not recognizing simple math functions like sin, cos, sqrt, pow, etc.  I’m sure this is a really simple issue, and I’m just clueless about c in general.  But I really don’t know how to fix this.

Googling around, I did find some information – I think I’m missing a ‘-lm’ option somewhere (so that c links to the math library).  I found this conversation on an Ubuntu forum. Someone else was having the same problem, and part of the troubleshooting involved created a simple test program in C that uses some a math function (sin in this case). Here’s the little script that they use to create the test program. It’s called ‘test1.c’.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
main()
{
float x,y;
printf("enter the value of x\n");
scanf("%f",&amp;x);
printf("Hello world\n");
y=sin(x);
printf("value of y is %f \n",y);
printf("\nEnd of program\n");
}

Then if I type gcc -o test1 -lm test1.c in the terminal window, it creates a compliled program test1 from the test1.c code. I was then able to run it by type ./test1. Now, this didn’t exactly solve my problem, but it was pretty cool, and it worked. Which is significant in its own right since it is, quite literally, my VERY FIRST C PROGRAM. Ever. Yup, I just skipped right over “Hello, world”.

So, eventually I did manage to get past the above problem. I had a typo in my install_makefiles script, so I had to re-run it:
./install_makefiles
then sudo make all.

I was then able to find and use the appropriate math library. But I was still getting a ton of ‘undefined reference’ errors for a bunch of GDAL files. Not sure how to fix that. I think it’ll have to wait until tomorrow…

Inkscape + LaTeX? (Textext)

Okay, I’m being really indecisive here… but I finally found one that I think I like (so far).  It’s not perfect, and it’s a bit quirky, but at least I managed to do what I need to do.  Here’s the main website:  http://www.elisanet.fi/ptvirtan/software/textext/. I also found this blog post to be helpful.

I tried making a really simple depiction of Snell’s law, basically showing the relationship between the angles of incidence and refraction and the refractive indices of two layers. In this case, it is sound waves travelling through homogeneous layers of water with different sound speeds. Easy peasy :-) The sketch only took me about 15 minutes to create.

All I had to do was go to Extensions –> textext, set the scale to 2.5, and enter the following text into the box:

\begin{minipage}{5cm}

$\frac{c_{i}}{\sin{\theta_{i}}} = \frac{c_{i+1}}{\sin{\theta_{i+1}}}$

\end{minipage}

Yes, it’s sort of annoying to have to add that \begin{minipage} stuff. I’d much rather have it more behind the scenes, but I suppose that does give you more control. The resulting image looked like this:

So, nothing too special, but it’ll work for now.  I’ll keep an eye out for other options, but I am getting to really like Inkscape, so maybe I’ll stick with it.  There might be other Latex plugins too that work better.  This one is convenient because you can re-edit an equation once it’s been entered.  If it’s a complicated equation, it can be a real pain to re-type the whole thing if there’s only one little mistake.

One more thing I ought to mention: I keep getting this error message. I’ve been basically ignoring it because I’m getting the correct output, but Inkscape is clearly not happy with something:

/home/michelle/.config/inkscape/extensions/textext.py:55: DeprecationWarning: the md5 module is deprecated; use hashlib instead
import os, sys, tempfile, traceback, glob, re, md5, copy

PS: Why did I abandon SketchLatex so quickly, when it seemed so promising this morning? Simply because their website was down. Anyway, the Skencil GUI was a bit old-fashioned Unix-y anyway. That alone would not have stopped me from using it, but combined with other difficulties it becomes a problem. Hence going back to Inkscape
PPS: The only Inkscape drawing I’ve ever done was my little star website icon (see it up there? the purple star on the blue background?)

FFT Review

I haven’t done signal processing of any sort for a while now (that’s not to say I ever did very much of it) – but I occasionally find myself needing to do some filtering or frequency spectrum analysis. And as usual, I always need to look up how I did it before. I should really write myself a little cheat sheet. But since I don’t have time for that now, here’s a quick link: FFT Tutorial. It’s from someone in the EE department at the University of Rhode Island. I had a quick look and I like it because it provides some theory, and also a Matlab example (and it’s pretty clearly written using LaTeX – yeah!). And while I’m on the topic of signal processing, here’s a link to a tutorial by Richard Lyons: “Quadrature Signals, Complex but not Complicated“. I like this one because it has a movie trivia question on page 3. And I totally knew the answer without looking.

Python – matrices or arrays?

Sometimes I think I have my biggest breakthroughs while biking home. Tonight, for instance, it dawned on me (on the stretch between the beach and Patterson) just how awful the Matlab version of my ray tracing code really is. And I realised that I could vastly improve its simplicity and efficiency by using matrices (Yikes! Why on earth did I implement all of those nested loops?). I pictured the steps and the math involved, the Matlab commands that I would need, and got really excited – until I realized that I don’t know how to do any of the same stuff in Python yet. First of all, I need to figure out how to work with arrays in Matlab. Thankfully, there’s a special page on Scipy.org Matlab users who are trying to migrate to Numpy/Scipy. Yes! And here it is: Numpy for Matlab Users. My first question was, “How do I make it do element-wise operations?” In Matlab, you need to modify the operator, for example using “.*” to multiply by elements, and just “*” to do matrix multiplication. Matlab thinks in linear algebra for 2d matrices. But, as I quickly learned, the default array in Numpy does element by element operations, unless you create a special matrix object. Awesome.

LaTeX-ing again

Here I am, sitting indoors during a snowstorm, blundering my way through my raytracing script.  Ah, Snell’s law and optics.  What fun!  Anyhow, I realized that it was the perfect opportunity to practice some LaTeX skills.  I’ll be able to describe the theory of what I’m doing in my script.  Not that it’s anything complicated, but it’s enough for me to be able to practice some TeX-style math notation.  Sweet.

Here’s what I’ve got so far, using Emacs.  Easy!  No math yet though.

\documentclass[12pt]{article}
\title{Raytrace script – how it works}
\author{M. Weirathmueller}
\date{1 January 2010}
\begin{document}
\maketitle

\section{Indroduction}
This document is meant to accompany the my raytrace.py script, in an attempt to describe the theory behind what it’s doing.

The main idea is to read two sound speed profiles, and to compare depths computed by a multibeam echosounder for these profiles.

\section{theory}

\end{document}

(incidentally – I just discovered that WordPress source code posting supports LaTeX – fun!)

It was also the first time I’d ever compiled a LaTeX file from the command line. I know, I know, it’s no big deal. But it was new for me!

Created my PDF like this:

pdflatex raytrace.tex

Then looked at it in my PDF viewer like this:

gnome-open raytrace.pdf

gnome-open just opens the file with the default program for that extension. Also – I added an alias to my .bashrc file so that just typing “g file.pdf” works like “gnome-open file.pdf”.