def chisquare(observe, expect, error, ddof, verbose=True):

chisq = <NUM_LIT:0><EOL>error   = error.flatten()<EOL>observe = observe.flatten()<EOL>expect  = expect.flatten()<EOL>for i, el in enumerate(observe):<EOL><INDENT>chisq = chisq + _np.power((el - expect[i]) / error[i], <NUM_LIT:2>)<EOL><DEDENT>red_chisq = chisq / (len(observe) - ddof)<EOL>if verbose:<EOL><INDENT>print('<STR_LIT>'.format(red_chisq))<EOL><DEDENT>return red_chisq<EOL>

Finds the reduced chi square difference of *observe* and *expect* with a given *error* and *ddof* degrees of freedom.

*verbose* flag determines if the reduced chi square is printed to the terminal.


return self._popt<EOL>

The fit parameters for the fit function.


return self._pcov<EOL>


return self._chisq_red<EOL>


return self._y_unweighted<EOL>

The :math:`y` of the problem :math:`X_{ij} \\beta_{i} = y_j`. Setting this attribute forces a recalculation.


return self._y_error<EOL>

The measured error of :math:`y` of the problem :math:`X_{ij} \\beta_{i} = y_j`. Setting this attribute forces a recalculation.


return self._X_unweighted<EOL>

The :math:`X`. Setting this attribute forces a recalculation.


if self._X is None:<EOL><INDENT>X = _copy.deepcopy(self.X_unweighted)<EOL>for i, el in enumerate(X):<EOL><INDENT>X[i, :] = el/self.y_error[i]<EOL><DEDENT>self._X = X<EOL><DEDENT>return self._X<EOL>

The :math:`X` weighted properly by the errors from *y_error*


if self._y is None:<EOL><INDENT>self._y = self.y_unweighted/self.y_error<EOL><DEDENT>return self._y<EOL>


if self._y_fit is None:<EOL><INDENT>self._y_fit = _np.dot(self.X_unweighted, self.beta)<EOL><DEDENT>return self._y_fit<EOL>

Using the result of the linear least squares, the result of :math:`X_{ij}\\beta_i`


if self._beta is None:<EOL><INDENT>self._beta = _np.dot(_np.linalg.pinv(self.X) , self.y)<EOL><DEDENT>return self._beta<EOL>

The result :math:`\\beta` of the linear least squares


if self._covar is None:<EOL><INDENT>self._covar = _np.linalg.inv(_np.dot(_np.transpose(self.X), self.X))<EOL><DEDENT>return self._covar<EOL>

The covariance matrix for the result :math:`\\beta`


if self._chisq_red is None:<EOL><INDENT>self._chisq_red = chisquare(self.y_unweighted.transpose(), _np.dot(self.X_unweighted, self.beta), self.y_error, ddof=<NUM_LIT:3>, verbose=False)<EOL><DEDENT>return self._chisq_red<EOL>

The reduced chi-square of the linear least squares


def fft(values, freq=None, timestamps=None, fill_missing=False):

<EOL>if freq is None:<EOL><INDENT>from .. import qt<EOL>freq = qt.getDouble(title='<STR_LIT>', text='<STR_LIT>', min=<NUM_LIT:0>, decimals=<NUM_LIT:2>, value=<NUM_LIT:1.0>)<EOL>freq = freq.input<EOL><DEDENT>if fill_missing:<EOL><INDENT>(t_x, x_filled) = fill_missing_timestamps(timestamps, values)<EOL><DEDENT>else:<EOL><INDENT>x_filled = values<EOL><DEDENT>num_samples = _np.size(x_filled)<EOL>xfft = _sp.fftpack.rfft(x_filled)<EOL>factor = freq/num_samples<EOL>num_fft = _np.size(xfft)<EOL>f = factor * _np.linspace(<NUM_LIT:1>, num_fft, num_fft)<EOL>xpow = _np.abs(xfft*_np.conj(xfft))<EOL>xpow = xpow[<NUM_LIT:1>:]<EOL>f = f[<NUM_LIT:1>:]<EOL>return (f, xpow)<EOL>

Adds options to :func:`scipy.fftpack.rfft`:

* *freq* is the frequency the samples were taken at
* *timestamps* is the time the samples were taken, to help with filling in missing data if *fill_missing* is true


return _sltr.GeV2gamma(self.E)<EOL>


return self.emit * self.gamma<EOL>

Normalized emittance of beam :math:`\\epsilon_n = \\gamma\\epsilon`


return self._emit<EOL>

Emittance of the beam, :math:`\\epsilon = \\sqrt{ \\langle x^2 \\rangle \\langle {x'}^2 \\rangle - \\langle x x' \\rangle^2 }`


return _np.power(<NUM_LIT:2>*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.plasma.n_p * _np.power(_spc.elementary_charge, <NUM_LIT:2>)) , <NUM_LIT>) * _np.sqrt(self.emit)<EOL>

Spot size of matched beam :math:`\\left( \\frac{2 E \\varepsilon_0 }{ n_p e^2 } \\right)^{1/4} \\sqrt{\\epsilon}`


return <NUM_LIT:1.0> / _np.sqrt(self.plasma.k_ion(E))<EOL>


return _np.sqrt(self.emit/self.beta(self.E))<EOL>


return self.emit * self.gamma<EOL>

Specified beam emittance :math:`\\epsilon`.


self.emit = value / self.gamma<EOL>

Specified normalized beam emittance :math:`\\gamma \\epsilon`.


return self.sigma**<NUM_LIT:2>/self.emit<EOL>

The Courant-Snyder parameter :math:`\\beta` that is matched.


return <NUM_LIT:2>*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.beta*_spc.elementary_charge)**<NUM_LIT:2><EOL>


return self.n_p*<NUM_LIT><EOL>


return _Plasma(self.n_p, species=species)<EOL>


return self._k_xi<EOL>


return self._phi<EOL>


return self._beam<EOL>


return self._plasma<EOL>


return self._s<EOL>


return self._x<EOL>


return self._xp<EOL>


return _np.mean(self.x**<NUM_LIT:2>, axis=<NUM_LIT:0>)<EOL>

The beam variance :math:`\\langle x^2 \\rangle`.


return _np.mean(self.xp**<NUM_LIT:2>, axis=<NUM_LIT:0>)<EOL>

The beam divergence :math:`\\langle x'^2 \\rangle`.


return _np.mean(self.x*self.xp, axis=<NUM_LIT:0>)<EOL>

The beam correlation :math:`\\langle x x' \\rangle`.


return _np.sqrt(self.spotsq*self.divsq-self.xxp**<NUM_LIT:2>)<EOL>

The beam emittance :math:`\\langle x x' \\rangle`.


return self.N_e / ( (<NUM_LIT:2>*_np.pi)**(<NUM_LIT:3>/<NUM_LIT:2>) * self.sig_r**<NUM_LIT:2> * self.sig_xi)<EOL>


return <NUM_LIT:2>*_np.sqrt(<NUM_LIT:2>*_np.pi/self.k)*r0<EOL>

The wavelength for large (:math:`r_0 < \\sigma_r`) oscillations.


return r0*_np.cos(_np.sqrt(self.k_small) * x)<EOL>

Approximate trajectory function for small (:math:`r_0 < \\sigma_r`) oscillations.


return r0*_np.cos(x*self.omega_big(r0))<EOL>

Approximate trajectory function for large (:math:`r_0 > \\sigma_r`) oscillations.


try:<EOL><INDENT>return self._k<EOL><DEDENT>except AttributeError:<EOL><INDENT>self._k = e**<NUM_LIT:2> * self.N_e / ( (<NUM_LIT:2>*_np.pi)**(<NUM_LIT:5>/<NUM_LIT:2>) * e0 * self.m * c**<NUM_LIT:2> * self.sig_xi)<EOL>return self._k<EOL><DEDENT>

Driving force term: :math:`r'' = -k \\left( \\frac{1-e^{-r^2/2{\\sigma_r}^2}}{r} \\right)`


return self.k / (<NUM_LIT:2>*self.sig_r**<NUM_LIT:2>)<EOL>

Small-angle driving force term: :math:`r'' = -k_{small} r`.

Note: :math:`k_{small} = \\frac{k}{2{\\sigma_r^2}}`


return self._sig_r<EOL>


return self._species<EOL>

The species of gas used (see :class:`periodictable.core.Element`).

For instance:

    >>> periodictable.hydrogen


return self._dims<EOL>


return <NUM_LIT:2>*_np.pi/_np.sqrt(self.k_small)<EOL>

The wavelength for small (:math:`r_0 < \\sigma_r`) oscillations.


return amu * self.species.mass<EOL>


return self.species.mass<EOL>


return self._N_e<EOL>


return self._sig_xi<EOL>

Longitudinal R.M.S. width :math:`\\sigma_\\xi`.


y1_0 = q0<EOL>y0_0 = <NUM_LIT:0><EOL>y0   = [y0_0, y1_0]<EOL>y = _sp.integrate.odeint(self._func, y0, x, Dfun=self._gradient, rtol=self.rtol, atol=self.atol)<EOL>return y[:, <NUM_LIT:1>]<EOL>

Numerically solved trajectory function for initial conditons :math:`q(0) = q_0` and :math:`q'(0) = 0`.


return self._nb0<EOL>


return self._E<EOL>


return self._dE<EOL>


return self._emit<EOL>


return self._emit*_sltr.GeV2gamma(self.E)<EOL>

Normalized beam emittance :math:`\\gamma \\epsilon`.


return self._s_r<EOL>


self._sx   = sx<EOL>self._sxp  = sxp<EOL>self._sxxp = sxxp<EOL>emit = _np.sqrt(sx**<NUM_LIT:2> * sxp**<NUM_LIT:2> - sxxp**<NUM_LIT:2>)<EOL>self._store_emit(emit=emit)<EOL>

Sets the beam moments directly.

Parameters
----------
sx : float
    Beam moment where :math:`\\text{sx}^2 = \\langle x^2 \\rangle`.
sxp : float
    Beam moment where :math:`\\text{sxp}^2 = \\langle x'^2 \\rangle`.
sxxp : float
    Beam moment where :math:`\\text{sxxp} = \\langle x x' \\rangle`.


return self._sx<EOL>

Beam moment where :math:`\\text{sx}^2 = \\langle x^2 \\rangle`.


return self._sxp<EOL>

Beam moment where :math:`\\text{sxp}^2 = \\langle x'^2 \\rangle`.


return self._sxxp<EOL>

Beam moment where :math:`\\text{sxxp} = \\langle x x' \\rangle`.


def set_Courant_Snyder(self, beta, alpha, emit=None, emit_n=None):

self._store_emit(emit=emit, emit_n=emit_n)<EOL>self._sx   = _np.sqrt(beta*self.emit)<EOL>self._sxp  = _np.sqrt((<NUM_LIT:1>+alpha**<NUM_LIT:2>)/beta*self.emit)<EOL>self._sxxp = -alpha*self.emit<EOL>

Sets the beam moments indirectly using Courant-Snyder parameters.

Parameters
----------
beta : float
    Courant-Snyder parameter :math:`\\beta`.
alpha : float
    Courant-Snyder parameter :math:`\\alpha`.
emit : float
    Beam emittance :math:`\\epsilon`.
emit_n : float
    Normalized beam emittance :math:`\\gamma \\epsilon`.


beta = _np.sqrt(self.sx)/self.emit<EOL>return beta<EOL>


alpha = -self.sxxp/self.emit<EOL>return alpha<EOL>


return <NUM_LIT:4>*_np.sqrt(<NUM_LIT:2>*y0/self.k)<EOL>


return self._sig_x<EOL>


return self._sig_y<EOL>


return self.N_e / (<NUM_LIT:4>*_np.sqrt(<NUM_LIT:3>) * _np.pi * self.sig_x * self.sig_y * self.sig_xi)<EOL>


try:<EOL><INDENT>return self._k<EOL><DEDENT>except AttributeError:<EOL><INDENT>self._k = _np.sqrt(_np.pi/<NUM_LIT:8>) * e**<NUM_LIT:2> * self.nb0 * self.sig_y / ( e0 * self.m * c**<NUM_LIT:2>)<EOL>return self._k<EOL><DEDENT>


return self.k * _np.sqrt(<NUM_LIT:2>/_np.pi) / self.sig_y<EOL>


return self._species<EOL>


return self._species.mass * _spc.m_u<EOL>


return self.m * _spc.c**<NUM_LIT:2><EOL>


return self._n_p<EOL>


return _np.sqrt(self.n_p * _np.power(_spc.e, <NUM_LIT:2>) / (_spc.m_e * _spc.epsilon_0))<EOL>

Plasma frequency :math:`\\omega_p` for given plasma density


return self.n_p * _np.power(_spc.e, <NUM_LIT:2>) / (<NUM_LIT:2>*_sltr.GeV2joule(E) * _spc.epsilon_0)<EOL>

Geometric focusing force due to ion column for given plasma density as a function of *E*


return self.n_p * <NUM_LIT><EOL>


return self._sig_xi<EOL>

Std. dev. of :math:`\\xi`: :math:`\\sigma_\\xi`.


return self._xi<EOL>


return self._mean<EOL>


return self._cov<EOL>


return self._nparts<EOL>


return self._x<EOL>


return self._xp<EOL>


return self._delta<EOL>


return self._emit<EOL>


return self._E<EOL>


return self._sig_delta<EOL>

Beam energy spread :math:`\\sigma_\\delta`.


return self._beta<EOL>


return self._alpha<EOL>


return self._step<EOL>


def githubtunnel(user1, server1, user2, server2, port, verbose, stanford=False):

if stanford:<EOL><INDENT>port_shift = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>port_shift = <NUM_LIT:0><EOL><DEDENT>command1 = '<STR_LIT>'.format(port-<NUM_LIT:1>-port_shift, server2, user1, server1)<EOL>command2 = '<STR_LIT>'.format(port-port_shift, port-port_shift-<NUM_LIT:1>, user2)<EOL>command3 = '<STR_LIT>'.format(port, port-<NUM_LIT:1>, user2)<EOL>if verbose:<EOL><INDENT>print(command1)<EOL>if stanford:<EOL><INDENT>print(command2)<EOL><DEDENT>print(command3)<EOL><DEDENT>try:<EOL><INDENT>call(shlex.split(command1))<EOL>if stanford:<EOL><INDENT>call(shlex.split(command2))<EOL><DEDENT>call(shlex.split(command3))<EOL><DEDENT>except:<EOL><INDENT>print('<STR_LIT>')<EOL>pass<EOL><DEDENT>

Opens a nested tunnel, first to *user1*@*server1*, then to *user2*@*server2*, for accessing on *port*.

If *verbose* is true, prints various ssh commands.

If *stanford* is true, shifts ports up by 1.

Attempts to get *user1*, *user2* from environment variable ``USER_NAME`` if called from the command line.


command = '<STR_LIT>'.format(file_in, file_out)<EOL>_subprocess.call(_shlex.split(command))<EOL>

Uses `ImageMagick <http://www.imagemagick.org/>`_ to convert an input *file_in* pdf to a *file_out* png. (Untested with other formats.)

Parameters
----------

file_in : str
    The path to the pdf file to be converted.
file_out : str
    The path to the png file to be written.


