Search is not available for this dataset
text
stringlengths 75
104k
|
---|
def ma(self):
"""Represent data as a masked array.
The array is returned with column-first indexing, i.e. for a data file with
columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .
inf and nan are filtered via :func:`numpy.isfinite`.
"""
a = self.array
return numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))
|
def _tcorrel(self, nstep=100, **kwargs):
"""Correlation "time" of data.
The 0-th column of the data is interpreted as a time and the
decay of the data is computed from the autocorrelation
function (using FFT).
.. SeeAlso:: :func:`numkit.timeseries.tcorrel`
"""
t = self.array[0,::nstep]
r = gromacs.collections.Collection([numkit.timeseries.tcorrel(t, Y, nstep=1, **kwargs) for Y in self.array[1:,::nstep]])
return r
|
def set_correlparameters(self, **kwargs):
"""Set and change the parameters for calculations with correlation functions.
The parameters persist until explicitly changed.
:Keywords:
*nstep*
only process every *nstep* data point to speed up the FFT; if
left empty a default is chosen that produces roughly 25,000 data
points (or whatever is set in *ncorrel*)
*ncorrel*
If no *nstep* is supplied, aim at using *ncorrel* data points for
the FFT; sets :attr:`XVG.ncorrel` [25000]
*force*
force recalculating correlation data even if cached values are
available
*kwargs*
see :func:`numkit.timeseries.tcorrel` for other options
.. SeeAlso: :attr:`XVG.error` for details and references.
"""
self.ncorrel = kwargs.pop('ncorrel', self.ncorrel) or 25000
nstep = kwargs.pop('nstep', None)
if nstep is None:
# good step size leads to ~25,000 data points
nstep = len(self.array[0])/float(self.ncorrel)
nstep = int(numpy.ceil(nstep)) # catch small data sets
kwargs['nstep'] = nstep
self.__correlkwargs.update(kwargs) # only contains legal kw for numkit.timeseries.tcorrel or force
return self.__correlkwargs
|
def parse(self, stride=None):
"""Read and cache the file as a numpy array.
Store every *stride* line of data; if ``None`` then the class default is used.
The array is returned with column-first indexing, i.e. for a data file with
columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .
"""
if stride is None:
stride = self.stride
self.corrupted_lineno = []
irow = 0 # count rows of data
# cannot use numpy.loadtxt() because xvg can have two types of 'comment' lines
with utilities.openany(self.real_filename) as xvg:
rows = []
ncol = None
for lineno,line in enumerate(xvg):
line = line.strip()
if len(line) == 0:
continue
if "label" in line and "xaxis" in line:
self.xaxis = line.split('"')[-2]
if "label" in line and "yaxis" in line:
self.yaxis = line.split('"')[-2]
if line.startswith("@ legend"):
if not "legend" in self.metadata: self.metadata["legend"] = []
self.metadata["legend"].append(line.split("legend ")[-1])
if line.startswith("@ s") and "subtitle" not in line:
name = line.split("legend ")[-1].replace('"','').strip()
self.names.append(name)
if line.startswith(('#', '@')) :
continue
if line.startswith('&'):
raise NotImplementedError('{0!s}: Multi-data not supported, only simple NXY format.'.format(self.real_filename))
# parse line as floats
try:
row = [float(el) for el in line.split()]
except:
if self.permissive:
self.logger.warn("%s: SKIPPING unparsable line %d: %r",
self.real_filename, lineno+1, line)
self.corrupted_lineno.append(lineno+1)
continue
self.logger.error("%s: Cannot parse line %d: %r",
self.real_filename, lineno+1, line)
raise
# check for same number of columns as in previous step
if ncol is not None and len(row) != ncol:
if self.permissive:
self.logger.warn("%s: SKIPPING line %d with wrong number of columns: %r",
self.real_filename, lineno+1, line)
self.corrupted_lineno.append(lineno+1)
continue
errmsg = "{0!s}: Wrong number of columns in line {1:d}: {2!r}".format(self.real_filename, lineno+1, line)
self.logger.error(errmsg)
raise IOError(errno.ENODATA, errmsg, self.real_filename)
# finally: a good line
if irow % stride == 0:
ncol = len(row)
rows.append(row)
irow += 1
try:
self.__array = numpy.array(rows).transpose() # cache result
except:
self.logger.error("%s: Failed reading XVG file, possibly data corrupted. "
"Check the last line of the file...", self.real_filename)
raise
finally:
del rows
|
def plot(self, **kwargs):
"""Plot xvg file data.
The first column of the data is always taken as the abscissa
X. Additional columns are plotted as ordinates Y1, Y2, ...
In the special case that there is only a single column then this column
is plotted against the index, i.e. (N, Y).
:Keywords:
*columns* : list
Select the columns of the data to be plotted; the list
is used as a numpy.array extended slice. The default is
to use all columns. Columns are selected *after* a transform.
*transform* : function
function ``transform(array) -> array`` which transforms
the original array; must return a 2D numpy array of
shape [X, Y1, Y2, ...] where X, Y1, ... are column
vectors. By default the transformation is the
identity [``lambda x: x``].
*maxpoints* : int
limit the total number of data points; matplotlib has issues processing
png files with >100,000 points and pdfs take forever to display. Set to
``None`` if really all data should be displayed. At the moment we simply
decimate the data at regular intervals. [10000]
*method*
method to decimate the data to *maxpoints*, see :meth:`XVG.decimate`
for details
*color*
single color (used for all plots); sequence of colors
(will be repeated as necessary); or a matplotlib
colormap (e.g. "jet", see :mod:`matplotlib.cm`). The
default is to use the :attr:`XVG.default_color_cycle`.
*ax*
plot into given axes or create new one if ``None`` [``None``]
*kwargs*
All other keyword arguments are passed on to :func:`matplotlib.pyplot.plot`.
:Returns:
*ax*
axes instance
"""
columns = kwargs.pop('columns', Ellipsis) # slice for everything
maxpoints = kwargs.pop('maxpoints', self.maxpoints_default)
transform = kwargs.pop('transform', lambda x: x) # default is identity transformation
method = kwargs.pop('method', "mean")
ax = kwargs.pop('ax', None)
if columns is Ellipsis or columns is None:
columns = numpy.arange(self.array.shape[0])
if len(columns) == 0:
raise MissingDataError("plot() needs at least one column of data")
if len(self.array.shape) == 1 or self.array.shape[0] == 1:
# special case: plot against index; plot would do this automatically but
# we'll just produce our own xdata and pretend that this was X all along
a = numpy.ravel(self.array)
X = numpy.arange(len(a))
a = numpy.vstack((X, a))
columns = [0] + [c+1 for c in columns]
else:
a = self.array
color = kwargs.pop('color', self.default_color_cycle)
try:
cmap = matplotlib.cm.get_cmap(color)
colors = cmap(matplotlib.colors.Normalize()(numpy.arange(len(columns[1:]), dtype=float)))
except TypeError:
colors = cycle(utilities.asiterable(color))
if ax is None:
ax = plt.gca()
# (decimate/smooth o slice o transform)(array)
a = self.decimate(method, numpy.asarray(transform(a))[columns], maxpoints=maxpoints)
# now deal with infs, nans etc AFTER all transformations (needed for plotting across inf/nan)
ma = numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))
# finally plot (each column separately to catch empty sets)
for column, color in zip(range(1,len(columns)), colors):
if len(ma[column]) == 0:
warnings.warn("No data to plot for column {column:d}".format(**vars()), category=MissingDataWarning)
kwargs['color'] = color
ax.plot(ma[0], ma[column], **kwargs) # plot all other columns in parallel
return ax
|
def plot_coarsened(self, **kwargs):
"""Plot data like :meth:`XVG.plot` with the range of **all** data shown.
Data are reduced to *maxpoints* (good results are obtained
with low values such as 100) and the actual range of observed
data is plotted as a translucent error band around the mean.
Each column in *columns* (except the abscissa, i.e. the first
column) is decimated (with :meth:`XVG.decimate`) and the range
of data is plotted alongside the mean using
:meth:`XVG.errorbar` (see for arguments). Additional
arguments:
:Kewords:
*maxpoints*
number of points (bins) to coarsen over
*color*
single color (used for all plots); sequence of colors
(will be repeated as necessary); or a matplotlib
colormap (e.g. "jet", see :mod:`matplotlib.cm`). The
default is to use the :attr:`XVG.default_color_cycle`.
*method*
Method to coarsen the data. See :meth:`XVG.decimate`
The *demean* keyword has no effect as it is required to be ``True``.
.. SeeAlso:: :meth:`XVG.plot`, :meth:`XVG.errorbar` and :meth:`XVG.decimate`
"""
ax = kwargs.pop('ax', None)
columns = kwargs.pop('columns', Ellipsis) # slice for everything
if columns is Ellipsis or columns is None:
columns = numpy.arange(self.array.shape[0])
if len(columns) < 2:
raise MissingDataError("plot_coarsened() assumes that there is at least one column "
"of data for the abscissa and one or more for the ordinate.")
color = kwargs.pop('color', self.default_color_cycle)
try:
cmap = matplotlib.cm.get_cmap(color)
colors = cmap(matplotlib.colors.Normalize()(numpy.arange(len(columns[1:]), dtype=float)))
except TypeError:
colors = cycle(utilities.asiterable(color))
if ax is None:
ax = plt.gca()
t = columns[0]
kwargs['demean'] = True
kwargs['ax'] = ax
for column, color in zip(columns[1:], colors):
kwargs['color'] = color
self.errorbar(columns=[t, column, column], **kwargs)
return ax
|
def errorbar(self, **kwargs):
"""errorbar plot for a single time series with errors.
Set *columns* keyword to select [x, y, dy] or [x, y, dx, dy],
e.g. ``columns=[0,1,2]``. See :meth:`XVG.plot` for
details. Only a single timeseries can be plotted and the user
needs to select the appropriate columns with the *columns*
keyword.
By default, the data are decimated (see :meth:`XVG.plot`) for
the default of *maxpoints* = 10000 by averaging data in
*maxpoints* bins.
x,y,dx,dy data can plotted with error bars in the x- and
y-dimension (use *filled* = ``False``).
For x,y,dy use *filled* = ``True`` to fill the region between
y±dy. *fill_alpha* determines the transparency of the fill
color. *filled* = ``False`` will draw lines for the error
bars. Additional keywords are passed to
:func:`pylab.errorbar`.
By default, the errors are decimated by plotting the 5% and
95% percentile of the data in each bin. The percentile can be
changed with the *percentile* keyword; e.g. *percentile* = 1
will plot the 1% and 99% perentile (as will *percentile* =
99).
The *error_method* keyword can be used to compute errors as
the root mean square sum (*error_method* = "rms") across each
bin instead of percentiles ("percentile"). The value of the
keyword *demean* is applied to the decimation of error data
alone.
.. SeeAlso::
:meth:`XVG.plot` lists keywords common to both methods.
"""
ax = kwargs.pop('ax', None)
color = kwargs.pop('color', 'black')
filled = kwargs.pop('filled', True)
fill_alpha = kwargs.pop('fill_alpha', 0.2)
kwargs.setdefault('capsize', 0)
kwargs.setdefault('elinewidth', 1)
kwargs.setdefault('ecolor', color)
kwargs.setdefault('alpha', 0.3)
kwargs.setdefault('fmt', None)
columns = kwargs.pop('columns', Ellipsis) # slice for everything
maxpoints = kwargs.pop('maxpoints', self.maxpoints_default)
transform = kwargs.pop('transform', lambda x: x) # default is identity transformation
method = kwargs.pop('method', "mean")
if method != "mean":
raise NotImplementedError("For errors only method == 'mean' is supported.")
error_method = kwargs.pop('error_method', "percentile") # can also use 'rms' and 'error'
percentile = numpy.abs(kwargs.pop('percentile', 95.))
demean = kwargs.pop('demean', False)
# order: (decimate/smooth o slice o transform)(array)
try:
data = numpy.asarray(transform(self.array))[columns]
except IndexError:
raise MissingDataError("columns {0!r} are not suitable to index the transformed array, possibly not eneough data".format(columns))
if data.shape[-1] == 0:
raise MissingDataError("There is no data to be plotted.")
a = numpy.zeros((data.shape[0], maxpoints), dtype=numpy.float64)
a[0:2] = self.decimate("mean", data[0:2], maxpoints=maxpoints)
error_data = numpy.vstack((data[0], data[2:]))
if error_method == "percentile":
if percentile > 50:
upper_per = percentile
lower_per = 100 - percentile
else:
upper_per = 100 - percentile
lower_per = percentile
# demean generally does not make sense with the percentiles (but for analysing
# the regularised data itself we use this as a flag --- see below!)
upper = a[2:] = self.decimate("percentile", error_data, maxpoints=maxpoints,
per=upper_per, demean=False)[1:]
lower = self.decimate("percentile", error_data, maxpoints=maxpoints,
per=lower_per, demean=False)[1:]
else:
a[2:] = self.decimate(error_method, error_data, maxpoints=maxpoints, demean=demean)[1:]
lower = None
# now deal with infs, nans etc AFTER all transformations (needed for plotting across inf/nan)
ma = numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))
if lower is not None:
mlower = numpy.ma.MaskedArray(lower, mask=numpy.logical_not(numpy.isfinite(lower)))
# finally plot
X = ma[0] # abscissa set separately
Y = ma[1]
try:
kwargs['yerr'] = ma[3]
kwargs['xerr'] = ma[2]
except IndexError:
try:
kwargs['yerr'] = ma[2]
except IndexError:
raise TypeError("Either too few columns selected or data does not have a error column")
if ax is None:
ax = plt.gca()
if filled:
# can only plot dy
if error_method == "percentile":
if demean:
# signal that we are looking at percentiles of an observable and not error
y1 = mlower[-1]
y2 = kwargs['yerr']
else:
# percentiles of real errors (>0)
y1 = Y - mlower[-1]
y2 = Y + kwargs['yerr']
else:
y1 = Y - kwargs['yerr']
y2 = Y + kwargs['yerr']
ax.fill_between(X, y1, y2, color=color, alpha=fill_alpha)
else:
if error_method == "percentile":
# errorbars extend to different lengths;
if demean:
kwargs['yerr'] = numpy.vstack((mlower[-1], kwargs['yerr']))
else:
kwargs['yerr'] = numpy.vstack((Y - mlower[-1], Y + kwargs['yerr']))
try:
# xerr only makes sense when the data is a real
# error so we don't even bother with demean=?
kwargs['xerr'] = numpy.vstack((X - mlower[0], X + kwargs['xerr']))
except (KeyError, IndexError):
pass
ax.errorbar(X, Y, **kwargs)
# clean up args for plot
for kw in "yerr", "xerr", "capsize", "ecolor", "elinewidth", "fmt":
kwargs.pop(kw, None)
kwargs['alpha'] = 1.0
ax.plot(X, Y, color=color, **kwargs)
return ax
|
def decimate(self, method, a, maxpoints=10000, **kwargs):
"""Decimate data *a* to *maxpoints* using *method*.
If *a* is a 1D array then it is promoted to a (2, N) array
where the first column simply contains the index.
If the array contains fewer than *maxpoints* points or if
*maxpoints* is ``None`` then it is returned as it is. The
default for *maxpoints* is 10000.
Valid values for the reduction *method*:
* "mean", uses :meth:`XVG.decimate_mean` to coarse grain by
averaging the data in bins along the time axis
* "circmean", uses :meth:`XVG.decimate_circmean` to coarse
grain by calculating the circular mean of the data in bins
along the time axis. Use additional keywords *low* and
*high* to set the limits. Assumes that the data are in
degrees.
* "min" and "max* select the extremum in each bin
* "rms", uses :meth:`XVG.decimate_rms` to coarse grain by
computing the root mean square sum of the data in bins
along the time axis (for averaging standard deviations and
errors)
* "percentile" with keyword *per*: :meth:`XVG.decimate_percentile`
reduces data in each bin to the percentile *per*
* "smooth", uses :meth:`XVG.decimate_smooth` to subsample
from a smoothed function (generated with a running average
of the coarse graining step size derived from the original
number of data points and *maxpoints*)
:Returns: numpy array ``(M', N')`` from a ``(M', N)`` array
with ``M' == M`` (except when ``M == 1``, see above)
and ``N' <= N`` (``N'`` is *maxpoints*).
"""
methods = {'mean': self.decimate_mean,
'min': self.decimate_min,
'max': self.decimate_max,
'smooth': self.decimate_smooth,
'rms': self.decimate_rms,
'percentile': self.decimate_percentile,
'error': self.decimate_error, # undocumented, not working well
'circmean': self.decimate_circmean,
}
if len(a.shape) == 1:
# add first column as index
# (probably should do this in class/init anyway...)
X = numpy.arange(len(a))
a = numpy.vstack([X, a])
ny = a.shape[-1] # assume 1D or 2D array with last dimension varying fastest
if maxpoints is None or ny <= maxpoints:
return a
return methods[method](a, maxpoints, **kwargs)
|
def decimate_mean(self, a, maxpoints, **kwargs):
"""Return data *a* mean-decimated on *maxpoints*.
Histograms each column into *maxpoints* bins and calculates
the weighted average in each bin as the decimated data, using
:func:`numkit.timeseries.mean_histogrammed_function`. The coarse grained
time in the first column contains the centers of the histogram
time.
If *a* contains <= *maxpoints* then *a* is simply returned;
otherwise a new array of the same dimensions but with a
reduced number of *maxpoints* points is returned.
.. Note::
Assumes that the first column is time.
"""
return self._decimate(numkit.timeseries.mean_histogrammed_function, a, maxpoints, **kwargs)
|
def decimate_circmean(self, a, maxpoints, **kwargs):
"""Return data *a* circmean-decimated on *maxpoints*.
Histograms each column into *maxpoints* bins and calculates
the weighted circular mean in each bin as the decimated data,
using
:func:`numkit.timeseries.circmean_histogrammed_function`. The
coarse grained time in the first column contains the centers
of the histogram time.
If *a* contains <= *maxpoints* then *a* is simply returned;
otherwise a new array of the same dimensions but with a
reduced number of *maxpoints* points is returned.
Keywords *low* and *high* can be used to set the
boundaries. By default they are [-pi, +pi].
This method returns a **masked** array where jumps are flagged
by an insertion of a masked point.
.. Note::
Assumes that the first column is time and that the data are
in **degrees**.
.. Warning::
Breaking of arrays only works properly with a two-column
array because breaks are only inserted in the x-column
(a[0]) where y1 = a[1] has a break.
"""
a_rad = numpy.vstack((a[0], numpy.deg2rad(a[1:])))
b = self._decimate(numkit.timeseries.circmean_histogrammed_function, a_rad, maxpoints, **kwargs)
y_ma, x_ma = break_array(b[1], threshold=numpy.pi, other=b[0])
v = [y_ma]
for y in b[2:]:
v.append(break_array(y, threshold=numpy.pi)[0])
if v[-1].shape != v[0].shape:
raise ValueError("y dimensions have different breaks: you MUST deal with them separately")
return numpy.vstack((x_ma, numpy.rad2deg(v)))
|
def decimate_min(self, a, maxpoints, **kwargs):
"""Return data *a* min-decimated on *maxpoints*.
Histograms each column into *maxpoints* bins and calculates
the minimum in each bin as the decimated data, using
:func:`numkit.timeseries.min_histogrammed_function`. The coarse grained
time in the first column contains the centers of the histogram
time.
If *a* contains <= *maxpoints* then *a* is simply returned;
otherwise a new array of the same dimensions but with a
reduced number of *maxpoints* points is returned.
.. Note::
Assumes that the first column is time.
"""
return self._decimate(numkit.timeseries.min_histogrammed_function, a, maxpoints, **kwargs)
|
def decimate_max(self, a, maxpoints, **kwargs):
"""Return data *a* max-decimated on *maxpoints*.
Histograms each column into *maxpoints* bins and calculates
the maximum in each bin as the decimated data, using
:func:`numkit.timeseries.max_histogrammed_function`. The coarse grained
time in the first column contains the centers of the histogram
time.
If *a* contains <= *maxpoints* then *a* is simply returned;
otherwise a new array of the same dimensions but with a
reduced number of *maxpoints* points is returned.
.. Note::
Assumes that the first column is time.
"""
return self._decimate(numkit.timeseries.max_histogrammed_function, a, maxpoints, **kwargs)
|
def decimate_rms(self, a, maxpoints, **kwargs):
"""Return data *a* rms-decimated on *maxpoints*.
Histograms each column into *maxpoints* bins and calculates
the root mean square sum in each bin as the decimated data,
using :func:`numkit.timeseries.rms_histogrammed_function`. The coarse
grained time in the first column contains the centers of the
histogram time.
If *a* contains <= *maxpoints* then *a* is simply returned;
otherwise a new array of the same dimensions but with a
reduced number of *maxpoints* points is returned.
.. Note::
Assumes that the first column is time.
"""
return self._decimate(numkit.timeseries.rms_histogrammed_function, a, maxpoints, **kwargs)
|
def decimate_percentile(self, a, maxpoints, **kwargs):
"""Return data *a* percentile-decimated on *maxpoints*.
Histograms each column into *maxpoints* bins and calculates
the percentile *per* in each bin as the decimated data, using
:func:`numkit.timeseries.percentile_histogrammed_function`. The
coarse grained time in the first column contains the centers
of the histogram time.
If *a* contains <= *maxpoints* then *a* is simply returned;
otherwise a new array of the same dimensions but with a
reduced number of *maxpoints* points is returned.
.. Note::
Assumes that the first column is time.
:Keywords:
*per*
percentile as a percentage, e.g. 75 is the value that splits
the data into the lower 75% and upper 25%; 50 is the median [50.0]
.. SeeAlso:: :func:`numkit.timeseries.regularized_function` with :func:`scipy.stats.scoreatpercentile`
"""
return self._decimate(numkit.timeseries.percentile_histogrammed_function, a, maxpoints, **kwargs)
|
def decimate_error(self, a, maxpoints, **kwargs):
"""Return data *a* error-decimated on *maxpoints*.
Histograms each column into *maxpoints* bins and calculates an
error estimate in each bin as the decimated data, using
:func:`numkit.timeseries.error_histogrammed_function`. The
coarse grained time in the first column contains the centers
of the histogram time.
If *a* contains <= *maxpoints* then *a* is simply returned;
otherwise a new array of the same dimensions but with a
reduced number of *maxpoints* points is returned.
.. SeeAlso:: :func:`numkit.timeseries.tcorrel`
.. Note::
Assumes that the first column is time.
Does not work very well because often there are too few
datapoints to compute a good autocorrelation function.
"""
warnings.warn("Using undocumented decimate_error() is highly EXPERIMENTAL",
category=gromacs.exceptions.LowAccuracyWarning)
return self._decimate(numkit.timeseries.error_histogrammed_function, a,
maxpoints, **kwargs)
|
def decimate_smooth(self, a, maxpoints, window="flat"):
"""Return smoothed data *a* decimated on approximately *maxpoints* points.
1. Produces a smoothed graph using the smoothing window *window*;
"flat" is a running average.
2. select points at a step size approximatelt producing maxpoints
If *a* contains <= *maxpoints* then *a* is simply returned;
otherwise a new array of the same dimensions but with a
reduced number of points (close to *maxpoints*) is returned.
.. Note::
Assumes that the first column is time (which will *never*
be smoothed/averaged), except when the input array *a* is
1D and therefore to be assumed to be data at equidistance
timepoints.
TODO:
- Allow treating the 1st column as data
"""
ny = a.shape[-1] # assume 1D or 2D array with last dimension varying fastest
# reduce size by averaging oover stepsize steps and then just
# picking every stepsize data points. (primitive --- can
# leave out bits at the end or end up with almost twice of
# maxpoints)
stepsize = int(ny / maxpoints)
if stepsize % 2 == 0:
stepsize += 1 # must be odd for the running average/smoothing window
out = numpy.empty_like(a)
# smoothed
out[0,:] = a[0]
for i in range(1, a.shape[0]):
# process columns because smooth() only handles 1D arrays :-p
out[i,:] = numkit.timeseries.smooth(a[i], stepsize, window=window)
if maxpoints == self.maxpoints_default: # only warn if user did not set maxpoints
warnings.warn("Plot had %d datapoints > maxpoints = %d; decimated to %d regularly "
"spaced points with smoothing (%r) over %d steps."
% (ny, maxpoints, ny/stepsize, window, stepsize),
category=AutoCorrectionWarning)
return out[..., ::stepsize]
|
def _parse(self, fname):
"""Parse a processed.top GROMACS topology file
The function reads in the file line-by-line, and it's a bunch of 'elif' statements,
writing parameter/atom line to current section/molecule.
ParamTypes are added to self.xyztypes (AtomType goes to self.atomtypes).
Params are added to current molecule (Atom goes to mol.atoms.append(atom))
MoleculeTypes and Molecules are odd, and are added to
* MoleculeType to :attr:`self.dict_molname_mol[mol.name] = mol`
* Molecule to :attr:`self.molecules.append(self.dict_molname_mol[mname])`
:obj:`curr_sec` variable stores to current section being read-in
:obj:`mol` variable stores the current molecule being read-in
:obj:`cmap_lines` are a little odd, since CMAP parameters are stored on multiple lines
:Arguments:
*fname*
name of the processed.top file
:Returns: None
"""
def _find_section(line):
return line.strip('[').strip(']').strip()
def _add_info(sys_or_mol, section, container):
# like (mol, 'atomtypes', mol.atomtypes)
if sys_or_mol.information.get(section, False) is False:
sys_or_mol.information[section] = container
mol = None # to hold the current mol
curr_sec = None
cmap_lines = []
with open(fname) as f:
for i_line, line in enumerate(f):
# trimming
if ';' in line:
line = line[0:line.index(';')]
line = line.strip()
if line == '':
continue
if line[0] == '*':
continue
# the topology must be stand-alone (i.e. no includes)
if line.startswith('#include'):
msg = 'The topology file has "#include" statements.'
msg+= ' You must provide a processed topology file that grompp creates.'
raise ValueError(msg)
# find sections
if line[0] == '[':
curr_sec = _find_section(line)
self.found_sections.append(curr_sec)
continue
fields = line.split()
if curr_sec == 'defaults':
'''
# ; nbfunc comb-rule gen-pairs fudgeLJ fudgeQQ
#1 2 yes 0.5 0.8333
'''
assert len(fields) in [2, 5]
self.defaults['nbfunc'] = int(fields[0])
self.defaults['comb-rule'] = int(fields[1])
if len(fields) == 5:
self.defaults['gen-pairs'] = fields[2]
self.defaults['fudgeLJ'] = float(fields[3])
self.defaults['fudgeQQ'] = float(fields[4])
elif curr_sec == 'atomtypes':
'''
# ;name at.num mass charge ptype sigma epsilon
# ;name bond_type at.num mass charge ptype sigma epsilon
# ;name mass charge ptype c6 c12
'''
if len(fields) not in (6,7,8):
self.logger.warning('skipping atomtype line with neither 7 or 8 fields: \n {0:s}'.format(line))
continue
#shift = 0 if len(fields) == 7 else 1
shift = len(fields) - 7
at = blocks.AtomType('gromacs')
at.atype = fields[0]
if shift == 1: at.bond_type = fields[1]
at.mass = float(fields[2+shift])
at.charge= float(fields[3+shift])
particletype = fields[4+shift]
assert particletype in ('A', 'S', 'V', 'D')
if particletype not in ('A',):
self.logger.warning('warning: non-atom particletype: "{0:s}"'.format(line))
sig = float(fields[5+shift])
eps = float(fields[6+shift])
at.gromacs= {'param': {'lje':eps, 'ljl':sig, 'lje14':None, 'ljl14':None} }
self.atomtypes.append(at)
_add_info(self, curr_sec, self.atomtypes)
# extend system.molecules
elif curr_sec == 'moleculetype':
assert len(fields) == 2
mol = blocks.Molecule()
mol.name = fields[0]
mol.exclusion_numb = int(fields[1])
self.dict_molname_mol[mol.name] = mol
elif curr_sec == 'atoms':
'''
#id at_type res_nr residu_name at_name cg_nr charge mass typeB chargeB massB
# 1 OC 1 OH O1 1 -1.32
OR
[ atoms ]
; id at type res nr residu name at name cg nr charge
1 OT 1 SOL OW 1 -0.834
'''
aserial = int(fields[0])
atype = fields[1]
resnumb = int(fields[2])
resname = fields[3]
aname = fields[4]
cgnr = int(fields[5])
charge = float(fields[6])
rest = fields[7:]
atom = blocks.Atom()
atom.name = aname
atom.atomtype= atype
atom.number = aserial
atom.resname = resname
atom.resnumb = resnumb
atom.charge = charge
if rest:
mass = float(rest[0])
atom.mass = mass
mol.atoms.append(atom)
_add_info(mol, curr_sec, mol.atoms)
elif curr_sec in ('pairtypes', 'pairs', 'pairs_nb'):
'''
section #at fu #param
---------------------------------
pairs 2 1 V,W
pairs 2 2 fudgeQQ, qi, qj, V, W
pairs_nb 2 1 qi, qj, V, W
'''
ai, aj = fields[:2]
fu = int(fields[2])
assert fu in (1,2)
pair = blocks.InteractionType('gromacs')
if fu == 1:
if curr_sec=='pairtypes':
pair.atype1 = ai
pair.atype2 = aj
v, w = list(map(float, fields[3:5]))
pair.gromacs = {'param': {'lje':None, 'ljl':None, 'lje14':w, 'ljl14':v}, 'func':fu }
self.pairtypes.append(pair)
_add_info(self, curr_sec, self.pairtypes)
elif curr_sec == 'pairs':
ai, aj = list( map(int, [ai,aj]) )
pair.atom1 = mol.atoms[ai-1]
pair.atom2 = mol.atoms[aj-1]
pair.gromacs['func'] = fu
mol.pairs.append(pair)
_add_info(mol, curr_sec, mol.pairs)
else:
raise ValueError
else:
raise NotImplementedError('{0:s} with functiontype {1:d} is not supported'.format(curr_sec,fu))
elif curr_sec == 'nonbond_params':
'''
; typei typej f.type sigma epsilon
; f.type=1 means LJ (not buckingham)
; sigma&eps since mixing-rule = 2
'''
assert len(fields) == 5
ai, aj = fields[:2]
fu = int(fields[2])
assert fu == 1
sig = float(fields[3])
eps = float(fields[4])
nonbond_param = blocks.NonbondedParamType('gromacs')
nonbond_param.atype1 = ai
nonbond_param.atype2 = aj
nonbond_param.gromacs['func'] = fu
nonbond_param.gromacs['param'] = {'eps': eps, 'sig': sig}
self.nonbond_params.append(nonbond_param)
_add_info(self, curr_sec, self.nonbond_params)
elif curr_sec in ('bondtypes', 'bonds'):
'''
section #at fu #param
----------------------------------
bonds 2 1 2
bonds 2 2 2
bonds 2 3 3
bonds 2 4 2
bonds 2 5 ??
bonds 2 6 2
bonds 2 7 2
bonds 2 8 ??
bonds 2 9 ??
bonds 2 10 4
'''
ai, aj = fields[:2]
fu = int(fields[2])
assert fu in (1,2,3,4,5,6,7,8,9,10)
if fu != 1:
raise NotImplementedError('function {0:d} is not yet supported'.format(fu))
bond = blocks.BondType('gromacs')
if fu == 1:
if curr_sec == 'bondtypes':
bond.atype1 = ai
bond.atype2 = aj
b0, kb = list(map(float, fields[3:5]))
bond.gromacs = {'param':{'kb':kb, 'b0':b0}, 'func':fu}
self.bondtypes.append(bond)
_add_info(self, curr_sec, self.bondtypes)
elif curr_sec == 'bonds':
ai, aj = list(map(int, [ai, aj]))
bond.atom1 = mol.atoms[ai-1]
bond.atom2 = mol.atoms[aj-1]
bond.gromacs['func'] = fu
if len(fields) > 3:
b0, kb = list(map(float, fields[3:5]))
bond.gromacs = {'param':{'kb':kb, 'b0':b0}, 'func':fu}
mol.bonds.append(bond)
_add_info(mol, curr_sec, mol.bonds)
else:
raise NotImplementedError
elif curr_sec in ('angletypes', 'angles'):
'''
section #at fu #param
----------------------------------
angles 3 1 2
angles 3 2 2
angles 3 3 3
angles 3 4 4
angles 3 5 4
angles 3 6 6
angles 3 8 ??
'''
ai, aj , ak = fields[:3]
fu = int(fields[3])
assert fu in (1,2,3,4,5,6,8) # no 7
if fu not in (1,2,5):
raise NotImplementedError('function {0:d} is not yet supported'.format(fu))
ang = blocks.AngleType('gromacs')
if fu == 1:
if curr_sec == 'angletypes':
ang.atype1 = ai
ang.atype2 = aj
ang.atype3 = ak
tetha0, ktetha = list(map(float, fields[4:6]))
ang.gromacs = {'param':{'ktetha':ktetha, 'tetha0':tetha0, 'kub':None, 's0':None}, 'func':fu}
self.angletypes.append(ang)
_add_info(self, curr_sec, self.angletypes)
elif curr_sec == 'angles':
ai, aj, ak = list(map(int, [ai, aj, ak]))
ang.atom1 = mol.atoms[ai-1]
ang.atom2 = mol.atoms[aj-1]
ang.atom3 = mol.atoms[ak-1]
ang.gromacs['func'] = fu
mol.angles.append(ang)
_add_info(mol, curr_sec, mol.angles)
else:
raise ValueError
elif fu == 2:
if curr_sec == 'angletypes':
raise NotImplementedError()
elif curr_sec == 'angles':
ai, aj, ak = list(map(int, [ai, aj, ak]))
ang.atom1 = mol.atoms[ai-1]
ang.atom2 = mol.atoms[aj-1]
ang.atom3 = mol.atoms[ak-1]
ang.gromacs['func'] = fu
tetha0, ktetha = list(map(float, fields[4:6]))
ang.gromacs = {'param':{'ktetha':ktetha, 'tetha0':tetha0, 'kub':None, 's0':None}, 'func':fu}
mol.angles.append(ang)
_add_info(mol, curr_sec, mol.angles)
elif fu == 5:
if curr_sec == 'angletypes':
ang.atype1 = ai
ang.atype2 = aj
ang.atype3 = ak
tetha0, ktetha, s0, kub = list(map(float, fields[4:8]))
ang.gromacs = {'param':{'ktetha':ktetha, 'tetha0':tetha0, 'kub':kub, 's0':s0}, 'func':fu}
self.angletypes.append(ang)
_add_info(self, curr_sec, self.angletypes)
elif curr_sec == 'angles':
ai, aj, ak = list(map(int, [ai, aj, ak]))
ang.atom1 = mol.atoms[ai-1]
ang.atom2 = mol.atoms[aj-1]
ang.atom3 = mol.atoms[ak-1]
ang.gromacs['func'] = fu
mol.angles.append(ang)
_add_info(mol, curr_sec, mol.angles)
else:
raise ValueError
else:
raise NotImplementedError
elif curr_sec in ('dihedraltypes', 'dihedrals'):
'''
section #at fu #param
----------------------------------
dihedrals 4 1 3
dihedrals 4 2 2
dihedrals 4 3 6
dihedrals 4 4 3
dihedrals 4 5 4
dihedrals 4 8 ??
dihedrals 4 9 3
'''
if curr_sec == 'dihedraltypes' and len(fields) == 6:
# in oplsaa - quartz parameters
fields.insert(2, 'X')
fields.insert(0, 'X')
ai, aj, ak, am = fields[:4]
fu = int(fields[4])
assert fu in (1,2,3,4,5,8,9)
if fu not in (1,2,3,4,9):
raise NotImplementedError('dihedral function {0:d} is not yet supported'.format(fu))
dih = blocks.DihedralType('gromacs')
imp = blocks.ImproperType('gromacs')
# proper dihedrals
if fu in (1,3,9):
if curr_sec == 'dihedraltypes':
dih.atype1 = ai
dih.atype2 = aj
dih.atype3 = ak
dih.atype4 = am
dih.line = i_line + 1
if fu == 1:
delta, kchi, n = list(map(float, fields[5:8]))
dih.gromacs['param'].append({'kchi':kchi, 'n':n, 'delta':delta})
elif fu == 3:
c0, c1, c2, c3, c4, c5 = list(map(float, fields[5:11]))
m = dict(c0=c0, c1=c1, c2=c2, c3=c3, c4=c4, c5=c5)
dih.gromacs['param'].append(m)
elif fu == 4:
delta, kchi, n = list(map(float, fields[5:8]))
dih.gromacs['param'].append({'kchi':kchi, 'n':int(n), 'delta':delta})
elif fu == 9:
delta, kchi, n = list(map(float, fields[5:8]))
dih.gromacs['param'].append({'kchi':kchi, 'n':int(n), 'delta':delta})
else:
raise ValueError
dih.gromacs['func'] = fu
self.dihedraltypes.append(dih)
_add_info(self, curr_sec, self.dihedraltypes)
elif curr_sec == 'dihedrals':
ai, aj, ak, am = list(map(int, fields[:4]))
dih.atom1 = mol.atoms[ai-1]
dih.atom2 = mol.atoms[aj-1]
dih.atom3 = mol.atoms[ak-1]
dih.atom4 = mol.atoms[am-1]
dih.gromacs['func'] = fu
dih.line = i_line + 1
if fu == 1:
delta, kchi, n = list(map(float, fields[5:8]))
dih.gromacs['param'].append({'kchi':kchi, 'n': int(n), 'delta':delta})
elif fu == 3:
pass
elif fu == 4:
pass
elif fu == 9:
if len(fields[5:8]) == 3:
delta, kchi, n = list(map(float, fields[5:8]))
dih.gromacs['param'].append({'kchi':kchi, 'n':int(n), 'delta':delta})
else:
raise ValueError
mol.dihedrals.append(dih)
_add_info(mol, curr_sec, mol.dihedrals)
else:
raise ValueError
# impropers
elif fu in (2,4):
if curr_sec == 'dihedraltypes':
imp.atype1 = ai
imp.atype2 = aj
imp.atype3 = ak
imp.atype4 = am
imp.line = i_line + 1
if fu == 2:
psi0 , kpsi = list(map(float, fields[5:7]))
imp.gromacs['param'].append({'kpsi':kpsi, 'psi0': psi0})
elif fu == 4:
psi0 , kpsi, n = list(map(float, fields[5:8]))
imp.gromacs['param'].append({'kpsi':kpsi, 'psi0': psi0, 'n': int(n)})
else:
raise ValueError
imp.gromacs['func'] = fu
self.impropertypes.append(imp)
_add_info(self, curr_sec, self.impropertypes)
elif curr_sec == 'dihedrals':
ai, aj, ak, am = list(map(int, fields[:4]))
imp.atom1 = mol.atoms[ai-1]
imp.atom2 = mol.atoms[aj-1]
imp.atom3 = mol.atoms[ak-1]
imp.atom4 = mol.atoms[am-1]
imp.gromacs['func'] = fu
imp.line = i_line + 1
if fu == 2:
pass
elif fu == 4:
# in-line override of dihedral parameters
if len(fields[5:8]) == 3:
psi0 , kpsi, n = list(map(float, fields[5:8]))
imp.gromacs['param'].append({'kpsi':kpsi, 'psi0': psi0, 'n': int(n)})
else:
raise ValueError
mol.impropers.append(imp)
_add_info(mol, curr_sec, mol.impropers)
else:
raise ValueError
else:
raise NotImplementedError
elif curr_sec in ('cmaptypes', 'cmap'):
cmap = blocks.CMapType('gromacs')
if curr_sec == 'cmaptypes':
cmap_lines.append(line)
_add_info(self, curr_sec, self.cmaptypes)
else:
ai, aj, ak, am, an = list(map(int, fields[:5]))
fu = int(fields[5])
assert fu == 1
cmap.atom1 = mol.atoms[ai-1]
cmap.atom2 = mol.atoms[aj-1]
cmap.atom3 = mol.atoms[ak-1]
cmap.atom4 = mol.atoms[am-1]
cmap.atom8 = mol.atoms[an-1]
cmap.gromacs['func'] = fu
mol.cmaps.append(cmap)
_add_info(mol, curr_sec, mol.cmaps)
elif curr_sec == 'settles':
'''
section #at fu #param
----------------------------------
'''
assert len(fields) == 4
ai = int(fields[0])
fu = int(fields[1])
assert fu == 1
settle = blocks.SettleType('gromacs')
settle.atom = mol.atoms[ai-1]
settle.dOH = float(fields[2])
settle.dHH = float(fields[3])
mol.settles.append(settle)
_add_info(mol, curr_sec, mol.settles)
elif curr_sec == "virtual_sites3":
'''
; Dummy from funct a b
4 1 2 3 1 0.131937768 0.131937768
'''
assert len(fields) == 7
ai = int(fields[0])
aj = int(fields[1])
ak = int(fields[2])
al = int(fields[3])
fu = int(fields[4])
assert fu == 1
a = float(fields[5])
b = float(fields[6])
vs3 = blocks.VirtualSites3Type('gromacs')
vs3.atom1 = ai
vs3.atom2 = aj
vs3.atom3 = ak
vs3.atom4 = al
vs3.gromacs['func'] = fu
vs3.gromacs['param'] = { 'a': a, 'b':b }
mol.virtual_sites3.append(vs3)
_add_info(mol, curr_sec, mol.virtual_sites3)
elif curr_sec in ('exclusions',):
ai = int(fields[0])
other = list(map(int, fields[1:]))
exc = blocks.Exclusion()
exc.main_atom = mol.atoms[ai-1]
exc.other_atoms= [mol.atoms[k-1] for k in other]
mol.exclusions.append(exc)
_add_info(mol, curr_sec, mol.exclusions)
elif curr_sec in ('constrainttypes', 'constraints'):
'''
section #at fu #param
----------------------------------
constraints 2 1 1
constraints 2 2 1
'''
ai, aj = fields[:2]
fu = int(fields[2])
assert fu in (1,2)
cons = blocks.ConstraintType('gromacs')
# TODO: what's different between 1 and 2
if fu in [1, 2]:
if curr_sec == 'constrainttypes':
cons.atype1 = ai
cons.atype2 = aj
b0 = float(fields[3])
cons.gromacs = {'param':{'b0':b0}, 'func': fu}
self.constrainttypes.append(cons)
_add_info(self, curr_sec, self.constrainttypes)
elif curr_sec == 'constraints':
ai, aj = list(map(int, fields[:2]))
cons.atom1 = mol.atoms[ai-1]
cons.atom2 = mol.atoms[aj-1]
cons.gromacs['func'] = fu
mol.constraints.append(cons)
_add_info(mol, curr_sec, mol.constraints)
else:
raise ValueError
else:
raise ValueError
elif curr_sec in ('position_restraints',
'distance_restraints',
'dihedral_restraints',
'orientation_restraints',
'angle_restraints',
'angle_restraints_z'):
pass
elif curr_sec in ('implicit_genborn_params',):
'''
attype sar st pi gbr hct
'''
pass
elif curr_sec == 'system':
#assert len(fields) == 1
self.name = fields[0]
elif curr_sec == 'molecules':
assert len(fields) == 2
mname, nmol = fields[0], int(fields[1])
# if the number of a molecule is more than 1, add copies to system.molecules
for i in range(nmol):
self.molecules.append(self.dict_molname_mol[mname])
else:
raise NotImplementedError('Unknown section in topology: {0}'.format(curr_sec))
# process cmap_lines
curr_cons = None
for line in cmap_lines:
# cmaptype opening line
if len(line.split()) == 8:
cons = blocks.CMapType('gromacs')
atype1, atype2, atype3, atype4, atype8, func, sizeX, sizeY = line.replace("\\","").split()
func, sizeX, sizeY = int(func), int(sizeX), int(sizeY)
cons.atype1 = atype1
cons.atype2 = atype2
cons.atype3 = atype3
cons.atype4 = atype4
cons.atype8 = atype8
cons.gromacs = {'param':[], 'func': func}
curr_cons = cons
# cmap body
elif len(line.split()) == 10:
cmap_param = map(float, line.replace("\\","").split())
cons.gromacs['param'] += cmap_param
# cmaptype cloning line
elif len(line.split()) == 6:
cmap_param = map(float, line.replace("\\","").split())
cons.gromacs['param'] += cmap_param
self.cmaptypes.append(curr_cons)
else:
raise ValueError
|
def assemble_topology(self):
"""Call the various member self._make_* functions to convert the topology object into a string"""
self.logger.debug("starting to assemble topology...")
top = ''
self.logger.debug("making atom/pair/bond/angle/dihedral/improper types")
top += self.toptemplate
top = top.replace('*DEFAULTS*', ''.join( self._make_defaults(self.system)) )
top = top.replace('*ATOMTYPES*', ''.join( self._make_atomtypes(self.system)) )
top = top.replace('*NONBOND_PARAM*', ''.join( self._make_nonbond_param(self.system)) )
top = top.replace('*PAIRTYPES*', ''.join( self._make_pairtypes(self.system)) )
top = top.replace('*BONDTYPES*', ''.join( self._make_bondtypes(self.system)) )
top = top.replace('*CONSTRAINTTYPES*',''.join( self._make_constrainttypes(self.system)))
top = top.replace('*ANGLETYPES*', ''.join( self._make_angletypes(self.system)))
top = top.replace('*DIHEDRALTYPES*', ''.join( self._make_dihedraltypes(self.system)) )
top = top.replace('*IMPROPERTYPES*', ''.join( self._make_impropertypes(self.system)) )
top = top.replace('*CMAPTYPES*', ''.join( self._make_cmaptypes(self.system)) )
for i,(molname,m) in enumerate(self.system.dict_molname_mol.items()):
itp = self.itptemplate
itp = itp.replace('*MOLECULETYPE*', ''.join( self._make_moleculetype(m, molname, m.exclusion_numb)) )
itp = itp.replace('*ATOMS*', ''.join( self._make_atoms(m)) )
itp = itp.replace('*BONDS*', ''.join( self._make_bonds(m)) )
itp = itp.replace('*PAIRS*', ''.join( self._make_pairs(m)) )
itp = itp.replace('*SETTLES*', ''.join( self._make_settles(m)) )
itp = itp.replace('*VIRTUAL_SITES3*',''.join( self._make_virtual_sites3(m)) )
itp = itp.replace('*EXCLUSIONS*', ''.join( self._make_exclusions(m)) )
itp = itp.replace('*ANGLES*', ''.join( self._make_angles(m)) )
itp = itp.replace('*DIHEDRALS*', ''.join( self._make_dihedrals(m)) )
itp = itp.replace('*IMPROPERS*', ''.join( self._make_impropers(m)) )
itp = itp.replace('*CMAPS*', ''.join( self._make_cmaps(m)) )
if not self.multiple_output:
top += itp
else:
outfile = "mol_{0}.itp".format(molname)
top += '#include "mol_{0}.itp" \n'.format( molname )
with open(outfile, "w") as f:
f.writelines([itp])
top += '\n[system] \nConvertedSystem\n\n'
top += '[molecules] \n'
molecules = [("", 0)]
for m in self.system.molecules:
if (molecules[-1][0] != m.name):
molecules.append([m.name, 0])
if molecules[-1][0] == m.name:
molecules[-1][1] += 1
for molname, n in molecules[1:]:
top += '{0:s} {1:d}\n'.format(molname, n)
top += '\n'
with open(self.outfile, 'w') as f:
f.writelines([top])
|
def topology(struct=None, protein='protein',
top='system.top', dirname='top',
posres="posres.itp",
ff="oplsaa", water="tip4p",
**pdb2gmx_args):
"""Build Gromacs topology files from pdb.
:Keywords:
*struct*
input structure (**required**)
*protein*
name of the output files
*top*
name of the topology file
*dirname*
directory in which the new topology will be stored
*ff*
force field (string understood by ``pdb2gmx``); default
"oplsaa"
*water*
water model (string), default "tip4p"
*pdb2gmxargs*
other arguments for ``pdb2gmx``
.. note::
At the moment this function simply runs ``pdb2gmx`` and uses
the resulting topology file directly. If you want to create
more complicated topologies and maybe also use additional itp
files or make a protein itp file then you will have to do this
manually.
"""
structure = realpath(struct)
new_struct = protein + '.pdb'
if posres is None:
posres = protein + '_posres.itp'
pdb2gmx_args.update({'f': structure, 'o': new_struct, 'p': top, 'i': posres,
'ff': ff, 'water': water})
with in_dir(dirname):
logger.info("[{dirname!s}] Building topology {top!r} from struct = {struct!r}".format(**vars()))
# perhaps parse output from pdb2gmx 4.5.x to get the names of the chain itp files?
gromacs.pdb2gmx(**pdb2gmx_args)
return { \
'top': realpath(dirname, top), \
'struct': realpath(dirname, new_struct), \
'posres' : realpath(dirname, posres) }
|
def make_main_index(struct, selection='"Protein"', ndx='main.ndx', oldndx=None):
"""Make index file with the special groups.
This routine adds the group __main__ and the group __environment__
to the end of the index file. __main__ contains what the user
defines as the *central* and *most important* parts of the
system. __environment__ is everything else.
The template mdp file, for instance, uses these two groups for T-coupling.
These groups are mainly useful if the default groups "Protein" and "Non-Protein"
are not appropriate. By using symbolic names such as __main__ one
can keep scripts more general.
:Returns:
*groups* is a list of dictionaries that describe the index groups. See
:func:`gromacs.cbook.parse_ndxlist` for details.
:Arguments:
*struct* : filename
structure (tpr, pdb, gro)
*selection* : string
is a ``make_ndx`` command such as ``"Protein"`` or ``r DRG`` which
determines what is considered the main group for centering etc. It is
passed directly to ``make_ndx``.
*ndx* : string
name of the final index file
*oldndx* : string
name of index file that should be used as a basis; if None
then the ``make_ndx`` default groups are used.
This routine is very dumb at the moment; maybe some heuristics will be
added later as could be other symbolic groups such as __membrane__.
"""
logger.info("Building the main index file {ndx!r}...".format(**vars()))
# pass 1: select
# get a list of groups
# need the first "" to get make_ndx to spit out the group list.
_,out,_ = gromacs.make_ndx(f=struct, n=oldndx, o=ndx, stdout=False,
input=("", "q"))
groups = cbook.parse_ndxlist(out)
# find the matching groups,
# there is a nasty bug in GROMACS where make_ndx may have multiple
# groups, which caused the previous approach to fail big time.
# this is a work around the make_ndx bug.
# striping the "" allows compatibility with existing make_ndx selection commands.
selection = selection.strip("\"")
selected_groups = [g for g in groups if g['name'].lower() == selection.lower()]
if len(selected_groups) > 1:
logging.warn("make_ndx created duplicated groups, performing work around")
if len(selected_groups) <= 0:
msg = "no groups found for selection {0}, available groups are {1}".format(selection, groups)
logging.error(msg)
raise ValueError(msg)
# Found at least one matching group, we're OK
# index of last group
last = len(groups) - 1
assert last == groups[-1]['nr']
group = selected_groups[0]
# pass 2:
# 1) last group is __main__
# 2) __environment__ is everything else (eg SOL, ions, ...)
_,out,_ = gromacs.make_ndx(f=struct, n=ndx, o=ndx,
stdout=False,
# make copy selected group, this now has index last + 1
input=("{0}".format(group['nr']),
# rename this to __main__
"name {0} __main__".format(last+1),
# make a complement to this group, it get index last + 2
"! \"__main__\"",
# rename this to __environment__
"name {0} __environment__".format(last+2),
# list the groups
"",
# quit
"q"))
return cbook.parse_ndxlist(out)
|
def get_lipid_vdwradii(outdir=os.path.curdir, libdir=None):
"""Find vdwradii.dat and add special entries for lipids.
See :data:`gromacs.setup.vdw_lipid_resnames` for lipid
resnames. Add more if necessary.
"""
vdwradii_dat = os.path.join(outdir, "vdwradii.dat")
if libdir is not None:
filename = os.path.join(libdir, 'vdwradii.dat') # canonical name
if not os.path.exists(filename):
msg = 'No VDW database file found in {filename!r}.'.format(**vars())
logger.exception(msg)
raise OSError(msg, errno.ENOENT)
else:
try:
filename = os.path.join(os.environ['GMXLIB'], 'vdwradii.dat')
except KeyError:
try:
filename = os.path.join(os.environ['GMXDATA'], 'top', 'vdwradii.dat')
except KeyError:
msg = "Cannot find vdwradii.dat. Set GMXLIB (point to 'top') or GMXDATA ('share/gromacs')."
logger.exception(msg)
raise OSError(msg, errno.ENOENT)
if not os.path.exists(filename):
msg = "Cannot find {filename!r}; something is wrong with the Gromacs installation.".format(**vars())
logger.exception(msg, errno.ENOENT)
raise OSError(msg)
# make sure to catch 3 and 4 letter resnames
patterns = vdw_lipid_resnames + list({x[:3] for x in vdw_lipid_resnames})
# TODO: should do a tempfile...
with open(vdwradii_dat, 'w') as outfile:
# write lipid stuff before general
outfile.write('; Special larger vdw radii for solvating lipid membranes\n')
for resname in patterns:
for atom,radius in vdw_lipid_atom_radii.items():
outfile.write('{resname:4!s} {atom:<5!s} {radius:5.3f}\n'.format(**vars()))
with open(filename, 'r') as infile:
for line in infile:
outfile.write(line)
logger.debug('Created lipid vdW radii file {vdwradii_dat!r}.'.format(**vars()))
return realpath(vdwradii_dat)
|
def solvate(struct='top/protein.pdb', top='top/system.top',
distance=0.9, boxtype='dodecahedron',
concentration=0, cation='NA', anion='CL',
water='tip4p', solvent_name='SOL', with_membrane=False,
ndx = 'main.ndx', mainselection = '"Protein"',
dirname='solvate',
**kwargs):
"""Put protein into box, add water, add counter-ions.
Currently this really only supports solutes in water. If you need
to embedd a protein in a membrane then you will require more
sophisticated approaches.
However, you *can* supply a protein already inserted in a
bilayer. In this case you will probably want to set *distance* =
``None`` and also enable *with_membrane* = ``True`` (using extra
big vdw radii for typical lipids).
.. Note:: The defaults are suitable for solvating a globular
protein in a fairly tight (increase *distance*!) dodecahedral
box.
:Arguments:
*struct* : filename
pdb or gro input structure
*top* : filename
Gromacs topology
*distance* : float
When solvating with water, make the box big enough so that
at least *distance* nm water are between the solute *struct*
and the box boundary.
Set *boxtype* to ``None`` in order to use a box size in the input
file (gro or pdb).
*boxtype* or *bt*: string
Any of the box types supported by :class:`~gromacs.tools.Editconf`
(triclinic, cubic, dodecahedron, octahedron). Set the box dimensions
either with *distance* or the *box* and *angle* keywords.
If set to ``None`` it will ignore *distance* and use the box
inside the *struct* file.
*bt* overrides the value of *boxtype*.
*box*
List of three box lengths [A,B,C] that are used by :class:`~gromacs.tools.Editconf`
in combination with *boxtype* (``bt`` in :program:`editconf`) and *angles*.
Setting *box* overrides *distance*.
*angles*
List of three angles (only necessary for triclinic boxes).
*concentration* : float
Concentration of the free ions in mol/l. Note that counter
ions are added in excess of this concentration.
*cation* and *anion* : string
Molecule names of the ions. This depends on the chosen force field.
*water* : string
Name of the water model; one of "spc", "spce", "tip3p",
"tip4p". This should be appropriate for the chosen force
field. If an alternative solvent is required, simply supply the path to a box
with solvent molecules (used by :func:`~gromacs.genbox`'s *cs* argument)
and also supply the molecule name via *solvent_name*.
*solvent_name*
Name of the molecules that make up the solvent (as set in the itp/top).
Typically needs to be changed when using non-standard/non-water solvents.
["SOL"]
*with_membrane* : bool
``True``: use special ``vdwradii.dat`` with 0.1 nm-increased radii on
lipids. Default is ``False``.
*ndx* : filename
How to name the index file that is produced by this function.
*mainselection* : string
A string that is fed to :class:`~gromacs.tools.Make_ndx` and
which should select the solute.
*dirname* : directory name
Name of the directory in which all files for the solvation stage are stored.
*includes*
List of additional directories to add to the mdp include path
*kwargs*
Additional arguments are passed on to
:class:`~gromacs.tools.Editconf` or are interpreted as parameters to be
changed in the mdp file.
"""
sol = solvate_sol(struct=struct, top=top,
distance=distance, boxtype=boxtype,
water=water, solvent_name=solvent_name,
with_membrane=with_membrane,
dirname=dirname, **kwargs)
ion = solvate_ion(struct=sol['struct'], top=top,
concentration=concentration, cation=cation, anion=anion,
solvent_name=solvent_name, ndx=ndx,
mainselection=mainselection, dirname=dirname,
**kwargs)
return ion
|
def check_mdpargs(d):
"""Check if any arguments remain in dict *d*."""
if len(d) > 0:
wmsg = "Unprocessed mdp option are interpreted as options for grompp:\n"+str(d)
logger.warn(wmsg)
warnings.warn(wmsg, category=UsageWarning)
return len(d) == 0
|
def energy_minimize(dirname='em', mdp=config.templates['em.mdp'],
struct='solvate/ionized.gro', top='top/system.top',
output='em.pdb', deffnm="em",
mdrunner=None, mdrun_args=None,
**kwargs):
"""Energy minimize the system.
This sets up the system (creates run input files) and also runs
``mdrun_d``. Thus it can take a while.
Additional itp files should be in the same directory as the top file.
Many of the keyword arguments below already have sensible values.
:Keywords:
*dirname*
set up under directory dirname [em]
*struct*
input structure (gro, pdb, ...) [solvate/ionized.gro]
*output*
output structure (will be put under dirname) [em.pdb]
*deffnm*
default name for mdrun-related files [em]
*top*
topology file [top/system.top]
*mdp*
mdp file (or use the template) [templates/em.mdp]
*includes*
additional directories to search for itp files
*mdrunner*
:class:`gromacs.run.MDrunner` instance; by default we
just try :func:`gromacs.mdrun_d` and :func:`gromacs.mdrun` but a
MDrunner instance gives the user the ability to run mpi jobs
etc. [None]
*mdrun_args*
arguments for *mdrunner* (as a dict), e.g. ``{'nt': 2}``;
empty by default
.. versionaddedd:: 0.7.0
*kwargs*
remaining key/value pairs that should be changed in the
template mdp file, eg ``nstxtcout=250, nstfout=250``.
.. note:: If :func:`~gromacs.mdrun_d` is not found, the function
falls back to :func:`~gromacs.mdrun` instead.
"""
structure = realpath(struct)
topology = realpath(top)
mdp_template = config.get_template(mdp)
deffnm = deffnm.strip()
mdrun_args = {} if mdrun_args is None else mdrun_args
# write the processed topology to the default output
kwargs.setdefault('pp', 'processed.top')
# filter some kwargs that might come through when feeding output
# from previous stages such as solvate(); necessary because *all*
# **kwargs must be *either* substitutions in the mdp file *or* valid
# command line parameters for ``grompp``.
kwargs.pop('ndx', None)
# mainselection is not used but only passed through; right now we
# set it to the default that is being used in all argument lists
# but that is not pretty. TODO.
mainselection = kwargs.pop('mainselection', '"Protein"')
# only interesting when passed from solvate()
qtot = kwargs.pop('qtot', 0)
# mdp is now the *output* MDP that will be generated from mdp_template
mdp = deffnm+'.mdp'
tpr = deffnm+'.tpr'
logger.info("[{dirname!s}] Energy minimization of struct={struct!r}, top={top!r}, mdp={mdp!r} ...".format(**vars()))
cbook.add_mdp_includes(topology, kwargs)
if qtot != 0:
# At the moment this is purely user-reported and really only here because
# it might get fed into the function when using the keyword-expansion pipeline
# usage paradigm.
wmsg = "Total charge was reported as qtot = {qtot:g} <> 0; probably a problem.".format(**vars())
logger.warn(wmsg)
warnings.warn(wmsg, category=BadParameterWarning)
with in_dir(dirname):
unprocessed = cbook.edit_mdp(mdp_template, new_mdp=mdp, **kwargs)
check_mdpargs(unprocessed)
gromacs.grompp(f=mdp, o=tpr, c=structure, r=structure, p=topology, **unprocessed)
mdrun_args.update(v=True, stepout=10, deffnm=deffnm, c=output)
if mdrunner is None:
mdrun = run.get_double_or_single_prec_mdrun()
mdrun(**mdrun_args)
else:
if type(mdrunner) is type:
# class
# user wants full control and provides simulation.MDrunner **class**
# NO CHECKING --- in principle user can supply any callback they like
mdrun = mdrunner(**mdrun_args)
mdrun.run()
else:
# anything with a run() method that takes mdrun arguments...
try:
mdrunner.run(mdrunargs=mdrun_args)
except AttributeError:
logger.error("mdrunner: Provide a gromacs.run.MDrunner class or instance or a callback with a run() method")
raise TypeError("mdrunner: Provide a gromacs.run.MDrunner class or instance or a callback with a run() method")
# em.gro --> gives 'Bad box in file em.gro' warning --- why??
# --> use em.pdb instead.
if not os.path.exists(output):
errmsg = "Energy minimized system NOT produced."
logger.error(errmsg)
raise GromacsError(errmsg)
final_struct = realpath(output)
logger.info("[{dirname!s}] energy minimized structure {final_struct!r}".format(**vars()))
return {'struct': final_struct,
'top': topology,
'mainselection': mainselection,
}
|
def em_schedule(**kwargs):
"""Run multiple energy minimizations one after each other.
:Keywords:
*integrators*
list of integrators (from 'l-bfgs', 'cg', 'steep')
[['bfgs', 'steep']]
*nsteps*
list of maximum number of steps; one for each integrator in
in the *integrators* list [[100,1000]]
*kwargs*
mostly passed to :func:`gromacs.setup.energy_minimize`
:Returns: dictionary with paths to final structure ('struct') and
other files
:Example:
Conduct three minimizations:
1. low memory Broyden-Goldfarb-Fletcher-Shannon (BFGS) for 30 steps
2. steepest descent for 200 steps
3. finish with BFGS for another 30 steps
We also do a multi-processor minimization when possible (i.e. for steep
(and conjugate gradient) by using a :class:`gromacs.run.MDrunner` class
for a :program:`mdrun` executable compiled for OpenMP in 64 bit (see
:mod:`gromacs.run` for details)::
import gromacs.run
gromacs.setup.em_schedule(struct='solvate/ionized.gro',
mdrunner=gromacs.run.MDrunnerOpenMP64,
integrators=['l-bfgs', 'steep', 'l-bfgs'],
nsteps=[50,200, 50])
.. Note:: You might have to prepare the mdp file carefully because at the
moment one can only modify the *nsteps* parameter on a
per-minimizer basis.
"""
mdrunner = kwargs.pop('mdrunner', None)
integrators = kwargs.pop('integrators', ['l-bfgs', 'steep'])
kwargs.pop('integrator', None) # clean input; we set intgerator from integrators
nsteps = kwargs.pop('nsteps', [100, 1000])
outputs = ['em{0:03d}_{1!s}.pdb'.format(i, integrator) for i,integrator in enumerate(integrators)]
outputs[-1] = kwargs.pop('output', 'em.pdb')
files = {'struct': kwargs.pop('struct', None)} # fake output from energy_minimize()
for i, integrator in enumerate(integrators):
struct = files['struct']
logger.info("[em %d] energy minimize with %s for maximum %d steps", i, integrator, nsteps[i])
kwargs.update({'struct':struct, 'output':outputs[i],
'integrator':integrator, 'nsteps': nsteps[i]})
if not integrator == 'l-bfgs':
kwargs['mdrunner'] = mdrunner
else:
kwargs['mdrunner'] = None
logger.warning("[em %d] Not using mdrunner for L-BFGS because it cannot "
"do parallel runs.", i)
files = energy_minimize(**kwargs)
return files
|
def _setup_MD(dirname,
deffnm='md', mdp=config.templates['md_OPLSAA.mdp'],
struct=None,
top='top/system.top', ndx=None,
mainselection='"Protein"',
qscript=config.qscript_template, qname=None, startdir=None, mdrun_opts="", budget=None, walltime=1/3.,
dt=0.002, runtime=1e3, **mdp_kwargs):
"""Generic function to set up a ``mdrun`` MD simulation.
See the user functions for usage.
"""
if struct is None:
raise ValueError('struct must be set to a input structure')
structure = realpath(struct)
topology = realpath(top)
try:
index = realpath(ndx)
except AttributeError: # (that's what realpath(None) throws...)
index = None # None is handled fine below
qname = mdp_kwargs.pop('sgename', qname) # compatibility for old scripts
qscript = mdp_kwargs.pop('sge', qscript) # compatibility for old scripts
qscript_template = config.get_template(qscript)
mdp_template = config.get_template(mdp)
nsteps = int(float(runtime)/float(dt))
mdp = deffnm + '.mdp'
tpr = deffnm + '.tpr'
mainindex = deffnm + '.ndx'
final_structure = deffnm + '.gro' # guess... really depends on templates,could also be DEFFNM.pdb
# write the processed topology to the default output
mdp_parameters = {'nsteps':nsteps, 'dt':dt, 'pp': 'processed.top'}
mdp_parameters.update(mdp_kwargs)
cbook.add_mdp_includes(topology, mdp_parameters)
logger.info("[%(dirname)s] input mdp = %(mdp_template)r", vars())
with in_dir(dirname):
if not (mdp_parameters.get('Tcoupl','').lower() == 'no' or mainselection is None):
logger.info("[{dirname!s}] Automatic adjustment of T-coupling groups".format(**vars()))
# make index file in almost all cases; with mainselection == None the user
# takes FULL control and also has to provide the template or index
groups = make_main_index(structure, selection=mainselection,
oldndx=index, ndx=mainindex)
natoms = {g['name']: float(g['natoms']) for g in groups}
tc_group_names = ('__main__', '__environment__') # defined in make_main_index()
try:
x = natoms['__main__']/natoms['__environment__']
except KeyError:
x = 0 # force using SYSTEM in code below
wmsg = "Missing __main__ and/or __environment__ index group.\n" \
"This probably means that you have an atypical system. You can " \
"set mainselection=None and provide your own mdp and index files " \
"in order to set up temperature coupling.\n" \
"If no T-coupling is required then set Tcoupl='no'.\n" \
"For now we will just couple everything to 'System'."
logger.warn(wmsg)
warnings.warn(wmsg, category=AutoCorrectionWarning)
if x < 0.1:
# couple everything together
tau_t = firstof(mdp_parameters.pop('tau_t', 0.1))
ref_t = firstof(mdp_parameters.pop('ref_t', 300))
# combine all in one T-coupling group
mdp_parameters['tc-grps'] = 'System'
mdp_parameters['tau_t'] = tau_t # this overrides the commandline!
mdp_parameters['ref_t'] = ref_t # this overrides the commandline!
mdp_parameters['gen-temp'] = mdp_parameters.pop('gen_temp', ref_t)
wmsg = "Size of __main__ is only %.1f%% of __environment__ so " \
"we use 'System' for T-coupling and ref_t = %g K and " \
"tau_t = %g 1/ps (can be changed in mdp_parameters).\n" \
% (x * 100, ref_t, tau_t)
logger.warn(wmsg)
warnings.warn(wmsg, category=AutoCorrectionWarning)
else:
# couple protein and bath separately
n_tc_groups = len(tc_group_names)
tau_t = asiterable(mdp_parameters.pop('tau_t', 0.1))
ref_t = asiterable(mdp_parameters.pop('ref_t', 300))
if len(tau_t) != n_tc_groups:
tau_t = n_tc_groups * [tau_t[0]]
wmsg = "%d coupling constants should have been supplied for tau_t. "\
"Using %f 1/ps for all of them." % (n_tc_groups, tau_t[0])
logger.warn(wmsg)
warnings.warn(wmsg, category=AutoCorrectionWarning)
if len(ref_t) != n_tc_groups:
ref_t = n_tc_groups * [ref_t[0]]
wmsg = "%d temperatures should have been supplied for ref_t. "\
"Using %g K for all of them." % (n_tc_groups, ref_t[0])
logger.warn(wmsg)
warnings.warn(wmsg, category=AutoCorrectionWarning)
mdp_parameters['tc-grps'] = tc_group_names
mdp_parameters['tau_t'] = tau_t
mdp_parameters['ref_t'] = ref_t
mdp_parameters['gen-temp'] = mdp_parameters.pop('gen_temp', ref_t[0])
index = realpath(mainindex)
if mdp_parameters.get('Tcoupl','').lower() == 'no':
logger.info("Tcoupl == no: disabling all temperature coupling mdp options")
mdp_parameters['tc-grps'] = ""
mdp_parameters['tau_t'] = ""
mdp_parameters['ref_t'] = ""
mdp_parameters['gen-temp'] = ""
if mdp_parameters.get('Pcoupl','').lower() == 'no':
logger.info("Pcoupl == no: disabling all pressure coupling mdp options")
mdp_parameters['tau_p'] = ""
mdp_parameters['ref_p'] = ""
mdp_parameters['compressibility'] = ""
unprocessed = cbook.edit_mdp(mdp_template, new_mdp=mdp, **mdp_parameters)
check_mdpargs(unprocessed)
gromacs.grompp(f=mdp, p=topology, c=structure, n=index, o=tpr, **unprocessed)
runscripts = qsub.generate_submit_scripts(
qscript_template, deffnm=deffnm, jobname=qname, budget=budget,
startdir=startdir, mdrun_opts=mdrun_opts, walltime=walltime)
logger.info("[%(dirname)s] output mdp = %(mdp)r", vars())
logger.info("[%(dirname)s] output ndx = %(ndx)r", vars())
logger.info("[%(dirname)s] output tpr = %(tpr)r", vars())
logger.info("[%(dirname)s] output runscripts = %(runscripts)r", vars())
logger.info("[%(dirname)s] All files set up for a run time of %(runtime)g ps "
"(dt=%(dt)g, nsteps=%(nsteps)g)" % vars())
kwargs = {'struct': realpath(os.path.join(dirname, final_structure)), # guess
'top': topology,
'ndx': index, # possibly mainindex
'qscript': runscripts,
'mainselection': mainselection,
'deffnm': deffnm, # return deffnm (tpr = deffnm.tpr!)
}
kwargs.update(mdp_kwargs) # return extra mdp args so that one can use them for prod run
return kwargs
|
def MD_restrained(dirname='MD_POSRES', **kwargs):
"""Set up MD with position restraints.
Additional itp files should be in the same directory as the top file.
Many of the keyword arguments below already have sensible values. Note that
setting *mainselection* = ``None`` will disable many of the automated
choices and is often recommended when using your own mdp file.
:Keywords:
*dirname*
set up under directory dirname [MD_POSRES]
*struct*
input structure (gro, pdb, ...) [em/em.pdb]
*top*
topology file [top/system.top]
*mdp*
mdp file (or use the template) [templates/md.mdp]
*ndx*
index file (supply when using a custom mdp)
*includes*
additional directories to search for itp files
*mainselection*
:program:`make_ndx` selection to select main group ["Protein"]
(If ``None`` then no canonical index file is generated and
it is the user's responsibility to set *tc_grps*,
*tau_t*, and *ref_t* as keyword arguments, or provide the mdp template
with all parameter pre-set in *mdp* and probably also your own *ndx*
index file.)
*deffnm*
default filename for Gromacs run [md]
*runtime*
total length of the simulation in ps [1000]
*dt*
integration time step in ps [0.002]
*qscript*
script to submit to the queuing system; by default
uses the template :data:`gromacs.config.qscript_template`, which can
be manually set to another template from :data:`gromacs.config.templates`;
can also be a list of template names.
*qname*
name to be used for the job in the queuing system [PR_GMX]
*mdrun_opts*
option flags for the :program:`mdrun` command in the queuing system
scripts such as "-stepout 100". [""]
*kwargs*
remaining key/value pairs that should be changed in the template mdp
file, eg ``nstxtcout=250, nstfout=250`` or command line options for
``grompp` such as ``maxwarn=1``.
In particular one can also set **define** and activate
whichever position restraints have been coded into the itp
and top file. For instance one could have
*define* = "-DPOSRES_MainChain -DPOSRES_LIGAND"
if these preprocessor constructs exist. Note that there
**must not be any space between "-D" and the value.**
By default *define* is set to "-DPOSRES".
:Returns: a dict that can be fed into :func:`gromacs.setup.MD`
(but check, just in case, especially if you want to
change the ``define`` parameter in the mdp file)
.. Note:: The output frequency is drastically reduced for position
restraint runs by default. Set the corresponding ``nst*``
variables if you require more output. The `pressure coupling`_
option *refcoord_scaling* is set to "com" by default (but can
be changed via *kwargs*) and the pressure coupling
algorithm itself is set to *Pcoupl* = "Berendsen" to
run a stable simulation.
.. _`pressure coupling`: http://manual.gromacs.org/online/mdp_opt.html#pc
"""
logger.info("[{dirname!s}] Setting up MD with position restraints...".format(**vars()))
kwargs.setdefault('struct', 'em/em.pdb')
kwargs.setdefault('qname', 'PR_GMX')
kwargs.setdefault('define', '-DPOSRES')
# reduce size of output files
kwargs.setdefault('nstxout', '50000') # trr pos
kwargs.setdefault('nstvout', '50000') # trr veloc
kwargs.setdefault('nstfout', '0') # trr forces
kwargs.setdefault('nstlog', '500') # log file
kwargs.setdefault('nstenergy', '2500') # edr energy
kwargs.setdefault('nstxtcout', '5000') # xtc pos
# try to get good pressure equilibration
kwargs.setdefault('refcoord_scaling', 'com')
kwargs.setdefault('Pcoupl', "Berendsen")
new_kwargs = _setup_MD(dirname, **kwargs)
# clean up output kwargs
new_kwargs.pop('define', None) # but make sure that -DPOSRES does not stay...
new_kwargs.pop('refcoord_scaling', None)
new_kwargs.pop('Pcoupl', None)
return new_kwargs
|
def MD(dirname='MD', **kwargs):
"""Set up equilibrium MD.
Additional itp files should be in the same directory as the top file.
Many of the keyword arguments below already have sensible values. Note that
setting *mainselection* = ``None`` will disable many of the automated
choices and is often recommended when using your own mdp file.
:Keywords:
*dirname*
set up under directory dirname [MD]
*struct*
input structure (gro, pdb, ...) [MD_POSRES/md_posres.pdb]
*top*
topology file [top/system.top]
*mdp*
mdp file (or use the template) [templates/md.mdp]
*ndx*
index file (supply when using a custom mdp)
*includes*
additional directories to search for itp files
*mainselection*
``make_ndx`` selection to select main group ["Protein"]
(If ``None`` then no canonical index file is generated and
it is the user's responsibility to set *tc_grps*,
*tau_t*, and *ref_t* as keyword arguments, or provide the mdp template
with all parameter pre-set in *mdp* and probably also your own *ndx*
index file.)
*deffnm*
default filename for Gromacs run [md]
*runtime*
total length of the simulation in ps [1000]
*dt*
integration time step in ps [0.002]
*qscript*
script to submit to the queuing system; by default
uses the template :data:`gromacs.config.qscript_template`, which can
be manually set to another template from :data:`gromacs.config.templates`;
can also be a list of template names.
*qname*
name to be used for the job in the queuing system [MD_GMX]
*mdrun_opts*
option flags for the :program:`mdrun` command in the queuing system
scripts such as "-stepout 100 -dgdl". [""]
*kwargs*
remaining key/value pairs that should be changed in the template mdp
file, e.g. ``nstxtcout=250, nstfout=250`` or command line options for
:program`grompp` such as ``maxwarn=1``.
:Returns: a dict that can be fed into :func:`gromacs.setup.MD`
(but check, just in case, especially if you want to
change the *define* parameter in the mdp file)
"""
logger.info("[{dirname!s}] Setting up MD...".format(**vars()))
kwargs.setdefault('struct', 'MD_POSRES/md.gro')
kwargs.setdefault('qname', 'MD_GMX')
return _setup_MD(dirname, **kwargs)
|
def generate_submit_scripts(templates, prefix=None, deffnm='md', jobname='MD', budget=None,
mdrun_opts=None, walltime=1.0, jobarray_string=None, startdir=None,
npme=None, **kwargs):
"""Write scripts for queuing systems.
This sets up queuing system run scripts with a simple search and replace in
templates. See :func:`gromacs.cbook.edit_txt` for details. Shell scripts
are made executable.
:Arguments:
*templates*
Template file or list of template files. The "files" can also be names
or symbolic names for templates in the templates directory. See
:mod:`gromacs.config` for details and rules for writing templates.
*prefix*
Prefix for the final run script filename; by default the filename will be
the same as the template. [None]
*dirname*
Directory in which to place the submit scripts. [.]
*deffnm*
Default filename prefix for :program:`mdrun` ``-deffnm`` [md]
*jobname*
Name of the job in the queuing system. [MD]
*budget*
Which budget to book the runtime on [None]
*startdir*
Explicit path on the remote system (for run scripts that need to `cd`
into this directory at the beginning of execution) [None]
*mdrun_opts*
String of additional options for :program:`mdrun`.
*walltime*
Maximum runtime of the job in hours. [1]
*npme*
number of PME nodes
*jobarray_string*
Multi-line string that is spliced in for job array functionality
(see :func:`gromacs.qsub.generate_submit_array`; do not use manually)
*kwargs*
all other kwargs are ignored
:Returns: list of generated run scripts
"""
if not jobname[0].isalpha():
jobname = 'MD_'+jobname
wmsg = "To make the jobname legal it must start with a letter: changed to {0!r}".format(jobname)
logger.warn(wmsg)
warnings.warn(wmsg, category=AutoCorrectionWarning)
if prefix is None:
prefix = ""
if mdrun_opts is not None:
mdrun_opts = '"'+str(mdrun_opts)+'"' # TODO: could test if quotes already present
dirname = kwargs.pop('dirname', os.path.curdir)
wt = Timedelta(hours=walltime)
walltime = wt.strftime("%h:%M:%S")
wall_hours = wt.ashours
def write_script(template):
submitscript = os.path.join(dirname, prefix + os.path.basename(template))
logger.info("Setting up queuing system script {submitscript!r}...".format(**vars()))
# These substitution rules are documented for the user in the module doc string
qsystem = detect_queuing_system(template)
if qsystem is not None and (qsystem.name == 'Slurm'):
cbook.edit_txt(template,
[('^ *DEFFNM=','(?<==)(.*)', deffnm),
('^#.*(-J)', '((?<=-J\s))\s*\w+', jobname),
('^#.*(-A|account_no)', '((?<=-A\s)|(?<=account_no\s))\s*\w+', budget),
('^#.*(-t)', '(?<=-t\s)(\d+:\d+:\d+)', walltime),
('^ *WALL_HOURS=', '(?<==)(.*)', wall_hours),
('^ *STARTDIR=', '(?<==)(.*)', startdir),
('^ *NPME=', '(?<==)(.*)', npme),
('^ *MDRUN_OPTS=', '(?<==)("")', mdrun_opts), # only replace literal ""
('^# JOB_ARRAY_PLACEHOLDER', '^.*$', jobarray_string),
],
newname=submitscript)
ext = os.path.splitext(submitscript)[1]
else:
cbook.edit_txt(template,
[('^ *DEFFNM=','(?<==)(.*)', deffnm),
('^#.*(-N|job_name)', '((?<=-N\s)|(?<=job_name\s))\s*\w+', jobname),
('^#.*(-A|account_no)', '((?<=-A\s)|(?<=account_no\s))\s*\w+', budget),
('^#.*(-l walltime|wall_clock_limit)', '(?<==)(\d+:\d+:\d+)', walltime),
('^ *WALL_HOURS=', '(?<==)(.*)', wall_hours),
('^ *STARTDIR=', '(?<==)(.*)', startdir),
('^ *NPME=', '(?<==)(.*)', npme),
('^ *MDRUN_OPTS=', '(?<==)("")', mdrun_opts), # only replace literal ""
('^# JOB_ARRAY_PLACEHOLDER', '^.*$', jobarray_string),
],
newname=submitscript)
ext = os.path.splitext(submitscript)[1]
if ext in ('.sh', '.csh', '.bash'):
os.chmod(submitscript, 0o755)
return submitscript
return [write_script(template) for template in config.get_templates(templates)]
|
def generate_submit_array(templates, directories, **kwargs):
"""Generate a array job.
For each ``work_dir`` in *directories*, the array job will
1. cd into ``work_dir``
2. run the job as detailed in the template
It will use all the queuing system directives found in the
template. If more complicated set ups are required, then this
function cannot be used.
:Arguments:
*templates*
Basic template for a single job; the job array logic is spliced into
the position of the line ::
# JOB_ARRAY_PLACEHOLDER
The appropriate commands for common queuing systems (Sun Gridengine, PBS)
are hard coded here. The queuing system is detected from the suffix of
the template.
*directories*
List of directories under *dirname*. One task is set up for each
directory.
*dirname*
The array script will be placed in this directory. The *directories*
**must** be located under *dirname*.
*kwargs*
See :func:`gromacs.setup.generate_submit_script` for details.
"""
dirname = kwargs.setdefault('dirname', os.path.curdir)
reldirs = [relpath(p, start=dirname) for p in asiterable(directories)]
missing = [p for p in (os.path.join(dirname, subdir) for subdir in reldirs)
if not os.path.exists(p)]
if len(missing) > 0:
logger.debug("template=%(template)r: dirname=%(dirname)r reldirs=%(reldirs)r", vars())
logger.error("Some directories are not accessible from the array script: "
"%(missing)r", vars())
def write_script(template):
qsystem = detect_queuing_system(template)
if qsystem is None or not qsystem.has_arrays():
logger.warning("Not known how to make a job array for %(template)r; skipping...", vars())
return None
kwargs['jobarray_string'] = qsystem.array(reldirs)
return generate_submit_scripts(template, **kwargs)[0] # returns list of length 1
# must use config.get_templates() because we need to access the file for detecting
return [write_script(template) for template in config.get_templates(templates)]
|
def array(self, directories):
"""Return multiline string for simple array jobs over *directories*.
.. Warning:: The string is in ``bash`` and hence the template must also
be ``bash`` (and *not* ``csh`` or ``sh``).
"""
if not self.has_arrays():
raise NotImplementedError('Not known how make array jobs for '
'queuing system %(name)s' % vars(self))
hrule = '#'+60*'-'
lines = [
'',
hrule,
'# job array:',
self.array_flag(directories),
hrule,
'# directories for job tasks',
'declare -a jobdirs']
for i,dirname in enumerate(asiterable(directories)):
idx = i+1 # job array indices are 1-based
lines.append('jobdirs[{idx:d}]={dirname!r}'.format(**vars()))
lines.extend([
'# Switch to the current tasks directory:',
'wdir="${{jobdirs[${{{array_variable!s}}}]}}"'.format(**vars(self)),
'cd "$wdir" || { echo "ERROR: failed to enter $wdir."; exit 1; }',
hrule,
''
])
return "\n".join(lines)
|
def isMine(self, scriptname):
"""Primitive queuing system detection; only looks at suffix at the moment."""
suffix = os.path.splitext(scriptname)[1].lower()
if suffix.startswith('.'):
suffix = suffix[1:]
return self.suffix == suffix
|
def anumb_to_atom(self, anumb):
'''Returns the atom object corresponding to an atom number'''
assert isinstance(anumb, int), "anumb must be integer"
if not self._anumb_to_atom: # empty dictionary
if self.atoms:
for atom in self.atoms:
self._anumb_to_atom[atom.number] = atom
return self._anumb_to_atom[anumb]
else:
self.logger("no atoms in the molecule")
return False
else:
if anumb in self._anumb_to_atom:
return self._anumb_to_atom[anumb]
else:
self.logger("no such atom number ({0:d}) in the molecule".format(anumb))
return False
|
def renumber_atoms(self):
"""Reset the molecule's atoms :attr:`number` to be 1-indexed"""
if self.atoms:
# reset the mapping
self._anumb_to_atom = {}
for i,atom in enumerate(self.atoms):
atom.number = i+1 # starting from 1
else:
self.logger("the number of atoms is zero - no renumbering")
|
def total_regular_pixels_from_mask(mask):
"""Compute the total number of unmasked regular pixels in a masks."""
total_regular_pixels = 0
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
if not mask[y, x]:
total_regular_pixels += 1
return total_regular_pixels
|
def total_sparse_pixels_from_mask(mask, unmasked_sparse_grid_pixel_centres):
"""Given the full (i.e. without removing pixels which are outside the regular-masks) pixelization grid's pixel centers
and the regular-masks, compute the total number of pixels which are within the regular-masks and thus used by the
pixelization grid.
Parameters
-----------
mask : ccd.masks.Mask
The regular-masks within which pixelization pixels must be inside
unmasked_sparse_grid_pixel_centres : ndarray
The centres of the unmasked pixelization grid pixels.
"""
total_sparse_pixels = 0
for unmasked_sparse_pixel_index in range(unmasked_sparse_grid_pixel_centres.shape[0]):
y = unmasked_sparse_grid_pixel_centres[unmasked_sparse_pixel_index, 0]
x = unmasked_sparse_grid_pixel_centres[unmasked_sparse_pixel_index, 1]
if not mask[y,x]:
total_sparse_pixels += 1
return total_sparse_pixels
|
def mask_circular_from_shape_pixel_scale_and_radius(shape, pixel_scale, radius_arcsec, centre=(0.0, 0.0)):
"""Compute a circular masks from an input masks radius and regular shape."""
mask = np.full(shape, True)
centres_arcsec = mask_centres_from_shape_pixel_scale_and_centre(shape=mask.shape, pixel_scale=pixel_scale, centre=centre)
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
y_arcsec = (y - centres_arcsec[0]) * pixel_scale
x_arcsec = (x - centres_arcsec[1]) * pixel_scale
r_arcsec = np.sqrt(x_arcsec ** 2 + y_arcsec ** 2)
if r_arcsec <= radius_arcsec:
mask[y, x] = False
return mask
|
def mask_circular_annular_from_shape_pixel_scale_and_radii(shape, pixel_scale, inner_radius_arcsec, outer_radius_arcsec,
centre=(0.0, 0.0)):
"""Compute an annular masks from an input inner and outer masks radius and regular shape."""
mask = np.full(shape, True)
centres_arcsec = mask_centres_from_shape_pixel_scale_and_centre(shape=mask.shape, pixel_scale=pixel_scale, centre=centre)
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
y_arcsec = (y - centres_arcsec[0]) * pixel_scale
x_arcsec = (x - centres_arcsec[1]) * pixel_scale
r_arcsec = np.sqrt(x_arcsec ** 2 + y_arcsec ** 2)
if outer_radius_arcsec >= r_arcsec >= inner_radius_arcsec:
mask[y, x] = False
return mask
|
def mask_elliptical_from_shape_pixel_scale_and_radius(shape, pixel_scale, major_axis_radius_arcsec, axis_ratio, phi,
centre=(0.0, 0.0)):
"""Compute a circular masks from an input masks radius and regular shape."""
mask = np.full(shape, True)
centres_arcsec = mask_centres_from_shape_pixel_scale_and_centre(shape=mask.shape, pixel_scale=pixel_scale,
centre=centre)
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
y_arcsec = (y - centres_arcsec[0]) * pixel_scale
x_arcsec = (x - centres_arcsec[1]) * pixel_scale
r_arcsec_elliptical = elliptical_radius_from_y_x_phi_and_axis_ratio(y_arcsec, x_arcsec, phi, axis_ratio)
if r_arcsec_elliptical <= major_axis_radius_arcsec:
mask[y, x] = False
return mask
|
def mask_elliptical_annular_from_shape_pixel_scale_and_radius(shape, pixel_scale,
inner_major_axis_radius_arcsec, inner_axis_ratio, inner_phi,
outer_major_axis_radius_arcsec, outer_axis_ratio, outer_phi,
centre=(0.0, 0.0)):
"""Compute a circular masks from an input masks radius and regular shape."""
mask = np.full(shape, True)
centres_arcsec = mask_centres_from_shape_pixel_scale_and_centre(shape=mask.shape, pixel_scale=pixel_scale,
centre=centre)
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
y_arcsec = (y - centres_arcsec[0]) * pixel_scale
x_arcsec = (x - centres_arcsec[1]) * pixel_scale
inner_r_arcsec_elliptical = elliptical_radius_from_y_x_phi_and_axis_ratio(y_arcsec, x_arcsec,
inner_phi, inner_axis_ratio)
outer_r_arcsec_elliptical = elliptical_radius_from_y_x_phi_and_axis_ratio(y_arcsec, x_arcsec,
outer_phi, outer_axis_ratio)
if inner_r_arcsec_elliptical >= inner_major_axis_radius_arcsec and \
outer_r_arcsec_elliptical <= outer_major_axis_radius_arcsec:
mask[y, x] = False
return mask
|
def mask_blurring_from_mask_and_psf_shape(mask, psf_shape):
"""Compute a blurring masks from an input masks and psf shape.
The blurring masks corresponds to all pixels which are outside of the masks but will have a fraction of their \
light blur into the masked region due to PSF convolution."""
blurring_mask = np.full(mask.shape, True)
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
if not mask[y, x]:
for y1 in range((-psf_shape[0] + 1) // 2, (psf_shape[0] + 1) // 2):
for x1 in range((-psf_shape[1] + 1) // 2, (psf_shape[1] + 1) // 2):
if 0 <= x + x1 <= mask.shape[1] - 1 and 0 <= y + y1 <= mask.shape[0] - 1:
if mask[y + y1, x + x1]:
blurring_mask[y + y1, x + x1] = False
else:
raise exc.MaskException(
"setup_blurring_mask extends beyond the sub_grid_size of the masks - pad the "
"datas array before masking")
return blurring_mask
|
def masked_grid_1d_index_to_2d_pixel_index_from_mask(mask):
"""Compute a 1D array that maps every unmasked pixel to its corresponding 2d pixel using its (y,x) pixel indexes.
For howtolens if pixel [2,5] corresponds to the second pixel on the 1D array, grid_to_pixel[1] = [2,5]"""
total_regular_pixels = total_regular_pixels_from_mask(mask)
grid_to_pixel = np.zeros(shape=(total_regular_pixels, 2))
pixel_count = 0
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
if not mask[y, x]:
grid_to_pixel[pixel_count, :] = y, x
pixel_count += 1
return grid_to_pixel
|
def masked_sub_grid_1d_index_to_2d_sub_pixel_index_from_mask(mask, sub_grid_size):
"""Compute a 1D array that maps every unmasked pixel to its corresponding 2d pixel using its (y,x) pixel indexes.
For howtolens if pixel [2,5] corresponds to the second pixel on the 1D array, grid_to_pixel[1] = [2,5]"""
total_sub_pixels = total_sub_pixels_from_mask_and_sub_grid_size(mask=mask, sub_grid_size=sub_grid_size)
sub_grid_to_sub_pixel = np.zeros(shape=(total_sub_pixels, 2))
sub_pixel_count = 0
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
if not mask[y, x]:
for y1 in range(sub_grid_size):
for x1 in range(sub_grid_size):
sub_grid_to_sub_pixel[sub_pixel_count, :] = (y*sub_grid_size)+y1, (x*sub_grid_size)+x1
sub_pixel_count += 1
return sub_grid_to_sub_pixel
|
def total_edge_pixels_from_mask(mask):
"""Compute the total number of borders-pixels in a masks."""
border_pixel_total = 0
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
if not mask[y, x]:
if mask[y + 1, x] or mask[y - 1, x] or mask[y, x + 1] or mask[y, x - 1] or \
mask[y + 1, x + 1] or mask[y + 1, x - 1] or mask[y - 1, x + 1] or mask[y - 1, x - 1]:
border_pixel_total += 1
return border_pixel_total
|
def edge_pixels_from_mask(mask):
"""Compute a 1D array listing all edge pixel indexes in the masks. An edge pixel is a pixel which is not fully \
surrounding by False masks values i.e. it is on an edge."""
edge_pixel_total = total_edge_pixels_from_mask(mask)
edge_pixels = np.zeros(edge_pixel_total)
edge_index = 0
regular_index = 0
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
if not mask[y, x]:
if mask[y + 1, x] or mask[y - 1, x] or mask[y, x + 1] or mask[y, x - 1] or \
mask[y + 1, x + 1] or mask[y + 1, x - 1] or mask[y - 1, x + 1] or mask[y - 1, x - 1]:
edge_pixels[edge_index] = regular_index
edge_index += 1
regular_index += 1
return edge_pixels
|
def total_border_pixels_from_mask_and_edge_pixels(mask, edge_pixels, masked_grid_index_to_pixel):
"""Compute the total number of borders-pixels in a masks."""
border_pixel_total = 0
for i in range(edge_pixels.shape[0]):
if check_if_border_pixel(mask, edge_pixels[i], masked_grid_index_to_pixel):
border_pixel_total += 1
return border_pixel_total
|
def border_pixels_from_mask(mask):
"""Compute a 1D array listing all borders pixel indexes in the masks. A borders pixel is a pixel which:
1) is not fully surrounding by False masks values.
2) Can reach the edge of the array without hitting a masked pixel in one of four directions (upwards, downwards,
left, right).
The borders pixels are thus pixels which are on the exterior edge of the masks. For example, the inner ring of edge \
pixels in an annular masks are edge pixels but not borders pixels."""
edge_pixels = edge_pixels_from_mask(mask)
masked_grid_index_to_pixel = masked_grid_1d_index_to_2d_pixel_index_from_mask(mask)
border_pixel_total = total_border_pixels_from_mask_and_edge_pixels(mask, edge_pixels, masked_grid_index_to_pixel)
border_pixels = np.zeros(border_pixel_total)
border_pixel_index = 0
for edge_pixel_index in range(edge_pixels.shape[0]):
if check_if_border_pixel(mask, edge_pixels[edge_pixel_index], masked_grid_index_to_pixel):
border_pixels[border_pixel_index] = edge_pixels[edge_pixel_index]
border_pixel_index += 1
return border_pixels
|
def bin_up_mask_2d(mask_2d, bin_up_factor):
"""Bin up an array to coarser resolution, by binning up groups of pixels and using their sum value to determine \
the value of the new pixel.
If an array of shape (8,8) is input and the bin up size is 2, this would return a new array of size (4,4) where \
every pixel was the sum of each collection of 2x2 pixels on the (8,8) array.
If binning up the array leads to an edge being cut (e.g. a (9,9) array binned up by 2), an array is first \
extracted around the centre of that array.
Parameters
----------
mask_2d : ndarray
The 2D array that is resized.
new_shape : (int, int)
The (y,x) new pixel dimension of the trimmed array.
origin : (int, int)
The oigin of the resized array, e.g. the central pixel around which the array is extracted.
Returns
-------
ndarray
The resized 2D array from the input 2D array.
Examples
--------
array_2d = np.ones((5,5))
resize_array = resize_array_2d(array_2d=array_2d, new_shape=(2,2), origin=(2, 2))
"""
padded_array_2d = array_util.pad_2d_array_for_binning_up_with_bin_up_factor(
array_2d=mask_2d, bin_up_factor=bin_up_factor, pad_value=True)
binned_array_2d = np.zeros(shape=(padded_array_2d.shape[0] // bin_up_factor,
padded_array_2d.shape[1] // bin_up_factor))
for y in range(binned_array_2d.shape[0]):
for x in range(binned_array_2d.shape[1]):
value = True
for y1 in range(bin_up_factor):
for x1 in range(bin_up_factor):
padded_y = y*bin_up_factor + y1
padded_x = x*bin_up_factor + x1
if padded_array_2d[padded_y, padded_x] == False:
value = False
binned_array_2d[y,x] = value
return binned_array_2d
|
def plot_fit_subplot_lens_plane_only(
fit, should_plot_mask=True, extract_array_from_mask=False, zoom_around_mask=False, positions=None,
should_plot_image_plane_pix=False,
units='arcsec', figsize=None, aspect='square',
cmap='jet', norm='linear', norm_min=None, norm_max=None, linthresh=0.05, linscale=0.01,
cb_ticksize=10, cb_fraction=0.047, cb_pad=0.01, cb_tick_values=None, cb_tick_labels=None,
titlesize=10, xlabelsize=10, ylabelsize=10, xyticksize=10,
mask_pointsize=10, position_pointsize=10, grid_pointsize=1,
output_path=None, output_filename='lens_fit', output_format='show'):
"""Plot the model datas_ of an analysis, using the *Fitter* class object.
The visualization and output type can be fully customized.
Parameters
-----------
fit : autolens.lens.fitting.Fitter
Class containing fit between the model datas_ and observed lens datas_ (including residual_map, chi_squared_map etc.)
output_path : str
The path where the datas_ is output if the output_type is a file format (e.g. png, fits)
output_filename : str
The name of the file that is output, if the output_type is a file format (e.g. png, fits)
output_format : str
How the datas_ is output. File formats (e.g. png, fits) output the datas_ to harddisk. 'show' displays the datas_ \
in the python interpreter window.
"""
rows, columns, figsize_tool = plotter_util.get_subplot_rows_columns_figsize(number_subplots=6)
mask = lens_plotter_util.get_mask(fit=fit, should_plot_mask=should_plot_mask)
if figsize is None:
figsize = figsize_tool
plt.figure(figsize=figsize)
plt.subplot(rows, columns, 1)
kpc_per_arcsec = fit.tracer.image_plane.kpc_per_arcsec
image_plane_pix_grid = lens_plotter_util.get_image_plane_pix_grid(should_plot_image_plane_pix, fit)
lens_plotter_util.plot_image(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
positions=positions, image_plane_pix_grid=image_plane_pix_grid, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
grid_pointsize=grid_pointsize, position_pointsize=position_pointsize, mask_pointsize=mask_pointsize,
output_path=output_path, output_filename='', output_format=output_format)
plt.subplot(rows, columns, 2)
lens_plotter_util.plot_noise_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
positions=positions, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
position_pointsize=position_pointsize, mask_pointsize=mask_pointsize,
output_path=output_path, output_filename='', output_format=output_format)
plt.subplot(rows, columns, 3)
lens_plotter_util.plot_signal_to_noise_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
positions=positions, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
position_pointsize=position_pointsize, mask_pointsize=mask_pointsize,
output_path=output_path, output_filename='', output_format=output_format)
plt.subplot(rows, columns, 4)
lens_plotter_util.plot_model_data(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
output_path=output_path, output_filename='', output_format=output_format)
plt.subplot(rows, columns, 5)
lens_plotter_util.plot_residual_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
output_path=output_path, output_filename='', output_format=output_format)
plt.subplot(rows, columns, 6)
lens_plotter_util.plot_chi_squared_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
output_path=output_path, output_filename='', output_format=output_format)
plotter_util.output_subplot_array(output_path=output_path, output_filename=output_filename,
output_format=output_format)
plt.close()
|
def plot_fit_subplot_lens_and_source_planes(
fit, should_plot_mask=True, extract_array_from_mask=False, zoom_around_mask=False,
should_plot_source_grid=False, positions=None, should_plot_image_plane_pix=False, plot_mass_profile_centres=True,
units='arcsec', figsize=None, aspect='square',
cmap='jet', norm='linear', norm_min=None, norm_max=None, linthresh=0.05, linscale=0.01,
cb_ticksize=10, cb_fraction=0.047, cb_pad=0.01, cb_tick_values=None, cb_tick_labels=None,
titlesize=10, xlabelsize=10, ylabelsize=10, xyticksize=10,
mask_pointsize=10, position_pointsize=10, grid_pointsize=1,
output_path=None, output_filename='lens_fit', output_format='show'):
"""Plot the model datas_ of an analysis, using the *Fitter* class object.
The visualization and output type can be fully customized.
Parameters
-----------
fit : autolens.lens.fitting.Fitter
Class containing fit between the model datas_ and observed lens datas_ (including residual_map, chi_squared_map etc.)
output_path : str
The path where the datas_ is output if the output_type is a file format (e.g. png, fits)
output_filename : str
The name of the file that is output, if the output_type is a file format (e.g. png, fits)
output_format : str
How the datas_ is output. File formats (e.g. png, fits) output the datas_ to harddisk. 'show' displays the datas_ \
in the python interpreter window.
"""
rows, columns, figsize_tool = plotter_util.get_subplot_rows_columns_figsize(number_subplots=9)
mask = lens_plotter_util.get_mask(fit=fit, should_plot_mask=should_plot_mask)
if figsize is None:
figsize = figsize_tool
plt.figure(figsize=figsize)
kpc_per_arcsec = fit.tracer.image_plane.kpc_per_arcsec
image_plane_pix_grid = lens_plotter_util.get_image_plane_pix_grid(should_plot_image_plane_pix, fit)
plt.subplot(rows, columns, 1)
lens_plotter_util.plot_image(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask, positions=positions,
image_plane_pix_grid=image_plane_pix_grid, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
grid_pointsize=grid_pointsize, position_pointsize=position_pointsize, mask_pointsize=mask_pointsize,
output_path=output_path, output_filename='', output_format=output_format)
plt.subplot(rows, columns, 2)
lens_plotter_util.plot_noise_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask, positions=None, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
position_pointsize=position_pointsize, mask_pointsize=mask_pointsize,
output_path=output_path, output_filename='', output_format=output_format)
plt.subplot(rows, columns, 3)
lens_plotter_util.plot_signal_to_noise_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask, positions=None, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
position_pointsize=position_pointsize, mask_pointsize=mask_pointsize,
output_path=output_path, output_filename='', output_format=output_format)
plt.subplot(rows, columns, 4)
lens_plotter_util.plot_lens_subtracted_image(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask, positions=positions, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
title='Fit Lens Subtracted Image', titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize,
position_pointsize=position_pointsize, xyticksize=xyticksize,
output_path=output_path, output_filename='', output_format=output_format)
if fit.tracer.image_plane.has_light_profile:
plt.subplot(rows, columns, 5)
lens_plotter_util.plot_model_image_of_planes(
fit=fit, plot_foreground=True, mask=mask, extract_array_from_mask=extract_array_from_mask,
zoom_around_mask=zoom_around_mask, plot_mass_profile_centres=plot_mass_profile_centres, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
title='Fit Image-Plane Model Image', titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize,
xyticksize=xyticksize,
output_path=output_path, output_filename='', output_format=output_format)
plt.subplot(rows, columns, 6)
lens_plotter_util.plot_model_image_of_planes(
fit=fit, plot_source=True, mask=mask, extract_array_from_mask=extract_array_from_mask,
zoom_around_mask=zoom_around_mask, plot_mass_profile_centres=plot_mass_profile_centres, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
title='Fit Source-Plane Model Image', titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize,
xyticksize=xyticksize,
output_path=output_path, output_filename='lens_subtracted_image', output_format=output_format)
if fit.total_inversions == 0:
plt.subplot(rows, columns, 7)
plane_plotters.plot_plane_image(
plane=fit.tracer.source_plane, positions=None, plot_grid=should_plot_source_grid, as_subplot=True,
units=units, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
grid_pointsize=grid_pointsize, position_pointsize=position_pointsize,
output_path=output_path, output_filename='', output_format=output_format)
elif fit.total_inversions == 1:
ratio = float((fit.inversion.mapper.geometry.arc_second_maxima[1] - fit.inversion.mapper.geometry.arc_second_minima[1]) / \
(fit.inversion.mapper.geometry.arc_second_maxima[0] - fit.inversion.mapper.geometry.arc_second_minima[0]))
if aspect is 'square':
aspect_inv = ratio
elif aspect is 'auto':
aspect_inv = 1.0 / ratio
elif aspect is 'equal':
aspect_inv = 1.0
plt.subplot(rows, columns, 7, aspect=float(aspect_inv))
inversion_plotters.plot_reconstructed_pixelization(
inversion=fit.inversion, positions=None, should_plot_grid=False, should_plot_centres=False, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=None,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
output_path=output_path, output_filename=None, output_format=output_format)
plt.subplot(rows, columns, 8)
lens_plotter_util.plot_residual_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
output_path=output_path, output_filename='', output_format=output_format)
plt.subplot(rows, columns, 9)
lens_plotter_util.plot_chi_squared_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask, as_subplot=True,
units=units, kpc_per_arcsec=kpc_per_arcsec, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
output_path=output_path, output_filename='', output_format=output_format)
plotter_util.output_subplot_array(output_path=output_path, output_filename=output_filename,
output_format=output_format)
plt.close()
|
def plot_fit_individuals_lens_plane_only(
fit, should_plot_mask=True, extract_array_from_mask=False, zoom_around_mask=False, positions=None,
should_plot_image_plane_pix=False,
should_plot_image=False,
should_plot_noise_map=False,
should_plot_signal_to_noise_map=False,
should_plot_model_image=False,
should_plot_residual_map=False,
should_plot_chi_squared_map=False,
units='arcsec',
output_path=None, output_format='show'):
"""Plot the model datas_ of an analysis, using the *Fitter* class object.
The visualization and output type can be fully customized.
Parameters
-----------
fit : autolens.lens.fitting.Fitter
Class containing fit between the model datas_ and observed lens datas_ (including residual_map, chi_squared_map etc.)
output_path : str
The path where the datas_ is output if the output_type is a file format (e.g. png, fits)
output_format : str
How the datas_ is output. File formats (e.g. png, fits) output the datas_ to harddisk. 'show' displays the datas_ \
in the python interpreter window.
"""
mask = lens_plotter_util.get_mask(fit=fit, should_plot_mask=should_plot_mask)
kpc_per_arcsec = fit.tracer.image_plane.kpc_per_arcsec
if should_plot_image:
image_plane_pix_grid = lens_plotter_util.get_image_plane_pix_grid(should_plot_image_plane_pix, fit)
lens_plotter_util.plot_image(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
image_plane_pix_grid=image_plane_pix_grid,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_format=output_format)
if should_plot_noise_map:
lens_plotter_util.plot_noise_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_format=output_format)
if should_plot_signal_to_noise_map:
lens_plotter_util.plot_signal_to_noise_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_format=output_format)
if should_plot_model_image:
lens_plotter_util.plot_model_data(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask, positions=positions,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_format=output_format)
if should_plot_residual_map:
lens_plotter_util.plot_residual_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_format=output_format)
if should_plot_chi_squared_map:
lens_plotter_util.plot_chi_squared_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_format=output_format)
|
def plot_fit_individuals_lens_and_source_planes(
fit, should_plot_mask=True, extract_array_from_mask=False, zoom_around_mask=False, positions=None,
should_plot_image_plane_pix=False,
should_plot_image=False,
should_plot_noise_map=False,
should_plot_signal_to_noise_map=False,
should_plot_lens_subtracted_image=False,
should_plot_model_image=False,
should_plot_lens_model_image=False,
should_plot_source_model_image=False,
should_plot_source_plane_image=False,
should_plot_residual_map=False,
should_plot_chi_squared_map=False,
units='arcsec',
output_path=None, output_format='show'):
"""Plot the model datas_ of an analysis, using the *Fitter* class object.
The visualization and output type can be fully customized.
Parameters
-----------
fit : autolens.lens.fitting.Fitter
Class containing fit between the model datas_ and observed lens datas_ (including residual_map, chi_squared_map etc.)
output_path : str
The path where the datas_ is output if the output_type is a file format (e.g. png, fits)
output_format : str
How the datas_ is output. File formats (e.g. png, fits) output the datas_ to harddisk. 'show' displays the datas_ \
in the python interpreter window.
"""
mask = lens_plotter_util.get_mask(fit=fit, should_plot_mask=should_plot_mask)
kpc_per_arcsec = fit.tracer.image_plane.kpc_per_arcsec
if should_plot_image:
image_plane_pix_grid = lens_plotter_util.get_image_plane_pix_grid(should_plot_image_plane_pix, fit)
lens_plotter_util.plot_image(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
image_plane_pix_grid=image_plane_pix_grid,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_format=output_format)
if should_plot_noise_map:
lens_plotter_util.plot_noise_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_format=output_format)
if should_plot_signal_to_noise_map:
lens_plotter_util.plot_signal_to_noise_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_format=output_format)
if should_plot_lens_subtracted_image:
lens_plotter_util.plot_lens_subtracted_image(
fit=fit, mask=mask, positions=positions, extract_array_from_mask=extract_array_from_mask,
zoom_around_mask=zoom_around_mask,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_format=output_format)
if should_plot_model_image:
lens_plotter_util.plot_model_data(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_format=output_format)
if should_plot_lens_model_image:
lens_plotter_util.plot_model_image_of_planes(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
plot_foreground=True,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_filename='fit_lens_plane_model_image', output_format=output_format)
if should_plot_source_model_image:
lens_plotter_util.plot_model_image_of_planes(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
plot_source=True,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_filename='fit_source_plane_model_image', output_format=output_format)
if should_plot_source_plane_image:
if fit.total_inversions == 0:
plane_plotters.plot_plane_image(
plane=fit.tracer.source_plane, plot_grid=True,
units=units, figsize=(20, 20),
output_path=output_path, output_filename='fit_source_plane', output_format=output_format)
elif fit.total_inversions == 1:
inversion_plotters.plot_reconstructed_pixelization(
inversion=fit.inversion, should_plot_grid=True,
units=units, figsize=(20, 20),
output_path=output_path, output_filename='fit_source_plane', output_format=output_format)
if should_plot_residual_map:
lens_plotter_util.plot_residual_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_format=output_format)
if should_plot_chi_squared_map:
lens_plotter_util.plot_chi_squared_map(
fit=fit, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
units=units, kpc_per_arcsec=kpc_per_arcsec,
output_path=output_path, output_format=output_format)
|
def setup_figure(figsize, as_subplot):
"""Setup a figure for plotting an image.
Parameters
-----------
figsize : (int, int)
The size of the figure in (rows, columns).
as_subplot : bool
If the figure is a subplot, the setup_figure function is omitted to ensure that each subplot does not create a \
new figure and so that it can be output using the *output_subplot_array* function.
"""
if not as_subplot:
fig = plt.figure(figsize=figsize)
return fig
|
def output_figure(array, as_subplot, output_path, output_filename, output_format):
"""Output the figure, either as an image on the screen or to the hard-disk as a .png or .fits file.
Parameters
-----------
array : ndarray
The 2D array of image to be output, required for outputting the image as a fits file.
as_subplot : bool
Whether the figure is part of subplot, in which case the figure is not output so that the entire subplot can \
be output instead using the *output_subplot_array* function.
output_path : str
The path on the hard-disk where the figure is output.
output_filename : str
The filename of the figure that is output.
output_format : str
The format the figue is output:
'show' - display on computer screen.
'png' - output to hard-disk as a png.
'fits' - output to hard-disk as a fits file.'
"""
if not as_subplot:
if output_format is 'show':
plt.show()
elif output_format is 'png':
plt.savefig(output_path + output_filename + '.png', bbox_inches='tight')
elif output_format is 'fits':
array_util.numpy_array_2d_to_fits(array_2d=array, file_path=output_path + output_filename + '.fits',
overwrite=True)
|
def output_subplot_array(output_path, output_filename, output_format):
"""Output a figure which consists of a set of subplot,, either as an image on the screen or to the hard-disk as a \
.png file.
Parameters
-----------
output_path : str
The path on the hard-disk where the figure is output.
output_filename : str
The filename of the figure that is output.
output_format : str
The format the figue is output:
'show' - display on computer screen.
'png' - output to hard-disk as a png.
"""
if output_format is 'show':
plt.show()
elif output_format is 'png':
plt.savefig(output_path + output_filename + '.png', bbox_inches='tight')
elif output_format is 'fits':
raise exc.PlottingException('You cannot output a subplots with format .fits')
|
def image_psf_shape_tag_from_image_psf_shape(image_psf_shape):
"""Generate an image psf shape tag, to customize phase names based on size of the image PSF that the original PSF \
is trimmed to for faster run times.
This changes the phase name 'phase_name' as follows:
image_psf_shape = 1 -> phase_name
image_psf_shape = 2 -> phase_name_image_psf_shape_2
image_psf_shape = 2 -> phase_name_image_psf_shape_2
"""
if image_psf_shape is None:
return ''
else:
y = str(image_psf_shape[0])
x = str(image_psf_shape[1])
return ('_image_psf_' + y + 'x' + x)
|
def inversion_psf_shape_tag_from_inversion_psf_shape(inversion_psf_shape):
"""Generate an inversion psf shape tag, to customize phase names based on size of the inversion PSF that the \
original PSF is trimmed to for faster run times.
This changes the phase name 'phase_name' as follows:
inversion_psf_shape = 1 -> phase_name
inversion_psf_shape = 2 -> phase_name_inversion_psf_shape_2
inversion_psf_shape = 2 -> phase_name_inversion_psf_shape_2
"""
if inversion_psf_shape is None:
return ''
else:
y = str(inversion_psf_shape[0])
x = str(inversion_psf_shape[1])
return ('_inv_psf_' + y + 'x' + x)
|
def bulge_disk_tag_from_align_bulge_disks(align_bulge_disk_centre, align_bulge_disk_axis_ratio, align_bulge_disk_phi):
"""Generate a tag for the alignment of the geometry of the bulge and disk of a bulge-disk system, to customize \
phase names based on the bulge-disk model. This adds together the bulge_disk tags generated in the 3 functions
above
"""
align_bulge_disk_centre_tag = align_bulge_disk_centre_tag_from_align_bulge_disk_centre(
align_bulge_disk_centre=align_bulge_disk_centre)
align_bulge_disk_axis_ratio_tag = align_bulge_disk_axis_ratio_tag_from_align_bulge_disk_axis_ratio(
align_bulge_disk_axis_ratio=align_bulge_disk_axis_ratio)
align_bulge_disk_phi_tag = align_bulge_disk_phi_tag_from_align_bulge_disk_phi(
align_bulge_disk_phi=align_bulge_disk_phi)
return align_bulge_disk_centre_tag + align_bulge_disk_axis_ratio_tag + align_bulge_disk_phi_tag
|
def ordered_plane_redshifts_from_galaxies(galaxies):
"""Given a list of galaxies (with redshifts), return a list of the redshifts in ascending order.
If two or more galaxies have the same redshift that redshift is not double counted.
Parameters
-----------
galaxies : [Galaxy]
The list of galaxies in the ray-tracing calculation.
"""
ordered_galaxies = sorted(galaxies, key=lambda galaxy: galaxy.redshift, reverse=False)
# Ideally we'd extract the planes_red_Shfit order from the list above. However, I dont know how to extract it
# Using a list of class attributes so make a list of redshifts for now.
galaxy_redshifts = list(map(lambda galaxy: galaxy.redshift, ordered_galaxies))
return [redshift for i, redshift in enumerate(galaxy_redshifts) if redshift not in galaxy_redshifts[:i]]
|
def ordered_plane_redshifts_from_lens_and_source_plane_redshifts_and_slice_sizes(lens_redshifts, planes_between_lenses,
source_plane_redshift):
"""Given a set of lens plane redshifts, the source-plane redshift and the number of planes between each, setup the \
plane redshifts using these values. A lens redshift corresponds to the 'main' lens galaxy(s),
whereas the slices collect line-of-sight halos over a range of redshifts.
The source-plane redshift is removed from the ordered plane redshifts that are returned, so that galaxies are not \
planed at the source-plane redshift.
For example, if the main plane redshifts are [1.0, 2.0], and the bin sizes are [1,3], the following redshift \
slices for planes will be used:
z=0.5
z=1.0
z=1.25
z=1.5
z=1.75
z=2.0
Parameters
-----------
lens_redshifts : [float]
The redshifts of the main-planes (e.g. the lens galaxy), which determine where redshift intervals are placed.
planes_between_lenses : [int]
The number of slices between each main plane. The first entry in this list determines the number of slices \
between Earth (redshift 0.0) and main plane 0, the next between main planes 0 and 1, etc.
source_plane_redshift : float
The redshift of the source-plane, which is input explicitly to ensure galaxies are not placed in the \
source-plane.
"""
# Check that the number of slices between lens planes is equal to the number of intervals between the lens planes.
if len(lens_redshifts) != len(planes_between_lenses)-1:
raise exc.RayTracingException('The number of lens_plane_redshifts input is not equal to the number of '
'slices_between_lens_planes+1.')
plane_redshifts = []
# Add redshift 0.0 and the source plane redshifit to the lens plane redshifts, so that calculation below can use
# them when dividing slices. These will be removed by the return function at the end from the plane redshifts.
lens_redshifts.insert(0, 0.0)
lens_redshifts.append(source_plane_redshift)
for lens_plane_index in range(1, len(lens_redshifts)):
previous_plane_redshift = lens_redshifts[lens_plane_index - 1]
plane_redshift = lens_redshifts[lens_plane_index]
slice_total = planes_between_lenses[lens_plane_index - 1]
plane_redshifts += list(np.linspace(previous_plane_redshift, plane_redshift, slice_total+2))[1:]
return plane_redshifts[0:-1]
|
def galaxies_in_redshift_ordered_planes_from_galaxies(galaxies, plane_redshifts):
"""Given a list of galaxies (with redshifts), return a list of the galaxies where each entry contains a list \
of galaxies at the same redshift in ascending redshift order.
Parameters
-----------
galaxies : [Galaxy]
The list of galaxies in the ray-tracing calculation.
"""
galaxies_in_redshift_ordered_planes = [[] for i in range(len(plane_redshifts))]
for galaxy in galaxies:
index = (np.abs(np.asarray(plane_redshifts) - galaxy.redshift)).argmin()
galaxies_in_redshift_ordered_planes[index].append(galaxy)
return galaxies_in_redshift_ordered_planes
|
def compute_deflections_at_next_plane(plane_index, total_planes):
"""This function determines whether the tracer should compute the deflections at the next plane.
This is True if there is another plane after this plane, else it is False..
Parameters
-----------
plane_index : int
The index of the plane we are deciding if we should compute its deflections.
total_planes : int
The total number of planes."""
if plane_index < total_planes - 1:
return True
elif plane_index == total_planes - 1:
return False
else:
raise exc.RayTracingException('A galaxy was not correctly allocated its previous / next redshifts')
|
def scaled_deflection_stack_from_plane_and_scaling_factor(plane, scaling_factor):
"""Given a plane and scaling factor, compute a set of scaled deflections.
Parameters
-----------
plane : plane.Plane
The plane whose deflection stack is scaled.
scaling_factor : float
The factor the deflection angles are scaled by, which is typically the scaling factor between redshifts for \
multi-plane lensing.
"""
def scale(grid):
return np.multiply(scaling_factor, grid)
if plane.deflection_stack is not None:
return plane.deflection_stack.apply_function(scale)
else:
return None
|
def grid_stack_from_deflection_stack(grid_stack, deflection_stack):
"""For a deflection stack, comput a new grid stack but subtracting the deflections"""
if deflection_stack is not None:
def minus(grid, deflections):
return grid - deflections
return grid_stack.map_function(minus, deflection_stack)
|
def plot_ray_tracing_subplot(
tracer, mask=None, extract_array_from_mask=False, zoom_around_mask=False, positions=None,
units='arcsec', figsize=None, aspect='square',
cmap='jet', norm='linear', norm_min=None, norm_max=None, linthresh=0.05, linscale=0.01,
cb_ticksize=10, cb_fraction=0.047, cb_pad=0.01, cb_tick_values=None, cb_tick_labels=None,
titlesize=10, xlabelsize=10, ylabelsize=10, xyticksize=10,
mask_pointsize=10, position_pointsize=10.0, grid_pointsize=1.0,
output_path=None, output_filename='tracer', output_format='show'):
"""Plot the observed _tracer of an analysis, using the *CCD* class object.
The visualization and output type can be fully customized.
Parameters
-----------
tracer : autolens.ccd.tracer.CCD
Class containing the _tracer, noise_map-mappers and PSF that are to be plotted.
The font size of the figure ylabel.
output_path : str
The path where the _tracer is output if the output_type is a file format (e.g. png, fits)
output_format : str
How the _tracer is output. File formats (e.g. png, fits) output the _tracer to harddisk. 'show' displays the _tracer \
in the python interpreter window.
"""
rows, columns, figsize_tool = plotter_util.get_subplot_rows_columns_figsize(number_subplots=6)
if figsize is None:
figsize = figsize_tool
plt.figure(figsize=figsize)
plt.subplot(rows, columns, 1)
plot_image_plane_image(
tracer=tracer, mask=mask, extract_array_from_mask=extract_array_from_mask, zoom_around_mask=zoom_around_mask,
positions=positions, as_subplot=True,
units=units, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
mask_pointsize=mask_pointsize, position_pointsize=position_pointsize,
output_path=output_path, output_filename='', output_format=output_format)
if tracer.has_mass_profile:
plt.subplot(rows, columns, 2)
plot_convergence(
tracer=tracer, mask=mask, extract_array_from_mask=extract_array_from_mask,
zoom_around_mask=zoom_around_mask, as_subplot=True,
units=units, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
output_path=output_path, output_filename='', output_format=output_format)
plt.subplot(rows, columns, 3)
plot_potential(
tracer=tracer, mask=mask, extract_array_from_mask=extract_array_from_mask,
zoom_around_mask=zoom_around_mask, as_subplot=True,
units=units, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
output_path=output_path, output_filename='', output_format=output_format)
plt.subplot(rows, columns, 4)
plane_plotters.plot_plane_image(
plane=tracer.source_plane, as_subplot=True, positions=None, plot_grid=False,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
grid_pointsize=grid_pointsize,
output_path=output_path, output_filename='', output_format=output_format)
if tracer.has_mass_profile:
plt.subplot(rows, columns, 5)
plot_deflections_y(
tracer=tracer, mask=mask, extract_array_from_mask=extract_array_from_mask,
zoom_around_mask=zoom_around_mask, as_subplot=True,
units=units, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
output_path=output_path, output_filename='', output_format=output_format)
plt.subplot(rows, columns, 6)
plot_deflections_x(
tracer=tracer, mask=mask, extract_array_from_mask=extract_array_from_mask,
zoom_around_mask=zoom_around_mask, as_subplot=True,
units=units, figsize=figsize, aspect=aspect,
cmap=cmap, norm=norm, norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels,
titlesize=titlesize, xlabelsize=xlabelsize, ylabelsize=ylabelsize, xyticksize=xyticksize,
output_path=output_path, output_filename='', output_format=output_format)
plotter_util.output_subplot_array(output_path=output_path, output_filename=output_filename,
output_format=output_format)
plt.close()
|
def plot_ray_tracing_individual(
tracer, mask=None, extract_array_from_mask=False, zoom_around_mask=False, positions=None,
should_plot_image_plane_image=False,
should_plot_source_plane=False,
should_plot_convergence=False,
should_plot_potential=False,
should_plot_deflections=False,
units='arcsec',
output_path=None, output_format='show'):
"""Plot the observed _tracer of an analysis, using the *CCD* class object.
The visualization and output type can be fully customized.
Parameters
-----------
tracer : autolens.ccd.tracer.CCD
Class containing the _tracer, noise_map-mappers and PSF that are to be plotted.
The font size of the figure ylabel.
output_path : str
The path where the _tracer is output if the output_type is a file format (e.g. png, fits)
output_format : str
How the _tracer is output. File formats (e.g. png, fits) output the _tracer to harddisk. 'show' displays the _tracer \
in the python interpreter window.
"""
if should_plot_image_plane_image:
plot_image_plane_image(
tracer=tracer, mask=mask, extract_array_from_mask=extract_array_from_mask,
zoom_around_mask=zoom_around_mask, positions=positions,
units=units,
output_path=output_path, output_format=output_format)
if should_plot_convergence:
plot_convergence(
tracer=tracer, mask=mask, extract_array_from_mask=extract_array_from_mask,
zoom_around_mask=zoom_around_mask,
units=units,
output_path=output_path, output_format=output_format)
if should_plot_potential:
plot_potential(
tracer=tracer, mask=mask, extract_array_from_mask=extract_array_from_mask,
zoom_around_mask=zoom_around_mask,
units=units,
output_path=output_path, output_format=output_format)
if should_plot_source_plane:
plane_plotters.plot_plane_image(
plane=tracer.source_plane, positions=None, plot_grid=False,
units=units,
output_path=output_path, output_filename='tracer_source_plane', output_format=output_format)
if should_plot_deflections:
plot_deflections_y(
tracer=tracer, mask=mask, extract_array_from_mask=extract_array_from_mask,
zoom_around_mask=zoom_around_mask,
units=units,
output_path=output_path, output_format=output_format)
if should_plot_deflections:
plot_deflections_x(
tracer=tracer, mask=mask, extract_array_from_mask=extract_array_from_mask,
zoom_around_mask=zoom_around_mask,
units=units,
output_path=output_path, output_format=output_format)
|
def constant_regularization_matrix_from_pixel_neighbors(coefficients, pixel_neighbors, pixel_neighbors_size):
"""From the pixel-neighbors, setup the regularization matrix using the constant regularization scheme.
Parameters
----------
coefficients : tuple
The regularization coefficients which controls the degree of smoothing of the inversion reconstruction.
pixel_neighbors : ndarray
An array of length (total_pixels) which provides the index of all neighbors of every pixel in \
the Voronoi grid (entries of -1 correspond to no neighbor).
pixel_neighbors_size : ndarrayy
An array of length (total_pixels) which gives the number of neighbors of every pixel in the \
Voronoi grid.
"""
pixels = len(pixel_neighbors)
regularization_matrix = np.zeros(shape=(pixels, pixels))
regularization_coefficient = coefficients[0] ** 2.0
for i in range(pixels):
regularization_matrix[i, i] += 1e-8
for j in range(pixel_neighbors_size[i]):
neighbor_index = pixel_neighbors[i, j]
regularization_matrix[i, i] += regularization_coefficient
regularization_matrix[i, neighbor_index] -= regularization_coefficient
return regularization_matrix
|
def weighted_pixel_signals_from_images(pixels, signal_scale, regular_to_pix, galaxy_image):
"""Compute the (scaled) signal in each pixel, where the signal is the sum of its datas_-pixel fluxes. \
These pixel-signals are used to compute the effective regularization weight of each pixel.
The pixel signals are scaled in the following ways:
1) Divided by the number of datas_-pixels in the pixel, to ensure all pixels have the same \
'relative' signal (i.e. a pixel with 10 regular-pixels doesn't have x2 the signal of one with 5).
2) Divided by the maximum pixel-signal, so that all signals vary between 0 and 1. This ensures that the \
regularizations weights are defined identically for any datas_ units or signal-to-noise_map ratio.
3) Raised to the power of the hyper-parameter *signal_scale*, so the method can control the relative \
contribution regularization in different regions of pixelization.
Parameters
-----------
pixels : int
The total number of pixels in the pixelization the regularization scheme is applied to.
signal_scale : float
A factor which controls how rapidly the smoothness of regularization varies from high signal regions to \
low signal regions.
regular_to_pix : ndarray
A 1D array mapping every pixel on the regular-grid to a pixel on the pixelization.
galaxy_image : ndarray
The image of the galaxy which is used to compute the weigghted pixel signals.
"""
pixel_signals = np.zeros((pixels,))
pixel_sizes = np.zeros((pixels,))
for regular_index in range(galaxy_image.shape[0]):
pixel_signals[regular_to_pix[regular_index]] += galaxy_image[regular_index]
pixel_sizes[regular_to_pix[regular_index]] += 1
pixel_signals /= pixel_sizes
pixel_signals /= np.max(pixel_signals)
return pixel_signals ** signal_scale
|
def weighted_regularization_matrix_from_pixel_neighbors(regularization_weights, pixel_neighbors,
pixel_neighbors_size):
"""From the pixel-neighbors, setup the regularization matrix using the weighted regularization scheme.
Parameters
----------
regularization_weights : ndarray
The regularization_ weight of each pixel, which governs how much smoothing is applied to that individual pixel.
pixel_neighbors : ndarray
An array of length (total_pixels) which provides the index of all neighbors of every pixel in \
the Voronoi grid (entries of -1 correspond to no neighbor).
pixel_neighbors_size : ndarrayy
An array of length (total_pixels) which gives the number of neighbors of every pixel in the \
Voronoi grid.
"""
pixels = len(regularization_weights)
regularization_matrix = np.zeros(shape=(pixels, pixels))
regularization_weight = regularization_weights ** 2.0
for i in range(pixels):
for j in range(pixel_neighbors_size[i]):
neighbor_index = pixel_neighbors[i, j]
regularization_matrix[i, i] += regularization_weight[neighbor_index]
regularization_matrix[neighbor_index, neighbor_index] += regularization_weight[neighbor_index]
regularization_matrix[i, neighbor_index] -= regularization_weight[neighbor_index]
regularization_matrix[neighbor_index, i] -= regularization_weight[neighbor_index]
return regularization_matrix
|
def plot_array(array, origin=None, mask=None, extract_array_from_mask=False, zoom_around_mask=False,
should_plot_border=False, positions=None, centres=None, axis_ratios=None, phis=None, grid=None,
as_subplot=False,
units='arcsec', kpc_per_arcsec=None, figsize=(7, 7), aspect='equal',
cmap='jet', norm='linear', norm_min=None, norm_max=None, linthresh=0.05, linscale=0.01,
cb_ticksize=10, cb_fraction=0.047, cb_pad=0.01, cb_tick_values=None, cb_tick_labels=None,
title='Array', titlesize=16, xlabelsize=16, ylabelsize=16, xyticksize=16,
mask_pointsize=10, border_pointsize=2, position_pointsize=30, grid_pointsize=1,
xticks_manual=None, yticks_manual=None,
output_path=None, output_format='show', output_filename='array'):
"""Plot an array of data as a figure.
Parameters
-----------
array : data.array.scaled_array.ScaledArray
The 2D array of data which is plotted.
origin : (float, float).
The origin of the coordinate system of the array, which is plotted as an 'x' on the image if input.
mask : data.array.mask.Mask
The mask applied to the array, the edge of which is plotted as a set of points over the plotted array.
extract_array_from_mask : bool
The plotter array is extracted using the mask, such that masked values are plotted as zeros. This ensures \
bright features outside the mask do not impact the color map of the plot.
zoom_around_mask : bool
If True, the 2D region of the array corresponding to the rectangle encompassing all unmasked values is \
plotted, thereby zooming into the region of interest.
should_plot_border : bool
If a mask is supplied, its borders pixels (e.g. the exterior edge) is plotted if this is *True*.
positions : [[]]
Lists of (y,x) coordinates on the image which are plotted as colored dots, to highlight specific pixels.
grid : data.array.grids.RegularGrid
A grid of (y,x) coordinates which may be plotted over the plotted array.
as_subplot : bool
Whether the array is plotted as part of a subplot, in which case the grid figure is not opened / closed.
units : str
The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').
kpc_per_arcsec : float or None
The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.
figsize : (int, int)
The size of the figure in (rows, columns).
aspect : str
The aspect ratio of the array, specifically whether it is forced to be square ('equal') or adapts its size to \
the figure size ('auto').
cmap : str
The colormap the array is plotted using, which may be chosen from the standard matplotlib colormaps.
norm : str
The normalization of the colormap used to plot the image, specifically whether it is linear ('linear'), log \
('log') or a symmetric log normalization ('symmetric_log').
norm_min : float or None
The minimum array value the colormap map spans (all values below this value are plotted the same color).
norm_max : float or None
The maximum array value the colormap map spans (all values above this value are plotted the same color).
linthresh : float
For the 'symmetric_log' colormap normalization ,this specifies the range of values within which the colormap \
is linear.
linscale : float
For the 'symmetric_log' colormap normalization, this allowws the linear range set by linthresh to be stretched \
relative to the logarithmic range.
cb_ticksize : int
The size of the tick labels on the colorbar.
cb_fraction : float
The fraction of the figure that the colorbar takes up, which resizes the colorbar relative to the figure.
cb_pad : float
Pads the color bar in the figure, which resizes the colorbar relative to the figure.
xlabelsize : int
The fontsize of the x axes label.
ylabelsize : int
The fontsize of the y axes label.
xyticksize : int
The font size of the x and y ticks on the figure axes.
mask_pointsize : int
The size of the points plotted to show the mask.
border_pointsize : int
The size of the points plotted to show the borders.
positions_pointsize : int
The size of the points plotted to show the input positions.
grid_pointsize : int
The size of the points plotted to show the grid.
xticks_manual : [] or None
If input, the xticks do not use the array's default xticks but instead overwrite them as these values.
yticks_manual : [] or None
If input, the yticks do not use the array's default yticks but instead overwrite them as these values.
output_path : str
The path on the hard-disk where the figure is output.
output_filename : str
The filename of the figure that is output.
output_format : str
The format the figue is output:
'show' - display on computer screen.
'png' - output to hard-disk as a png.
'fits' - output to hard-disk as a fits file.'
Returns
--------
None
Examples
--------
array_plotters.plot_array(
array=image, origin=(0.0, 0.0), mask=circular_mask, extract_array_from_mask=True, zoom_around_mask=True,
should_plot_border=False, positions=[[1.0, 1.0], [2.0, 2.0]], grid=None, as_subplot=False,
units='arcsec', kpc_per_arcsec=None, figsize=(7,7), aspect='auto',
cmap='jet', norm='linear, norm_min=None, norm_max=None, linthresh=None, linscale=None,
cb_ticksize=10, cb_fraction=0.047, cb_pad=0.01, cb_tick_values=None, cb_tick_labels=None,
title='Image', titlesize=16, xlabelsize=16, ylabelsize=16, xyticksize=16,
mask_pointsize=10, border_pointsize=2, position_pointsize=10, grid_pointsize=10,
xticks_manual=None, yticks_manual=None,
output_path='/path/to/output', output_format='png', output_filename='image')
"""
if array is None:
return
if extract_array_from_mask and mask is not None:
array = np.add(array, 0.0, out=np.zeros_like(array), where=np.asarray(mask) == 0)
if zoom_around_mask and mask is not None:
array = array.zoomed_scaled_array_around_mask(mask=mask, buffer=2)
zoom_offset_pixels = np.asarray(mask.zoom_offset_pixels)
zoom_offset_arcsec = np.asarray(mask.zoom_offset_arcsec)
else:
zoom_offset_pixels = None
zoom_offset_arcsec = None
if aspect is 'square':
aspect = float(array.shape_arcsec[1]) / float(array.shape_arcsec[0])
fig = plot_figure(array=array, as_subplot=as_subplot, units=units, kpc_per_arcsec=kpc_per_arcsec,
figsize=figsize, aspect=aspect, cmap=cmap, norm=norm,
norm_min=norm_min, norm_max=norm_max, linthresh=linthresh, linscale=linscale,
xticks_manual=xticks_manual, yticks_manual=yticks_manual)
plotter_util.set_title(title=title, titlesize=titlesize)
set_xy_labels_and_ticksize(units=units, kpc_per_arcsec=kpc_per_arcsec, xlabelsize=xlabelsize, ylabelsize=ylabelsize,
xyticksize=xyticksize)
set_colorbar(cb_ticksize=cb_ticksize, cb_fraction=cb_fraction, cb_pad=cb_pad,
cb_tick_values=cb_tick_values, cb_tick_labels=cb_tick_labels)
plot_origin(array=array, origin=origin, units=units, kpc_per_arcsec=kpc_per_arcsec,
zoom_offset_arcsec=zoom_offset_arcsec)
plot_mask(mask=mask, units=units, kpc_per_arcsec=kpc_per_arcsec, pointsize=mask_pointsize,
zoom_offset_pixels=zoom_offset_pixels)
plot_border(mask=mask, should_plot_border=should_plot_border, units=units, kpc_per_arcsec=kpc_per_arcsec,
pointsize=border_pointsize, zoom_offset_pixels=zoom_offset_pixels)
plot_points(points_arcsec=positions, array=array, units=units, kpc_per_arcsec=kpc_per_arcsec,
pointsize=position_pointsize, zoom_offset_arcsec=zoom_offset_arcsec)
plot_grid(grid_arcsec=grid, array=array, units=units, kpc_per_arcsec=kpc_per_arcsec, pointsize=grid_pointsize,
zoom_offset_arcsec=zoom_offset_arcsec)
plot_centres(array=array, centres=centres, units=units, kpc_per_arcsec=kpc_per_arcsec,
zoom_offset_arcsec=zoom_offset_arcsec)
plot_ellipses(fig=fig, array=array, centres=centres, axis_ratios=axis_ratios, phis=phis, units=units,
kpc_per_arcsec=kpc_per_arcsec, zoom_offset_arcsec=zoom_offset_arcsec)
plotter_util.output_figure(array, as_subplot=as_subplot, output_path=output_path, output_filename=output_filename,
output_format=output_format)
plotter_util.close_figure(as_subplot=as_subplot)
|
def plot_figure(array, as_subplot, units, kpc_per_arcsec, figsize, aspect, cmap, norm, norm_min, norm_max,
linthresh, linscale, xticks_manual, yticks_manual):
"""Open a matplotlib figure and plot the array of data on it.
Parameters
-----------
array : data.array.scaled_array.ScaledArray
The 2D array of data which is plotted.
as_subplot : bool
Whether the array is plotted as part of a subplot, in which case the grid figure is not opened / closed.
units : str
The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').
kpc_per_arcsec : float or None
The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.
figsize : (int, int)
The size of the figure in (rows, columns).
aspect : str
The aspect ratio of the array, specifically whether it is forced to be square ('equal') or adapts its size to \
the figure size ('auto').
cmap : str
The colormap the array is plotted using, which may be chosen from the standard matplotlib colormaps.
norm : str
The normalization of the colormap used to plot the image, specifically whether it is linear ('linear'), log \
('log') or a symmetric log normalization ('symmetric_log').
norm_min : float or None
The minimum array value the colormap map spans (all values below this value are plotted the same color).
norm_max : float or None
The maximum array value the colormap map spans (all values above this value are plotted the same color).
linthresh : float
For the 'symmetric_log' colormap normalization ,this specifies the range of values within which the colormap \
is linear.
linscale : float
For the 'symmetric_log' colormap normalization, this allowws the linear range set by linthresh to be stretched \
relative to the logarithmic range.
xticks_manual : [] or None
If input, the xticks do not use the array's default xticks but instead overwrite them as these values.
yticks_manual : [] or None
If input, the yticks do not use the array's default yticks but instead overwrite them as these values.
"""
fig = plotter_util.setup_figure(figsize=figsize, as_subplot=as_subplot)
norm_min, norm_max = get_normalization_min_max(array=array, norm_min=norm_min, norm_max=norm_max)
norm_scale = get_normalization_scale(norm=norm, norm_min=norm_min, norm_max=norm_max,
linthresh=linthresh, linscale=linscale)
extent = get_extent(array=array, units=units, kpc_per_arcsec=kpc_per_arcsec,
xticks_manual=xticks_manual, yticks_manual=yticks_manual)
plt.imshow(array, aspect=aspect, cmap=cmap, norm=norm_scale, extent=extent)
return fig
|
def get_extent(array, units, kpc_per_arcsec, xticks_manual, yticks_manual):
"""Get the extent of the dimensions of the array in the units of the figure (e.g. arc-seconds or kpc).
This is used to set the extent of the array and thus the y / x axis limits.
Parameters
-----------
array : data.array.scaled_array.ScaledArray
The 2D array of data which is plotted.
units : str
The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').
kpc_per_arcsec : float
The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.
xticks_manual : [] or None
If input, the xticks do not use the array's default xticks but instead overwrite them as these values.
yticks_manual : [] or None
If input, the yticks do not use the array's default yticks but instead overwrite them as these values.
"""
if xticks_manual is not None and yticks_manual is not None:
return np.asarray([xticks_manual[0], xticks_manual[3], yticks_manual[0], yticks_manual[3]])
if units in 'pixels':
return np.asarray([0, array.shape[1], 0, array.shape[0]])
elif units in 'arcsec' or kpc_per_arcsec is None:
return np.asarray([array.arc_second_minima[1], array.arc_second_maxima[1],
array.arc_second_minima[0], array.arc_second_maxima[0]])
elif units in 'kpc':
return list(map(lambda tick : tick*kpc_per_arcsec,
np.asarray([array.arc_second_minima[1], array.arc_second_maxima[1],
array.arc_second_minima[0], array.arc_second_maxima[0]])))
else:
raise exc.PlottingException('The units supplied to the plotted are not a valid string (must be pixels | '
'arcsec | kpc)')
|
def get_normalization_min_max(array, norm_min, norm_max):
"""Get the minimum and maximum of the normalization of the array, which sets the lower and upper limits of the \
colormap.
If norm_min / norm_max are not supplied, the minimum / maximum values of the array of data are used.
Parameters
-----------
array : data.array.scaled_array.ScaledArray
The 2D array of data which is plotted.
norm_min : float or None
The minimum array value the colormap map spans (all values below this value are plotted the same color).
norm_max : float or None
The maximum array value the colormap map spans (all values above this value are plotted the same color).
"""
if norm_min is None:
norm_min = array.min()
if norm_max is None:
norm_max = array.max()
return norm_min, norm_max
|
def get_normalization_scale(norm, norm_min, norm_max, linthresh, linscale):
"""Get the normalization scale of the colormap. This will be scaled based on the input min / max normalization \
values.
For a 'symmetric_log' colormap, linthesh and linscale also change the colormap.
If norm_min / norm_max are not supplied, the minimum / maximum values of the array of data are used.
Parameters
-----------
array : data.array.scaled_array.ScaledArray
The 2D array of data which is plotted.
norm_min : float or None
The minimum array value the colormap map spans (all values below this value are plotted the same color).
norm_max : float or None
The maximum array value the colormap map spans (all values above this value are plotted the same color).
linthresh : float
For the 'symmetric_log' colormap normalization ,this specifies the range of values within which the colormap \
is linear.
linscale : float
For the 'symmetric_log' colormap normalization, this allowws the linear range set by linthresh to be stretched \
relative to the logarithmic range.
"""
if norm is 'linear':
return colors.Normalize(vmin=norm_min, vmax=norm_max)
elif norm is 'log':
if norm_min == 0.0:
norm_min = 1.e-4
return colors.LogNorm(vmin=norm_min, vmax=norm_max)
elif norm is 'symmetric_log':
return colors.SymLogNorm(linthresh=linthresh, linscale=linscale, vmin=norm_min, vmax=norm_max)
else:
raise exc.PlottingException('The normalization (norm) supplied to the plotter is not a valid string (must be '
'linear | log | symmetric_log')
|
def set_colorbar(cb_ticksize, cb_fraction, cb_pad, cb_tick_values, cb_tick_labels):
"""Setup the colorbar of the figure, specifically its ticksize and the size is appears relative to the figure.
Parameters
-----------
cb_ticksize : int
The size of the tick labels on the colorbar.
cb_fraction : float
The fraction of the figure that the colorbar takes up, which resizes the colorbar relative to the figure.
cb_pad : float
Pads the color bar in the figure, which resizes the colorbar relative to the figure.
cb_tick_values : [float]
Manually specified values of where the colorbar tick labels appear on the colorbar.
cb_tick_labels : [float]
Manually specified labels of the color bar tick labels, which appear where specified by cb_tick_values.
"""
if cb_tick_values is None and cb_tick_labels is None:
cb = plt.colorbar(fraction=cb_fraction, pad=cb_pad)
elif cb_tick_values is not None and cb_tick_labels is not None:
cb = plt.colorbar(fraction=cb_fraction, pad=cb_pad, ticks=cb_tick_values)
cb.ax.set_yticklabels(cb_tick_labels)
else:
raise exc.PlottingException('Only 1 entry of cb_tick_values or cb_tick_labels was input. You must either supply'
'both the values and labels, or neither.')
cb.ax.tick_params(labelsize=cb_ticksize)
|
def convert_grid_units(array, grid_arcsec, units, kpc_per_arcsec):
"""Convert the grid from its input units (arc-seconds) to the input unit (e.g. retain arc-seconds) or convert to \
another set of units (pixels or kilo parsecs).
Parameters
-----------
array : data.array.scaled_array.ScaledArray
The 2D array of data which is plotted, the shape of which is used for converting the grid to units of pixels.
grid_arcsec : ndarray or data.array.grids.RegularGrid
The (y,x) coordinates of the grid in arc-seconds, in an array of shape (total_coordinates, 2).
units : str
The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').
kpc_per_arcsec : float
The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.
"""
if units in 'pixels':
return array.grid_arcsec_to_grid_pixels(grid_arcsec=grid_arcsec)
elif units in 'arcsec' or kpc_per_arcsec is None:
return grid_arcsec
elif units in 'kpc':
return grid_arcsec * kpc_per_arcsec
else:
raise exc.PlottingException('The units supplied to the plotter are not a valid string (must be pixels | '
'arcsec | kpc)')
|
def plot_origin(array, origin, units, kpc_per_arcsec, zoom_offset_arcsec):
"""Plot the (y,x) origin ofo the array's coordinates as a 'x'.
Parameters
-----------
array : data.array.scaled_array.ScaledArray
The 2D array of data which is plotted.
origin : (float, float).
The origin of the coordinate system of the array, which is plotted as an 'x' on the image if input.
units : str
The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').
kpc_per_arcsec : float or None
The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.
"""
if origin is not None:
origin_grid = np.asarray(origin)
if zoom_offset_arcsec is not None:
origin_grid -= zoom_offset_arcsec
origin_units = convert_grid_units(array=array, grid_arcsec=origin_grid, units=units,
kpc_per_arcsec=kpc_per_arcsec)
plt.scatter(y=origin_units[0], x=origin_units[1], s=80, c='k', marker='x')
|
def plot_centres(array, centres, units, kpc_per_arcsec, zoom_offset_arcsec):
"""Plot the (y,x) centres (e.g. of a mass profile) on the array as an 'x'.
Parameters
-----------
array : data.array.scaled_array.ScaledArray
The 2D array of data which is plotted.
centres : [[tuple]]
The list of centres; centres in the same list entry are colored the same.
units : str
The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').
kpc_per_arcsec : float or None
The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.
"""
if centres is not None:
colors = itertools.cycle(["m", "y", "r", "w", "c", "b", "g", "k"])
for centres_of_galaxy in centres:
color = next(colors)
for centre in centres_of_galaxy:
if zoom_offset_arcsec is not None:
centre -= zoom_offset_arcsec
centre_units = convert_grid_units(array=array, grid_arcsec=centre, units=units,
kpc_per_arcsec=kpc_per_arcsec)
plt.scatter(y=centre_units[0], x=centre_units[1], s=300, c=color, marker='x')
|
def plot_ellipses(fig, array, centres, axis_ratios, phis, units, kpc_per_arcsec, zoom_offset_arcsec):
"""Plot the (y,x) centres (e.g. of a mass profile) on the array as an 'x'.
Parameters
-----------
array : data.array.scaled_array.ScaledArray
The 2D array of data which is plotted.
centres : [[tuple]]
The list of centres; centres in the same list entry are colored the same.
units : str
The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').
kpc_per_arcsec : float or None
The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.
"""
if centres is not None and axis_ratios is not None and phis is not None:
colors = itertools.cycle(["m", "y", "r", "w", "c", "b", "g", "k"])
for set_index in range(len(centres)):
color = next(colors)
for geometry_index in range(len(centres[set_index])):
centre = centres[set_index][geometry_index]
axis_ratio = axis_ratios[set_index][geometry_index]
phi = phis[set_index][geometry_index]
if zoom_offset_arcsec is not None:
centre -= zoom_offset_arcsec
centre_units = convert_grid_units(array=array, grid_arcsec=centre, units=units,
kpc_per_arcsec=kpc_per_arcsec)
y = 1.0
x = 1.0*axis_ratio
t = np.linspace(0, 2*np.pi, 100)
plt.plot(centre_units[0] + y*np.cos(t), centre_units[1] + x*np.sin(t), color=color)
|
def plot_mask(mask, units, kpc_per_arcsec, pointsize, zoom_offset_pixels):
"""Plot the mask of the array on the figure.
Parameters
-----------
mask : ndarray of data.array.mask.Mask
The mask applied to the array, the edge of which is plotted as a set of points over the plotted array.
units : str
The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').
kpc_per_arcsec : float or None
The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.
pointsize : int
The size of the points plotted to show the mask.
"""
if mask is not None:
plt.gca()
edge_pixels = mask.masked_grid_index_to_pixel[mask.edge_pixels] + 0.5
if zoom_offset_pixels is not None:
edge_pixels -= zoom_offset_pixels
edge_arcsec = mask.grid_pixels_to_grid_arcsec(grid_pixels=edge_pixels)
edge_units = convert_grid_units(array=mask, grid_arcsec=edge_arcsec, units=units,
kpc_per_arcsec=kpc_per_arcsec)
plt.scatter(y=edge_units[:,0], x=edge_units[:,1], s=pointsize, c='k')
|
def plot_border(mask, should_plot_border, units, kpc_per_arcsec, pointsize, zoom_offset_pixels):
"""Plot the borders of the mask or the array on the figure.
Parameters
-----------t.
mask : ndarray of data.array.mask.Mask
The mask applied to the array, the edge of which is plotted as a set of points over the plotted array.
should_plot_border : bool
If a mask is supplied, its borders pixels (e.g. the exterior edge) is plotted if this is *True*.
units : str
The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').
kpc_per_arcsec : float or None
The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.
border_pointsize : int
The size of the points plotted to show the borders.
"""
if should_plot_border and mask is not None:
plt.gca()
border_pixels = mask.masked_grid_index_to_pixel[mask.border_pixels]
if zoom_offset_pixels is not None:
border_pixels -= zoom_offset_pixels
border_arcsec = mask.grid_pixels_to_grid_arcsec(grid_pixels=border_pixels)
border_units = convert_grid_units(array=mask, grid_arcsec=border_arcsec, units=units,
kpc_per_arcsec=kpc_per_arcsec)
plt.scatter(y=border_units[:,0], x=border_units[:,1], s=pointsize, c='y')
|
def plot_points(points_arcsec, array, units, kpc_per_arcsec, pointsize, zoom_offset_arcsec):
"""Plot a set of points over the array of data on the figure.
Parameters
-----------
positions : [[]]
Lists of (y,x) coordinates on the image which are plotted as colored dots, to highlight specific pixels.
array : data.array.scaled_array.ScaledArray
The 2D array of data which is plotted.
units : str
The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').
kpc_per_arcsec : float or None
The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.
pointsize : int
The size of the points plotted to show the input positions.
"""
if points_arcsec is not None:
points_arcsec = list(map(lambda position_set: np.asarray(position_set), points_arcsec))
point_colors = itertools.cycle(["m", "y", "r", "w", "c", "b", "g", "k"])
for point_set_arcsec in points_arcsec:
if zoom_offset_arcsec is not None:
point_set_arcsec -= zoom_offset_arcsec
point_set_units = convert_grid_units(array=array, grid_arcsec=point_set_arcsec, units=units,
kpc_per_arcsec=kpc_per_arcsec)
plt.scatter(y=point_set_units[:,0], x=point_set_units[:,1], color=next(point_colors), s=pointsize)
|
def plot_grid(grid_arcsec, array, units, kpc_per_arcsec, pointsize, zoom_offset_arcsec):
"""Plot a grid of points over the array of data on the figure.
Parameters
-----------.
grid_arcsec : ndarray or data.array.grids.RegularGrid
A grid of (y,x) coordinates in arc-seconds which may be plotted over the array.
array : data.array.scaled_array.ScaledArray
The 2D array of data which is plotted.
units : str
The units of the y / x axis of the plots, in arc-seconds ('arcsec') or kiloparsecs ('kpc').
kpc_per_arcsec : float or None
The conversion factor between arc-seconds and kiloparsecs, required to plot the units in kpc.
grid_pointsize : int
The size of the points plotted to show the grid.
"""
if grid_arcsec is not None:
if zoom_offset_arcsec is not None:
grid_arcsec -= zoom_offset_arcsec
grid_units = convert_grid_units(grid_arcsec=grid_arcsec, array=array, units=units,
kpc_per_arcsec=kpc_per_arcsec)
plt.scatter(y=np.asarray(grid_units[:, 0]), x=np.asarray(grid_units[:, 1]), s=pointsize, c='k')
|
def mapping_matrix(self):
"""The mapping matrix is a matrix representing the mapping between every unmasked pixel of a grid and \
the pixels of a pixelization. Non-zero entries signify a mapping, whereas zeros signify no mapping.
For example, if the regular grid has 5 pixels and the pixelization 3 pixels, with the following mappings:
regular pixel 0 -> pixelization pixel 0
regular pixel 1 -> pixelization pixel 0
regular pixel 2 -> pixelization pixel 1
regular pixel 3 -> pixelization pixel 1
regular pixel 4 -> pixelization pixel 2
The mapping matrix (which is of dimensions regular_pixels x pixelization_pixels) would appear as follows:
[1, 0, 0] [0->0]
[1, 0, 0] [1->0]
[0, 1, 0] [2->1]
[0, 1, 0] [3->1]
[0, 0, 1] [4->2]
The mapping matrix is in fact built using the sub-grid of the grid-stack, whereby each regular-pixel is \
divided into a regular grid of sub-pixels which are all paired to pixels in the pixelization. The entires \
in the mapping matrix now become fractional values dependent on the sub-grid size. For example, for a 2x2 \
sub-grid in each pixel (which means the fraction value is 1.0/(2.0^2) = 0.25, if we have the following mappings:
regular pixel 0 -> sub pixel 0 -> pixelization pixel 0
regular pixel 0 -> sub pixel 1 -> pixelization pixel 1
regular pixel 0 -> sub pixel 2 -> pixelization pixel 1
regular pixel 0 -> sub pixel 3 -> pixelization pixel 1
regular pixel 1 -> sub pixel 0 -> pixelization pixel 1
regular pixel 1 -> sub pixel 1 -> pixelization pixel 1
regular pixel 1 -> sub pixel 2 -> pixelization pixel 1
regular pixel 1 -> sub pixel 3 -> pixelization pixel 1
regular pixel 2 -> sub pixel 0 -> pixelization pixel 2
regular pixel 2 -> sub pixel 1 -> pixelization pixel 2
regular pixel 2 -> sub pixel 2 -> pixelization pixel 3
regular pixel 2 -> sub pixel 3 -> pixelization pixel 3
The mapping matrix (which is still of dimensions regular_pixels x source_pixels) would appear as follows:
[0.25, 0.75, 0.0, 0.0] [1 sub-pixel maps to pixel 0, 3 map to pixel 1]
[ 0.0, 1.0, 0.0, 0.0] [All sub-pixels map to pixel 1]
[ 0.0, 0.0, 0.5, 0.5] [2 sub-pixels map to pixel 2, 2 map to pixel 3]
"""
return mapper_util.mapping_matrix_from_sub_to_pix(sub_to_pix=self.sub_to_pix, pixels=self.pixels,
regular_pixels=self.grid_stack.regular.shape[0],
sub_to_regular=self.grid_stack.sub.sub_to_regular,
sub_grid_fraction=self.grid_stack.sub.sub_grid_fraction)
|
def pix_to_regular(self):
"""Compute the mappings between a pixelization's pixels and the unmasked regular-grid pixels. These mappings \
are determined after the regular-grid is used to determine the pixelization.
The pixelization's pixels map to different number of regular-grid pixels, thus a list of lists is used to \
represent these mappings"""
pix_to_regular = [[] for _ in range(self.pixels)]
for regular_pixel, pix_pixel in enumerate(self.regular_to_pix):
pix_to_regular[pix_pixel].append(regular_pixel)
return pix_to_regular
|
def pix_to_sub(self):
"""Compute the mappings between a pixelization's pixels and the unmasked sub-grid pixels. These mappings \
are determined after the regular-grid is used to determine the pixelization.
The pixelization's pixels map to different number of sub-grid pixels, thus a list of lists is used to \
represent these mappings"""
pix_to_sub = [[] for _ in range(self.pixels)]
for regular_pixel, pix_pixel in enumerate(self.sub_to_pix):
pix_to_sub[pix_pixel].append(regular_pixel)
return pix_to_sub
|
def reconstructed_pixelization_from_solution_vector(self, solution_vector):
"""Given the solution vector of an inversion (see *inversions.Inversion*), determine the reconstructed \
pixelization of the rectangular pixelization by using the mapper."""
recon = mapping_util.map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape(array_1d=solution_vector,
shape=self.shape)
return scaled_array.ScaledRectangularPixelArray(array=recon, pixel_scales=self.geometry.pixel_scales,
origin=self.geometry.origin)
|
def regular_to_pix(self):
"""The 1D index mappings between the regular pixels and Voronoi pixelization pixels."""
return mapper_util.voronoi_regular_to_pix_from_grids_and_geometry(regular_grid=self.grid_stack.regular,
regular_to_nearest_pix=self.grid_stack.pix.regular_to_nearest_pix,
pixel_centres=self.geometry.pixel_centres, pixel_neighbors=self.geometry.pixel_neighbors,
pixel_neighbors_size=self.geometry.pixel_neighbors_size).astype('int')
|
def sub_to_pix(self):
""" The 1D index mappings between the sub pixels and Voronoi pixelization pixels. """
return mapper_util.voronoi_sub_to_pix_from_grids_and_geometry(sub_grid=self.grid_stack.sub,
regular_to_nearest_pix=self.grid_stack.pix.regular_to_nearest_pix,
sub_to_regular=self.grid_stack.sub.sub_to_regular, pixel_centres=self.geometry.pixel_centres,
pixel_neighbors=self.geometry.pixel_neighbors,
pixel_neighbors_size=self.geometry.pixel_neighbors_size).astype('int')
|
def centres_from_shape_pixel_scales_and_origin(shape, pixel_scales, origin):
"""Determine the (y,x) arc-second central coordinates of an array from its shape, pixel-scales and origin.
The coordinate system is defined such that the positive y axis is up and positive x axis is right.
Parameters
----------
shape : (int, int)
The (y,x) shape of the 2D array the arc-second centre is computed for.
pixel_scales : (float, float)
The (y,x) arc-second to pixel scales of the 2D array.
origin : (float, flloat)
The (y,x) origin of the 2D array, which the centre is shifted to.
Returns
--------
tuple (float, float)
The (y,x) arc-second central coordinates of the input array.
Examples
--------
centres_arcsec = centres_from_shape_pixel_scales_and_origin(shape=(5,5), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0))
"""
y_centre_arcsec = float(shape[0] - 1) / 2 + (origin[0] / pixel_scales[0])
x_centre_arcsec = float(shape[1] - 1) / 2 - (origin[1] / pixel_scales[1])
return (y_centre_arcsec, x_centre_arcsec)
|
def regular_grid_2d_from_shape_pixel_scales_and_origin(shape, pixel_scales, origin=(0.0, 0.0)):
"""Compute the (y,x) arc second coordinates at the centre of every pixel of an array of shape (rows, columns).
Coordinates are defined from the top-left corner, such that the first pixel at location [0, 0] has negative x \
and y values in arc seconds.
The regular grid is returned on an array of shape (total_pixels, total_pixels, 2) where coordinate indexes match \
those of the original 2D array. y coordinates are stored in the 0 index of the third dimension, x coordinates in \
the 1 index.
Parameters
----------
shape : (int, int)
The (y,x) shape of the 2D array the regular grid of coordinates is computed for.
pixel_scales : (float, float)
The (y,x) arc-second to pixel scales of the 2D array.
origin : (float, flloat)
The (y,x) origin of the 2D array, which the regular grid is shifted around.
Returns
--------
ndarray
A regular grid of (y,x) arc-second coordinates at the centre of every pixel on a 2D array. The regular grid \
array has dimensions (total_pixels, total_pixels, 2).
Examples
--------
regular_grid_1d = regular_grid_2d_from_shape_pixel_scales_and_origin(shape=(5,5), pixel_scales=(0.5, 0.5), \
origin=(0.0, 0.0))
"""
regular_grid_2d = np.zeros((shape[0], shape[1], 2))
centres_arcsec = centres_from_shape_pixel_scales_and_origin(shape=shape, pixel_scales=pixel_scales, origin=origin)
for y in range(shape[0]):
for x in range(shape[1]):
regular_grid_2d[y, x, 0] = -(y - centres_arcsec[0]) * pixel_scales[0]
regular_grid_2d[y, x, 1] = (x - centres_arcsec[1]) * pixel_scales[1]
return regular_grid_2d
|
def regular_grid_1d_from_shape_pixel_scales_and_origin(shape, pixel_scales, origin=(0.0, 0.0)):
"""Compute the (y,x) arc second coordinates at the centre of every pixel of an array of shape (rows, columns).
Coordinates are defined from the top-left corner, such that the first pixel at location [0, 0] has negative x \
and y values in arc seconds.
The regular grid is returned on an array of shape (total_pixels**2, 2) where the 2D dimension of the original 2D \
array are reduced to one dimension. y coordinates are stored in the 0 index of the second dimension, x coordinates
in the 1 index.
Parameters
----------
shape : (int, int)
The (y,x) shape of the 2D array the regular grid of coordinates is computed for.
pixel_scales : (float, float)
The (y,x) arc-second to pixel scales of the 2D array.
origin : (float, flloat)
The (y,x) origin of the 2D array, which the regular grid is shifted around.
Returns
--------
ndarray
A regular grid of (y,x) arc-second coordinates at the centre of every pixel on a 2D array. The regular grid
array has dimensions (total_pixels**2, 2).
Examples
--------
regular_grid_1d = regular_grid_1d_from_shape_pixel_scales_and_origin(shape=(5,5), pixel_scales=(0.5, 0.5), \
origin=(0.0, 0.0))
"""
regular_grid_1d = np.zeros((shape[0]*shape[1], 2))
centres_arcsec = centres_from_shape_pixel_scales_and_origin(shape=shape, pixel_scales=pixel_scales, origin=origin)
i=0
for y in range(shape[0]):
for x in range(shape[1]):
regular_grid_1d[i, 0] = -(y - centres_arcsec[0]) * pixel_scales[0]
regular_grid_1d[i, 1] = (x - centres_arcsec[1]) * pixel_scales[1]
i += 1
return regular_grid_1d
|
def regular_grid_1d_masked_from_mask_pixel_scales_and_origin(mask, pixel_scales, origin=(0.0, 0.0)):
"""Compute the (y,x) arc second coordinates at the centre of every pixel of a 2D mask array of shape (rows, columns).
Coordinates are defined from the top-left corner, where the first unmasked pixel corresponds to index 0. The pixel \
at the top-left of the array has negative x and y values in arc seconds.
The regular grid is returned on an array of shape (total_unmasked_pixels, 2). y coordinates are stored in the 0 \
index of the second dimension, x coordinates in the 1 index.
Parameters
----------
mask : ndarray
A 2D array of bools, where *False* values mean unmasked and are therefore included as part of the calculated \
regular grid.
pixel_scales : (float, float)
The (y,x) arc-second to pixel scales of the 2D mask array.
origin : (float, flloat)
The (y,x) origin of the 2D array, which the regular grid is shifted around.
Returns
--------
ndarray
A regular grid of (y,x) arc-second coordinates at the centre of every pixel unmasked pixel on the 2D mask \
array. The regular grid array has dimensions (total_unmasked_pixels, 2).
Examples
--------
mask = np.array([[True, False, True],
[False, False, False]
[True, False, True]])
regular_grid_1d = regular_grid_1d_masked_from_mask_pixel_scales_and_origin(mask=mask, pixel_scales=(0.5, 0.5),
origin=(0.0, 0.0))
"""
grid_2d = regular_grid_2d_from_shape_pixel_scales_and_origin(mask.shape, pixel_scales, origin)
total_regular_pixels = mask_util.total_regular_pixels_from_mask(mask)
regular_grid_1d = np.zeros(shape=(total_regular_pixels, 2))
pixel_count = 0
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
if not mask[y, x]:
regular_grid_1d[pixel_count, :] = grid_2d[y, x]
pixel_count += 1
return regular_grid_1d
|
def sub_grid_1d_masked_from_mask_pixel_scales_and_sub_grid_size(mask, pixel_scales, sub_grid_size, origin=(0.0, 0.0)):
""" For the sub-grid, every unmasked pixel of a 2D mask array of shape (rows, columns) is divided into a finer \
uniform grid of shape (sub_grid_size, sub_grid_size). This routine computes the (y,x) arc second coordinates at \
the centre of every sub-pixel defined by this grid.
Coordinates are defined from the top-left corner, where the first unmasked sub-pixel corresponds to index 0. \
Sub-pixels that are part of the same mask array pixel are indexed next to one another, such that the second \
sub-pixel in the first pixel has index 1, its next sub-pixel has index 2, and so forth.
The sub-grid is returned on an array of shape (total_unmasked_pixels*sub_grid_size**2, 2). y coordinates are \
stored in the 0 index of the second dimension, x coordinates in the 1 index.
Parameters
----------
mask : ndarray
A 2D array of bools, where *False* values mean unmasked and are therefore included as part of the calculated \
regular grid.
pixel_scales : (float, float)
The (y,x) arc-second to pixel scales of the 2D mask array.
sub_grid_size : int
The size of the sub-grid that each pixel of the 2D mask array is divided into.
origin : (float, flloat)
The (y,x) origin of the 2D array, which the sub-grid is shifted around.
Returns
--------
ndarray
A sub grid of (y,x) arc-second coordinates at the centre of every pixel unmasked pixel on the 2D mask \
array. The sub grid array has dimensions (total_unmasked_pixels*sub_grid_size**2, 2).
Examples
--------
mask = np.array([[True, False, True],
[False, False, False]
[True, False, True]])
sub_grid_1d = sub_grid_1d_from_mask_pixel_scales_and_origin(mask=mask, pixel_scales=(0.5, 0.5), origin=(0.0, 0.0))
"""
total_sub_pixels = mask_util.total_sub_pixels_from_mask_and_sub_grid_size(mask, sub_grid_size)
sub_grid_1d = np.zeros(shape=(total_sub_pixels, 2))
centres_arcsec = centres_from_shape_pixel_scales_and_origin(shape=mask.shape, pixel_scales=pixel_scales,
origin=origin)
sub_index = 0
y_sub_half = pixel_scales[0] / 2
y_sub_step = pixel_scales[0] / (sub_grid_size + 1)
x_sub_half = pixel_scales[1] / 2
x_sub_step = pixel_scales[1] / (sub_grid_size + 1)
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
if not mask[y, x]:
y_arcsec = (y - centres_arcsec[0]) * pixel_scales[0]
x_arcsec = (x - centres_arcsec[1]) * pixel_scales[1]
for y1 in range(sub_grid_size):
for x1 in range(sub_grid_size):
sub_grid_1d[sub_index, 0] = -(y_arcsec - y_sub_half + (y1 + 1) * y_sub_step)
sub_grid_1d[sub_index, 1] = x_arcsec - x_sub_half + (x1 + 1) * x_sub_step
sub_index += 1
return sub_grid_1d
|
def grid_arcsec_1d_to_grid_pixel_centres_1d(grid_arcsec_1d, shape, pixel_scales, origin=(0.0, 0.0)):
""" Convert a grid of (y,x) arc second coordinates to a grid of (y,x) pixel values. Pixel coordinates are \
returned as integers such that they map directly to the pixel they are contained within.
The pixel coordinate origin is at the top left corner of the grid, such that the pixel [0,0] corresponds to \
higher y arc-second coordinate value and lowest x arc-second coordinate.
The arc-second coordinate grid is defined by the class attribute origin, and coordinates are shifted to this \
origin before computing their 1D grid pixel indexes.
The input and output grids are both of shape (total_pixels, 2).
Parameters
----------
grid_arcsec_1d: ndarray
The grid of (y,x) coordinates in arc seconds which is converted to pixel indexes.
shape : (int, int)
The (y,x) shape of the original 2D array the arc-second coordinates were computed on.
pixel_scales : (float, float)
The (y,x) arc-second to pixel scales of the original 2D array.
origin : (float, flloat)
The (y,x) origin of the grid, which the arc-second grid is shifted
Returns
--------
ndarray
A grid of (y,x) pixel indexes with dimensions (total_pixels, 2).
Examples
--------
grid_arcsec_1d = np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]])
grid_pixels_1d = grid_arcsec_1d_to_grid_pixel_centres_1d(grid_arcsec_1d=grid_arcsec_1d, shape=(2,2),
pixel_scales=(0.5, 0.5), origin=(0.0, 0.0))
"""
grid_pixels_1d = np.zeros((grid_arcsec_1d.shape[0], 2))
centres_arcsec = centres_from_shape_pixel_scales_and_origin(shape=shape, pixel_scales=pixel_scales, origin=origin)
for i in range(grid_arcsec_1d.shape[0]):
grid_pixels_1d[i, 0] = int((-grid_arcsec_1d[i, 0] / pixel_scales[0]) + centres_arcsec[0] + 0.5)
grid_pixels_1d[i, 1] = int((grid_arcsec_1d[i, 1] / pixel_scales[1]) + centres_arcsec[1] + 0.5)
return grid_pixels_1d
|
def grid_arcsec_1d_to_grid_pixel_indexes_1d(grid_arcsec_1d, shape, pixel_scales, origin=(0.0, 0.0)):
""" Convert a grid of (y,x) arc second coordinates to a grid of (y,x) pixel 1D indexes. Pixel coordinates are \
returned as integers such that they are the pixel from the top-left of the 2D grid going rights and then \
downwards.
For example:
The pixel at the top-left, whose 2D index is [0,0], corresponds to 1D index 0.
The fifth pixel on the top row, whose 2D index is [0,5], corresponds to 1D index 4.
The first pixel on the second row, whose 2D index is [0,1], has 1D index 10 if a row has 10 pixels.
The arc-second coordinate grid is defined by the class attribute origin, and coordinates are shifted to this \
origin before computing their 1D grid pixel indexes.
The input and output grids are both of shape (total_pixels, 2).
Parameters
----------
grid_arcsec_1d: ndarray
The grid of (y,x) coordinates in arc seconds which is converted to 1D pixel indexes.
shape : (int, int)
The (y,x) shape of the original 2D array the arc-second coordinates were computed on.
pixel_scales : (float, float)
The (y,x) arc-second to pixel scales of the original 2D array.
origin : (float, flloat)
The (y,x) origin of the grid, which the arc-second grid is shifted.
Returns
--------
ndarray
A grid of 1d pixel indexes with dimensions (total_pixels, 2).
Examples
--------
grid_arcsec_1d = np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]])
grid_pixels_1d = grid_arcsec_1d_to_grid_pixel_indexes_1d(grid_arcsec_1d=grid_arcsec_1d, shape=(2,2),
pixel_scales=(0.5, 0.5), origin=(0.0, 0.0))
"""
grid_pixels_1d = grid_arcsec_1d_to_grid_pixel_centres_1d(grid_arcsec_1d=grid_arcsec_1d, shape=shape,
pixel_scales=pixel_scales, origin=origin)
grid_pixel_indexes_1d = np.zeros(grid_pixels_1d.shape[0])
for i in range(grid_pixels_1d.shape[0]):
grid_pixel_indexes_1d[i] = int(grid_pixels_1d[i,0] * shape[1] + grid_pixels_1d[i,1])
return grid_pixel_indexes_1d
|
def grid_pixels_1d_to_grid_arcsec_1d(grid_pixels_1d, shape, pixel_scales, origin=(0.0, 0.0)):
""" Convert a grid of (y,x) pixel coordinates to a grid of (y,x) arc second values.
The pixel coordinate origin is at the top left corner of the grid, such that the pixel [0,0] corresponds to \
higher y arc-second coordinate value and lowest x arc-second coordinate.
The arc-second coordinate origin is defined by the class attribute origin, and coordinates are shifted to this \
origin after computing their values from the 1D grid pixel indexes.
The input and output grids are both of shape (total_pixels, 2).
Parameters
----------
grid_pixels_1d: ndarray
The grid of (y,x) coordinates in pixel values which is converted to arc-second coordinates.
shape : (int, int)
The (y,x) shape of the original 2D array the arc-second coordinates were computed on.
pixel_scales : (float, float)
The (y,x) arc-second to pixel scales of the original 2D array.
origin : (float, flloat)
The (y,x) origin of the grid, which the arc-second grid is shifted.
Returns
--------
ndarray
A grid of 1d arc-second coordinates with dimensions (total_pixels, 2).
Examples
--------
grid_pixels_1d = np.array([[0,0], [0,1], [1,0], [1,1])
grid_pixels_1d = grid_pixels_1d_to_grid_arcsec_1d(grid_pixels_1d=grid_pixels_1d, shape=(2,2),
pixel_scales=(0.5, 0.5), origin=(0.0, 0.0))
"""
grid_arcsec_1d = np.zeros((grid_pixels_1d.shape[0], 2))
centres_arcsec = centres_from_shape_pixel_scales_and_origin(shape=shape, pixel_scales=pixel_scales, origin=origin)
for i in range(grid_arcsec_1d.shape[0]):
grid_arcsec_1d[i, 0] = -(grid_pixels_1d[i, 0] - centres_arcsec[0] - 0.5) * pixel_scales[0]
grid_arcsec_1d[i, 1] = (grid_pixels_1d[i, 1] - centres_arcsec[1] - 0.5) * pixel_scales[1]
return grid_arcsec_1d
|
def grid_arcsec_2d_to_grid_pixel_centres_2d(grid_arcsec_2d, shape, pixel_scales, origin=(0.0, 0.0)):
""" Convert a grid of (y,x) arc second coordinates to a grid of (y,x) pixel values. Pixel coordinates are \
returned as integers such that they map directly to the pixel they are contained within.
The pixel coordinate origin is at the top left corner of the grid, such that the pixel [0,0] corresponds to \
higher y arc-second coordinate value and lowest x arc-second coordinate.
The arc-second coordinate grid is defined by the class attribute origin, and coordinates are shifted to this \
origin before computing their 1D grid pixel indexes.
The input and output grids are both of shape (total_pixels, 2).
Parameters
----------
grid_arcsec_1d: ndarray
The grid of (y,x) coordinates in arc seconds which is converted to pixel indexes.
shape : (int, int)
The (y,x) shape of the original 2D array the arc-second coordinates were computed on.
pixel_scales : (float, float)
The (y,x) arc-second to pixel scales of the original 2D array.
origin : (float, flloat)
The (y,x) origin of the grid, which the arc-second grid is shifted
Returns
--------
ndarray
A grid of (y,x) pixel indexes with dimensions (total_pixels, 2).
Examples
--------
grid_arcsec_1d = np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]])
grid_pixels_1d = grid_arcsec_1d_to_grid_pixel_centres_1d(grid_arcsec_1d=grid_arcsec_1d, shape=(2,2),
pixel_scales=(0.5, 0.5), origin=(0.0, 0.0))
"""
grid_pixels_2d = np.zeros((grid_arcsec_2d.shape[0], grid_arcsec_2d.shape[1], 2))
centres_arcsec = centres_from_shape_pixel_scales_and_origin(shape=shape, pixel_scales=pixel_scales, origin=origin)
for y in range(grid_arcsec_2d.shape[0]):
for x in range(grid_arcsec_2d.shape[1]):
grid_pixels_2d[y, x, 0] = int((-grid_arcsec_2d[y, x, 0] / pixel_scales[0]) + centres_arcsec[0] + 0.5)
grid_pixels_2d[y, x, 1] = int((grid_arcsec_2d[y, x, 1] / pixel_scales[1]) + centres_arcsec[1] + 0.5)
return grid_pixels_2d
|
def setup_random_seed(seed):
"""Setup the random seed. If the input seed is -1, the code will use a random seed for every run. If it is \
positive, that seed is used for all runs, thereby giving reproducible results.
Parameters
----------
seed : int
The seed of the random number generator.
"""
if seed == -1:
seed = np.random.randint(0,
int(1e9)) # Use one seed, so all regions have identical column non-uniformity.
np.random.seed(seed)
|
def generate_poisson_noise(image, exposure_time_map, seed=-1):
"""
Generate a two-dimensional poisson noise_maps-mappers from an image.
Values are computed from a Poisson distribution using the image's input values in units of counts.
Parameters
----------
image : ndarray
The 2D image, whose values in counts are used to draw Poisson noise_maps values.
exposure_time_map : Union(ndarray, int)
2D array of the exposure time in each pixel used to convert to / from counts and electrons per second.
seed : int
The seed of the random number generator, used for the random noise_maps maps.
Returns
-------
poisson_noise_map: ndarray
An array describing simulated poisson noise_maps
"""
setup_random_seed(seed)
image_counts = np.multiply(image, exposure_time_map)
return image - np.divide(np.random.poisson(image_counts, image.shape), exposure_time_map)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.