Beispiel #1
0
def test_plot_functions():
    # This is only a smoke test
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
    data = np.zeros((20, 20, 20))
    data[3:-3, 3:-3, 3:-3] = 1
    img = nibabel.Nifti1Image(data, mni_affine)
    ortho_slicer = plot_anat(img, dim=True)
    # Test saving with empty plot
    z_slicer = plot_anat(anat_img=False, display_mode='z')
    ortho_slicer.savefig(tempfile.TemporaryFile())
    z_slicer = plot_anat(display_mode='z')
    ortho_slicer.savefig(tempfile.TemporaryFile())
    z_slicer.add_edges(img, color='c')

    for func in [plot_anat, plot_img, plot_stat_map,
                 plot_epi, plot_glass_brain]:
        ortho_slicer = func(img, cut_coords=(80, -120, -60))
        # Saving forces a draw, and thus smoke-tests the axes locators
        ortho_slicer.savefig(tempfile.TemporaryFile())
        ortho_slicer.add_edges(img, color='c')

        # Smoke test coordinate finder, with and without mask
        masked_img = nibabel.Nifti1Image(np.ma.masked_equal(data, 0),
                                         mni_affine)
        func(masked_img, display_mode='x')
        func(img, display_mode='y')

        out = func(img, output_file=tempfile.TemporaryFile(suffix='.png'))
        assert_true(out is None)
    pl.close('all')
def reason_pylab():
    from .utils import deliver_image
    def _canvas_deliver(canvas):
        tf = tempfile.TemporaryFile()
        canvas.print_png(tf)
        tf.seek(0)
        img_data = base64.b64encode(tf.read())
        tf.close()
        deliver_image(img_data)
    def reason_draw_if_interactive():
        if matplotlib.is_interactive():
            figManager =  Gcf.get_active()
            if figManager is not None:
                _canvas_deliver(figManager.canvas)
    def reason_show(mainloop = True):
        # We ignore mainloop here
        for manager in Gcf.get_all_fig_managers():
            _canvas_deliver(manager.canvas)
    # Matplotlib has very nice backend overriding.
    # We should really use that.  This is just a hack.
    import matplotlib
    matplotlib.use("agg") # Hotfix for when we import pylab below
    new_agg = imp.new_module("reason_agg")
    import matplotlib.backends.backend_agg as bagg
    new_agg.__dict__.update(bagg.__dict__)
    new_agg.__dict__.update(
        {'show': reason_show,
         'draw_if_interactive': reason_draw_if_interactive})
    sys.modules["reason_agg"] = new_agg
    bagg.draw_if_interactive = reason_draw_if_interactive
    from matplotlib._pylab_helpers import Gcf
    matplotlib.rcParams["backend"] = "module://reason_agg"
    import pylab
    pylab.switch_backend("module://reason_agg")
Beispiel #3
0
def test_demo_plot_map():
    # This is only a smoke test
    mp.use("svg", warn=False)
    import pylab as pl

    pl.switch_backend("svg")
    demo_plot_map()
def test_plot_anat():
    # This is only a smoke test
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
    data = np.zeros((20, 20, 20))
    data[3:-3, 3:-3, 3:-3] = 1
    img = nibabel.Nifti1Image(data, mni_affine)
    ortho_slicer = plot_anat(img, dim=True)
    ortho_slicer = plot_anat(img, cut_coords=(80, -120, -60))
    # Saving forces a draw, and thus smoke-tests the axes locators
    pl.savefig(tempfile.TemporaryFile())
    ortho_slicer.edge_map(img, color='c')

    # Test saving with empty plot
    z_slicer = plot_anat(anat_img=False, slicer='z')
    pl.savefig(tempfile.TemporaryFile())
    z_slicer = plot_anat(slicer='z')
    pl.savefig(tempfile.TemporaryFile())
    z_slicer.edge_map(img, color='c')
    # Smoke test coordinate finder, with and without mask
    masked_img = nibabel.Nifti1Image(np.ma.masked_equal(data, 0),
                                     mni_affine)
    plot_img(masked_img, slicer='x')
    plot_img(img, slicer='y')