<EOL>bdes        = _np.float_(bdes)<EOL>quad_length = _np.float_(quad_length)<EOL>energy      = _np.float_(energy)<EOL>Brho = energy/_np.float_(<NUM_LIT>)<EOL>K = bdes/(Brho*quad_length)<EOL>logger.log(level=loggerlevel, msg='<STR_LIT>'.format(<EOL>bdes        = bdes        ,<EOL>quad_length = quad_length ,<EOL>energy      = energy      ,<EOL>K           = K<EOL>)<EOL>)<EOL>return K<EOL>

Converts a quadrupole :math:`B_des` into a geometric focusing strength :math:`K`.

Parameters
----------

bdes : float
    The magnet value of :math:`B_des`.
quad_length : float
    The length of the quadrupole in meters.
energy : float
    The design energy of the beam in GeV.

Returns
-------
K : float
    The geometric focusing strength :math:`K`.


<EOL>K           = _np.float_(K)<EOL>quad_length = _np.float_(quad_length)<EOL>energy      = _np.float_(energy)<EOL>Brho = energy/_np.float_(<NUM_LIT>)<EOL>BDES = K*Brho*quad_length<EOL>logger.log(level=loggerlevel, msg='<STR_LIT>'.format(<EOL>bdes        = BDES        ,<EOL>quad_length = quad_length ,<EOL>energy      = energy      ,<EOL>K           = K<EOL>)<EOL>)<EOL>return BDES<EOL>

Returns the BDES for a quadrupole with geometric strength *K* and length *quad_length* for a beam with a given *energy*.
Converts a geometric focusing strength :math:`K` into a quadrupole :math:`B_des`.

Parameters
----------
K : float
    The geometric focusing strength :math:`K`.
quad_length : float
    The length of the quadrupole in meters.
energy : float
    The design energy of the beam in GeV.

Returns
-------
bdes : float
    The magnet value of :math:`B_des`.


def fitimageslice(img, res_x, res_y, xslice, yslice, avg_e_func=None, h5file=None, plot=False):

<EOL>x_start = xslice[<NUM_LIT:0>]<EOL>x_end   = xslice[<NUM_LIT:1>]<EOL>y_start = yslice[<NUM_LIT:0>]<EOL>y_end   = yslice[<NUM_LIT:1>]<EOL>y_low = _np.round(y_start-<NUM_LIT:0.5>) + <NUM_LIT:0.5><EOL>y_high = _np.round(y_end-<NUM_LIT:0.5>) + <NUM_LIT:0.5><EOL>y_px = linspacestep(<NUM_LIT:1>, img.shape[<NUM_LIT:0>])<EOL>y_bool = _np.logical_and(y_low < y_px, y_px < y_high)<EOL>strip = img[y_bool, x_start:x_end]<EOL>histdata = _np.sum(strip, <NUM_LIT:0>)<EOL>xbins = len(histdata)<EOL>x = _np.linspace(<NUM_LIT:1>, xbins, xbins)*res_x<EOL>varbool  = True<EOL>gaussout = _sp.GaussResults(<EOL>x,<EOL>histdata,<EOL>sigma_y    = _np.ones(xbins),<EOL>variance   = varbool,<EOL>background = True,<EOL>p0         = [<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT:0>]<EOL>)<EOL>if avg_e_func is not None:<EOL><INDENT>relcounts = _np.sum(strip, <NUM_LIT:1>) / _np.float(_np.sum(strip))<EOL>Eavg = <NUM_LIT:0><EOL>for i, val in enumerate(linspacestep(y_low, y_high-<NUM_LIT:1>)):<EOL><INDENT>Eavg = Eavg + avg_e_func(val, val+<NUM_LIT:1>, h5file, res_y)*relcounts[i]<EOL><DEDENT>return Eavg, gaussout<EOL><DEDENT>else:<EOL><INDENT>return gaussout<EOL><DEDENT>

Fits a gaussian to a slice of an image *img* specified by *xslice* x-coordinates and *yslice* y-coordinates. *res_x* and *res_y* specify image resolution in x and y. *avg_e_func* is a function that returns the energy of the image as a function of x. It should have the form:

*avg_e_func(x_1, x_2, h5file, res_y)*

Fits a gaussian to a slice of an image.

Parameters
----------

img : array
    Image to be fitted.
res_x : int
    Image resolution in :math:`x`.
res_y : int
    Image resolution in :math:`y`.
xslice : (int, int)
    Slice coordinates in :math:`x`
yslice : (int, int)
    Slice coordinates in :math:`y`
avg_e_func : function
    Of the form *avg_e_func(x_1, x_2, h5file, res_y)*, returns the energy of the image as a function of :math:`x`.
h5file : h5file
    Instance from dataset.
plot : boolean
    Whether to plot or not.


def colorbar(ax, im, fig=None, loc="<STR_LIT:right>", size="<STR_LIT>", pad="<STR_LIT>"):

if fig is None:<EOL><INDENT>fig = ax.get_figure()<EOL><DEDENT>if loc == "<STR_LIT:left>" or loc == "<STR_LIT:right>":<EOL><INDENT>width = fig.get_figwidth()<EOL>new = width * (<NUM_LIT:1> + _pc2f(size) + _pc2f(pad))<EOL>_logger.debug('<STR_LIT>'.format(new))<EOL><DEDENT>elif loc == "<STR_LIT>" or loc == "<STR_LIT>":<EOL><INDENT>height = fig.get_figheight()<EOL>new = height * (<NUM_LIT:1> + _pc2f(size) + _pc2f(pad))<EOL>_logger.debug('<STR_LIT>'.format(new))<EOL><DEDENT>divider = _ag1.make_axes_locatable(ax)<EOL>cax = divider.append_axes(loc, size=size, pad=pad)<EOL>return cax, _plt.colorbar(im, cax=cax)<EOL>

Adds a polite colorbar that steals space so :func:`matplotlib.pyplot.tight_layout` works nicely.

.. versionadded:: 1.3

Parameters
----------

ax : :class:`matplotlib.axis.Axis`
    The axis to plot to.
im : :class:`matplotlib.image.AxesImage`
    The plotted image to use for the colorbar.
fig : :class:`matplotlib.figure.Figure`, optional
    The figure to plot to.
loc : str, optional
    The location to place the axes.
size : str, optional
    The size to allocate for the colorbar.
pad : str, optional
    The amount to pad the colorbar.


<EOL>x_size = array.shape[<NUM_LIT:0>]+<NUM_LIT:1><EOL>y_size = array.shape[<NUM_LIT:1>]+<NUM_LIT:1><EOL>x = _np.empty((x_size, y_size))<EOL>y = _np.empty((x_size, y_size))<EOL>for i in range(x_size):<EOL><INDENT>for j in range(y_size):<EOL><INDENT>x[i, j], y[i, j] = px_to_units(i-<NUM_LIT:0.5>, j-<NUM_LIT:0.5>)<EOL><DEDENT><DEDENT>return x, y<EOL>

Return axes :code:`x, y` for *array* to be used with :func:`matplotlib.pyplot.color`.

*px_to_units* is a function to convert pixels to units. By default, returns pixels.


def hist(x, bins=<NUM_LIT:10>, labels=None, aspect="<STR_LIT>", plot=True, ax=None, range=None):

h, edge = _np.histogram(x, bins=bins, range=range)<EOL>mids = edge + (edge[<NUM_LIT:1>]-edge[<NUM_LIT:0>])/<NUM_LIT:2><EOL>mids = mids[:-<NUM_LIT:1>]<EOL>if plot:<EOL><INDENT>if ax is None:<EOL><INDENT>_plt.hist(x, bins=bins, range=range)<EOL><DEDENT>else:<EOL><INDENT>ax.hist(x, bins=bins, range=range)<EOL><DEDENT>if labels is not None:<EOL><INDENT>_addlabel(labels[<NUM_LIT:0>], labels[<NUM_LIT:1>], labels[<NUM_LIT:2>])<EOL><DEDENT><DEDENT>return h, mids<EOL>

Creates a histogram of data *x* with a *bins*, *labels* = :code:`[title, xlabel, ylabel]`.


if ax is None:<EOL><INDENT>fig, ax = _setup_axes()<EOL><DEDENT>pl = ax.plot(*args, **kwargs)<EOL>if _np.shape(args)[<NUM_LIT:0>] > <NUM_LIT:1>:<EOL><INDENT>if type(args[<NUM_LIT:1>]) is not str:<EOL><INDENT>min_x = min(args[<NUM_LIT:0>])<EOL>max_x = max(args[<NUM_LIT:0>])<EOL>ax.set_xlim((min_x, max_x))<EOL><DEDENT><DEDENT>return pl<EOL>

Plots but automatically resizes x axis.

.. versionadded:: 1.4

Parameters
----------
args
    Passed on to :meth:`matplotlib.axis.Axis.plot`.
ax : :class:`matplotlib.axis.Axis`, optional
    The axis to plot to.
kwargs
    Passed on to :meth:`matplotlib.axis.Axis.plot`.


return self._AxesImage<EOL>

The :class:`matplotlib.image.AxesImage` from :meth:`matplotlib.axes.Axes.imshow`.


return self._ax_img<EOL>

The :class:`matplotlib.axes.Axes` used for :meth:`matplotlib.axes.Axes.imshow`.


return _np.max(self.image)<EOL>


return _np.min(self.image)<EOL>


return self.minslider.val<EOL>


return self.maxslider.val<EOL>


return self._image<EOL>


figs = plt.get_fignums()<EOL>x       = <NUM_LIT:0><EOL>y       = <NUM_LIT:0><EOL>toppad  = <NUM_LIT><EOL>size = np.array([<NUM_LIT:0>, <NUM_LIT:0>])<EOL>if ( len(figs) != <NUM_LIT:0> ):<EOL><INDENT>fig     = plt.figure(figs[<NUM_LIT:0>])<EOL>screen  = fig.canvas.window.get_screen()<EOL>screenx = screen.get_monitor_geometry(screen.get_primary_monitor())<EOL>screenx = screenx[<NUM_LIT:2>]<EOL>fig = plt.figure(figs[<NUM_LIT:0>])<EOL>fig.canvas.manager.window.move(x, y)<EOL>maxy = np.array(fig.canvas.manager.window.get_position())[<NUM_LIT:1>]<EOL>size = np.array(fig.canvas.manager.window.get_size())<EOL>y    = maxy<EOL>x += size[<NUM_LIT:0>]+<NUM_LIT:1><EOL>for fig in figs[<NUM_LIT:1>:]:<EOL><INDENT>fig  = plt.figure(fig)<EOL>size = np.array(fig.canvas.manager.window.get_size())<EOL>if ( x+size[<NUM_LIT:0>] > screenx ):<EOL><INDENT>x    = <NUM_LIT:0><EOL>y    = maxy<EOL>maxy = y+size[<NUM_LIT:1>]+toppad<EOL><DEDENT>else:<EOL><INDENT>maxy = max(maxy, y+size[<NUM_LIT:1>]+toppad)<EOL><DEDENT>fig.canvas.manager.window.move(x, y)<EOL>x += size[<NUM_LIT:0>] + <NUM_LIT:1><EOL><DEDENT><DEDENT>


return self._num_imgs<EOL>


return self._AxesImage<EOL>


return self._ax_img<EOL>


if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>imgmax = _np.max(self.images[<NUM_LIT:0>])<EOL>for img in self.images:<EOL><INDENT>imax = _np.max(img)<EOL>if imax > imgmax:<EOL><INDENT>imgmax = imax<EOL><DEDENT><DEDENT>self._imgmax = imgmax<EOL><DEDENT>return self._imgmax<EOL>


if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>imgmin = _np.min(self.images[<NUM_LIT:0>])<EOL>for img in self.images:<EOL><INDENT>imin = _np.min(img)<EOL>if imin > imgmin:<EOL><INDENT>imgmin = imin<EOL><DEDENT><DEDENT>self._imgmin = imgmin<EOL><DEDENT>return _np.min(self.image)<EOL>


return self._images<EOL>


return self._images[self._image_ind]<EOL>


return _np.dot(image, [<NUM_LIT>, <NUM_LIT>, <NUM_LIT>])<EOL>


def NonUniformImage(x, y, z, ax=None, fig=None, cmap=None, alpha=None, scalex=True, scaley=True, add_cbar=True, **kwargs):

if ax is None and fig is None:<EOL><INDENT>fig, ax = _setup_axes()<EOL><DEDENT>elif ax is None:<EOL><INDENT>ax = fig.gca()<EOL><DEDENT>elif fig is None:<EOL><INDENT>fig = ax.get_figure()<EOL><DEDENT>norm = kwargs.get('<STR_LIT>', None)<EOL>im = _mplim.NonUniformImage(ax, **kwargs)<EOL>vmin = kwargs.pop('<STR_LIT>', _np.min(z))<EOL>vmax = kwargs.pop('<STR_LIT>', _np.max(z))<EOL>if cmap is not None:<EOL><INDENT>im.set_cmap(cmap)<EOL><DEDENT>m = _cm.ScalarMappable(cmap=im.get_cmap(), norm=norm)<EOL>m.set_array(z)<EOL>if add_cbar:<EOL><INDENT>cax, cb = _cb(ax=ax, im=m, fig=fig)<EOL><DEDENT>if alpha is not None:<EOL><INDENT>im.set_alpha(alpha)<EOL><DEDENT>im.set_data(x, y, z)<EOL>ax.images.append(im)<EOL>if scalex:<EOL><INDENT>xmin = min(x)<EOL>xmax = max(x)<EOL>ax.set_xlim(xmin, xmax)<EOL><DEDENT>if scaley:<EOL><INDENT>ymin = min(y)<EOL>ymax = max(y)<EOL>ax.set_ylim(ymin, ymax)<EOL><DEDENT>return _SI(im=im, cb=cb, cax=cax)<EOL>

Used to plot a set of coordinates.

Parameters
----------
x, y : :class:`numpy.ndarray`
    1-D ndarrays of lengths N and M, respectively, specifying pixel centers
z : :class:`numpy.ndarray`
    An (M, N) ndarray or masked array of values to be colormapped, or a (M, N, 3) RGB array, or a (M, N, 4) RGBA array.
ax : :class:`matplotlib.axes.Axes`, optional
    The axis to plot to.
fig : :class:`matplotlib.figure.Figure`, optional
    The figure to plot to.
cmap : :class:`matplotlib.colors.Colormap`, optional
    The colormap to use.
alpha : float, optional
    The transparency to use.
scalex : bool, optional
    To set the x limits to available data
scaley : bool, optional
    To set the y limits to available data
add_cbar : bool, optional
    Whether ot add a colorbar or not.

Returns
-------
img : :class:`matplotlib.image.NonUniformImage`
    Object representing the :class:`matplotlib.image.NonUniformImage`.


ax = fig.gca()<EOL>alim = list(ax.axis())<EOL>if alim[<NUM_LIT:3>] < alim[<NUM_LIT:2>]:<EOL><INDENT>temp    = alim[<NUM_LIT:2>]<EOL>alim[<NUM_LIT:2>] = alim[<NUM_LIT:3>]<EOL>alim[<NUM_LIT:3>] = temp<EOL>ax.axis(alim)<EOL><DEDENT>ax.set_aspect(aspect)<EOL>fig.show()<EOL>

Shows a figure with a typical orientation so that x and y axes are set up as expected.


def setup_figure(rows=<NUM_LIT:1>, cols=<NUM_LIT:1>, **kwargs):

