Commit 151c4e69 authored by Martin Reinecke's avatar Martin Reinecke

put plotting functionality into a class

parent 63789fe6
...@@ -79,8 +79,9 @@ if __name__ == '__main__': ...@@ -79,8 +79,9 @@ if __name__ == '__main__':
reconstruction = sky(H.position) reconstruction = sky(H.position)
ift.plot(reconstruction, title='reconstruction') plot = ift.Plot()
ift.plot(GR.adjoint_times(data), title='data') plot.add(reconstruction, title='reconstruction')
ift.plot(sky(mock_position), title='truth') plot.add(GR.adjoint_times(data), title='data')
ift.plot_finish(nx=3, xsize=16, ysize=5, title="results", plot.add(sky(mock_position), title='truth')
name="bernoulli.png") plot.output(nx=3, xsize=16, ysize=5, title="results",
name="bernoulli.png")
...@@ -103,18 +103,17 @@ if __name__ == '__main__': ...@@ -103,18 +103,17 @@ if __name__ == '__main__':
# PLOTTING # PLOTTING
rg = isinstance(position_space, ift.RGSpace) rg = isinstance(position_space, ift.RGSpace)
plot = ift.Plot()
if rg and len(position_space.shape) == 1: if rg and len(position_space.shape) == 1:
ift.plot([HT(MOCK_SIGNAL), GR.adjoint(data), HT(m)], plot.add([HT(MOCK_SIGNAL), GR.adjoint(data), HT(m)],
label=['Mock signal', 'Data', 'Reconstruction'], label=['Mock signal', 'Data', 'Reconstruction'],
alpha=[1, .3, 1]) alpha=[1, .3, 1])
ift.plot(mask_to_nan(mask, HT(m-MOCK_SIGNAL)), title='Residuals') plot.add(mask_to_nan(mask, HT(m-MOCK_SIGNAL)), title='Residuals')
ift.plot_finish(nx=2, ny=1, xsize=10, ysize=4, plot.output(nx=2, ny=1, xsize=10, ysize=4, title="getting_started_1")
title="getting_started_1")
else: else:
ift.plot(HT(MOCK_SIGNAL), title='Mock Signal') plot.add(HT(MOCK_SIGNAL), title='Mock Signal')
ift.plot(mask_to_nan(mask, (GR(Mask)).adjoint(data)), plot.add(mask_to_nan(mask, (GR(Mask)).adjoint(data)),
title='Data') title='Data')
ift.plot(HT(m), title='Reconstruction') plot.add(HT(m), title='Reconstruction')
ift.plot(mask_to_nan(mask, HT(m-MOCK_SIGNAL)), title='Residuals') plot.add(mask_to_nan(mask, HT(m-MOCK_SIGNAL)), title='Residuals')
ift.plot_finish(nx=2, ny=2, xsize=10, ysize=10, plot.output(nx=2, ny=2, xsize=10, ysize=10, title="getting_started_1")
title="getting_started_1")
...@@ -99,8 +99,9 @@ if __name__ == '__main__': ...@@ -99,8 +99,9 @@ if __name__ == '__main__':
# Plot results # Plot results
signal = sky(mock_position) signal = sky(mock_position)
reconst = sky(H.position) reconst = sky(H.position)
ift.plot(signal, title='Signal') plot = ift.Plot()
ift.plot(GR.adjoint(data), title='Data') plot.add(signal, title='Signal')
ift.plot(reconst, title='Reconstruction') plot.add(GR.adjoint(data), title='Data')
ift.plot(reconst - signal, title='Residuals') plot.add(reconst, title='Reconstruction')
ift.plot_finish(name='getting_started_2.png', xsize=16, ysize=16) plot.add(reconst - signal, title='Residuals')
plot.output(name='getting_started_2.png', xsize=16, ysize=16)
...@@ -83,10 +83,11 @@ if __name__ == '__main__': ...@@ -83,10 +83,11 @@ if __name__ == '__main__':
INITIAL_POSITION = ift.from_random('normal', domain) INITIAL_POSITION = ift.from_random('normal', domain)
position = INITIAL_POSITION position = INITIAL_POSITION
ift.plot(signal(MOCK_POSITION), title='ground truth') plot = ift.Plot()
ift.plot(R.adjoint_times(data), title='data') plot.add(signal(MOCK_POSITION), title='ground truth')
ift.plot([A(MOCK_POSITION)], title='power') plot.add(R.adjoint_times(data), title='data')
ift.plot_finish(nx=3, xsize=16, ysize=5, title="setup", name="setup.png") plot.add([A(MOCK_POSITION)], title='power')
plot.output(nx=3, xsize=16, ysize=5, title="setup", name="setup.png")
# number of samples used to estimate the KL # number of samples used to estimate the KL
N_samples = 20 N_samples = 20
...@@ -100,17 +101,18 @@ if __name__ == '__main__': ...@@ -100,17 +101,18 @@ if __name__ == '__main__':
KL, convergence = minimizer(KL) KL, convergence = minimizer(KL)
position = KL.position position = KL.position
ift.plot(signal(position), title="reconstruction") plot = ift.Plot()
ift.plot([A(position), A(MOCK_POSITION)], title="power") plot.add(signal(position), title="reconstruction")
ift.plot_finish(nx=2, xsize=12, ysize=6, title="loop", name="loop.png") plot.add([A(position), A(MOCK_POSITION)], title="power")
plot.output(nx=2, xsize=12, ysize=6, title="loop", name="loop.png")
plot = ift.Plot()
sc = ift.StatCalculator() sc = ift.StatCalculator()
for sample in samples: for sample in samples:
sc.add(signal(sample+position)) sc.add(signal(sample+position))
ift.plot(sc.mean, title="mean") plot.add(sc.mean, title="mean")
ift.plot(ift.sqrt(sc.var), title="std deviation") plot.add(ift.sqrt(sc.var), title="std deviation")
powers = [A(s+position) for s in samples] powers = [A(s+position) for s in samples]
ift.plot([A(position), A(MOCK_POSITION)]+powers, title="power") plot.add([A(position), A(MOCK_POSITION)]+powers, title="power")
ift.plot_finish(nx=3, xsize=16, ysize=5, title="results", plot.output(nx=3, xsize=16, ysize=5, title="results", name="results.png")
name="results.png")
...@@ -20,21 +20,24 @@ def plot_test(): ...@@ -20,21 +20,24 @@ def plot_test():
# Start various plotting tests # Start various plotting tests
ift.plot(field_rg1_1, title='Single plot') plot = ift.Plot()
ift.plot_finish() plot.add(field_rg1_1, title='Single plot')
plot.output()
ift.plot(field_rg2, title='2d rg')
ift.plot([field_rg1_1, field_rg1_2], title='list 1d rg', label=['1', '2']) plot = ift.Plot()
ift.plot(field_rg1_2, title='1d rg, xmin, ymin', xmin=0.5, ymin=0., plot.add(field_rg2, title='2d rg')
plot.add([field_rg1_1, field_rg1_2], title='list 1d rg', label=['1', '2'])
plot.add(field_rg1_2, title='1d rg, xmin, ymin', xmin=0.5, ymin=0.,
xlabel='xmin=0.5', ylabel='ymin=0') xlabel='xmin=0.5', ylabel='ymin=0')
ift.plot_finish(title='Three plots') plot.output(title='Three plots')
ift.plot(field_hp, title='HP planck-color', colormap='Planck-like') plot = ift.Plot()
ift.plot(field_rg1_2, title='1d rg') plot.add(field_hp, title='HP planck-color', colormap='Planck-like')
ift.plot(field_ps) plot.add(field_rg1_2, title='1d rg')
ift.plot(field_gl, title='GL') plot.add(field_ps)
ift.plot(field_rg2, title='2d rg') plot.add(field_gl, title='GL')
ift.plot_finish(nx=2, ny=3, title='Five plots') plot.add(field_rg2, title='2d rg')
plot.output(nx=2, ny=3, title='Five plots')
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -69,7 +69,7 @@ from .minimization.line_energy import LineEnergy ...@@ -69,7 +69,7 @@ from .minimization.line_energy import LineEnergy
from .minimization.energy_adapter import EnergyAdapter from .minimization.energy_adapter import EnergyAdapter
from .sugar import * from .sugar import *
from .plotting.plot import plot, plot_finish from .plotting.plot import Plot
from .library.amplitude_model import AmplitudeModel from .library.amplitude_model import AmplitudeModel
from .library.inverse_gamma_model import InverseGammaModel from .library.inverse_gamma_model import InverseGammaModel
......
...@@ -262,82 +262,81 @@ def _plot(f, ax, **kwargs): ...@@ -262,82 +262,81 @@ def _plot(f, ax, **kwargs):
raise ValueError("Field type not(yet) supported") raise ValueError("Field type not(yet) supported")
_plots = [] class Plot(object):
_kwargs = [] def __init__(self):
self._plots = []
self._kwargs = []
def plot(f, **kwargs):
"""Add a figure to the current list of plots.
def add(self, f, **kwargs):
Notes """Add a figure to the current list of plots.
-----
After doing one or more calls `plot()`, one also needs to call Notes
`plot_finish()` to output the result. -----
After doing one or more calls `plot()`, one also needs to call
Parameters `plot_finish()` to output the result.
----------
f: Field, or list of Field objects Parameters
If `f` is a single Field, it must live over a single `RGSpace`, ----------
`PowerSpace`, `HPSpace`, `GLSPace`. f: Field, or list of Field objects
If it is a list, all list members must be Fields living over the same If `f` is a single Field, it must live over a single `RGSpace`,
one-dimensional `RGSpace` or `PowerSpace`. `PowerSpace`, `HPSpace`, `GLSPace`.
title: string If it is a list, all list members must be Fields living over the
title of the plot same one-dimensional `RGSpace` or `PowerSpace`.
xlabel: string title: string
label for the x axis title of the plot
ylabel: string xlabel: string
label for the y axis label for the x axis
[xyz]min, [xyz]max: float ylabel: string
limits for the values to plot label for the y axis
colormap: string [xyz]min, [xyz]max: float
color map to use for the plot (if it is a 2D plot) limits for the values to plot
linewidth: float or list of floats colormap: string
line width color map to use for the plot (if it is a 2D plot)
label: string of list of strings linewidth: float or list of floats
annotation string line width
alpha: float or list of floats label: string of list of strings
transparency value annotation string
""" alpha: float or list of floats
_plots.append(f) transparency value
_kwargs.append(kwargs) """
self._plots.append(f)
self._kwargs.append(kwargs)
def plot_finish(**kwargs):
"""Plot the accumulated list of figures.
def output(self, **kwargs):
Parameters """Plot the accumulated list of figures.
----------
title: string Parameters
title of the full plot ----------
nx, ny: integer (default: square root of the numer of plots, rounded up) title: string
number of subplots to use in x- and y-direction title of the full plot
xsize, ysize: float (default: 6) nx, ny: integer (default: square root of the numer of plots, rounded up)
dimensions of the full plot in inches number of subplots to use in x- and y-direction
name: string (default: "") xsize, ysize: float (default: 6)
if left empty, the plot will be shown on the screen, dimensions of the full plot in inches
otherwise it will be written to a file with the given name. name: string (default: "")
Supported extensions: .png and .pdf if left empty, the plot will be shown on the screen,
""" otherwise it will be written to a file with the given name.
global _plots, _kwargs Supported extensions: .png and .pdf
import matplotlib.pyplot as plt """
nplot = len(_plots) import matplotlib.pyplot as plt
fig = plt.figure() nplot = len(self._plots)
if "title" in kwargs: fig = plt.figure()
plt.suptitle(kwargs.pop("title")) if "title" in kwargs:
nx = kwargs.pop("nx", int(np.ceil(np.sqrt(nplot)))) plt.suptitle(kwargs.pop("title"))
ny = kwargs.pop("ny", int(np.ceil(np.sqrt(nplot)))) nx = kwargs.pop("nx", int(np.ceil(np.sqrt(nplot))))
if nx*ny < nplot: ny = kwargs.pop("ny", int(np.ceil(np.sqrt(nplot))))
raise ValueError( if nx*ny < nplot:
'Figure dimensions not sufficient for number of plots. ' raise ValueError(
'Available plot slots: {}, number of plots: {}' 'Figure dimensions not sufficient for number of plots. '
.format(nx*ny, nplot)) 'Available plot slots: {}, number of plots: {}'
xsize = kwargs.pop("xsize", 6) .format(nx*ny, nplot))
ysize = kwargs.pop("ysize", 6) xsize = kwargs.pop("xsize", 6)
fig.set_size_inches(xsize, ysize) ysize = kwargs.pop("ysize", 6)
for i in range(nplot): fig.set_size_inches(xsize, ysize)
ax = fig.add_subplot(ny, nx, i+1) for i in range(nplot):
_plot(_plots[i], ax, **_kwargs[i]) ax = fig.add_subplot(ny, nx, i+1)
fig.tight_layout() _plot(self._plots[i], ax, **self._kwargs[i])
_makeplot(kwargs.pop("name", None)) fig.tight_layout()
_plots = [] _makeplot(kwargs.pop("name", None))
_kwargs = []
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment