{"id":25298564,"url":"https://github.com/lzkelley/kalepy","last_synced_at":"2025-10-28T04:33:16.585Z","repository":{"id":34904113,"uuid":"187267055","full_name":"lzkelley/kalepy","owner":"lzkelley","description":"Kernel Density Estimation and (re)sampling","archived":false,"fork":false,"pushed_at":"2023-05-22T20:00:59.000Z","size":104431,"stargazers_count":62,"open_issues_count":14,"forks_count":13,"subscribers_count":5,"default_branch":"main","last_synced_at":"2025-10-24T08:20:00.643Z","etag":null,"topics":["kde","kernel-density-estimation","pdfs","python","python3","resample","resampling","statistical-analysis","statistics"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lzkelley.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGES.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2019-05-17T18:56:34.000Z","updated_at":"2025-07-25T14:45:40.000Z","dependencies_parsed_at":"2024-06-21T13:11:39.595Z","dependency_job_id":"af2d7bd3-012e-413c-bb6c-7bf842a2dd95","html_url":"https://github.com/lzkelley/kalepy","commit_stats":{"total_commits":594,"total_committers":4,"mean_commits":148.5,"dds":"0.35016835016835013","last_synced_commit":"b9c8fe6973a878a5a89517c6a07a043d56d8b459"},"previous_names":[],"tags_count":18,"template":false,"template_full_name":null,"purl":"pkg:github/lzkelley/kalepy","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lzkelley%2Fkalepy","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lzkelley%2Fkalepy/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lzkelley%2Fkalepy/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lzkelley%2Fkalepy/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lzkelley","download_url":"https://codeload.github.com/lzkelley/kalepy/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lzkelley%2Fkalepy/sbom","scorecard":{"id":607764,"data":{"date":"2025-08-11","repo":{"name":"github.com/lzkelley/kalepy","commit":"6feb380cd4f6face912a4b370c99e03fe3cdca54"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":2.3,"checks":[{"name":"Code-Review","score":0,"reason":"Found 0/30 approved changesets -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Maintained","score":0,"reason":"0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"SAST","score":0,"reason":"no SAST tool detected","details":["Warn: no pull requests merged into dev branch"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Token-Permissions","score":0,"reason":"detected GitHub workflow tokens with excessive permissions","details":["Warn: no topLevel permission defined: .github/workflows/coverage.yaml:1","Warn: no topLevel permission defined: .github/workflows/publish-to-pypi.yml:1","Warn: no topLevel permission defined: .github/workflows/unit-tests-ci.yaml:1","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"Signed-Releases","score":0,"reason":"Project has not signed or included provenance with any releases.","details":["Warn: release artifact v1.1 not signed: https://api.github.com/repos/lzkelley/kalepy/releases/39130106","Warn: release artifact v1.1 does not have provenance: https://api.github.com/repos/lzkelley/kalepy/releases/39130106"],"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"License","score":9,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Warn: project license file does not contain an FSF or OSI license."],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Branch-Protection","score":0,"reason":"branch protection not enabled on development/release branches","details":["Warn: branch protection not enabled for branch 'main'"],"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"Pinned-Dependencies","score":0,"reason":"dependency not pinned by hash detected -- score normalized to 0","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/coverage.yaml:23: update your workflow using https://app.stepsecurity.io/secureworkflow/lzkelley/kalepy/coverage.yaml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/coverage.yaml:28: update your workflow using https://app.stepsecurity.io/secureworkflow/lzkelley/kalepy/coverage.yaml/main?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/coverage.yaml:62: update your workflow using https://app.stepsecurity.io/secureworkflow/lzkelley/kalepy/coverage.yaml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish-to-pypi.yml:13: update your workflow using https://app.stepsecurity.io/secureworkflow/lzkelley/kalepy/publish-to-pypi.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish-to-pypi.yml:21: update your workflow using https://app.stepsecurity.io/secureworkflow/lzkelley/kalepy/publish-to-pypi.yml/main?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/publish-to-pypi.yml:32: update your workflow using https://app.stepsecurity.io/secureworkflow/lzkelley/kalepy/publish-to-pypi.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/unit-tests-ci.yaml:34: update your workflow using https://app.stepsecurity.io/secureworkflow/lzkelley/kalepy/unit-tests-ci.yaml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/unit-tests-ci.yaml:37: update your workflow using https://app.stepsecurity.io/secureworkflow/lzkelley/kalepy/unit-tests-ci.yaml/main?enable=pin","Warn: pipCommand not pinned by hash: .github/workflows/coverage.yaml:36","Warn: pipCommand not pinned by hash: .github/workflows/coverage.yaml:37","Warn: pipCommand not pinned by hash: .github/workflows/coverage.yaml:38","Warn: pipCommand not pinned by hash: .github/workflows/publish-to-pypi.yml:27","Warn: pipCommand not pinned by hash: .github/workflows/unit-tests-ci.yaml:43","Warn: pipCommand not pinned by hash: .github/workflows/unit-tests-ci.yaml:44","Warn: pipCommand not pinned by hash: .github/workflows/unit-tests-ci.yaml:45","Warn: pipCommand not pinned by hash: .github/workflows/unit-tests-ci.yaml:49","Info:   0 out of   6 GitHub-owned GitHubAction dependencies pinned","Info:   0 out of   2 third-party GitHubAction dependencies pinned","Info:   0 out of   8 pipCommand dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"Vulnerabilities","score":0,"reason":"16 existing vulnerabilities detected","details":["Warn: Project is vulnerable to: PYSEC-2018-34 / GHSA-2fc2-6r4j-p65h","Warn: Project is vulnerable to: PYSEC-2021-856 / GHSA-5545-2q6w-2gh6","Warn: Project is vulnerable to: PYSEC-2019-108 / GHSA-9fq2-x9r6-wfmf","Warn: Project is vulnerable to: PYSEC-2018-33 / GHSA-cw6w-4rcx-xphc","Warn: Project is vulnerable to: PYSEC-2021-857 / GHSA-f7c7-j99h-c22f","Warn: Project is vulnerable to: GHSA-fpfv-jqm9-f5jm","Warn: Project is vulnerable to: PYSEC-2017-1 / GHSA-frgw-fgh6-9g52","Warn: Project is vulnerable to: PYSEC-2024-4 / GHSA-2mqj-m65w-jghx","Warn: Project is vulnerable to: PYSEC-2023-165 / GHSA-cwvm-v4w8-q58c","Warn: Project is vulnerable to: PYSEC-2022-42992 / GHSA-hcpj-qp55-gfph","Warn: Project is vulnerable to: PYSEC-2023-137 / GHSA-pr76-5cm5-w9cj","Warn: Project is vulnerable to: PYSEC-2023-161 / GHSA-wfm5-v35h-vwf4","Warn: Project is vulnerable to: PYSEC-2022-249 / GHSA-9jmq-rx5f-8jwq","Warn: Project is vulnerable to: PYSEC-2019-156 / GHSA-xp76-357g-9wqq","Warn: Project is vulnerable to: PYSEC-2023-102","Warn: Project is vulnerable to: PYSEC-2023-114"],"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}}]},"last_synced_at":"2025-08-21T01:58:29.233Z","repository_id":34904113,"created_at":"2025-08-21T01:58:29.233Z","updated_at":"2025-08-21T01:58:29.233Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":280807134,"owners_count":26394535,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-24T02:00:06.418Z","response_time":73,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["kde","kernel-density-estimation","pdfs","python","python3","resample","resampling","statistical-analysis","statistics"],"created_at":"2025-02-13T04:32:06.629Z","updated_at":"2025-10-28T04:33:11.565Z","avatar_url":"https://github.com/lzkelley.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# kalepy: Kernel Density Estimation and Sampling\n\n[![build](https://github.com/lzkelley/kalepy/actions/workflows/unit-tests-ci.yaml/badge.svg)](https://github.com/lzkelley/kalepy/actions/workflows/unit-tests-ci.yaml)\n[![codecov](https://codecov.io/gh/lzkelley/kalepy/branch/master/graph/badge.svg)](https://codecov.io/gh/lzkelley/kalepy)\n[![Documentation Status](https://readthedocs.org/projects/kalepy/badge/?version=latest)](https://kalepy.readthedocs.io/en/latest/?badge=latest)\n[![DOI](https://joss.theoj.org/papers/10.21105/joss.02784/status.svg)](https://doi.org/10.21105/joss.02784)\n[![DOI](https://zenodo.org/badge/187267055.svg)](https://zenodo.org/badge/latestdoi/187267055)\n\n![kalepy animated logo](https://raw.githubusercontent.com/lzkelley/kalepy/dev/docs/media/logo_anim_small.gif)\n\nThis package performs KDE operations on multidimensional data to: **1) calculate estimated PDFs** (probability distribution functions), and **2) resample new data** from those PDFs.\n\n## Documentation\n\nA number of examples (also used for continuous integration testing) are included in [the package notebooks](https://github.com/lzkelley/kalepy/tree/master/notebooks).  Some background information and references are included in [the JOSS paper](https://joss.theoj.org/papers/10.21105/joss.02784).\n\nFull documentation is available on [kalepy.readthedocs.io](https://kalepy.readthedocs.io/en/latest/).\n\n## README Contents\n\n- [Installation](#Installation)\n- Quickstart\n    - [Basic Usage](#Basic-Usage)\n    - [Fancy Usage](#Fancy-Usage)\n- [Development \u0026 Contributions](#Development-\u0026-Contributions)\n- [Attribution (citation)](#Attribution)\n\n\n## Installation\n\n#### from pypi (i.e. via pip)\n\n```bash\npip install kalepy\n```\n\n#### from source (e.g. for development)\n\n```bash\ngit clone https://github.com/lzkelley/kalepy.git\npip install -e kalepy/\n```\n\nIn this case the package can easily be updated by changing into the source directory, pulling, and rebuilding:\n\n```bash\ncd kalepy\ngit pull\npip install -e .\n# Optional: run unit tests (using the `pytest` package)\npytest\n```\n\n\n# Basic Usage\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nimport kalepy as kale\n\nfrom kalepy.plot import nbshow\n```\n\nGenerate some random data, and its corresponding distribution function\n\n\n```python\nNUM = int(1e4)\nnp.random.seed(12345)\n# Combine data from two different PDFs\n_d1 = np.random.normal(4.0, 1.0, NUM)\n_d2 = np.random.lognormal(0, 0.5, size=NUM)\ndata = np.concatenate([_d1, _d2])\n\n# Calculate the \"true\" distribution\nxx = np.linspace(0.0, 7.0, 100)[1:]\nyy = 0.5*np.exp(-(xx - 4.0)**2/2) / np.sqrt(2*np.pi)\nyy += 0.5 * np.exp(-np.log(xx)**2/(2*0.5**2)) / (0.5*xx*np.sqrt(2*np.pi))\n```\n\n### Plotting Smooth Distributions\n\n\n```python\n# Reconstruct the probability-density based on the given data points.\npoints, density = kale.density(data, probability=True)\n\n# Plot the PDF\nplt.plot(points, density, 'k-', lw=2.0, alpha=0.8, label='KDE')\n\n# Plot the \"true\" PDF\nplt.plot(xx, yy, 'r--', alpha=0.4, lw=3.0, label='truth')\n\n# Plot the standard, histogram density estimate\nplt.hist(data, density=True, histtype='step', lw=2.0, alpha=0.5, label='hist')\n\nplt.legend()\nnbshow()\n```\n\n\n    \n![png](https://raw.githubusercontent.com/lzkelley/kalepy/dev/docs/media/demo_files/demo_8_0.png)\n    \n\n\n### resampling: constructing statistically similar values\n\nDraw a new sample of data-points from the KDE PDF\n\n\n```python\n# Draw new samples from the KDE reconstructed PDF\nsamples = kale.resample(data)\n\n# Plot new samples\nplt.hist(samples, density=True, label='new samples', alpha=0.5, color='0.65', edgecolor='b')\n# Plot the old samples\nplt.hist(data, density=True, histtype='step', lw=2.0, alpha=0.5, color='r', label='input data')\n\n# Plot the KDE reconstructed PDF\nplt.plot(points, density, 'k-', lw=2.0, alpha=0.8, label='KDE')\n\nplt.legend()\nnbshow()\n```\n\n\n    \n![png](https://raw.githubusercontent.com/lzkelley/kalepy/dev/docs/media/demo_files/demo_11_0.png)\n    \n\n\n### Multivariate Distributions\n\n\n```python\nreload(kale.plot)\n\n# Load some random-ish three-dimensional data\nnp.random.seed(9485)\ndata = kale.utils._random_data_3d_02(num=3e3)\n\n# Construct a KDE\nkde = kale.KDE(data)\n\n# Construct new data by resampling from the KDE\nresamp = kde.resample(size=1e3)\n\n# Plot the data and distributions using the builtin `kalepy.corner` plot\ncorner, h1 = kale.corner(kde, quantiles=[0.5, 0.9])\nh2 = corner.clean(resamp, quantiles=[0.5, 0.9], dist2d=dict(median=False), ls='--')\n\ncorner.legend([h1, h2], ['input data', 'new samples'])\n\nnbshow()\n```\n\n\n    \n![png](https://raw.githubusercontent.com/lzkelley/kalepy/dev/docs/media/demo_files/demo_13_0.png)\n    \n\n\n\n```python\n# Resample the data (default output is the same size as the input data)\nsamples = kde.resample()\n\n\n# ---- Plot the input data compared to the resampled data ----\n\nfig, axes = plt.subplots(figsize=[16, 4], ncols=kde.ndim)\n\nfor ii, ax in enumerate(axes):\n    # Calculate and plot PDF for `ii`th parameter (i.e. data dimension `ii`)\n    xx, yy = kde.density(params=ii, probability=True)\n    ax.plot(xx, yy, 'k--', label='KDE', lw=2.0, alpha=0.5)\n    # Draw histograms of original and newly resampled datasets\n    *_, h1 = ax.hist(data[ii], histtype='step', density=True, lw=2.0, label='input')\n    *_, h2 = ax.hist(samples[ii], histtype='step', density=True, lw=2.0, label='resample')\n    # Add 'kalepy.carpet' plots showing the data points themselves\n    kale.carpet(data[ii], ax=ax, color=h1[0].get_facecolor())\n    kale.carpet(samples[ii], ax=ax, color=h2[0].get_facecolor(), shift=ax.get_ylim()[0])\n\naxes[0].legend()\nnbshow()\n```\n\n\n    \n![png](https://raw.githubusercontent.com/lzkelley/kalepy/dev/docs/media/demo_files/demo_14_0.png)\n    \n\n\n# Fancy Usage\n\n### Reflecting Boundaries\n\nWhat if the distributions you're trying to capture have edges in them, like in a uniform distribution between two bounds?  Here, the KDE chooses 'reflection' locations based on the extrema of the given data.\n\n\n```python\n# Uniform data (edges at -1 and +1)\nNDATA = 1e3\nnp.random.seed(54321)\ndata = np.random.uniform(-1.0, 1.0, int(NDATA))\n\n# Create a 'carpet' plot of the data\nkale.carpet(data, label='data')\n# Histogram the data\nplt.hist(data, density=True, alpha=0.5, label='hist', color='0.65', edgecolor='k')\n\n# ---- Standard KDE will undershoot just-inside the edges and overshoot outside edges\npoints, pdf_basic = kale.density(data, probability=True)\nplt.plot(points, pdf_basic, 'r--', lw=3.0, alpha=0.5, label='KDE')\n\n# ---- Reflecting KDE keeps probability within the given bounds\n# setting `reflect=True` lets the KDE guess the edge locations based on the data extrema\npoints, pdf_reflect = kale.density(data, reflect=True, probability=True)\nplt.plot(points, pdf_reflect, 'b-', lw=2.0, alpha=0.75, label='reflecting KDE')\n\nplt.legend()\nnbshow()\n```\n\n\n    \n![png](https://raw.githubusercontent.com/lzkelley/kalepy/dev/docs/media/demo_files/demo_18_0.png)\n    \n\n\nExplicit reflection locations can also be provided (in any number of dimensions).\n\n\n```python\n# Construct random data, add an artificial 'edge'\nnp.random.seed(5142)\nedge = 1.0\ndata = np.random.lognormal(sigma=0.5, size=int(3e3))\ndata = data[data \u003e= edge]\n\n# Histogram the data, use fixed bin-positions\nedges = np.linspace(edge, 4, 20)\nplt.hist(data, bins=edges, density=True, alpha=0.5, label='data', color='0.65', edgecolor='k')\n\n# Standard KDE with over \u0026 under estimates\npoints, pdf_basic = kale.density(data, probability=True)\nplt.plot(points, pdf_basic, 'r--', lw=4.0, alpha=0.5, label='Basic KDE')\n\n# Reflecting KDE setting the lower-boundary to the known value\n#    There is no upper-boundary when `None` is given.\npoints, pdf_basic = kale.density(data, reflect=[edge, None], probability=True)\nplt.plot(points, pdf_basic, 'b-', lw=3.0, alpha=0.5, label='Reflecting KDE')\n\nplt.gca().set_xlim(edge - 0.5, 3)\nplt.legend()\nnbshow()\n```\n\n\n    \n![png](https://raw.githubusercontent.com/lzkelley/kalepy/dev/docs/media/demo_files/demo_20_0.png)\n    \n\n\n### Multivariate Reflection\n\n\n```python\n# Load a predefined dataset that has boundaries at:\n#   x: 0.0 on the low-end\n#   y: 1.0 on the high-end\ndata = kale.utils._random_data_2d_03()\n\n# Construct a KDE with the given reflection boundaries given explicitly\nkde = kale.KDE(data, reflect=[[0, None], [None, 1]])\n\n# Plot using default settings\nkale.corner(kde)\n\nnbshow()\n```\n\n\n    \n![png](https://raw.githubusercontent.com/lzkelley/kalepy/dev/docs/media/demo_files/demo_22_0.png)\n    \n\n\n### Specifying Bandwidths and Kernel Functions\n\n\n```python\n# Load predefined 'random' data\ndata = kale.utils._random_data_1d_02(num=100)\n# Choose a uniform x-spacing for drawing PDFs\nxx = np.linspace(-2, 8, 1000)\n\n# ------ Choose the kernel-functions and bandwidths to test -------  #\nkernels = ['parabola', 'gaussian', 'box']                            #\nbandwidths = [None, 0.9, 0.15]     # `None` means let kalepy choose  #\n# -----------------------------------------------------------------  #\n\nylabels = ['Automatic', 'Course', 'Fine']\nfig, axes = plt.subplots(figsize=[16, 10], ncols=len(kernels), nrows=len(bandwidths), sharex=True, sharey=True)\nplt.subplots_adjust(hspace=0.2, wspace=0.05)\nfor (ii, jj), ax in np.ndenumerate(axes):\n    \n    # ---- Construct KDE using particular kernel-function and bandwidth ---- #\n    kern = kernels[jj]                                                       # \n    bw = bandwidths[ii]                                                      #\n    kde = kale.KDE(data, kernel=kern, bandwidth=bw)                          #\n    # ---------------------------------------------------------------------- #\n    \n    # If bandwidth was set to `None`, then the KDE will choose the 'optimal' value\n    if bw is None:\n        bw = kde.bandwidth[0, 0]\n        \n    ax.set_title('{} (bw={:.3f})'.format(kern, bw))\n    if jj == 0:\n        ax.set_ylabel(ylabels[ii])\n\n    # plot the KDE\n    ax.plot(*kde.pdf(points=xx), color='r')\n    # plot histogram of the data (same for all panels)\n    ax.hist(data, bins='auto', color='b', alpha=0.2, density=True)\n    # plot  carpet   of the data (same for all panels)\n    kale.carpet(data, ax=ax, color='b')\n    \nax.set(xlim=[-2, 5], ylim=[-0.2, 0.6])\nnbshow()\n```\n\n\n    \n![png](https://raw.githubusercontent.com/lzkelley/kalepy/dev/docs/media/demo_files/demo_24_0.png)\n    \n\n\n## Resampling\n\n### Using different data `weights`\n\n\n```python\n# Load some random data (and the 'true' PDF, for comparison)\ndata, truth = kale.utils._random_data_1d_01()\n\n# ---- Resample the same data, using different weightings ---- #\nresamp_uni = kale.resample(data, size=1000)                       # \nresamp_sqr  = kale.resample(data, weights=data**2, size=1000)      #\nresamp_inv = kale.resample(data, weights=data**-1, size=1000)     #\n# ------------------------------------------------------------ # \n\n\n# ---- Plot different distributions ----\n\n# Setup plotting parameters\nkw = dict(density=True, histtype='step', lw=2.0, alpha=0.75, bins='auto')\n\nxx, yy = truth\nsamples = [resamp_inv, resamp_uni, resamp_sqr]\nyvals = [yy/xx, yy, yy*xx**2/10]\nlabels = [r'$\\propto X^{-1}$', r'$\\propto 1$', r'$\\propto X^2$']\n\nplt.figure(figsize=[10, 5])\n\nfor ii, (res, yy, lab) in enumerate(zip(samples, yvals, labels)):\n    hh, = plt.plot(xx, yy, ls='--', alpha=0.5, lw=2.0)\n    col = hh.get_color()\n    kale.carpet(res, color=col, shift=-0.1*ii)\n    plt.hist(res, color=col, label=lab, **kw)\n\nplt.gca().set(xlim=[-0.5, 6.5])\n# Add legend\nplt.legend()\n# display the figure if this is a notebook\nnbshow()\n```\n\n\n    \n![png](https://raw.githubusercontent.com/lzkelley/kalepy/dev/docs/media/demo_files/demo_27_0.png)\n    \n\n\n### Resampling while 'keeping' certain parameters/dimensions\n\n\n```python\n# Construct covariant 2D dataset where the 0th parameter takes on discrete values\nxx = np.random.randint(2, 7, 1000)\nyy = np.random.normal(4, 2, xx.size) + xx**(3/2)\ndata = [xx, yy]\n\n# 2D plotting settings: disable the 2D histogram \u0026 disable masking of dense scatter-points\ndist2d = dict(hist=False, mask_dense=False)\n\n# Draw a corner plot \nkale.corner(data, dist2d=dist2d)\n\nnbshow()\n```\n\n\n    \n![png](https://raw.githubusercontent.com/lzkelley/kalepy/dev/docs/media/demo_files/demo_29_0.png)\n    \n\n\nA standard KDE resampling will smooth out the discrete variables, creating a smooth(er) distribution.  Using the `keep` parameter, we can choose to resample from the actual data values of that parameter instead of resampling with 'smoothing' based on the KDE.\n\n\n```python\nkde = kale.KDE(data)\n\n# ---- Resample the data both normally, and 'keep'ing the 0th parameter values ---- #\nresamp_stnd = kde.resample()                                                        #\nresamp_keep = kde.resample(keep=0)                                                  #\n# --------------------------------------------------------------------------------- #\n\ncorner = kale.Corner(2)\ndist2d['median'] = False    # disable median 'cross-hairs'\nh1 = corner.plot(resamp_stnd, dist2d=dist2d)\nh2 = corner.plot(resamp_keep, dist2d=dist2d)\n\ncorner.legend([h1, h2], ['Standard', \"'keep'\"])\nnbshow()\n```\n\n\n    \n![png](https://raw.githubusercontent.com/lzkelley/kalepy/dev/docs/media/demo_files/demo_31_0.png)\n    \n\n\n## Development \u0026 Contributions\n\nPlease visit the `github page \u003chttps://github.com/lzkelley/kalepy\u003e`_ for issues or bug reports.  Contributions and feedback are very welcome.\n\nContributors:\n* Luke Zoltan Kelley (@lzkelley)\n* Zachary Hafen (@zhafen)\n\nJOSS Paper:\n* Kexin Rong (@kexinrong)\n* Arfon Smith (@arfon)\n* Will Handley (@williamjameshandley)\n\n\n## Attribution\n\nA JOSS paper has been submitted.  If you have found this package useful in your research, please add a reference to the code paper:\n\n.. code-block:: tex\n\n    @article{kalepy,\n      author = {Luke Zoltan Kelley},\n      title = {kalepy: a python package for kernel density estimation and sampling},\n      journal = {The Journal of Open Source Software},\n      publisher = {The Open Journal},\n    }\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flzkelley%2Fkalepy","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flzkelley%2Fkalepy","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flzkelley%2Fkalepy/lists"}