Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
r"""An object to expose some numerical methods and plotting tools.
A ``curve`` object takes any two dimensional dataset and its uncertainty (both in the :math:`x` and :math:`y` direction). Each data set includes :math:`x` and :math:`y` data and uncertainty associated with that, as well as a name and a data shape designation (whether this is smooth data or binned).
There exist three ways to add uncertainty to the measurements. The first is to define an array or list of values that define the absolute uncertainty at each ``x``. The second is to define a list of tuples that define the lower and upper absolute uncertainty at each ``x``, respectively. The final way is to define a two dimensional array, where the first row is the lower absolute uncertainty at each ``x``, and the second row is the upper absolute uncertainty at each ``x``.
:param list-like x: The ordinate data of the curve :param list-like u_x: The uncertainty in the ordinate data of the curve :param list-like y: The abscissa data of the curve :param list-like u_y: The uncertainty in the abscissa data of the curve :param str name: The name of the data set, used for plotting, etc. :param str data: The type of data, whether 'smooth' or 'binned'. This parameter affects the interpolation (and in turn, many other functions) by determining what the value is between data points. For smooth data, linear interpolation is enacted to find values between points, for binned data, constant interpolation is used. :return: the ``curve`` object. :rtype: curve """
########################################################################### # Data Input - tests in tests/test_data_input.py ########################################################################### # assert that x and y are 1d lists of same size else: else: else: else:
r"""Rename the current curve."""
r"""Sort the list depending on the :math:`x` coordinate.
``sort()`` sorts all of the data input to the curve so that it is ordered from decreasing :math:`x` to increasing :math:`x`.
:return: the ``curve`` object, but it has been sorted in-place. :rtype: curve """ else: else: else: else:
"""Add data to the already populated x and y.
:param list-like x: The ordinate data to add to the already populated curve object. :param list-like y: The abscissa data to add to the already populated curve object. :param list-like u_x: The uncertainty in the ordinate data to be added. :param list-like u_y: The uncertainty in the abscissa data to be added. :return: A curve object with the added data, fully sorted. :rtype: curve """
r"""Perform a deep copy of the curve and passes it out to another ``curve`` object so that it can be manipulated out-of-place.
:return: a copy of the ``curve`` object calling the function :rtype: curve """ else: name=newname)
replace=None): r"""Crop the data within the specified rectange.
``crop(y_min, y_max, x_min, x_max, replace)`` will find any data points that fall outside of the rectangle with corners at ``(x_min, y_min)`` to ``(x_max, y_max)`` and replace it with the value specified as ``return``.
:param float x_min: A value for which any values with :math:`x<x_{min}` will be replaced with the value ``replace``. :param float x_max: A value for which any values with :math:`x>x_{max}` will be replaced with the value ``replace``. :param float y_min: A value for which any values with :math:`y<y_{min}` will be replaced with the value ``replace``. :param float y_max: A value for which any values with :math:`y>y_{max}` will be replaced with the value ``replace``. :param float replace: The value to replace any value outside of the rectangle with. Default ``None``. :return: the cropped ``curve`` object """
r"""Find the first point with y value above the given value y.
:param float y_min: the comparitor value :returns: the tuple (x, y) which is the first in ``x`` space where ``y`` is above the given y_min """
r"""Redistribute the curve along a new set of x values.
``rebin(x)`` takes a list-like input of new points on the ordinate and redistributes the abscissa so that the x values are only on those points. For continuous/smooth data, this simply interpolates the previous curve to the new points. For binned data, this integrates between left bin points and redistributes the fraction of data between those points.
:param list x: the new x values to redistribute the curve. If binned, this indicates the left edge :returns: the curve object with redistributed values """ # assume the last bin has the same width for _x, bw in zip(x, bin_widths)]
r"""Remove all but every ``R`` th point in the curve.
:param int R: An integer value telling how often to save a point. :param int length: *Alternate*, an integer telling how big you want the final array. :return: the decimated ``curve`` object """
########################################################################### # Data Retrieving and Interpolation - tests in tests/test_data_interp.py ########################################################################### """Check if a point is within the range of data.
:param float x: The data point to check if it is in the range of the existing curve data. :return: Whether or not the data is in the range of the curve data. :rtype: bool """ else:
""" ``at(x)`` finds a value at x.
``at(x)`` uses interpolation or extrapolation to determine the value of the curve at a given point, :math:`x`. The function first checks if :math:`x` is in the range of the curve. If it is in the range, the function calls :py:func:`interpolate` to determine the value. If it is not in the range, the function calls :py:func:`extrapolate` to determine the value.
:param float x: The coordinate of which the value is desired. :returns: the value of the curve at point :math:`x` :rtype: float """ else: else: # if it is in the data range, interpolate else: # if it is not in the data range, extrapolate else:
r""" ``u_y_at(x)`` finds a the uncertainty of a value at x.
``u_y_at(x)`` uses interpolation or extrapolation to determine the uncertainty of the value of the curve at a given point, :math:`x`. The function first checks if :math:`x` is in the range of the curve. If it is in the range, the function calls :py:func:`interpolate` and :py:func:`propogate_error` to find the uncertainty of the point. If it is not in the range, the function calls :py:func:`extrapolate` and :py:func:`propogate_error` to determine the value.
We use the following equation to perform the interpolation:
.. math::
y\left(x\right) = \left(x-x_{\downarrow}\right) \frac{\left(y_{\uparrow}-y_{\downarrow}\right)} {\left(x_{\uparrow}-x_{\downarrow}\right)}
And using the *error propagation formula* from (Knoll, 1999), which is
.. math::
\sigma_{\zeta}^{2} = \left(\frac{\partial\zeta}{\partial x}\right)^{2}\sigma_{x}^{2} + \left(\frac{\partial\zeta}{\partial y}\right)^{2}\sigma_{y}^{2}
for a derived value :math:`\zeta`, we can apply this to interpolation and get:
.. math::
\sigma_{y}^{2} = \left(\frac{\partial y}{\partial x}\right)^{2}\sigma_{x}^{2} + \left(\frac{\partial y}{\partial x_{\downarrow}}\right)^{2} \sigma_{x_{\downarrow}}^{2} + \left(\frac{\partial y}{\partial x_{\uparrow}}\right)^{2} \sigma_{x_{\uparrow}}^{2} + \left(\frac{\partial y}{\partial y_{\downarrow}}\right)^{2} \sigma_{y_{\downarrow}}^{2} + \left(\frac{\partial y}{\partial y_{\uparrow}}\right)^{2} \sigma_{y_{\uparrow}}^{2}
and, performing the derivatives, we can get:
.. math::
\sigma_{y}^{2}=\left(\frac{\left(y_{\uparrow}-y_{\downarrow}\right)} {\left(x_{\uparrow}-x_{\downarrow}\right)}\right)^{2} \sigma_{x}^{2}+\left(-\left(x-x_{\uparrow}\right) \frac{\left(y_{\uparrow}-y_{\downarrow}\right)} {\left(x_{\uparrow}-x_{\downarrow}\right)^{2}}\right)^{2} \sigma_{x_{\downarrow}}^{2}+\left(\left(x-x_{\downarrow}\right) \frac{\left(y_{\uparrow}-y_{\downarrow}\right)}{ \left(x_{\uparrow}-x_{\downarrow}\right)^{2}}\right)^{2} \sigma_{x_{\uparrow}}^{2}\\+\left(-\frac{\left(x-x_{\downarrow} \right)}{\left(x_{\uparrow}-x_{\downarrow}\right)}\right)^{2} \sigma_{y_{\downarrow}}^{2}+\left(\frac{ \left(x-x_{\downarrow}\right)}{\left(x_{\uparrow}-x_{\downarrow} \right)}\right)^{2}\sigma_{y_{\uparrow}}^{2}
Finally, if we take :math:`m=\frac{\left(y_{\uparrow}-y_{\downarrow} \right)}{\left(x_{\uparrow}-x_{\downarrow}\right)}`, and :math:`\Delta\xi=\frac{\left(x-x_{\downarrow}\right)}{\left(x_{ \uparrow}-x_{\downarrow}\right)}`, we can get:
.. math::
\sigma_{y}^{2}=m^{2}\left[\sigma_{x}^{2}+ \sigma_{y_{\downarrow}}^{2}+\sigma_{y_{\uparrow}}^{2}+ \Delta\xi^{2}\left(\sigma_{x_{\downarrow}}^{2}+ \sigma_{x_{\uparrow}}^{2}\right)\right]
and the square root of that is the uncertainty.
.. math::
\sigma_{y}=m\sqrt{\sigma_{x}^{2}+\sigma_{y_{\downarrow}}^{2}+ \sigma_{y_{\uparrow}}^{2}+\Delta\xi^{2}\left( \sigma_{x_{\downarrow}}^{2}+\sigma_{x_{\uparrow}}^{2}\right)}
Note that if an uncertainty in x is not supplied, that the first term will go to zero, giving
.. math::
\require{cancel} \sigma_{y}=m\sqrt{\cancel{\sigma_{x}^{2}} +\sigma_{y_{\downarrow}}^{2}+ \sigma_{y_{\uparrow}}^{2}+\Delta\xi^{2}\left( \sigma_{x_{\downarrow}}^{2}+\sigma_{x_{\uparrow}}^{2}\right)}
:param float x: The coordinate of which the value is desired. :param float dx: *Optional* The uncertainty in the x coordinate requested, given in the above equations as :math:`\sigma_{x}`. :returns: :math:`\sigma_{y}`, the uncertainty of the value of the curve at point :math:`x` :rtype: float """ else: # if it is in the data range, interpolate dxi**2. * (uxi1**2. + uxi2**2.)) else: # if it is not in the data range, extrapolate # find the uncertainty extrapolated
r""" ``find(y)`` finds values of :math:`x` that have value :math:`y`
This function takes a parameter :math:`y` and finds all of the ordinate coordinates that have that value. Basically, this is a root-finding problem, but since we have a linear interpolation, the actual root-finding is trivial. The function first finds all intervals in the dataset that include the value :math:`y`, and then solves the interpolation to find those :math:`x` values according to
.. math::
x=\left(y-y_{\downarrow}\right)\frac{\left(x_{\uparrow} -x_{\downarrow}\right)}{\left(y_{\uparrow}-y_{\downarrow}\right)} +x_{\downarrow}
:param float y: the value which ordinate values are desired :return: a list of :math:`x` that have value :math:`y` :rtype: list """ # take the entire list of y's and subtract the value. those intervals # where the sign changes are where the function crosses the value # find where the sign change is # using those intervals, create y_0s and y_1s # generate an array by solving the point slope form equation * (y - y_left[i]) + x_left[i] # return all of those intervals
r""" ``interpolate(x)`` finds the value of a point in the curve range.
The function uses linear interpolation to find the value of a point in the range of the curve data. First, it uses :py:func:`find_nearest_down` and :py:func:`find_nearest_up` to find the two points comprising the interval which :math:`x` exists in. Then, it casts the linear interpolation as a line in point slope form and solves
.. math::
y=\frac{\left(y_{1}-y_{0}\right)}{\left(x_{1}-x_{0}\right)} \left(x-x_{0}\right)+y_{0}
:param float x: The coordinate of the desired value. :return: the value of the curve at :math:`x` :rtype: float """ # if not, we have to do linear interpolation # find closest value below # find the closest value above # find the percentage of x distance between # find the slope # find the y value
r""" ``extrapolate(x)`` finds value of a point out of the curve range.
The function uses linear extrapolation to find the value of a point without the range of the already existing curve. First, it determines whether the requested point is above or below the existing data. Then, it uses :py:func:`find_nearest_down` or :py:func:`find_nearest_up` to find the nearest point. Then it uses :py:func:`find_nearest_down` or :py:func:`find_nearest_up` to find the second nearest point. Finally, it solves the following equation to determine the value
.. math::
y=\frac{\left(y_{\downarrow}-y_{\downarrow \downarrow} \right)}{\left(x_{\downarrow}-x_{\downarrow \downarrow}\right)} \left(x-x_{\downarrow}\right)+y_{\downarrow}
:param float x: the ordinate of the value requested :returns: the value of the curve at point :math:`x` :rtype: float """ # find whether the point is above or below # now find the slope # find the y change between closest point and new point # find the new point
r""" ``find_nearest_down(x)`` will find the actual data point that is closest in negative ``x``-distance to the data point ``x`` passed to the function.
:param float x: The data point ``x`` which to find the closest value below. :param bool error: If true, the u_x and u_y will be returned at that point, even if they are ``None``. :return: a tuple containing the ``x`` and ``y`` value of the data point immediately below in ``x`` value to the value passed to the function, optionally containing the ``u_x`` and ``u_y`` value. """ else:
r""" ``find_nearest_up(x, error=False)`` will find the actual data point that is closest in positive ``x``-distance to the data point ``x`` passed to the function.
:param float x: The data point ``x`` which to find the closest value above. :param bool error: If true, the u_x and u_y will be returned at that point, even if they are ``None``. :return: a tuple containing the ``x`` and ``y`` value of the data point immediately above in ``x`` value to the value passed to the function, optionally containing the ``u_x`` and ``u_y`` value. :rtype: tuple """ else:
r""" ``average()`` will find the average ``y``-value across the entire range.
:param float xmin: The lower bound of ``x``-value to include in the average. Default: ``x.min()`` :param float xmax: The upper bound of ``x``-value to include in the average. Default: ``x.max()`` :return: A float value equal to
.. math::
\bar{y} = \frac{\int_{x_{min}}^{x_{max}} y dx} {\int_{x_{min}}^{x_{max}} dx}
:rtype: float """ / (xmax - xmin)
def round_to_amt(num, amt): r""" ``round_to_amt`` is a static method that round a number to an arbitrary interval
Given a number ``num`` such as :math:`1.2` and an amount ``amt`` such as :math:`0.25`, ``round_to_amt`` would return :math:`1.20` because that is the closest value downward on a :math:`0.25` wide grid.
:param float num: the number to be rounded. :param float amt: the amount to round the number to. :returns: the number after it has been rounded. """
r""" ``rolling_avg(bin_width)`` redistributes the data on a certain bin width, propogating the error needed.
If we have data in an array such as
.. math::
\left[\begin{array}{c} \vec{x}\\ \vec{y} \end{array}\right]=\left[\begin{array}{cccc} 0.1 & 0.75 & 1.75 & 1.9\\ 1.0 & 2.0 & 3.0 & 4.0 \end{array}\right]
and we want to see the data only on integer bins, we will return
.. math::
\left[\begin{array}{c} \vec{x}\\ \vec{y} \end{array}\right]=\left[\begin{array}{cc} 0.0 & 2.0\\ 1.5 & 3.5 \end{array}\right]
This function will also return the uncertainty in each bin, taking into account both the uncertainty of each value in the bin, as well as the uncertainty caused by standard deviation within the bin itself. This can be expressed by
.. math::
\left[\begin{array}{c} \vec{x}\\ \vec{y}\\ \vec{u}_{x}\\ \vec{u}_{y} \end{array}\right]=\left[\begin{array}{c} \frac{\sum_{x\text{ in bin}}x}{N_{x}}\\ \frac{\sum_{x\text{ in bin}}y}{N_{y}}\\ \frac{\sum_{x\text{ in bin}}\sqrt{ \left(\frac{\text{bin width}}{2}\right)^{2} +\text{mean}\left(\sigma_{x}\right)^{2}}}{N_{x}}\\ \frac{\sum_{x\text{ in bin}}\sqrt{\sigma_{y}^{2} +stdev_{y}^{2}}}{N_{x}} \end{array}\right]
:param float bin_width: The width in which the redistribution will happen. :rtype: The redistributed curve. """ # find the start bin (round the minimum value to the next lowest bin) # then, for everything in a certain bin: bin_width): # average to find the mean if x >= left and x < left + bin_width] if x >= left and x < left + bin_width] if x >= left and x < left + bin_width] # determine the standard deviation # propagate the uncertainty and add the standard deviation else: (np.mean(u_left))**2) else: # add to new distribution
########################################################################### # Data Integration and Normalization - tests in tests/test_data_integ.py ########################################################################### r""" ``integrate`` integrates under the curve.
``integrate`` will integrate under the given curve, providing the result to :math:`\int_{x_{min}}^{x_{max}}`. ``x_min`` and ``x_max`` can be provided to change the range of integration. ``quad`` can also be provided to change the quadrature, but the only quadrature currently supported is ``'lin'`` which uses trapezoidal rule to integrate the curve.
:param float x_min: *Optional* the bottom of the range to be integrated. :param float x_max: *Optional* the top of the range to be integrated. :param str quad: *Optional* the "quadrature" to be used for numerical integration. :returns: the result of the integration. """ else:
r""" ``bin_int`` integrates a bar chart.
``bin_int`` is a convenience function used through the class when calling ``integrate``. It integrates for curves that have the ``.data`` property set to ``'binned'``. It does this simply by summing the bin width and bin heights, such that
.. math::
\int_{x_{min}}^{x_{max}} \approx \sum_{i=1,\dots}^{N} \Delta x \cdot y
Note that this function assumes that the last bin has the same bin width as the penultimate bin width. This could be remedied in certain ways, but I'm not sure which to choose yet.
:param float x_min: *Optional* the bottom of the range to be integrated. :param float x_max: *Optional* the top of the range to be integrated. :returns: the result of the integration. """ # assume the last bin has the same width # for each bin, find what fraction is within the range - np.nanmax([_x, x_min])])# / bw else:
r""" ``derivative(x)`` takes the derivative at point :math:`x`.
``derivative(x)`` takes the derivative at point provided ``x``, using a surrounding increment of :math:`\varepsilon`, provided by ``epsilon``. ``epsilon`` has a default value of :math:`\min \frac{\Delta x}{100}`, but you can specify this smaller if your points are closer. Because we're currently only using linear integration, this won't change a thing as long as its smaller than the change in your ordinate variable.
:param float x: The ordinate to take the derivative at. :param float epsilon: The :math:`\Delta x` around the point at :math:`x` used to calculate the derivative. :returns: the derivative at point ``x`` """
r""" ``trapezoidal()`` uses the trapezoidal rule to integrate the curve.
``trapezoidal(x_min, x_max)`` integrates the curve using the trapezoidal rule, i.e.
.. math::
\int_{x_{min}}^{x_{max}}y dx \approx \sum_{i=1,\dots}^{N} \left(x_{\uparrow} - x_{\downarrow}\right) \cdot \left( \frac{y_{\downarrow} + y_{uparrow}}{2}\right)
Right now, it uses :math:`10 \times N_{x}` points to integrate between values, but that is completely arbitrary and I'll be looking into changing this. There is also the ability to pass ``quad`` to the function as ``'log'`` **CURRENTLY FAILING** and it will calculate the trapezoids in logarithmic space, giving exact integrals for exponential functions.
:param float x_min: the left bound of integration. :param float x_max: the right bound of integration. :param str quad: the type of quadrature to use, currently only ``'lin'`` or ``'log'`` :returns: the integral of the curve from trapezoidal rule. """ # then, between each x, we find the value there ((x_sub[i+1] - x_sub[i]) * (y_sub[i+1] - y_sub[i])) / 2. for i in np.arange(0, len(x_sub) - 1)]) # then, we do the trapezoidal rule
r""" ``normalize()`` normalizes the entire curve to be normalized.
**Caution! This will change all of the y values in the entire curve!**
Normalize will take the data of the curve (optionally just the data between ``xmin`` and ``xmax``) and normalize it based on the option given by ``norm``. The options for norm are ``max`` and ``int``. For a ``max`` normalization, first the function finds the maximum value of the curve in the range of the :math:`x` data and adjusts all :math:`y` values according to
.. math::
y = \frac{y}{y_{max}}
For an ``int`` normalization, the function adjusts all :math:`y` values according to
.. math::
y=\frac{y}{\int_{x_{min}}^{x_{max}}y \left( x \right) dx}
:param float xmin: optional argument giving the lower bound of the integral in an integral normalization or the lower bound in which to find the max in a max normalization :param float xmax: optional argument giving the upper bound of the integral in an integral normalization or the upper bound in which to find the max in a max normalization :param str norm: a string of 'max' or 'int' (default 'max') which defines which of the two types of normalization to perform :return: None """
########################################################################### # Curve Arithmetic - tests in tests/test_curve_arithmetic.py ########################################################################### r""" ``add(value)`` adds a value to the curve.
The ``add`` function will add the provided value to the curve in place.
:param number right: the number or curve to be added to the curve :returns: ``curve`` with added :math:`y` values """ # first trim the curves to the same range (smallest) # and resample these to the most points we can get
else:
else:
r""" ``multiply(mult)`` multiplies the curve by a value.
The ``multiply`` function will multiply the curve by the value passed to it in ``mult``. This value can be an array with the same size or a scalar of type integer or float. Note that this will only change the value (``y``) of the function, not the abscissa (``x``).
:param number mult: the number to multiply the curve by :returns: the curve after multiplication """
r""" ``curve_mult(curve)`` multiplies two curves together.
This is a helper class, usually only called through ``curve.multiply``, or using the ``*`` operator. The class first takes a unique set of ``x`` points that are within the range of both curves. Then, it multiplies those two together.
:param number mult: the curve to multiply by :returns: the left ``curve`` object, with the values multipled in place. """
else:
r""" ``divide(denominator)`` divides a curve by a value.
The ``divide`` function will divide the curve by the value provided in ``numerator``. Note that this will only change the value (``y``) of the function, not the abscissa (``x``).
:param number denominator: the number to divide the curve by. :returns: none """
r""" ``divide_by(numerator)`` divides a value by the curve.
The ``divide`` function will divide the value provided in ``numerator`` by the values in the curve. Note that this will only change the value (``y``) of the function, not the abscissa (``x``).
:param number numerator: the number to be divided by the curve. :returns: none """
r""" ``curve_div(curve)`` divides one curve by another.
This is a helper class, usually only called through ``curve.divide``, or using the ``/`` operator. The class first takes a unique set of ``x`` points that are within the range of both curves. Then, it divides the ``y`` values by the other.
:param number right: the curve to divide by. :returns: the left ``curve`` object, with the values divided in place. """
else:
else:
""" a convienience class to add data to the already populated x and y.
:param list-like x: The ordinate data to add to the already populated curve object. :param list-like y: The abscissa data to add to the already populated curve object. :return: A curve object with the added data, fully sorted. :rtype: curve """ else: else:
########################################################################### # Analysis - tests in tests/test_analysis.py ########################################################################### r""" ``fft`` finds the fft of the curve
``fft`` assumes that the values contained in ``curve.x`` are time values and are evenly distributed, and returns the fft of the values in ``curve.y`` versus ``curve.x``.
:param bool pos: if ``True``, returns only the positive frequency components :param bool curve: if ``True``, returns the data as a curve :returns: ``f`` the array of frequencies and ``a`` the amplitude of of components present at that frequency """ # use scipy's fft to find the negative and positive fft else: # determine the number of samples for determination of the nyquist # frequency # Find the period # distribute frequencies up to the nyquist frequency # return only the positive frequency components else: # distribute frequencies up to the nyquist frequency # return only the positive frequency components else:
else:
r""" ``find_peaks`` finds the peaks in the curve """
########################################################################### # Curve Fitting - tests in tests/test_curve_fitting.py ########################################################################### r""" ``fit_exp`` fits an exponential to the function.
``fit_exp`` fits an exponential of form :math:`y=B\cdot \exp \left( \alpha\cdot x\right)` to the curve, returning the parameters :math:`\left(\alpha, B\right)` as a tuple.
:returns: the tuple :math:`\left(\alpha, B\right)` """
r""" ``fit_lin`` fits a linear function to the curve.
``fit_lin`` fits a linear function of form :math:`y=m\cdot x + b` to the curve, returning the parameters :math:`\left(m, b\right)` as a tuple.
:returns: the tuple :math:`\left(m, b\right)` """
r""" ``fit_gen`` fits a general function to the curve.
``fit_gen`` fits a general function to the curve. The general function is a python function that takes a parameters and an ordinate variable, ``x`` and returns the value of the function at that point, ``y``. The function must have the prototype ``def func(x, alpha, beta, ...):``. Then, the coefficients are returned as a tuple.
:returns: the coefficients to the general function """ sigma=u_y, absolute_sigma=True)
r""" ``fit_gauss`` fits a gaussian function to the curve.
``fit_gauss`` fits a gaussian function of form :math:`y=\alpha \exp \left[ -\frac{\left(x - \mu\right)^{2}}{2 \sigma^{2}}\right]` to the curve, returning the parameters :math:`\left(\alpha, \mu, \sigma\right)` as a tuple.
:returns: the tuple :math:`\left(\alpha, \mu, \sigma\right)` """
r""" ``fit_gauss`` fits a gaussian function to the curve.
``fit_gauss`` fits a gaussian function of form :math:`y=\alpha \exp \left[ -\frac{\left(x - \mu\right)^{2}}{2 \sigma^{2}}\right]` to the curve, returning the parameters :math:`\left(\alpha, \mu, \sigma\right)` as a tuple.
:returns: the tuple :math:`\left(\alpha, \mu, \sigma\right)` """ def pow_fun(x, a, n):
r""" ``fit_at`` returns the point at coordinate :math:`x` from a previously fitted curve.
:param float x: the ordinate variable for which the fit value is needed. """ else: return self.fun(x,*self.coeffs)
r""" ``fit_square`` fits a function of order 2 to the curve.
``fit_square`` fits a quadratic function of form :math:`y=a x^{2} + b x + c` to the curve, returning the parameters :math:`\left(a, b, c\right)` as a tuple.
:returns: the tuple :math:`\left(a, b, c\right)` """ return np.polyval(coeffs,x)
r""" ``fit_cube`` fits a function of order 3 to the curve.
``fit_cube`` fits a cubic function of form :math:`y=a x^{3} + b x^{2} + c x + d` to the curve, returning the parameters :math:`\left(a, b, c, d\right)` as a tuple.
:returns: the tuple :math:`\left(a, b, c, d\right)` """
r"""Return the fit as a ``curve``.""" self.fitx = np.linspace(xmin, xmax, num=1000) self.fity = self.fit_at(self.fitx) name = self.name + 'fit' return curve(self.fitx, self.fity, name)
########################################################################### # Curve Plotting - no tests currently ########################################################################### def plot(self, x=None, y=None, addto=None, # pragma: no cover linestyle=None, linecolor='black', # pragma: no cover markerstyle=None, # pragma: no cover yy=False, xerr=None, yerr=None, # pragma: no cover legend=True, env='plot', axes=None, # pragma: no cover polar=False, xx=False, alpha=1.0, **kwargs): # pragma: no cover if addto is None: plot = ahp.pyg2d(env=env, polar=polar); else: plot = addto; if xerr is None: xerr = self.u_x if yerr is None: yerr = self.u_y if x is None and y is None: x = self.x y = self.y if self.data == 'binned': # plot the bins # setup a matix # preallocate this later *********************************** plot_x = np.array([]); plot_y = np.array([]); # plot the thick bars for i in np.arange(0,len(x)-1): plot_x = np.append(plot_x,x[i]); plot_y = np.append(plot_y,y[i]); plot_x = np.append(plot_x,x[i+1]); plot_y = np.append(plot_y,y[i]); plot_x = np.append(plot_x,np.nan); plot_y = np.append(plot_y,np.nan); # self.binned_data_x = plot_x # self.binned_data_y = plot_y if yy: fun = plot.add_line_yy elif xx: fun = plot.add_line_xx else: fun = plot.add_line fun(plot_x, plot_y, name=self.name, linewidth=2.0, linecolor=linecolor, linestyle='-', markerstyle=markerstyle, legend=legend, alpha=alpha, **kwargs) conn_x = np.array([]) conn_y = np.array([]) for i in np.arange(1,len(x)): conn_x = np.append(conn_x,x[i]) conn_y = np.append(conn_y,y[i-1]) conn_x = np.append(conn_x,x[i]) conn_y = np.append(conn_y,y[i]) conn_x = np.append(conn_x,np.nan) conn_y = np.append(conn_y,np.nan) fun(conn_x, conn_y, name=self.name+'connectors', linewidth=0.1, linestyle='-', linecolor=linecolor, markerstyle=markerstyle, gend=legend, alpha=alpha, **kwargs) plot.markers_off() plot.lines_on() elif self.data is 'smooth': if yy is False and xx is False: plot.add_line(x, y, xerr=self.u_x, yerr=self.u_y, name=self.name, linestyle=linestyle, linecolor=linecolor, markerstyle=markerstyle, axes=axes, legend=legend, alpha=alpha, **kwargs) elif yy is True and xx is False: plot.add_line_yy(x, y, xerr=self.u_x, yerr=self.u_y, name=self.name,linestyle=linestyle, linecolor=linecolor, markerstyle=markerstyle, axes=axes, legend=legend, alpha=alpha, **kwargs) elif xx is True and yy is False: plot.add_line_xx(x, y, xerr=self.u_x, yerr=self.u_y, name=self.name,linestyle=linestyle, linecolor=linecolor, markerstyle=markerstyle, axes=axes, legend=legend, alpha=alpha, **kwargs) return plot
def plot_fit(self, xmin=None, xmax=None, addto=None, # pragma: no cover linestyle=None, linecolor='black', # pragma: no cover name=None, axes=None): # pragma: no cover if addto is None: plot = ahp.pyg2d() else: plot = addto if xmin is None: xmin = self.x.min() if xmax is None: xmax = self.x.max() self.fitx = np.linspace(xmin, xmax, num=1000) self.fity = self.fit_at(self.fitx) if name is None: name = self.name + 'fit' plot.add_line(self.fitx, self.fity, name=name, linestyle=linestyle, linecolor=linecolor, axes=axes) plot.fit_lines_on() plot.fit_markers_off() return plot |