Beispiel #5
0
def test_replace_inside():
    # This is only a smoke test
    mp.use("svg", warn=False)
    import pylab as pl

    pl.switch_backend("svg")
    replace_inside(pl.cm.jet, pl.cm.hsv, 0.2, 0.8)
Beispiel #6
0
def test_replace_inside():
    # This is only a smoke test
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
    replace_inside(pl.cm.jet, pl.cm.hsv, .2, .8)
    # We also test with gnuplot, which is defined using function
    replace_inside(pl.cm.gnuplot, pl.cm.gnuplot2, .2, .8)
def test_demo_plot_map():
    # This is only a smoke test
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
    demo_plot_map()
    # Test the black background code path
    demo_plot_map(black_bg=True)
Beispiel #8
0
def test_plot_map_with_auto_cut_coords():
    import pylab as pl
    pl.switch_backend('svg')
    data = np.zeros((20, 20, 20))
    data[3:-3, 3:-3, 3:-3] = 1

    for slicer in 'xyz':
        plot_map(data, np.eye(4), cut_coords=None, slicer=slicer,
                 black_bg=True)
Beispiel #9
0
def test_plot_anat():
    # This is only a smoke test
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
    ortho_slicer = plot_anat()
    data = np.zeros((100, 100, 100))
    data[3:-3, 3:-3, 3:-3] = 1
    ortho_slicer.edge_map(data, mni_sform, color='c')
Beispiel #10
0
def test_demo_ortho_slicer():
    # This is only a smoke test
    # conditioned on presence of MNI templated
    if not find_mni_template():
        raise nose.SkipTest("MNI Template is absent for the smoke test")
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
    demo_ortho_slicer()
def test_plot_img_with_auto_cut_coords():
    import pylab as pl
    pl.switch_backend('svg')
    data = np.zeros((20, 20, 20))
    data[3:-3, 3:-3, 3:-3] = 1
    img = nibabel.Nifti1Image(data, np.eye(4))

    for slicer in 'xyz':
        plot_img(img, cut_coords=None, slicer=slicer, black_bg=True)
Beispiel #12
0
def test_demo_ortho_slicer():
    # This is only a smoke test
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
    pl.clf()
    oslicer = OrthoSlicer(cut_coords=(0, 0, 0))
    img = load_mni152_template()
    oslicer.add_overlay(img, cmap=pl.cm.gray)
    oslicer.close()
Beispiel #13
0
def test_demo_plot_roi():
    # This is only a smoke test
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
    demo_plot_roi()
    # Test the black background code path
    demo_plot_roi(black_bg=True)

    out = demo_plot_roi(output_file=tempfile.TemporaryFile(suffix='.png'))
    assert_true(out is None)
Beispiel #14
0
def test_demo_ortho_projector():
    # This is only a smoke test
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
    pl.clf()
    img = load_mni152_template()
    oprojector = OrthoProjector.init_with_figure(img=img)
    oprojector.add_overlay(img, cmap=pl.cm.gray)
    oprojector.savefig(tempfile.TemporaryFile())
    oprojector.close()
Beispiel #15
0
def test_plot_map_empty():
    # Test that things don't crash when we give a map with nothing above
    # threshold
    # This is only a smoke test
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
    data = np.zeros((20, 20, 20))
    plot_anat(data, mni_sform)
    plot_map(data, mni_sform, slicer='y', threshold=1)
    pl.close('all')
Beispiel #16
0
def test_stacked_slicer():
    # Test stacked slicers, like the XSlicer
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
    pl.clf()
    img = load_mni152_template()
    slicer = XSlicer.init_with_figure(img=img, cut_coords=3)
    slicer.add_overlay(img, cmap=pl.cm.gray)
    # Forcing a layout here, to test the locator code
    slicer.savefig(tempfile.TemporaryFile())
    slicer.close()
def test_plot_img_empty():
    # Test that things don't crash when we give a map with nothing above
    # threshold
    # This is only a smoke test
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
    data = np.zeros((20, 20, 20))
    img = nibabel.Nifti1Image(data, mni_affine)
    plot_anat(img)
    plot_img(img, slicer='y', threshold=1)
    pl.close('all')
