Its been ages since I did any proper C/C++ so I had to remind myself of a few things, particularly the compilation of libraries. Libraries are really useful as it simplifies multiple use and sharing of components. I'm a Linux person so I'm going to look at this with a Linux hat on. In Linux there are two types; Static libraries (.a) and dynamically linked shared object libraries (.so). Let take a look at static libraries.
Lets create a library, firstly lets define some code, say in a file example1.c:
To create a library you can do:
cc -c example1.c
which compiles the code. Then you need to make the libary:
ar -cvq libexample.a example1.o
(you can of course include other object files here)
Say you call the function in you maincode.c to now compile this do:
I spend a lot of my time working on noise statistics and of course and an important part of this is how to fit signals. I was asked earlier for an example code on how to fit a Gaussian, in particular fitting well defined signals. In python this is quite straight forward as you already have a bunch of nice libraries to count on.
So the first thing todo is to ensure you have these libraries. These are scipy, numpy, matplotlib and asciidata. Of course, you don't need matplotlib if you don't want todo the plotting but or asciddata if you don't want to import an ascii file. (note: to students in 3rd year obs lab at Brum - you have this on hydra)
If you want to create some test data you can do something like:
from pylab import *
gaussian = lambda x: 1*exp(-(3-x)**2/10.) #change the parameters as you see fit
data = gaussian(arange(100))
x_pos = arange(100)
Now on to the fitting, this is simplistic and works well with "clean" data.
import warnings
warnings.simplefilter("ignore",DeprecationWarning)
import matplotlib
matplotlib.use('Agg') #avoid X11 issues.
import scipy, numpy, pylab, asciidata
from numpy import *
from pylab import *
from scipy import *
from scipy.optimize import leastsq
data = "test_gauss.dat" #your input data - should be x,y
demo = asciidata.open(data)
x_pos = double(demo[0]) #this is expected to be pixel number
y_power = double(demo[1])
v0= [1.0,mean(x_pos),1.0] #inital guesses for Gaussian Fit. $just do it around the peak
out = leastsq(e_gauss_fit, v0[:], args=(x_pos, y_power), maxfev=100000, full_output=1) #Gauss Fit
v = out[0] #fit parammeters out
covar = out[1] #covariance matrix output
xxx = arange(min(x_pos),max(x_pos),x_pos[1]-x_pos[0])
ccc = gauss_fit(v,xxx) # this will only work if the units are pixel and not wavelength
fig = figure(figsize=(9, 9)) #make a plot
ax1 = fig.add_subplot(111)
ax1.plot(x_pos,y_power,'gs') #spectrum
ax1.plot(xxx,ccc,'b--') #fitted spectrum
ax1.axvline(x=xxx[where(ccc == max(ccc))[0]][0],color='r') #max position in data
setp(gca(), ylabel="power", xlabel="pixel position")
pylab.savefig("plotfitting.png")
Download this, change the input data parameter to your asciifile and run as simplegaussfit.py - ensuring you have the correct file permissions to execute (you can change this with chmod).
Yesterday I showed you [how to fit a single Gaussian in some data]. Today lets deal with the case of two Gaussians. This came about due to some students trying to fit two Gaussian's to a shell star as the spectral line was altered from a simple Gaussian, actually there is a nice P-Cygni dip in there data so you should be able to recover the absorption line by this kind of fitting. Anyway, fitting 2 Gaussian's is basically the same thing as fitting one in python but with the added function. I'm thinking I'll work up how to deal with a whole spectrum including source finding. In this case what you have to deal with is that there are two sources and so a rough estimation of the peak position of both is crucial to the fit (well in the way it is implemented).
You basically want to end up with something like this:
Where the green points are the data, the blue dashed line the fit and the red line where the maximum is in the array. The fitting is done via a least-squares fitting routine.
In this example we will first start by generating some data, skipping the input from a file (but you can use the code from the 1 Gaussian example).
import scipy, numpy, pylab, asciidata
from numpy import *
from pylab import *
from scipy import *
from scipy.optimize import leastsq
#generate some data
gaussian = lambda x: 3*exp(-(10-x)**2/10.) + 1*exp(-(30-x)**2/10.)#change the parameters as you see fit
y_power = gaussian(arange(100))
x_pos = arange(100)
v0= [1,10,1,1,30,1] #inital guesses for Gaussian Fit. - just do it around the peaks
out = leastsq(e_gauss_fit, v0[:], args=(x_pos, y_power), maxfev=100000, full_output=1) #Gauss Fit
v = out[0] #fit parameters out
covar = out[1] #covariance matrix output
xxx = arange(min(x_pos),max(x_pos),x_pos[1]-x_pos[0])
ccc = gauss_fit(v,xxx) # this will only work if the units are pixel and not wavelength
fig = figure(figsize=(9, 9)) #make a plot
ax1 = fig.add_subplot(111)
ax1.plot(x_pos,y_power,'gs') #spectrum
ax1.plot(xxx,ccc,'b--') #fitted spectrum
ax1.axvline(x=xxx[where(ccc == max(ccc))[0]][0],color='r') #max position in data
setp(gca(), ylabel="power", xlabel="pixel position")
pylab.savefig("plotfitting.png")
Probably not the best picture I'll ever take of this source, I blame the bright moon, but here is a picture of the Christmas Tree Cluster that we took last night....
We know that the spectra, by looking at the FITS file with DS9 has data in a small aperture. For now we will ignore any averaging. Lets take line 144 as we know there is data.
We have now extracted the data for a spectral column. I will follow this post up in the not to distant future with how to now identify the lines and run spectral calibration. Once you have this you can apply to a target spectra. Of course I've so far also ignored dark/bias counts but these can be easily dealt with.
I had an odd CASA issue yesterday. It was complaining about missing leap second information for TAI_UTC! Seemed really quite odd to me as I hadn't done anything to my installation... anyway simple fix is to update the latest leap second information into CASA by running a simple command in the root casa install directory:
cd $CASA_ROOT/data
rsync -avz rsync.aoc.nrao.edu::casadata .
A simple example, very similar to that given in the CFITSIO guidebook, on how to create a FITS file using CFITSIO. In this case I'm also building against some casacore libraries, but these aren't going to be used in this little code snippet but the idea is to use casacore todo further analysis. I'm hoping to post more here over time. Anyway the code (this can also be found as a filebuild_fits.cpp:
/* Create a FITS file, using cfitsio and some casacore libraries
by Samuel George
21-11-2011
Compile: g++ build_fits.cpp -o build_fits -lcasa_casa -lcfitsio
*/
#include // STL iostream
#include
#include
extern "C"{
#include
}
using std::cerr;
using std::cout;
using std::endl;
using std::string;
int main()
{
cout << "Create a FITS file" << endl;
int lenTime(10), status (0), lenFreq(20);
long naxis(2), naxes[2] = {lenTime,lenFreq};
long nelements (lenTime*lenFreq);
long fpixel (1), exposure (1500);
char comment[] ="Total Exposure Time";
cout << comment << endl;
float pixels[lenFreq][lenTime];
// create an array of pixels
try {
for (int ii(0); ii < lenTime; ii++){
for (int jj(0); jj
pixels[jj][ii] = 10.0*(ii+jj);
}
}
} catch (string message) {
cerr << "Error creating pixel array" << message << endl;
}
try { // write the image to a fits file...
fitsfile *fptr;
fits_create_file (&fptr, "!output.fits", &status);
fits_create_img (fptr, FLOAT_IMG,naxis,naxes,&status);
/* Write a keyword - its the address you pass */
fits_update_key(fptr,TLONG,"EXPOSURE",&exposure,comment,&status);
//write an array to the image
fits_write_img(fptr, TFLOAT, fpixel, nelements, pixels[0],&status);
fits_close_file(fptr,&status);
status = 0 ;
} catch (std::string message) {
cerr << message << endl;
}
}
It wasn't particularly clear during our observing session, which was mostly aimed at taking a look at the ISS and Jupiter with our own eyes, but we focused the Meade out at Wast Hills and took a couple of images...
If you change the contrast a little you can clearly see the Moons:
It was rather cloudy but we still managed a short exposure of the Dumbbell Nebula:
2011 will always be one of the most memorable years in my life - it better be as I did get married :-)
The year started off with me being back in the UK for my birthday which was great but my time at home was all to short and I jetted back off to Calgary (Canada). It is always a sad time to end up back in an empty flat far away from family. Though saying that I do have some
epic friends out in Calgary too. Once back in Calgary it wasn't long before I was trying out something new... yep I went snowboarding for the first time:
Was painful and so far has turned out to be the last time. I just can't believe how poor my balance is.
In March my best-man Steve came over to visit me in Calgary and that was a lot of fun. Amongst the highlights of his trip over where seeing ice sculptures (and standing on the lake) at Lake Louise:
In May, I said goodbye to Calgary as I had been offered a position at the University of Cambridge, back in the UK. I have to say I'm very glad to have come home and can spend a lot more time with my beautiful wife but I'll always have very fond memories of Calgary and miss lots about it - in particular the people. I wrote a detailed review of my time in Calgary. Though before I left Calgary I got to go to the wonderfully named small town of Vulcan:
Before I left Calgary I had a bit of a shock with a health issue, all was fine but lets just say I've since changed my work all hours, cut out go out drinking lots and living off caffeine.
July was a very busy time. We were heavily involved in Wedding preparation though I did manage to stop for a few bits of fun. This included going to the British Grand Prix for the first time. Yes, it rained - it was a great time though.
July also involved my stag do, but we don't talk about that. It was great fun... we went go karting, had burgers and drank. Epic times.I even won a laser quest:
August... well this was a hectic month but all got more relaxed after the 19th. On the 19th we got married:
most of the better pictures aren't mine and well I feel bad about linking them so won't
(I wrote lots about the preparations before)
In November I got to go to the University of Birmingham Vale Fireworks for the first time in 2 years so I was quite pleased - always
feels good to celebrate the saving of parliament by blowing up part of the country:
and now its December. December has been a hectic month, and we are moving down to Cambridge in the new year so busy busy but we did manage to go out observing the other week and capture the Christmas tree cluser. Merry Christmas!
I'm looking forward to 2012... should be lots of fun. So far I have lots of observing planned, trip to India in Feb and tickets for the Olympics (alas just football). As a friend of mine said to me recently einen guten Rutsch ins neue Jahr
At the end of each year, yes I know I'm a few days early but bah I have to move house at the start of the new year, I like to summarise the music I've been listening to. The last few years have been much easier as last.fm keeps hold of that info. I suspect that its missing about 20% of the music I listen to, which isn't scrobbled for one reason and another. It might be a little higher than that but I don't like to include the car journeys when we are using the CD player.
I was a little shocked to see the number 1 artist of the year, and indeed a few different names in the top 10. I'm putting this down to a Calgary scene influence... (number, artist, plays)
1 Daft Punk 1,163
2 Linkin Park 664
3 Avril Lavigne 552
4 My Chemical Romance 526
5 Tiƫsto 522
6 Rise Against 285
7 Angels & Airwaves 271
8 Dead by April 259
9 Lostprophets 239
10 Disturbed 238
I have to say I did love the Daft Punk Tron album so I'm guessing this is what dominates that. I also find Tiesto quite good for background music whilst I'm reading (in particular I really think Kaleidoscope fits in really well with the Garth Nix books I've been reading).
Not that much new for 2011 in this list though. Wonder if that will change in 2012.
Been handed a dead hard drive and want to try and recover some of the data? That's the problem I had the other day. So I turned to some good old linux tools to try and recover the data. One of my favourite recovery tools is ddrescue. It works really well and given enough time can do a pretty solid job of data recovery - of course a better solution is proper backups but that's not always the way people go. Anyway, this is as much a note for myself but here is how to do some basic recovery using it:
sudo ddrescue -r 3 /dev/sde2 imaging loging
This images /dev/sed2 and produces the image file "imaging" with the log "logging".
To try and extract files you could use something like foremost
sudo foremost -w -i imaging -o /recovery/foremost
To make an audit of the files that can be recovered, recovering them with: