Skip to content

Commit

Permalink
Fix print statements for Py3
Browse files Browse the repository at this point in the history
  • Loading branch information
taldcroft committed Feb 6, 2015
1 parent 01ce577 commit 7201f04
Show file tree
Hide file tree
Showing 13 changed files with 66 additions and 67 deletions.
8 changes: 4 additions & 4 deletions source/astropy-UVES/UVES.rst
Expand Up @@ -253,7 +253,7 @@ than two lines::
# Let's just print the setup on the screen
# We'll see if it's all the same.
for f in filelist:
print read_setup(f)
print(read_setup(f))

.. raw:: html

Expand Down Expand Up @@ -427,7 +427,7 @@ spectroscopically estimated surface gravity::
of the following wavelengths relative to :math:`H_\alpha`::

waveclosetoHa = np.array([6562.,6563,6565.]) * u.AA
print wave2doppler(waveclosetoHa, 656.489 * u.nm)
print(wave2doppler(waveclosetoHa, 656.489 * u.nm))

I get -132, -86 and +5 km/s.

Expand All @@ -441,7 +441,7 @@ spectroscopically estimated surface gravity::
doppler = ((w-w0)/w0 * c)
return doppler

print wave2doppler(waveclosetoHa, 656.489 * u.nm).decompose().to(u.km/u.s)
print(wave2doppler(waveclosetoHa, 656.489 * u.nm).decompose().to(u.km/u.s))

.. raw:: html

Expand Down Expand Up @@ -579,7 +579,7 @@ for the first spectrum::

ew = fcaII[0,:] - 1.
ew = ew[:-1] * np.diff(wcaII.to(u.AA).value)
print ew.sum()
print(ew.sum())

Using ``numpy`` array notation we can actually process all spectra at once::

Expand Down
2 changes: 1 addition & 1 deletion source/astropy/wcs.rst
Expand Up @@ -160,7 +160,7 @@ image have a valid position on the sky.
values = image[py, px]

# Print out the values
print values
print(values)

which gives::

Expand Down
4 changes: 2 additions & 2 deletions source/core/ipython.rst
Expand Up @@ -35,7 +35,7 @@ matplotlib routines and are widely used in scientific code.
`import <http://docs.python.org/reference/simple_stmts.html#import>`_ statement
makes the functions in a module available::

print time.ctime() # will fail
print(time.ctime()) # will fail
# need to import the time module first
import time
time.ctime() # prints the system time
Expand Down Expand Up @@ -122,7 +122,7 @@ Try::

y = dict((x, 'value is %d' % x**2) for x in range(10))
y
print y
print(y)

Further resources
^^^^^^^^^^^^^^^^^^
Expand Down
6 changes: 3 additions & 3 deletions source/files/asciifiles.rst
Expand Up @@ -90,12 +90,12 @@ But what we'd really like to do is read the file line by line. There are several

f = open('data.txt', 'r')
for line in f:
print repr(line)
print(repr(line))

Notice the indent before ``print``, which is necessary to indicate that we are inside the loop (there is no ``end for`` in Python). Note that we are using ``repr()`` to show any invisible characters (this will be useful in a minute). The output should now look something like this::

>>> for line in f:
print repr(line)
print(repr(line))

'RAJ DEJ Jmag e_Jmag\n'
'2000 (deg) 2000 (deg) 2MASS (mag) (mag) \n'
Expand Down Expand Up @@ -178,7 +178,7 @@ We can put all this together to write a little script to read the data from the
columns = line.split()
name = columns[2]
j = float(columns[3])
print name, j
print(name, j)
f.close()

Expand Down
20 changes: 10 additions & 10 deletions source/fitting/classes.rst
Expand Up @@ -25,12 +25,12 @@ declaration indicating a no-op.
Class instances are mutable, meaning that attributes and functions can be added
after instantiation::

print h.msg
print(h.msg)

There is no attribute ``msg``, so add one::

h.msg = "Hello World!"
print h.msg
print(h.msg)

Create a class with a static string attribute ``msg1`` and a class method
``echo`` to print the attribute. Comments begin with a ``#`` and extend to the
Expand All @@ -40,12 +40,12 @@ end of the line::
# static attribute string "msg1"
msg1 = "Hello"
def echo(self):
print self.msg1
print(self.msg1)

print "Hello's msg1:", Hello.msg1
print("Hello's msg1: {0}".format(Hello.msg1))
h = Hello()
h.echo()
print h
print(h)

Create a class with a constructor definition. Initialize an attribute ``msg2``
at class instance creation time::
Expand All @@ -56,11 +56,11 @@ at class instance creation time::
# attribute "msg2" initialized in constructor
self.msg2 = msg2
def echo(self):
print self.msg2
print(self.msg2)

w = World()
w.echo()
print w
print(w)


Multiple Inheritance
Expand All @@ -87,7 +87,7 @@ return the attribute ``msg3`` when the class instance is printed with

hw = HelloWorld()
hw.echo()
print hw
print(hw)


Class ``HelloWorld`` is of type ``Hello``, ``World``, and ``HelloWorld``::
Expand Down Expand Up @@ -126,12 +126,12 @@ language operators. Define how a class behaves using the '+' operator::
class Hello:
msg = "Hello"
def __add__(self, lhs):
print self.msg + lhs.msg
print(self.msg + lhs.msg)

class World:
msg = "World"
def __add__(self, rhs):
print self.msg + rhs.msg
print(self.msg + rhs.msg)

Hello() + World()
World() + Hello()
Expand Down
4 changes: 2 additions & 2 deletions source/fitting/image.rst
Expand Up @@ -340,7 +340,7 @@ ERF(sigma/SQRT(2)). We can invert this operation using the inverse
error-function found in SciPy in the special functions module::

import scipy.special
print scipy.special.erfinv(0.90)*numpy.sqrt(2)
print(scipy.special.erfinv(0.90) * numpy.sqrt(2))

.. raw:: html

Expand All @@ -355,7 +355,7 @@ Save the 90% calculated parameter limits::
f.write("NAME VALUE MIN MAX\n")
for name, val, minval, maxval in zip(results.parnames,results.parvals,results.parmins,results.parmaxes):
line = [name, str(val), str(val+minval), str(val+maxval)]
print line
print(line)
f.write(" ".join(line)+"\n")

f.close()
Expand Down
41 changes: 22 additions & 19 deletions source/fitting/low-level.rst
Expand Up @@ -9,17 +9,20 @@ Explore the Sherpa Object Model
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In a new working directory, download a MAST spectrum of :download:`3C 273 <./3c273.fits>`
and start IPython::
and start IPython along with the standard imports::

$ ipython --pylab
$ ipython --matplotlib

import numpy as np
import matplotlib.pyplot as plt

If you have trouble accessing the spectrum you can download it straight away
using Python::

import urllib2
url = 'http://python4astronomers.github.com/_downloads/3c273.fits'
open('3c273.fits', 'wb').write(urllib2.urlopen(url).read())
ls
%ls

Import a few Sherpa classes needed to characterize a fit::

Expand All @@ -29,10 +32,10 @@ Import a few Sherpa classes needed to characterize a fit::
from sherpa.optmethods import LevMar
from sherpa.fit import Fit

Import the Python FITS reader ``pyfits`` and open the spectrum as a table::
Import the Python FITS reader ``astropy.io.fits`` and open the spectrum as a table::

import pyfits
dat = pyfits.open('3c273.fits')[1].data
from astropy.io import fits
dat = fits.open('3c273.fits')[1].data

Access the `WAVELENGTH` and `FLUX` columns from the pyFITS ``RecArray``. Populate
variables represented as ``wave``, ``flux``, and ``err``. Normalize the flux and assume
Expand All @@ -47,13 +50,13 @@ Create a Sherpa ``Data1D`` data set from the NumPy arrays ``wave``, ``flux``, an
``x``, ``y``, and ``staterror``::

data = Data1D('3C 273', wave, flux, err)
print data
print(data)

Array access::

print 'x', data.x
print 'y', data.y
print 'err', data.staterror
print('x {0}'.format(data.x))
print('y {0}'.format(data.y))
print('err {0}'.format(data.staterror))


Define a convenience function ``plot_data`` that calls the matplotlib functions
Expand All @@ -65,10 +68,10 @@ in the Sherpa data set using our new function and its default arguments::

def plot_data(x, y, err=None, fmt='.', clear=True):
if clear:
clf()
plot(x, y, fmt)
plt.clf()
plt.plot(x, y, fmt)
if err is not None:
errorbar(x, y, err, fmt=None, ecolor='b')
plt.errorbar(x, y, err, fmt=None, ecolor='b')

plot_data(data.x, data.y, data.staterror)

Expand All @@ -83,21 +86,21 @@ the ``name`` and ``val`` attributes::
pl = PowLaw1D('pl')
pl.pars
for par in pl.pars:
print par.name, par.val
print('{0} {1}'.format(par.name, par.val))

print pl
print(pl)

Set the power-law reference to be 4000 Angstroms and print out the ``PowLaw1D``
object and its parameter information. Each model parameter is accessible as an
attribute its model. For example, the power-law amplitude is referenced with
``pl.ampl``::

pl.ref = 4000.
print pl
print(pl)

Model parameters are themselves class objects::

print pl.ampl
print(pl.ampl)


.. admonition:: Exercise (for the interested reader): Special methods and properties
Expand Down Expand Up @@ -151,9 +154,9 @@ optimization method. Fit the spectrum to a power-law with least squares

f = Fit(data, pl, Chi2DataVar(), LevMar())
result = f.fit()
print result
print(result)
# or alternatively
print result.format()
print(result.format())

Over-plot the fitted model atop the data points using our convenience function
``plot_data``. This time calculate the model using the best-fit parameter
Expand Down
2 changes: 1 addition & 1 deletion source/intro/comparison.rst
Expand Up @@ -59,7 +59,7 @@ Python::
y = v + x * 12 # OK
y = str(v) + "+x*12" # Two strings can be added (concatenated)
y = str(v+x*12) # Make a string from the number
print x, y, v # print x, y and v.
print(x, y, v) # print x, y and v.

IDL
-----
Expand Down
8 changes: 4 additions & 4 deletions source/intro/quick-tour.rst
Expand Up @@ -109,9 +109,9 @@ uncertainties.
popt, pcov = curve_fit(gaussian, x, y, sigma=e)

# Print results
print "Scale = %.3f +/- %.3f" % (popt[0], sqrt(pcov[0, 0]))
print "Offset = %.3f +/- %.3f" % (popt[1], sqrt(pcov[1, 1]))
print "Sigma = %.3f +/- %.3f" % (popt[2], sqrt(pcov[2, 2]))
print("Scale = %.3f +/- %.3f" % (popt[0], sqrt(pcov[0, 0])))
print("Offset = %.3f +/- %.3f" % (popt[1], sqrt(pcov[1, 1])))
print("Sigma = %.3f +/- %.3f" % (popt[2], sqrt(pcov[2, 2])))

# Plot data
errorbar(x, y, yerr=e, linewidth=1, color='black', fmt=None)
Expand Down Expand Up @@ -213,7 +213,7 @@ together other codes and doing system type tasks.
for noise in noises:
# Run the compiled code "make_data" to make data as a list of x, y, y_smooth
cmd = 'make_data %s %s %s' % (freq, noise, smoothing)
print 'Running', cmd
print('Running {0}'.format(cmd))
out = os.popen(cmd).read()
# out now contains the output from <cmd> as a single string

Expand Down
6 changes: 3 additions & 3 deletions source/local/cfa.rst
Expand Up @@ -92,8 +92,8 @@ Now within ``sherpa`` do::

import scipy
import scipy.linalg
print scipy.__version__
print scipy.linalg.eig([[1,2],[3,4]])
print(scipy.__version__)
print(scipy.linalg.eig([[1,2],[3,4]]))

Now quit and install the rest::

Expand All @@ -117,7 +117,7 @@ Once again fire up ``sherpa`` or ``chips`` and do::
import atpy
import aplpy

print np.__version__
print(np.__version__)

x = np.linspace(0, 20, 100)
plt.plot(x, np.sin(x))
Expand Down
2 changes: 1 addition & 1 deletion source/plotting/matplotlib.rst
Expand Up @@ -781,7 +781,7 @@ clarify the relationship between **pylab** and **pyplot**.
matplotlib work like MATLAB. This is just a package module that you can import::

import matplotlib.pyplot
print sorted(dir(matplotlib.pyplot))
print(sorted(dir(matplotlib.pyplot)))

Likewise pylab is also a module provided by matplotlib that you can import::

Expand Down
12 changes: 4 additions & 8 deletions source/vo/votools.rst
Expand Up @@ -156,7 +156,7 @@ The ``Siap`` acronym stands for *Simple Image Access Protocol* and as with
The returned array contains **66** fields!
::
print image_table.dtype.names
print(image_table.dtype.names)
If all we want is the actual data then the important column is **URL**
while the **filename** column is also useful.
Expand All @@ -183,16 +183,16 @@ We use `pyfits`_ to open the image file and examine its contents.

import pyfits
import aplpy
import matplotlib.pyplot as mpl
import matplotlib.pyplot as plt
hdulist = pyfits.open(filename)

# check for multiple FITS extensions and their contents
# in this case the "PRIMARY" header is empty
for hdu in hdulist:
print hdu.name, type(hdu.data)
print('name: {0} type: {1}'.format(hdu.name, type(hdu.data)))
fig = mpl.figure(figsize=(15, 7))
fig = plt.figure(figsize=(15, 7))
f1 = aplpy.FITSFigure(filename, hdu=1, subplot=[0.1,0.1,0.3,0.65], figure=fig)
f1.set_tick_labels_font(size='x-small')
f1.set_axis_labels_font(size='small')
Expand All @@ -211,7 +211,3 @@ We use `pyfits`_ to open the image file and examine its contents.
f3.hide_yaxis_label()
f3.hide_ytick_labels()
f3.show_colorscale(cmap='spring')

0 comments on commit 7201f04

Please sign in to comment.