diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..2b3d2bfc8e3685f1e6f5d0911db82259ec0e726c --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,362 @@ +# -*- coding: utf-8 -*- +# +# evapy_4s documentation build configuration file, created by +# sphinx-quickstart on Sat Jul 02 14:36:14 2016. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys +# sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath('..')) +import datetime + +import pkg_resources + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.napoleon", + "sphinx.ext.autosummary", + "sphinx.ext.doctest", + "sphinx.ext.intersphinx", + "sphinx.ext.todo", + "sphinx.ext.coverage", + "sphinx.ext.viewcode", + "sphinx.ext.mathjax", + #'sphinx.ext.githubpages', +] + +# Napoleon settings +napoleon_google_docstring = False +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = False +napoleon_use_rtype = False + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = ".rst" + +# The encoding of source files. +# +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = "evapy_4s" +copyright = "{}, 4Subsea".format(datetime.datetime.now().year) +author = "4Subsea" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = pkg_resources.get_distribution(project).version +# The full version, including alpha/beta/rc tags. +release = version + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = "en" + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# +# today = '' +# +# Else, today_fmt is used as the format for a strftime call. +# +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", "**.ipynb_checkpoints"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = "sphinx_rtd_theme" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. +# " v documentation" by default. +# +# html_title = u'evapy v0.1.0' + +# A shorter title for the navigation bar. Default is the same as html_title. +# +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# +# html_logo = None + +# The name of an image file (relative to this directory) to use as a favicon of +# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +# html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# +# html_extra_path = [] + +# If not None, a 'Last updated on:' timestamp is inserted at every page +# bottom, using the given strftime format. +# The empty string is equivalent to '%b %d, %Y'. +# +# html_last_updated_fmt = None + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# +# html_additional_pages = {} + +# If false, no module index is generated. +# +# html_domain_indices = True + +# If false, no index is generated. +# +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' +# +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# 'ja' uses this config value. +# 'zh' user can custom change `jieba` dictionary path. +# +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "evapy4sdoc" + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, "evapy_4s.tex", "evapy_4s Documentation", "4Subsea", "manual"), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# +# latex_use_parts = False + +# If true, show page references after internal links. +# +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# +# latex_appendices = [] + +# If false, no module index is generated. +# +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [(master_doc, "evapy_4s", "evapy_4s Documentation", [author], 1)] + +# If true, show URL addresses after external links. +# +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "evapy_4s", + "evapy_4s Documentation", + author, + "evapy_4s", + "One line description of project.", + "Miscellaneous", + ), +] + +# Documents to append as an appendix to all manuals. +# +# texinfo_appendices = [] + +# If false, no module index is generated. +# +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {'': ('https://docs.python.org/', None)} diff --git a/evapy_4s/__init__.py b/evapy_4s/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2db78c635b5091df5adacc5f1619068c70d74abc --- /dev/null +++ b/evapy_4s/__init__.py @@ -0,0 +1,2 @@ +from . import evstats +from . import distributions diff --git a/evapy_4s/_continuous_distns.py b/evapy_4s/_continuous_distns.py new file mode 100644 index 0000000000000000000000000000000000000000..77d7544f53ac45103473f96190a5b099fa97e95e --- /dev/null +++ b/evapy_4s/_continuous_distns.py @@ -0,0 +1,281 @@ +''' +The distributions will rely on the `scipy.stats` framework. +Similar to scipy.stats._continous_distns. + +Thanks to all SciPy developers for their great work! +''' + + +from __future__ import division + +from scipy import special +from scipy.stats import rv_continuous +from scipy import optimize + +from numpy import (exp, log, sqrt, pi, inf) + +import numpy as np + +from ._optimize import _residual_error + + +# Special constants +_EULER = 0.577215664901532860606512090082402431042 +_ZETA3 = 1.202056903159594285399738161511449990765 + + +class rayleigh_gen(rv_continuous): + """A Rayleigh continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `rayleigh` is:: + + rayleigh.pdf(x) = x * exp(-x**2/2) + + for ``x >= 0``. + + %(after_notes)s + + %(example)s + + """ + def _pdf(self, x): + return x*exp(-0.5*x**2) + + def _cdf(self, x): + return -special.expm1(-0.5*x**2) + + def _ppf(self, f): + return sqrt(-2*special.log1p(-f)) + + def _sf(self, x): + return exp(-0.5*x**2) + + def _isf(self, s): + return sqrt(-2*log(s)) + + def _stats(self): + val = 4 - pi + return (sqrt(pi/2), val/2, 2*(pi-3)*sqrt(pi)/val**1.5, + 6*pi/val-16/val**2) + + def _entropy(self): + return _EULER/2.0 + 1 - 0.5*log(2) +rayleigh = rayleigh_gen(a=0.0, name="rayleigh") + + +class frechet_r_gen(rv_continuous): + """ + A Frechet right class continuous random variable. + + %(before_notes)s + + See Also + -------- + weibull, weibull_min + + Notes + ----- + The probability density function for `frechet_r` is:: + + frechet_r.pdf(x, c) = c * x**(c-1) * exp(-x**c) + + for ``x > 0``, ``c > 0``. + + `frechet_r` takes ``c`` as a shape parameter. + + %(after_notes)s + + %(example)s + + """ + def _pdf(self, x, c): + return c*x**(c-1)*exp(-x**c) + + def _logpdf(self, x, c): + return log(c) + (c-1)*log(x) - x**c + + def _cdf(self, x, c): + return -special.expm1(-x**c) + + def _ppf(self, f, c): + return (-special.log1p(-f))**(1.0/c) + + def _munp(self, n, c): + return special.gamma(1.0+n*1.0/c) + + def _entropy(self, c): + return -_EULER / c - log(c) + _EULER + 1 +weibull = frechet_r_gen(a=0.0, name='weibull') +weibull_min = frechet_r_gen(a=0.0, name='weibull_min') + + +class gumbel_r_gen(rv_continuous): + """ + A right-skewed Gumbel continuous random variable. + + %(before_notes)s + + See Also + -------- + gumbel, gumbel_max + + Notes + ----- + The probability density function for `gumbel_r` is:: + + gumbel_r.pdf(x) = exp(-(x + exp(-x))) + + The Gumbel distribution is sometimes referred to as a type I Fisher-Tippett + distribution. It is also related to the extreme value distribution, + log-Weibull and Gompertz distributions. + + %(after_notes)s + + %(example)s + + """ + def _pdf(self, x): + return exp(self._logpdf(x)) + + def _logpdf(self, x): + return -x - exp(-x) + + def _cdf(self, x): + return exp(-exp(-x)) + + def _logcdf(self, x): + return -exp(-x) + + def _ppf(self, f): + return -log(-log(f)) + + def _stats(self): + return _EULER, pi*pi/6.0, 12*sqrt(6)/pi**3 * _ZETA3, 12.0/5 + + def _entropy(self): + return _EULER + 1. +gumbel = gumbel_r_gen(name='gumbel') +gumbel_max = gumbel_r_gen(name='gumbel_max') + + +class gen_exp_tail_gen(rv_continuous): + """ + A generalized exponential tail continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `gen_exp_tail` is:: + + gen_exp_tail.pdf(x, c, q) = c*x**(c-1.)*exp(-x**c + log(q)) + + The generelized exponential tail distribution is related to + peak-over-threshold distributions. It assumes a exponentially decreasing + tail and is in the domain of attraction of type I extreme value + distribution. + + The MLE for this distribution do not exist. Thus, ``fit`` method is + overwritten with a least-square procedure. It is also recommended to lock + the location parameter for more robust parameter estimates. + + %(after_notes)s + + %(example)s + + """ + def _pdf(self, x, c, q): + return c*x**(c-1.)*exp(-x**c + log(q)) + + def _logpdf(self, x, c, q): + return log(c) + (c-1)*log(x) - x**c + log(q) + + def _cdf(self, x, c, q): + return -special.expm1(-x**c + log(q)) + + def _logcdf(self, x, c, q): + return special.log1p(-np.exp(-x**c + log(q))) + + def _ppf(self, f, c, q): + return (np.log(q) - special.log1p(-f))**(1./c) + + def _sf(self, x, c, q): + return np.exp(-x**c + np.log(q)) + + def _penalized_nnlf(self, theta, x): + ''' + Method is overwritten to hook into scipy.stats optimization framework + with custom residual error function. ML estimator do not exist. + + ''' + def y_fun(cdf): + return log(1/(1 - cdf)) + + return _residual_error(self, theta, x, y_fun) +genexptail = gen_exp_tail_gen(name='genexptail', a=0.) + + +class acer_o1_gen(rv_continuous): + """ + A generalized Gumbel-like continuous random variable. + + %(before_notes)s + + See Also + -------- + gumbel, gumbel_max + + Notes + ----- + The probability density function for `acer_o1` is:: + + acer_o1.pdf(x, c, qn) = c*qn*x^(c-1)*exp(-exp(-x**c + log(qn))-x**c) + + The generelized Gumbel-like distributions. It assumes a exponentially + decreasing tail and will approach a type I (Gumbel) extreme value + distribution. Note that for c=1 and qn=1 the distribution reduces to the + conventional Gumbel distribution. + + The MLE for this distribution do not exist. Thus, ``fit`` method is + overwritten with a least-square procedure. It is also recommended to lock + the location parameter for more robust parameter estimates. + + %(after_notes)s + + References + ---------- + [1]. Naess et al. + + %(example)s + + """ + def _pdf(self, x, c, qn): + return c*qn*x**(c-1)*exp(-exp(-x**c + log(qn))-x**c) + + def _logpdf(self, x, c, q): + return log(c*q*x**(c-1)) + (-exp(-x**c + log(qn))-x**c) + + def _cdf(self, x, c, qn): + return exp(-exp(-x**c + log(qn))) + + def _logcdf(self, x, c, qn): + return -exp(-x**c + log(qn)) + + def _ppf(self, f, c, qn): + return (-(log(-(log(f))/qn)))**(1/c) + + def _penalized_nnlf(self, theta, x): + ''' + Method is overwritten to hook into scipy.stats optimization framework + with custom residual error function. ML estimator do not exist. + + ''' + def y_fun(cdf): + return log(-1./log(cdf)) + + return _residual_error(self, theta, x, y_fun) +acer_o1 = acer_o1_gen(name='acer_o1') diff --git a/evapy_4s/_optimize.py b/evapy_4s/_optimize.py new file mode 100644 index 0000000000000000000000000000000000000000..3e64173b26e13a4bdc1d1a714130a3c36579df7f --- /dev/null +++ b/evapy_4s/_optimize.py @@ -0,0 +1,59 @@ +''' +Custom optimization routines for distributions where ML estimators perform +poorly or do not exist. +''' + +import numpy as np + + +def _residual_error(self, theta, x, y_fun, **kwargs): + ''' + Return special purspose lsq objective error function to minimize. + Method is overwritten to hook into scipy.stats optimization framework. + + Parameters + ---------- + self : object + Distribution object based on rv_continious + thete : array-like + List of parameters according to target distribution. + y_fun: callable + Function that takes in a y value and tranforms it. + + Keywords + -------- + Not documented + + Returns + ------- + error : float + Return sum of penilized residual error. + + ''' + try: + loc = theta[-2] + scale = theta[-1] + args = tuple(theta[:-2]) + except IndexError: + raise ValueError("Not enough input arguments.") + + if not self._argcheck(*args) or scale <= 0: + return np.inf + + x = np.asarray((x-loc) / scale) + x.sort() + + if np.isneginf(self.a).all() and np.isinf(self.b).all(): + Nbad = 0 + else: + cond0 = (x <= self.a) | (self.b <= x) + Nbad = sum(cond0) + if Nbad > 0: + x = x[~cond0] + + N = len(x) + +# Refactor ecdf out into own code at some point. + f_ecdf = np.array([(i + 1 - 0.3)/(N + 0.4) for i in range(N)]) + error = np.abs(y_fun(f_ecdf) - y_fun(self._cdf(x, *args)))**2. + return np.sum(error) + Nbad * 10000. diff --git a/evapy_4s/distributions.py b/evapy_4s/distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..4141265bca59a08acbcf9e1aedd76f2447f80966 --- /dev/null +++ b/evapy_4s/distributions.py @@ -0,0 +1,4 @@ +from . import _continuous_distns as _distns + +from ._continuous_distns import (rayleigh, weibull, weibull_min, gumbel, + gumbel_max, genexptail, acer_o1) diff --git a/evapy_4s/evstats.py b/evapy_4s/evstats.py new file mode 100644 index 0000000000000000000000000000000000000000..0d2afaf772eb3d252b0f198962fb6beef5f2231c --- /dev/null +++ b/evapy_4s/evstats.py @@ -0,0 +1,119 @@ +import numpy as np + + +def _argrelmax(x): + ''' + Find the relative maxima of 1D time series data. + + Parameters + ---------- + x : array-like + Time series data. + + Returns + ------- + peaks : array-like + Return the True values for all peaks. + ''' + peaks = np.r_[False, x[1:] > x[:-1]] & np.r_[x[:-1] >= x[1:], False] + return peaks + + +def _argupcross(x, x_up): + ''' + Find the cross ups of 1D time series data. + + Parameters + ---------- + x : array-like + Time series data. + x_up : float + Upcrossing value. + + Returns + ------- + zeroups : array-like + Return the True values for all upcrossings. + ''' + zeroups = np.r_[x[1:] > x_up, False] & np.r_[x <= x_up] + return zeroups + + +def argrelmax(x): + ''' + Find the relative maxima of 1D time series data. + + Parameters + ---------- + x : array-like + Time series data. + + Returns + ------- + peaks : array-like + Return the index of all peaks. If no peak is found, the index of the + largest value is returned. + + Notes + ----- + Similar to scipy.signal.argrelmax but significantly faster. + ''' + peaks_bool = _argrelmax(x) + peaks = np.flatnonzero(peaks_bool) + if peaks.size: + return peaks + else: + return np.asarray([np.argmax(x)]) + + +def argupcross(x, x_up=0.): + ''' + Find the upcrossing of 1D time series data. + + Parameters + ---------- + x : array-like + Time series data. + x_up : float, optional + Upcrossing value. Default is 0. + + Returns + ------- + zeroups : array-like + Return the index of all values just before an upcrossing. If no + upcrossings are found, the index of the first value is returned. + ''' + zeroups_bool = _argupcross(x, x_up=x_up) + zeroups = np.flatnonzero(zeroups_bool) + if zeroups.size: + return zeroups + else: + return np.array([0]) + + +def argrelmax_decluster(x, x_up=0.): + ''' + Find the declustred relative maxima of 1D time series data. + + Parameters + ---------- + x : array-like + Time series data. + x_up : float, optional + Upcrossing value. Default is 0. + + Returns + ------- + peaks : array-like + Return the index of largest peaks between two upcrossing. If no peak or + upcrossing pair is found, the index of the largest value is returned. + ''' + zeroups = argupcross(x, x_up) + x_sub = np.split(x, zeroups) + peaks = np.asarray( + [x_len + np.argmax(x) for x_len, x in zip(zeroups, x_sub[1:-1])]) + + if peaks.size: + return peaks + else: + return np.asarray([np.max([np.argmax(x), x_up])]) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_distributions.py b/tests/test_distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..cb532fb14569a6ac75a0a39341a5f56d0a7d1749 --- /dev/null +++ b/tests/test_distributions.py @@ -0,0 +1,155 @@ +import unittest + +import numpy as np + +import evapy_4s.distributions as dist + + +class Test_rayleigh_gen(unittest.TestCase): + def setUp(self): + self.dist = dist._distns.rayleigh_gen() + + def tearDown(self): + pass + + def test_cdf(self): + calculated = self.dist.cdf(2.5, loc=0.5, scale=np.sqrt(2.0)) + expected = -np.expm1(-1.0) + self.assertAlmostEqual(calculated, expected, places=4) + + def test_pdf(self): + calculated = self.dist.pdf(2.5, loc=0.5, scale=np.sqrt(2.0)) + expected = np.exp(-1.0) + self.assertAlmostEqual(calculated, expected, places=4) + + def test_ppf(self): + calculated = self.dist.ppf(0.5, loc=0.5, scale=np.sqrt(2.0)) + expected = 2.0 * np.sqrt(np.log(2.0)) + 0.5 + self.assertAlmostEqual(calculated, expected, places=4) + + def test_instance_rayleigh(self): + calculated = dist.rayleigh.cdf(2.5, loc=0.5, scale=np.sqrt(2.0)) + expected = -np.expm1(-1.0) + self.assertAlmostEqual(calculated, expected, places=4) + + +class Test_frechet_r_gen(unittest.TestCase): + def setUp(self): + self.dist = dist._distns.frechet_r_gen() + + def tearDown(self): + pass + + def test_cdf(self): + calculated = self.dist.cdf(2.5, 2.0, loc=0.5, scale=2.0) + expected = -np.expm1(-1.0) + self.assertAlmostEqual(calculated, expected, places=4) + + def test_pdf(self): + calculated = self.dist.pdf(2.5, 2.0, loc=0.5, scale=2.0) + expected = np.exp(-1.0) + self.assertAlmostEqual(calculated, expected, places=4) + + def test_ppf(self): + calculated = self.dist.ppf(0.5, 2.0, loc=0.5, scale=2.0) + expected = 2.0 * np.sqrt(np.log(2.0)) + 0.5 + self.assertAlmostEqual(calculated, expected, places=4) + + def test_instance_weibull(self): + calculated = dist.weibull.cdf(2.5, 2.0, loc=0.5, scale=2.0) + expected = self.dist.cdf(2.5, 2.0, loc=0.5, scale=2.0) + self.assertAlmostEqual(calculated, expected, places=4) + + def test_instance_weibull_min(self): + calculated = dist.weibull_min.cdf(2.5, 2.0, loc=0.5, scale=2.0) + expected = self.dist.cdf(2.5, 2.0, loc=0.5, scale=2.0) + self.assertAlmostEqual(calculated, expected, places=4) + + +class Test_gumbel_r_gen(unittest.TestCase): + def setUp(self): + self.dist = dist._distns.gumbel_r_gen() + + def tearDown(self): + pass + + def test_cdf(self): + calculated = self.dist.cdf(3.0, loc=1.0, scale=2.0) + expected = np.exp(-np.exp(-1.0)) + self.assertAlmostEqual(calculated, expected, places=4) + + def test_pdf(self): + calculated = self.dist.pdf(3.0, loc=1.0, scale=2.0) + expected = np.exp(-1.0 - np.exp(-1.0)) / 2.0 + self.assertAlmostEqual(calculated, expected, places=4) + + def test_ppf(self): + calculated = self.dist.ppf(0.5, loc=1.0, scale=2.0) + expected = 1.0 - 2.0 * np.log(np.log(2)) + self.assertAlmostEqual(calculated, expected, places=4) + + def test_instance_gumbel(self): + calculated = dist.gumbel.cdf(2.5, loc=0.5, scale=2.0) + expected = self.dist.cdf(2.5, loc=0.5, scale=2.0) + self.assertAlmostEqual(calculated, expected, places=4) + + def test_instance_gumbel_max(self): + calculated = dist.gumbel_max.cdf(2.5, loc=0.5, scale=2.0) + expected = self.dist.cdf(2.5, loc=0.5, scale=2.0) + self.assertAlmostEqual(calculated, expected, places=4) + + +class Test_gen_exp_tail_gen(unittest.TestCase): + def setUp(self): + self.dist = dist._distns.gen_exp_tail_gen() + + def tearDown(self): + pass + + def test_cdf(self): + calculated = self.dist.cdf(2.5, 2.0, 1.0, loc=0.5, scale=2.0) + expected = -np.expm1(-1.0) + self.assertAlmostEqual(calculated, expected, places=4) + + def test_pdf(self): + calculated = self.dist.pdf(2.5, 2.0, 1.0, loc=0.5, scale=2.0) + expected = np.exp(-1.0) + self.assertAlmostEqual(calculated, expected, places=4) + + def test_ppf(self): + calculated = self.dist.ppf(0.5, 2.0, 1.0, loc=0.5, scale=2.0) + expected = 2.0 * np.sqrt(np.log(2.0)) + 0.5 + self.assertAlmostEqual(calculated, expected, places=4) + + def test_instance_gen_exp_tail(self): + calculated = dist.genexptail.cdf(2.5, 2.0, 1.0, loc=0.5, scale=2.0) + expected = self.dist.cdf(2.5, 2.0, 1.0, loc=0.5, scale=2.0) + self.assertAlmostEqual(calculated, expected, places=4) + + +class Test_acer_o1_gen(unittest.TestCase): + def setUp(self): + self.dist = dist._distns.acer_o1_gen() + + def tearDown(self): + pass + + def test_cdf(self): + calculated = self.dist.cdf(3.0, 1.0, 1.0, loc=1.0, scale=2.0) + expected = np.exp(-np.exp(-1.0)) + self.assertAlmostEqual(calculated, expected, places=4) + + def test_pdf(self): + calculated = self.dist.pdf(3.0, 1.0, 1.0, loc=1.0, scale=2.0) + expected = np.exp(-1.0 - np.exp(-1.0)) / 2.0 + self.assertAlmostEqual(calculated, expected, places=4) + + def test_ppf(self): + calculated = self.dist.ppf(0.5, 1.0, 1.0, loc=1.0, scale=2.0) + expected = 1.0 - 2.0 * np.log(np.log(2)) + self.assertAlmostEqual(calculated, expected, places=4) + + def test_instance_acer_o1(self): + calculated = dist.acer_o1.cdf(2.5, 1.0, 1.0, loc=0.5, scale=2.0) + expected = self.dist.cdf(2.5, 1.0, 1.0, loc=0.5, scale=2.0) + self.assertAlmostEqual(calculated, expected, places=4) diff --git a/tests/test_evstats.py b/tests/test_evstats.py new file mode 100644 index 0000000000000000000000000000000000000000..22f2f47277c2631e2329f81c062fc610502119f5 --- /dev/null +++ b/tests/test_evstats.py @@ -0,0 +1,188 @@ +import unittest + +import numpy as np + +from evapy_4s import evstats + + +class Test__argrelmax(unittest.TestCase): + def setUp(self): + pass + + def tearDown(self): + pass + + def test_simple_find(self): + x = np.array([0.0, 1.0, 0.0, -1.0, 0.0, 2.0]) + calculated = evstats._argrelmax(x) + expected = np.array([False, True, False, False, False, False]) + np.testing.assert_array_equal(calculated, expected) + + def test_simple_find_none(self): + x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) + calculated = evstats._argrelmax(x) + expected = np.array([False, False, False, False, False, False]) + np.testing.assert_array_equal(calculated, expected) + + +class Test__argupcross(unittest.TestCase): + def setUp(self): + pass + + def tearDown(self): + pass + + def test_simple_find(self): + x = np.array([0.0, 1.0, -1.0, -2.0, -1.0, 1.0, 0.0]) + calculated = evstats._argupcross(x, x_up=0.0) + expected = np.array([True, False, False, False, True, False, False]) + np.testing.assert_array_equal(calculated, expected) + + def test_simple_find_w_zero(self): + x = np.array([0.0, 1.0, 0.0, -1.0, -2.0, -1.0, 0.0, 1.0, 0.0]) + calculated = evstats._argupcross(x, x_up=0.0) + expected = np.array( + [True, False, False, False, False, False, True, False, False] + ) + np.testing.assert_array_equal(calculated, expected) + + def test_simple_find_w_other(self): + x = np.array([0.0, 1.0, 0.0, -1.0, -2.0, -1.0, 0.0, 1.0, 0.0]) + 2.0 + calculated = evstats._argupcross(x, x_up=2.0) + expected = np.array( + [True, False, False, False, False, False, True, False, False] + ) + np.testing.assert_array_equal(calculated, expected) + + def test_simple_find_none(self): + x = np.array([0.1, 1.0, 2.0, 3.0, 4.0, 5.0]) + calculated = evstats._argupcross(x, x_up=0.0) + expected = np.array([False, False, False, False, False, False]) + np.testing.assert_array_equal(calculated, expected) + + +class Test_argrelmax(unittest.TestCase): + def setUp(self): + pass + + def tearDown(self): + pass + + def test_simple_find(self): + x = np.array([0.0, 1.0, 0.0, -1.0, 0.0, 2.0]) + calculated = evstats.argrelmax(x) + expected = np.array([1]) + np.testing.assert_array_equal(calculated, expected) + + def test_simple_find_repeat(self): + x = np.array([0.0, 1.0, 1.0, 0.0, -1.0, 0.0, 2.0]) + calculated = evstats.argrelmax(x) + expected = np.array([1]) + np.testing.assert_array_equal(calculated, expected) + + def test_simple_find_none(self): + x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) + calculated = evstats.argrelmax(x) + expected = np.array([5]) + np.testing.assert_array_equal(calculated, expected) + + +class Test_argupcross(unittest.TestCase): + def setUp(self): + pass + + def tearDown(self): + pass + + def test_simple_find(self): + x = np.array([-1.0, 1.0, -1.0, -2.0, -1.0, 1.0, 0.0]) + calculated = evstats.argupcross(x, x_up=0.0) + expected = np.array([0.0, 4]) + np.testing.assert_array_equal(calculated, expected) + + def test_simple_find_w_zero(self): + x = np.array([0.0, 1.0, 0.0, -1.0, -2.0, -1.0, 0.0, 1.0, 0.0, 1.0]) + calculated = evstats.argupcross(x, x_up=0.0) + expected = np.array([0, 6, 8]) + np.testing.assert_array_equal(calculated, expected) + + def test_simple_find_touch_below(self): + x = np.array([0.0, -1.0, 0.0, -1.0]) + calculated = evstats.argupcross(x, x_up=0.0) + expected = np.array([0]) + np.testing.assert_array_equal(calculated, expected) + + def test_simple_find_w_other(self): + x = np.array([0.0, 1.0, 0.0, -1.0, -2.0, -1.0, 0.0, 1.0, 0.0]) + 2.0 + calculated = evstats.argupcross(x, x_up=2.0) + expected = np.array([0.0, 6.0]) + np.testing.assert_array_equal(calculated, expected) + + def test_simple_find_none(self): + x = np.array([0.1, 1.0, 2.0, 3.0, 4.0, 5.0]) + calculated = evstats.argupcross(x, x_up=0.0) + expected = np.array([0.0]) + np.testing.assert_array_equal(calculated, expected) + + +class Test_argrelmax_decluster(unittest.TestCase): + def setUp(self): + pass + + def tearDown(self): + pass + + def test_simple_find(self): + x = np.array([0.0, 1.0, 0.0, -1.0, 0.0, 2.0]) + calculated = evstats.argrelmax_decluster(x, x_up=0.0) + expected = np.array([1]) + np.testing.assert_array_equal(calculated, expected) + + def test_simple_find_2(self): + x = np.array([0.0, 1.0, 0.0, -1.0, 0.0, 2.0, 1.0, -1.0, 1.0]) + calculated = evstats.argrelmax_decluster(x, x_up=0.0) + expected = np.array([1, 5]) + np.testing.assert_array_equal(calculated, expected) + + def test_simple_find_decluster(self): + x = np.array([0.0, 1.0, 2.0, 1.0, 2.0, 3.0, 2.0, 1.0, 0.0, 2.0, -1.0, 1.0]) + calculated = evstats.argrelmax_decluster(x, x_up=0.0) + expected = np.array([5, 9]) + np.testing.assert_array_equal(calculated, expected) + + def test_simple_find_none(self): + x = np.array([0.1, 1.0, 2.0, 3.0, 4.0, 5.0]) + calculated = evstats.argrelmax_decluster(x) + expected = np.array([5]) + np.testing.assert_array_equal(calculated, expected) + + def test_find_decluster_below_upcross(self): + x = np.array( + [ + 0.0, + 1.0, + 2.0, + 1.0, + 2.0, + 3.0, + 2.0, + 1.0, + 0.0, + -1.0, + -2.0, + -1, + -2, + -1, + 0.0, + 1, + 0.0, + -1.0, + -2.0, + -1.0, + 0.0, + 1.0, + ] + ) + calculated = evstats.argrelmax_decluster(x, x_up=0.0) + expected = np.array([5, 15.0]) + np.testing.assert_array_equal(calculated, expected)