fig = _plt.figure(**kwargs)<EOL>gs = _gridspec.GridSpec(rows, cols)<EOL>return fig, gs<EOL>

Sets up a figure with a number of rows (*rows*) and columns (*cols*), *\*\*kwargs* passes through to :class:`matplotlib.figure.Figure`.

.. versionchanged:: 1.3
   Supports *\*\*kwargs* pass-through to :class:`matplotlib.figure.Figure`.

.. versionchanged:: 1.2
   Changed *gridspec_x* to *rows*, *gridspec_y* to *cols*, added *figsize* control.

Parameters
----------

rows : int
    Number of rows to create.
cols : int
    Number of columns to create.

Returns
-------

fig : :class:`matplotlib.figure.Figure`
    The figure.
gs : :class:`matplotlib.gridspec.GridSpec`
    Instance with *gridspec_x* rows and *gridspec_y* columns


def imshow(X, ax=None, add_cbar=True, rescale_fig=True, **kwargs):

return _plot_array(X, plottype=_IMSHOW, ax=ax, add_cbar=add_cbar, rescale_fig=rescale_fig, **kwargs)<EOL>

Plots an array *X* such that the first coordinate is the *x* coordinate and the second coordinate is the *y* coordinate, with the origin at the bottom left corner.

Optional argument *ax* allows an existing axes to be used.

*\*\*kwargs* are passed on to :meth:`matplotlib.axes.Axes.imshow`.

.. versionadded:: 1.3

Returns
-------
fig, ax, im :
    if axes aren't specified.
im :
    if axes are specified.


def contour(X, ax=None, add_cbar=True, rescale_fig=True, **kwargs):

return _plot_array(X, plottype=_CONTOUR, ax=ax, add_cbar=add_cbar, rescale_fig=rescale_fig, **kwargs)<EOL>

Plots an array *X* such that the first coordinate is the *x* coordinate and the second coordinate is the *y* coordinate, with the origin at the bottom left corner.

Optional argument *ax* allows an existing axes to be used.

*\*\*kwargs* are passed on to :meth:`matplotlib.axes.Axes.contour`.

.. versionadded:: 1.3

Returns
-------
im : :class:`matplotlib.image.AxesImage`.


def quiver(*args, ax=None, rescale_fig=True, **kwargs):

return _plot_array(*args, plottype=_QUIVER, ax=ax, add_cbar=False, rescale_fig=rescale_fig, **kwargs)<EOL>

Plots an array *X* such that the first coordinate is the *x* coordinate and the second coordinate is the *y* coordinate, with the origin at the bottom left corner.

Optional argument *ax* allows an existing axes to be used.

*\*\*kwargs* are passed on to :meth:`matplotlib.axes.Axes.quiver`.

.. versionadded:: 1.3

Returns
-------
im : :class:`matplotlib.image.AxesImage`.


def scaled_figsize(X, figsize=None, h_pad=None, v_pad=None):

if figsize is None:<EOL><INDENT>figsize = _mpl.rcParams['<STR_LIT>']<EOL><DEDENT>width, height = _np.shape(X)<EOL>ratio = width / height<EOL>if ratio > figsize[<NUM_LIT:0>]/figsize[<NUM_LIT:1>]:<EOL><INDENT>figsize[<NUM_LIT:1>] = figsize[<NUM_LIT:0>] / ratio<EOL><DEDENT>else:<EOL><INDENT>figsize[<NUM_LIT:0>] = figsize[<NUM_LIT:1>] * ratio<EOL><DEDENT>return figsize<EOL>

Given an array *X*, determine a good size for the figure to be by shrinking it to fit within *figsize*. If not specified, shrinks to fit the figsize specified by the current :attr:`matplotlib.rcParams`.

.. versionadded:: 1.3


def imshow_batch(images, cbar=True, show=True, pdf=None, figsize=(<NUM_LIT:16>, <NUM_LIT:12>), rows=<NUM_LIT:2>, columns=<NUM_LIT:2>, cmap=None, **kwargs):

<EOL>images = _np.array(images)<EOL>gs = _gridspec.GridSpec(rows, columns)<EOL>num_imgs = images.shape[<NUM_LIT:0>]<EOL>max_ind = num_imgs-<NUM_LIT:1><EOL>per_page = rows*columns<EOL>num_pages = _np.int(_np.ceil(num_imgs/per_page))<EOL>fig_array = _np.empty(shape=num_pages, dtype=object)<EOL>if num_pages > <NUM_LIT:1>:<EOL><INDENT>logger.info('<STR_LIT>')<EOL><DEDENT>if pdf is not None:<EOL><INDENT>f = _PdfPages(pdf)<EOL><DEDENT>for p in range(num_pages):<EOL><INDENT>fig_array[p] = _plt.figure(figsize=figsize)<EOL>pg_max_ind = _np.min( [(p+<NUM_LIT:1>) * per_page - <NUM_LIT:1>, max_ind] )<EOL>num_rows = _np.int(_np.ceil((pg_max_ind+<NUM_LIT:1> - p * per_page) / columns))<EOL>for i in range(num_rows):<EOL><INDENT>i_min_ind = p * per_page + i * columns<EOL>col_max_ind = _np.min([i_min_ind + columns - <NUM_LIT:1>, max_ind])<EOL>for j, image in enumerate(images[i_min_ind:col_max_ind+<NUM_LIT:1>]):<EOL><INDENT>ax = fig_array[p].add_subplot(gs[i, j])<EOL>try:<EOL><INDENT>if _np.issubdtype(image.dtype, _np.integer):<EOL><INDENT>image = _np.array(image, dtype=float)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>plot = ax.imshow(image, **kwargs)<EOL>if cmap is not None:<EOL><INDENT>plot.set_cmap(cmap)<EOL><DEDENT>if cbar:<EOL><INDENT>fig_array[p].colorbar(plot)<EOL><DEDENT><DEDENT><DEDENT>fig_array[p].tight_layout()<EOL>if pdf is not None:<EOL><INDENT>f.savefig(fig_array[p])<EOL><DEDENT>if not show:<EOL><INDENT>_plt.close(fig_array[p])<EOL><DEDENT><DEDENT>if pdf is not None:<EOL><INDENT>f.close()<EOL><DEDENT>return fig_array<EOL>

Plots an array of *images* to a single window of size *figsize* with *rows* and *columns*.

* *cmap*: Specifies color map
* *cbar*: Add color bars
* *show*: If false, dismisses each window after it is created and optionally saved
* *pdf*: Save to a pdf of filename *pdf*
* *\*\*kwargs* passed to :class:`matplotlib.axis.imshow`


<EOL>toplabel = kwargs.pop('<STR_LIT>', None)<EOL>xlabel   = kwargs.pop('<STR_LIT>', None)<EOL>ylabel   = kwargs.pop('<STR_LIT>', None)<EOL>legend   = kwargs.pop('<STR_LIT>', None)<EOL>error    = kwargs.pop('<STR_LIT:error>', None)<EOL>figlabel = kwargs.pop('<STR_LIT>', None)<EOL>fig      = kwargs.pop('<STR_LIT>', None)<EOL>if figlabel is not None:<EOL><INDENT>fig = _figure(figlabel)<EOL><DEDENT>elif fig is None:<EOL><INDENT>try:<EOL><INDENT>fig = _plt.gcf()<EOL><DEDENT>except:<EOL><INDENT>fig = _plt.fig()<EOL><DEDENT><DEDENT>if error is None:<EOL><INDENT>_plt.plot(*args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>_plt.errorbar(*args, **kwargs)<EOL><DEDENT>_addlabel(toplabel, xlabel, ylabel, fig=fig)<EOL>if legend is not None:<EOL><INDENT>_plt.legend(legend)<EOL><DEDENT>return fig<EOL>

Wrapper for matplotlib.pyplot.plot() / errorbar().

Takes options:

* 'error': if true, use :func:`matplotlib.pyplot.errorbar` instead of :func:`matplotlib.pyplot.plot`. *\*args* and *\*\*kwargs* passed through here.
* 'fig': figure to use.
* 'figlabel': figure label.
* 'legend': legend location.
* 'toplabel': top label of plot.
* 'xlabel': x-label of plot.
* 'ylabel': y-label of plot.


fig = _figure(**kwargs)<EOL>if title is not None:<EOL><INDENT>fig.canvas.set_window_title(title)<EOL><DEDENT>return fig<EOL>

Creates a figure with *\*\*kwargs* with a window title *title*.

Returns class :class:`matplotlib.figure.Figure`.


def savefig(filename, path="<STR_LIT>", fig=None, ext='<STR_LIT>', verbose=False, **kwargs):

filename       = os.path.join(path, filename)<EOL>final_filename = '<STR_LIT>'.format(filename, ext).replace("<STR_LIT:U+0020>", "<STR_LIT>").replace("<STR_LIT:\n>", "<STR_LIT>")<EOL>final_filename = os.path.abspath(final_filename)<EOL>final_path = os.path.dirname(final_filename)<EOL>if not os.path.exists(final_path):<EOL><INDENT>os.makedirs(final_path)<EOL><DEDENT>if verbose:<EOL><INDENT>print('<STR_LIT>'.format(final_filename))<EOL><DEDENT>if fig is not None:<EOL><INDENT>fig.savefig(final_filename, bbox_inches='<STR_LIT>', **kwargs)<EOL><DEDENT>else:<EOL><INDENT>plt.savefig(final_filename, bbox_inches='<STR_LIT>', **kwargs)<EOL><DEDENT>

Save the figure *fig* (optional, if not specified, latest figure in focus) to *filename* in the path *path* with extension *ext*.

*\*\*kwargs* is passed to :meth:`matplotlib.figure.Figure.savefig`.


def less_labels(ax, x_fraction=<NUM_LIT:0.5>, y_fraction=<NUM_LIT:0.5>):

nbins = _np.size(ax.get_xticklabels())<EOL>ax.locator_params(nbins=_np.floor(nbins*x_fraction), axis='<STR_LIT:x>')<EOL>nbins = _np.size(ax.get_yticklabels())<EOL>ax.locator_params(nbins=_np.floor(nbins*y_fraction), axis='<STR_LIT:y>')<EOL>

Scale the number of tick labels in x and y by *x_fraction* and *y_fraction* respectively.


return self._parent<EOL>


return self._verbose<EOL>

Determines whether rectangle coordinates are printed to the terminal on selection.


return self._RectangleSelector<EOL>

The instance of :class:`matplotlib.widgets.RectangleSelector`.


return self._ax<EOL>


return self._selfunc<EOL>

A placeholder for the function called on each mouse release.


if self.selfunc is not None:<EOL><INDENT>return self.selfunc(self)<EOL><DEDENT>

The results of :func:`selfunc(instance) <scisalt.matplotlib.RectangleSelector.selfunc>` where *instance* is this class.


if self._eclick is None:<EOL><INDENT>raise IOError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return self._eclick<EOL><DEDENT>

The starting mouse click from :class:`RectangleSelector <scisalt.matplotlib.RectangleSelector.RectangleSelector>`.


if self._erelease is None:<EOL><INDENT>raise IOError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return self._erelease<EOL><DEDENT>

The ending mouse click from :class:`RectangleSelector <scisalt.matplotlib.RectangleSelector.RectangleSelector>`.


return self._x0<EOL>


return self._x1<EOL>


return self._y0<EOL>


return self._y1<EOL>


return [self.x0, self.x1]<EOL>


return [self.y0, self.y1]<EOL>


return self.x1-self.x0<EOL>


return self.y1-self.y0<EOL>


def hist2d(x, y, bins=<NUM_LIT:10>, labels=None, aspect="<STR_LIT>", plot=True, fig=None, ax=None, interpolation='<STR_LIT:none>', cbar=True, **kwargs):

h_range   = kwargs.pop('<STR_LIT>', None)<EOL>h_normed  = kwargs.pop('<STR_LIT>', None)<EOL>h_weights = kwargs.pop('<STR_LIT>', None)<EOL>h, xe, ye = _np.histogram2d(x, y, bins=bins, range=h_range, normed=h_normed, weights=h_weights)<EOL>extent    = [xe[<NUM_LIT:0>], xe[-<NUM_LIT:1>], ye[<NUM_LIT:0>], ye[-<NUM_LIT:1>]]<EOL>if plot:<EOL><INDENT>if ax is None:<EOL><INDENT>if fig is None:<EOL><INDENT>fig = _figure('<STR_LIT>')<EOL><DEDENT>ax = fig.gca()<EOL>ax.clear()<EOL><DEDENT>img = ax.imshow(h.transpose(), extent=extent, interpolation=interpolation, aspect=aspect, **kwargs)<EOL>if cbar:<EOL><INDENT>_colorbar(ax=ax, im=img)<EOL><DEDENT>if labels is not None:<EOL><INDENT>_addlabel(labels[<NUM_LIT:0>], labels[<NUM_LIT:1>], labels[<NUM_LIT:2>])<EOL><DEDENT><DEDENT>return h, extent<EOL>

Creates a 2-D histogram of data *x*, *y* with *bins*, *labels* = :code:`[title, xlabel, ylabel]`, aspect ration *aspect*. Attempts to use axis *ax* first, then the current axis of *fig*, then the last axis, to use an already-created window.

Plotting (*plot*) is on by default, setting false doesn't attempt to create a figure.

*interpolation* sets the interpolation type of :meth:`matplotlib.axis.imshow`.

Returns a handle and extent as :code:`h, extent`


items = ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels())<EOL>for item in items:<EOL><INDENT>item.set_fontsize(fontsize)<EOL><DEDENT>

Change the font size for the title, x and y labels, and x and y tick labels for axis *ax* to *fontsize*.


def setup_axes(rows=<NUM_LIT:1>, cols=<NUM_LIT:1>, figsize=(<NUM_LIT:8>, <NUM_LIT:6>), expand=True, tight_layout=None, **kwargs):

