From 0efac1051a6096e04ddb73a813fb0a4f2ec0c7a2 Mon Sep 17 00:00:00 2001 From: Gustavo Rosa Date: Tue, 19 Apr 2022 18:25:42 -0300 Subject: [PATCH] chore(statys): Adds pre-commit hooks and annotated typing. --- .github/dependabot.yml | 23 + .pre-commit-config.yaml | 25 + .pylintrc | 599 ------------------------ docs/conf.py | 71 ++- docs/requirements.txt | 2 +- examples/plotters/plot_h_index.py | 2 +- examples/plotters/plot_p_value.py | 2 +- pyproject.toml | 2 + requirements.txt | 3 +- setup.cfg | 7 + setup.py | 78 +-- statys/__init__.py | 2 +- statys/core/distribution.py | 32 +- statys/plotters/critical.py | 298 ++++++++---- statys/plotters/significance.py | 65 ++- statys/tests/friedman.py | 22 +- statys/tests/mann_whitney.py | 8 +- statys/tests/measure.py | 40 +- statys/tests/wilcoxon.py | 12 +- statys/utils/constants.py | 204 ++++---- statys/utils/exception.py | 52 +- statys/utils/logging.py | 24 +- statys/utils/wrappers.py | 35 +- tests/statys/tests/test_friedman.py | 6 +- tests/statys/tests/test_mann_whitney.py | 5 +- tests/statys/tests/test_measure.py | 18 +- tests/statys/tests/test_wilcoxon.py | 4 +- tests/statys/utils/test_constants.py | 2 +- tests/statys/utils/test_exception.py | 10 +- tests/statys/utils/test_logging.py | 8 +- tests/statys/utils/test_wrappers.py | 4 +- 31 files changed, 635 insertions(+), 1030 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .pre-commit-config.yaml delete mode 100644 .pylintrc create mode 100644 pyproject.toml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..8127040 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,23 @@ +# Please see the documentation for all configuration options: +# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "monthly" + assignees: + - "gugarosa" + labels: + - "dependencies" + + - package-ecosystem: "pip" + directory: "/docs/" + schedule: + interval: "monthly" + assignees: + - "gugarosa" + labels: + - "docs" + - "dependencies" \ No newline at end of file diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..9336cde --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,25 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.1.0 + hooks: + - id: check-added-large-files + args: ['--maxkb=1000'] + - id: check-case-conflict + - id: check-docstring-first + - id: check-merge-conflict + - id: check-yaml + - id: detect-private-key + - id: trailing-whitespace + - id: requirements-txt-fixer + - repo: https://github.com/PyCQA/isort + rev: 5.10.1 + hooks: + - id: isort + - repo: https://github.com/psf/black + rev: 22.3.0 + hooks: + - id: black + - repo: https://github.com/PyCQA/flake8 + rev: 4.0.1 + hooks: + - id: flake8 \ No newline at end of file diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index aba6f19..0000000 --- a/.pylintrc +++ /dev/null @@ -1,599 +0,0 @@ -[MASTER] - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code. -extension-pkg-whitelist= - -# Specify a score threshold to be exceeded before program exits with error. -fail-under=10 - -# Add files or directories to the blacklist. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the blacklist. The -# regex matches against base names, not paths. -ignore-patterns= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the -# number of processors available to use. -jobs=1 - -# Control the amount of potential inferred values when inferring a single -# object. This can help the performance when dealing with large functions or -# complex, nested conditions. -limit-inference-results=100 - -# List of plugins (as comma separated values of python module names) to load, -# usually to register additional checkers. -load-plugins= - -# Pickle collected data for later comparisons. -persistent=yes - -# When enabled, pylint would attempt to guess common misconfiguration and emit -# user-friendly hints instead of false-positive error messages. -suggestion-mode=yes - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. -confidence= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once). You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use "--disable=all --enable=classes -# --disable=W". -disable=print-statement, - parameter-unpacking, - unpacking-in-except, - old-raise-syntax, - backtick, - long-suffix, - old-ne-operator, - old-octal-literal, - import-star-module-level, - non-ascii-bytes-literal, - raw-checker-failed, - bad-inline-option, - locally-disabled, - file-ignored, - suppressed-message, - useless-suppression, - deprecated-pragma, - use-symbolic-message-instead, - apply-builtin, - basestring-builtin, - buffer-builtin, - cmp-builtin, - coerce-builtin, - execfile-builtin, - file-builtin, - long-builtin, - raw_input-builtin, - reduce-builtin, - standarderror-builtin, - unicode-builtin, - xrange-builtin, - coerce-method, - delslice-method, - getslice-method, - setslice-method, - no-absolute-import, - old-division, - dict-iter-method, - dict-view-method, - next-method-called, - metaclass-assignment, - indexing-exception, - raising-string, - reload-builtin, - oct-method, - hex-method, - nonzero-method, - cmp-method, - input-builtin, - round-builtin, - intern-builtin, - unichr-builtin, - map-builtin-not-iterating, - zip-builtin-not-iterating, - range-builtin-not-iterating, - filter-builtin-not-iterating, - using-cmp-argument, - eq-without-hash, - div-method, - idiv-method, - rdiv-method, - exception-message-attribute, - invalid-str-codec, - sys-max-int, - bad-python3-import, - deprecated-string-function, - deprecated-str-translate-call, - deprecated-itertools-function, - deprecated-types-field, - next-method-defined, - dict-items-not-iterating, - dict-keys-not-iterating, - dict-values-not-iterating, - deprecated-operator-function, - deprecated-urllib-function, - xreadlines-attribute, - deprecated-sys-function, - exception-escape, - comprehension-escape, - invalid-name, - super-with-arguments, - redefined-builtin, - no-member - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable=c-extension-no-member - - -[REPORTS] - -# Python expression which should return a score less than or equal to 10. You -# have access to the variables 'error', 'warning', 'refactor', and 'convention' -# which contain the number of messages in each category, as well as 'statement' -# which is the total number of statements analyzed. This score is used by the -# global evaluation report (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details. -#msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio). You can also give a reporter class, e.g. -# mypackage.mymodule.MyReporterClass. -output-format=text - -# Tells whether to display a full report or only the messages. -reports=no - -# Activate the evaluation score. -score=yes - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - -# Complete name of functions that never returns. When checking for -# inconsistent-return-statements if a never returning function is called then -# it will be considered as an explicit return statement and no message will be -# printed. -never-returning-functions=sys.exit - - -[LOGGING] - -# The type of string formatting that logging methods do. `old` means using % -# formatting, `new` is for `{}` formatting. -logging-format-style=old - -# Logging modules to check that the string format arguments are in logging -# function parameter format. -logging-modules=logging - - -[SPELLING] - -# Limits count of emitted suggestions for spelling mistakes. -max-spelling-suggestions=4 - -# Spelling dictionary name. Available dictionaries: none. To make it work, -# install the python-enchant package. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains the private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to the private dictionary (see the -# --spelling-private-dict-file option) instead of raising a message. -spelling-store-unknown-words=no - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -notes=FIXME, - XXX, - TODO - -# Regular expression of note tags to take in consideration. -#notes-rgx= - - -[TYPECHECK] - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members= - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# Tells whether to warn about missing members when the owner of the attribute -# is inferred to be None. -ignore-none=yes - -# This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis). It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules= - -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes - -# The minimum edit distance a name should have in order to be considered a -# similar match for a missing member name. -missing-member-hint-distance=1 - -# The total number of similar names that should be taken in consideration when -# showing a hint for a missing member. -missing-member-max-choices=1 - -# List of decorators that change the signature of a decorated function. -signature-mutators= - - -[VARIABLES] - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid defining new builtins when possible. -additional-builtins= - -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_, - _cb - -# A regular expression matching the name of dummy variables (i.e. expected to -# not be used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore. -ignored-argument-names=_.*|^ignored_|^unused_ - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io - - -[FORMAT] - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -expected-line-ending-format= - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Maximum number of characters on a single line. -max-line-length=130 - -# Maximum number of lines in a module. -max-module-lines=1000 - -# List of optional constructs for which whitespace checking is disabled. `dict- -# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. -# `trailing-comma` allows a space between comma and closing bracket: (a, ). -# `empty-line` allows space-only lines. -no-space-check=trailing-comma, - dict-separator - -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - - -[SIMILARITIES] - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=no - -# Minimum lines number of a similarity. -min-similarity-lines=4 - - -[BASIC] - -# Naming style matching correct argument names. -argument-naming-style=snake_case - -# Regular expression matching correct argument names. Overrides argument- -# naming-style. -#argument-rgx= - -# Naming style matching correct attribute names. -attr-naming-style=snake_case - -# Regular expression matching correct attribute names. Overrides attr-naming- -# style. -#attr-rgx= - -# Bad variable names which should always be refused, separated by a comma. -bad-names=foo, - bar, - baz, - toto, - tutu, - tata - -# Bad variable names regexes, separated by a comma. If names match any regex, -# they will always be refused -bad-names-rgxs= - -# Naming style matching correct class attribute names. -class-attribute-naming-style=any - -# Regular expression matching correct class attribute names. Overrides class- -# attribute-naming-style. -#class-attribute-rgx= - -# Naming style matching correct class names. -class-naming-style=PascalCase - -# Regular expression matching correct class names. Overrides class-naming- -# style. -#class-rgx= - -# Naming style matching correct constant names. -const-naming-style=UPPER_CASE - -# Regular expression matching correct constant names. Overrides const-naming- -# style. -#const-rgx= - -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 - -# Naming style matching correct function names. -function-naming-style=snake_case - -# Regular expression matching correct function names. Overrides function- -# naming-style. -#function-rgx= - -# Good variable names which should always be accepted, separated by a comma. -good-names=i, - j, - k, - ex, - Run, - _ - -# Good variable names regexes, separated by a comma. If names match any regex, -# they will always be accepted -good-names-rgxs= - -# Include a hint for the correct naming format with invalid-name. -include-naming-hint=no - -# Naming style matching correct inline iteration names. -inlinevar-naming-style=any - -# Regular expression matching correct inline iteration names. Overrides -# inlinevar-naming-style. -#inlinevar-rgx= - -# Naming style matching correct method names. -method-naming-style=snake_case - -# Regular expression matching correct method names. Overrides method-naming- -# style. -#method-rgx= - -# Naming style matching correct module names. -module-naming-style=snake_case - -# Regular expression matching correct module names. Overrides module-naming- -# style. -#module-rgx= - -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= - -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ - -# List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -# These decorators are taken in consideration only for invalid-name. -property-classes=abc.abstractproperty - -# Naming style matching correct variable names. -variable-naming-style=snake_case - -# Regular expression matching correct variable names. Overrides variable- -# naming-style. -#variable-rgx= - - -[STRING] - -# This flag controls whether inconsistent-quotes generates a warning when the -# character used as a quote delimiter is used inconsistently within a module. -check-quote-consistency=no - -# This flag controls whether the implicit-str-concat should generate a warning -# on implicit string concatenation in sequences defined over several lines. -check-str-concat-over-line-jumps=no - - -[IMPORTS] - -# List of modules that can be imported at any level, not just the top level -# one. -allow-any-import-level= - -# Allow wildcard imports from modules that define __all__. -allow-wildcard-with-all=no - -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no - -# Deprecated modules which should not be used, separated by a comma. -deprecated-modules=optparse,tkinter.tix - -# Create a graph of external dependencies in the given file (report RP0402 must -# not be disabled). -ext-import-graph= - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report RP0402 must not be disabled). -import-graph= - -# Create a graph of internal dependencies in the given file (report RP0402 must -# not be disabled). -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - -# Couples of modules and preferred modules, separated by a comma. -preferred-modules= - - -[CLASSES] - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__, - __new__, - setUp, - __post_init__ - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict, - _fields, - _replace, - _source, - _make - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=cls - - -[DESIGN] - -# Maximum number of arguments for function / method. -max-args=10 - -# Maximum number of attributes for a class (see R0902). -max-attributes=30 - -# Maximum number of boolean expressions in an if statement (see R0916). -max-bool-expr=5 - -# Maximum number of branch for function / method body. -max-branches=15 - -# Maximum number of locals for function / method body. -max-locals=20 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of return / yield for function / method body. -max-returns=6 - -# Maximum number of statements in function / method body. -max-statements=50 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=2 - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when being caught. Defaults to -# "BaseException, Exception". -overgeneral-exceptions=BaseException, - Exception diff --git a/docs/conf.py b/docs/conf.py index 4d5221f..f911a4c 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -17,20 +17,20 @@ import sphinx_rtd_theme -sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath(".")) # -- Project information ----------------------------------------------------- -project = 'statys' -copyright = '2020, Gustavo de Rosa' -author = 'Gustavo de Rosa' +project = "statys" +copyright = "2020, Gustavo de Rosa" +author = "Gustavo de Rosa" # The short X.Y version -version = '1.0.1' +version = "1.0.1" # The full version, including alpha/beta/rc tags -release = '1.0.1' +release = "1.0.1" # -- General configuration --------------------------------------------------- @@ -42,38 +42,34 @@ # 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', - 'autoapi.extension' -] +extensions = ["sphinx.ext.autodoc", "sphinx.ext.napoleon", "autoapi.extension"] -autoapi_dirs = ['../statys'] +autoapi_dirs = ["../statys"] autoapi_generate_api_docs = False # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +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' +source_suffix = ".rst" # The master toctree document. -master_doc = 'index' +master_doc = "index" # 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' +language = "en" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # The name of the Pygments (syntax highlighting) style to use. pygments_style = None @@ -84,7 +80,7 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -html_theme = 'sphinx_rtd_theme' +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 @@ -102,9 +98,9 @@ # documentation. # html_theme_options = { - 'collapse_navigation': False, - 'display_version': True, - 'logo_only': True, + "collapse_navigation": False, + "display_version": True, + "logo_only": True, } # Custom sidebar templates, must be a dictionary that maps document names @@ -121,7 +117,7 @@ # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. -htmlhelp_basename = 'statys_doc' +htmlhelp_basename = "statys_doc" # -- Options for LaTeX output ------------------------------------------------ @@ -130,15 +126,12 @@ # 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', @@ -148,8 +141,7 @@ # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'statys.tex', 'Statys Documentation', - 'Gustavo de Rosa', 'manual'), + (master_doc, "statys.tex", "Statys Documentation", "Gustavo de Rosa", "manual"), ] @@ -157,10 +149,7 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [ - (master_doc, 'statys', 'Statys Documentation', - [author], 1) -] +man_pages = [(master_doc, "statys", "Statys Documentation", [author], 1)] # -- Options for Texinfo output ---------------------------------------------- @@ -169,9 +158,15 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'statys', 'Statys Documentation', - author, 'statys', 'Statys is a library composed of statistical analyzers.', - 'Statistical Analysis'), + ( + master_doc, + "statys", + "Statys Documentation", + author, + "statys", + "Statys is a library composed of statistical analyzers.", + "Statistical Analysis", + ), ] @@ -190,12 +185,10 @@ # epub_uid = '' # A list of files that should not be packed into the epub file. -epub_exclude_files = ['search.html'] +epub_exclude_files = ["search.html"] # -- Extension configuration ------------------------------------------------- -autodoc_default_options = { - 'exclude-members': '__weakref__' -} +autodoc_default_options = {"exclude-members": "__weakref__"} -autodoc_member_order = 'bysource' +autodoc_member_order = "bysource" diff --git a/docs/requirements.txt b/docs/requirements.txt index b5c2d86..8cee5c2 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,3 +1,3 @@ sphinx==3.0.4 sphinx-autoapi>=1.3.0 -sphinx-rtd-theme>=0.4.3 \ No newline at end of file +sphinx-rtd-theme>=0.4.3 diff --git a/examples/plotters/plot_h_index.py b/examples/plotters/plot_h_index.py index fe5d7bc..5002f62 100644 --- a/examples/plotters/plot_h_index.py +++ b/examples/plotters/plot_h_index.py @@ -14,4 +14,4 @@ signed_rank = w.signed_rank(d) # Plots the h-index -s.plot_h_index(signed_rank, title='Wilcoxon Signed-Rank Test ($h$-index)') +s.plot_h_index(signed_rank, title="Wilcoxon Signed-Rank Test ($h$-index)") diff --git a/examples/plotters/plot_p_value.py b/examples/plotters/plot_p_value.py index 2e32d24..aba4b7e 100644 --- a/examples/plotters/plot_p_value.py +++ b/examples/plotters/plot_p_value.py @@ -14,4 +14,4 @@ signed_rank = w.signed_rank(d) # Plots the p-values -s.plot_p_value(signed_rank, title='Wilcoxon Signed-Rank Test ($p$-values)') +s.plot_p_value(signed_rank, title="Wilcoxon Signed-Rank Test ($p$-values)") diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..5312e35 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,2 @@ +[tool.black] +line-length = 88 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index d16544a..4c89cf1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ coverage>=5.5 matplotlib>=3.3.4 numpy>=1.19.5 +pre-commit>=2.17.0 pylint>=2.7.2 pytest>=6.2.2 -scipy>=1.5.4 \ No newline at end of file +scipy>=1.5.4 diff --git a/setup.cfg b/setup.cfg index 224a779..5b20855 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,2 +1,9 @@ +[flake8] +max-line-length = 88 +extend-ignore = E203, E402, E501, F401, F407 + +[isort] +profile = black + [metadata] description-file = README.md \ No newline at end of file diff --git a/setup.py b/setup.py index 053e207..6455aee 100644 --- a/setup.py +++ b/setup.py @@ -1,41 +1,45 @@ from setuptools import find_packages, setup -with open('README.md', 'r') as f: +with open("README.md", "r") as f: long_description = f.read() -setup(name='statys', - version='1.0.1', - description='Statistical Analyzers', - long_description=long_description, - long_description_content_type='text/markdown', - author='Gustavo Rosa', - author_email='gustavo.rosa@unesp.br', - url='https://github.com/gugarosa/statys', - license='Apache 2.0', - install_requires=['coverage>=5.5', - 'matplotlib>=3.3.4', - 'numpy>=1.19.5', - 'pylint>=2.7.2', - 'pytest>=6.2.2' - 'scipy>=1.5.4' - ], - extras_require={ - 'tests': ['coverage', - 'pytest', - 'pytest-pep8', - ], - }, - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'Intended Audience :: Education', - 'Intended Audience :: Science/Research', - 'License :: OSI Approved :: Apache Software License', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Software Development :: Libraries', - 'Topic :: Software Development :: Libraries :: Python Modules' - ], - packages=find_packages()) +setup( + name="statys", + version="1.0.1", + description="Statistical Analyzers", + long_description=long_description, + long_description_content_type="text/markdown", + author="Gustavo Rosa", + author_email="gustavo.rosa@unesp.br", + url="https://github.com/gugarosa/statys", + license="Apache 2.0", + install_requires=[ + "coverage>=5.5", + "matplotlib>=3.3.4", + "numpy>=1.19.5", + "pre-commit>=2.17.0", + "pylint>=2.7.2", + "pytest>=6.2.2" "scipy>=1.5.4", + ], + extras_require={ + "tests": [ + "coverage", + "pytest", + "pytest-pep8", + ], + }, + classifiers=[ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Intended Audience :: Education", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Topic :: Software Development :: Libraries", + "Topic :: Software Development :: Libraries :: Python Modules", + ], + packages=find_packages(), +) diff --git a/statys/__init__.py b/statys/__init__.py index 861465b..db4120d 100644 --- a/statys/__init__.py +++ b/statys/__init__.py @@ -2,4 +2,4 @@ of several modules and sub-modules. """ -__version__ = '1.0.1' +__version__ = "1.0.1" diff --git a/statys/core/distribution.py b/statys/core/distribution.py index a8ea1e0..5a7e014 100644 --- a/statys/core/distribution.py +++ b/statys/core/distribution.py @@ -1,12 +1,14 @@ """Distribution-related definitions. """ +from typing import Any, Dict + import numpy as np import statys.utils.exception as e -import statys.utils.logging as l +from statys.utils import logging -logger = l.get_logger(__name__) +logger = logging.get_logger(__name__) class Distribution: @@ -15,35 +17,39 @@ class Distribution: """ - def __init__(self, *args): - """Initialization method. - - """ + def __init__(self, *args) -> None: + """Initialization method.""" - logger.info('Initializing class with %d arguments ...', len(args)) + logger.info("Initializing class with %d arguments ...", len(args)) for i, arg in enumerate(args): - attr = f'arg{i}' + attr = f"arg{i}" if not isinstance(arg, (list, np.ndarray)): - raise e.TypeError(f'`{attr}` should be a list or np.ndarray') + raise e.TypeError(f"`{attr}` should be a list or np.ndarray") setattr(self, attr, arg) - logger.debug('%s', self) - logger.info('Class initialized.') + logger.debug("%s", self) + logger.info("Class initialized.") - def __repr__(self): + def __repr__(self) -> str: """Class' string representation. + Returns: + (str): String representation. + """ return str(self.__dict__) @property - def attrs(self): + def attrs(self) -> Dict[str, Any]: """Gathers all attributes from class. + Returns: + (Dict[str, Any]): Attributes encoded into a dictionary. + """ return self.__dict__.items() diff --git a/statys/plotters/critical.py b/statys/plotters/critical.py index cadfebf..391d596 100644 --- a/statys/plotters/critical.py +++ b/statys/plotters/critical.py @@ -3,102 +3,120 @@ """ +from typing import Any, Dict, List, Optional, Tuple + import numpy as np +from matplotlib.axis import Axis from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure -def _create_labels(size=1): +def _create_labels(size: Optional[int] = 1) -> List[str]: """Creates a list of labels strings. Args: - size (int): Amount of strings to be created. + size: Amount of strings to be created. Returns: - A list of stringed labels, e.g., x0, x1, ..., xn. + (List[str]): Stringed labels, e.g., x0, x1, ..., xn. """ labels = [] for i in range(size): - labels.append(f'$x_{{{i}}}$') + labels.append(f"$x_{{{i}}}$") return labels -def _multiple_range(l): +def _multiple_range(input_list: List[Any]) -> Tuple[Any, ...]: """Performs a multiple range, used to traverse matrices. Args: - l (List): List to be traversed. + input_list: List to be traversed. Yields: - An iterator of tuples. + (Tuple[Any, ...]): Iterator of tuples. """ - length = len(l) + length = len(input_list) if length == 0: yield () else: - index = l[0] + index = input_list[0] if isinstance(index, int): index = [index] for a in range(*index): - for b in _multiple_range(l[1:]): + for b in _multiple_range(input_list[1:]): yield tuple([a] + list(b)) -def _line_factoring(line, factor): +def _line_factoring(line: List[float], factor: float) -> List[float]: """Factors a line's positioning. Args: - line (list): List of lines to be factored. - factor (float): Factor to use in the factoring. + line: Lines to be factored. + factor: Factor to use in the factoring. Returns: - A list of factored lines. + (List[float]): Factored lines. """ return [a * factor for a in line] -def _plot_line(ax, l, width_factor, height_factor, color='k', **kwargs): +def _plot_line( + ax: Axis, + input_list: List[Tuple[int, int]], + width_factor: float, + height_factor: float, + color: Optional[str] = "k", + **kwargs, +) -> None: """Plots pairs of points as lines. Args: - ax (Axis): Axis to be plotted. - l (list): List of pairs of points. - width_factor (float): Width factor. - height_factor (float): Height factor. - color (str): Color to be plotted. + ax: Axis to be plotted. + input_list: List of pairs of points. + width_factor: Width factor. + height_factor: Height factor. + color: Color to be plotted. """ # Calculates the `x` and `y` elements - x = _line_factoring(_get_element(l, 0), width_factor) - y = _line_factoring(_get_element(l, 1), height_factor) + x = _line_factoring(_get_element(input_list, 0), width_factor) + y = _line_factoring(_get_element(input_list, 1), height_factor) # Plots the pair of points ax.plot(x, y, color=color, **kwargs) -def _plot_text(ax, x, y, s, width_factor, height_factor, **kwargs): +def _plot_text( + ax: Axis, + x: int, + y: int, + s: str, + width_factor: float, + height_factor: float, + **kwargs, +) -> None: """Plots a text on the desired position. Args: - ax (Axis): Axis to be plotted. - x (int): `x` position to be plotted. - y (int): `y` position to be plotted. - s (str): String to be plotted. - width_factor (float): Width factor. - height_factor (float): Height factor. + ax: Axis to be plotted. + x: `x` position to be plotted. + y: `y` position to be plotted. + s: String to be plotted. + width_factor: Width factor. + height_factor: Height factor. """ @@ -106,15 +124,15 @@ def _plot_text(ax, x, y, s, width_factor, height_factor, **kwargs): ax.text(width_factor * x, height_factor * y, s, **kwargs) -def _get_amount_lines(ranks, cd): +def _get_amount_lines(ranks: List[int], cd: float) -> List[Tuple[Any, ...]]: """Gets the amount of possible lines to create the plot. Args: - ranks (list): List of ranks. - cd (float): Critical difference. + ranks: List of ranks. + cd: Critical difference. Returns: - List of tuples containing the longest possible amount of lines. + (List[Tuple[Any, ...]]): Longest possible amount of lines. """ @@ -128,7 +146,7 @@ def _get_amount_lines(ranks, cd): non_pairs = [(i, j) for i, j in pairs if abs(ranks[i] - ranks[j]) <= cd] # Internal function to return the longest pairs - def get_longest(i, j, pairs): + def get_longest(i: int, j: int, pairs: Tuple[int, int]) -> bool: for k, l in pairs: # Checks if iterated pair is bigger than current one if (k <= i and l > j) or (k < i and l >= j): @@ -142,38 +160,40 @@ def get_longest(i, j, pairs): return longest -def _get_element(l, n): +def _get_element(input_list: List[Any], n: int) -> List[Any]: """Gets a specific element from a list of tuples. Args: - l (list): List to be iterated. - n (int): Element to be retrieved. + input_list: List to be iterated. + n: Element to be retrieved. Returns: - A new list with only the retrieved elements. + (List[Any]): Only retrieved elements. """ if n < 0: # Adds the length of the list to gather the desired index - i = len(l[0]) + n + i = len(input_list[0]) + n else: # Use the index as usual i = n - return [a[i] for a in l] + return [a[i] for a in input_list] -def _calculate_plot_properties(sort_ranks, cd): +def _calculate_plot_properties( + sort_ranks: List[int], cd: float +) -> Tuple[int, float, float, int, float, float]: """Calculates a set of properties used to accurately plot the statistical test. Args: - sort_ranks (list): List holding the sorted ranks. - cd (float): Critical difference. + sort_ranks: List holding the sorted ranks. + cd: Critical difference. Returns: - A set of properties used in the plot's construction. + (Tuple[int, float, float, int, float, float]): Properties used in the plot's construction. """ @@ -197,15 +217,15 @@ def _calculate_plot_properties(sort_ranks, cd): return n_ranks, height_distance, top_distance, n_lines, not_sig_distance, height -def _prepare_plot(width, height): +def _prepare_plot(width: float, height: float) -> Tuple[Figure, Axis]: """Prepares the plot prior to its use. Args: - width (float): Width of the plot. - height (float): Height of the plot. + width: Width of the plot. + height: Height of the plot. Returns: - The figure and axis properties from the plot. + (Tuple[Figure, Axis]): Figure and axis properties from the plot. """ @@ -219,7 +239,7 @@ def _prepare_plot(width, height): ax.set_axis_off() # Plots its boundaries - ax.plot([0, 1], [0, 1], c='w') + ax.plot([0, 1], [0, 1], c="w") # Sets the `x` and `y` limits ax.set_xlim(0, 1) @@ -228,19 +248,21 @@ def _prepare_plot(width, height): return fig, ax -def _position_rank(index, low, high, text_spacing, scale, reverse): +def _position_rank( + index: int, low: int, high: int, text_spacing: int, scale: float, reverse: bool +) -> int: """Positions a rank according to its value. Args: - index (int): Index to be positioned. - low (int): Minimum rank possible. - high (int): Maximum rank possible. - text_spacing (int): Text spacing inside the plot. - scale (float): Plot's scale. - reverse (bool): Whether plot should use ascending or descending order. + index: Index to be positioned. + low: Minimum rank possible. + high: Maximum rank possible. + text_spacing: Text spacing inside the plot. + scale: Plot's scale. + reverse: Whether plot should use ascending or descending order. Returns: - A value that indicates where the rank should be positioned in the plot. + (int): Rank should be positioned in the plot. """ @@ -253,15 +275,21 @@ def _position_rank(index, low, high, text_spacing, scale, reverse): return text_spacing + scale / (high - low) * x -def plot_critical_difference(cd_dict, labels=None, width=6, text_spacing=2, reverse=False): +def plot_critical_difference( + cd_dict: Dict[str, Any], + labels: Optional[List[str]] = None, + width: Optional[int] = 6, + text_spacing: Optional[int] = 2, + reverse: Optional[bool] = False, +) -> None: """Plots the critical difference between the averaged ranks. Args: - cd_dict (dict): Dictionary of average ranks and critical differences. - labels (list): List of stringed labels. - width (int): Plot's width. - text_spacing (int): Text spacing inside the plot. - reverse (bool): Whether plot should use ascending or descending order. + cd_dict: Dictionary of average ranks and critical differences. + labels: List of stringed labels. + width: Plot's width. + text_spacing: Text spacing inside the plot. + reverse: Whether plot should use ascending or descending order. """ @@ -279,7 +307,9 @@ def plot_critical_difference(cd_dict, labels=None, width=6, text_spacing=2, reve sort_operator = sorted([(r, i) for i, r in enumerate(ranks)], reverse=reverse) # Gathers the sorted ranks and their indexes - sort_ranks, sort_idx = _get_element(sort_operator, 0), _get_element(sort_operator, 1) + sort_ranks, sort_idx = _get_element(sort_operator, 0), _get_element( + sort_operator, 1 + ) # Checks if labels exists and number of supplied labels equals the number of arguments if labels and len(labels) == len(ranks): @@ -293,8 +323,14 @@ def plot_critical_difference(cd_dict, labels=None, width=6, text_spacing=2, reve sort_labels = [labels[i] for i in sort_idx] # Calculates a set of properties used to perform an accurate plot - n_ranks, height_distance, top_distance, n_lines, not_sig_distance, height = _calculate_plot_properties( - sort_ranks, cd) + ( + n_ranks, + height_distance, + top_distance, + n_lines, + not_sig_distance, + height, + ) = _calculate_plot_properties(sort_ranks, cd) # Prepares the plot based on inputted width and calculated height fig, ax = _prepare_plot(width, height) @@ -325,8 +361,14 @@ def plot_critical_difference(cd_dict, labels=None, width=6, text_spacing=2, reve tick = big_tick # Defines `x` and `y` points - x = (_position_rank(a, low, high, text_spacing, scale, reverse), top_distance - tick / 2) - y = (_position_rank(a, low, high, text_spacing, scale, reverse), top_distance) + x = ( + _position_rank(a, low, high, text_spacing, scale, reverse), + top_distance - tick / 2, + ) + y = ( + _position_rank(a, low, high, text_spacing, scale, reverse), + top_distance, + ) # Plots a new line _plot_line(ax, [x, y], width_factor, height_factor, linewidth=0.7) @@ -335,8 +377,16 @@ def plot_critical_difference(cd_dict, labels=None, width=6, text_spacing=2, reve # for plotting the text for a in range(low, high + 1): # Plots the text label - _plot_text(ax, _position_rank(a, low, high, text_spacing, scale, reverse), top_distance - - tick / 2 - 0.05, str(a), width_factor, height_factor, ha='center', va='bottom') + _plot_text( + ax, + _position_rank(a, low, high, text_spacing, scale, reverse), + top_distance - tick / 2 - 0.05, + str(a), + width_factor, + height_factor, + ha="center", + va="bottom", + ) # Iterates over every possible left-sided rank for i in range(int((n_ranks + 1) / 2)): @@ -344,16 +394,30 @@ def plot_critical_difference(cd_dict, labels=None, width=6, text_spacing=2, reve arrow = top_distance + not_sig_distance + i * 0.2 # Defines `x`, `y` and `z` points - x = (_position_rank(sort_ranks[i], low, high, text_spacing, scale, reverse), top_distance) - y = (_position_rank(sort_ranks[i], low, high, text_spacing, scale, reverse), arrow) + x = ( + _position_rank(sort_ranks[i], low, high, text_spacing, scale, reverse), + top_distance, + ) + y = ( + _position_rank(sort_ranks[i], low, high, text_spacing, scale, reverse), + arrow, + ) z = (text_spacing - 0.1, arrow) # Plots a new line _plot_line(ax, [x, y, z], width_factor, height_factor, linewidth=0.7) # Plots the text label - _plot_text(ax, text_spacing - 0.2, arrow, - sort_labels[i], width_factor, height_factor, ha='right', va='center') + _plot_text( + ax, + text_spacing - 0.2, + arrow, + sort_labels[i], + width_factor, + height_factor, + ha="right", + va="center", + ) # Iterates over every possible right-sided rank for i in range(int((n_ranks + 1) / 2), n_ranks): @@ -361,16 +425,30 @@ def plot_critical_difference(cd_dict, labels=None, width=6, text_spacing=2, reve arrow = top_distance + not_sig_distance + (n_ranks - i - 1) * 0.2 # Defines `x`, `y` and `z` points - x = (_position_rank(sort_ranks[i], low, high, text_spacing, scale, reverse), top_distance) - y = (_position_rank(sort_ranks[i], low, high, text_spacing, scale, reverse), arrow) + x = ( + _position_rank(sort_ranks[i], low, high, text_spacing, scale, reverse), + top_distance, + ) + y = ( + _position_rank(sort_ranks[i], low, high, text_spacing, scale, reverse), + arrow, + ) z = (text_spacing + scale + 0.1, arrow) # Plots a new line _plot_line(ax, [x, y, z], width_factor, height_factor, linewidth=0.7) # Plots the text label - _plot_text(ax, text_spacing + scale + 0.2, arrow, - sort_labels[i], width_factor, height_factor, ha='left', va='center') + _plot_text( + ax, + text_spacing + scale + 0.2, + arrow, + sort_labels[i], + width_factor, + height_factor, + ha="left", + va="center", + ) if reverse: # Calculates the starting and ending position from `high` values @@ -383,29 +461,71 @@ def plot_critical_difference(cd_dict, labels=None, width=6, text_spacing=2, reve end = _position_rank(low + cd, low, high, text_spacing, scale, reverse) # Plots the starting and ending points of the CD line - _plot_line(ax, [(start, height_distance), (end, height_distance)], width_factor, height_factor, linewidth=0.7) + _plot_line( + ax, + [(start, height_distance), (end, height_distance)], + width_factor, + height_factor, + linewidth=0.7, + ) # Plots the starting ticks of the CD line - _plot_line(ax, [(start, height_distance + big_tick / 2), - (start, height_distance - big_tick / 2)], width_factor, height_factor, linewidth=0.7) + _plot_line( + ax, + [ + (start, height_distance + big_tick / 2), + (start, height_distance - big_tick / 2), + ], + width_factor, + height_factor, + linewidth=0.7, + ) # Plots the ending ticks of the CD line - _plot_line(ax, [(end, height_distance + big_tick / 2), - (end, height_distance - big_tick / 2)], width_factor, height_factor, linewidth=0.7) + _plot_line( + ax, + [ + (end, height_distance + big_tick / 2), + (end, height_distance - big_tick / 2), + ], + width_factor, + height_factor, + linewidth=0.7, + ) # Plots the CD line itself - _plot_text(ax, (start + end) / 2, height_distance - 0.05, f'CD={cd}', - width_factor, height_factor, ha='center', va='bottom') + _plot_text( + ax, + (start + end) / 2, + height_distance - 0.05, + f"CD={cd}", + width_factor, + height_factor, + ha="center", + va="bottom", + ) # Plots non-significant lines # Defines a new starting point start = top_distance + 0.2 # Iterates over every non-significant line - for l, r in n_lines: + for left, right in n_lines: # Defines `x` and `y` points - x = (_position_rank(sort_ranks[l], low, high, text_spacing, scale, reverse) - 0.05, start) - y = (_position_rank(sort_ranks[r], low, high, text_spacing, scale, reverse) + 0.05, start) + x = ( + _position_rank( + sort_ranks[left], low, high, text_spacing, scale, reverse + ) + - 0.05, + start, + ) + y = ( + _position_rank( + sort_ranks[right], low, high, text_spacing, scale, reverse + ) + + 0.05, + start, + ) # Plots the line _plot_line(ax, [x, y], width_factor, height_factor, linewidth=2.5) @@ -417,4 +537,4 @@ def plot_critical_difference(cd_dict, labels=None, width=6, text_spacing=2, reve canvas = FigureCanvasAgg(fig) # Printing out the figure - canvas.print_figure(f'cd_{key}.pdf') + canvas.print_figure(f"cd_{key}.pdf") diff --git a/statys/plotters/significance.py b/statys/plotters/significance.py index 4d1b117..fb63b82 100644 --- a/statys/plotters/significance.py +++ b/statys/plotters/significance.py @@ -1,39 +1,42 @@ """Significance-based plotting utilities, such as h-index and p-value. """ +from typing import Any, Dict, List, Optional + import matplotlib.pyplot as plt import numpy as np +from matplotlib.axis import Axis -def _create_labels(size=1): +def _create_labels(size: Optional[int] = 1) -> List[str]: """Creates a list of labels strings. Args: - size (int): Amount of strings to be created. + size: Amount of strings to be created. Returns: - A list of stringed labels, e.g., arg0, arg1, ..., argn. + (List[str]): Stringed labels, e.g., arg0, arg1, ..., argn. """ labels = [] for i in range(size): - labels.append(f'$arg_{{{i}}}$') + labels.append(f"$arg_{{{i}}}$") return labels -def _prepare_plot(n_args, labels, title): +def _prepare_plot(n_args: int, labels: List[str], title: str) -> Axis: """Prepares the plot with common definitions. Args: - n_args (int): Number of arguments. - labels (list): List of stringed labels. - title (str): Title to be displayed. + n_args: Number of arguments. + labels: List of stringed labels. + title: Title to be displayed. Returns: - The axis property from the plot. + (Axis): Axis property from the plot. """ @@ -59,8 +62,8 @@ def _prepare_plot(n_args, labels, title): ax.set_title(title) ax.set_xticks(np.arange(n_args + 1) - 0.5, minor=True) ax.set_yticks(np.arange(n_args + 1) - 0.5, minor=True) - ax.grid(which='minor', color='w', linestyle='-', linewidth=3) - ax.tick_params(which='minor', bottom=False, left=False) + ax.grid(which="minor", color="w", linestyle="-", linewidth=3) + ax.tick_params(which="minor", bottom=False, left=False) # Iterates through every spine for _, spine in ax.spines.items(): @@ -70,14 +73,19 @@ def _prepare_plot(n_args, labels, title): return ax -def plot_p_value(p_dict, color_map='YlOrRd', labels=None, title=None): +def plot_p_value( + p_dict: Dict[str, Any], + color_map: Optional[str] = "YlOrRd", + labels: Optional[List[str]] = None, + title: Optional[str] = None, +) -> None: """Plots a p-value grid according to statistical results. Args: - p_dict (dict): Dictionary of significances and p-values. - color_map (str): A color map from matplotlib. - labels (list): List of stringed labels. - title (str): Title to be displayed. + p_dict: Significances and p-values. + color_map: Color map from matplotlib. + labels: Stringed labels. + title: Title to be displayed. """ @@ -92,7 +100,7 @@ def plot_p_value(p_dict, color_map='YlOrRd', labels=None, title=None): for k, v in p_dict.items(): # Gathers the positions from the arguments - args = k.replace('arg', '').split('-') + args = k.replace("arg", "").split("-") # Transforms the positions into integers i, j = int(args[0]), int(args[1]) @@ -103,7 +111,7 @@ def plot_p_value(p_dict, color_map='YlOrRd', labels=None, title=None): # Iterates through the p-valued matrix for (i, j), z in np.ndenumerate(p): # Applies the corresponding value to the position - ax.text(j, i, '{:0.3f}'.format(1 - z), ha='center', va='center') + ax.text(j, i, "{:0.3f}".format(1 - z), ha="center", va="center") # Adds the significances to the plot ax.imshow(p, cmap=color_map) @@ -112,14 +120,19 @@ def plot_p_value(p_dict, color_map='YlOrRd', labels=None, title=None): plt.show() -def plot_h_index(h_dict, color_map='YlOrRd', labels=None, title=None): +def plot_h_index( + h_dict: Dict[str, Any], + color_map: Optional[str] = "YlOrRd", + labels: Optional[List[str]] = None, + title: Optional[str] = None, +) -> None: """Plots an h-index grid according to statistical results. Args: - h_dict (dict): Dictionary of h-indexes and p-values. - color_map (str): A color map from matplotlib. - labels (list): List of stringed labels. - title (str): Title to be displayed. + h_dict: H-indexes and p-values. + color_map: Color map from matplotlib. + labels: Stringed labels. + title: Title to be displayed. """ @@ -130,11 +143,11 @@ def plot_h_index(h_dict, color_map='YlOrRd', labels=None, title=None): ax = _prepare_plot(n_args, labels, title) # Instantiates the significance matrix - sigs = np.zeros((n_args, n_args), dtype='int') + sigs = np.zeros((n_args, n_args), dtype="int") for k, v in h_dict.items(): # Gathers the positions from the arguments - args = k.replace('arg', '').split('-') + args = k.replace("arg", "").split("-") # Transforms the positions into integers i, j = int(args[0]), int(args[1]) @@ -145,7 +158,7 @@ def plot_h_index(h_dict, color_map='YlOrRd', labels=None, title=None): # Iterates through the significance matrix for (i, j), z in np.ndenumerate(sigs): # Applies the corresponding value to the position - ax.text(j, i, z, ha='center', va='center') + ax.text(j, i, z, ha="center", va="center") # Adds the significances to the plot ax.imshow(sigs, cmap=color_map) diff --git a/statys/tests/friedman.py b/statys/tests/friedman.py index a51cc28..9c35cf6 100644 --- a/statys/tests/friedman.py +++ b/statys/tests/friedman.py @@ -5,9 +5,9 @@ import statys.tests.measure as m import statys.utils.constants as c -import statys.utils.logging as l +from statys.utils import logging -logger = l.get_logger(__name__) +logger = logging.get_logger(__name__) def friedman(dist, **kwargs): @@ -21,7 +21,7 @@ def friedman(dist, **kwargs): """ - logger.info('Performing Friedman test ...') + logger.info("Performing Friedman test ...") # Initializes a empty dictionary for the outputs output = {} @@ -45,8 +45,12 @@ def friedman(dist, **kwargs): k = len(val) # Calculates the Friedman's statistic - f = 12 * n * (sum([v ** 2.0 for v in val]) - - (k * (k + 1) * (k + 1) / 4)) / (k * (k + 1)) + f = ( + 12 + * n + * (sum([v**2.0 for v in val]) - (k * (k + 1) * (k + 1) / 4)) + / (k * (k + 1)) + ) # Calculates the F-distribution f_dist = (k - 1, (k - 1) * (n - 1)) @@ -57,13 +61,13 @@ def friedman(dist, **kwargs): # Adds the tuple to the output dictionary output[key] = (f, k - 1), (iman, f_dist) - logger.info('Test performed.') + logger.info("Test performed.") logger.debug(output) return output -def friedman_with_posthoc(dist, alpha=0.05, post_hoc='nemenyi', **kwargs): +def friedman_with_posthoc(dist, alpha=0.05, post_hoc="nemenyi", **kwargs): """Performs the Friedman test with a post-hoc analysis. Args: @@ -76,7 +80,7 @@ def friedman_with_posthoc(dist, alpha=0.05, post_hoc='nemenyi', **kwargs): """ - logger.info('Performing Friedman-%s test ...', post_hoc) + logger.info("Performing Friedman-%s test ...", post_hoc) # Initializes a empty dictionary for the outputs output = {} @@ -117,7 +121,7 @@ def friedman_with_posthoc(dist, alpha=0.05, post_hoc='nemenyi', **kwargs): # Adds the tuple to the output dictionary output[key] = (val, cd) - logger.info('Test performed.') + logger.info("Test performed.") logger.debug(output) return output diff --git a/statys/tests/mann_whitney.py b/statys/tests/mann_whitney.py index 7ab5bda..3865d85 100644 --- a/statys/tests/mann_whitney.py +++ b/statys/tests/mann_whitney.py @@ -3,10 +3,10 @@ import scipy.stats as s -import statys.utils.logging as l import statys.utils.wrappers as w +from statys.utils import logging -logger = l.get_logger(__name__) +logger = logging.get_logger(__name__) def u_test(dist, alpha=0.05): @@ -21,11 +21,11 @@ def u_test(dist, alpha=0.05): """ - logger.info('Performing Mann-Whitney U test ...') + logger.info("Performing Mann-Whitney U test ...") output = w.statistical_pipeline(s.mannwhitneyu, dist, alpha) - logger.info('Test performed.') + logger.info("Test performed.") logger.debug(output) return output diff --git a/statys/tests/measure.py b/statys/tests/measure.py index 1940ac3..a108141 100644 --- a/statys/tests/measure.py +++ b/statys/tests/measure.py @@ -4,10 +4,10 @@ import numpy as np import scipy.stats as s -import statys.utils.logging as l import statys.utils.wrappers as w +from statys.utils import logging -logger = l.get_logger(__name__) +logger = logging.get_logger(__name__) def kurtosis(dist, **kwargs): @@ -21,11 +21,11 @@ def kurtosis(dist, **kwargs): """ - logger.info('Calculating kurtosis ...') + logger.info("Calculating kurtosis ...") output = w.measure_pipeline(s.kurtosis, dist, **kwargs) - logger.info('Kurtosis calculated.') + logger.info("Kurtosis calculated.") logger.debug(output) return output @@ -42,11 +42,11 @@ def max(dist, **kwargs): """ - logger.info('Finding maximum value ...') + logger.info("Finding maximum value ...") output = w.measure_pipeline(np.max, dist, **kwargs) - logger.info('Maximum value found.') + logger.info("Maximum value found.") logger.debug(output) return output @@ -63,11 +63,11 @@ def mean(dist, **kwargs): """ - logger.info('Calculating mean ...') + logger.info("Calculating mean ...") output = w.measure_pipeline(np.mean, dist, **kwargs) - logger.info('Mean calculated.') + logger.info("Mean calculated.") logger.debug(output) return output @@ -84,11 +84,11 @@ def median(dist, **kwargs): """ - logger.info('Calculating median ...') + logger.info("Calculating median ...") output = w.measure_pipeline(np.median, dist, **kwargs) - logger.info('Median calculated.') + logger.info("Median calculated.") logger.debug(output) return output @@ -105,11 +105,11 @@ def min(dist, **kwargs): """ - logger.info('Finding minimum value ...') + logger.info("Finding minimum value ...") output = w.measure_pipeline(np.min, dist, **kwargs) - logger.info('Minimum value found.') + logger.info("Minimum value found.") logger.debug(output) return output @@ -126,11 +126,11 @@ def rank(dist, **kwargs): """ - logger.info('Ranking distribution ...') + logger.info("Ranking distribution ...") output = w.measure_pipeline(s.rankdata, dist, **kwargs) - logger.info('Distribution ranked.') + logger.info("Distribution ranked.") logger.debug(output) return output @@ -147,11 +147,11 @@ def skewness(dist, **kwargs): """ - logger.info('Calculating skewness ...') + logger.info("Calculating skewness ...") output = w.measure_pipeline(s.skew, dist, **kwargs) - logger.info('Skewness calculated.') + logger.info("Skewness calculated.") logger.debug(output) return output @@ -168,11 +168,11 @@ def std(dist, **kwargs): """ - logger.info('Calculating standard deviation ...') + logger.info("Calculating standard deviation ...") output = w.measure_pipeline(np.std, dist, **kwargs) - logger.info('Standard deviation calculated.') + logger.info("Standard deviation calculated.") logger.debug(output) return output @@ -189,11 +189,11 @@ def var(dist, **kwargs): """ - logger.info('Calculating variance ...') + logger.info("Calculating variance ...") output = w.measure_pipeline(np.var, dist, **kwargs) - logger.info('Variance calculated.') + logger.info("Variance calculated.") logger.debug(output) return output diff --git a/statys/tests/wilcoxon.py b/statys/tests/wilcoxon.py index 8f094ad..aa1f72f 100644 --- a/statys/tests/wilcoxon.py +++ b/statys/tests/wilcoxon.py @@ -3,10 +3,10 @@ import scipy.stats as s -import statys.utils.logging as l import statys.utils.wrappers as w +from statys.utils import logging -logger = l.get_logger(__name__) +logger = logging.get_logger(__name__) def signed_rank(dist, alpha=0.05): @@ -21,11 +21,11 @@ def signed_rank(dist, alpha=0.05): """ - logger.info('Performing Wilcoxon signed-rank test ...') + logger.info("Performing Wilcoxon signed-rank test ...") output = w.statistical_pipeline(s.wilcoxon, dist, alpha) - logger.info('Test performed.') + logger.info("Test performed.") logger.debug(output) return output @@ -43,11 +43,11 @@ def rank_sum(dist, alpha=0.05): """ - logger.info('Performing Wilcoxon rank-sum test ...') + logger.info("Performing Wilcoxon rank-sum test ...") output = w.statistical_pipeline(s.ranksums, dist, alpha) - logger.info('Test performed.') + logger.info("Test performed.") logger.debug(output) return output diff --git a/statys/utils/constants.py b/statys/utils/constants.py index 1d9ec7e..4f8c674 100644 --- a/statys/utils/constants.py +++ b/statys/utils/constants.py @@ -3,103 +3,107 @@ # Defines the critical values used in Friedman's post-hoc analysis # Significance values: 0.01, 0.05, 0.1 -CRITICAL_VALUES = {'nemenyi': [[0, 0, 0], - [2.575829491, 1.959964233, 1.64485341], - [2.913494192, 2.343700476, 2.05229258], - [3.113250443, 2.569032073, 2.291341341], - [3.254685942, 2.727774717, 2.459516082], - [3.363740192, 2.849705382, 2.588520643], - [3.452212685, 2.948319908, 2.692731919], - [3.526470918, 3.030878867, 2.779883537], - [3.590338924, 3.10173026, 2.854606339], - [3.646291577, 3.16368342, 2.919888558], - [3.696020982, 3.218653901, 2.977768077], - [3.740733465, 3.268003591, 3.029694463], - [3.781318566, 3.312738701, 3.076733328], - [3.818450865, 3.353617959, 3.1196936], - [3.852654327, 3.391230382, 3.159198949], - [3.884343317, 3.426041249, 3.195743642], - [3.913850176, 3.458424619, 3.229723658], - [3.941446432, 3.488684546, 3.261461439], - [3.967356946, 3.517072762, 3.29122427], - [3.991769808, 3.543799277, 3.31923277], - [4.014841995, 3.569040161, 3.345675735], - [4.036709272, 3.592946027, 3.370711558], - [4.057487605, 3.615646276, 3.39447671], - [4.077275281, 3.637252631, 3.417089277], - [4.096160689, 3.657860551, 3.438651085], - [4.114219489, 3.677556303, 3.459252641], - [4.131518856, 3.696413427, 3.478971727], - [4.148118188, 3.71449839, 3.497877641], - [4.164069103, 3.731869175, 3.516032608], - [4.179419684, 3.748578108, 3.533492489], - [4.194212358, 3.764671858, 3.550305367], - [4.208483894, 3.780192852, 3.566516497], - [4.222268941, 3.795178566, 3.58216477], - [4.235598611, 3.809663649, 3.597287662], - [4.248501188, 3.823679212, 3.611916995], - [4.261002129, 3.837254248, 3.626083879], - [4.273124768, 3.850413505, 3.639814478], - [4.284891024, 3.863181025, 3.653134249], - [4.296319991, 3.875578729, 3.666065818], - [4.307430053, 3.887627121, 3.678630398], - [4.31823818, 3.899344587, 3.690847789], - [4.328759929, 3.910747391, 3.702736375], - [4.339009442, 3.921852503, 3.714311713], - [4.348999447, 3.932673359, 3.725589359], - [4.358743378, 3.943224099, 3.736584163], - [4.368251843, 3.953518159, 3.747309558], - [4.377536155, 3.963566147, 3.757777567], - [4.386605506, 3.973379375, 3.767999503], - [4.395470504, 3.98296845, 3.777987386], - [4.404138926, 3.992343271, 3.787749702], - [4.412619258, 4.001512325, 3.797297058], - [4.42091857, 4.010484803, 3.806637939], - [4.429046055, 4.019267776, 3.815781537], - [4.437006664, 4.02786973, 3.824734923], - [4.444807466, 4.036297029, 3.833505168], - [4.452454825, 4.044556036, 3.842100758], - [4.4599544, 4.05265453, 3.850526642], - [4.467311139, 4.060596753, 3.858790599], - [4.474529992, 4.068389777, 3.866897579], - [4.481617323, 4.076037844, 3.874853237], - [4.488575961, 4.083547318, 3.882663231], - [4.495411562, 4.090921028, 3.890333219], - [4.50212837, 4.098166044, 3.897866734], - [4.508729212, 4.105284488, 3.905268728], - [4.51521833, 4.112282016, 3.912543443], - [4.521599969, 4.119161458, 3.919695828], - [4.527876956, 4.125927056, 3.926729419], - [4.53405212, 4.132582345, 3.933647045], - [4.540129702, 4.139131568, 3.940452947], - [4.546111826, 4.145576139, 3.94715137], - [4.552002025, 4.151921008, 3.953744433], - [4.557802422, 4.158168297, 3.960235674], - [4.563515138, 4.164320833, 3.966628626], - [4.569143708, 4.170380738, 3.972924705], - [4.574690253, 4.176352255, 3.979128153], - [4.580156896, 4.182236797, 3.985240384], - [4.585545757, 4.188036487, 3.991264934], - [4.590859664, 4.19375486, 3.997203923], - [4.596099325, 4.199392622, 4.003058768], - [4.601267569, 4.204952603, 4.008833001], - [4.606365809, 4.21043763, 4.01452804], - [4.611396874, 4.215848411, 4.02014671], - [4.616481678, 4.221187067, 4.02568972], - [4.621261013, 4.22645572, 4.031159898], - [4.626098331, 4.23165649, 4.036558658], - [4.63087413, 4.236790793, 4.041887415], - [4.635590532, 4.241859334, 4.047148997], - [4.64024683, 4.246864943, 4.052344817], - [4.644847267, 4.251809034, 4.057475584], - [4.649391842, 4.256692313, 4.062543418], - [4.65388197, 4.261516196, 4.067549734], - [4.658319065, 4.266282802, 4.072495239], - [4.662703834, 4.270992841, 4.077382761], - [4.667037692, 4.275648432, 4.082213008], - [4.671322759, 4.280249575, 4.086986686], - [4.675558329, 4.284798393, 4.091705209], - [4.679746522, 4.289294885, 4.0963707], - [4.683888754, 4.29374188, 4.100983157], - [4.687985023, 4.298139377, 4.105544703], - [4.692036745, 4.302488791, 4.110055337]]} +CRITICAL_VALUES = { + "nemenyi": [ + [0, 0, 0], + [2.575829491, 1.959964233, 1.64485341], + [2.913494192, 2.343700476, 2.05229258], + [3.113250443, 2.569032073, 2.291341341], + [3.254685942, 2.727774717, 2.459516082], + [3.363740192, 2.849705382, 2.588520643], + [3.452212685, 2.948319908, 2.692731919], + [3.526470918, 3.030878867, 2.779883537], + [3.590338924, 3.10173026, 2.854606339], + [3.646291577, 3.16368342, 2.919888558], + [3.696020982, 3.218653901, 2.977768077], + [3.740733465, 3.268003591, 3.029694463], + [3.781318566, 3.312738701, 3.076733328], + [3.818450865, 3.353617959, 3.1196936], + [3.852654327, 3.391230382, 3.159198949], + [3.884343317, 3.426041249, 3.195743642], + [3.913850176, 3.458424619, 3.229723658], + [3.941446432, 3.488684546, 3.261461439], + [3.967356946, 3.517072762, 3.29122427], + [3.991769808, 3.543799277, 3.31923277], + [4.014841995, 3.569040161, 3.345675735], + [4.036709272, 3.592946027, 3.370711558], + [4.057487605, 3.615646276, 3.39447671], + [4.077275281, 3.637252631, 3.417089277], + [4.096160689, 3.657860551, 3.438651085], + [4.114219489, 3.677556303, 3.459252641], + [4.131518856, 3.696413427, 3.478971727], + [4.148118188, 3.71449839, 3.497877641], + [4.164069103, 3.731869175, 3.516032608], + [4.179419684, 3.748578108, 3.533492489], + [4.194212358, 3.764671858, 3.550305367], + [4.208483894, 3.780192852, 3.566516497], + [4.222268941, 3.795178566, 3.58216477], + [4.235598611, 3.809663649, 3.597287662], + [4.248501188, 3.823679212, 3.611916995], + [4.261002129, 3.837254248, 3.626083879], + [4.273124768, 3.850413505, 3.639814478], + [4.284891024, 3.863181025, 3.653134249], + [4.296319991, 3.875578729, 3.666065818], + [4.307430053, 3.887627121, 3.678630398], + [4.31823818, 3.899344587, 3.690847789], + [4.328759929, 3.910747391, 3.702736375], + [4.339009442, 3.921852503, 3.714311713], + [4.348999447, 3.932673359, 3.725589359], + [4.358743378, 3.943224099, 3.736584163], + [4.368251843, 3.953518159, 3.747309558], + [4.377536155, 3.963566147, 3.757777567], + [4.386605506, 3.973379375, 3.767999503], + [4.395470504, 3.98296845, 3.777987386], + [4.404138926, 3.992343271, 3.787749702], + [4.412619258, 4.001512325, 3.797297058], + [4.42091857, 4.010484803, 3.806637939], + [4.429046055, 4.019267776, 3.815781537], + [4.437006664, 4.02786973, 3.824734923], + [4.444807466, 4.036297029, 3.833505168], + [4.452454825, 4.044556036, 3.842100758], + [4.4599544, 4.05265453, 3.850526642], + [4.467311139, 4.060596753, 3.858790599], + [4.474529992, 4.068389777, 3.866897579], + [4.481617323, 4.076037844, 3.874853237], + [4.488575961, 4.083547318, 3.882663231], + [4.495411562, 4.090921028, 3.890333219], + [4.50212837, 4.098166044, 3.897866734], + [4.508729212, 4.105284488, 3.905268728], + [4.51521833, 4.112282016, 3.912543443], + [4.521599969, 4.119161458, 3.919695828], + [4.527876956, 4.125927056, 3.926729419], + [4.53405212, 4.132582345, 3.933647045], + [4.540129702, 4.139131568, 3.940452947], + [4.546111826, 4.145576139, 3.94715137], + [4.552002025, 4.151921008, 3.953744433], + [4.557802422, 4.158168297, 3.960235674], + [4.563515138, 4.164320833, 3.966628626], + [4.569143708, 4.170380738, 3.972924705], + [4.574690253, 4.176352255, 3.979128153], + [4.580156896, 4.182236797, 3.985240384], + [4.585545757, 4.188036487, 3.991264934], + [4.590859664, 4.19375486, 3.997203923], + [4.596099325, 4.199392622, 4.003058768], + [4.601267569, 4.204952603, 4.008833001], + [4.606365809, 4.21043763, 4.01452804], + [4.611396874, 4.215848411, 4.02014671], + [4.616481678, 4.221187067, 4.02568972], + [4.621261013, 4.22645572, 4.031159898], + [4.626098331, 4.23165649, 4.036558658], + [4.63087413, 4.236790793, 4.041887415], + [4.635590532, 4.241859334, 4.047148997], + [4.64024683, 4.246864943, 4.052344817], + [4.644847267, 4.251809034, 4.057475584], + [4.649391842, 4.256692313, 4.062543418], + [4.65388197, 4.261516196, 4.067549734], + [4.658319065, 4.266282802, 4.072495239], + [4.662703834, 4.270992841, 4.077382761], + [4.667037692, 4.275648432, 4.082213008], + [4.671322759, 4.280249575, 4.086986686], + [4.675558329, 4.284798393, 4.091705209], + [4.679746522, 4.289294885, 4.0963707], + [4.683888754, 4.29374188, 4.100983157], + [4.687985023, 4.298139377, 4.105544703], + [4.692036745, 4.302488791, 4.110055337], + ] +} diff --git a/statys/utils/exception.py b/statys/utils/exception.py index a7bb808..eb9649d 100644 --- a/statys/utils/exception.py +++ b/statys/utils/exception.py @@ -1,9 +1,9 @@ """Exceptions. """ -import statys.utils.logging as l +from statys.utils import logging -logger = l.get_logger(__name__) +logger = logging.get_logger(__name__) class Error(Exception): @@ -13,80 +13,72 @@ class Error(Exception): """ - def __init__(self, cls, msg): + def __init__(self, cls: str, msg: str) -> None: """Initialization method. Args: - cls (str): Class identifier. - msg (str): Message to be logged. + cls: Class identifier. + msg: Message to be logged. """ super(Error, self).__init__() # Logs the error in a formatted way - logger.error('%s: %s.', cls, msg) + logger.error("%s: %s.", cls, msg) class ArgumentError(Error): - """An ArgumentError class for logging errors related to wrong number of provided arguments. + """An ArgumentError class for logging errors related to wrong number of provided arguments.""" - """ - - def __init__(self, error): + def __init__(self, error: str) -> None: """Initialization method. Args: - error (str): Error message to be logged. + error: Error message to be logged. """ - super(ArgumentError, self).__init__('ArgumentError', error) + super(ArgumentError, self).__init__("ArgumentError", error) class SizeError(Error): - """A SizeError class for logging errors related to wrong length or size of variables. - - """ + """A SizeError class for logging errors related to wrong length or size of variables.""" - def __init__(self, error): + def __init__(self, error: str) -> None: """Initialization method. Args: - error (str): Error message to be logged. + error: Error message to be logged. """ - super(SizeError, self).__init__('SizeError', error) + super(SizeError, self).__init__("SizeError", error) class TypeError(Error): - """A TypeError class for logging errors related to wrong type of variables. + """A TypeError class for logging errors related to wrong type of variables.""" - """ - - def __init__(self, error): + def __init__(self, error: str) -> None: """Initialization method. Args: - error (str): Error message to be logged. + error: Error message to be logged. """ - super(TypeError, self).__init__('TypeError', error) + super(TypeError, self).__init__("TypeError", error) class ValueError(Error): - """A ValueError class for logging errors related to wrong value of variables. - - """ + """A ValueError class for logging errors related to wrong value of variables.""" - def __init__(self, error): + def __init__(self, error: str) -> None: """Initialization method. Args: - error (str): Error message to be logged. + error: Error message to be logged. """ - super(ValueError, self).__init__('ValueError', error) + super(ValueError, self).__init__("ValueError", error) diff --git a/statys/utils/logging.py b/statys/utils/logging.py index ef9ea5c..af73605 100644 --- a/statys/utils/logging.py +++ b/statys/utils/logging.py @@ -3,51 +3,51 @@ import logging import sys +from logging import Logger, StreamHandler from logging.handlers import TimedRotatingFileHandler -FORMATTER = logging.Formatter( - "%(asctime)s - %(name)s — %(levelname)s — %(message)s") +FORMATTER = logging.Formatter("%(asctime)s - %(name)s — %(levelname)s — %(message)s") LOG_FILE = "statys.log" -def get_console_handler(): +def get_console_handler() -> StreamHandler: """Gets a console handler to handle logging into console. Returns: - A handler to output information into console. + (StreamHandler): Handler to output information into console. """ # Creates a stream handler for logger - console_handler = logging.StreamHandler(sys.stdout) + console_handler = StreamHandler(sys.stdout) console_handler.setFormatter(FORMATTER) return console_handler -def get_timed_file_handler(): +def get_timed_file_handler() -> TimedRotatingFileHandler: """Gets a timed file handler to handle logging into files. Returns: - A handler to output information into timed files. + (TimedRotatingFileHandler): Handler to output information into timed files. """ # Creates a timed rotating file handler for logger - file_handler = TimedRotatingFileHandler(LOG_FILE, delay=True, when='midnight') + file_handler = TimedRotatingFileHandler(LOG_FILE, delay=True, when="midnight") file_handler.setFormatter(FORMATTER) return file_handler -def get_logger(logger_name): - """Gets a log and make it avaliable for further use. +def get_logger(logger_name: str) -> Logger: + """Gets a logger and make it avaliable for further use. Args: - logger_name (str): The name of the logger. + logger_name: The name of the logger. Returns: - A handler to output information into console's. + (Logger): Logger instance. """ diff --git a/statys/utils/wrappers.py b/statys/utils/wrappers.py index 279be03..3ded026 100644 --- a/statys/utils/wrappers.py +++ b/statys/utils/wrappers.py @@ -2,15 +2,20 @@ """ -def calculate_hypothesis(p, alpha): +from typing import Any, Dict + +from statys.core.distribution import Distribution + + +def calculate_hypothesis(p: float, alpha: float) -> bool: """Calculates whether hypothesis' rejection fails or not according to a significance value. Args: - p (float): P-value from a statistical test. - alpha (float): Significance value. + p: P-value from a statistical test. + alpha: Significance value. Returns: - 1 if hypothesis is rejected and 0 if it failed to be rejected. + (bool): 1 if hypothesis is rejected and 0 if it failed to be rejected. """ @@ -25,15 +30,15 @@ def calculate_hypothesis(p, alpha): return h -def measure_pipeline(measure, dist, **kwargs): +def measure_pipeline(measure: callable, dist: Distribution, **kwargs) -> Dict[str, Any]: """Wraps the pipeline of conducting a measure. Args: - measure (pointer): Pointer to a measure function. - dist (Distribution): Distribution to be analyzed. + measure: Pointer to a measure function. + dist: Distribution to be analyzed. Returns: - Dictionary holding the test's outputs. + (Dict[str, Any]): Test's outputs. """ @@ -47,16 +52,18 @@ def measure_pipeline(measure, dist, **kwargs): return output -def statistical_pipeline(test, dist, alpha): +def statistical_pipeline( + test: callable, dist: Distribution, alpha: float +) -> Dict[str, Any]: """Wraps the pipeline of conducting a statistical test and calculating its hypothesis. Args: - test (pointer): Pointer to a statistical test. - dist (Distribution): Distribution to be analyzed. - alpha (float): Significance value. + test: Pointer to a statistical test. + dist: Distribution to be analyzed. + alpha: Significance value. Returns: - Dictionary holding the test's outputs. + (Dict[str, Any]): Test's outputs. """ @@ -70,7 +77,7 @@ def statistical_pipeline(test, dist, alpha): else: # Creates a key to the dictionary - key = attr + '-' + attr2 + key = attr + "-" + attr2 # Performs the statistical test _, p = test(value, value2) diff --git a/tests/statys/tests/test_friedman.py b/tests/statys/tests/test_friedman.py index 4e9151a..dc6a43c 100644 --- a/tests/statys/tests/test_friedman.py +++ b/tests/statys/tests/test_friedman.py @@ -8,7 +8,7 @@ def test_friedman(): output = friedman.friedman(d) - assert output['arg0'] == ((10.76923076923077, 11), (0.0, (11, 0))) + assert output["arg0"] == ((10.76923076923077, 11), (0.0, (11, 0))) def test_friedman_with_posthoc(): @@ -17,5 +17,5 @@ def test_friedman_with_posthoc(): output = friedman.friedman_with_posthoc(d, axis=1) - assert len(output['arg0'][0]) == 6 - assert output['arg0'][1] == 5.331310596344878 + assert len(output["arg0"][0]) == 6 + assert output["arg0"][1] == 5.331310596344878 diff --git a/tests/statys/tests/test_mann_whitney.py b/tests/statys/tests/test_mann_whitney.py index a0406d0..446b7b1 100644 --- a/tests/statys/tests/test_mann_whitney.py +++ b/tests/statys/tests/test_mann_whitney.py @@ -9,4 +9,7 @@ def test_u_test(): output = mann_whitney.u_test(d) - assert output['arg0-arg1'] == (0, 0.18923879662233944) or output['arg0-arg1'] == (0, 0.3939393939393939) + assert output["arg0-arg1"] == (0, 0.18923879662233944) or output["arg0-arg1"] == ( + 0, + 0.3939393939393939, + ) diff --git a/tests/statys/tests/test_measure.py b/tests/statys/tests/test_measure.py index 159a6d1..a30887a 100644 --- a/tests/statys/tests/test_measure.py +++ b/tests/statys/tests/test_measure.py @@ -8,7 +8,7 @@ def test_kurtosis(): output = measure.kurtosis(d) - assert output['arg0'] == -1.268571428571428 + assert output["arg0"] == -1.268571428571428 def test_max(): @@ -17,7 +17,7 @@ def test_max(): output = measure.max(d) - assert output['arg0'] == 0.5 + assert output["arg0"] == 0.5 def test_mean(): @@ -26,7 +26,7 @@ def test_mean(): output = measure.mean(d) - assert output['arg0'] == 0.25 + assert output["arg0"] == 0.25 def test_median(): @@ -35,7 +35,7 @@ def test_median(): output = measure.median(d) - assert output['arg0'] == 0.25 + assert output["arg0"] == 0.25 def test_min(): @@ -44,7 +44,7 @@ def test_min(): output = measure.min(d) - assert output['arg0'] == 0 + assert output["arg0"] == 0 def test_rank(): @@ -53,7 +53,7 @@ def test_rank(): output = measure.rank(d) - assert len(output['arg0']) == 6 + assert len(output["arg0"]) == 6 def test_skewness(): @@ -62,7 +62,7 @@ def test_skewness(): output = measure.skewness(d) - assert output['arg0'] == 5.804286057433026e-17 + assert output["arg0"] == 5.804286057433026e-17 def test_std(): @@ -71,7 +71,7 @@ def test_std(): output = measure.std(d) - assert output['arg0'] == 0.1707825127659933 + assert output["arg0"] == 0.1707825127659933 def test_var(): @@ -80,4 +80,4 @@ def test_var(): output = measure.var(d) - assert output['arg0'] == 0.029166666666666664 + assert output["arg0"] == 0.029166666666666664 diff --git a/tests/statys/tests/test_wilcoxon.py b/tests/statys/tests/test_wilcoxon.py index 2f09483..eec4728 100644 --- a/tests/statys/tests/test_wilcoxon.py +++ b/tests/statys/tests/test_wilcoxon.py @@ -9,7 +9,7 @@ def test_signed_rank(): output = wilcoxon.signed_rank(d) - assert output['arg0-arg1'] == (0, 0.15625) + assert output["arg0-arg1"] == (0, 0.15625) def test_rank_sum(): @@ -19,4 +19,4 @@ def test_rank_sum(): output = wilcoxon.rank_sum(d) - assert output['arg0-arg1'] == (0, 0.3366683676100388) + assert output["arg0-arg1"] == (0, 0.3366683676100388) diff --git a/tests/statys/utils/test_constants.py b/tests/statys/utils/test_constants.py index b9c14a1..a7cd53d 100644 --- a/tests/statys/utils/test_constants.py +++ b/tests/statys/utils/test_constants.py @@ -2,4 +2,4 @@ def test_constants(): - assert len(constants.CRITICAL_VALUES['nemenyi']) == 100 + assert len(constants.CRITICAL_VALUES["nemenyi"]) == 100 diff --git a/tests/statys/utils/test_exception.py b/tests/statys/utils/test_exception.py index ce94fb6..71ded11 100644 --- a/tests/statys/utils/test_exception.py +++ b/tests/statys/utils/test_exception.py @@ -2,7 +2,7 @@ def test_error(): - new_exception = exception.Error('Error', 'error') + new_exception = exception.Error("Error", "error") try: raise new_exception @@ -11,7 +11,7 @@ def test_error(): def test_argument_error(): - new_exception = exception.ArgumentError('error') + new_exception = exception.ArgumentError("error") try: raise new_exception @@ -20,7 +20,7 @@ def test_argument_error(): def test_size_error(): - new_exception = exception.SizeError('error') + new_exception = exception.SizeError("error") try: raise new_exception @@ -29,7 +29,7 @@ def test_size_error(): def test_type_error(): - new_exception = exception.TypeError('error') + new_exception = exception.TypeError("error") try: raise new_exception @@ -38,7 +38,7 @@ def test_type_error(): def test_value_error(): - new_exception = exception.ValueError('error') + new_exception = exception.ValueError("error") try: raise new_exception diff --git a/tests/statys/utils/test_logging.py b/tests/statys/utils/test_logging.py index 23fca24..35337eb 100644 --- a/tests/statys/utils/test_logging.py +++ b/tests/statys/utils/test_logging.py @@ -4,18 +4,18 @@ def test_get_console_handler(): c = logging.get_console_handler() - assert c != None + assert c is not None def test_get_file_handler(): f = logging.get_timed_file_handler() - assert f != None + assert f is not None def test_get_logger(): logger = logging.get_logger(__name__) - assert logger.name == 'test_logging' + assert logger.name == "test_logging" - assert logger.hasHandlers() == True + assert logger.hasHandlers() is True diff --git a/tests/statys/utils/test_wrappers.py b/tests/statys/utils/test_wrappers.py index 4e3ab51..8778c51 100644 --- a/tests/statys/utils/test_wrappers.py +++ b/tests/statys/utils/test_wrappers.py @@ -19,7 +19,7 @@ def f(x): output = wrappers.measure_pipeline(f, d) - assert output['arg0'] == True + assert output["arg0"] is True def test_statistical_pipeline(): @@ -31,4 +31,4 @@ def f(x, y): output = wrappers.statistical_pipeline(f, d, alpha) - assert output['arg0-arg1'] == (1, 0) + assert output["arg0-arg1"] == (1, 0)