Beispiel #18
0
def test_demo_ortho_slicer():
    # This is only a smoke test
    # conditioned on presence of MNI templated
    if not find_mni_template():
        raise nose.SkipTest("MNI Template is absent for the smoke test")
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
    pl.clf()
    oslicer = OrthoSlicer(cut_coords=(0, 0, 0))
    img, _ = _AnatCache.get_anat()
    oslicer.add_overlay(img, cmap=pl.cm.gray)
Beispiel #19
0
def test_plot_anat():
    # This is only a smoke test
    mp.use("svg", warn=False)
    import pylab as pl

    pl.switch_backend("svg")
    data = np.zeros((20, 20, 20))
    data[3:-3, 3:-3, 3:-3] = 1
    ortho_slicer = plot_anat(data, mni_sform, dim=True)
    ortho_slicer = plot_anat(data, mni_sform, cut_coords=(80, -120, -60))
    # Saving forces a draw, and thus smoke-tests the axes locators
    pl.savefig(tempfile.TemporaryFile())
    ortho_slicer.edge_map(data, mni_sform, color="c")

    z_slicer = plot_anat(slicer="z")
    pl.savefig(tempfile.TemporaryFile())
    z_slicer.edge_map(data, mni_sform, color="c")
    # Smoke test coordinate finder, with and without mask
    plot_map(np.ma.masked_equal(data, 0), mni_sform, slicer="x")
    plot_map(data, mni_sform, slicer="y")
Beispiel #20
0
	stat.py
	Used to create plots of execution times.
	
	Stronly inspired by http://stackoverflow.com/a/16598291/4620080

	Author: Martin Storgaard and Konstantinos Mampentzidis
"""
from pylab import plot, show, savefig, xlim, figure, \
                hold, ylim, legend, boxplot, setp, axes, \
                title, ylabel, xlabel, subplots_adjust, suptitle, switch_backend

from utils import get_test_cases, get_test_case
from sys import argv
import numpy as np
switch_backend('TKAgg')
# Built-in colors: Blue, Green, Red,
# Cyan, Magenta, Yellow and Black
colors = "bgrcmyk"
# Number of algorithms to be plotted
num_algs = 2
#
if len(argv) != 2:
	print "Use ./stat.py [query | del | ins] to generate graphs"
	exit()
	
reading = argv[1]
plural = ""
if reading == "query":
	plural = "queries"
elif reading == "del":
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import tempfile

import numpy as np

from nose import SkipTest
try:
    import matplotlib as mp
    # Make really sure that we don't try to open an Xserver connection.
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
except ImportError:
    raise SkipTest('Could not import matplotlib')

from ..activation_maps import demo_plot_map, plot_anat, plot_map
from ..anat_cache import mni_sform, _AnatCache



def test_demo_plot_map():
    # This is only a smoke test
    mp.use('svg', warn=False)
    import pylab as pl
    pl.switch_backend('svg')
    demo_plot_map()
    # Test the black background code path
    demo_plot_map(black_bg=True)

'''
Created on Oct 29, 2013

@author: leal
'''

import nxs
import time
import numpy as np
import pylab as plt
plt.switch_backend('macosx')
#import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import LogNorm

partial_time = time.time()
start_time = time.time()

def timeit():
  global partial_time
  now = time.time()
  diff_total = now - start_time
  diff_partial = now - partial_time
  partial_time = time.time()
  print '**** Time: last: %dm %ds :: total: %dm %ds' % (int(diff_partial // 60),
    int(diff_partial % 60), int(diff_total // 60), int(diff_total % 60))


class NexusReader(object):
    '''
    Functions to a read a nexus file
"""
Copied from despotic/examples/gmcChem and modified
"""
from __future__ import print_function
import matplotlib
import pylab as pl
pl.switch_backend('Qt4Agg')
from astropy import units as u
from astropy import constants
import paths
from paths import fpath
from astropy.utils.console import ProgressBar
import pprint

# Import the despotic library and the NL99 network; also import numpy
from despotic import cloud
import despotic
import os
import numpy as np

# Use the Milky Way GMC file as a base
gmc=cloud('cloud.desp')

from despotic.chemistry import NL99
# gmc.setChemEq(network=NL99)

def turb_heating_generator(lengthscale=1*u.pc, turbulence=True):
    def turb_heating(cloud, lengthscale=lengthscale):
        """ Turbulent heating rate depends on cloud linewidth
        (sigma_nonthermal) and driving scale of the turbulence
        DESPOTIC wants units of erg/s/H (per hydrogen), so the turbulent