if expand:<EOL><INDENT>figsize = (figsize[<NUM_LIT:0>]*cols, figsize[<NUM_LIT:1>]*rows)<EOL><DEDENT>figargs = {}<EOL>if isinstance(tight_layout, dict):<EOL><INDENT>figargs["<STR_LIT>"] = tight_layout<EOL><DEDENT>elif tight_layout == "<STR_LIT>":<EOL><INDENT>figargs["<STR_LIT>"] = {"<STR_LIT>": (<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT>)}<EOL><DEDENT>dpi = kwargs.pop('<STR_LIT>', None)<EOL>fig, gs = _setup_figure(rows=rows, cols=cols, figsize=figsize, dpi=dpi, **figargs)<EOL>axes = _np.empty(shape=(rows, cols), dtype=object)<EOL>for i in range(rows):<EOL><INDENT>for j in range(cols):<EOL><INDENT>axes[i, j] = fig.add_subplot(gs[i, j], **kwargs)<EOL><DEDENT><DEDENT>if axes.shape == (<NUM_LIT:1>, <NUM_LIT:1>):<EOL><INDENT>return fig, axes[<NUM_LIT:0>, <NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return fig, axes<EOL><DEDENT>

Sets up a figure of size *figsize* with a number of rows (*rows*) and columns (*cols*). \*\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`.

.. versionadded:: 1.2

Parameters
----------

rows : int
    Number of rows to create.
cols : int
    Number of columns to create.
figsize : tuple
    Size of figure to create.
expand : bool
    Make the entire figure with size `figsize`.

Returns
-------

fig : :class:`matplotlib.figure.Figure`
    The figure.
axes : :class:`numpy.ndarray`
    An array of all of the axes. (Unless there's only one axis, in which case it returns an object instance :class:`matplotlib.axis.Axis`.)


xmin = <NUM_LIT:0><EOL>xmax = img.shape[<NUM_LIT:1>]-<NUM_LIT:1><EOL>ymin = <NUM_LIT:0><EOL>ymax = img.shape[<NUM_LIT:0>]-<NUM_LIT:1><EOL>x = _np.linspace(xmin, xmax, img.shape[<NUM_LIT:1>])<EOL>y = _np.linspace(ymin, ymax, img.shape[<NUM_LIT:0>])<EOL>return x, y<EOL>

Returns axes *x, y* for a given image *img* to be used with :func:`scisalt.matplotlib.NonUniformImage`.

Returns
-------
x, y : float, float


def addlabel(ax=None, toplabel=None, xlabel=None, ylabel=None, zlabel=None, clabel=None, cb=None, windowlabel=None, fig=None, axes=None):

if (axes is None) and (ax is not None):<EOL><INDENT>axes = ax<EOL><DEDENT>if (windowlabel is not None) and (fig is not None):<EOL><INDENT>fig.canvas.set_window_title(windowlabel)<EOL><DEDENT>if fig is None:<EOL><INDENT>fig = _plt.gcf()<EOL><DEDENT>if fig is not None and axes is None:<EOL><INDENT>axes = fig.get_axes()<EOL>if axes == []:<EOL><INDENT>logger.error('<STR_LIT>')<EOL><DEDENT><DEDENT>if axes is not None:<EOL><INDENT>if toplabel is not None:<EOL><INDENT>axes.set_title(toplabel)<EOL><DEDENT>if xlabel is not None:<EOL><INDENT>axes.set_xlabel(xlabel)<EOL><DEDENT>if ylabel is not None:<EOL><INDENT>axes.set_ylabel(ylabel)<EOL><DEDENT>if zlabel is not None:<EOL><INDENT>axes.set_zlabel(zlabel)<EOL><DEDENT><DEDENT>if (clabel is not None) or (cb is not None):<EOL><INDENT>if (clabel is not None) and (cb is not None):<EOL><INDENT>cb.set_label(clabel)<EOL><DEDENT>else:<EOL><INDENT>if clabel is None:<EOL><INDENT>logger.error('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>logger.error('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>


return self._sorted_x[<NUM_LIT:0>]<EOL>


return self._sorted_x[<NUM_LIT:1>]<EOL>


return self._sorted_y[<NUM_LIT:0>]<EOL>


return self._sorted_y[<NUM_LIT:1>]<EOL>


def print2elog(author='<STR_LIT>', title='<STR_LIT>', text='<STR_LIT>', link=None, file=None, now=None):

<EOL>if now is None:<EOL><INDENT>now  = _dt.datetime.now()<EOL><DEDENT>fulltime = now.strftime('<STR_LIT>')<EOL>if not ((link is None) ^ (file is None)):<EOL><INDENT>link_copied = _copy_file(link, fulltime)<EOL>file_copied = _copy_file(file, fulltime)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>loader = _jj.PackageLoader('<STR_LIT>', '<STR_LIT>')<EOL>env = _jj.Environment(loader=loader, trim_blocks=True)<EOL>template = env.get_template('<STR_LIT>')<EOL>stream = template.stream(author=author, title=title, text=text, link=link_copied, file=file_copied, now=now)<EOL>with _tempfile.TemporaryDirectory() as dirname:<EOL><INDENT>filename = '<STR_LIT>'.format(fulltime)<EOL>filepath = _os.path.join(dirname, filename)<EOL>with open(filepath, '<STR_LIT>') as fid:<EOL><INDENT>stream.dump(fid)<EOL><DEDENT>finalpath = _os.path.join(basedir, filename)<EOL>_shutil.copyfile(filepath, finalpath)<EOL><DEDENT>

Prints to the elog.

Parameters
----------

author : str, optional
    Author of the elog.
title : str, optional
    Title of the elog.
link : str, optional
    Path to a thumbnail.
file : str, optional
    Path to a file.
now : :class:`datetime.datetime`
    Time of the elog.


from os import path<EOL>import sys<EOL>try:<EOL><INDENT>base_path = sys._MEIPASS<EOL><DEDENT>except Exception:<EOL><INDENT>base_path = path.dirname(path.abspath(__file__))<EOL><DEDENT>return path.join(base_path, relative_path)<EOL>

Get absolute path to resource, works for dev and for PyInstaller


def addLogbook(self, physDef= "<STR_LIT>", mccDef="<STR_LIT>", initialInstance=False):

if self.logMenuCount < <NUM_LIT:5>:<EOL><INDENT>self.logMenus.append(LogSelectMenu(self.logui.multiLogLayout, initialInstance))<EOL>self.logMenus[-<NUM_LIT:1>].addLogbooks(self.logTypeList[<NUM_LIT:1>], self.physics_programs, physDef)<EOL>self.logMenus[-<NUM_LIT:1>].addLogbooks(self.logTypeList[<NUM_LIT:0>], self.mcc_programs, mccDef)<EOL>self.logMenus[-<NUM_LIT:1>].show()<EOL>self.logMenuCount += <NUM_LIT:1><EOL>if initialInstance:<EOL><INDENT>QObject.connect(self.logMenus[-<NUM_LIT:1>].logButton, SIGNAL("<STR_LIT>"), self.addLogbook)<EOL><DEDENT>else:<EOL><INDENT>from functools import partial<EOL>QObject.connect(self.logMenus[-<NUM_LIT:1>].logButton, SIGNAL("<STR_LIT>"), partial(self.removeLogbook, self.logMenus[-<NUM_LIT:1>]))<EOL><DEDENT><DEDENT>

Add new block of logbook selection windows. Only 5 allowed.


if self.logMenuCount > <NUM_LIT:1> and menu is not None:<EOL><INDENT>menu.removeMenu()<EOL>self.logMenus.remove(menu)<EOL>self.logMenuCount -= <NUM_LIT:1><EOL><DEDENT>


mcclogs = []<EOL>physlogs = []<EOL>for i in range(len(self.logMenus)):<EOL><INDENT>logType = self.logMenus[i].selectedType()<EOL>log = self.logMenus[i].selectedProgram()<EOL>if logType == "<STR_LIT>":<EOL><INDENT>if log not in mcclogs:<EOL><INDENT>mcclogs.append(log)<EOL><DEDENT><DEDENT>elif logType == "<STR_LIT>":<EOL><INDENT>if log not in physlogs:<EOL><INDENT>physlogs.append(log)<EOL><DEDENT><DEDENT><DEDENT>return mcclogs, physlogs<EOL>


from urllib2 import urlopen, URLError, HTTPError<EOL>import json<EOL>isApproved = False<EOL>userName = str(self.logui.userName.text())<EOL>if userName == "<STR_LIT>":<EOL><INDENT>return False  <EOL><DEDENT>if logType == "<STR_LIT>":<EOL><INDENT>networkFault = False<EOL>data = []<EOL>log_url = "<STR_LIT>" + userName<EOL>try:<EOL><INDENT>data = urlopen(log_url, None, <NUM_LIT:5>).read()<EOL>data = json.loads(data)<EOL><DEDENT>except URLError as error:<EOL><INDENT>print("<STR_LIT>" + str(error.reason))<EOL>networkFault = True<EOL><DEDENT>except HTTPError as error:<EOL><INDENT>print("<STR_LIT>" + str(error.reason))<EOL>networkFault = True<EOL><DEDENT>if networkFault:<EOL><INDENT>msgBox = QMessageBox()<EOL>msgBox.setText("<STR_LIT>")<EOL>msgBox.setInformativeText("<STR_LIT>")<EOL>msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)<EOL>msgBox.setDefaultButton(QMessageBox.Ok)<EOL>if msgBox.exec_() == QMessageBox.Ok:<EOL><INDENT>isApproved = True<EOL><DEDENT><DEDENT>if data != [] and (data is not None):<EOL><INDENT>isApproved = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>isApproved = True<EOL><DEDENT>return isApproved<EOL>

Verify enetered user name is on accepted MCC logbook list.


from xml.etree.ElementTree import Element, SubElement, ElementTree<EOL>from datetime import datetime<EOL>curr_time = datetime.now()<EOL>if logType == "<STR_LIT>":<EOL><INDENT>log_entry = Element('<STR_LIT>')<EOL>title     = SubElement(log_entry, '<STR_LIT:title>')<EOL>program   = SubElement(log_entry, '<STR_LIT>')<EOL>timestamp = SubElement(log_entry, '<STR_LIT>')<EOL>priority  = SubElement(log_entry, '<STR_LIT>')<EOL>os_user   = SubElement(log_entry, '<STR_LIT>')<EOL>hostname  = SubElement(log_entry, '<STR_LIT>')<EOL>text      = SubElement(log_entry, '<STR_LIT:text>')<EOL>log_user  = SubElement(log_entry, '<STR_LIT>')<EOL>logbook = []<EOL>for i in range(len(logList)):<EOL><INDENT>logbook.append(SubElement(log_entry, '<STR_LIT>'))<EOL>logbook[i].text = logList[i].lower()<EOL><DEDENT>log_entry.attrib['<STR_LIT:type>'] = "<STR_LIT>"<EOL>program.text = "<STR_LIT>"<EOL>priority.text = "<STR_LIT>"<EOL>os_user.text = "<STR_LIT>"<EOL>hostname.text = "<STR_LIT>"<EOL>text.attrib['<STR_LIT:type>'] = "<STR_LIT>"<EOL>if not self.imagePixmap.isNull():<EOL><INDENT>attachment = SubElement(log_entry, '<STR_LIT>')<EOL>attachment.attrib['<STR_LIT:name>'] = "<STR_LIT>"<EOL>attachment.attrib['<STR_LIT:type>'] = "<STR_LIT>" + self.imageType<EOL>attachment.text = curr_time.strftime("<STR_LIT>") + str(curr_time.microsecond) + "<STR_LIT:.>" + self.imageType<EOL><DEDENT>timestamp.text = curr_time.strftime("<STR_LIT>")<EOL>fileName = "<STR_LIT>" + curr_time.strftime("<STR_LIT>") + str(curr_time.microsecond) + "<STR_LIT>"<EOL><DEDENT>else:  <EOL><INDENT>timeString = curr_time.strftime("<STR_LIT>")<EOL>log_entry = Element(None)<EOL>severity  = SubElement(log_entry, '<STR_LIT>')<EOL>location  = SubElement(log_entry, '<STR_LIT:location>')<EOL>keywords  = SubElement(log_entry, '<STR_LIT>')<EOL>time      = SubElement(log_entry, '<STR_LIT:time>')<EOL>isodate   = SubElement(log_entry, '<STR_LIT>')<EOL>log_user  = SubElement(log_entry, '<STR_LIT>')<EOL>category  = SubElement(log_entry, '<STR_LIT>')<EOL>title     = SubElement(log_entry, '<STR_LIT:title>')<EOL>metainfo  = SubElement(log_entry, '<STR_LIT>')<EOL>if not self.imagePixmap.isNull():<EOL><INDENT>imageFile = SubElement(log_entry, '<STR_LIT>')<EOL>imageFile.text = timeString + "<STR_LIT>" + self.imageType<EOL>thumbnail = SubElement(log_entry, '<STR_LIT:file>')<EOL>thumbnail.text = timeString + "<STR_LIT>"<EOL><DEDENT>text      = SubElement(log_entry, '<STR_LIT:text>')  <EOL>log_entry.attrib['<STR_LIT:type>'] = "<STR_LIT>"<EOL>category.text = "<STR_LIT>"<EOL>location.text = "<STR_LIT>"<EOL>severity.text = "<STR_LIT>"<EOL>keywords.text = "<STR_LIT:none>"<EOL>time.text = curr_time.strftime("<STR_LIT>")<EOL>isodate.text = curr_time.strftime("<STR_LIT>")<EOL>metainfo.text = timeString + "<STR_LIT>"<EOL>fileName = "<STR_LIT>" + metainfo.text<EOL><DEDENT>log_user.text = str(self.logui.userName.text())<EOL>title.text = str(self.logui.titleEntry.text())<EOL>if title.text == "<STR_LIT>":<EOL><INDENT>QMessageBox().warning(self, "<STR_LIT>", "<STR_LIT>")<EOL>return None<EOL><DEDENT>text.text = str(self.logui.textEntry.toPlainText())<EOL>if text.text == "<STR_LIT>":<EOL><INDENT>text.text = "<STR_LIT:U+0020>"<EOL><DEDENT>xmlFile = open(fileName, "<STR_LIT:w>")<EOL>if logType == "<STR_LIT>":<EOL><INDENT>ElementTree(log_entry).write(xmlFile)<EOL><DEDENT>else:<EOL><INDENT>xmlString = self.prettify(log_entry)<EOL>xmlFile.write(xmlString)<EOL><DEDENT>xmlFile.write("<STR_LIT:\n>")  <EOL>xmlFile.close()<EOL>return fileName.rstrip("<STR_LIT>")<EOL>

Create xml file with fields from logbook form.


from xml.etree import ElementTree<EOL>from re import sub<EOL>rawString = ElementTree.tostring(elem, '<STR_LIT:utf-8>')<EOL>parsedString = sub(r'<STR_LIT>', '<STR_LIT:\n>', rawString)  <EOL>return parsedString[<NUM_LIT:1>:]<EOL>


def prepareImages(self, fileName, logType):

import subprocess<EOL>if self.imageType == "<STR_LIT>":<EOL><INDENT>self.imagePixmap.save(fileName + "<STR_LIT>", "<STR_LIT>", -<NUM_LIT:1>)<EOL>if logType == "<STR_LIT>":<EOL><INDENT>makePostScript = "<STR_LIT>" + fileName + "<STR_LIT>" + fileName + "<STR_LIT>"<EOL>process = subprocess.Popen(makePostScript, shell=True)<EOL>process.wait()<EOL>thumbnailPixmap = self.imagePixmap.scaled(<NUM_LIT>, <NUM_LIT>, Qt.KeepAspectRatio)<EOL>thumbnailPixmap.save(fileName + "<STR_LIT>", "<STR_LIT>", -<NUM_LIT:1>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>renameImage = "<STR_LIT>" + self.image + "<STR_LIT:U+0020>" + fileName + "<STR_LIT>"<EOL>process = subprocess.Popen(renameImage, shell=True)<EOL>process.wait()<EOL>if logType == "<STR_LIT>":<EOL><INDENT>thumbnailPixmap = self.imagePixmap.scaled(<NUM_LIT>, <NUM_LIT>, Qt.KeepAspectRatio)<EOL>thumbnailPixmap.save(fileName + "<STR_LIT>", "<STR_LIT>", -<NUM_LIT:1>)<EOL><DEDENT><DEDENT>

Convert supplied QPixmap object to image file.


<EOL>mcclogs, physlogs = self.selectedLogs()<EOL>success = True<EOL>if mcclogs != []:<EOL><INDENT>if not self.acceptedUser("<STR_LIT>"):<EOL><INDENT>QMessageBox().warning(self, "<STR_LIT>", "<STR_LIT>")<EOL>return<EOL><DEDENT>fileName = self.xmlSetup("<STR_LIT>", mcclogs)<EOL>if fileName is None:<EOL><INDENT>return<EOL><DEDENT>if not self.imagePixmap.isNull():<EOL><INDENT>self.prepareImages(fileName, "<STR_LIT>")<EOL><DEDENT>success = self.sendToLogbook(fileName, "<STR_LIT>")<EOL><DEDENT>if physlogs != []:<EOL><INDENT>for i in range(len(physlogs)):<EOL><INDENT>fileName = self.xmlSetup("<STR_LIT>", physlogs[i])<EOL>if fileName is None:<EOL><INDENT>return<EOL><DEDENT>if not self.imagePixmap.isNull():<EOL><INDENT>self.prepareImages(fileName, "<STR_LIT>")<EOL><DEDENT>success_phys = self.sendToLogbook(fileName, "<STR_LIT>", physlogs[i])<EOL>success = success and success_phys<EOL><DEDENT><DEDENT>self.done(success)<EOL>

Process user inputs and subit logbook entry when user clicks Submit button


def sendToLogbook(self, fileName, logType, location=None):

import subprocess<EOL>success = True<EOL>if logType == "<STR_LIT>":<EOL><INDENT>fileString = "<STR_LIT>"<EOL>if not self.imagePixmap.isNull():<EOL><INDENT>fileString = fileName + "<STR_LIT:.>" + self.imageType<EOL><DEDENT>logcmd = "<STR_LIT>" + fileName + "<STR_LIT>" + fileString<EOL>process = subprocess.Popen(logcmd, shell=True)<EOL>process.wait()<EOL>if process.returncode != <NUM_LIT:0>:<EOL><INDENT>success = False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>from shutil import copy<EOL>path = "<STR_LIT>" + location.lower() + "<STR_LIT>"  <EOL>try:<EOL><INDENT>if not self.imagePixmap.isNull():<EOL><INDENT>copy(fileName + "<STR_LIT>", path)<EOL>if self.imageType == "<STR_LIT>":<EOL><INDENT>copy(fileName + "<STR_LIT>", path)<EOL><DEDENT>else:<EOL><INDENT>copy(fileName + "<STR_LIT:.>" + self.imageType, path)<EOL><DEDENT><DEDENT>copy(fileName + "<STR_LIT>", path)<EOL><DEDENT>except IOError as error:<EOL><INDENT>print(error)<EOL>success = False<EOL><DEDENT><DEDENT>return success<EOL>

Process log information and push to selected logbooks.


self.logui.titleEntry.clear()<EOL>self.logui.textEntry.clear()<EOL>while self.logMenuCount > <NUM_LIT:1>:<EOL><INDENT>self.removeLogbook(self.logMenus[-<NUM_LIT:1>])<EOL><DEDENT>


labelSizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)<EOL>labelSizePolicy.setHorizontalStretch(<NUM_LIT:0>)<EOL>labelSizePolicy.setVerticalStretch(<NUM_LIT:0>)<EOL>menuSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)<EOL>menuSizePolicy.setHorizontalStretch(<NUM_LIT:0>)<EOL>menuSizePolicy.setVerticalStretch(<NUM_LIT:0>)<EOL>logTypeLayout = QHBoxLayout()<EOL>logTypeLayout.setSpacing(<NUM_LIT:0>)<EOL>typeLabel = QLabel("<STR_LIT>")<EOL>typeLabel.setMinimumSize(QSize(<NUM_LIT>, <NUM_LIT:0>))<EOL>typeLabel.setMaximumSize(QSize(<NUM_LIT>, <NUM_LIT>))<EOL>typeLabel.setSizePolicy(labelSizePolicy)<EOL>logTypeLayout.addWidget(typeLabel)<EOL>self.logType = QComboBox(self)<EOL>self.logType.setMinimumSize(QSize(<NUM_LIT:100>, <NUM_LIT:0>))<EOL>self.logType.setMaximumSize(QSize(<NUM_LIT>, <NUM_LIT>))<EOL>menuSizePolicy.setHeightForWidth(self.logType.sizePolicy().hasHeightForWidth())<EOL>self.logType.setSizePolicy(menuSizePolicy)<EOL>logTypeLayout.addWidget(self.logType)<EOL>logTypeLayout.setStretch(<NUM_LIT:1>, <NUM_LIT:6>)<EOL>programLayout = QHBoxLayout()<EOL>programLayout.setSpacing(<NUM_LIT:0>)<EOL>programLabel = QLabel("<STR_LIT>")<EOL>programLabel.setMinimumSize(QSize(<NUM_LIT>, <NUM_LIT:0>))<EOL>programLabel.setMaximumSize(QSize(<NUM_LIT>, <NUM_LIT>))<EOL>programLabel.setSizePolicy(labelSizePolicy)<EOL>programLayout.addWidget(programLabel)<EOL>self.programName = QComboBox(self)<EOL>self.programName.setMinimumSize(QSize(<NUM_LIT:100>, <NUM_LIT:0>))<EOL>self.programName.setMaximumSize(QSize(<NUM_LIT>, <NUM_LIT>))<EOL>menuSizePolicy.setHeightForWidth(self.programName.sizePolicy().hasHeightForWidth())<EOL>self.programName.setSizePolicy(menuSizePolicy)<EOL>programLayout.addWidget(self.programName)<EOL>programLayout.setStretch(<NUM_LIT:1>, <NUM_LIT:6>)<EOL>if self.initialInstance:<EOL><INDENT>self.logButton = QPushButton("<STR_LIT:+>", self)<EOL>self.logButton.setToolTip("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>self.logButton = QPushButton("<STR_LIT:->")<EOL>self.logButton.setToolTip("<STR_LIT>")<EOL><DEDENT>self.logButton.setMinimumSize(QSize(<NUM_LIT:16>, <NUM_LIT:16>))  <EOL>self.logButton.setMaximumSize(QSize(<NUM_LIT:16>, <NUM_LIT:16>))  <EOL>self.logButton.setObjectName("<STR_LIT>")<EOL>self.logButton.setStyleSheet("<STR_LIT>")<EOL>self._logSelectLayout = QHBoxLayout()<EOL>self._logSelectLayout.setSpacing(<NUM_LIT:6>)<EOL>self._logSelectLayout.addLayout(logTypeLayout)<EOL>self._logSelectLayout.addLayout(programLayout)<EOL>self._logSelectLayout.addWidget(self.logButton)<EOL>self._logSelectLayout.setStretch(<NUM_LIT:0>, <NUM_LIT:6>)<EOL>self._logSelectLayout.setStretch(<NUM_LIT:1>, <NUM_LIT:6>)<EOL>


<EOL>QObject.connect(self.logType, SIGNAL("<STR_LIT>"), self.changeLogType)<EOL>


self.parent.addLayout(self._logSelectLayout)<EOL>self.menuCount += <NUM_LIT:1><EOL>self._connectSlots()<EOL>


def addLogbooks(self, type=None, logs=[], default="<STR_LIT>"):

if type is not None and len(logs) != <NUM_LIT:0>:<EOL><INDENT>if type in self.logList:<EOL><INDENT>for logbook in logs:<EOL><INDENT>if logbook not in self.logList.get(type)[<NUM_LIT:0>]:<EOL><INDENT>self.logList.get(type)[<NUM_LIT:0>].append(logbook)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>self.logList[type] = []<EOL>self.logList[type].append(logs)<EOL><DEDENT>if len(self.logList[type]) > <NUM_LIT:1> and default != "<STR_LIT>":<EOL><INDENT>self.logList.get(type)[<NUM_LIT:1>] == default<EOL><DEDENT>else:<EOL><INDENT>self.logList.get(type).append(default)<EOL><DEDENT>self.logType.clear()<EOL>self.logType.addItems(list(self.logList.keys()))<EOL>self.changeLogType()<EOL><DEDENT>


def removeLogbooks(self, type=None, logs=[]):

if type is not None and type in self.logList:<EOL><INDENT>if len(logs) == <NUM_LIT:0> or logs == "<STR_LIT>":<EOL><INDENT>del self.logList[type]<EOL><DEDENT>else:<EOL><INDENT>for logbook in logs:<EOL><INDENT>if logbook in self.logList[type]:<EOL><INDENT>self.logList[type].remove(logbook)<EOL><DEDENT><DEDENT><DEDENT>self.changeLogType()<EOL><DEDENT>


logType = self.selectedType()<EOL>programs = self.logList.get(logType)[<NUM_LIT:0>]<EOL>default = self.logList.get(logType)[<NUM_LIT:1>]<EOL>if logType in self.logList:<EOL><INDENT>self.programName.clear()<EOL>self.programName.addItems(programs)<EOL>self.programName.setCurrentIndex(programs.index(default))<EOL><DEDENT>

Populate log program list to correspond with log type selection.


self.parent.multiLogLayout.addLayout(self.logSelectLayout)<EOL>self.getPrograms(logType, programName)<EOL>


for cnt in reversed(range(layout.count())):<EOL><INDENT>item = layout.takeAt(cnt)<EOL>widget = item.widget()<EOL>if widget is not None:<EOL><INDENT>widget.deleteLater()<EOL><DEDENT>else:<EOL><INDENT>'''<STR_LIT>'''<EOL>self.removeLayout(item.layout())<EOL><DEDENT><DEDENT>

Iteratively remove graphical objects from layout.


self.removeLayout(self._logSelectLayout)<EOL>self.deleteLater()<EOL>

Remove layout from parent gui and destroy object on completion.


if domain != '<STR_LIT>':<EOL><INDENT>return None<EOL><DEDENT>modname = info['<STR_LIT>']<EOL>fullname = info['<STR_LIT>']<EOL>submod = sys.modules.get(modname)<EOL>if submod is None:<EOL><INDENT>return None<EOL><DEDENT>obj = submod<EOL>for part in fullname.split('<STR_LIT:.>'):<EOL><INDENT>try:<EOL><INDENT>obj = getattr(obj, part)<EOL><DEDENT>except:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>try:<EOL><INDENT>fn = inspect.getsourcefile(obj)<EOL><DEDENT>except:<EOL><INDENT>fn = None<EOL><DEDENT>if not fn:<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>source, lineno = inspect.getsourcelines(obj)<EOL><DEDENT>except:<EOL><INDENT>lineno = None<EOL><DEDENT>if lineno:<EOL><INDENT>linespec = "<STR_LIT>" % (lineno, lineno + len(source) - <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>linespec = "<STR_LIT>"<EOL><DEDENT>fn = relpath(fn, start=dirname(scisalt.__file__))<EOL>if '<STR_LIT>' in scisalt.__version__:<EOL><INDENT>return "<STR_LIT>" % (<EOL>fn, linespec)<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>" % (<EOL>scisalt.__version__, fn, linespec)<EOL><DEDENT>

Determine the URL corresponding to Python object


return t<EOL>


t.value = float(t.value)<EOL>return t<EOL>


t.value = int(t.value)<EOL>return t<EOL>


t.lexer.lineno += len(t.value)<EOL>


p[<NUM_LIT:0>] = p[<NUM_LIT:1>] + [p[<NUM_LIT:2>]]<EOL>


model : connection_banner transition_list


p[<NUM_LIT:0>] = [p[<NUM_LIT:3>], p[<NUM_LIT:5>]]<EOL>

connection_banner : CONNECTION_KWD LPAREN TRANSPORT_KWD COMMA port RPAREN COLON


p[<NUM_LIT:0>] = p[<NUM_LIT:1>]<EOL>


transition_list : transition_list transition


p[<NUM_LIT:0>] = [p[<NUM_LIT:1>]]<EOL>


p[<NUM_LIT:3>] = None if p[<NUM_LIT:3>] == '<STR_LIT>' else p[<NUM_LIT:3>]<EOL>if p[<NUM_LIT:4>] == '<STR_LIT:error>':<EOL><INDENT>p[<NUM_LIT:0>] = MarionetteTransition(p[<NUM_LIT:1>], p[<NUM_LIT:2>], p[<NUM_LIT:3>], <NUM_LIT:0>, True)<EOL><DEDENT>else:<EOL><INDENT>p[<NUM_LIT:0>] = MarionetteTransition(p[<NUM_LIT:1>], p[<NUM_LIT:2>], p[<NUM_LIT:3>], p[<NUM_LIT:4>], False)<EOL><DEDENT>

transition : START_KWD KEY NULL_KWD FLOAT
transition : KEY KEY NULL_KWD FLOAT
transition : KEY END_KWD NULL_KWD FLOAT
transition : START_KWD KEY KEY FLOAT
transition : KEY KEY KEY FLOAT
transition : KEY END_KWD KEY FLOAT
transition : START_KWD KEY NULL_KWD INTEGER
transition : KEY KEY NULL_KWD INTEGER
transition : KEY END_KWD NULL_KWD INTEGER
transition : START_KWD KEY KEY INTEGER
transition : KEY KEY KEY INTEGER
transition : KEY END_KWD KEY INTEGER
transition : START_KWD KEY NULL_KWD KEY
transition : KEY KEY NULL_KWD KEY
transition : KEY END_KWD NULL_KWD KEY
transition : START_KWD KEY KEY KEY
transition : KEY KEY KEY KEY
transition : KEY END_KWD KEY KEY


if isinstance(p[<NUM_LIT:1>], list):<EOL><INDENT>if isinstance(p[<NUM_LIT:1>][<NUM_LIT:0>], list):<EOL><INDENT>p[<NUM_LIT:0>] = p[<NUM_LIT:1>][<NUM_LIT:0>] + [p[<NUM_LIT:2>]]<EOL><DEDENT>else:<EOL><INDENT>p[<NUM_LIT:0>] = p[<NUM_LIT:1>] + p[<NUM_LIT:2>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>p[<NUM_LIT:0>] = [p[<NUM_LIT:1>], p[<NUM_LIT:2>]]<EOL><DEDENT>

action_blocks : action_blocks action_block


p[<NUM_LIT:0>] = []<EOL>for i in range(len(p[<NUM_LIT:4>])):<EOL><INDENT>p[<NUM_LIT:0>] += [marionette_tg.action.MarionetteAction(p[<NUM_LIT:2>], p[<NUM_LIT:4>][i][<NUM_LIT:0>],<EOL>p[<NUM_LIT:4>][i][<NUM_LIT:1>],<EOL>p[<NUM_LIT:4>][i][<NUM_LIT:2>],<EOL>p[<NUM_LIT:4>][i][<NUM_LIT:3>],<EOL>p[<NUM_LIT:4>][i][<NUM_LIT:4>])]<EOL><DEDENT>

action_block : ACTION_KWD KEY COLON actions


if len(p)==<NUM_LIT:8>:<EOL><INDENT>p[<NUM_LIT:0>] = [p[<NUM_LIT:1>], p[<NUM_LIT:2>], p[<NUM_LIT:4>], p[<NUM_LIT:6>], None]<EOL><DEDENT>elif len(p)==<NUM_LIT>:<EOL><INDENT>p[<NUM_LIT:0>] = [p[<NUM_LIT:1>], p[<NUM_LIT:2>], p[<NUM_LIT:4>], p[<NUM_LIT:6>], p[<NUM_LIT:11>]]<EOL><DEDENT>

action : CLIENT_KWD KEY DOT KEY LPAREN args RPAREN
action : SERVER_KWD KEY DOT KEY LPAREN args RPAREN
action : CLIENT_KWD KEY DOT KEY LPAREN args RPAREN IF_KWD REGEX_MATCH_INCOMING_KWD LPAREN p_string_arg RPAREN
action : SERVER_KWD KEY DOT KEY LPAREN args RPAREN IF_KWD REGEX_MATCH_INCOMING_KWD LPAREN p_string_arg RPAREN


if len(p) == <NUM_LIT:4>:<EOL><INDENT>p[<NUM_LIT:0>] = p[<NUM_LIT:1>] + [p[<NUM_LIT:3>]]<EOL><DEDENT>else:<EOL><INDENT>p[<NUM_LIT:0>] = [p[<NUM_LIT:1>]]<EOL><DEDENT>


p[<NUM_LIT:0>] = p[<NUM_LIT:1>]<EOL>

arg : p_string_arg
arg : p_integer_arg
arg : p_float_arg


p[<NUM_LIT:0>] = str(p[<NUM_LIT:1>][<NUM_LIT:1>:-<NUM_LIT:1>])<EOL>p[<NUM_LIT:0>] = p[<NUM_LIT:0>].decode("<STR_LIT>")<EOL>


p[<NUM_LIT:0>] = int(p[<NUM_LIT:1>])<EOL>


p[<NUM_LIT:0>] = float(p[<NUM_LIT:1>])<EOL>


bytestring = hex(N)<EOL>bytestring = bytestring[<NUM_LIT:2>:] if bytestring.startswith('<STR_LIT>') else bytestring<EOL>bytestring = bytestring[:-<NUM_LIT:1>] if bytestring.endswith('<STR_LIT:L>') else bytestring<EOL>bytestring = '<STR_LIT:0>' + bytestring if (len(bytestring) % <NUM_LIT:2>) != <NUM_LIT:0> else bytestring<EOL>bytestring = binascii.unhexlify(bytestring)<EOL>if blocksize > <NUM_LIT:0> and len(bytestring) % blocksize != <NUM_LIT:0>:<EOL><INDENT>bytestring = '<STR_LIT:\x00>' *(blocksize - (len(bytestring) % blocksize)) + bytestring<EOL><DEDENT>return bytestring<EOL>

Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes.
    If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes,
    such that the return values length is a multiple of ``blocksize``.


if offset is None:<EOL><INDENT>offset = getattr(settings, '<STR_LIT>', defaults.MAILQUEUE_CLEAR_OFFSET)<EOL><DEDENT>if type(offset) is int:<EOL><INDENT>offset = datetime.timedelta(hours=offset)<EOL><DEDENT>delete_before = timezone.now() - offset<EOL>self.filter(sent=True, last_attempt__lte=delete_before).delete()<EOL>


if self.pk is None:<EOL><INDENT>self._save_without_sending()<EOL><DEDENT>original_filename = attachment.file.name.split(os.sep)[-<NUM_LIT:1>]<EOL>file_content = ContentFile(attachment.read())<EOL>new_attachment = Attachment()<EOL>new_attachment.file_attachment.save(original_filename, file_content, save=False)<EOL>new_attachment.email = self<EOL>new_attachment.original_filename = original_filename<EOL>try:<EOL><INDENT>new_attachment.save()<EOL><DEDENT>except Exception as e:<EOL><INDENT>logger.error(e)<EOL>new_attachment.file_attachment.delete()<EOL><DEDENT>

Takes a Django `File` object and creates an attachment for this mailer message.


def _save_without_sending(self, *args, **kwargs):

self.do_not_send = True<EOL>super(MailerMessage, self).save(*args, **kwargs)<EOL>

Saves the MailerMessage instance without sending the e-mail. This ensures
other models (e.g. `Attachment`) have something to relate to in the database.


if getattr(settings, '<STR_LIT>', defaults.MAILQUEUE_CELERY):<EOL><INDENT>from mailqueue.tasks import send_mail<EOL>send_mail.delay(self.pk)<EOL><DEDENT>else:<EOL><INDENT>self._send()<EOL><DEDENT>

Public api to send mail.  Makes the determinination
         of using celery or not and then calls the appropriate methods.


positions_wo_cash = positions.drop('<STR_LIT>', axis='<STR_LIT>')<EOL>gross_exposure = positions_wo_cash.abs().sum(axis='<STR_LIT>')<EOL>style_factor_exposure = positions_wo_cash.multiply(risk_factor).divide(gross_exposure, axis='<STR_LIT:index>')<EOL>tot_style_factor_exposure = style_factor_exposure.sum(axis='<STR_LIT>',<EOL>skipna=True)<EOL>return tot_style_factor_exposure<EOL>

Returns style factor exposure of an algorithm's positions

Parameters
----------
positions : pd.DataFrame
    Daily equity positions of algorithm, in dollars.
    - See full explanation in create_risk_tear_sheet

risk_factor : pd.DataFrame
    Daily risk factor per asset.
    - DataFrame with dates as index and equities as columns
    - Example:
                     Equity(24   Equity(62
                       [AAPL])      [ABT])
    2017-04-03	  -0.51284     1.39173
    2017-04-04	  -0.73381     0.98149
    2017-04-05	  -0.90132     1.13981


if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>if factor_name is None:<EOL><INDENT>factor_name = tot_style_factor_exposure.name<EOL><DEDENT>ax.plot(tot_style_factor_exposure.index, tot_style_factor_exposure,<EOL>label=factor_name)<EOL>avg = tot_style_factor_exposure.mean()<EOL>ax.axhline(avg, linestyle='<STR_LIT>', label='<STR_LIT>'.format(avg))<EOL>ax.axhline(<NUM_LIT:0>, color='<STR_LIT:k>', linestyle='<STR_LIT:->')<EOL>_, _, y1, y2 = plt.axis()<EOL>lim = max(abs(y1), abs(y2))<EOL>ax.set(title='<STR_LIT>'.format(factor_name),<EOL>ylabel='<STR_LIT>'.format(factor_name),<EOL>ylim=(-lim, lim))<EOL>ax.legend(frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>return ax<EOL>

Plots DataFrame output of compute_style_factor_exposures as a line graph

Parameters
----------
tot_style_factor_exposure : pd.Series
    Daily style factor exposures (output of compute_style_factor_exposures)
    - Time series with decimal style factor exposures
    - Example:
        2017-04-24    0.037820
        2017-04-25    0.016413
        2017-04-26   -0.021472
        2017-04-27   -0.024859

factor_name : string
    Name of style factor, for use in graph title
    - Defaults to tot_style_factor_exposure.name


def compute_sector_exposures(positions, sectors, sector_dict=SECTORS):

sector_ids = sector_dict.keys()<EOL>long_exposures = []<EOL>short_exposures = []<EOL>gross_exposures = []<EOL>net_exposures = []<EOL>positions_wo_cash = positions.drop('<STR_LIT>', axis='<STR_LIT>')<EOL>long_exposure = positions_wo_cash[positions_wo_cash > <NUM_LIT:0>].sum(axis='<STR_LIT>')<EOL>short_exposure = positions_wo_cash[positions_wo_cash < <NUM_LIT:0>].abs().sum(axis='<STR_LIT>')<EOL>gross_exposure = positions_wo_cash.abs().sum(axis='<STR_LIT>')<EOL>for sector_id in sector_ids:<EOL><INDENT>in_sector = positions_wo_cash[sectors == sector_id]<EOL>long_sector = in_sector[in_sector > <NUM_LIT:0>].sum(axis='<STR_LIT>').divide(long_exposure)<EOL>short_sector = in_sector[in_sector < <NUM_LIT:0>].sum(axis='<STR_LIT>').divide(short_exposure)<EOL>gross_sector = in_sector.abs().sum(axis='<STR_LIT>').divide(gross_exposure)<EOL>net_sector = long_sector.subtract(short_sector)<EOL>long_exposures.append(long_sector)<EOL>short_exposures.append(short_sector)<EOL>gross_exposures.append(gross_sector)<EOL>net_exposures.append(net_sector)<EOL><DEDENT>return long_exposures, short_exposures, gross_exposures, net_exposures<EOL>

Returns arrays of long, short and gross sector exposures of an algorithm's
positions

Parameters
----------
positions : pd.DataFrame
    Daily equity positions of algorithm, in dollars.
    - See full explanation in compute_style_factor_exposures.

sectors : pd.DataFrame
    Daily Morningstar sector code per asset
    - See full explanation in create_risk_tear_sheet

sector_dict : dict or OrderedDict
    Dictionary of all sectors
    - Keys are sector codes (e.g. ints or strings) and values are sector
      names (which must be strings)
    - Defaults to Morningstar sectors


def plot_sector_exposures_longshort(long_exposures, short_exposures,<EOL>sector_dict=SECTORS, ax=None):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>if sector_dict is None:<EOL><INDENT>sector_names = SECTORS.values()<EOL><DEDENT>else:<EOL><INDENT>sector_names = sector_dict.values()<EOL><DEDENT>color_list = plt.cm.gist_rainbow(np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:11>))<EOL>ax.stackplot(long_exposures[<NUM_LIT:0>].index, long_exposures,<EOL>labels=sector_names, colors=color_list, alpha=<NUM_LIT>,<EOL>baseline='<STR_LIT>')<EOL>ax.stackplot(long_exposures[<NUM_LIT:0>].index, short_exposures,<EOL>colors=color_list, alpha=<NUM_LIT>, baseline='<STR_LIT>')<EOL>ax.axhline(<NUM_LIT:0>, color='<STR_LIT:k>', linestyle='<STR_LIT:->')<EOL>ax.set(title='<STR_LIT>',<EOL>ylabel='<STR_LIT>')<EOL>ax.legend(loc='<STR_LIT>', frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>return ax<EOL>

Plots outputs of compute_sector_exposures as area charts

Parameters
----------
long_exposures, short_exposures : arrays
    Arrays of long and short sector exposures (output of
    compute_sector_exposures).

sector_dict : dict or OrderedDict
    Dictionary of all sectors
    - See full description in compute_sector_exposures


def plot_sector_exposures_gross(gross_exposures, sector_dict=None, ax=None):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>if sector_dict is None:<EOL><INDENT>sector_names = SECTORS.values()<EOL><DEDENT>else:<EOL><INDENT>sector_names = sector_dict.values()<EOL><DEDENT>color_list = plt.cm.gist_rainbow(np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:11>))<EOL>ax.stackplot(gross_exposures[<NUM_LIT:0>].index, gross_exposures,<EOL>labels=sector_names, colors=color_list, alpha=<NUM_LIT>,<EOL>baseline='<STR_LIT>')<EOL>ax.axhline(<NUM_LIT:0>, color='<STR_LIT:k>', linestyle='<STR_LIT:->')<EOL>ax.set(title='<STR_LIT>',<EOL>ylabel='<STR_LIT>')<EOL>return ax<EOL>

Plots output of compute_sector_exposures as area charts

Parameters
----------
gross_exposures : arrays
    Arrays of gross sector exposures (output of compute_sector_exposures).

sector_dict : dict or OrderedDict
    Dictionary of all sectors
    - See full description in compute_sector_exposures


def plot_sector_exposures_net(net_exposures, sector_dict=None, ax=None):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>if sector_dict is None:<EOL><INDENT>sector_names = SECTORS.values()<EOL><DEDENT>else:<EOL><INDENT>sector_names = sector_dict.values()<EOL><DEDENT>color_list = plt.cm.gist_rainbow(np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:11>))<EOL>for i in range(len(net_exposures)):<EOL><INDENT>ax.plot(net_exposures[i], color=color_list[i], alpha=<NUM_LIT>,<EOL>label=sector_names[i])<EOL><DEDENT>ax.set(title='<STR_LIT>',<EOL>ylabel='<STR_LIT>')<EOL>return ax<EOL>

Plots output of compute_sector_exposures as line graphs

Parameters
----------
net_exposures : arrays
    Arrays of net sector exposures (output of compute_sector_exposures).

sector_dict : dict or OrderedDict
    Dictionary of all sectors
    - See full description in compute_sector_exposures


long_exposures = []<EOL>short_exposures = []<EOL>gross_exposures = []<EOL>net_exposures = []<EOL>positions_wo_cash = positions.drop('<STR_LIT>', axis='<STR_LIT>')<EOL>tot_gross_exposure = positions_wo_cash.abs().sum(axis='<STR_LIT>')<EOL>tot_long_exposure = positions_wo_cash[positions_wo_cash > <NUM_LIT:0>].sum(axis='<STR_LIT>')<EOL>tot_short_exposure = positions_wo_cash[positions_wo_cash < <NUM_LIT:0>].abs().sum(axis='<STR_LIT>')<EOL>for bucket_name, boundaries in CAP_BUCKETS.items():<EOL><INDENT>in_bucket = positions_wo_cash[(caps >= boundaries[<NUM_LIT:0>]) &<EOL>(caps <= boundaries[<NUM_LIT:1>])]<EOL>gross_bucket = in_bucket.abs().sum(axis='<STR_LIT>').divide(tot_gross_exposure)<EOL>long_bucket = in_bucket[in_bucket > <NUM_LIT:0>].sum(axis='<STR_LIT>').divide(tot_long_exposure)<EOL>short_bucket = in_bucket[in_bucket < <NUM_LIT:0>].sum(axis='<STR_LIT>').divide(tot_short_exposure)<EOL>net_bucket = long_bucket.subtract(short_bucket)<EOL>gross_exposures.append(gross_bucket)<EOL>long_exposures.append(long_bucket)<EOL>short_exposures.append(short_bucket)<EOL>net_exposures.append(net_bucket)<EOL><DEDENT>return long_exposures, short_exposures, gross_exposures, net_exposures<EOL>

Returns arrays of long, short and gross market cap exposures of an
algorithm's positions

Parameters
----------
positions : pd.DataFrame
    Daily equity positions of algorithm, in dollars.
    - See full explanation in compute_style_factor_exposures.

caps : pd.DataFrame
    Daily Morningstar sector code per asset
    - See full explanation in create_risk_tear_sheet


def plot_cap_exposures_longshort(long_exposures, short_exposures, ax=None):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>color_list = plt.cm.gist_rainbow(np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:5>))<EOL>ax.stackplot(long_exposures[<NUM_LIT:0>].index, long_exposures,<EOL>labels=CAP_BUCKETS.keys(), colors=color_list, alpha=<NUM_LIT>,<EOL>baseline='<STR_LIT>')<EOL>ax.stackplot(long_exposures[<NUM_LIT:0>].index, short_exposures, colors=color_list,<EOL>alpha=<NUM_LIT>, baseline='<STR_LIT>')<EOL>ax.axhline(<NUM_LIT:0>, color='<STR_LIT:k>', linestyle='<STR_LIT:->')<EOL>ax.set(title='<STR_LIT>',<EOL>ylabel='<STR_LIT>')<EOL>ax.legend(loc='<STR_LIT>', frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>return ax<EOL>

Plots outputs of compute_cap_exposures as area charts

Parameters
----------
long_exposures, short_exposures : arrays
    Arrays of long and short market cap exposures (output of
    compute_cap_exposures).


if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>color_list = plt.cm.gist_rainbow(np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:5>))<EOL>ax.stackplot(gross_exposures[<NUM_LIT:0>].index, gross_exposures,<EOL>labels=CAP_BUCKETS.keys(), colors=color_list, alpha=<NUM_LIT>,<EOL>baseline='<STR_LIT>')<EOL>ax.axhline(<NUM_LIT:0>, color='<STR_LIT:k>', linestyle='<STR_LIT:->')<EOL>ax.set(title='<STR_LIT>',<EOL>ylabel='<STR_LIT>')<EOL>return ax<EOL>

Plots outputs of compute_cap_exposures as area charts

Parameters
----------
gross_exposures : array
    Arrays of gross market cap exposures (output of compute_cap_exposures).


if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>color_list = plt.cm.gist_rainbow(np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:5>))<EOL>cap_names = CAP_BUCKETS.keys()<EOL>for i in range(len(net_exposures)):<EOL><INDENT>ax.plot(net_exposures[i], color=color_list[i], alpha=<NUM_LIT>,<EOL>label=cap_names[i])<EOL><DEDENT>ax.axhline(<NUM_LIT:0>, color='<STR_LIT:k>', linestyle='<STR_LIT:->')<EOL>ax.set(title='<STR_LIT>',<EOL>ylabel='<STR_LIT>')<EOL>return ax<EOL>

Plots outputs of compute_cap_exposures as line graphs

Parameters
----------
net_exposures : array
    Arrays of gross market cap exposures (output of compute_cap_exposures).


def compute_volume_exposures(shares_held, volumes, percentile):

shares_held = shares_held.replace(<NUM_LIT:0>, np.nan)<EOL>shares_longed = shares_held[shares_held > <NUM_LIT:0>]<EOL>shares_shorted = -<NUM_LIT:1> * shares_held[shares_held < <NUM_LIT:0>]<EOL>shares_grossed = shares_held.abs()<EOL>longed_frac = shares_longed.divide(volumes)<EOL>shorted_frac = shares_shorted.divide(volumes)<EOL>grossed_frac = shares_grossed.divide(volumes)<EOL>longed_threshold = <NUM_LIT:100> * longed_frac.apply(<EOL>partial(np.nanpercentile, q=<NUM_LIT:100> * percentile),<EOL>axis='<STR_LIT>',<EOL>)<EOL>shorted_threshold = <NUM_LIT:100> * shorted_frac.apply(<EOL>partial(np.nanpercentile, q=<NUM_LIT:100> * percentile),<EOL>axis='<STR_LIT>',<EOL>)<EOL>grossed_threshold = <NUM_LIT:100> * grossed_frac.apply(<EOL>partial(np.nanpercentile, q=<NUM_LIT:100> * percentile),<EOL>axis='<STR_LIT>',<EOL>)<EOL>return longed_threshold, shorted_threshold, grossed_threshold<EOL>

Returns arrays of pth percentile of long, short and gross volume exposures
of an algorithm's held shares

Parameters
----------
shares_held : pd.DataFrame
    Daily number of shares held by an algorithm.
    - See full explanation in create_risk_tear_sheet

volume : pd.DataFrame
    Daily volume per asset
    - See full explanation in create_risk_tear_sheet

percentile : float
    Percentile to use when computing and plotting volume exposures
    - See full explanation in create_risk_tear_sheet


def plot_volume_exposures_longshort(longed_threshold, shorted_threshold,<EOL>percentile, ax=None):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>ax.plot(longed_threshold.index, longed_threshold,<EOL>color='<STR_LIT:b>', label='<STR_LIT>')<EOL>ax.plot(shorted_threshold.index, shorted_threshold,<EOL>color='<STR_LIT:r>', label='<STR_LIT>')<EOL>ax.axhline(<NUM_LIT:0>, color='<STR_LIT:k>')<EOL>ax.set(title='<STR_LIT>',<EOL>ylabel='<STR_LIT>'<EOL>.format(<NUM_LIT:100> * percentile))<EOL>ax.legend(frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>return ax<EOL>

Plots outputs of compute_volume_exposures as line graphs

Parameters
----------
longed_threshold, shorted_threshold : pd.Series
    Series of longed and shorted volume exposures (output of
    compute_volume_exposures).

percentile : float
    Percentile to use when computing and plotting volume exposures.
    - See full explanation in create_risk_tear_sheet


def plot_volume_exposures_gross(grossed_threshold, percentile, ax=None):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>ax.plot(grossed_threshold.index, grossed_threshold,<EOL>color='<STR_LIT:b>', label='<STR_LIT>')<EOL>ax.axhline(<NUM_LIT:0>, color='<STR_LIT:k>')<EOL>ax.set(title='<STR_LIT>',<EOL>ylabel='<STR_LIT>'<EOL>.format(<NUM_LIT:100> * percentile))<EOL>ax.legend(frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>return ax<EOL>

Plots outputs of compute_volume_exposures as line graphs

Parameters
----------
grossed_threshold : pd.Series
    Series of grossed volume exposures (output of
    compute_volume_exposures).

percentile : float
    Percentile to use when computing and plotting volume exposures
    - See full explanation in create_risk_tear_sheet


dts = pd.date_range(start_date, periods=periods)<EOL>np.random.seed(<NUM_LIT>)<EOL>tickers = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>styles = ['<STR_LIT>'.format(i) for i in range(num_styles)]<EOL>returns = pd.Series(index=dts,<EOL>data=np.random.randn(periods)) / <NUM_LIT:100><EOL>factor_returns = pd.DataFrame(<EOL>columns=styles, index=dts,<EOL>data=np.random.randn(periods, len(styles))) / <NUM_LIT:100><EOL>arrays = [dts, tickers]<EOL>index = pd.MultiIndex.from_product(arrays, names=['<STR_LIT>', '<STR_LIT>'])<EOL>positions = pd.DataFrame(<EOL>columns=tickers, index=dts,<EOL>data=np.random.randint(<NUM_LIT:100>, size=(periods, len(tickers)))<EOL>)<EOL>positions['<STR_LIT>'] = np.zeros(periods)<EOL>factor_loadings = pd.DataFrame(<EOL>columns=styles, index=index,<EOL>data=np.random.randn(periods * len(tickers), len(styles))<EOL>)<EOL>return returns, positions, factor_returns, factor_loadings<EOL>

Generate toy risk model output.

Parameters
----------
start_date : str
    date to start generating toy data
periods : int
    number of days for which to generate toy data

Returns
-------
tuple of (returns, factor_returns, positions, factor_loadings)
returns : pd.DataFrame
factor_returns : pd.DataFrame


if (unadjusted_returns is None) and (slippage is not None) and(transactions is not None):<EOL><INDENT>unadjusted_returns = returns.copy()<EOL>returns = txn.adjust_returns_for_slippage(returns, positions,<EOL>transactions, slippage)<EOL><DEDENT>positions = utils.check_intraday(estimate_intraday, returns,<EOL>positions, transactions)<EOL>create_returns_tear_sheet(<EOL>returns,<EOL>positions=positions,<EOL>transactions=transactions,<EOL>live_start_date=live_start_date,<EOL>cone_std=cone_std,<EOL>benchmark_rets=benchmark_rets,<EOL>bootstrap=bootstrap,<EOL>turnover_denom=turnover_denom,<EOL>header_rows=header_rows,<EOL>set_context=set_context)<EOL>create_interesting_times_tear_sheet(returns,<EOL>benchmark_rets=benchmark_rets,<EOL>set_context=set_context)<EOL>if positions is not None:<EOL><INDENT>create_position_tear_sheet(returns, positions,<EOL>hide_positions=hide_positions,<EOL>set_context=set_context,<EOL>sector_mappings=sector_mappings,<EOL>estimate_intraday=False)<EOL>if transactions is not None:<EOL><INDENT>create_txn_tear_sheet(returns, positions, transactions,<EOL>unadjusted_returns=unadjusted_returns,<EOL>estimate_intraday=False,<EOL>set_context=set_context)<EOL>if round_trips:<EOL><INDENT>create_round_trip_tear_sheet(<EOL>returns=returns,<EOL>positions=positions,<EOL>transactions=transactions,<EOL>sector_mappings=sector_mappings,<EOL>estimate_intraday=False)<EOL><DEDENT>if market_data is not None:<EOL><INDENT>create_capacity_tear_sheet(returns, positions, transactions,<EOL>market_data,<EOL>liquidation_daily_vol_limit=<NUM_LIT>,<EOL>last_n_days=<NUM_LIT>,<EOL>estimate_intraday=False)<EOL><DEDENT><DEDENT>if style_factor_panel is not None:<EOL><INDENT>create_risk_tear_sheet(positions, style_factor_panel, sectors,<EOL>caps, shares_held, volumes, percentile)<EOL><DEDENT>if factor_returns is not None and factor_loadings is not None:<EOL><INDENT>create_perf_attrib_tear_sheet(returns, positions, factor_returns,<EOL>factor_loadings, transactions,<EOL>pos_in_dollars=pos_in_dollars,<EOL>factor_partitions=factor_partitions)<EOL><DEDENT><DEDENT>if bayesian:<EOL><INDENT>create_bayesian_tear_sheet(returns,<EOL>live_start_date=live_start_date,<EOL>benchmark_rets=benchmark_rets,<EOL>set_context=set_context)<EOL><DEDENT>

Generate a number of tear sheets that are useful
for analyzing a strategy's performance.

- Fetches benchmarks if needed.
- Creates tear sheets for returns, and significant events.
    If possible, also creates tear sheets for position analysis,
    transaction analysis, and Bayesian analysis.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - Time series with decimal returns.
     - Example:
        2015-07-16    -0.012143
        2015-07-17    0.045350
        2015-07-20    0.030957
        2015-07-21    0.004902
positions : pd.DataFrame, optional
    Daily net position values.
     - Time series of dollar amount invested in each position and cash.
     - Days where stocks are not held can be represented by 0 or NaN.
     - Non-working capital is labelled 'cash'
     - Example:
        index         'AAPL'         'MSFT'          cash
        2004-01-09    13939.3800     -14012.9930     711.5585
        2004-01-12    14492.6300     -14624.8700     27.1821
        2004-01-13    -13853.2800    13653.6400      -43.6375
transactions : pd.DataFrame, optional
    Executed trade volumes and fill prices.
    - One row per trade.
    - Trades on different names that occur at the
      same time will have identical indicies.
    - Example:
        index                  amount   price    symbol
        2004-01-09 12:18:01    483      324.12   'AAPL'
        2004-01-09 12:18:01    122      83.10    'MSFT'
        2004-01-13 14:12:23    -75      340.43   'AAPL'
market_data : pd.Panel, optional
    Panel with items axis of 'price' and 'volume' DataFrames.
    The major and minor axes should match those of the
    the passed positions DataFrame (same dates and symbols).
slippage : int/float, optional
    Basis points of slippage to apply to returns before generating
    tearsheet stats and plots.
    If a value is provided, slippage parameter sweep
    plots will be generated from the unadjusted returns.
    Transactions and positions must also be passed.
    - See txn.adjust_returns_for_slippage for more details.
live_start_date : datetime, optional
    The point in time when the strategy began live trading,
    after its backtest period. This datetime should be normalized.
hide_positions : bool, optional
    If True, will not output any symbol names.
bayesian: boolean, optional
    If True, causes the generation of a Bayesian tear sheet.
round_trips: boolean, optional
    If True, causes the generation of a round trip tear sheet.
sector_mappings : dict or pd.Series, optional
    Security identifier to sector mapping.
    Security ids as keys, sectors as values.
estimate_intraday: boolean or str, optional
    Instead of using the end-of-day positions, use the point in the day
    where we have the most $ invested. This will adjust positions to
    better approximate and represent how an intraday strategy behaves.
    By default, this is 'infer', and an attempt will be made to detect
    an intraday strategy. Specifying this value will prevent detection.
cone_std : float, or tuple, optional
    If float, The standard deviation to use for the cone plots.
    If tuple, Tuple of standard deviation values to use for the cone plots
     - The cone is a normal distribution with this standard deviation
         centered around a linear regression.
bootstrap : boolean (optional)
    Whether to perform bootstrap analysis for the performance
    metrics. Takes a few minutes longer.
turnover_denom : str
    Either AGB or portfolio_value, default AGB.
    - See full explanation in txn.get_turnover.
factor_returns : pd.Dataframe, optional
    Returns by factor, with date as index and factors as columns
factor_loadings : pd.Dataframe, optional
    Factor loadings for all days in the date range, with date and
    ticker as index, and factors as columns.
pos_in_dollars : boolean, optional
    indicates whether positions is in dollars
header_rows : dict or OrderedDict, optional
    Extra rows to display at the top of the perf stats table.
set_context : boolean, optional
    If True, set default plotting style context.
     - See plotting.context().
factor_partitions : dict, optional
    dict specifying how factors should be separated in perf attrib
    factor returns and risk exposures plots
    - See create_perf_attrib_tear_sheet().


positions = utils.check_intraday(estimate_intraday, returns,<EOL>positions, transactions)<EOL>if (slippage is not None) and (transactions is not None):<EOL><INDENT>returns = txn.adjust_returns_for_slippage(returns, positions,<EOL>transactions, slippage)<EOL><DEDENT>always_sections = <NUM_LIT:4><EOL>positions_sections = <NUM_LIT:4> if positions is not None else <NUM_LIT:0><EOL>transactions_sections = <NUM_LIT:2> if transactions is not None else <NUM_LIT:0><EOL>live_sections = <NUM_LIT:1> if live_start_date is not None else <NUM_LIT:0><EOL>benchmark_sections = <NUM_LIT:1> if benchmark_rets is not None else <NUM_LIT:0><EOL>vertical_sections = sum([<EOL>always_sections,<EOL>positions_sections,<EOL>transactions_sections,<EOL>live_sections,<EOL>benchmark_sections,<EOL>])<EOL>if live_start_date is not None:<EOL><INDENT>live_start_date = ep.utils.get_utc_timestamp(live_start_date)<EOL><DEDENT>plotting.show_perf_stats(returns,<EOL>benchmark_rets,<EOL>positions=positions,<EOL>transactions=transactions,<EOL>turnover_denom=turnover_denom,<EOL>live_start_date=live_start_date,<EOL>header_rows=header_rows)<EOL>fig = plt.figure(figsize=(<NUM_LIT>, vertical_sections * <NUM_LIT:6>))<EOL>gs = gridspec.GridSpec(vertical_sections, <NUM_LIT:3>, wspace=<NUM_LIT:0.5>, hspace=<NUM_LIT:0.5>)<EOL>ax_rolling_returns = plt.subplot(gs[:<NUM_LIT:2>, :])<EOL>i = <NUM_LIT:2><EOL>if benchmark_rets is not None:<EOL><INDENT>ax_rolling_beta = plt.subplot(gs[i, :], sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL><DEDENT>ax_rolling_sharpe = plt.subplot(gs[i, :], sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>ax_underwater = plt.subplot(gs[i, :], sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>plotting.plot_rolling_returns(returns,<EOL>factor_returns=benchmark_rets,<EOL>live_start_date=live_start_date,<EOL>cone_std=(<NUM_LIT:1.0>, <NUM_LIT>, <NUM_LIT>),<EOL>ax=ax_rolling_returns)<EOL>ax_rolling_returns.set_title('<STR_LIT>')<EOL>if benchmark_rets is not None:<EOL><INDENT>plotting.plot_rolling_beta(returns, benchmark_rets, ax=ax_rolling_beta)<EOL><DEDENT>plotting.plot_rolling_sharpe(returns, ax=ax_rolling_sharpe)<EOL>plotting.plot_drawdown_underwater(returns, ax=ax_underwater)<EOL>if positions is not None:<EOL><INDENT>ax_exposures = plt.subplot(gs[i, :])<EOL>i += <NUM_LIT:1><EOL>ax_top_positions = plt.subplot(gs[i, :], sharex=ax_exposures)<EOL>i += <NUM_LIT:1><EOL>ax_holdings = plt.subplot(gs[i, :], sharex=ax_exposures)<EOL>i += <NUM_LIT:1><EOL>ax_long_short_holdings = plt.subplot(gs[i, :])<EOL>i += <NUM_LIT:1><EOL>positions_alloc = pos.get_percent_alloc(positions)<EOL>plotting.plot_exposures(returns, positions, ax=ax_exposures)<EOL>plotting.show_and_plot_top_positions(returns,<EOL>positions_alloc,<EOL>show_and_plot=<NUM_LIT:0>,<EOL>hide_positions=False,<EOL>ax=ax_top_positions)<EOL>plotting.plot_holdings(returns, positions_alloc, ax=ax_holdings)<EOL>plotting.plot_long_short_holdings(returns, positions_alloc,<EOL>ax=ax_long_short_holdings)<EOL>if transactions is not None:<EOL><INDENT>ax_turnover = plt.subplot(gs[i, :])<EOL>i += <NUM_LIT:1><EOL>ax_txn_timings = plt.subplot(gs[i, :])<EOL>i += <NUM_LIT:1><EOL>plotting.plot_turnover(returns,<EOL>transactions,<EOL>positions,<EOL>ax=ax_turnover)<EOL>plotting.plot_txn_time_hist(transactions, ax=ax_txn_timings)<EOL><DEDENT><DEDENT>for ax in fig.axes:<EOL><INDENT>plt.setp(ax.get_xticklabels(), visible=True)<EOL><DEDENT>

Simpler version of create_full_tear_sheet; generates summary performance
statistics and important plots as a single image.

- Plots: cumulative returns, rolling beta, rolling Sharpe, underwater,
    exposure, top 10 holdings, total holdings, long/short holdings,
    daily turnover, transaction time distribution.
- Never accept market_data input (market_data = None)
- Never accept sector_mappings input (sector_mappings = None)
- Never perform bootstrap analysis (bootstrap = False)
- Never hide posistions on top 10 holdings plot (hide_positions = False)
- Always use default cone_std (cone_std = (1.0, 1.5, 2.0))

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - Time series with decimal returns.
     - Example:
        2015-07-16    -0.012143
        2015-07-17    0.045350
        2015-07-20    0.030957
        2015-07-21    0.004902
positions : pd.DataFrame, optional
    Daily net position values.
     - Time series of dollar amount invested in each position and cash.
     - Days where stocks are not held can be represented by 0 or NaN.
     - Non-working capital is labelled 'cash'
     - Example:
        index         'AAPL'         'MSFT'          cash
        2004-01-09    13939.3800     -14012.9930     711.5585
        2004-01-12    14492.6300     -14624.8700     27.1821
        2004-01-13    -13853.2800    13653.6400      -43.6375
transactions : pd.DataFrame, optional
    Executed trade volumes and fill prices.
    - One row per trade.
    - Trades on different names that occur at the
      same time will have identical indicies.
    - Example:
        index                  amount   price    symbol
        2004-01-09 12:18:01    483      324.12   'AAPL'
        2004-01-09 12:18:01    122      83.10    'MSFT'
        2004-01-13 14:12:23    -75      340.43   'AAPL'
benchmark_rets : pd.Series, optional
    Daily returns of the benchmark, noncumulative.
slippage : int/float, optional
    Basis points of slippage to apply to returns before generating
    tearsheet stats and plots.
    If a value is provided, slippage parameter sweep
    plots will be generated from the unadjusted returns.
    Transactions and positions must also be passed.
    - See txn.adjust_returns_for_slippage for more details.
live_start_date : datetime, optional
    The point in time when the strategy began live trading,
    after its backtest period. This datetime should be normalized.
turnover_denom : str, optional
    Either AGB or portfolio_value, default AGB.
    - See full explanation in txn.get_turnover.
header_rows : dict or OrderedDict, optional
    Extra rows to display at the top of the perf stats table.
set_context : boolean, optional
    If True, set default plotting style context.


if benchmark_rets is not None:<EOL><INDENT>returns = utils.clip_returns_to_benchmark(returns, benchmark_rets)<EOL><DEDENT>plotting.show_perf_stats(returns, benchmark_rets,<EOL>positions=positions,<EOL>transactions=transactions,<EOL>turnover_denom=turnover_denom,<EOL>bootstrap=bootstrap,<EOL>live_start_date=live_start_date,<EOL>header_rows=header_rows)<EOL>plotting.show_worst_drawdown_periods(returns)<EOL>vertical_sections = <NUM_LIT:11><EOL>if live_start_date is not None:<EOL><INDENT>vertical_sections += <NUM_LIT:1><EOL>live_start_date = ep.utils.get_utc_timestamp(live_start_date)<EOL><DEDENT>if benchmark_rets is not None:<EOL><INDENT>vertical_sections += <NUM_LIT:1><EOL><DEDENT>if bootstrap:<EOL><INDENT>vertical_sections += <NUM_LIT:1><EOL><DEDENT>fig = plt.figure(figsize=(<NUM_LIT>, vertical_sections * <NUM_LIT:6>))<EOL>gs = gridspec.GridSpec(vertical_sections, <NUM_LIT:3>, wspace=<NUM_LIT:0.5>, hspace=<NUM_LIT:0.5>)<EOL>ax_rolling_returns = plt.subplot(gs[:<NUM_LIT:2>, :])<EOL>i = <NUM_LIT:2><EOL>ax_rolling_returns_vol_match = plt.subplot(gs[i, :],<EOL>sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>ax_rolling_returns_log = plt.subplot(gs[i, :],<EOL>sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>ax_returns = plt.subplot(gs[i, :],<EOL>sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>if benchmark_rets is not None:<EOL><INDENT>ax_rolling_beta = plt.subplot(gs[i, :], sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL><DEDENT>ax_rolling_volatility = plt.subplot(gs[i, :], sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>ax_rolling_sharpe = plt.subplot(gs[i, :], sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>ax_drawdown = plt.subplot(gs[i, :], sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>ax_underwater = plt.subplot(gs[i, :], sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>ax_monthly_heatmap = plt.subplot(gs[i, <NUM_LIT:0>])<EOL>ax_annual_returns = plt.subplot(gs[i, <NUM_LIT:1>])<EOL>ax_monthly_dist = plt.subplot(gs[i, <NUM_LIT:2>])<EOL>i += <NUM_LIT:1><EOL>ax_return_quantiles = plt.subplot(gs[i, :])<EOL>i += <NUM_LIT:1><EOL>plotting.plot_rolling_returns(<EOL>returns,<EOL>factor_returns=benchmark_rets,<EOL>live_start_date=live_start_date,<EOL>cone_std=cone_std,<EOL>ax=ax_rolling_returns)<EOL>ax_rolling_returns.set_title(<EOL>'<STR_LIT>')<EOL>plotting.plot_rolling_returns(<EOL>returns,<EOL>factor_returns=benchmark_rets,<EOL>live_start_date=live_start_date,<EOL>cone_std=None,<EOL>volatility_match=(benchmark_rets is not None),<EOL>legend_loc=None,<EOL>ax=ax_rolling_returns_vol_match)<EOL>ax_rolling_returns_vol_match.set_title(<EOL>'<STR_LIT>')<EOL>plotting.plot_rolling_returns(<EOL>returns,<EOL>factor_returns=benchmark_rets,<EOL>logy=True,<EOL>live_start_date=live_start_date,<EOL>cone_std=cone_std,<EOL>ax=ax_rolling_returns_log)<EOL>ax_rolling_returns_log.set_title(<EOL>'<STR_LIT>')<EOL>plotting.plot_returns(<EOL>returns,<EOL>live_start_date=live_start_date,<EOL>ax=ax_returns,<EOL>)<EOL>ax_returns.set_title(<EOL>'<STR_LIT>')<EOL>if benchmark_rets is not None:<EOL><INDENT>plotting.plot_rolling_beta(<EOL>returns, benchmark_rets, ax=ax_rolling_beta)<EOL><DEDENT>plotting.plot_rolling_volatility(<EOL>returns, factor_returns=benchmark_rets, ax=ax_rolling_volatility)<EOL>plotting.plot_rolling_sharpe(<EOL>returns, ax=ax_rolling_sharpe)<EOL>plotting.plot_drawdown_periods(<EOL>returns, top=<NUM_LIT:5>, ax=ax_drawdown)<EOL>plotting.plot_drawdown_underwater(<EOL>returns=returns, ax=ax_underwater)<EOL>plotting.plot_monthly_returns_heatmap(returns, ax=ax_monthly_heatmap)<EOL>plotting.plot_annual_returns(returns, ax=ax_annual_returns)<EOL>plotting.plot_monthly_returns_dist(returns, ax=ax_monthly_dist)<EOL>plotting.plot_return_quantiles(<EOL>returns,<EOL>live_start_date=live_start_date,<EOL>ax=ax_return_quantiles)<EOL>if bootstrap and (benchmark_rets is not None):<EOL><INDENT>ax_bootstrap = plt.subplot(gs[i, :])<EOL>plotting.plot_perf_stats(returns, benchmark_rets,<EOL>ax=ax_bootstrap)<EOL><DEDENT>elif bootstrap:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>for ax in fig.axes:<EOL><INDENT>plt.setp(ax.get_xticklabels(), visible=True)<EOL><DEDENT>if return_fig:<EOL><INDENT>return fig<EOL><DEDENT>

Generate a number of plots for analyzing a strategy's returns.

- Fetches benchmarks, then creates the plots on a single figure.
- Plots: rolling returns (with cone), rolling beta, rolling sharpe,
    rolling Fama-French risk factors, drawdowns, underwater plot, monthly
    and annual return plots, daily similarity plots,
    and return quantile box plot.
- Will also print the start and end dates of the strategy,
    performance statistics, drawdown periods, and the return range.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in create_full_tear_sheet.
positions : pd.DataFrame, optional
    Daily net position values.
     - See full explanation in create_full_tear_sheet.
transactions : pd.DataFrame, optional
    Executed trade volumes and fill prices.
    - See full explanation in create_full_tear_sheet.
live_start_date : datetime, optional
    The point in time when the strategy began live trading,
    after its backtest period.
cone_std : float, or tuple, optional
    If float, The standard deviation to use for the cone plots.
    If tuple, Tuple of standard deviation values to use for the cone plots
     - The cone is a normal distribution with this standard deviation
         centered around a linear regression.
benchmark_rets : pd.Series, optional
    Daily noncumulative returns of the benchmark.
     - This is in the same style as returns.
bootstrap : boolean, optional
    Whether to perform bootstrap analysis for the performance
    metrics. Takes a few minutes longer.
turnover_denom : str, optional
    Either AGB or portfolio_value, default AGB.
    - See full explanation in txn.get_turnover.
header_rows : dict or OrderedDict, optional
    Extra rows to display at the top of the perf stats table.
return_fig : boolean, optional
    If True, returns the figure that was plotted on.


positions = utils.check_intraday(estimate_intraday, returns,<EOL>positions, transactions)<EOL>if hide_positions:<EOL><INDENT>show_and_plot_top_pos = <NUM_LIT:0><EOL><DEDENT>vertical_sections = <NUM_LIT:7> if sector_mappings is not None else <NUM_LIT:6><EOL>fig = plt.figure(figsize=(<NUM_LIT>, vertical_sections * <NUM_LIT:6>))<EOL>gs = gridspec.GridSpec(vertical_sections, <NUM_LIT:3>, wspace=<NUM_LIT:0.5>, hspace=<NUM_LIT:0.5>)<EOL>ax_exposures = plt.subplot(gs[<NUM_LIT:0>, :])<EOL>ax_top_positions = plt.subplot(gs[<NUM_LIT:1>, :], sharex=ax_exposures)<EOL>ax_max_median_pos = plt.subplot(gs[<NUM_LIT:2>, :], sharex=ax_exposures)<EOL>ax_holdings = plt.subplot(gs[<NUM_LIT:3>, :], sharex=ax_exposures)<EOL>ax_long_short_holdings = plt.subplot(gs[<NUM_LIT:4>, :])<EOL>ax_gross_leverage = plt.subplot(gs[<NUM_LIT:5>, :], sharex=ax_exposures)<EOL>positions_alloc = pos.get_percent_alloc(positions)<EOL>plotting.plot_exposures(returns, positions, ax=ax_exposures)<EOL>plotting.show_and_plot_top_positions(<EOL>returns,<EOL>positions_alloc,<EOL>show_and_plot=show_and_plot_top_pos,<EOL>hide_positions=hide_positions,<EOL>ax=ax_top_positions)<EOL>plotting.plot_max_median_position_concentration(positions,<EOL>ax=ax_max_median_pos)<EOL>plotting.plot_holdings(returns, positions_alloc, ax=ax_holdings)<EOL>plotting.plot_long_short_holdings(returns, positions_alloc,<EOL>ax=ax_long_short_holdings)<EOL>plotting.plot_gross_leverage(returns, positions,<EOL>ax=ax_gross_leverage)<EOL>if sector_mappings is not None:<EOL><INDENT>sector_exposures = pos.get_sector_exposures(positions,<EOL>sector_mappings)<EOL>if len(sector_exposures.columns) > <NUM_LIT:1>:<EOL><INDENT>sector_alloc = pos.get_percent_alloc(sector_exposures)<EOL>sector_alloc = sector_alloc.drop('<STR_LIT>', axis='<STR_LIT>')<EOL>ax_sector_alloc = plt.subplot(gs[<NUM_LIT:6>, :], sharex=ax_exposures)<EOL>plotting.plot_sector_allocations(returns, sector_alloc,<EOL>ax=ax_sector_alloc)<EOL><DEDENT><DEDENT>for ax in fig.axes:<EOL><INDENT>plt.setp(ax.get_xticklabels(), visible=True)<EOL><DEDENT>if return_fig:<EOL><INDENT>return fig<EOL><DEDENT>

Generate a number of plots for analyzing a
strategy's positions and holdings.

- Plots: gross leverage, exposures, top positions, and holdings.
- Will also print the top positions held.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in create_full_tear_sheet.
positions : pd.DataFrame
    Daily net position values.
     - See full explanation in create_full_tear_sheet.
show_and_plot_top_pos : int, optional
    By default, this is 2, and both prints and plots the
    top 10 positions.
    If this is 0, it will only plot; if 1, it will only print.
hide_positions : bool, optional
    If True, will not output any symbol names.
    Overrides show_and_plot_top_pos to 0 to suppress text output.
return_fig : boolean, optional
    If True, returns the figure that was plotted on.
sector_mappings : dict or pd.Series, optional
    Security identifier to sector mapping.
    Security ids as keys, sectors as values.
transactions : pd.DataFrame, optional
    Prices and amounts of executed trades. One row per trade.
     - See full explanation in create_full_tear_sheet.
estimate_intraday: boolean or str, optional
    Approximate returns for intraday strategies.
    See description in create_full_tear_sheet.