extern crate fitsio;
#[macro_use]
extern crate fitsio_derive;
extern crate tempdir;
use std::error::Error;
use tempdir::TempDir;
use fitsio::FitsFile;
use fitsio::fitsfile::{FitsRow, ImageDescription};
use fitsio::types::ImageType;
use fitsio::columndescription::{ColumnDataType, ColumnDescription};
fn run() -> Result<(), Box<Error>> {
let tmp_dir = TempDir::new("fitsio")?;
let file_path = tmp_dir.path().join("example.fits");
let primary_hdu_description = ImageDescription {
data_type: ImageType::Double,
dimensions: &[512, 1024],
};
{
let mut fitsfile = FitsFile::create(&file_path)
.with_custom_primary(&primary_hdu_description)
.open()?;
let hdu = fitsfile.primary_hdu()?;
hdu.write_key(&mut fitsfile, "PROJECT", "My First Astronomy Project")?;
hdu.write_key(&mut fitsfile, "EXPTIME", 15.2f32)?;
hdu.write_key(&mut fitsfile, "IMAGE_ID", 20180101010005i64)?;
let dummy_data: Vec<f32> = (0..(1024 * 512))
.map(|val| (val as f32) * 12.5 + 102.5)
.collect();
hdu.write_image(&mut fitsfile, &dummy_data)?;
let image_description = ImageDescription {
data_type: ImageType::Long,
dimensions: &[256, 256],
};
fitsfile.create_image("IMG", &image_description)?;
let col1 = ColumnDescription::new("OBJ_ID")
.with_type(ColumnDataType::Int)
.create()?;
let col2 = ColumnDescription::new("NAME")
.with_type(ColumnDataType::String)
.that_repeats(10)
.create()?;
let col3 = ColumnDescription::new("MAG")
.with_type(ColumnDataType::Float)
.create()?;
let columns = &[col1, col2, col3];
let table_hdu = fitsfile.create_table("DATA", columns)?;
let n_rows = 10;
let obj_id_data: Vec<i32> = (0..n_rows).collect();
let name_data: Vec<String> = (0..n_rows).map(|idx| format!("N{}", idx)).collect();
let mag_data: Vec<f32> = (0..n_rows).map(|idx| -0.2 * idx as f32).collect();
table_hdu.write_col(&mut fitsfile, "OBJ_ID", &obj_id_data)?;
table_hdu.write_col(&mut fitsfile, "NAME", &name_data)?;
table_hdu.write_col(&mut fitsfile, "MAG", &mag_data)?;
}
let mut fitsfile = FitsFile::edit(&file_path)?;
fitsfile.pretty_print().expect("printing fits file");
let phdu = fitsfile.primary_hdu()?;
let image_data: Vec<f32> = phdu.read_region(&mut fitsfile, &[&(19..29), &(19..29)])?;
assert_eq!(image_data.len(), 100);
let table_hdu = fitsfile.hdu("DATA")?;
let magnitudes: Vec<f32> = table_hdu.read_col_range(&mut fitsfile, "MAG", &(3..6))?;
assert_eq!(magnitudes.len(), 3);
#[derive(Default, FitsRow)]
struct Row {
#[fitsio(colname = "OBJ_ID")]
obj_id: i32,
#[fitsio(colname = "NAME")]
name: String,
#[fitsio(colname = "MAG")]
mag: f32,
}
let row: Row = table_hdu.row(&mut fitsfile, 4)?;
assert_eq!(row.obj_id, 4);
assert_eq!(row.name, "N4");
assert!(row.mag > -1.0 && row.mag < -0.5);
Ok(())
}
fn main() {
run().unwrap();
}