BOOT CAMP

Astropy: A Community Python Library for Astronomy

Astropy: A Community Python Library for Astronomy

iPTF Workshop | 25 August 2014 | Leo Singer | California Insitute of Technology

An XKCD commic about Python

An XKCD commic about Python

^ XKCD comic #353, 'Python', by Randall Munroe

A little girl goes into a pet show and asks for a wabbit. The shop keeper looks down at her, smiles and says:

"Would you like a lovely fluffy little white rabbit, or a cutesy wootesly little brown rabbit?"

"Actually", says the little girl, "I don't think my python would notice."

—Nick Leaton, Wed, 04 Dec 1996

I. Introduction

This workshop is about doing astronomical data analysis with the Python programming language. No previous experience with Python is necessary!

Python is a powerful tool, but it comes into its own as a numerical and data analysis environment with the following packages, which you will definitely want to have:

  • Matplotlib: plotting interactive or publication-quality figures
  • Numpy: vectorized arithmetic and linear algebra
  • Scipy: curated collection of algorithms for root finding, interpolation, integration, signal processing, statistics, linear algebra, and much more
  • IPython Notebook, the Mathematica-like interface that you are using now, and last but not least
  • Astropy, a community library for astronomy. See also Robitaille et al. (2013).

We'll cover the basics of Python itself and then dive in to some applications to explore each of these packages.

NOTE: The purest way of interacting with Python is via its command line interpreter, which looks like this:

A session in the Python command line interpreter

A session in the Python command line interpreter

However, a relatively new but very powerful way of using Python is through the IPython Notebook interface, which like Mathematica allows you to intermingle computer code with generated plots...

In [1]:
x = np.linspace(0, 2 * np.pi)
plt.plot(x, np.sin(x))
plt.xlabel('ppm caffeine in bloodstream')
plt.ylabel('cheeriness')
Out[1]:
<matplotlib.text.Text at 0x10de5bd50>

and tables...

In [2]:
import astropy.table
tbl = astropy.table.Table()
tbl.add_column(astropy.table.Column(data=np.arange(5),
    name='integers'))
tbl.add_column(astropy.table.Column(data=np.arange(5)**2,
    name='their squares'))
tbl
Out[2]:
integerstheir squares
00
11
24
39
416

and even notes and typeset mathematics...

And God said:

\[\nabla \cdot \mathbf{D} = \rho\] \[\nabla \cdot \mathbf{B} = 0\] \[\nabla \times \mathbf{E} = -\frac{\partial\mathbf{B}}{\partial t}\] \[\nabla \times \mathbf{H} = J + \frac{\partial\mathbf{D}}{\partial t}\]

and there was light.

This is all very useful for doing interactive data analysis, so we will use the IPython Notebook interface for this tutorial. WARNING: I'm spoiling you rotten by doing this.


II. How to get Python/Matplotlib/Numpy/Scipy

Python and all of the packages that we discuss in this tutorial are open source software, so there multiple options for installing them.

Anaconda and Canopy are free, self-contained Python distributions for Linux, Mac, Windows. Both come with an excellent selection of up-to-date scientific Python libraries, including Astropy.

TIP These are both great Python environments for everyday use. If you need the latest version of Python in a headless environment like a cluster or web server, consider the lightweight Miniconda distribution.

Advanced: Debian/Ubuntu

Most operating systems already come with Python. Release schedules vary, but generally the 'testing' versions of Debian and Ubuntu come with very up-to-date versions of Python. Debian Jessie and Ubuntu 13.10 (Saucy Salamander) both come with the latest version of Astropy. On these systems, you can set up a pretty complete Python environment with:

$ sudo apt-get install ipython-notebook python-matplotlib python-scipy python-pip python-astropy

Advanced: MacPorts

Every version of Mac OS comes with a Python interpreter, but it's slightly easier to obtain Matplotlib and Numpy if you use a package manager such as MacPorts, HomeBrew, or Fink. I use MacPorts (and contribute to it, too), so that's what I suggest. Install MacPorts and then do:

$ sudo port install py27-pip py27-matplotlib py27-scipy py27-astropy py27-ipython +notebook

How to install Python packages