Beispiel #24
0
        print "Failed to create PNG for %s. (%s)" % (filename, str(e))
        html += "<td>Failed to create PNG"
        thtml += "<td>Failed to create PNG"
        if options.crash:
            raise

    try:
        svg_filename = filename[:-2] + "svg"
        f.canvas.print_svg("./output/" + svg_filename, dpi=f.dpi)
        html += "<td><img src='%s' width='%dpx' height='%dpx' />" % (svg_filename, w, h)
    except Exception, e:
        print "Failed to create SVG for %s. (%s)" % (filename, str(e))
        html += "<td>Failed to create SVG"
        if options.crash:
            raise
    switch_backend('module://mplh5canvas.backend_h5canvas')
    html += "</tr>"
    thtml += "</tr>"

print "Finished processing files..."
html += "</table><script> var total_plots = " + str(count) + "; "
pi = """
function connect() {
  s = new WebSocket("ws://192.168.184.1:8123");
}

function put_images() {
  for (var i=0; i<total_plots+1;i++) { 
   try {
   s.send(document.getElementById("name_"+i).innerText.split(".py")[0] + ".png " + document.getElementById("canvas_"+i).toDataURL());
   } catch (err) {}
Beispiel #25
0
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import tempfile

import numpy as np

from nose import SkipTest

try:
    import matplotlib as mp

    # Make really sure that we don't try to open an Xserver connection.
    mp.use("svg", warn=False)
    import pylab as pl

    pl.switch_backend("svg")
except ImportError:
    raise SkipTest("Could not import matplotlib")

from ..activation_maps import demo_plot_map, plot_anat, plot_map
from ..anat_cache import mni_sform, _AnatCache


def test_demo_plot_map():
    # This is only a smoke test
    mp.use("svg", warn=False)
    import pylab as pl

    pl.switch_backend("svg")
    demo_plot_map()
import numpy as np
import tools.nbc as cal
import tools.shapes as s
import tools.diagnostics as di
import tools.plots as pl
import fitsio as fi
import pylab as plt
import os, yaml, argparse

plt.switch_backend("agg")


def main(args):
	im3shape_columns = ["e1", "e2", "mean_psf_e1_sky", "mean_psf_e2_sky", "mean_psf_fwhm", "snr", "mean_rgpp_rp", "radius", "coadd_objects_id", "mean_flux", "n_exposure", "stamp_size", "info_flag", "is_bulge", "tilename"]
	truth_columns = ['DES_id', 'cosmos_ident', 'cosmos_photoz', 'sextractor_pixel_offset', 'true_g1', 'true_g2', 'intrinsic_e1', 'intrinsic_e2', 'ra', 'dec', 'hlr', 'mag', 'flux']

	# Load the y1 data
	if args.calculate or args.catalogue:
		y1v2 = s.shapecat(res=config["i3s_dir"])
		y1v2.load(truth=False, prune=True, cols=[im3shape_columns,truth_columns])
		y1v2.res=y1v2.res[y1v2.res["info_flag"]==0]
	

	# And the simulation results
	if args.calculate:
		if ".fits" not in config["hoopoe_dir"]:
			hoopoe = s.shapecat(res="%s/bord-fits/main"%config["hoopoe_dir"] ,truth="%s/truth"%config["hoopoe_dir"])
			hoopoe.load(truth=True, cols=[im3shape_columns,truth_columns])

		else:
			hoopoe = s.shapecat(res=config["hoopoe_dir"], truth=config["hoopoe_dir"] )