├── .credo.exs ├── .formatter.exs ├── .github └── workflows │ └── main.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── LICENSE.md ├── README.md ├── coveralls.json ├── lib ├── statistex.ex └── statistex │ ├── helper.ex │ ├── mode.ex │ └── percentile.ex ├── mix.exs ├── mix.lock └── test ├── statistex ├── mode_test.exs └── percentile_test.exs ├── statistex_test.exs └── test_helper.exs /.credo.exs: -------------------------------------------------------------------------------- 1 | # This file contains the configuration for Credo and you are probably reading 2 | # this after creating it with `mix credo.gen.config`. 3 | # 4 | # If you find anything wrong or unclear in this file, please report an 5 | # issue on GitHub: https://github.com/rrrene/credo/issues 6 | # 7 | %{ 8 | # 9 | # You can have as many configs as you like in the `configs:` field. 10 | configs: [ 11 | %{ 12 | # 13 | # Run any exec using `mix credo -C `. If no exec name is given 14 | # "default" is used. 15 | # 16 | name: "default", 17 | # 18 | # These are the files included in the analysis: 19 | files: %{ 20 | # 21 | # You can give explicit globs or simply directories. 22 | # In the latter case `**/*.{ex,exs}` will be used. 23 | # 24 | included: ["lib/", "src/", "test/", "web/", "apps/"], 25 | excluded: [~r"/_build/", ~r"/deps/"] 26 | }, 27 | # 28 | # If you create your own checks, you must specify the source files for 29 | # them here, so they can be loaded by Credo before running the analysis. 30 | # 31 | requires: [], 32 | # 33 | # If you want to enforce a style guide and need a more traditional linting 34 | # experience, you can change `strict` to `true` below: 35 | # 36 | strict: true, 37 | # 38 | # If you want to use uncolored output by default, you can change `color` 39 | # to `false` below: 40 | # 41 | color: true, 42 | # 43 | # You can customize the parameters of any check by adding a second element 44 | # to the tuple. 45 | # 46 | # To disable a check put `false` as second element: 47 | # 48 | # {Credo.Check.Design.DuplicatedCode, false} 49 | # 50 | checks: [ 51 | # 52 | ## Consistency Checks 53 | # 54 | {Credo.Check.Consistency.ExceptionNames}, 55 | {Credo.Check.Consistency.LineEndings}, 56 | {Credo.Check.Consistency.ParameterPatternMatching}, 57 | {Credo.Check.Consistency.SpaceAroundOperators}, 58 | {Credo.Check.Consistency.SpaceInParentheses}, 59 | {Credo.Check.Consistency.TabsOrSpaces}, 60 | 61 | # 62 | ## Design Checks 63 | # 64 | # You can customize the priority of any check 65 | # Priority values are: `low, normal, high, higher` 66 | # 67 | {Credo.Check.Design.AliasUsage, false}, 68 | # For some checks, you can also set other parameters 69 | # 70 | # If you don't want the `setup` and `test` macro calls in ExUnit tests 71 | # or the `schema` macro in Ecto schemas to trigger DuplicatedCode, just 72 | # set the `excluded_macros` parameter to `[:schema, :setup, :test]`. 73 | # 74 | {Credo.Check.Design.DuplicatedCode, excluded_macros: []}, 75 | # You can also customize the exit_status of each check. 76 | # If you don't want TODO comments to cause `mix credo` to fail, just 77 | # set this value to 0 (zero). 78 | # 79 | {Credo.Check.Design.TagTODO, exit_status: 2}, 80 | {Credo.Check.Design.TagFIXME}, 81 | 82 | # 83 | ## Readability Checks 84 | # 85 | {Credo.Check.Readability.FunctionNames}, 86 | {Credo.Check.Readability.LargeNumbers}, 87 | {Credo.Check.Readability.MaxLineLength, priority: :low, max_length: 98}, 88 | {Credo.Check.Readability.ModuleAttributeNames}, 89 | {Credo.Check.Readability.ModuleDoc}, 90 | {Credo.Check.Readability.ModuleNames}, 91 | {Credo.Check.Readability.ParenthesesOnZeroArityDefs}, 92 | {Credo.Check.Readability.ParenthesesInCondition}, 93 | {Credo.Check.Readability.PredicateFunctionNames}, 94 | {Credo.Check.Readability.PreferImplicitTry}, 95 | {Credo.Check.Readability.RedundantBlankLines}, 96 | {Credo.Check.Readability.StringSigils}, 97 | {Credo.Check.Readability.TrailingBlankLine}, 98 | {Credo.Check.Readability.TrailingWhiteSpace}, 99 | {Credo.Check.Readability.VariableNames}, 100 | {Credo.Check.Readability.Semicolons}, 101 | {Credo.Check.Readability.SpaceAfterCommas}, 102 | 103 | # 104 | ## Refactoring Opportunities 105 | # 106 | {Credo.Check.Refactor.DoubleBooleanNegation}, 107 | {Credo.Check.Refactor.CondStatements}, 108 | {Credo.Check.Refactor.CyclomaticComplexity}, 109 | {Credo.Check.Refactor.FunctionArity}, 110 | {Credo.Check.Refactor.LongQuoteBlocks}, 111 | {Credo.Check.Refactor.MatchInCondition}, 112 | {Credo.Check.Refactor.NegatedConditionsInUnless}, 113 | {Credo.Check.Refactor.NegatedConditionsWithElse}, 114 | {Credo.Check.Refactor.Nesting}, 115 | {Credo.Check.Refactor.PipeChainStart, 116 | excluded_argument_types: [:atom, :binary, :fn, :keyword], excluded_functions: []}, 117 | {Credo.Check.Refactor.UnlessWithElse}, 118 | 119 | # 120 | ## Warnings 121 | # 122 | {Credo.Check.Warning.BoolOperationOnSameValues}, 123 | {Credo.Check.Warning.ExpensiveEmptyEnumCheck}, 124 | {Credo.Check.Warning.IExPry}, 125 | {Credo.Check.Warning.IoInspect}, 126 | {Credo.Check.Warning.LazyLogging}, 127 | {Credo.Check.Warning.OperationOnSameValues}, 128 | {Credo.Check.Warning.OperationWithConstantResult}, 129 | {Credo.Check.Warning.UnusedEnumOperation}, 130 | {Credo.Check.Warning.UnusedFileOperation}, 131 | {Credo.Check.Warning.UnusedKeywordOperation}, 132 | {Credo.Check.Warning.UnusedListOperation}, 133 | {Credo.Check.Warning.UnusedPathOperation}, 134 | {Credo.Check.Warning.UnusedRegexOperation}, 135 | {Credo.Check.Warning.UnusedStringOperation}, 136 | {Credo.Check.Warning.UnusedTupleOperation}, 137 | {Credo.Check.Warning.RaiseInsideRescue}, 138 | 139 | # 140 | # Controversial and experimental checks (opt-in, just remove `, false`) 141 | # 142 | {Credo.Check.Refactor.ABCSize, false}, 143 | {Credo.Check.Refactor.AppendSingleItem, false}, 144 | {Credo.Check.Refactor.VariableRebinding, false}, 145 | {Credo.Check.Warning.MapGetUnsafePass, false}, 146 | {Credo.Check.Consistency.MultiAliasImportRequireUse, false}, 147 | 148 | # 149 | # Deprecated checks (these will be deleted after a grace period) 150 | # 151 | {Credo.Check.Readability.Specs, false} 152 | 153 | # 154 | # Custom checks can be created using `mix credo.gen.check`. 155 | # 156 | ] 157 | } 158 | ] 159 | } 160 | -------------------------------------------------------------------------------- /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test,samples,mix}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | env: 4 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 5 | 6 | on: [pull_request, push] 7 | 8 | jobs: 9 | linux: 10 | name: Test on Ubuntu (Elixir ${{ matrix.elixir_version }}, OTP ${{ matrix.otp_version }}) 11 | runs-on: ubuntu-24.04 12 | 13 | strategy: 14 | matrix: 15 | # Run tests at least once for every supported elixir or erlang version 16 | # 17 | # Since all the code is running at least once with each version, that should cover enough. 18 | # Like, what are the chances a bug would happen on 1.18@26 but not on 1.17@26 or 1.18@27? 19 | # And if it does, it's more likely an elixir bug than a benchee bug. We'll see. 20 | # We've been using enough of githubs CI resources and our own wait time :) 21 | # 22 | # https://hexdocs.pm/elixir/compatibility-and-deprecations.html#between-elixir-and-erlang-otp 23 | # 24 | # We're also further limited by the support the setup-beam action offers: 25 | # https://github.com/erlef/setup-beam?tab=readme-ov-file#compatibility-between-operating-system-and-erlangotp 26 | include: 27 | # stream_data doesn't support elixir 1.11 and below 28 | # https://github.com/whatyouhide/stream_data/blob/main/CHANGELOG.md#v110 29 | - elixir_version: '1.12' 30 | otp_version: '24.3' 31 | - elixir_version: '1.13' 32 | otp_version: '25.3' 33 | - elixir_version: '1.14' 34 | otp_version: '25.3' 35 | - elixir_version: '1.15' 36 | otp_version: '26.2' 37 | - elixir_version: '1.16' 38 | otp_version: '26.2' 39 | - elixir_version: '1.17' 40 | otp_version: '27.3' 41 | - elixir_version: '1.18' 42 | otp_version: '27.3' 43 | type_check: true 44 | lint: true 45 | 46 | steps: 47 | - name: Checkout 48 | uses: actions/checkout@v3 49 | - name: Setup Elixir 50 | uses: erlef/setup-beam@v1 51 | with: 52 | elixir-version: ${{ matrix.elixir_version }} 53 | otp-version: ${{ matrix.otp_version }} 54 | - name: Restore deps and _build 55 | uses: actions/cache@v3 56 | with: 57 | path: | 58 | deps 59 | _build 60 | key: erlef-${{ runner.os }}-mix-${{ matrix.elixir_version }}-${{ matrix.otp_version }}-${{ hashFiles(format('{0}{1}', github.workspace, '/mix.lock')) }} 61 | - name: Restore plts 62 | uses: actions/cache@v3 63 | with: 64 | path: tools/plts 65 | key: erlef-${{ runner.os }}-dialyzer-${{ matrix.elixir_version }}-${{ matrix.otp_version }}-${{ hashFiles(format('{0}{1}', github.workspace, '/mix.lock')) }} 66 | if: ${{ matrix.type_check }} 67 | - run: mix deps.get 68 | - run: MIX_ENV=test mix compile --warnings-as-errors 69 | - run: mix credo 70 | if: ${{ matrix.lint }} 71 | - name: Check if formatted 72 | if: ${{ matrix.lint }} 73 | run: mix format --check-formatted 74 | - name: Actual Tests 75 | # this will let warnings slip through but I don't wanna replicate all that magic 76 | # right now 77 | run: MIX_ENV=test mix coveralls.github || mix test --failed 78 | # Apparently the one with `!` can't go without the fancy expression syntax 79 | if: ${{ !matrix.lint }} 80 | # warnings as errors is a form of linting! 81 | - name: Actual Tests WITH warnings as errors 82 | run: MIX_ENV=test mix coveralls.github --warnings-as-errors || mix test --failed 83 | if: ${{ matrix.lint }} 84 | - name: Dialyzer 85 | run: mix dialyzer --halt-exit-status 86 | if: ${{ matrix.type_check }} 87 | 88 | macos: 89 | name: Test on MacOS 90 | runs-on: macos-latest 91 | 92 | steps: 93 | - name: Checkout 94 | uses: actions/checkout@v3 95 | # no versioning on brew but getting asdf or something was a bigger headache 96 | - name: Install Elixir 97 | run: brew install elixir 98 | - name: Restore deps and _build 99 | uses: actions/cache@v3 100 | with: 101 | path: | 102 | deps 103 | _build 104 | key: ${{ runner.os }}-mix-${{ hashFiles(format('{0}{1}', github.workspace, '/mix.lock')) }} 105 | - run: mix local.hex --force 106 | - run: mix deps.get 107 | - run: mix local.rebar --force 108 | - run: MIX_ENV=test mix compile --warnings-as-errors 109 | - run: mix test || mix test --failed 110 | 111 | windows: 112 | name: Test on Windows 113 | runs-on: windows-2022 114 | 115 | steps: 116 | - name: Checkout 117 | uses: actions/checkout@v3 118 | - name: Setup Elixir 119 | uses: erlef/setup-beam@v1 120 | with: 121 | elixir-version: '1.18' 122 | otp-version: '27.3' 123 | - name: Get deps 124 | run: mix deps.get 125 | - name: Test 126 | run: mix test || mix test --failed 127 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /_build 2 | /cover 3 | /deps 4 | erl_crash.dump 5 | *.ez 6 | elixir_build_* 7 | doc 8 | docs 9 | /test/tmp 10 | 11 | # Don't feel like tracking that gives me what I want any more :) 12 | .tool-versions 13 | 14 | # dialyzer 15 | /tools 16 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 1.1 (Unreleased) 2 | 3 | This release adds functionality around identifying outliers. 4 | 5 | * the Statistex struct comes with more keys: `:lower_outlier_bound`, `:upper_outlier_bound` & `:outliers`, 6 | along with the new public functions `:outliers/2` and `:outlier_bounds/2`. 7 | * `statistics/2` now also accepts `exclude_outliers: true` to exclude the outliers from the calculation 8 | of statistics. 9 | * some functions have also been updated to accept more optional arguments such as `:sorted?` to avoid unnecessary extra work. 10 | 11 | Huge thanks for these changes go to [@NickNeck](https://github.com/NickNeck)! 12 | 13 | ## 1.0 2019-07-05 14 | 15 | Import of the initial functionality from [benchee](github.com/bencheeorg/benchee). 16 | 17 | Dubbed 1.0 because many people had already been running this code indirectly through benchee. 18 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at pragtob@gmail.com (sorry, just me for now). All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Tobias Pfeiffer 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Statistex [![Hex Version](https://img.shields.io/hexpm/v/statistex.svg)](https://hex.pm/packages/statistex) [![docs](https://img.shields.io/badge/docs-hexpm-blue.svg)](https://hexdocs.pm/statistex/) [![CI](https://github.com/bencheeorg/statistex/actions/workflows/main.yml/badge.svg)](https://github.com/bencheeorg/statistex/actions/workflows/main.yml) [![Coverage Status](https://coveralls.io/repos/github/bencheeorg/statistex/badge.svg?branch=main)](https://coveralls.io/github/bencheeorg/statistex?branch=main) 2 | 3 | Statistex helps you do common statistics calculations and to explore a data set. It focusses on two things: 4 | 5 | * providing you a `statistics/2` function that just **computes all statistics it knows for a data set**, reusing previously made calculations to not compute something again (for instance standard deviation needs the average, so it first computes the average and then passes it on): `Statistex.statistics(samples)` 6 | * gives you the opportunity to **pass known values to functions** so that it doesn't need to compute more than it absolutely needs to: `Statistex.standard_deviation(samples, average: computed_average)` 7 | 8 | ## Installation 9 | 10 | ```elixir 11 | def deps do 12 | [ 13 | {:statistex, "~> 1.0"} 14 | ] 15 | end 16 | ``` 17 | 18 | Supported elixir versions are 1.6+ (together with their respective erlang OTP versions aka 19+). 19 | Tests are only running against elixir 1.12+ though, as some dependencies aren't compatible with versions that old. 20 | But also, most people probably don't care about them. 21 | 22 | ## Usage 23 | 24 | Check out the [documentation of the main Statistex module](https://hexdocs.pm/statistex/Statistex.html) but here is a small overview: 25 | 26 | ```elixir 27 | iex> samples = [1, 3.0, 2.35, 11.0, 1.37, 35, 5.5, 10, 0, 2.35] 28 | # calculate all available statistics at once, efficiently reusing already calculated values 29 | iex> Statistex.statistics(samples) 30 | %Statistex{ 31 | average: 7.156999999999999, 32 | frequency_distribution: %{ 33 | 0 => 1, 34 | 1 => 1, 35 | 10 => 1, 36 | 35 => 1, 37 | 1.37 => 1, 38 | 2.35 => 2, 39 | 3.0 => 1, 40 | 5.5 => 1, 41 | 11.0 => 1 42 | }, 43 | maximum: 35, 44 | median: 2.675, 45 | minimum: 0, 46 | mode: 2.35, 47 | percentiles: %{50 => 2.675}, 48 | sample_size: 10, 49 | standard_deviation: 10.47189577445799, 50 | standard_deviation_ratio: 1.46316833512058, 51 | total: 71.57, 52 | variance: 109.6606011111111 53 | } 54 | # or just calculate the value you need 55 | iex> Statistex.average(samples) 56 | 7.156999999999999 57 | # Calculate the value you want reusing values you already know 58 | # (check the docs for what functions accepts what options) 59 | iex> Statistex.average(samples, sample_size: 10) 60 | 7.156999999999999 61 | # Most Statistex functions raise given an empty list as most functions don't make sense then. 62 | # It is recommended that you manually handle the empty list case should that occur as your 63 | # output is likely also very different from when you have statistics. 64 | iex> Statistex.statistics([]) 65 | ** (ArgumentError) Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number. 66 | ``` 67 | 68 | ## Supported Statistics 69 | 70 | For an up to date overview with explanations please check out the [documentation of the Statistex module](https://hexdocs.pm/statistex/Statistex.html). 71 | 72 | Statistics currently supported: 73 | 74 | * average 75 | * frequency_distribution 76 | * maximum 77 | * median 78 | * minimum 79 | * mode 80 | * percentiles 81 | * sample_size 82 | * standard_deviation 83 | * standard_deviation_ratio 84 | * total 85 | * variance 86 | 87 | ## Alternatives 88 | 89 | In elixir there are 2 notable other libraries that I'm aware of: [statistics](https://github.com/msharp/elixir-statistics) and [Numerix](https://github.com/safwank/Numerix). 90 | 91 | Both include more functions than just for statistics: general math and more (drawing of random values for instance). They also have more statistics related functions as of this writing. So if you'e looking for something, that Statistex doesn't provide (yet) these are some of the first places I'd look. 92 | 93 | Why would you still want to use Statistex? 94 | 95 | * `statistics/2` is really nice when you're just exploring a data set or just want to have _everything_ at once 96 | * when calling `statistics/2` Statistex **reuses previously calculated values** (_average_ for _standard_deviation_ for instance, or a sorted list of samples for some calculations) which makes for more efficient calculations. Statistex **extends that capability to you** so that you can pass pre calculated values as optional arguments. 97 | * small and focussed on just statistics :) 98 | 99 | We're naturally also looking to add more statistical functions as we go along, and pull requests are very welcome :) 100 | 101 | ## Performance 102 | 103 | Statistex is written in pure elixir. C-extensions and friends would surely be faster. The goal of statistex is to be as fast possible in pure elixir while providing correct results. Hence, the focus on reusing previously calculated values and providing that ability to users. 104 | 105 | ## History 106 | 107 | Statistex was extracted from [benchee](https://github.com/bencheeorg/benchee) and as such it powers benchees statistics calculations. Its great ancestor (if you will) was first conceived in [this commit](https://github.com/bencheeorg/benchee/commit/60fba66f927e0da20c4d16379dbf7274f77e63b5#diff-9d500e7ee9bd945a93b7172cca013d64). 108 | 109 | ## Contributing 110 | 111 | Contributions to benchee are **very welcome**! Bug reports, documentation, spelling corrections, new statistics, bugfixes... all of those (and probably more) are much appreciated contributions! 112 | 113 | Please respect the [Code of Conduct](//github.com/bencheeorg/statistex/blob/master/CODE_OF_CONDUCT.md). 114 | 115 | You can also look directly at the [open issues](https://github.com/bencheeorg/statistex/issues). 116 | 117 | A couple of (hopefully) helpful points: 118 | 119 | * Feel free to ask for help and guidance on an issue/PR ("How can I implement this?", "How could I test this?", ...) 120 | * Feel free to open early/not yet complete pull requests to get some early feedback 121 | * When in doubt if something is a good idea open an issue first to discuss it 122 | * In case I don't respond feel free to bump the issue/PR or ping me in other places 123 | 124 | ## Development 125 | 126 | * `mix deps.get` to install dependencies 127 | * `mix test` to run tests 128 | * `mix dialyzer` to run dialyzer for type checking, might take a while on the first invocation (try building plts first with `mix dialyzer --plt`) 129 | * `mix credo` to find code style problems 130 | -------------------------------------------------------------------------------- /coveralls.json: -------------------------------------------------------------------------------- 1 | { 2 | "default_stop_words": [ 3 | "defmodule", 4 | "defrecord", 5 | "defimpl", 6 | "defexception", 7 | "defprotocol", 8 | "defstruct", 9 | "def.+(.+\\\\.+).+do", 10 | "^\\s+use\\s+" 11 | ], 12 | 13 | "custom_stop_words": [ 14 | ], 15 | 16 | "coverage_options": { 17 | "treat_no_relevant_lines_as_covered": false, 18 | "output_dir": "cover/", 19 | "minimum_coverage": 0 20 | }, 21 | 22 | "terminal_options": { 23 | "file_column_width": 40 24 | }, 25 | 26 | "skip_files": [ 27 | "test/support" 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /lib/statistex.ex: -------------------------------------------------------------------------------- 1 | defmodule Statistex do 2 | @moduledoc """ 3 | Calculate all the statistics for given samples. 4 | 5 | Works all at once with `statistics/1` or has a lot of functions that can be triggered individually. 6 | 7 | To avoid wasting computation, function can be given values they depend on as optional keyword arguments so that these values can be used instead of recalculating them. For an example see `average/2`. 8 | 9 | Most statistics don't really make sense when there are no samples, for that reason all functions except for `sample_size/1` raise `ArgumentError` when handed an empty list. 10 | It is suggested that if it's possible for your program to throw an empty list at Statistex to handle that before handing it to Staistex to take care of the "no reasonable statistics" path entirely separately. 11 | 12 | Limitations of ther erlang standard library apply (particularly `:math.pow/2` raises for VERY large numbers). 13 | """ 14 | 15 | alias Statistex.{Mode, Percentile} 16 | require Integer 17 | 18 | import Statistex.Helper, only: [maybe_sort: 2] 19 | 20 | defstruct [ 21 | :total, 22 | :average, 23 | :variance, 24 | :standard_deviation, 25 | :standard_deviation_ratio, 26 | :median, 27 | :percentiles, 28 | :frequency_distribution, 29 | :mode, 30 | :minimum, 31 | :maximum, 32 | :lower_outlier_bound, 33 | :upper_outlier_bound, 34 | :outliers, 35 | sample_size: 0 36 | ] 37 | 38 | @typedoc """ 39 | All the statistics `statistics/1` computes from the samples. 40 | 41 | For a description of what a given value means please check out the function here by the same name, it will have an explanation. 42 | """ 43 | @type t :: %__MODULE__{ 44 | total: number, 45 | average: float, 46 | variance: float, 47 | standard_deviation: float, 48 | standard_deviation_ratio: float, 49 | median: number, 50 | percentiles: percentiles, 51 | frequency_distribution: %{sample => pos_integer}, 52 | mode: mode, 53 | minimum: number, 54 | maximum: number, 55 | lower_outlier_bound: number, 56 | upper_outlier_bound: number, 57 | outliers: [number], 58 | sample_size: non_neg_integer 59 | } 60 | 61 | @typedoc """ 62 | The samples to compute statistics from. 63 | 64 | Importantly this list is not empty/includes at least one sample otherwise an `ArgumentError` will be raised. 65 | """ 66 | @type samples :: [sample, ...] 67 | 68 | @typedoc """ 69 | A single sample/ 70 | """ 71 | @type sample :: number 72 | 73 | @typedoc """ 74 | The optional configuration handed to a lot of functions. 75 | 76 | Keys used are function dependent and are documented there. 77 | """ 78 | @type configuration :: keyword 79 | 80 | @typedoc """ 81 | Careful with the mode, might be multiple values, one value or nothing.😱 See `mode/1`. 82 | """ 83 | @type mode :: [sample()] | sample() | nil 84 | 85 | @typedoc """ 86 | The percentiles map returned by `percentiles/2`. 87 | """ 88 | @type percentiles :: %{number() => float} 89 | 90 | @empty_list_error_message "Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number." 91 | 92 | @first_quartile 25 93 | @median_percentile 50 94 | @third_quartile 75 95 | # https://en.wikipedia.org/wiki/Interquartile_range#Outliers 96 | # https://builtin.com/articles/1-5-iqr-rule 97 | @iqr_factor 1.5 98 | 99 | @doc """ 100 | Calculate all statistics Statistex offers for a given list of numbers. 101 | 102 | The statistics themselves are described in the individual samples that can be used to calculate individual values. 103 | 104 | `ArgumentError` is raised if the given list is empty. 105 | 106 | ## Options 107 | 108 | * `:percentiles`: percentiles to calculate (see `percentiles/2`). 109 | The percentiles 25th, 50th (median) and 75th are always calculated. 110 | * `:exclude_outliers` can be set to `true` or `false`. Defaults to `false`. 111 | If this option is set to `true` the outliers are excluded from the calculation 112 | of the statistics. 113 | * `:sorted?`: indicating the samples you're passing in are already sorted. Defaults to `false`. Only set this, 114 | if they are truly sorted - otherwise your results will be wrong. 115 | 116 | ## Examples 117 | 118 | iex> Statistex.statistics([50, 50, 450, 450, 450, 500, 500, 500, 600, 900]) 119 | %Statistex{ 120 | total: 4450, 121 | average: 445.0, 122 | variance: 61_361.11111111111, 123 | standard_deviation: 247.71175004652304, 124 | standard_deviation_ratio: 0.5566556180820742, 125 | median: 475.0, 126 | percentiles: %{25 => 350.0, 50 => 475.0, 75 => 525.0}, 127 | frequency_distribution: %{50 => 2, 450 => 3, 500 => 3, 600 => 1, 900 => 1}, 128 | mode: [500, 450], 129 | minimum: 50, 130 | maximum: 900, 131 | lower_outlier_bound: 87.5, 132 | upper_outlier_bound: 787.5, 133 | outliers: [50, 50, 900], 134 | sample_size: 10 135 | } 136 | 137 | # excluding outliers changes the results 138 | iex> Statistex.statistics([50, 50, 450, 450, 450, 500, 500, 500, 600, 900], exclude_outliers: true) 139 | %Statistex{ 140 | total: 3450, 141 | average: 492.85714285714283, 142 | variance: 2857.142857142857, 143 | standard_deviation: 53.452248382484875, 144 | standard_deviation_ratio: 0.1084538372977954, 145 | median: 500.0, 146 | percentiles: %{25 => 450.0, 50 => 500.0, 75 => 500.0}, 147 | frequency_distribution: %{450 => 3, 500 => 3, 600 => 1}, 148 | mode: [500, 450], 149 | maximum: 600, 150 | minimum: 450, 151 | lower_outlier_bound: 87.5, 152 | upper_outlier_bound: 787.5, 153 | outliers: [50, 50, 900], 154 | sample_size: 7 155 | } 156 | 157 | iex> Statistex.statistics([]) 158 | ** (ArgumentError) Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number. 159 | 160 | """ 161 | @spec statistics(samples, configuration) :: t() 162 | def statistics(samples, configuration \\ []) 163 | 164 | def statistics([], _) do 165 | raise(ArgumentError, @empty_list_error_message) 166 | end 167 | 168 | def statistics(samples, configuration) do 169 | sorted_samples = maybe_sort(samples, configuration) 170 | 171 | percentiles = calculate_percentiles(sorted_samples, configuration) 172 | outlier_bounds = outlier_bounds(sorted_samples, percentiles: percentiles) 173 | 174 | # rest remains sorted here/it's an important property 175 | {outliers, rest} = outliers(sorted_samples, outlier_bounds: outlier_bounds) 176 | 177 | if exclude_outliers?(configuration) and Enum.any?(outliers) do 178 | # need to recalculate with the outliers removed 179 | percentiles = calculate_percentiles(rest, configuration) 180 | 181 | create_full_statistics(rest, percentiles, outliers, outlier_bounds) 182 | else 183 | create_full_statistics(sorted_samples, percentiles, outliers, outlier_bounds) 184 | end 185 | end 186 | 187 | defp exclude_outliers?(configuration) do 188 | Access.get(configuration, :exclude_outliers) == true 189 | end 190 | 191 | defp create_full_statistics(sorted_samples, percentiles, outliers, outlier_bounds) do 192 | total = total(sorted_samples) 193 | sample_size = length(sorted_samples) 194 | minimum = hd(sorted_samples) 195 | maximum = List.last(sorted_samples) 196 | 197 | average = average(sorted_samples, total: total, sample_size: sample_size) 198 | variance = variance(sorted_samples, average: average, sample_size: sample_size) 199 | 200 | frequency_distribution = frequency_distribution(sorted_samples) 201 | 202 | standard_deviation = standard_deviation(sorted_samples, variance: variance) 203 | 204 | standard_deviation_ratio = 205 | standard_deviation_ratio(sorted_samples, standard_deviation: standard_deviation) 206 | 207 | {lower_outlier_bound, upper_outlier_bound} = outlier_bounds 208 | 209 | %__MODULE__{ 210 | total: total, 211 | average: average, 212 | variance: variance, 213 | standard_deviation: standard_deviation, 214 | standard_deviation_ratio: standard_deviation_ratio, 215 | median: median(sorted_samples, percentiles: percentiles), 216 | percentiles: percentiles, 217 | frequency_distribution: frequency_distribution, 218 | mode: mode(sorted_samples, frequency_distribution: frequency_distribution), 219 | minimum: minimum, 220 | maximum: maximum, 221 | lower_outlier_bound: lower_outlier_bound, 222 | upper_outlier_bound: upper_outlier_bound, 223 | outliers: outliers, 224 | sample_size: sample_size 225 | } 226 | end 227 | 228 | @doc """ 229 | The total of all samples added together. 230 | 231 | `Argumenterror` is raised if the given list is empty. 232 | 233 | ## Examples 234 | 235 | iex> Statistex.total([1, 2, 3, 4, 5]) 236 | 15 237 | 238 | iex> Statistex.total([10, 10.5, 5]) 239 | 25.5 240 | 241 | iex> Statistex.total([-10, 5, 3, 2]) 242 | 0 243 | 244 | iex> Statistex.total([]) 245 | ** (ArgumentError) Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number. 246 | """ 247 | @spec total(samples) :: number 248 | def total([]), do: raise(ArgumentError, @empty_list_error_message) 249 | def total(samples), do: Enum.sum(samples) 250 | 251 | @doc """ 252 | Number of samples in the given list. 253 | 254 | Nothing to fancy here, this just calls `length(list)` and is only provided for completeness sake. 255 | 256 | ## Examples 257 | 258 | iex> Statistex.sample_size([]) 259 | 0 260 | 261 | iex> Statistex.sample_size([1, 1, 1, 1, 1]) 262 | 5 263 | """ 264 | @spec sample_size([sample]) :: non_neg_integer 265 | def sample_size(samples), do: length(samples) 266 | 267 | @doc """ 268 | Calculate the average. 269 | 270 | It's.. well the average. 271 | When the given samples are empty there is no average. 272 | 273 | `Argumenterror` is raised if the given list is empty. 274 | 275 | ## Options 276 | If you already have these values, you can provide both `:total` and `:sample_size`. Should you provide both the provided samples are wholly ignored. 277 | 278 | ## Examples 279 | 280 | iex> Statistex.average([5]) 281 | 5.0 282 | 283 | iex> Statistex.average([600, 470, 170, 430, 300]) 284 | 394.0 285 | 286 | iex> Statistex.average([-1, 1]) 287 | 0.0 288 | 289 | iex> Statistex.average([2, 3, 4], sample_size: 3) 290 | 3.0 291 | 292 | iex> Statistex.average([20, 20, 20, 20, 20], total: 100, sample_size: 5) 293 | 20.0 294 | 295 | iex> Statistex.average(:ignored, total: 100, sample_size: 5) 296 | 20.0 297 | 298 | iex> Statistex.average([]) 299 | ** (ArgumentError) Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number. 300 | """ 301 | @spec average(samples, keyword) :: float 302 | def average(samples, options \\ []) 303 | def average([], _), do: raise(ArgumentError, @empty_list_error_message) 304 | 305 | def average(samples, options) do 306 | total = Keyword.get_lazy(options, :total, fn -> total(samples) end) 307 | sample_size = Keyword.get_lazy(options, :sample_size, fn -> sample_size(samples) end) 308 | 309 | total / sample_size 310 | end 311 | 312 | @doc """ 313 | Calculate the variance. 314 | 315 | A measurement how much samples vary (the higher the more the samples vary). This is the variance of a sample and is hence in its calculation divided by sample_size - 1 (Bessel's correction). 316 | 317 | `Argumenterror` is raised if the given list is empty. 318 | 319 | ## Options 320 | If already calculated, the `:average` and `:sample_size` options can be provided to avoid recalulating those values. 321 | 322 | ## Examples 323 | 324 | iex> Statistex.variance([4, 9, 11, 12, 17, 5, 8, 12, 12]) 325 | 16.0 326 | 327 | iex> Statistex.variance([4, 9, 11, 12, 17, 5, 8, 12, 12], sample_size: 9, average: 10.0) 328 | 16.0 329 | 330 | iex> Statistex.variance([42]) 331 | 0.0 332 | 333 | iex> Statistex.variance([1, 1, 1, 1, 1, 1, 1]) 334 | 0.0 335 | 336 | iex> Statistex.variance([]) 337 | ** (ArgumentError) Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number. 338 | """ 339 | @spec variance(samples, keyword) :: float 340 | def variance(samples, options \\ []) 341 | def variance([], _), do: raise(ArgumentError, @empty_list_error_message) 342 | 343 | def variance(samples, options) do 344 | sample_size = Keyword.get_lazy(options, :sample_size, fn -> sample_size(samples) end) 345 | 346 | average = 347 | Keyword.get_lazy(options, :average, fn -> average(samples, sample_size: sample_size) end) 348 | 349 | do_variance(samples, average, sample_size) 350 | end 351 | 352 | defp do_variance(_samples, _average, 1), do: 0.0 353 | 354 | defp do_variance(samples, average, sample_size) do 355 | total_variance = 356 | Enum.reduce(samples, 0, fn sample, total -> 357 | total + :math.pow(sample - average, 2) 358 | end) 359 | 360 | total_variance / (sample_size - 1) 361 | end 362 | 363 | @doc """ 364 | Calculate the standard deviation. 365 | 366 | A measurement how much samples vary (the higher the more the samples vary). It's the square root of the variance. Unlike the variance, its unit is the same as that of the sample (as calculating the variance includes squaring). 367 | 368 | ## Options 369 | If already calculated, the `:variance` option can be provided to avoid recalulating those values. 370 | 371 | `Argumenterror` is raised if the given list is empty. 372 | 373 | ## Examples 374 | 375 | iex> Statistex.standard_deviation([4, 9, 11, 12, 17, 5, 8, 12, 12]) 376 | 4.0 377 | 378 | iex> Statistex.standard_deviation(:dontcare, variance: 16.0) 379 | 4.0 380 | 381 | iex> Statistex.standard_deviation([42]) 382 | 0.0 383 | 384 | iex> Statistex.standard_deviation([1, 1, 1, 1, 1, 1, 1]) 385 | 0.0 386 | 387 | iex> Statistex.standard_deviation([]) 388 | ** (ArgumentError) Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number. 389 | """ 390 | @spec standard_deviation(samples, keyword) :: float 391 | def standard_deviation(samples, options \\ []) 392 | def standard_deviation([], _), do: raise(ArgumentError, @empty_list_error_message) 393 | 394 | def standard_deviation(samples, options) do 395 | variance = Keyword.get_lazy(options, :variance, fn -> variance(samples) end) 396 | :math.sqrt(variance) 397 | end 398 | 399 | @doc """ 400 | Calculate the standard deviation relative to the average. 401 | 402 | This helps put the absolute standard deviation value into perspective expressing it relative to the average. It's what percentage of the absolute value of the average the variance takes. 403 | 404 | `Argumenterror` is raised if the given list is empty. 405 | 406 | ## Options 407 | If already calculated, the `:average` and `:standard_deviation` options can be provided to avoid recalulating those values. 408 | 409 | If both values are provided, the provided samples will be ignored. 410 | 411 | ## Examples 412 | 413 | iex> Statistex.standard_deviation_ratio([4, 9, 11, 12, 17, 5, 8, 12, 12]) 414 | 0.4 415 | 416 | iex> Statistex.standard_deviation_ratio([-4, -9, -11, -12, -17, -5, -8, -12, -12]) 417 | 0.4 418 | 419 | iex> Statistex.standard_deviation_ratio([4, 9, 11, 12, 17, 5, 8, 12, 12], average: 10.0, standard_deviation: 4.0) 420 | 0.4 421 | 422 | iex> Statistex.standard_deviation_ratio(:ignored, average: 10.0, standard_deviation: 4.0) 423 | 0.4 424 | 425 | iex> Statistex.standard_deviation_ratio([]) 426 | ** (ArgumentError) Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number. 427 | """ 428 | @spec standard_deviation_ratio(samples, keyword) :: float 429 | def standard_deviation_ratio(samples, options \\ []) 430 | def standard_deviation_ratio([], _), do: raise(ArgumentError, @empty_list_error_message) 431 | 432 | def standard_deviation_ratio(samples, options) do 433 | average = Keyword.get_lazy(options, :average, fn -> average(samples) end) 434 | 435 | std_dev = 436 | Keyword.get_lazy(options, :standard_deviation, fn -> 437 | standard_deviation(samples, average: average) 438 | end) 439 | 440 | if average == 0 do 441 | 0.0 442 | else 443 | abs(std_dev / average) 444 | end 445 | end 446 | 447 | defp calculate_percentiles(sorted_samples, configuration) do 448 | percentiles_configuration = Keyword.get(configuration, :percentiles, []) 449 | 450 | # median_percentile is manually added so that it can be used directly by median 451 | percentiles_configuration = 452 | Enum.uniq([ 453 | @first_quartile, 454 | @median_percentile, 455 | @third_quartile | percentiles_configuration 456 | ]) 457 | 458 | Percentile.percentiles(sorted_samples, percentiles_configuration, sorted: true) 459 | end 460 | 461 | @doc """ 462 | Calculates the value at the `percentile_rank`-th percentile. 463 | 464 | Think of this as the value below which `percentile_rank` percent of the samples lie. 465 | For example, if `Statistex.percentile(samples, 99) == 123.45`, 466 | 99% of samples are less than 123.45. 467 | 468 | Passing a number for `percentile_rank` calculates a single percentile. 469 | Passing a list of numbers calculates multiple percentiles, and returns them 470 | as a map like %{90 => 45.6, 99 => 78.9}, where the keys are the percentile 471 | numbers, and the values are the percentile values. 472 | 473 | Percentiles must be between 0 and 100 (excluding the boundaries). 474 | 475 | The method used for interpolation is [described here and recommended by NIST](https://www.itl.nist.gov/div898/handbook/prc/section2/prc262.htm). 476 | 477 | `Argumenterror` is raised if the given list is empty. 478 | 479 | ## Options 480 | 481 | * `:sorted?`: indicating the samples you're passing in are already sorted. Defaults to `false`. Only set this, 482 | if they are truly sorted - otherwise your results will be wrong. 483 | 484 | ## Examples 485 | 486 | iex> Statistex.percentiles([5, 3, 4, 5, 1, 3, 1, 3], 12.5) 487 | %{12.5 => 1.0} 488 | 489 | iex> Statistex.percentiles([1, 1, 3, 3, 3, 4, 5, 5], 12.5, sorted?: true) 490 | %{12.5 => 1.0} 491 | 492 | iex> Statistex.percentiles([5, 3, 4, 5, 1, 3, 1, 3], [50]) 493 | %{50 => 3.0} 494 | 495 | iex> Statistex.percentiles([5, 3, 4, 5, 1, 3, 1, 3], [75]) 496 | %{75 => 4.75} 497 | 498 | iex> Statistex.percentiles([5, 3, 4, 5, 1, 3, 1, 3], 99) 499 | %{99 => 5.0} 500 | 501 | iex> Statistex.percentiles([5, 3, 4, 5, 1, 3, 1, 3], [50, 75, 99]) 502 | %{50 => 3.0, 75 => 4.75, 99 => 5.0} 503 | 504 | iex> Statistex.percentiles([5, 3, 4, 5, 1, 3, 1, 3], 100) 505 | ** (ArgumentError) percentile must be between 0 and 100, got: 100 506 | 507 | iex> Statistex.percentiles([5, 3, 4, 5, 1, 3, 1, 3], 0) 508 | ** (ArgumentError) percentile must be between 0 and 100, got: 0 509 | 510 | iex> Statistex.percentiles([], [50]) 511 | ** (ArgumentError) Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number. 512 | """ 513 | @spec percentiles(samples, number | [number(), ...]) :: 514 | percentiles() 515 | defdelegate percentiles(samples, percentiles, options), to: Percentile 516 | defdelegate percentiles(samples, percentiles), to: Percentile 517 | 518 | @doc """ 519 | A map showing which sample occurs how often in the samples. 520 | 521 | Goes from a concrete occurence of the sample to the number of times it was observed in the samples. 522 | 523 | `Argumenterror` is raised if the given list is empty. 524 | 525 | ## Examples 526 | 527 | iex> Statistex.frequency_distribution([1, 2, 4.23, 7, 2, 99]) 528 | %{ 529 | 2 => 2, 530 | 1 => 1, 531 | 4.23 => 1, 532 | 7 => 1, 533 | 99 => 1 534 | } 535 | 536 | iex> Statistex.frequency_distribution([]) 537 | ** (ArgumentError) Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number. 538 | """ 539 | @spec frequency_distribution(samples) :: %{required(sample) => pos_integer} 540 | def frequency_distribution([]), do: raise(ArgumentError, @empty_list_error_message) 541 | 542 | def frequency_distribution(samples) do 543 | Enum.reduce(samples, %{}, fn sample, counts -> 544 | Map.update(counts, sample, 1, fn old_value -> old_value + 1 end) 545 | end) 546 | end 547 | 548 | @doc """ 549 | Calculates the mode of the given samples. 550 | 551 | Mode is the sample(s) that occur the most. Often one value, but can be multiple values if they occur the same amount of times. If no value occurs at least twice, there is no mode and it hence returns `nil`. 552 | 553 | `Argumenterror` is raised if the given list is empty. 554 | 555 | ## Options 556 | 557 | If already calculated, the `:frequency_distribution` option can be provided to avoid recalulating it. 558 | 559 | ## Examples 560 | 561 | iex> Statistex.mode([5, 3, 4, 5, 1, 3, 1, 3]) 562 | 3 563 | 564 | iex> Statistex.mode([1, 2, 3, 4, 5]) 565 | nil 566 | 567 | # When a measurement failed and nils is reported as the only value 568 | iex> Statistex.mode([nil]) 569 | nil 570 | 571 | iex> Statistex.mode([]) 572 | ** (ArgumentError) Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number. 573 | 574 | iex> mode = Statistex.mode([5, 3, 4, 5, 1, 3, 1]) 575 | iex> Enum.sort(mode) 576 | [1, 3, 5] 577 | """ 578 | @spec mode(samples, keyword) :: mode 579 | def mode(samples, opts \\ []), do: Mode.mode(samples, opts) 580 | 581 | @doc """ 582 | Calculates the median of the given samples. 583 | 584 | The median can be thought of separating the higher half from the lower half of the samples. 585 | When all samples are sorted, this is the middle value (or average of the two middle values when the number of times is even). 586 | More stable than the average. 587 | 588 | `Argumenterror` is raised if the given list is empty. 589 | 590 | ## Options 591 | * `:percentiles` - you can pass it a map of calculated percentiles to fetch the median from (it is the 50th percentile). 592 | If it doesn't include the median/50th percentile - it will still be computed. 593 | * `:sorted?`: indicating the samples you're passing in are already sorted. Defaults to `false`. Only set this, 594 | if they are truly sorted - otherwise your results will be wrong. Sorting only occurs when percentiles aren't provided. 595 | 596 | ## Examples 597 | 598 | iex> Statistex.median([1, 3, 4, 6, 7, 8, 9]) 599 | 6.0 600 | 601 | iex> Statistex.median([1, 3, 4, 6, 7, 8, 9], percentiles: %{50 => 6.0}) 602 | 6.0 603 | 604 | iex> Statistex.median([1, 3, 4, 6, 7, 8, 9], percentiles: %{25 => 3.0}) 605 | 6.0 606 | 607 | iex> Statistex.median([1, 3, 4, 6, 7, 8, 9], sorted?: true) 608 | 6.0 609 | 610 | iex> Statistex.median([1, 2, 3, 4, 5, 6, 8, 9]) 611 | 4.5 612 | 613 | iex> Statistex.median([0]) 614 | 0.0 615 | 616 | iex> Statistex.median([]) 617 | ** (ArgumentError) Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number. 618 | """ 619 | @spec median(samples, keyword) :: number 620 | def median(samples, options \\ []) 621 | def median([], _), do: raise(ArgumentError, @empty_list_error_message) 622 | 623 | def median(samples, options) do 624 | percentiles = Access.get(options, :percentiles, %{}) 625 | 626 | percentiles = 627 | case percentiles do 628 | %{@median_percentile => _} -> 629 | percentiles 630 | 631 | # missing necessary keys 632 | %{} -> 633 | Percentile.percentiles(samples, @median_percentile, options) 634 | end 635 | 636 | Map.fetch!(percentiles, @median_percentile) 637 | end 638 | 639 | @doc """ 640 | Calculates the lower and upper bound for outliers. 641 | 642 | Any sample that is `<` as the lower bound and any sample `>` are outliers of 643 | the given `samples`. 644 | 645 | List passed needs to be non empty, otherwise an `ArgumentError` is raised. 646 | 647 | ## Options 648 | * `:percentiles` - you can pass it a map of calculated percentiles (25th and 75th are needed). 649 | If it doesn't include them - it will still be computed. 650 | * `:sorted?`: indicating the samples you're passing in are already sorted. Defaults to `false`. Only set this, 651 | if they are truly sorted - otherwise your results will be wrong. Sorting only occurs when percentiles aren't provided. 652 | 653 | ## Examples 654 | 655 | iex> Statistex.outlier_bounds([3, 4, 5]) 656 | {0.0, 8.0} 657 | 658 | iex> Statistex.outlier_bounds([4, 5, 3]) 659 | {0.0, 8.0} 660 | 661 | iex> Statistex.outlier_bounds([3, 4, 5], sorted?: true) 662 | {0.0, 8.0} 663 | 664 | iex> Statistex.outlier_bounds([3, 4, 5], percentiles: %{25 => 3.0, 75 => 5.0}) 665 | {0.0, 8.0} 666 | 667 | iex> Statistex.outlier_bounds([1, 2, 6, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50]) 668 | {22.5, 66.5} 669 | 670 | iex> Statistex.outlier_bounds([50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 99, 99, 99]) 671 | {31.625, 80.625} 672 | 673 | iex> Statistex.outlier_bounds([]) 674 | ** (ArgumentError) Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number. 675 | """ 676 | @spec outlier_bounds(samples, keyword) :: {lower :: number, upper :: number} 677 | def outlier_bounds(samples, options \\ []) 678 | def outlier_bounds([], _), do: raise(ArgumentError, @empty_list_error_message) 679 | 680 | def outlier_bounds(samples, options) do 681 | percentiles = Access.get(options, :percentiles, %{}) 682 | 683 | percentiles = 684 | case percentiles do 685 | %{@first_quartile => _, @third_quartile => _} -> 686 | percentiles 687 | 688 | # missing necessary keys 689 | %{} -> 690 | Percentile.percentiles(samples, [@first_quartile, @third_quartile], options) 691 | end 692 | 693 | q1 = Map.fetch!(percentiles, @first_quartile) 694 | q3 = Map.fetch!(percentiles, @third_quartile) 695 | iqr = q3 - q1 696 | outlier_tolerance = iqr * @iqr_factor 697 | 698 | {q1 - outlier_tolerance, q3 + outlier_tolerance} 699 | end 700 | 701 | @doc """ 702 | Returns all outliers for the given `samples`, along with the remaining values. 703 | 704 | Returns: `{outliers, remaining_samples`} where `remaining_samples` has the outliers removed. 705 | 706 | ## Options 707 | * `:outlier_bounds` - if you already have calculated the outlier bounds. 708 | * `:percentiles` - you can pass it a map of calculated percentiles (25th and 75th are needed). 709 | If it doesn't include them - it will still be computed. 710 | * `:sorted?`: indicating the samples you're passing in are already sorted. Defaults to `false`. Only set this, 711 | if they are truly sorted - otherwise your results will be wrong. Sorting only occurs when percentiles aren't provided. 712 | 713 | ## Examples 714 | 715 | iex> Statistex.outliers([3, 4, 5]) 716 | {[], [3, 4, 5]} 717 | 718 | iex> Statistex.outliers([1, 2, 6, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50]) 719 | {[1, 2, 6], [50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50]} 720 | 721 | iex> Statistex.outliers([50, 50, 1, 50, 50, 50, 50, 50, 2, 50, 50, 50, 50, 6]) 722 | {[1, 2, 6], [50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50]} 723 | 724 | iex> Statistex.outliers([50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 99, 99, 99]) 725 | {[99, 99, 99], [50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50]} 726 | """ 727 | @spec outliers(samples, keyword) :: {samples | [], samples} 728 | def outliers(samples, options \\ []) do 729 | {lower_bound, upper_bound} = 730 | Keyword.get_lazy(options, :outlier_bounds, fn -> 731 | outlier_bounds(samples, options) 732 | end) 733 | 734 | Enum.split_with(samples, fn sample -> sample < lower_bound || sample > upper_bound end) 735 | end 736 | 737 | @doc """ 738 | The biggest sample. 739 | 740 | `Argumenterror` is raised if the given list is empty. 741 | 742 | ## Examples 743 | 744 | iex> Statistex.maximum([1, 100, 24]) 745 | 100 746 | 747 | iex> Statistex.maximum([]) 748 | ** (ArgumentError) Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number. 749 | """ 750 | @spec maximum(samples) :: sample 751 | def maximum([]), do: raise(ArgumentError, @empty_list_error_message) 752 | def maximum(samples), do: Enum.max(samples) 753 | 754 | @doc """ 755 | The smallest sample. 756 | 757 | `Argumenterror` is raised if the given list is empty. 758 | 759 | ## Examples 760 | 761 | iex> Statistex.minimum([1, 100, 24]) 762 | 1 763 | 764 | iex> Statistex.minimum([]) 765 | ** (ArgumentError) Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number. 766 | """ 767 | @spec minimum(samples) :: sample 768 | def minimum([]), do: raise(ArgumentError, @empty_list_error_message) 769 | def minimum(samples), do: Enum.min(samples) 770 | end 771 | -------------------------------------------------------------------------------- /lib/statistex/helper.ex: -------------------------------------------------------------------------------- 1 | defmodule Statistex.Helper do 2 | @moduledoc false 3 | # Everyone loves helper modules... ok ok, no. But I needed/wanted this function, 4 | # but didn't wanna put it on the main module. 5 | 6 | # With the design goal that we don't want to needlessly do operations, esp. big ones 7 | # like sorting we need an optional `sorted?` arguments in a bunch of places. 8 | # This unifies the handling of that. 9 | def maybe_sort(samples, options) do 10 | sorted? = Access.get(options, :sorted?, false) 11 | 12 | if sorted? do 13 | samples 14 | else 15 | Enum.sort(samples) 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /lib/statistex/mode.ex: -------------------------------------------------------------------------------- 1 | defmodule Statistex.Mode do 2 | @moduledoc false 3 | 4 | import Statistex 5 | 6 | @spec mode(Statistex.samples(), keyword) :: Statistex.mode() 7 | def mode([], _) do 8 | raise( 9 | ArgumentError, 10 | "Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number." 11 | ) 12 | end 13 | 14 | def mode(samples, opts) do 15 | frequencies = 16 | Keyword.get_lazy(opts, :frequency_distribution, fn -> frequency_distribution(samples) end) 17 | 18 | frequencies 19 | |> max_multiple() 20 | |> decide_mode() 21 | end 22 | 23 | defp max_multiple(map) do 24 | max_multiple(Enum.to_list(map), [{nil, 0}]) 25 | end 26 | 27 | defp max_multiple([{sample, count} | rest], ref = [{_, max_count} | _]) do 28 | new_ref = 29 | cond do 30 | count < max_count -> ref 31 | count == max_count -> [{sample, count} | ref] 32 | true -> [{sample, count}] 33 | end 34 | 35 | max_multiple(rest, new_ref) 36 | end 37 | 38 | defp max_multiple([], ref) do 39 | ref 40 | end 41 | 42 | defp decide_mode([{nil, _}]), do: nil 43 | defp decide_mode([{_, 1} | _rest]), do: nil 44 | defp decide_mode([{sample, _count}]), do: sample 45 | 46 | defp decide_mode(multi_modes) do 47 | Enum.map(multi_modes, fn {sample, _} -> sample end) 48 | end 49 | end 50 | -------------------------------------------------------------------------------- /lib/statistex/percentile.ex: -------------------------------------------------------------------------------- 1 | defmodule Statistex.Percentile do 2 | @moduledoc false 3 | 4 | import Statistex.Helper, only: [maybe_sort: 2] 5 | 6 | @spec percentiles(Statistex.samples(), number | [number, ...], keyword()) :: 7 | Statistex.percentiles() 8 | def percentiles(samples, percentiles, options \\ []) 9 | 10 | def percentiles([], _, _) do 11 | raise( 12 | ArgumentError, 13 | "Passed an empty list ([]) to calculate statistics from, please pass a list containing at least one number." 14 | ) 15 | end 16 | 17 | def percentiles(samples, percentile_ranks, options) do 18 | number_of_samples = length(samples) 19 | sorted_samples = maybe_sort(samples, options) 20 | 21 | percentile_ranks 22 | |> List.wrap() 23 | |> Map.new(fn percentile_rank -> 24 | perc = percentile(sorted_samples, number_of_samples, percentile_rank) 25 | {percentile_rank, perc} 26 | end) 27 | end 28 | 29 | defp percentile(_, _, percentile_rank) when percentile_rank >= 100 or percentile_rank <= 0 do 30 | raise ArgumentError, "percentile must be between 0 and 100, got: #{inspect(percentile_rank)}" 31 | end 32 | 33 | defp percentile(sorted_samples, number_of_samples, percentile_rank) do 34 | percent = percentile_rank / 100 35 | rank = percent * (number_of_samples + 1) 36 | percentile_value(sorted_samples, rank) 37 | end 38 | 39 | # According to https://www.itl.nist.gov/div898/handbook/prc/section2/prc262.htm 40 | # the full integer of rank being 0 is an edge case and we simple choose the first 41 | # element. See clause 2, our rank is k there. 42 | defp percentile_value(sorted_samples, rank) when rank < 1 do 43 | [first | _] = sorted_samples 44 | first 45 | end 46 | 47 | defp percentile_value(sorted_samples, rank) do 48 | index = max(0, trunc(rank) - 1) 49 | {pre_index, post_index} = Enum.split(sorted_samples, index) 50 | calculate_percentile_value(rank, pre_index, post_index) 51 | end 52 | 53 | # The common case: interpolate between the two values after the split 54 | defp calculate_percentile_value(rank, _, [lower_bound, upper_bound | _]) do 55 | lower_bound + interpolation_value(lower_bound, upper_bound, rank) 56 | end 57 | 58 | # Nothing to interpolate toward: use the first value after the split 59 | defp calculate_percentile_value(_, _, [lower_bound]) do 60 | to_float(lower_bound) 61 | end 62 | 63 | # Interpolation implemented according to: https://www.itl.nist.gov/div898/handbook/prc/section2/prc262.htm 64 | # 65 | # "Type 6" interpolation strategy. There are many ways to interpolate a value 66 | # when the rank is not an integer (in other words, we don't exactly land on a 67 | # particular sample). Of the 9 main strategies, (types 1-9), types 6, 7, and 8 68 | # are generally acceptable and give similar results. 69 | # 70 | # R uses type 7, but you can change the strategies used in R with arguments. 71 | # 72 | # > quantile(c(9, 9, 10, 10, 10, 11, 12, 36), probs = c(0.25, 0.5, 0.75), type = 6) 73 | # 25% 50% 75% 74 | # 9.25 10.00 11.75 75 | # > quantile(c(9, 9, 10, 10, 10, 11, 12, 36), probs = c(0.25, 0.5, 0.75), type = 7) 76 | # 25% 50% 75% 77 | # 9.75 10.00 11.25 78 | # 79 | # For more information on interpolation strategies, see: 80 | # - https://stat.ethz.ch/R-manual/R-devel/library/stats/html/quantile.html 81 | # - http://www.itl.nist.gov/div898/handbook/prc/section2/prc262.htm 82 | defp interpolation_value(lower_bound, upper_bound, rank) do 83 | # in our source rank is k, and interpolation_weight is d 84 | interpolation_weight = rank - trunc(rank) 85 | interpolation_weight * (upper_bound - lower_bound) 86 | end 87 | 88 | defp to_float(maybe_integer) do 89 | :erlang.float(maybe_integer) 90 | end 91 | end 92 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule Statistex.MixProject do 2 | use Mix.Project 3 | 4 | @version "1.0.0" 5 | def project do 6 | [ 7 | app: :statistex, 8 | version: @version, 9 | elixir: "~> 1.6", 10 | start_permanent: Mix.env() == :prod, 11 | deps: deps(), 12 | docs: [ 13 | source_ref: @version, 14 | extras: ["README.md"], 15 | main: "readme" 16 | ], 17 | package: package(), 18 | test_coverage: [tool: ExCoveralls], 19 | preferred_cli_env: [ 20 | coveralls: :test, 21 | "coveralls.detail": :test, 22 | "coveralls.post": :test, 23 | "coveralls.html": :test, 24 | "coveralls.travis": :test, 25 | "safe_coveralls.travis": :test 26 | ], 27 | dialyzer: [ 28 | flags: [:unmatched_returns, :error_handling, :underspecs], 29 | plt_file: {:no_warn, "tools/plts/benchee.plt"} 30 | ], 31 | name: "Statistex", 32 | source_url: "https://github.com/bencheeorg/statistex", 33 | description: """ 34 | Calculate statistics on data sets, reusing previously calculated values or just all metrics at once. Part of the benchee library family. 35 | """ 36 | ] 37 | end 38 | 39 | # Run "mix help compile.app" to learn about applications. 40 | def application do 41 | [] 42 | end 43 | 44 | # Run "mix help deps" to learn about dependencies. 45 | defp deps do 46 | [ 47 | {:credo, "~> 1.0", only: :dev}, 48 | {:ex_doc, "~> 0.20", only: :dev}, 49 | {:earmark, "~> 1.0", only: :dev}, 50 | {:excoveralls, "~> 0.7", only: :test}, 51 | # dev and test so that the formatter has access 52 | {:stream_data, "~> 1.1", only: [:dev, :test]}, 53 | {:inch_ex, "~> 2.0", only: :docs}, 54 | {:dialyxir, "~> 1.0", only: :dev, runtime: false} 55 | ] 56 | end 57 | 58 | defp package do 59 | [ 60 | maintainers: ["Tobias Pfeiffer"], 61 | licenses: ["MIT"], 62 | links: %{ 63 | "github" => "https://github.com/bencheeorg/statistex" 64 | } 65 | ] 66 | end 67 | end 68 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "bunt": {:hex, :bunt, "0.2.1", "e2d4792f7bc0ced7583ab54922808919518d0e57ee162901a16a1b6664ef3b14", [:mix], [], "hexpm", "a330bfb4245239787b15005e66ae6845c9cd524a288f0d141c148b02603777a5"}, 3 | "credo": {:hex, :credo, "1.7.12", "9e3c20463de4b5f3f23721527fcaf16722ec815e70ff6c60b86412c695d426c1", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "8493d45c656c5427d9c729235b99d498bd133421f3e0a683e5c1b561471291e5"}, 4 | "dialyxir": {:hex, :dialyxir, "1.4.5", "ca1571ac18e0f88d4ab245f0b60fa31ff1b12cbae2b11bd25d207f865e8ae78a", [:mix], [{:erlex, ">= 0.2.7", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "b0fb08bb8107c750db5c0b324fa2df5ceaa0f9307690ee3c1f6ba5b9eb5d35c3"}, 5 | "earmark": {:hex, :earmark, "1.4.47", "7e7596b84fe4ebeb8751e14cbaeaf4d7a0237708f2ce43630cfd9065551f94ca", [:mix], [], "hexpm", "3e96bebea2c2d95f3b346a7ff22285bc68a99fbabdad9b655aa9c6be06c698f8"}, 6 | "earmark_parser": {:hex, :earmark_parser, "1.4.44", "f20830dd6b5c77afe2b063777ddbbff09f9759396500cdbe7523efd58d7a339c", [:mix], [], "hexpm", "4778ac752b4701a5599215f7030989c989ffdc4f6df457c5f36938cc2d2a2750"}, 7 | "erlex": {:hex, :erlex, "0.2.7", "810e8725f96ab74d17aac676e748627a07bc87eb950d2b83acd29dc047a30595", [:mix], [], "hexpm", "3ed95f79d1a844c3f6bf0cea61e0d5612a42ce56da9c03f01df538685365efb0"}, 8 | "ex_doc": {:hex, :ex_doc, "0.37.3", "f7816881a443cd77872b7d6118e8a55f547f49903aef8747dbcb345a75b462f9", [:mix], [{:earmark_parser, "~> 1.4.42", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "e6aebca7156e7c29b5da4daa17f6361205b2ae5f26e5c7d8ca0d3f7e18972233"}, 9 | "excoveralls": {:hex, :excoveralls, "0.18.5", "e229d0a65982613332ec30f07940038fe451a2e5b29bce2a5022165f0c9b157e", [:mix], [{:castore, "~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "523fe8a15603f86d64852aab2abe8ddbd78e68579c8525ae765facc5eae01562"}, 10 | "file_system": {:hex, :file_system, "1.1.0", "08d232062284546c6c34426997dd7ef6ec9f8bbd090eb91780283c9016840e8f", [:mix], [], "hexpm", "bfcf81244f416871f2a2e15c1b515287faa5db9c6bcf290222206d120b3d43f6"}, 11 | "inch_ex": {:hex, :inch_ex, "2.0.0", "24268a9284a1751f2ceda569cd978e1fa394c977c45c331bb52a405de544f4de", [:mix], [{:bunt, "~> 0.2", [hex: :bunt, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "96d0ec5ecac8cf63142d02f16b7ab7152cf0f0f1a185a80161b758383c9399a8"}, 12 | "jason": {:hex, :jason, "1.4.4", "b9226785a9aa77b6857ca22832cffa5d5011a667207eb2a0ad56adb5db443b8a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "c5eb0cab91f094599f94d55bc63409236a8ec69a21a67814529e8d5f6cc90b3b"}, 13 | "makeup": {:hex, :makeup, "1.2.1", "e90ac1c65589ef354378def3ba19d401e739ee7ee06fb47f94c687016e3713d1", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "d36484867b0bae0fea568d10131197a4c2e47056a6fbe84922bf6ba71c8d17ce"}, 14 | "makeup_elixir": {:hex, :makeup_elixir, "1.0.1", "e928a4f984e795e41e3abd27bfc09f51db16ab8ba1aebdba2b3a575437efafc2", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "7284900d412a3e5cfd97fdaed4f5ed389b8f2b4cb49efc0eb3bd10e2febf9507"}, 15 | "makeup_erlang": {:hex, :makeup_erlang, "1.0.2", "03e1804074b3aa64d5fad7aa64601ed0fb395337b982d9bcf04029d68d51b6a7", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "af33ff7ef368d5893e4a267933e7744e46ce3cf1f61e2dccf53a111ed3aa3727"}, 16 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.2", "8efba0122db06df95bfaa78f791344a89352ba04baedd3849593bfce4d0dc1c6", [:mix], [], "hexpm", "4b21398942dda052b403bbe1da991ccd03a053668d147d53fb8c4e0efe09c973"}, 17 | "stream_data": {:hex, :stream_data, "1.2.0", "58dd3f9e88afe27dc38bef26fce0c84a9e7a96772b2925c7b32cd2435697a52b", [:mix], [], "hexpm", "eb5c546ee3466920314643edf68943a5b14b32d1da9fe01698dc92b73f89a9ed"}, 18 | } 19 | -------------------------------------------------------------------------------- /test/statistex/mode_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Statistex.ModeTest do 2 | use ExUnit.Case, async: true 3 | doctest Statistex.Mode 4 | end 5 | -------------------------------------------------------------------------------- /test/statistex/percentile_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Statistex.PercentileTest do 2 | use ExUnit.Case, async: true 3 | import Statistex.Percentile 4 | 5 | doctest Statistex.Percentile 6 | 7 | @nist_sample_data [ 8 | 95.1772, 9 | 95.1567, 10 | 95.1937, 11 | 95.1959, 12 | 95.1442, 13 | 95.0610, 14 | 95.1591, 15 | 95.1195, 16 | 95.1065, 17 | 95.0925, 18 | 95.1990, 19 | 95.1682 20 | ] 21 | 22 | # Test data from: 23 | # http://www.itl.nist.gov/div898/handbook/prc/section2/prc262.htm 24 | test "90th percentile" do 25 | %{90 => result} = percentiles(@nist_sample_data, 90) 26 | assert Float.round(result, 4) == 95.1981 27 | end 28 | 29 | test "an empty list raises an argument error" do 30 | assert_raise ArgumentError, fn -> percentiles([], [1]) end 31 | end 32 | 33 | describe "a list of one element" do 34 | @samples [300] 35 | test "1st percentile" do 36 | %{1 => result} = percentiles(@samples, [1]) 37 | assert result == 300.0 38 | end 39 | 40 | test "50th percentile" do 41 | %{50 => result} = percentiles(@samples, [50]) 42 | assert result == 300.0 43 | end 44 | 45 | test "99th percentile" do 46 | %{99 => result} = percentiles(@samples, [99]) 47 | assert result == 300.0 48 | end 49 | end 50 | 51 | describe "a list of two elements" do 52 | @samples [300, 200] 53 | test "1st percentile (small sample size simply picks first element)" do 54 | %{1 => result} = percentiles(@samples, [1]) 55 | assert result == 200.0 56 | end 57 | 58 | test "50th percentile" do 59 | %{50 => result} = percentiles(@samples, [50]) 60 | assert result == 250.0 61 | end 62 | 63 | test "99th percentile" do 64 | %{99 => result} = percentiles(@samples, [99]) 65 | assert result == 300.0 66 | end 67 | end 68 | 69 | describe "seemingly problematic 2 element list [9, 1]" do 70 | @samples [9, 1] 71 | 72 | percentiles = %{ 73 | 25 => 1, 74 | 50 => 5, 75 | 75 => 9.0, 76 | 90 => 9.0, 77 | 99 => 9.0 78 | } 79 | 80 | for {percentile, expected} <- percentiles do 81 | @percentile percentile 82 | @expected expected 83 | test "#{percentile}th percentile" do 84 | %{@percentile => result} = percentiles(@samples, [@percentile]) 85 | assert result == @expected 86 | end 87 | end 88 | end 89 | 90 | describe "a list of three elements" do 91 | @samples [100, 300, 200] 92 | test "1st percentile (small sample size simply picks first element)" do 93 | %{1 => result} = percentiles(@samples, [1]) 94 | assert result == 100.0 95 | end 96 | 97 | test "50th percentile" do 98 | %{50 => result} = percentiles(@samples, [50]) 99 | assert result == 200.0 100 | end 101 | 102 | test "99th percentile" do 103 | %{99 => result} = percentiles(@samples, [99]) 104 | assert result == 300.0 105 | end 106 | 107 | test "99.9999th percentile" do 108 | %{99.9999 => result} = percentiles(@samples, [99.9999]) 109 | assert result == 300.0 110 | end 111 | end 112 | end 113 | -------------------------------------------------------------------------------- /test/statistex_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Statistex.StatistexTest do 2 | use ExUnit.Case, async: true 3 | doctest Statistex 4 | 5 | use ExUnitProperties 6 | import Statistex 7 | import StreamData 8 | 9 | describe ".median/2" do 10 | test "if handed percentiles missing the median percentile still calculates it" do 11 | assert Statistex.median([1, 2, 3, 4, 5, 6, 8, 9], percentiles: %{}) == 4.5 12 | end 13 | 14 | # what an odd test to write, huh? Well that way we can see we trust the `sorted?` 15 | # value not resorting. 16 | test "if told that the list is sorted while it isn't the result will be wrong" do 17 | assert Statistex.median([1, 6, 4, 3, 5, 9, 2, 8], sorted?: true) != 4.5 18 | end 19 | end 20 | 21 | describe ".outlier_bounds/2" do 22 | # examples doubled up, maybe get rid of them? 23 | test "returns outlier bounds for samples without outliers" do 24 | assert Statistex.outlier_bounds([200, 400, 400, 400, 500, 500, 500, 700, 900]) == 25 | {100.0, 900.0} 26 | end 27 | 28 | test "returns outlier bounds for samples with outliers" do 29 | assert Statistex.outlier_bounds([50, 50, 450, 450, 450, 500, 500, 500, 600, 900]) == 30 | {87.5, 787.5} 31 | end 32 | end 33 | 34 | describe ".statistics/2" do 35 | test "all 0 values do what you think they would" do 36 | assert Statistex.statistics([0, 0, 0, 0]) == %Statistex{ 37 | average: 0.0, 38 | variance: 0.0, 39 | standard_deviation: 0.0, 40 | standard_deviation_ratio: 0.0, 41 | median: 0.0, 42 | percentiles: %{25 => 0.0, 50 => 0.0, 75 => 0.0}, 43 | frequency_distribution: %{0 => 4}, 44 | mode: 0, 45 | minimum: 0, 46 | maximum: 0, 47 | sample_size: 4, 48 | total: 0, 49 | outliers: [], 50 | lower_outlier_bound: 0.0, 51 | upper_outlier_bound: 0.0 52 | } 53 | end 54 | 55 | test "returns Statistex struct without outliers" do 56 | assert Statistex.statistics([200, 400, 400, 400, 500, 500, 500, 700, 900]) == 57 | %Statistex{ 58 | total: 4500, 59 | average: 500.0, 60 | variance: 40_000.0, 61 | standard_deviation: 200.0, 62 | standard_deviation_ratio: 0.4, 63 | median: 500.0, 64 | percentiles: %{25 => 400.0, 50 => 500.0, 75 => 600.0}, 65 | frequency_distribution: %{200 => 1, 400 => 3, 500 => 3, 700 => 1, 900 => 1}, 66 | mode: [500, 400], 67 | minimum: 200, 68 | maximum: 900, 69 | lower_outlier_bound: 100.0, 70 | upper_outlier_bound: 900.0, 71 | outliers: [], 72 | sample_size: 9 73 | } 74 | end 75 | 76 | test "returns Statistex struct with outliers" do 77 | assert Statistex.statistics([50, 50, 450, 450, 450, 500, 500, 500, 600, 900]) == 78 | %Statistex{ 79 | total: 4450, 80 | average: 445.0, 81 | variance: 61_361.11111111111, 82 | standard_deviation: 247.71175004652304, 83 | standard_deviation_ratio: 0.5566556180820742, 84 | median: 475.0, 85 | percentiles: %{25 => 350.0, 50 => 475.0, 75 => 525.0}, 86 | frequency_distribution: %{50 => 2, 450 => 3, 500 => 3, 600 => 1, 900 => 1}, 87 | mode: [500, 450], 88 | minimum: 50, 89 | maximum: 900, 90 | lower_outlier_bound: 87.5, 91 | upper_outlier_bound: 787.5, 92 | outliers: [50, 50, 900], 93 | sample_size: 10 94 | } 95 | end 96 | 97 | # https://www.youtube.com/watch?v=rZJbj2I-_Ek 98 | test "gets outliers from the sample right" do 99 | # One could argue that this is controversial, R comes up with these results (by default): 100 | # > summary(c(9, 9, 10, 10, 10, 11, 12, 36)) 101 | # Min. 1st Qu. Median Mean 3rd Qu. Max. 102 | # 9.00 9.75 10.00 13.38 11.25 36.00 103 | # 104 | # R by default uses type 7 interpolation, we implemented type 6 interpolation though. Which 105 | # R can also use: 106 | # > quantile(c(9, 9, 10, 10, 10, 11, 12, 36), probs = c(0.25, 0.5, 0.75), type = 6) 107 | # 25% 50% 75% 108 | # 9.25 10.00 11.75 109 | # Which is our result. 110 | 111 | assert %Statistex{ 112 | median: 10.0, 113 | percentiles: %{25 => 9.25, 50 => 10.0, 75 => 11.75}, 114 | minimum: 9, 115 | maximum: 36, 116 | lower_outlier_bound: 5.5, 117 | upper_outlier_bound: 15.5, 118 | outliers: [36] 119 | } = Statistex.statistics([9, 9, 10, 10, 10, 11, 12, 36], exclude_outliers: false) 120 | end 121 | 122 | # https://en.wikipedia.org/wiki/Box_plot#Example_with_outliers 123 | test "another example with outliers" do 124 | data = [ 125 | 52, 126 | 57, 127 | 57, 128 | 58, 129 | 63, 130 | 66, 131 | 66, 132 | 67, 133 | 67, 134 | 68, 135 | 69, 136 | 70, 137 | 70, 138 | 70, 139 | 70, 140 | 72, 141 | 73, 142 | 75, 143 | 75, 144 | 76, 145 | 76, 146 | 78, 147 | 79, 148 | 89 149 | ] 150 | 151 | assert %Statistex{ 152 | median: 70.0, 153 | percentiles: %{25 => 66.0, 50 => 70.0, 75 => 75.0}, 154 | # report interquantile range? 155 | lower_outlier_bound: 52.5, 156 | upper_outlier_bound: 88.5, 157 | outliers: [52, 89] 158 | } = Statistex.statistics(data, exclude_outliers: false) 159 | end 160 | 161 | # https://en.wikipedia.org/wiki/Interquartile_range#Data_set_in_a_table 162 | test "quartile example" do 163 | assert %Statistex{ 164 | median: 87.0, 165 | percentiles: %{25 => 31.0, 50 => 87.0, 75 => 119.0} 166 | } = 167 | Statistex.statistics([7, 7, 31, 31, 47, 75, 87, 115, 116, 119, 119, 155, 177], 168 | exclude_outliers: false 169 | ) 170 | end 171 | end 172 | 173 | describe "property testing as we might get loads of data" do 174 | property "doesn't blow up no matter what kind of nonempty list of floats it's given" do 175 | check all(samples <- list_of(float(), min_length: 1)) do 176 | assert_statistics_properties(samples) 177 | end 178 | end 179 | 180 | # is milli seconds aka 90s 181 | @tag timeout: 90_000 182 | property "with a much bigger list properties still hold" do 183 | check all(samples <- big_list_big_floats()) do 184 | assert_statistics_properties(samples) 185 | end 186 | end 187 | 188 | defp assert_statistics_properties(samples) do 189 | stats = statistics(samples) 190 | 191 | assert_basic_statistics(stats) 192 | assert_mode_in_samples(stats, samples) 193 | assert_frequencies(stats, samples) 194 | assert_bounds_and_outliers(stats, samples) 195 | 196 | # shuffling values around shouldn't change the results 197 | shuffled_stats = samples |> Enum.shuffle() |> statistics() 198 | assert stats == shuffled_stats 199 | end 200 | 201 | defp assert_basic_statistics(stats) do 202 | assert stats.sample_size >= 1 203 | assert stats.minimum <= stats.maximum 204 | 205 | assert stats.minimum <= stats.average 206 | assert stats.average <= stats.maximum 207 | 208 | assert stats.minimum <= stats.median 209 | assert stats.median <= stats.maximum 210 | 211 | assert stats.median == stats.percentiles[50] 212 | 213 | assert stats.median >= stats.percentiles[25] 214 | assert stats.percentiles[75] >= stats.median 215 | 216 | assert stats.variance >= 0 217 | assert stats.standard_deviation >= 0 218 | assert stats.standard_deviation_ratio >= 0 219 | end 220 | 221 | defp assert_mode_in_samples(stats, samples) do 222 | case stats.mode do 223 | [_ | _] -> 224 | Enum.each(stats.mode, fn mode -> 225 | assert(mode in samples) 226 | end) 227 | 228 | # nothing to do there is no real mode 229 | nil -> 230 | nil 231 | 232 | mode -> 233 | assert mode in samples 234 | end 235 | end 236 | 237 | defp assert_frequencies(stats, samples) do 238 | frequency_distribution = stats.frequency_distribution 239 | frequency_entry_count = map_size(frequency_distribution) 240 | 241 | assert frequency_entry_count >= 1 242 | assert frequency_entry_count <= stats.sample_size 243 | 244 | # frequencies actually occur in samples 245 | Enum.each(frequency_distribution, fn {key, value} -> 246 | assert key in samples 247 | assert value >= 1 248 | assert is_integer(value) 249 | end) 250 | 251 | # all samples are in frequencies 252 | Enum.each(samples, fn sample -> assert Map.has_key?(frequency_distribution, sample) end) 253 | 254 | # counts of frequencies sum up to sample_size 255 | count_sum = 256 | frequency_distribution 257 | |> Map.values() 258 | |> Enum.sum() 259 | 260 | assert count_sum == stats.sample_size 261 | end 262 | 263 | defp assert_bounds_and_outliers(stats, samples) do 264 | Enum.each(stats.outliers, fn outlier -> 265 | assert outlier in samples 266 | assert outlier < stats.lower_outlier_bound || outlier > stats.upper_outlier_bound 267 | end) 268 | 269 | assert stats.lower_outlier_bound <= stats.percentiles[25] 270 | assert stats.upper_outlier_bound >= stats.percentiles[75] 271 | 272 | non_outlier_statistics = Statistex.statistics(samples, exclude_outliers: true) 273 | # outlier or not, outliers or bounds aren't changed 274 | assert non_outlier_statistics.outliers == stats.outliers 275 | assert non_outlier_statistics.lower_outlier_bound == stats.lower_outlier_bound 276 | assert non_outlier_statistics.upper_outlier_bound == stats.upper_outlier_bound 277 | 278 | if Enum.empty?(stats.outliers) do 279 | # no outliers? Then excluding outliers shouldn't change anything! 280 | assert non_outlier_statistics == stats 281 | else 282 | assert non_outlier_statistics.sample_size < stats.sample_size 283 | assert non_outlier_statistics.standard_deviation < stats.standard_deviation 284 | # property may not hold vor the std_dev ratio seemingly as values may be skewed too much 285 | 286 | frequency_occurrences = Map.keys(non_outlier_statistics.percentiles) 287 | 288 | # outliers don't make an appearances in the frequency occurrences 289 | assert MapSet.intersection(MapSet.new(stats.outliers), MapSet.new(frequency_occurrences)) == 290 | MapSet.new([]) 291 | end 292 | end 293 | 294 | defp big_list_big_floats do 295 | sized(fn size -> 296 | resize( 297 | list_of( 298 | float(), 299 | min_length: 1 300 | ), 301 | size * 4 302 | ) 303 | end) 304 | end 305 | 306 | property "percentiles are correctly related to each other" do 307 | check all(samples <- list_of(float(), min_length: 1)) do 308 | percies = percentiles(samples, [25, 50, 75, 90, 99, 99.9999]) 309 | 310 | assert percies[25] <= percies[50] 311 | assert percies[50] <= percies[75] 312 | assert percies[75] <= percies[90] 313 | assert percies[90] <= percies[99] 314 | assert percies[99] <= percies[99.9999] 315 | end 316 | end 317 | end 318 | end 319 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | --------------------------------------------------------------------------------