The Python community has developed a huge collection of packages for various tasks. The best place to find Python libraries is the Python Package Index (PyPI, https://pypi.python.org/).

No matter how you installed Python, you can install any Python package from PyPI using pip. For example:

$ pip install astroquery

or

$ pip install --user astroquery

In Anaconda, you can also install some popular packages using conda. On Debian or Ubuntu, you can get many Python packages with apt-get and on MacPorts with port.


IV. Python basics

The print statement and string literals

If this is your first time looking at Python code, the first thing that you might notice is that it is very easy to understand. For example, to print something to the screen, it's just:

In [3]:
print 'Hello world!'
Hello world!

Note: print changed from a built-in statement to a function in Python 3. If you are using Python 3, just put the arguments in parentheses. To get this behavior in previous versions of Python, put this at the top of your script:

from __future__ import print_function

This is a Python statement, consisting of the built-in command print and a string surrounded by single quotes. Double quotes are fine inside a string:

In [4]:
print 'She said, "Hello, world!"'
She said, "Hello, world!"

But if you want single quotes inside your string, you had better delimit it with double quotes:

In [5]:
print "She said, 'Hello, world!'"
She said, 'Hello, world!'

If you need both single quotes and double quotes, you can use backslashes to escape characters.

In [6]:
print 'She said, "O brave new world, that has such people in\'t!"'
She said, "O brave new world, that has such people in't!"

If you need a string that contains newlines, use triple quotes (''') or triple double quotes ("""):

In [7]:
print """MIRANDA
  O, wonder!
  How many goodly creatures are there here!
  How beauteous mankind is! O brave new world
  That has such people in't!"""
MIRANDA
  O, wonder!
  How many goodly creatures are there here!
  How beauteous mankind is! O brave new world
  That has such people in't!

Let's say that you need to print a few different things on the same line. Just separate them with commas, as in:

In [8]:
person = 'Miranda'
print "'Tis new to", person
'Tis new to Miranda

Oops. I'm getting ahead of myself—you've now seen your first variable assignment in Python. Strings can be concatened by adding them:

In [9]:
'abc' + 'def'
Out[9]:
'abcdef'

Or repeated by multiplying them:

In [10]:
'abcdef' * 2
Out[10]:
'abcdefabcdef'

Numeric and boolean literals

Python's numeric types include integers and both real and complex floating point numbers:

In [11]:
a = 30 # an integer
b = 030 # WARNING! octal, =24 in decimal; probably not what you meant
c = 3.14159 # a floating point number
d = 5.1e10 # scientific notation
e = 2.5 + 5.3j # a complex number
hungry = True # boolean literal
need_coffee = False # another boolean literal

By the way, all of the text on a given line after the trailing hash sign (#) is a comment, ignored by Python.

The arithmetic operators in Python are similar to C, C++, Java, and so on. There is addition (and subtraction):

In [12]:
a + c
Out[12]:
33.14159

Multiplication:

In [13]:
a * e
Out[13]:
(75+159j)

Division:

In [14]:
a / c
Out[14]:
9.549304651466295

But beware that, like in C, C++, Java, etc., division of integers gives you integers:

In [15]:
7 / 3
Out[15]:
2

If you want true division, convert one or both of the operands to floating point:

In [16]:
a = 7
b = 3
float(a) / b
Out[16]:
2.3333333333333335

NOTE that in Python 3, division of integers is true division.

If you are using Python 2.2 or higher, you can enable true division by putting the following statement at the top of your script:

from __future__ import division

However, in both Python 2 and Python 3, the double-slash operator // represents integer division:

In [17]:
7 // 3
Out[17]:
2

The % sign is the remainder operator:

In [18]:
32 % 26
Out[18]:
6

Exponentiation is accomplished with the ** operator:

In [19]:
print 5 ** 3, 9**-0.5
125 0.333333333333

Tuples

A tuple is a sequence of values. It's just about the handiest thing since integers. A tuple is immutable: once you have created it, you cannot add items to it, remove items from it, or change items. Tuples are very handy for storing short sequences of related values or returning multiple values from a function. This is what tuples look like:

In [20]:
some_tuple = ('a', 'b', 'c')
another_tuple = ('caffeine', 6.674e-11, 3.14, 2.718)
nested_tuple = (5, 4, 3, 2, ('a', 'b'), 'c')

Once you have made a tuple, you might want to retrieve a value from it. You index a tuple with square brackets, starting from zero:

In [21]:
some_tuple[0]
Out[21]:
'a'
In [22]:
some_tuple[1]
Out[22]:
'b'

You can access whole ranges of values using slice notation:

In [23]:
nested_tuple[1:4]
Out[23]:
(4, 3, 2)

Or, to count backward from the end of the tuple, use a negative index:

In [24]:
another_tuple[-1]
Out[24]:
2.718
In [25]:
another_tuple[-2]
Out[25]:
3.14

Strings can be treated just like tuples of individual charaters:

In [26]:
person = 'Miranda'
print person[3:6]
and

Lists

What if you want a container like a tuple but to which you can add or remove items or alter existing items? That's a list. The syntax is almost the same, except that you create a list using square brackets [] instead of round ones ():

In [27]:
your_list = ['foo', 'bar', 'bat', 'baz']
my_list = ['xyzzy', 1, 3, 5, 7]

But you can change elements:

In [28]:
my_list[1] = 2
print my_list
['xyzzy', 2, 3, 5, 7]

Or append elements to an existing list:

In [29]:
my_list.append(11)
print my_list
['xyzzy', 2, 3, 5, 7, 11]

Or delete elements:

In [30]:
del my_list[0]
print my_list
[2, 3, 5, 7, 11]

Sets

Sometimes you need a collection of items where order doesn't necessarily matter, but each item is guaranteed to be unique. That's a set, created just like a list or tuple but with curly braces {}:

In [31]:
a = {5, 6, 'foo', 7, 7, 8}
print a
set([8, 'foo', 5, 6, 7])

You can add items to a set:

In [32]:
a.add(3)
print a
set([3, 5, 6, 7, 8, 'foo'])

Or take them away:

In [33]:
a.remove(3)

You also have set-theoretic intersections with the & operator:

In [34]:
{1, 2, 3, 4, 5, 6} & {3, 4}
Out[34]:
{3, 4}

And union with the | operator:

In [35]:
{1, 2, 3, 4, 5, 6} | {6, 7}
Out[35]:
{1, 2, 3, 4, 5, 6, 7}

And set difference with the - operator:

In [36]:
{1, 2, 3, 4, 5, 6} - {3, 4}
Out[36]:
{1, 2, 5, 6}

Dictionaries

Sometimes, you want a collection that is like a list, but whose indices are strings or other Python values. That's a dictionary. Dictionaries are handy for any type of database-like operation, or for storing mappings from one set of values to another. You create a dictionary by enclosing a list of key-value pairs in curly braces:

In [37]:
my_grb = {'name': 'GRB 130702A', 'redshift': 0.145, 'ra': (14, 29, 14.78), 'dec': (15, 46, 26.4)}
my_grb
Out[37]:
{'dec': (15, 46, 26.4),
 'name': 'GRB 130702A',
 'ra': (14, 29, 14.78),
 'redshift': 0.145}

You can index items in dictionaries with square braces [], similar to tuples or lists:

In [38]:
my_grb['dec']
Out[38]:
(15, 46, 26.4)

or add items to them:

In [39]:
my_grb['url'] = 'http://gcn.gsfc.nasa.gov/other/130702A.gcn3'
my_grb
Out[39]:
{'dec': (15, 46, 26.4),
 'name': 'GRB 130702A',
 'ra': (14, 29, 14.78),
 'redshift': 0.145,
 'url': 'http://gcn.gsfc.nasa.gov/other/130702A.gcn3'}

or delete items from them:

In [40]:
del my_grb['url']
my_grb
Out[40]:
{'dec': (15, 46, 26.4),
 'name': 'GRB 130702A',
 'ra': (14, 29, 14.78),
 'redshift': 0.145}

Dictionary keys can be any immutable kind of Python object: tuples, strings, integers, and floats are all fine. Values in a dictionary can be any Python value at all, including lists or other dictionaries:

In [41]:
{
    'foods': ['chicken', 'veggie burger', 'banana'],
    'cheeses': {'muenster', 'gouda', 'camembert', 'mozarella'},
    (5.5, 2): 42,
    'plugh': 'bat'
}
Out[41]:
{'cheeses': {'camembert', 'gouda', 'mozarella', 'muenster'},
 'foods': ['chicken', 'veggie burger', 'banana'],
 'plugh': 'bat',
 (5.5, 2): 42}

The None object

Sometimes you need to represent the absence of a value, for instance, if you have a gap in a dataset. You might be tempted to use some special value like -1 or 99 for this purpose, but don't! Use the built-in object None.

In [42]:
a = None

Conditionals

In Python, control flow statements such as conditionals and loops have blocks indicated with indentation. Any number of spaces or tabs is fine, as long as you are consistent within a block. Common choices include four spaces, two spaces, or a tab.

You can use the if...elif...else statement to have different bits of code run depending on the truth or falsehood of boolean expressions. For example:

In [43]:
a = 5

if a < 3:
    print "i'm in the 'if' block"
    messsage = 'a is less than 3'
elif a == 3:
    print "i'm in the 'elif' block"
    messsage = 'a is 3'
else:
    print "i'm in the 'else' block"
    message = 'a is greater than 3'

print message
i'm in the 'else' block
a is greater than 3

You can chain together inequalities just like in mathematical notation:

In [44]:
if 0 < a <= 5:
    print 'a is greater than 0 but less than or equal to 5'
a is greater than 0 but less than or equal to 5

You can also combine comparison operators with the boolean and, or, and not operators:

In [45]:
if a < 6 or a > 8:
    print 'yahoo!'
yahoo!

In [46]:
if a < 6 and a % 2 == 1:
    print 'a is an odd number less than 6!'
a is an odd number less than 6!

In [47]:
if not a == 5: # same as a != 5
    print 'a is not 5'

The comparison operator is tests whether two Python values are not only equal, but represent the same object. Since there is only one None object, the is operator is particularly useful for detecting None.

In [48]:
food = None

if food is None:
    print 'No, thanks'
else:
    print 'Here is your', food
No, thanks

Likewise, there is an is not operator:

In [49]:
if food is not None:
    print 'Yum!'

The in and not in operators are handy for testing for membership in a string, set, or dictionary:

In [50]:
if 3 in {1, 2, 3, 4, 5}:
    print 'indeed it is'
indeed it is

In [51]:
if 'i' not in 'team':
    print 'there is no "i" in "team"'
there is no "i" in "team"

When referring to a dictionary, the in operator tests if the item is among the keys of the dictionary.

In [52]:
d = {'foo': 3, 'bar': 5, 'bat': 9}
if 'foo' in d:
    print 'the key "foo" is in the dictionary'
the key "foo" is in the dictionary

The for and while loops

In Python, there are just two types of loops: for and while. for loops are useful for repeating a set of statements for each item in a collection (tuple, set, list, dictionary, or string). while loops are not as common, but can be used to repeat a set of statements until a boolean expression becomes false.

In [53]:
for i in [0, 1, 2, 3]:
    print i**2
0
1
4
9

The built-in function range, which returns a list of numbers, is often handy here:

In [54]:
for i in range(4):
    print i**2
0
1
4
9

Or you can have the range start from a nonzero value:

In [55]:
for i in range(-2, 4):
    print i**2
4
1
0
1
4
9

You can iterate over the keys and values in a dictionary with .items() or .iteritems():

In [56]:
for key, val in d.items():
    print key, '...', val**3
bat ... 729
foo ... 27
bar ... 125

The syntax of the while loop is similar to the if statement:

In [57]:
a = 1
while a < 5:
    a = a * 2
    print a
2
4
8

List comprehensions

Sometimes you need a loop to create one list from another. List comprehensions make this very terse. For example, the following for loop:

In [58]:
a = []
for i in range(5):
    a.append(i * 10)

is equivalent to this list comprehension:

In [59]:
a = [i * 10 for i in range(5)]

You can even incorporate conditionals into a list comprehension. The following:

In [60]:
a = []
for i in range(5):
    if i % 2 == 0:
        # i is even
        a.append(i * 10)

can be written as:

In [61]:
a = [i * 10 for i in range(5) if i % 2 == 0]

Conditional expressions

Conditional expressions are a closely related shorthand. The following:

In [62]:
if 6/2 == 3:
    a = 'foo'
else:
    a = 'bar'

is equivalent to:

In [63]:
a = 'foo' if 6/2 == 3 else 'bar'

Functions

Functions are created with the def statement. A function may either have or not have a return statement to send back a return value.

In [64]:
def square(n):
    return n * n

a = square(3)
print a
9

If you want to return multiple values from a function, return a tuple. Parentheses around the tuple are optional.

In [65]:
def powers(n):
    return n**2, n**3

print powers(3)
(9, 27)

If a function returns multiple values, you can automatically unpack them into multiple variables:

In [66]:
square, cube = powers(3)
print square
9

If you pass a mutable value such as a list to a function, then the function may modify that value. For example, you might implement the Fibonacci sequence like this:

In [67]:
def fibonacci(seed, n):
    while len(seed) < n:
        seed.append(seed[-1] + seed[-2])
    # Note: no return statement

seed = [1, 1]
fibonacci(seed, 10)
print seed
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

You can also give a function's arguments default values, such as:

In [68]:
def fibonacci(seed, n=6):
    """Fill a seed list with values from the Fibonacci sequence until
    it has length n."""
    # If the first line of a function is a string, then that string is
    # used to create online help for the function.
    while len(seed) < n:
        seed.append(seed[-1] + seed[-2])
    # Note: no return statement

seed = [1, 1]
fibonacci(seed)
print seed
[1, 1, 2, 3, 5, 8]

If a function has a large number of arguments, it may be easier to read if you pass the arguments by keyword, as in:

In [69]:
seq = [1, 1]
fibonacci(seed=seq, n=4)

Python standard library

Python comes with an extensive standard library consisting of individual modules that you can opt to use with the import statement. For example:

In [70]:
import math
math.sqrt(3)
Out[70]:
1.7320508075688772
In [71]:
from math import pi
pi
Out[71]:
3.141592653589793

Some particularly useful parts of the Python standard library are:

Error handling

It can be important for your code to be able to handle error conditions. For example, let's say that you are implementing a sinc function:

In [72]:
def sinc(x):
    return math.sin(x) / x

print sinc(0)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-72-0e6b1b141058> in <module>()
      2     return math.sin(x) / x
      3 
----> 4 print sinc(0)

<ipython-input-72-0e6b1b141058> in sinc(x)
      1 def sinc(x):
----> 2     return math.sin(x) / x
      3 
      4 print sinc(0)

ZeroDivisionError: float division by zero

Oops! We know that by definition \(\mathrm{sinc}(0) = 1\) , so we should catch this error:

In [73]:
def sinc(x):
    try:
        result = math.sin(x) / x
    except ZeroDivisionError:
        result = 1
    return result

print sinc(0)
1

Reading and writing files

The built-in open function opens a file and returns a file object that you can use to read or write data. Here's an example of writing data to a file:

In [74]:
myfile = open('myfile.txt', 'w') # open file for writing
myfile.write("red 1\n")
myfile.write("green 2\n")
myfile.write("blue 3\n")
myfile.close()

And here is reading it:

In [75]:
d = {} # create empty dictionary

for line in open('myfile.txt', 'r'): # open file for reading
    color, num = line.split() # break apart line by whitespace
    num = int(num) # convert num to integer
    d[color] = num # 

print d
{'blue': 3, 'green': 2, 'red': 1}

V. Numpy & Matplotlib

Numpy provides array operations and linear algebra to Python. A Numpy array is a bit like a Python list, but supports elementwise arithmetic. For example:

In [76]:
import numpy as np

x = np.asarray([1, 2, 3, 4, 5])
y = 2 * x
print y
[ 2  4  6  8 10]

Numpy arrays may have any number of dimensions:

In [77]:
x = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
x
Out[77]:
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
In [78]:
y = np.asarray([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
y
Out[78]:
array([[9, 8, 7],
       [6, 5, 4],
       [3, 2, 1]])

An array has a certain number of dimensions denoted .ndim:

In [79]:
x.ndim
Out[79]:
2

and the dimensions' individual lengths are given by .shape:

In [80]:
x.shape
Out[80]:
(3, 3)

and the total number of elements by .size:

In [81]:
x.size
Out[81]:
9

By default, multiplication is elementwise:

In [82]:
x * y
Out[82]:
array([[ 9, 16, 21],
       [24, 25, 24],
       [21, 16,  9]])

To perform matrix multiplication, either convert arrays to np.matrix or use np.dot:

In [83]:
np.asmatrix(x) * np.asmatrix(y)
Out[83]:
matrix([[ 30,  24,  18],
        [ 84,  69,  54],
        [138, 114,  90]])
In [84]:
np.dot(x, y)
Out[84]:
array([[ 30,  24,  18],
       [ 84,  69,  54],
       [138, 114,  90]])

You can also perform comparison operations on arrays...

In [85]:
x > 5
Out[85]:
array([[False, False, False],
       [False, False,  True],
       [ True,  True,  True]], dtype=bool)

Although a boolean array doesn't directly make sense in an if statement:

In [86]:
if x > 5:
    print 'oops'
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-86-10c0a9479885> in <module>()
----> 1 if x > 5:
      2     print 'oops'

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [87]:
if np.any(x > 5):
    print 'at least some elements are greater than 5'
at least some elements are greater than 5

You can use conditional expressions like indices:

In [88]:
x[x > 5] = 5
x
Out[88]:
array([[1, 2, 3],
       [4, 5, 5],
       [5, 5, 5]])

Or manipulate individual rows:

In [89]:
x[1, :] = -1
x
Out[89]:
array([[ 1,  2,  3],
       [-1, -1, -1],
       [ 5,  5,  5]])

Or individual columns:

In [90]:
x[:, 1] += 100
x
Out[90]:
array([[  1, 102,   3],
       [ -1,  99,  -1],
       [  5, 105,   5]])

Other useful features include various random number generators:

In [91]:
from matplotlib import pyplot as plt

# Plot histogram of 10k normal random variates
plt.hist(np.random.randn(10000))
Out[91]:
(array([  1.00000000e+00,   1.80000000e+01,   2.23000000e+02,
          9.84000000e+02,   2.43700000e+03,   3.10900000e+03,
          2.26300000e+03,   7.91000000e+02,   1.57000000e+02,
          1.70000000e+01]),
 array([-4.38088429, -3.57238871, -2.76389312, -1.95539754, -1.14690195,
        -0.33840637,  0.47008922,  1.2785848 ,  2.08708039,  2.89557598,
         3.70407156]),
 <a list of 10 Patch objects>)
In [92]:
np.random.uniform(low=0, high=2*np.pi)
Out[92]:
2.4532995610657253

You've already seen a few examples of Matplotlib. If you have used MATLAB, then Matplotlib code may look familiar.

In [93]:
x = np.linspace(-10, 10)
y = 1 / (1 + np.exp(x))
plt.plot(x, y)
plt.annotate(
    'foo bar', (x[20], y[20]), (50, 5),
    textcoords='offset points',
    arrowprops={'arrowstyle': '->'})
plt.grid()

VII. Astropy

Astropy is a core Python package for astronomy. It is formed from the merger of a number of other Python astronomy packages, but also contains a lot of original code. Core features include:

  • astropy.constants, astropy.units: Physical constants, units, and unit conversion
  • astropy.time: Manipulation of dates and times
  • astropy.coordinates: Representation of and conversion between astronomical coordinate systems
  • astropy.table: Tables and gridded data
  • astropy.io.fits: Manipulating FITS files
  • astropy.io.ascii: Manipulating ASCII tables of many different formats
  • astropy.io.votable: Virtual Observatory tables
  • astropy.wcs: World Coordinate System transformations
  • astropy.cosmology: Cosmological calculations
  • astropy.stats: Astrostatistics
  • astropy.modeling: multi-D model fitting Swiss army knife

The Astropy project also has sevearl "affiliated packages" that have similar design but are maintained separately, including:

  • APLPy: High-level astronomical map making with Matplotlib
  • WCSAxes: Nuts-and-bolts astronomical mapmaking for Matplotlib experts
  • Photutils: Aperture photometry
  • Astroquery: Query astronomical databases

Let's experiment by opening up a P48 image. We'll need several modules from the Astropy package for this exercise.

In [94]:
import astropy.coordinates
import astropy.units as u
import astropy.io.fits
import astropy.stats
import astropy.table
import astropy.wcs
import astropy.cosmology
import scipy.optimize
import scipy.odr

I've downloaded a P48 image and put it in the same directory as this noteobook for you.

In [95]:
fits = astropy.io.fits.open('PTF_201307021787_i_p_scie_t041723_u016616794_f02_p003486_c11.fits')
fits
Out[95]:
[<astropy.io.fits.hdu.image.PrimaryHDU at 0x10eb36050>]

Let's grab the first (and only) HDU of this FITS file:

In [96]:
hdu = fits[0]

Then let's take a look at the contents of the header:

In [97]:
hdu.header
Out[97]:
SIMPLE  =                    T / Fits standard                                  
BITPIX  =                  -32 / FOUR-BYTE SINGLE PRECISION FLOATING POINT      
NAXIS   =                    2 / STANDARD FITS FORMAT                           
NAXIS1  =                 2048 / STANDARD FITS FORMAT                           
NAXIS2  =                 4096 / STANDARD FITS FORMAT                           
ORIGIN  = 'Palomar Transient Factory' / Origin of these image data              
CREATOR = 'Infrared Processing and Analysis Center' / Creator of this FITS file 
TELESCOP= 'P48     '           / Name of telescope                              
INSTRUME= 'PTF/MOSAIC'         / Instrument name                                
OBSERVER= 'KulkarniPTF'        / Observer name and project                      
CCDID   = '11      '           / CCD number (0..11)                             
DATE-OBS= '2013-07-02T04:17:23.555' / UTC shutter time YYYY-MM-DDTHH:MM:SS.SSS  
DATE    = '2013-07-01T21:35:19' / File creation date (YYYY-MM-DDThh:mm:ss UT)   
REFERENC= 'http://www.astro.caltech.edu/ptf' / URL of PTF website               
                                                                                
          / PROPOSAL INFORMATION                                                
                                                                                
PTFPRPI = 'Kulkarni'           / PTF Project PI                                 
PTFPID  = '30011   '           / Project type: 00000-49999                      
OBJECT  = 'PTF_survey'         / Fields object                                  
PTFFIELD= '3486    '           / PTF unique field ID                            
PTFFLAG = '1       '           / 1 = PTF; 0 = non-PTF category                  
                                                                                
          / TIME AND EXPOSURE INFORMATION                                       
                                                                                
FILTER  = 'R       '           / Filter name                                    
FILTERID= '2       '           / Filter ID                                      
FILTERSL= '1       '           / Filter changer slot position                   
EXPTIME =                  60. / [s] Requested exposure time                    
AEXPTIME=                  60. / actual exposure time (sec)                     
UTC-OBS = '2013-07-02T04:17:23.555' / UTC time shutter open YYYY-MM-DDTHH:MM:SS.
OBSJD   =        2456475.67874 / [day] Julian day corresponds to UTC-OBS        
OBSMJD  =          56475.17874 / MJD corresponds to UTC-OBS (day)               
OBSLST  = '15:11:26.46'        / Mean LST corresponds to UTC-OBS 'HH:MM:SS.S'   
HOURANG = '0:48:14.61'         / Mean HA (sHH:MM:SS.S) based on LMST at UTC-OBS 
HJD     =        2456475.68019 / [day] Heliocentric Julian Day                  
OBSTYPE = 'object  '           / Image type (dark,science,bias,focus)           
IMGTYP  = 'object  '           / Image type (dark,science,bias,focus)           
                                                                                
          / MOON AND SUN                                                        
                                                                                
MOONRA  =             30.98457 / [deg] Moon J2000.0 R.A.                        
MOONDEC =            12.984756 / [deg] Moon J2000.0 Dec.                        
MOONILLF=            -0.306369 / [frac] Moon illuminated fraction               
MOONPHAS=             247.2158 / [deg] Moon phase angle                         
MOONESB =                  -0. / Moon excess in sky brightness V-band           
MOONALT =            -40.94289 / [deg] Moon altitude                            
SUNAZ   =             310.3019 / [deg] Sun azimuth                              
SUNALT  =            -14.00398 / [deg] Sun altitude                             
                                                                                
          / PHOTOMETRY                                                          
                                                                                
BUNIT   = 'DN      '           / Data number (analog-to-digital units or ADU)   
PHTCALEX=                    1 / Was phot.-cal. module executed?                
PHTCALFL=                    1 / Flag for image is photometric (0=N, 1=Y)       
PCALRMSE=             0.215766 / RMSE from (zeropoint, extinction) data fit     
IMAGEZPT=             23.72382 / Image magnitude zeropoint                      
COLORTRM=            -0.012228 / Image color term (g-r)                         
ZPTSIGMA=             1.886777 / Robust dispersion of SEx-SDSS magnitudes       
IZPORIG = 'SDSS    '           / Photometric-calibration origin                 
ZPRULE  = 'DIRECT  '           / Photometric-calibration method                 
MAGZPT  =             23.77773 / Magnitude zeropoint at airmass=1               
EXTINCT =            -0.195707 / Extinction                                     
APSFILT = 'r       '           / SDSS filter used in abs phot cal               
APSCOL  = 'r-i     '           / SDSS color used in abs phot cal                
APRMS   =           0.05618604 / RMS in mag of final abs phot cal               
APBSRMS =            0.0344094 / RMS in mag of final abs phot cal for bright sta
APNSTDI1=               177080 / Number of standard stars in first iteration    
APNSTDIF=               160107 / Number of standard stars in final iteration    
APCHI2  =      771280.24477198 / Chi2 of final abs phot cal                     
APDOF   =              160096. / Dof of chi2 of final abs phot cal              
APMEDJD =     2456475.80246722 / Median JD used in abs phot cal                 
APPN01  = 'ZeroPoint'          / Name of parameter abs phot cal 01              
APPAR01 =          23.68493517 / Value of parameter abs phot cal 01             
APPARE01=            0.0026937 / Error of parameter abs phot cal 01             
APPN02  = 'ColorTerm'          / Name of parameter abs phot cal 02              
APPAR02 =          -0.03174945 / Value of parameter abs phot cal 02             
APPARE02=           0.00383537 / Error of parameter abs phot cal 02             
APPN03  = 'AirMassTerm'        / Name of parameter abs phot cal 03              
APPAR03 =          -0.28459543 / Value of parameter abs phot cal 03             
APPARE03=           0.00226667 / Error of parameter abs phot cal 03             
APPN04  = 'AirMassColorTerm'   / Name of parameter abs phot cal 04              
APPAR04 =           0.24261075 / Value of parameter abs phot cal 04             
APPARE04=           0.00313212 / Error of parameter abs phot cal 04             
APPN05  = 'TimeTerm'           / Name of parameter abs phot cal 05              
APPAR05 =           0.19911481 / Value of parameter abs phot cal 05             
APPARE05=           0.00219937 / Error of parameter abs phot cal 05             
APPN06  = 'Time2Term'          / Name of parameter abs phot cal 06              
APPAR06 =           1.65698453 / Value of parameter abs phot cal 06             
APPARE06=           0.02684713 / Error of parameter abs phot cal 06             
APPN07  = 'XTerm   '           / Name of parameter abs phot cal 07              
APPAR07 =           0.02703671 / Value of parameter abs phot cal 07             
APPARE07=           0.00053429 / Error of parameter abs phot cal 07             
APPN08  = 'YTerm   '           / Name of parameter abs phot cal 08              
APPAR08 =          -0.01528394 / Value of parameter abs phot cal 08             
APPARE08=           0.00131972 / Error of parameter abs phot cal 08             
APPN09  = 'Y2Term  '           / Name of parameter abs phot cal 09              
APPAR09 =           0.00938432 / Value of parameter abs phot cal 09             
APPARE09=           0.00208283 / Error of parameter abs phot cal 09             
APPN10  = 'Y3Term  '           / Name of parameter abs phot cal 10              
APPAR10 =           0.03443254 / Value of parameter abs phot cal 10             
APPARE10=           0.00825142 / Error of parameter abs phot cal 10             
APPN11  = 'XYTerm  '           / Name of parameter abs phot cal 11              
APPAR11 =           0.01025838 / Value of parameter abs phot cal 11             
APPARE11=           0.00188474 / Error of parameter abs phot cal 11             
                                                                                
          / ASTROMETRY                                                          
                                                                                
WCSAXES =                    2 / Number of axes in world coordinate system      
CRVAL1  =     217.309490953823 / [deg] RA of reference point                    
CRVAL2  =     16.6581466832508 / [deg] DEC of reference point                   
CRPIX1  =             1497.193 / [pix] Image reference point                    
CRPIX2  =             609.3031 / [pix] Image reference point                    
CTYPE1  = 'RA---TAN-SIP'       / TAN (gnomic) projection + SIP distortions      
CTYPE2  = 'DEC--TAN-SIP'       / TAN (gnomic) projection + SIP distortions      
CUNIT1  = 'deg     '           / Image axis-1 celestial-coordinate units        
CUNIT2  = 'deg     '           / Image axis-2 celestial-coordinate units        
CRTYPE1 = 'deg     '           / Data units of CRVAL1                           
CRTYPE2 = 'deg     '           / Data units of CRVAL2                           
CD1_1   = 0.000280377484830748 / Transformation matrix                          
CD1_2   = -1.71606271442079E-06                                                 
CD2_1   = -1.61073877029747E-06                                                 
CD2_2   = -0.000280943199913645                                                 
OBJRA   = '14:22:34.454'       / Requested field J2000.0 Ra.                    
OBJDEC  = '+16:52:30.00'       / Requested field J2000.0 Dec.                   
OBJRAD  =            215.64356 / [deg] Requested field RA (J2000.0)             
OBJDECD =               16.875 / [deg] Requested field Dec (J2000.0)            
PIXSCALE=                 1.01 / [arcsec/pix] Pixel scale                       
EQUINOX =                2000. / [yr] Equatorial coordinates definition         
LONPOLE =                 180.                                                  
LATPOLE =                   0.                                                  
                                                                                
          / IMAGE QUALITY                                                       
                                                                                
SEEING  =                 1.71 / [pix] Seeing FWHM                              
PEAKDIST=    0.389898704794061 / [pix] Mean dist brightest pixel-centroid pixel 
ELLIP   =                0.107 / Mean image ellipticity A/B                     
ELLIPPA =               -35.01 / [deg] Mean image ellipticity PA                
FBIAS   =             689.3355 / [DN] Floating bias of the image                
SATURVAL=               53000. / [DN] Saturation value of the CCD array         
FWHMSEX =                 1.85 / [arcsec] SExtractor SEEING estimate            
MDSKYMAG=             20.39761 / [mag/s-arcsec^2] Median sky obsolete           
MSMAPCZP=             20.05711 / [mag/s-arcsec^2] Median sky abs. phot. cal.    
LIMITMAG=             21.74218 / [mag/s-arcsec^2] Limiting magnitude obsolete   
LMGAPCZP=             21.40168 / [mag/s-arcsec^2] Limiting mag. abs. phot. cal. 
MEDFWHM =             2.608781 / [arcsecond] Median FWHM                        
MEDELONG=             1.168383 / [dimensionless] Median elongation              
STDELONG=            0.6377625 / [dimensionless] Std. dev. of elongation        
MEDTHETA=            -7.846824 / [deg] Atan(median sin(theta)/median cos(theta))
STDTHETA=              64.7667 / [deg] Atan(stddev sin(theta)/stddev cos(theta))
MEDDLMAG=             30.16257 / [mag/s-arcsec^2] Median (MU_MAX-MAG_AUTO)      
STDDLMAG=             1.823812 / [mag/s-arcsec^2] Stddev of (MU_MAX-MAG_AUTO)   
                                                                                
          / OBSERVATORY AND TCS                                                 
                                                                                
OCS_TIME= '2013-07-02T04:17:23.461' / UTC Date for OCS calc time-dep params     
OPERMODE= 'OCS     '           / Mode of operation: OCS | Manual | N/A          
SOFTVER = '1.1.1.1 '           / Softwere version (TCS.Camera.OCS.Sched)        
OCS_VER = '1       '           / OCS software version and date                  
TCS_VER = '1       '           / TCS software version and date                  
SCH_VER = '1       '           / OCS-Scheduler software version and date        
MAT_VER = '7.7.0.471'          / Matlab version                                 
HDR_VER = '1       '           / Header version                                 
TRIGGER = 'N/A     '           / trigger ID for TOO, e.g. VOEVENT-Nr            
TCSMODE = 'Star    '           / TCS fundamental mode                           
TCSSMODE= 'Active  '           / TCS fundamental submode                        
TCSFMODE= 'Pos     '           / TCS focus mode                                 
TCSFSMOD= 'On-Target'          / TCS focus submode                              
TCSDMODE= 'Stop    '           / TCS dome mode                                  
TCSDSMOD= 'N/A     '           / TCS dome submode                               
TCSWMODE= 'Slave   '           / TCS windscreen mode                            
TCSWSMOD= 'N/A     '           / TCS windscreen submode                         
OBSLAT  =              33.3574 / [deg] Telescope geodetic latitude in WGS84     
OBSLON  =            -116.8599 / [deg] Telescope geodetic longitude in WGS84    
OBSALT  =               1703.2 / [m] Telescope geodetic altitude in WGS84       
DEFOCUS =                   0. / [mm] Focus position - nominal focus            
FOCUSPOS=               1.3785 / [mm] Exposures focusPos                        
DOMESTAT= 'open    '           / Dome status at begining of exposure            
TRACKRA =                 10.6 / [arcsec/hr] Track speed RA rel to sidereal     
TRACKDEC=                  1.3 / [arcsec/hr] Track speed Dec rel to sidereal    
AZIMUTH =             216.6835 / [deg] Telescope Azimuth                        
ALTITUDE=             70.18806 / [deg] Telescope altitude                       
AIRMASS =             1.062788 / Telescope airmass                              
TELRA   =             215.7994 / [deg] Telescope ap equinox of date RA          
TELDEC  =              16.8139 / [deg] Telescope ap equinox of date Dec         
TELHA   =              12.0595 / [deg] Telescope ap equinox of date HA          
DOMEAZ  =             215.3933 / [deg] Dome azimuth                             
WINDSCAL=              10.1089 / [deg] Wind screen altitude                     
WINDDIR =                  1.6 / [deg] Azimuth of wind direction                
WINDSPED=               9.1656 / Wind speed (km/hour)                           
OUTTEMP =             23.33333 / [C] Outside temperature                        
OUTRELHU=                0.409 / [frac] Outside relative humidity               
OUTDEWPT=             9.277778 / [C] Outside dew point                          
                                                                                
          / INSTRUMENT TELEMETRY                                                
                                                                                
PANID   = '_p48s   '           / PAN identification                             
DHSID   = '_p48s   '           / DHS identification                             
CCDSEC  = '[1:2048,1:4096]'    / CCD section                                    
CCDSIZE = '[1:2048,1:4096]'    / CCD size                                       
DATASEC = '[1:2048,1:4096]'    / Data section                                   
DETSEC  = '[1:2048,1:4096]'    / Detector section                               
ROISEC  = '[1:2048,1:4096]'    / ROI section                                    
FPA     = 'P48MOSAIC'          / Focal plan array                               
CCDNAME = 'W7C1    '           / Detector mfg serial number                     
CHECKSUM= '        '           / Image header unit checksum                     
DATASUM = '        '           / Image data unit checksum                       
DHEINF  = 'SDSU, Gen-III'      / Controller info                                
DHEFIRM = '/usr/src/dsp/20090618/tim_m.lod' / DSP software                      
CAM_VER = '20090615.1.3.100000' / Camera server date.rev.cfitsio                
LV_VER  = '8.5     '           / LabVIEW software version                       
PCI_VER = '2.0c    '           / Astropci software version                      
DETID   = 'PTF/MOSAIC'         / Detector ID                                    
AUTHOR  = 'PTF/OCS/TCS/Camera' / Source for header information                  
DATAMIN =                   0. / Minimum value for array                        
ROISTATE= 'ROI     '           / ROI State (FULL | ROI)                         
LEDBLUE = 'OFF     '           / 470nm LED state (ON | OFF)                     
LEDRED  = 'OFF     '           / 660nm LED state (ON | OFF)                     
LEDNIR  = 'OFF     '           / 880nm LED state (ON | OFF)                     
CCD9TEMP=              175.002 / [K] 0x0 servo temp sensor on CCD09             
HSTEMP  =               150.25 / [K] 0x1 heat spreader temp                     
DHE0TEMP=              303.015 / [K] 0x2 detector head electronics temp, master 
DHE1TEMP=              304.935 / [K] 0x3 detector head electronics temp, slave  
DEWWTEMP=              292.787 / [K] 0x4 dewar wall temp                        
HEADTEMP=              141.038 / [K] 0x5 cryo cooler cold head temp             
CCD5TEMP=              175.312 / [K] 0x6 temp sensor on CCD05                   
CCD11TEM=              176.263 / [K] 0x7 temp sensor on CCD11                   
CCD0TEMP=              169.376 / [K] 0x8 temp sensor on CCD00                   
RSTEMP  =              241.756 / [K] 0x9 temp sensor on radiation shield        
DEWPRESS=                  2.3 / [milli-torr] Dewar pressure                    
DETHEAT =                 28.5 / [%] Detector focal plane heater power          
NAMPSXY = '6 2     '           / Number of amplifiers in x y                    
CCDSUM  = '1 1     '           / [pix] Binning in x and y                       
MODELFOC= 'N/A     '           / MODELFOC                                       
EXPCKSUM= '4VHn7S9l4SEl4S9l'   / Primary header unit checksum                   
EXPDTSUM= '         0'         / Primary data unit checksum                     
GAIN    =                  1.5 / [e-/D.N.] Gain of detector.                    
READNOI =                  5.2 / [e-] Read noise of detector.                   
DARKCUR =                  0.1 / [e-/s] Dark current of detector                
                                                                                
          / SCAMP DISTORTION KEYWORDS                                           
                                                                                
RADECSYS= 'ICRS    '           / Astrometric system                             
PV1_0   =                   0. / Projection distortion parameter                
PV1_1   =                   1. / Projection distortion parameter                
PV1_2   =                   0. / Projection distortion parameter                
PV1_4   = -0.00173789497161513 / Projection distortion parameter                
PV1_5   = 6.00083003595371E-05 / Projection distortion parameter                
PV1_6   = -0.00054585707358405 / Projection distortion parameter                
PV1_7   = -0.00133490210858131 / Projection distortion parameter                
PV1_8   = 0.000173741003278833 / Projection distortion parameter                
PV1_9   = -0.000547160675264968 / Projection distortion parameter               
PV1_10  = 0.000251433351740168 / Projection distortion parameter                
PV1_12  = -0.00328774077188989 / Projection distortion parameter                
PV1_13  = -0.000280710215945655 / Projection distortion parameter               
PV1_14  = 0.000714951620183291 / Projection distortion parameter                
PV1_15  = -0.000275634808657675 / Projection distortion parameter               
PV1_16  = 0.000192684172156633 / Projection distortion parameter                
PV2_0   =                   0. / Projection distortion parameter                
PV2_1   =                   1. / Projection distortion parameter                
PV2_2   =                   0. / Projection distortion parameter                
PV2_4   =  0.00025061777603867 / Projection distortion parameter                
PV2_5   = -0.00125376481783182 / Projection distortion parameter                
PV2_6   = -0.000118547045320473 / Projection distortion parameter               
PV2_7   = -0.000709046387896288 / Projection distortion parameter               
PV2_8   = 0.000780095509401425 / Projection distortion parameter                
PV2_9   = -0.000924905030225836 / Projection distortion parameter               
PV2_10  = -0.000525520061118934 / Projection distortion parameter               
PV2_12  = -0.000283472622900895 / Projection distortion parameter               
PV2_13  = 0.000738353372557653 / Projection distortion parameter                
PV2_14  = 0.000164958172111789 / Projection distortion parameter                
PV2_15  = -0.00144743155797026 / Projection distortion parameter                
PV2_16  = -0.000422174086212961 / Projection distortion parameter               
FGROUPNO=                    1 / SCAMP field group label                        
ASTIRMS1=                   0. / Astrom. dispersion RMS (intern., high S/N)     
ASTIRMS2=                   0. / Astrom. dispersion RMS (intern., high S/N)     
ASTRRMS1=          2.60633E-05 / Astrom. dispersion RMS (ref., high S/N)        
ASTRRMS2=         2.679676E-05 / Astrom. dispersion RMS (ref., high S/N)        
ASTINST =                    1 / SCAMP astrometric instrument label             
FLXSCALE=                   0. / SCAMP relative flux scale                      
MAGZEROP=                   0. / SCAMP zero-point                               
PHOTIRMS=                   0. / mag dispersion RMS (internal, high S/N)        
RA_RMS  =            0.4284936 / [arcsec] RMS of SCAMP fit from 2MASS matching  
DEC_RMS =            0.3289862 / [arcsec] RMS of SCAMP fit from 2MASS matching  
ASTROMN =                 1003 / Number of stars in SCAMP astrometric solution  
SCAMPPTH= '/ptf/pos/archive/fallbackcal/scamp/11/' / SCAMP catalog path         
SCAMPFIL= 'PTF_201102044118_c_e_sdss_t095258_u003860515_f01_p003486_c11.fits'   
                                                                                
          / SIP DISTORTION KEYWORDS                                             
                                                                                
A_ORDER =                    4 / Distortion order for A                         
A_0_2   = -1.53991686981733E-07 / Projection distortion parameter               
A_0_3   = -1.9961153583439E-11 / Projection distortion parameter                
A_0_4   = 4.28220501859733E-15 / Projection distortion parameter                
A_1_1   = -1.48140435828959E-08 / Projection distortion parameter               
A_1_2   = -4.37451084272745E-11 / Projection distortion parameter               
A_1_3   = 6.11763923987906E-15 / Projection distortion parameter                
A_2_0   = -4.87160559968282E-07 / Projection distortion parameter               
A_2_1   = -1.27084757090404E-11 / Projection distortion parameter               
A_2_2   = 1.57779409644097E-14 / Projection distortion parameter                
A_3_0   = -1.04765134994984E-10 / Projection distortion parameter               
A_3_1   = 7.95789862286398E-15 / Projection distortion parameter                
A_4_0   = -7.23704568938464E-14 / Projection distortion parameter               
A_DMAX  =     2.44291521352919 / Projection distortion parameter                
B_ORDER =                    4 / Distortion order for B                         
B_0_2   = -6.7373693835656E-08 / Projection distortion parameter                
B_0_3   = -5.54765729401967E-11 / Projection distortion parameter               
B_0_4   = 6.16120047283346E-15 / Projection distortion parameter                
B_1_1   = -3.5264356557202E-07 / Projection distortion parameter                
B_1_2   = -6.12610617364653E-11 / Projection distortion parameter               
B_1_3   = 1.64880764414739E-14 / Projection distortion parameter                
B_2_0   = 3.39463080480267E-08 / Projection distortion parameter                
B_2_1   = -7.40973776817625E-11 / Projection distortion parameter               
B_2_2   = -2.8629870353495E-15 / Projection distortion parameter                
B_3_0   = 4.14105136847929E-11 / Projection distortion parameter                
B_3_1   = -3.22124747225646E-14 / Projection distortion parameter               
B_4_0   = 9.51825972208521E-15 / Projection distortion parameter                
B_DMAX  =     2.95057287643024 / Projection distortion parameter                
AP_ORDER=                    4 / Distortion order for AP                        
AP_0_1  = 2.05105623663409E-08 / Projection distortion parameter                
AP_0_2  = 1.54047990787523E-07 / Projection distortion parameter                
AP_0_3  = 1.99841723199859E-11 / Projection distortion parameter                
AP_0_4  = -4.27260819246964E-15 / Projection distortion parameter               
AP_1_0  = -7.88989114580002E-08 / Projection distortion parameter               
AP_1_1  = 1.49024754213322E-08 / Projection distortion parameter                
AP_1_2  = 4.39773302986539E-11 / Projection distortion parameter                
AP_1_3  = -6.1078457561122E-15 / Projection distortion parameter                
AP_2_0  = 4.87351326761802E-07 / Projection distortion parameter                
AP_2_1  = 1.27034030399091E-11 / Projection distortion parameter                
AP_2_2  = -1.56781266527055E-14 / Projection distortion parameter               
AP_3_0  = 1.05609755183277E-10 / Projection distortion parameter                
AP_3_1  = -7.88269146660008E-15 / Projection distortion parameter               
AP_4_0  =  7.2479268759029E-14 / Projection distortion parameter                
BP_ORDER=                    4 / Distortion order for BP                        
BP_0_1  = -3.61828763934933E-08 / Projection distortion parameter               
BP_0_2  = 6.74317721340757E-08 / Projection distortion parameter                
BP_0_3  = 5.55651238033361E-11 / Projection distortion parameter                
BP_0_4  = -6.14956183405539E-15 / Projection distortion parameter               
BP_1_0  = -5.01841161647254E-08 / Projection distortion parameter               
BP_1_1  = 3.52809293826258E-07 / Projection distortion parameter                
BP_1_2  = 6.13665672637537E-11 / Projection distortion parameter                
BP_1_3  = -1.64300062518365E-14 / Projection distortion parameter               
BP_2_0  = -3.4054112344702E-08 / Projection distortion parameter                
BP_2_1  = 7.45298070253847E-11 / Projection distortion parameter                
BP_2_2  = 2.92717865788252E-15 / Projection distortion parameter                
BP_3_0  = -4.14183265768535E-11 / Projection distortion parameter               
BP_3_1  = 3.23323470749901E-14 / Projection distortion parameter                
BP_4_0  = -9.48831790286268E-15 / Projection distortion parameter               
                                                                                
          / DATA FLOW                                                           
                                                                                
ORIGNAME= '/data/PTF_default_56753.fits' / Filename as written by the camera    
FILENAME= 'PTF201307021787_2_o_56753.fits' / Filename of delivered camera image 
PROCORIG= 'IPAC-PTF pipelines' / Processing origin                              
PROCDATE= 'Wed Jul  3 19:07:12 2013' / Processing date/time (Pacific time)      
PTFVERSN=                   5. / Version of PTFSCIENCEPIPELINE program          
PMASKPTH= '/ptf/pos/archive/fallbackcal/pmasks/' / Pathname of pixel mask       
PMASKFIL= '70sOn35s_pixmask_chip11.trimmed.v4.fits' / Filename of pixel mask    
SFLATPTH= '/ptf/pos/sbx2/2013/07/02/f2/c11/cal/p4/cId98684/' / Pathname of super
SFLATFIL= 'PTF_201307020000_i_s_flat_t120000_u000098684_f02_p000000_c11.fits'   
SBIASPTH= '/ptf/pos/sbx2/2013/07/02/f2/c11/cal/p1/cId98678/' / Pathname of super
SBIASFIL= 'PTF_201307020000_i_s_bias_t120000_u000098678_f00_p000000_c11.fits'   
DBNID   =                 1550 / Database night ID                              
DBEXPID =               342625 / Database exposure ID                           
DBRID   =              5743856 / Database raw-image ID                          
DBPID   =             16616794 / Database processed-image ID                    
DBFID   =                    2 / Database filter ID                             
DBPIID  =                    1 / Database P.I. ID                               
DBPRID  =                   17 / Database project ID                            
DBFIELD =               342625 / Database field ID                              
DBSVID  =                   51 / Database software-version ID                   
DBCVID  =                   57 / Database config-data-file ID                   
INFOBITS=                    0 / Database infobits (2^2 and 2^3 excluded)       

Now let's plot the image data. But let's use sigma-clipping to pick a nice scale for the image.

In [98]:
clipped_data = astropy.stats.sigma_clip(hdu.data.flatten())
mid = np.median(clipped_data)
std = np.std(clipped_data - mid)
In [99]:
plt.figure(figsize=(20, 10))
plt.imshow(hdu.data, vmin=mid-std, vmax=mid+3*std, cmap='binary')
plt.xlabel('pixel $x$')
plt.ylabel('pixel $y$')
Out[99]:
<matplotlib.text.Text at 0x10e95fb90>

I happen to know that there is something interesting to look at near \(\mathrm{RA, Dec}=14^\mathrm{h}29^{m}14.781^{s}, +15^\circ46^\prime26.385^{\prime\prime}\). Let's open the catalog file from IPAC and find this object.

In [100]:
catalog_filename = 'PTF_201307021787_c_p_scie_t041723_u016616794_f02_p003486_c11.ctlg.gz'
catalog_table = astropy.table.Table.read(catalog_filename)
catalog_table
Out[100]:
NUMBERFLAGSXWIN_IMAGEYWIN_IMAGEX_WORLDY_WORLDXPEAK_IMAGEYPEAK_IMAGEERRTHETAWIN_IMAGEDELTAWIN_J2000X2WIN_IMAGEY2WIN_IMAGEXYWIN_IMAGEAWIN_WORLDBWIN_WORLDMAG_ISOMAGERR_ISOMAG_AUTOMAGERR_AUTOMAG_ISOCORMAGERR_ISOCORMAG_APER [5]MAGERR_APER [5]MAG_PETROMAGERR_PETROMAG_BESTMAGERR_BESTMU_THRESHOLDMU_MAXBACKGROUNDTHRESHOLDALPHAWIN_J2000THETAWIN_IMAGETHETAWIN_J2000ELONGATIONISOAREA_WORLDISOAREAF_WORLDISO0ISO1ISO2ISO3ISO4ISO5ISO6ISO7FWHM_IMAGEKRON_RADIUSPETRO_RADIUSCLASS_STARFLUX_BESTFLUXERR_BESTFLUX_AUTOFLUXERR_AUTOFLUX_ISOFLUXERR_ISOFLUX_APER [5]FLUXERR_APER [5]X_IMAGEY_IMAGEX2_IMAGEY2_IMAGEXY_IMAGETHETA_IMAGEERRAWIN_IMAGEERRBWIN_IMAGETHETAWIN_WORLDERRX2WIN_IMAGEERRY2WIN_IMAGEERRXYWIN_IMAGEFLUX_RADIUS [5]IMAFLAGS_ISONIMAFLAGS_ISOERRAWIN_WORLDERRBWIN_WORLDERRTHETAWIN_WORLDA_IMAGEERRA_IMAGEB_IMAGEERRB_IMAGEA_WORLDERRA_WORLDB_WORLDERRB_WORLDERRTHETA_IMAGEERRX2_IMAGEERRY2_IMAGEERRXY_IMAGEAWIN_IMAGEBWIN_IMAGEFLUX_PETROFLUXERR_PETROZEROPOINT
pixpixdegdegpixpixdegdegpix2pix2pix2degdegmagmagmagmagmagmagmagmagmagmagmagmagmag / arcsec2mag / arcsec2ctctdegdegdegdeg2deg2pix2pix2pix2pix2pix2pix2pix2pix2pixctctctctctctctctpixpixpix2pix2pix2degpixpixdegpix2pix2pix2pixdegdegdegpixpixpixpixdegdegdegdegdegpix2pix2pix2pixpixctct
1282043.07354532214.094174964217.46988032116.7680411417204321287.361816.76821099365.6769986186516.9655029460.0651969856810.001157010.000667602-17.51350.000312259-17.49880.000304322-17.51440.000313243-13.2036 .. -16.4910.00332232 .. 0.000526935-17.51180.000321372-17.49880.000304322-4.04479-11.92321316.338.6513217.46999230689.66910.05969244.557618.0994e-058.7291e-05102971746530423720317816729.23682.55.280.7123949.98935e+062799.249.98935e+062799.241.01253e+072911.33191173.0 .. 3.94812e+06584.841 .. 1915.652042.69214.7015.20661210638108.150261299-0.0569632310367-89.96830.001080970.00086031589.94037.41048956213e-071.16759326735e-061.96962849267e-083.7187 .. 22.71289629473.03627e-072.41076e-07-87.777810.39950.003364292.281790.001000880.002921249.45015e-070.0006393172.8049e-0789.69661.002043701e-061.13181350792e-055.46230766146e-084.118972.382571.01096e+072991.6727.8462
2465.3796000687121.919426679216.89073056916.797018545666122-89.014216.79701914691.325023736142.14409431293-0.009723764220760.0004115420.000323209-15.55040.000780183-15.51370.000717886-15.55260.000787251-13.1979 .. -15.51720.00336865 .. 0.000720459-15.53960.000738907-15.51370.000717886-3.9759-11.92041302.1342.1467216.890742798-89.31990.9232641.374322.68406e-053.1642e-0534823413586564232252.17012.53.960.9949251.60507e+061061.011.60507e+061061.011.66012e+061192.63190185.0 .. 1.61022e+06589.934 .. 1068.2365.3379121.9222.898546934625.4736777658-0.029297647083-89.34830.0008851280.00078437189.07676.15287429928e-077.83401615848e-07-2.89353080611e-091.47737 .. 4.476612583012.48763e-072.20249e-0788.75532.339660.002754831.702410.002057850.0006575587.74227e-070.0004780285.7785e-0789.68844.23484759239e-067.58898725937e-061.82404605635e-081.464311.151051.64384e+061118.4627.8244
30983.1664455938.5584028713217.15994445316.81931139269833955.286316.81929261021.113994151481.1306721510.0405665877610.0003028940.000291846-11.03970.0145841-10.9770.0140901-11.12720.0166746-9.30163 .. -10.90050.019648 .. 0.0132189-11.33120.025697-10.9770.0140901-4.04479-8.218211296.6241.9948217.15990685250.808-37.71651.178618.89439e-061.05473e-051138349292014742.736182.704427.260.029578624591.9319.06424591.9319.06426055.4349.9035255.96 .. 22919.095.0915 .. 278.972983.29438.49094.400334781975.331211190710.64142420463462.98290.009801840.00973746-52.28359.52260901701e-059.56681194092e-055.88851967933e-071.12103 .. 5.774392922.75273e-062.73279e-06-62.02682.378710.04900752.018230.03928520.0006680031.37622e-050.0005664811.10276e-0563.98920.00170841324170.00223665073340.0003383183169331.078771.0396734078.7806.37227.8277
424347.4346651911.8799604679216.97360841216.82748112783471216.644816.827623985710.35550569599.427139664270.629756886370.0009172360.000847906-12.4540.00773088-12.41150.00759902-12.53340.00854046-8.92665 .. -11.57080.0261645 .. 0.00791912-12.4740.014162-12.41150.00759902-4.04479-7.851491296.0438.5743216.97359601426.8034-62.70261.249583.66795e-053.95918e-05466397296189124692278.313992.55.940.024877592170.5644.9492170.5644.9495853.7682.3523721.01 .. 42494.789.6486 .. 309.872347.47912.388125.359695764520.8878507564.5488104493731.9120.01761370.0173677-27.29740.0003095353362260.0003023434564732.36116217484e-063.19321 .. 11.879924534.94415e-064.88024e-06-18.07375.309650.05074914.249130.03960330.001490951.42506e-050.001193481.11232e-0532.97190.00227719863880.001866691871430.0004597930595913.267063.0181197637.41273.2427.8298
501419.6443503516.5434826546217.28782282516.824814907314201752.924216.8248089680.4417843929140.4331154095080.007113947482570.0001873110.000183951-13.30290.00241345-13.25590.00215125-13.30750.00245252-12.3278 .. -13.29720.00397694 .. 0.00233339-13.29950.00236045-13.25590.00215125-4.04479-11.21561298.3342.1008217.2878235929.3231-57.81291.011066.9266e-067.79243e-068867463223151141.97612.53.960.97946200614.0397.395200614.0397.395209490.0465.55585333.2 .. 208391.0312.491 .. 447.7511419.6416.52241.779471537311.74092744553-0.00188059912377-2.786690.001375610.00135171-32.18711.8508188539e-061.86861803206e-063.13495500575e-080.76407 .. 3.081692873.86214e-073.79287e-07-56.1551.3340.004472271.319410.004455420.0003740541.25571e-060.0003706941.25009e-0649.361.99145459679e-051.99373544938e-057.43536762809e-080.6676680.655072208835.0453.90827.8346
60514.56377607510.7055897669217.02260024316.827724382651411-62.443516.82774979910.5914244750280.655560884701-0.1005152613460.0002398510.000202023-7.2930.126139-7.663140.128526-7.753330.156948-6.43072 .. -7.911190.157155 .. 0.187355-7.652760.140174-7.663140.128526-4.04479-5.553111294.7442.0844217.022599919-53.847336.07941.432876.29691e-078.65826e-07866653222.933883.229263.50.5672761162.14137.5371162.14137.537826.41995.9886373.499 .. 1460.4254.0491 .. 251.949514.56510.7960.7941011174220.744202386921-0.264126778737-42.30190.0833060.082836553.92060.006878585782140.00692320218832-3.19934710412e-050.879676 .. 2.90618272.34052e-052.32502e-0566.85261.017080.1497670.7098230.09967870.0002855934.20514e-050.0001993492.79971e-05-41.08640.01703371517310.0153321807233-0.006188894918610.8538150.7197121151.08148.57427.824
716681.2116439426.82584123698217.07146999316.828635858368176.9168916.82862557830.4450701480.4351836828860.003203518779060.0001874010.000185148-11.22040.00852639-11.18530.0075306-11.2380.00890691-10.2205 .. -11.22990.0119008 .. 0.0100799-11.23530.0109642-11.18530.0075306-4.04479-9.377261297.5342.1391217.07145765916.4729-71.57321.027263.06975e-063.77815e-0639312418139631.881792.54.620.98141229792.9206.59229792.9206.59230771.3241.59112251.4 .. 31041.8134.256 .. 288.121681.2546.789061.532485130691.46177700693-0.019257480957-14.28860.004076940.00403746-18.42681.66167930786e-051.6305715315e-053.83012796274e-080.694942 .. 2.957842451.1439e-061.13451e-06-8.05221.239920.01431531.207010.01336230.0003479224.01677e-060.0003391353.75456e-06-15.3150.0002030871923280.00018039068319-6.71935235715e-060.6678450.65896631196.8314.96327.8255
8171702.201875293.99537423504217.37056495316.827823623917024-88.25916.82785555810.3948578316440.505787877524-0.01827924072720.0002003850.000175477-7.461290.104592-7.48520.107078-7.746010.131219-6.6235 .. -7.865850.136609 .. 0.188425-8.099360.172227-7.746010.131219-4.04479-5.65561296.5542.3409217.370605606-80.87989.304711.204867.08403e-077.87114e-07987444412.307972.57.260.0154671254.31151.555986.45797.2633964.97792.9361446.067 .. 1400.6856.1112 .. 243.0221702.064.109910.5450602445690.788015483009-0.0179720544728-85.79220.06113590.060849780.69530.003702713711350.00373757030168-1.06048998764e-060.689262 .. 1.90875281.71752e-051.70573e-0588.60580.8884470.1127770.7373860.08931910.0002496093.16835e-050.0002066852.5037e-05-88.95360.007979473745520.0127170633031-8.65593558427e-050.7132480.6260381736.77275.43127.8403
9161462.955315474.04146788793217.30049055316.828159934714634-6.9849516.82825041540.4320852385790.302417146455-0.05374774151910.000188390.000149498-6.297390.212145-6.297390.212145-6.90740.252833-5.81432 .. -3.969020.26874 .. 6.80963-4.686972.98363-6.297390.212145-4.04479-4.981851298.342.091217.30053223-19.829470.27551.688033.14846e-073.93557e-07444332113.369582.57.260.191464330.33864.5299330.33864.5299330.33864.5299211.703 .. 38.690852.3878 .. 242.6061462.814.364350.5180675822210.231598294165-0.109154928926-18.6550.1027760.10187419.72450.01056009970870.0103810902406-2.22660923668e-050.610324 .. 1.29903002.8818e-052.86208e-058.77870.7449290.2015330.4413010.1166440.0002088165.64924e-050.0001241213.28108e-05-18.54520.03788347244330.0163381306015-0.008144461190720.6719130.53201174.9525205.92127.834
1016316.4417980824.16184454884216.96450162616.829845502531646.7643516.82982959310.390314391350.3965031107020.01998763720540.0001806320.000171568-7.561240.0997192-7.61080.0993573-7.84630.125159-6.81729 .. -7.544430.115152 .. 0.253524-7.4730.26895-7.61080.0993573-4.04479-5.762931296.0842.2305216.96451759349.4002-39.81351.278536.29691e-078.65826e-07877654322.20572.55.940.3507441107.44101.3181107.44101.3181058.0397.1509533.232 .. 1041.7756.5404 .. 243.2316.3874.105460.8394566308520.5529527141160.087197019552115.66440.05341930.0528021-50.18650.002852710499090.002788975328517.66761945026e-060.672661 .. 2.0723281.49942e-051.48383e-05-7.401510.9294670.1172140.7269810.08315120.0002609523.29099e-050.0002042252.33556e-0515.11210.0132753316650.007378020230860.001717830242630.6431440.610887975.436241.56927.8309
1124886.7102313341.81463439866217.13239802616.8296399378882-5.8384216.82975404281.039081608030.568454713824-0.11983300310.0002898390.000206504-9.26920.0377295-10.140.0230593-9.373520.0419091-6.59437 .. -10.06280.156542 .. 0.023648-10.1970.0276122-10.140.0230593-4.04479-7.016731296.3838.624217.13169593-13.493776.69255.612182.28263e-062.51877e-062926242354449.801522.53.50.97601311376.7241.56511376.7241.5655101.29177.227434.26 .. 10595.562.5964 .. 230.721889.1082.2087618.73751639561.01635787466-2.72132677669-8.536580.01861820.015504413.30750.0003455385167390.000241485522247-1.07522352008e-052.03198 .. 8.39858514305.22255e-064.35691e-065.623894.375610.2015390.7796640.02455650.001227095.65204e-050.00022147.04417e-06-7.653130.0399084067420.00131271583731-0.005281560783211.033360.73464211989.8304.84927.8268
....................................................................................................................................................................................................................................................................................
36680633.1486560223001.56959249217.0529078115.9873722675633300287.963215.98738329510.3169508531220.3125568398760.01469210182840.0001609570.000153819-6.441590.18596-6.445040.217803-6.896550.231713-5.98 .. -6.944020.230054 .. 0.453981-6.998230.258787-6.445040.217803-4.05242-5.09981314.1842.0286217.05290086640.7476-48.81811.614173.93557e-073.93557e-07543332212.349242.715555.280.519764378.45675.9016378.45675.9016377.25464.5987246.604 .. 599.2552.2396 .. 250.505633.1733001.610.4982747331420.238165292358-0.0998571723727-18.75870.1009440.0939796-41.18190.008833877788640.01018800969014.82184271494e-050.589735 .. 1.35128002.83352e-052.63637e-05-88.96750.7295130.1957570.4519420.1132570.0002046745.49198e-050.0001268743.18001e-05-18.44460.03576872237040.0153790153699-0.00765153110480.5741160.54763629.93150.10827.8234
366901349.198123182992.66803804217.26180191915.98905037761349299330.183415.98904516760.4999271719310.4516881597610.01235008956760.000198740.00018807-9.029430.0380558-9.023980.0389921-9.125210.043849-8.03824 .. -9.088750.0447006 .. 0.0650792-9.074740.0656173-9.023980.0389921-4.05162-7.105681311.0142.6258217.26178920113.5571-76.85441.130131.49552e-061.73165e-061916141176322.192952.54.620.4280474069.96146.1294069.96146.1294090.45143.3381641.71 .. 4320.1667.5742 .. 258.8881349.242992.651.262768635671.063112164590.10036056951222.57620.02030040.0202353-13.14560.0004114387714210.000410134332141.14656486267e-060.759194 .. 2.665182205.68751e-065.6828e-06-28.62761.142150.05287541.010640.04378270.0003200681.48183e-050.000283771.22928e-0525.360.002634577619330.002078152514270.0003401525206790.7091580.6698584264.75257.68127.8271
36700480.2565259943026.58744914217.00821868615.98053840584803027-59.243715.98051492970.5788628996450.6101940136620.01665377377450.0002204110.000212288-8.630680.0540228-8.621170.0555588-8.811750.0658523-7.45454 .. -8.750480.0691245 .. 0.0868504-8.745270.102718-8.621170.0555588-4.05167-6.387481315.9141.897217.00824618566.6243-21.91741.175371.41681e-061.81036e-061818121087442.522622.55.280.1985972808.47143.6792808.47143.6792833.18140.936958.993 .. 3163.6861.0404 .. 253.008480.1623026.51.183387098531.365764026750.1826837376158.26330.03331770.0332128-68.08260.001104915268640.0011082441067-3.06707874088e-060.843262 .. 2.864512159.35897e-069.31205e-0657.31661.216040.08110761.03460.06485050.000341022.27456e-050.0002906111.82176e-0560.27110.004789108919260.005994930535560.001021816857360.7857430.7560853148.52297.79927.8226
36710438.9923775983038.13407781216.99621434915.9772965077439303825.739315.97731363880.7732853303520.781778811385-0.007504780337070.0002490640.000245862-9.085890.0409438-9.147360.0431611-9.226550.0488328-7.72078 .. -9.217040.0578702 .. 0.0570135-9.354570.0748753-9.147360.0431611-4.03393-6.800841317.0241.9845216.996186311-59.752131.24251.025242.20392e-062.36134e-062821171298412.744012.694895.940.02122474559.76181.224559.76181.224308.8162.4481225.49 .. 4862.0165.3035 .. 255.249439.0893038.191.56068225141.64011893551-0.00369465284357-87.34280.02825410.028180758.75750.0007975126475320.0007949313634211.62131783327e-060.944886 .. 3.458992247.92337e-067.91476e-06-7.210471.280740.06218431.24920.05945280.0003595771.74497e-050.0003504421.66874e-0577.71790.003549666656760.003851850910126.90612126392e-050.8866540.8768755518.57380.48327.8224
367201200.922997572973.86948439217.21859431615.994474844812012974-63.225915.99450883420.461803832240.526684442712-0.1053928885060.0002183670.000173573-6.724160.170722-6.724160.170722-7.26930.207941-5.8372 .. -6.952770.266302 .. 0.454459-7.079780.277969-6.724160.170722-4.04627-4.866981312.2542.37217.218582176-53.554336.55951.67655.5098e-075.5098e-07766643324.053062.55.280.000422344489.39976.9346489.39976.9346489.39976.9346216.213 .. 604.09853.0183 .. 252.7971200.972973.990.5297157893940.537528729202-0.253523863309-45.44140.1110310.11011553.44050.01216643664490.0122867742905-8.14566111965e-050.68351 .. 1.64114003.11828e-053.08547e-0562.11850.887230.1989990.5292150.1152060.0002491075.58713e-050.0001482363.22702e-05-44.96260.02645380369960.0264194038715-0.01316418230030.7775070.619654679.067173.81227.8277
367301900.714030312959.84809201217.42267630915.99750926661901296014.807315.99749852780.4593256813850.3861273514810.07214222887610.0001987710.000164138-6.739870.162464-6.866760.155978-7.152620.203551-6.03596 .. -6.728210.2293 .. 0.578937-6.648680.540097-6.866760.155978-4.04141-5.062751311.3343.9685217.4226542131.5502-58.19421.331274.72269e-074.72269e-07666652223.227832.56.60.0287059558.08980.1562558.08980.1562496.53574.2809259.647 .. 491.22854.8224 .. 261.8691900.792959.810.4349714468640.4245466501620.11960471761243.75230.0983630.0974273-31.80580.009663323003390.009504043944714.52684007383e-050.690053 .. 1.64709002.75494e-052.735e-05-9.899190.7412670.1593720.5568130.1176110.0002076324.46408e-050.0001563483.30255e-0544.81810.0196526029640.01957917972070.005783332922640.7096630.584664456.535227.04727.8438
36740871.1564644362991.50492758217.1223687415.9899701722871299285.141715.98995006390.4972037934130.4875838403390.002176516368630.0001977860.00019597-12.29290.00447396-12.25270.00390336-12.30240.0046004-11.2074 .. -12.29170.00705358 .. 0.0045239-12.29470.00463471-12.25270.00390336-4.04356-10.20121313.7142.2938217.12235877812.1734-81.75441.011864.95882e-065.98207e-06635037291914842.001562.53.960.97628379630.5286.21279630.5286.21282632.9340.4230407.3 .. 82544.0197.496 .. 343.85871.192991.431.8141462941.79799995532-0.0197008699371-33.85840.002403480.00235613-8.245625.55294711032e-065.77512116952e-061.90215983223e-080.777625 .. 3.250232636.74583e-076.60849e-07-88.23691.35180.008371031.335960.008221750.0003795592.35112e-060.0003745572.30439e-06-51.97066.85372649983e-056.91340381446e-05-1.20201537409e-060.705460.69793682773.5353.25227.8261
367531023.865801233017.43749414217.16687005715.982508283710243017-55.289615.98249471260.7208349401990.791051307285-0.05072137800360.0002539710.00023347-8.765430.0508763-8.772190.0531502-8.946990.0620394-7.43212 .. -9.027420.0706823 .. 0.0676491-9.153890.0870592-8.946990.0620394-4.07834-6.305261311.4242.0287217.166859252-62.345127.9591.236111.73165e-062.0465e-062219161297533.732172.555885.940.01270043791.38216.5893227.56157.9613207.53150.264939.39 .. 4082.961.1402 .. 254.3321023.93017.391.238239494861.83116049317-0.121833331731-78.82970.03597240.035785562.0410.001284950207720.00128966585972-6.27983259476e-060.930043 .. 3.033212221.01031e-051.00285e-0555.9841.362060.08138091.10190.06416770.000382492.28481e-050.0003087891.79871e-05-84.76890.004138320601480.00660201953674-0.0002274706137570.9042290.8332214587.29367.74127.8291
367601179.158702893018.95656348217.21207826415.98189251011180301975.891915.98188112640.9950743552511.266734281380.1617546184880.0003247970.000269248-7.38590.121398-7.880020.138565-7.851530.150899-5.82733 .. -8.075940.276838 .. 0.16183-8.231490.178827-7.880020.138565-4.07737-5.241191310.8642.2534217.21214978165.0106-24.44261.588417.08403e-079.44537e-07777664435.324053.563126.60.0429441419.09181.0631419.09181.063900.24100.633214.256 .. 1699.7154.6171 .. 253.2821178.913018.920.8061209454611.301329210740.382365179961.46270.1215410.121032-65.55740.01465612895680.01476482659412.91614872885e-051.2742 .. 4.03529263.41046e-053.39432e-0589.36751.228520.1865840.7734280.1117680.0003443485.22976e-050.0002173663.14187e-0561.19640.01767382900810.02963189420680.009424051776451.15850.9590011961.53322.99627.8279
367701662.326949353030.11100211217.3529697615.9780824541662303060.145215.97811979880.5310564986180.583833344481-0.0155264847660.0002153150.000203303-7.522450.108642-7.753230.127469-7.890070.136656-6.6035 .. -7.935650.137902 .. 0.185999-7.935410.217366-7.753230.127469-4.03866-5.884631310.8342.6602217.353012903-74.764116.19521.193947.87114e-079.44537e-071087522112.563883.222236.60.5378121262.68148.2071262.68148.2071020.89102.129437.924 .. 1493.6955.6082 .. 255.8241662.183030.240.7588956215480.862725347153-0.132420787472-55.70370.07459560.074449373.80480.005548100895360.00555910198519.41669563121e-060.766142 .. 3.17874282.09238e-052.08749e-0582.41920.976240.12720.8176650.1022030.0002741553.57211e-050.0002289362.86136e-05-54.8210.01234891020960.0142765108527-0.0027003988950.7668520.7258291493.35298.89927.8341

Now, let's create a coordinates object to represent the target that we are searching for:

In [101]:
target_coord = astropy.coordinates.SkyCoord(
    '14h29m14.781s +15d46m26.385s')
target_coord
Out[101]:
<SkyCoord (ICRS): ra=217.3115875 deg, dec=15.7739958333 deg>

Now, let's match this position against the source catalog:

In [102]:
# Coordinates of objects in catalog
catalog_coords = astropy.coordinates.SkyCoord(
    ra=catalog_table['ALPHAWIN_J2000'],
    dec=catalog_table['DELTAWIN_J2000'])

# Do source matching
index, separation, distance = target_coord.match_to_catalog_sky(catalog_coords)
index, separation
Out[102]:
(array(3259), <Angle [  4.20500043e-06] deg>)

Here is the closest-matching row:

In [103]:
index = np.asscalar(index)
matching_row = catalog_table[index]
In [104]:
plt.figure(figsize=(10, 10))
plt.imshow(hdu.data, vmin=mid-std, vmax=mid+3*std, cmap='binary', interpolation='nearest')
plt.xlim(matching_row['XWIN_IMAGE'] - 64, matching_row['XWIN_IMAGE'] + 64)
plt.ylim(matching_row['YWIN_IMAGE'] - 64, matching_row['YWIN_IMAGE'] + 64)

# I happen to know that these images are upside down; use APLPy or the like to
# automatically orient North upward
plt.gca().invert_yaxis()

plt.xlabel('pixel $x$')
plt.ylabel('pixel $y$')
Out[104]:
<matplotlib.text.Text at 0x12c2098d0>

Let's calibrate the Sextractor photometry. We'll query the PTF photometric calibrator catalog at IRSA using Astroquery...

In [105]:
from astroquery.irsa import Irsa

calib_table = Irsa.query_region(
    target_coord,
    catalog='ptfphotcalcat',
    radius=200*u.arcsec)
calib_table
Out[105]:
radecclonclatnpntbstrmsrptfrerrrmerrrperrmutypeerrmuptffieldciflagdistangleid
degdegmagmagmagmagarcsdeg
217.34215.78114h29m22.06s15d46m52.22s950.0218.7220000000000010.0310.0240.039-0.0290000000000000010.1073486111108.25466776.1956349999999960
217.31615.75314h29m15.86s15d45m09.99s950.0216.1879999999999990.010.00600000000000000010.0149999999999999990.0379999999999999990.085000000000000006348611177.979508999999993168.484482000000011
217.32615.78914h29m18.12s15d47m19.13s950.0215.2090.00700000000000000010.00700000000000000010.0070000000000000001-0.00300000000000000010.058999999999999997348611171.44111499999999642.4300599999999972
217.27515.74514h29m05.90s15d44m42.06s950.0218.2100000000000010.0270.0250000000000000010.0299999999999999990.0630.1283486111165.32226600000001230.870343999999993
217.29415.78814h29m10.52s15d47m18.12s950.0218.1020.0439999999999999970.0500000000000000030.037999999999999999-1.1590.089999999999999997348611180.340373999999997310.076373999999994
217.26815.76814h29m04.35s15d46m05.74s950.0218.2979999999999980.0270.0390.014999999999999999-0.271000000000000020.101999999999999993486111152.00161900000001262.192586000000015
217.28015.76914h29m07.21s15d46m06.83s850.0218.5810.0280000000000000010.0129999999999999990.0429999999999999970.0179999999999999990.0889999999999999963486111111.05929259.855291000000026
217.27115.76814h29m04.98s15d46m03.62s950.0217.7620.0290000000000000010.0230.035999999999999997-0.553000000000000050.0929999999999999993486111143.25297699999999260.856699999999997
217.34415.74914h29m22.58s15d44m57.72s950.0218.2719999999999980.0299999999999999990.0259999999999999990.033000000000000002-0.632000000000000010.102999999999999993486111143.30828099999999128.225789999999998
217.27915.75514h29m07.01s15d45m18.12s950.0218.1999999999999990.0230.00600000000000000010.040000000000000001-0.356999999999999980.0820000000000000033486111131.38173800000001238.6893579
217.29115.77014h29m09.80s15d46m13.63s950.0217.9420.0230.0350000000000000030.01-0.399000000000000020.076999999999999999348611172.972505999999996259.92207810
217.31115.77214h29m14.59s15d46m19.51s950.0218.0509999999999980.0320000000000000010.0219999999999999990.042000000000000003-0.930000000000000050.1160000000000000134861117.4282130000000004201.9365919999999911
217.29615.73014h29m11.02s15d43m47.69s950.0215.4870.0109999999999999990.00300000000000000010.0179999999999999990.0010.100000000000000013486111167.738282198.89024312
217.27915.74614h29m06.85s15d44m45.74s950.0217.7510000000000010.0210000000000000010.0270.0149999999999999990.0500000000000000030.0869999999999999943486111152.512542228.70215813
217.29815.76014h29m11.60s15d45m35.21s950.0215.7420000000000010.0109999999999999990.0160.0060000000000000001-0.00800000000000000020.109348611168.740981000000005221.87221914
217.34915.80714h29m23.79s15d48m23.43s950.0217.520.0190.0190.0190.00400000000000000010.0800000000000000023486111174.98033548.02110299999999715
217.29315.80714h29m10.39s15d48m24.89s950.0214.5980000000000010.00800000000000000020.00300000000000000010.012999999999999999-0.0429999999999999970.0929999999999999993486111134.386258331.8491950000000116
217.29915.80214h29m11.65s15d48m07.24s950.0216.7280000000000020.0160.0010.0320000000000000010.010.0943486111110.518047335.8446410000000217
217.32315.82614h29m17.40s15d49m34.13s840.0218.7590.0369999999999999980.0179999999999999990.056000000000000001-0.0459999999999999990.0919999999999999983486111191.5126239999999911.40079000000000118

Let's look at where these are in relation to are target. We'll need to convert the RA, Dec in the table to pixel coordinates. That's where the World Coordinate System (WCS) transformation comes in.

In [106]:
wcs = astropy.wcs.WCS(hdu.header)
WARNING: FITSFixedWarning: RADECSYS= 'ICRS ' / Astrometric system 
RADECSYS is non-standard, use RADESYSa. [astropy.wcs.wcs]
WARNING:astropy:FITSFixedWarning: RADECSYS= 'ICRS ' / Astrometric system 
RADECSYS is non-standard, use RADESYSa.
WARNING: FITSFixedWarning: Removed redundant SCAMP distortion parameters because SIP parameters are also present [astropy.wcs.wcs]
WARNING:astropy:FITSFixedWarning: Removed redundant SCAMP distortion parameters because SIP parameters are also present

In [107]:
plt.figure(figsize=(10, 10))
plt.imshow(hdu.data, vmin=mid-std, vmax=mid+3*std, cmap='binary')
plt.xlim(matching_row['XWIN_IMAGE'] - 256, matching_row['XWIN_IMAGE'] + 256)
plt.ylim(matching_row['YWIN_IMAGE'] - 256, matching_row['YWIN_IMAGE'] + 256)

# Note: last argument is 'origin': FITS standard uses 1-based Fortran-like
# indexing, but Python uses 0-based C-like indexing. In this case, we are
# aligning these locations to a Python array, so we want 0-based indexing.

x, y = wcs.all_world2pix(calib_table['ra'], calib_table['dec'], 0)
plt.scatter(x, y, facecolor='none', edgecolor='red')

# I happen to know that these images are upside down; use APLPy or the like to
# automatically orient North upward
plt.gca().invert_yaxis()

plt.xlabel('pixel $x$')
plt.ylabel('pixel $y$')
Out[107]:
<matplotlib.text.Text at 0x1217a7c90>