licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
217
# Lennard-Jones-FJC model thermodynamics (isotensional/asymptotic/reduced/legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.LennardJones.Thermodynamics.Isotensional.Asymptotic.Reduced.Legendre] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
300
# Log-squared-FJC model thermodynamics * [Log-squared-FJC model thermodynamics (isometric)](../../../../isometric) * [Log-squared-FJC model thermodynamics (isotensional)](../../../../isotensional) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.LogSquared.Thermodynamics] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
252
# Log-squared-FJC model thermodynamics (isometric) * [Log-squared-FJC model thermodynamics (isometric/asymptotic)](../../../../../asymptotic) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.LogSquared.Thermodynamics.Isometric] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
354
# Log-squared-FJC model thermodynamics (isotensional) * [Log-squared-FJC model thermodynamics (isotensional/asymptotic)](../../../../../asymptotic) * [Log-squared-FJC model thermodynamics (isotensional/legendre)](../../../../../legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.LogSquared.Thermodynamics.Isotensional] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
386
# Log-squared-FJC model thermodynamics (isometric/asymptotic) * [Log-squared-FJC model thermodynamics (isometric/asymptotic/reduced)](../../../../../../reduced) * [Log-squared-FJC model thermodynamics (isometric/asymptotic/legendre)](../../../../../../legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.LogSquared.Thermodynamics.Isometric.Asymptotic] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
191
# Log-squared-FJC model thermodynamics (isometric/asymptotic/legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.LogSquared.Thermodynamics.Isometric.Asymptotic.Legendre] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
311
# Log-squared-FJC model thermodynamics (isometric/asymptotic/reduced) * [Log-squared-FJC model thermodynamics (isometric/asymptotic/reduced/legendre)](../../../../../../../legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.LogSquared.Thermodynamics.Isometric.Asymptotic.Reduced] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
207
# Log-squared-FJC model thermodynamics (isometric/asymptotic/reduced/legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.LogSquared.Thermodynamics.Isometric.Asymptotic.Reduced.Legendre] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
398
# Log-squared-FJC model thermodynamics (isotensional/asymptotic) * [Log-squared-FJC model thermodynamics (isotensional/asymptotic/reduced)](../../../../../../reduced) * [Log-squared-FJC model thermodynamics (isotensional/asymptotic/legendre)](../../../../../../legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.LogSquared.Thermodynamics.Isotensional.Asymptotic] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
175
# Log-squared-FJC model thermodynamics (isotensional/legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.LogSquared.Thermodynamics.Isotensional.Legendre] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
197
# Log-squared-FJC model thermodynamics (isotensional/asymptotic/legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.LogSquared.Thermodynamics.Isotensional.Asymptotic.Legendre] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
320
# Log-squared-FJC model thermodynamics (isotensional/asymptotic/reduced) * [Log-squared-FJC model thermodynamics (isotensional/asymptotic/reduced/legendre)](../../../../../../../legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.LogSquared.Thermodynamics.Isotensional.Asymptotic.Reduced] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
213
# Log-squared-FJC model thermodynamics (isotensional/asymptotic/reduced/legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.LogSquared.Thermodynamics.Isotensional.Asymptotic.Reduced.Legendre] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
277
# Morse-FJC model thermodynamics * [Morse-FJC model thermodynamics (isometric)](../../../../isometric) * [Morse-FJC model thermodynamics (isotensional)](../../../../isotensional) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.Morse.Thermodynamics] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
235
# Morse-FJC model thermodynamics (isometric) * [Morse-FJC model thermodynamics (isometric/asymptotic)](../../../../../asymptotic) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.Morse.Thermodynamics.Isometric] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
331
# Morse-FJC model thermodynamics (isotensional) * [Morse-FJC model thermodynamics (isotensional/asymptotic)](../../../../../asymptotic) * [Morse-FJC model thermodynamics (isotensional/legendre)](../../../../../legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.Morse.Thermodynamics.Isotensional] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
363
# Morse-FJC model thermodynamics (isometric/asymptotic) * [Morse-FJC model thermodynamics (isometric/asymptotic/reduced)](../../../../../../reduced) * [Morse-FJC model thermodynamics (isometric/asymptotic/legendre)](../../../../../../legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.Morse.Thermodynamics.Isometric.Asymptotic] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
180
# Morse-FJC model thermodynamics (isometric/asymptotic/legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.Morse.Thermodynamics.Isometric.Asymptotic.Legendre] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
294
# Morse-FJC model thermodynamics (isometric/asymptotic/reduced) * [Morse-FJC model thermodynamics (isometric/asymptotic/reduced/legendre)](../../../../../../../legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.Morse.Thermodynamics.Isometric.Asymptotic.Reduced] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
196
# Morse-FJC model thermodynamics (isometric/asymptotic/reduced/legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.Morse.Thermodynamics.Isometric.Asymptotic.Reduced.Legendre] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
375
# Morse-FJC model thermodynamics (isotensional/asymptotic) * [Morse-FJC model thermodynamics (isotensional/asymptotic/reduced)](../../../../../../reduced) * [Morse-FJC model thermodynamics (isotensional/asymptotic/legendre)](../../../../../../legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.Morse.Thermodynamics.Isotensional.Asymptotic] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
164
# Morse-FJC model thermodynamics (isotensional/legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.Morse.Thermodynamics.Isotensional.Legendre] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
186
# Morse-FJC model thermodynamics (isotensional/asymptotic/legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.Morse.Thermodynamics.Isotensional.Asymptotic.Legendre] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
303
# Morse-FJC model thermodynamics (isotensional/asymptotic/reduced) * [Morse-FJC model thermodynamics (isotensional/asymptotic/reduced/legendre)](../../../../../../../legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.Morse.Thermodynamics.Isotensional.Asymptotic.Reduced] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
202
# Morse-FJC model thermodynamics (isotensional/asymptotic/reduced/legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Ufjc.Morse.Thermodynamics.Isotensional.Asymptotic.Reduced.Legendre] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
246
# WLC model thermodynamics * [WLC model thermodynamics (isometric)](../../../isometric) * [WLC model thermodynamics (isotensional)](../../../isotensional) ```@autodocs Modules = [Polymers.Physics.SingleChain.Wlc.Thermodynamics] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
209
# WLC model thermodynamics (isometric) * [WLC model thermodynamics (isometric/legendre)](../../../../legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Wlc.Thermodynamics.Isometric] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
218
# WLC model thermodynamics (isotensional) * [WLC model thermodynamics (isotensional/legendre)](../../../../legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Wlc.Thermodynamics.Isotensional] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
150
# WLC model thermodynamics (isometric/legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Wlc.Thermodynamics.Isometric.Legendre] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
156
# WLC model thermodynamics (isotensional/legendre) ```@autodocs Modules = [Polymers.Physics.SingleChain.Wlc.Thermodynamics.Isotensional.Legendre] ```
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
302
--- layout: default title: Contributors nav_order: 1 description: "This is the description!" permalink: /contributors --- # Contributors <br> <a href="https://github.com/sandialabs/Polymers/graphs/contributors"> <img src="https://contrib.rocks/image?repo=sandialabs/Polymers" /> </a>
Polymers
https://github.com/sandialabs/Polymers.git
[ "BSD-3-Clause" ]
0.3.7
5c9185bac8d9a5f2d96a37387c88fa5cf535e1be
docs
145
--- layout: default title: Home nav_order: 1 description: "This is the description!" permalink: / --- # Polymers Modeling Library Hello world!
Polymers
https://github.com/sandialabs/Polymers.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
2976
using EntropyHub using Documenter, DocumenterTools #OutdatedWarning.generate("src") DocMeta.setdocmeta!(EntropyHub, :DocTestSetup, :(using EntropyHub); recursive=true) makedocs( source="src", modules=[EntropyHub], authors="Matthew W. Flood <[email protected]>", #repo="https://github.com/MattWillFlood/EntropyHub.jl/blob/{commit}{path}#{line}", #repo = Remotes.repourl("https://github.com/MattWillFlood/EntropyHub.jl"), sitename="EntropyHub.jl", doctest=false, draft=false, clean=true, format=Documenter.HTML(; prettyurls=get(ENV, "CI", nothing) == "true", canonical="https://mattwillflood.github.io/EntropyHub.jl/", assets = ["assets/favicon.ico"], collapselevel = 1, ), pages=[ "Home" => "index.md", "Guide" => ["Base Entropies" => "Guide/Base_Entropies.md", "Cross-Entropies" => "Guide/Cross_Entropies.md", "Multivariate Entropies" => "Guide/Multivariate_Entropies.md", "Bidimensional Entropies" => "Guide/Bidimensional_Entropies.md", "Multiscale Entropies" => "Guide/Multiscale_Entropies.md", "Multiscale Cross-Entropies" => "Guide/Multiscale_Cross_Entropies.md", "Multivariate Multiscale Entropies" => "Guide/Multivariate_Multiscale_Entropies.md", "Other Functions" => "Guide/Other.md", ], "Examples" => ["Notes on Examples" => "Examples/Examples.md", "Ex.1: Sample Entropy" => "Examples/Example1.md", "Ex.2: Permutation Entropy" => "Examples/Example2.md", "Ex.3: Phase Entropy" => "Examples/Example3.md", "Ex.4: Cross-Distribution Entropy" => "Examples/Example4.md", "Ex.5: Multiscale Entropy Object" => "Examples/Example5.md", "Ex.6: Multiscale [Increment] Entropy" => "Examples/Example6.md", "Ex.7: Refined Multiscale [Sample] Entropy" => "Examples/Example7.md", "Ex.8: Composite Multiscale Cross-Approximate Entropy" => "Examples/Example8.md", "Ex.9: Hierarchical Multiscale corrected Cross-Conditional Entropy" => "Examples/Example9.md", "Ex.10: Bidimensional Fuzzy Entropy" => "Examples/Example10.md", "Ex.11: Multivariate Dispersion Entropy" => "Examples/Example11.md", "Ex.12: [Generalized] Refined-composite Multivariate Multiscale Fuzzy Entropy" => "Examples/Example12.md", "Ex.13: Window Data Tool" => "Examples/Example13.md", ], ], ) deploydocs( repo="github.com/MattWillFlood/EntropyHub.jl.git", versions = ["stable" => "v^", "v#.#"], branch = "gh-pages", #versions = nothing, ) #= deploydocs(; repo="github.com/MattWillFlood/EntropyHub.jl", devbranch = "master", devurl = "dev", versions = ["stable" => "v^", "v#.#.#", devurl =>devurl], ) """ =#
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
14164
module EntropyHub export ApEn, AttnEn, BubbEn, CoSiEn, CondEn, DispEn, DistEn, DivEn, EnofEn, FuzzEn, GridEn, IncrEn, K2En, PermEn, PhasEn, RangEn, SampEn, SlopEn, SyDyEn, SpecEn, XApEn, XCondEn, XDistEn, XFuzzEn, XK2En, XPermEn, XSpecEn, XSampEn, MvSampEn, MvCoSiEn, MvPermEn, MvDispEn, MvFuzzEn, SampEn2D, FuzzEn2D, DistEn2D, DispEn2D, PermEn2D, EspEn2D, MSobject, MSEn, cMSEn, rMSEn, hMSEn, XMSEn, cXMSEn, rXMSEn, hXMSEn, MvMSEn, cMvMSEn, EMD, ExampleData, WindowData # using Reexport include("./_ApEn.jl"), include("./_AttnEn.jl"), include("./_BubbEn.jl"), include("./_CondEn.jl"), include("./_CoSiEn.jl"), include("./_DispEn.jl"), include("./_DistEn.jl"), include("./_DivEn.jl"), include("./_FuzzEn.jl"), include("./_EnofEn.jl"), include("./_GridEn.jl"), include("./_IncrEn.jl"), include("./_K2En.jl"), include("./_PermEn.jl"), include("./_PhasEn.jl"), include("./_RangEn.jl"), include("./_SampEn.jl"), include("./_SpecEn.jl"), include("./_SyDyEn.jl"), include("./_SlopEn.jl"), include("./_XApEn.jl"), include("./_XFuzzEn.jl"), include("./_XDistEn.jl"), include("./_XCondEn.jl"), include("./_XSpecEn.jl"), include("./_XSampEn.jl"), include("./_XK2En.jl"), include("./_XPermEn.jl"), include("./_MSobject.jl"), include("./_ExampleData.jl"), include("./_WindowData.jl"), include("./_MSEn.jl"), include("./_XMSEn.jl"), include("./_cMSEn.jl"), include("./_cXMSEn.jl"), include("./_rMSEn.jl"), include("./_rXMSEn.jl"), include("./_hMSEn.jl"), include("./_hXMSEn.jl"), include("./_SampEn2D.jl"), include("./_FuzzEn2D.jl"), include("./_DistEn2D.jl"), include("./_DispEn2D.jl"), include("./_PermEn2D.jl"), include("./_EspEn2D.jl"), include("./_MvSampEn.jl"), include("./_MvFuzzEn.jl"), include("./_MvDispEn.jl"), include("./_MvPermEn.jl"), include("./_MvCoSiEn.jl"), include("./_MvMSEn.jl"), include("./_cMvMSEn.jl"), # Base Entropies: using ._ApEn: ApEn using ._AttnEn: AttnEn using ._BubbEn: BubbEn using ._CoSiEn: CoSiEn using ._CondEn: CondEn using ._DispEn: DispEn using ._DistEn: DistEn using ._DivEn: DivEn using ._EnofEn: EnofEn using ._FuzzEn: FuzzEn using ._GridEn: GridEn using ._IncrEn: IncrEn using ._K2En: K2En using ._PermEn: PermEn using ._PhasEn: PhasEn using ._RangEn: RangEn using ._SampEn: SampEn using ._SlopEn: SlopEn using ._SpecEn: SpecEn using ._SyDyEn: SyDyEn # Cross Entropies: using ._XApEn: XApEn using ._XCondEn: XCondEn using ._XDistEn: XDistEn using ._XFuzzEn: XFuzzEn using ._XK2En: XK2En using ._XPermEn: XPermEn using ._XSampEn: XSampEn using ._XSpecEn: XSpecEn # Multivariate Entropies: using ._MvSampEn: MvSampEn using ._MvFuzzEn: MvFuzzEn using ._MvCoSiEn: MvCoSiEn using ._MvDispEn: MvDispEn using ._MvPermEn: MvPermEn # Bidimensional Entropies using ._SampEn2D: SampEn2D using ._DistEn2D: DistEn2D using ._FuzzEn2D: FuzzEn2D using ._DispEn2D: DispEn2D using ._PermEn2D: PermEn2D using ._EspEn2D: EspEn2D # Multiscale Entropies using ._MSobject: MSobject using ._MSEn: MSEn, EMD using ._cMSEn: cMSEn using ._rMSEn: rMSEn using ._hMSEn: hMSEn using ._XMSEn: XMSEn using ._cXMSEn: cXMSEn using ._rXMSEn: rXMSEn using ._hXMSEn: hXMSEn using ._MvMSEn: MvMSEn using ._cMvMSEn: cMvMSEn # Other Functions using ._ExampleData: ExampleData using ._WindowData: WindowData greet() = print(raw""" ___ _ _ _____ _____ ____ ____ _ _ | _|| \ | ||_ _|| \| || || \ / | ___________ | \_ | \| | | | | __/| || __| \ \_/ / / _______ \ | _|| \ \ | | | | \ | || | \ / | / ___ \ | | \_ | |\ | | | | |\ \ | || | | | | | / \ | | |___||_| \_| |_| |_| \_||____||_| |_| _|_|__\___/ | | _ _ _ _ ____ / |__\______\/ | | | | || | | || \ An open-source | /\______\__|_/ | |_| || | | || | toolkit for | | / \ | | | _ || | | || \ entropic time- | | \___/ | | | | | || |_| || \ series analysis | \_______/ | |_| |_|\_____/|_____/ \___________/ Please use the following citation on any scientific outputs achieved with the help of EntropyHub: Matthew W. Flood, EntropyHub: An Open-Source Toolkit for Entropic Time Series Analysis, PLoS One 16(11):e0259448 (2021), DOI: 10.1371/journal.pone.0259448 www.EntropyHub.xyz """) raw""" ___ _ _ _____ _____ ____ ____ _ _ | _|| \ | ||_ _|| \| || || \ / | ___________ | \_ | \| | | | | __/| || __| \ \_/ / / _______ \ | _|| \ \ | | | | \ | || | \ / | / ___ \ | | \_ | |\ | | | | |\ \ | || | | | | | / \ | | |___||_| \_| |_| |_| \_||____||_| |_| _|_|__\___/ | | _ _ _ _ ____ / |__\______\/ | | | | || | | || \ An open-source | /\______\__|_/ | |_| || | | || | toolkit for | | / \ | | | _ || | | || \ entropic time- | | \___/ | | | | | || |_| || \ series analysis | \_______/ | |_| |_|\_____/|_____/ \___________/ EntropyHub functions belong to one of five main classes/categories: Base Entropies >> e.g. Approximate Entropy (ApEn), Sample Entropy (SampEn) Cross Entropies >> e.g. Cross-Approximate Entropy (XApEn) Cross-Sample Entropy (XSampEn) Bidimensional Entropies >> e.g. Bidimensional Sample Entropy (SampEn2D) Bidimensional Fuzzy Entropy (FuzzEn2D) Multiscale Entropies >> e.g. Multiscale Sample Entropy (MSEn) Refined Multiscale Sample Entropy (rMSEn) Composite Multiscale Sample Entropy (cMSEn) Multiscale Cross Entropies >> e.g. Multiscale Cross-Sample Entropy (XMSEn) Refined Multiscale Cross-Sample Entropy (rXMSEn) _________________________________________________________________________ Base Entropies | Function Name ______________________________________________________|__________________ Approximate Entropy | ApEn Sample Entropy | SampEn Fuzzy Entropy | FuzzEn Kolmogorov Entropy | K2En Permutation Entropy | PermEn Conditional Entropy | CondEn Distribution Entropy | DistEn Spectral Entropy | SpecEn Dispersion Entropy | DispEn Symbolic Dynamic Entropy | SyDyEn Increment Entropy | IncrEn Cosine Similarity Entropy | CoSiEn Phase Entropy | PhasEn Slope Entropy | SlopEn Bubble Entropy | BubbEn Gridded Distribution Entropy | GridEn Entropy of Entropy | EnofEn Attention Entropy | AttnEn Diversity Entropy | DivEn Range Entropy | RangEn _________________________________________________________________________ Cross Entropies | Function Name ______________________________________________________|__________________ Cross Sample Entropy | XSampEn Cross Approximate Entropy | XApEn Cross Fuzzy Entropy | XFuzzEn Cross Permutation Entropy | XPermEn Cross Conditional Entropy | XCondEn Cross Distribution Entropy | XDistEn Cross Spectral Entropy | XSpecEn Cross Kolmogorov Entropy | XK2En _________________________________________________________________________ Multivariate Entropies | Function Name _____________________________________________________|___________________ Multivariate Sample Entropy | MvSampEn Multivariate Fuzzy Entropy | MvFuzzEn Multivariate Cosine Similarity Entropy | MvCoSiEn Multivariate Dispersion Entropy | MvDispEn Multivariate Permutation Entropy | MvPermEn _________________________________________________________________________ Bidimensional Entropies | Function Name _____________________________________________________|__________________ Bidimensional Sample Entropy | SampEn2D Bidimensional Fuzzy Entropy | FuzzEn2D Bidimensional Distribution Entropy | DistEn2D Bidimensional Dispersion Entropy | DispEn2D Bidimensional Permutation Entropy | PermEn2D Bidimensional Espinosa Entropy | EspEn2D _________________________________________________________________________ Multiscale Entropy Functions | Function Name ______________________________________________________|__________________ Multiscale Entropy Object | MSobject | Multiscale Entropy | MSEn Composite/Refined-Composite Multiscale Entropy | cMSEn Refined Multiscale Entropy | rMSEn Hierarchical Multiscale Entropy Object | hMSEn _________________________________________________________________________ Multiscale Entropies MSEn | Function Name _________________________________________________________________________ Multiscale Sample Entropy | Multiscale Approximate Entropy | Multiscale Fuzzy Entropy | Multiscale Permutation Entropy | Multiscale Dispersion Entropy | Multiscale Cosine Similarity Entropy | Multiscale Symblic Dynamic Entropy | MSobject Multiscale Conditional Entropy | + Multiscale Entropy of Entropy | MSEn / cMSEn Multiscale Gridded Distribution Entropy | rMSEn / hMSEn Multiscale Slope Entropy | Multiscale Phase Entropy | Multiscale Kolmogorov Entropy | Multiscale Distribution Entropy | Multiscale Bubble Entropy | Multiscale Increment Entropy | Multiscale Attention Entropy | Multiscale Diversity Entropy | Multiscale Range Entropy | _________________________________________________________________________ Multiscale Cross-Entropy Functions | Function Name ______________________________________________________|__________________ Multiscale Cross-Entropy Object | MSobject | Multiscale Cross-Entropy | XMSEn Composite/Refined-Composite Multiscale Cross-Entropy | cXMSEn Refined Multiscale Entropy | rXMSEn Hierarchical Multiscale Entropy Object | hXMSEn _________________________________________________________________________ Multiscale Cross-Entropies | Function Name _________________________________________________________________________ Multiscale Cross-Sample Entropy | Multiscale Cross-Approximate Entropy | Multiscale Cross-Fuzzy Entropy | MSobject Multiscale Cross-Permutation Entropy | + Multiscale Cross-Distribution Entropy | XMSEn / cXMSEn Multiscale Cross-Kolmogorov Entropy | rXMSEn / hXMSEn Multiscale Cross-Conditional Entropy | We kindly ask that if you use EntropyHub in your research, to please include the following citation with the appropriate version number, as well as original articles upon which functions are derived: Matthew W. Flood (2021), "EntropyHub - An open source toolkit for entropic time series analysis" PLoS ONE 16(11):e0295448, DOI: 10.1371/journal.pone.0259448 https://www.EntropyHub.xyz © Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """ end
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
3430
module _ApEn export ApEn using Statistics: mean, std """ Ap, Phi = ApEn(Sig) Returns the approximate entropy estimates `Ap` and the log-average number of matched vectors `Phi` for `m` = [0,1,2], estimated from the data sequence `Sig` using the default parameters: embedding dimension = 2, time delay = 1, radius distance threshold = 0.2*SD(`Sig`), logarithm = natural Ap, Phi = ApEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Real=0.2*std(Sig,corrected=false), Logx::Real=exp(1)) Returns the approximate entropy estimates `Ap` of the data sequence `Sig` for dimensions = [0,1,...,`m`] using the specified keyword arguments: # Arguments: `m` - Embedding Dimension, a positive integer\n `tau` - Time Delay, a positive integer\n `r` - Radius Distance Threshold, a positive scalar \n `Logx` - Logarithm base, a positive scalar\n # See also `XApEn`, `SampEn`, `MSEn`, `FuzzEn`, `PermEn`, `CondEn`, `DispEn` # References: [1] Steven M. Pincus, "Approximate entropy as a measure of system complexity." Proceedings of the National Academy of Sciences 88.6 (1991): 2297-2301. """ function ApEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Real=0.2*std(Sig,corrected=false), Logx::Real=exp(1)) N = length(Sig) (N>10) ? nothing : error("Sig: must be a numeric vector with >10 samples") (m > 0) ? nothing : error("m: must be an integer > 0") (tau > 0) ? nothing : error("tau: must be an integer > 0") (r>=0) ? nothing : error("r: must be a positive value") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Counter = 1*(abs.(Sig .- transpose(Sig)) .<= r) M = Int.([m*ones(N-m*tau); repeat(collect(m-1:-1:1),inner=tau)]) Ap = zeros(m+1) Phi = zeros(m+2) for n = 1:N-tau ix = findall(Counter[n, :] .== 1) for k = 1:M[n] ix = ix[(ix .+ (k*tau)) .<= N] p1 = repeat(transpose(Sig[n:tau: n+(tau*k)]), length(ix)) p2 = Sig[ix .+ transpose(collect(0:tau:(k*tau)))] ix = ix[findall(maximum(abs.(p1 - p2),dims=2) .<= r)] Counter[n, ix] .+= 1 end end #Phi[1] = log(Logx, N)/N Phi[2] = mean(log.(Logx, sum(Counter.>0,dims=2)/N)) Ap[1] = Phi[1] - Phi[2] for k = 0:m-1 ai = sum(Counter.>k+1,dims=2)/(N-(k+1)*tau) bi = sum(Counter.>k,dims=2)/(N-(k*tau)) ai = ai[ai.>0] bi = bi[bi.>0] Phi[k+3] = sum(log.(Logx,ai))/(N-(k+1)*tau) Ap[k+2] = sum(log.(Logx,bi))/(N-(k*tau)) - Phi[k+3] end return Ap, Phi end end """Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub"""
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
3602
module _AttnEn export AttnEn using StatsBase: Histogram, fit """ Av4, (Hxx,Hnn,Hxn,Hnx) = AttnEn(Sig) Returns the attention entropy (`Av4`) calculated as the average of the sub-entropies (`Hxx`,`Hxn`,`Hnn`,`Hnx`) estimated from the data sequence (`Sig`) using a base-2 logarithm. Av4, (Hxx, Hnn, Hxn, Hnx) = AttnEn(Sig::AbstractArray{T,1} where T<:Real; Logx::Real=2) Returns the attention entropy (`Av4`) and the sub-entropies (`Hxx`,`Hnn`,`Hxn`,`Hnx`) from the data sequence (`Sig`) where, Hxx: entropy of local-maxima intervals Hnn: entropy of local minima intervals Hxn: entropy of intervals between local maxima and subsequent minima Hnx: entropy of intervals between local minima and subsequent maxima # Arguments: `Logx` - Logarithm base, a positive scalar (Enter 0 for natural logarithm) See also `EnofEn`, `SpecEn`, `XSpecEn`, `PermEn`, `MSEn` # References: [1] Jiawei Yang, et al., "Classification of Interbeat Interval Time-series Using Attention Entropy." IEEE Transactions on Affective Computing (2020) """ function AttnEn(Sig::AbstractArray{T,1} where T<:Real; Logx::Real=2) (Logx == 0) ? Logx = exp(1) : nothing N = size(Sig,1) (N > 10) ? nothing : error("Sig: must be a numeric vector") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Xmax = PkFind(Sig) Xmin = PkFind(-Sig) Txx = diff(Xmax) Tnn = diff(Xmin) Temp = diff(sort(vcat(Xmax, Xmin))) if isempty(Xmax) error("No local maxima found!") elseif isempty(Xmin) error("No local minima found!") end (Xmax[1]<Xmin[1]) ? (Txn = Temp[1:2:end]; Tnx = Temp[2:2:end]) : (Txn = Temp[2:2:end]; Tnx = Temp[1:2:end]) Edges = -0.5:N Pnx = fit(Histogram,Tnx,Edges).weights Pnn = fit(Histogram,Tnn,Edges).weights Pxx = fit(Histogram,Txx,Edges).weights Pxn = fit(Histogram,Txn,Edges).weights Pnx = Pnx[Pnx.!=0]/size(Tnx,1) Pxn = Pxn[Pxn.!=0]/size(Txn,1) Pnn = Pnn[Pnn.!=0]/size(Tnn,1) Pxx = Pxx[Pxx.!=0]/size(Txx,1) Hxx = -sum(Pxx.*(log.(Logx,Pxx))) Hxn = -sum(Pxn.*(log.(Logx,Pxn))) Hnx = -sum(Pnx.*(log.(Logx,Pnx))) Hnn = -sum(Pnn.*(log.(Logx,Pnn))) Av4 = (Hnn + Hxx + Hxn + Hnx)/4 return Av4, (Hxx,Hnn,Hxn,Hnx) end function PkFind(X) Nx = size(X,1) Indx = zeros(Int,Nx); for n = 2:Nx-1 if X[n-1]< X[n] > X[n+1] Indx[n] = n elseif X[n-1] < X[n] == X[n+1] k = 1 while (n+k)<Nx && X[n] == X[n+k] k +=1 end if X[n] > X[n+k] Indx[n] = n + floor((k-1)/2) end end end Indx = Indx[Indx.!==0] return Indx end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
3401
module _BubbEn export BubbEn using GroupSlices """ Bubb, H = BubbEn(Sig) Returns the bubble entropy (`Bubb`) and the conditional Rényi entropy (`H`) estimates of dimension m = 2 from the data sequence (`Sig`) using the default parameters: embedding dimension = 2, time delay = 1, logarithm = natural Bubb, H = BubbEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, Logx::Real=exp(1)) Returns the bubble entropy (`Bubb`) estimate of the data sequence (`Sig`) using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, an integer > 1 \n BubbEn returns estimates for each dimension [2,...,m] `tau` - Time Delay, a positive integer \n `Logx` - Logarithm base, a positive scalar \n # See also `PhasEn`, `MSEn` # References: [1] George Manis, M.D. Aktaruzzaman and Roberto Sassi, "Bubble entropy: An entropy almost free of parameters." IEEE Transactions on Biomedical Engineering 64.11 (2017): 2711-2718. """ function BubbEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, Logx::Real=exp(1)) N = size(Sig,1) (N > 10) ? nothing : error("Sig: must be a numeric vector") (m > 1) ? nothing : error("m: must be an integer > 1") (tau >0) ? nothing : error("tau: must be an integer > 0") (Logx>0) ? nothing : error("Logx: must be a positive scalar > 0") Sx = zeros(N,m+1) H = zeros(m+1) Sx[:,1] = Sig for k = 2:m+1 Sx[1:N-(k-1)*tau,k] = Sig[1+(k-1)*tau:N] Swapx = BubbSort(Sx[1:N-(k-1)*tau,1:k]) Locs = getindex.(indexin(Swapx, unique(Swapx))) Temp = unique(Locs) p = zeros(size(Temp,1)) for n in Temp p[n] = sum(Locs.==n); end p ./= (N-(k-1)*tau) H[k] = -log(Logx, sum(p.^2)) if round(sum(p),digits=6) != 1 @warn("Potential error in detected swap number") end end Bubb = diff(H)./log.(Logx, (2:m+1)./(0:m-1)) Bubb = Bubb[2:end] return Bubb, H end function BubbSort(Data) x,N2 = size(Data) swaps = zeros(Int, x) for y = 1:x t = 1 while t <= N2-1 for kk = 1:N2-t if Data[y,kk] > Data[y,kk+1] temp = Data[y,kk] Data[y,kk] = Data[y,kk+1] Data[y,kk+1] = temp swaps[y] = swaps[y] + 1 end end t = t + 1; end end bsorted = Data; return swaps # bsorted end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
3876
module _CoSiEn export CoSiEn using Statistics: std, mean, median using LinearAlgebra: Diagonal, UpperTriangular """ CoSi, Bm = CoSiEn(Sig) Returns the cosine similarity entropy (`CoSi`) and the corresponding global probabilities estimated from the data sequence (`Sig`) using the default parameters: embedding dimension = 2, time delay = 1, angular threshold = .1, logarithm = base 2, CoSi, Bm = CoSiEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Real=.1, Logx::Real=2, Norm::Int=0) Returns the cosine similarity entropy (`CoSi`) estimated from the data sequence (`Sig`) using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, an integer > 1 \n `tau` - Time Delay, a positive integer \n `r` - Angular threshold, a value in range [0 < r < 1] \n `Logx` - Logarithm base, a positive scalar (enter 0 for natural log) \n `Norm` - Normalisation of `Sig`, one of the following integers: \n [0] no normalisation - default [1] normalises `Sig` by removing median(`Sig`) [2] normalises `Sig` by removing mean(`Sig`) [3] normalises `Sig` w.r.t. SD(`Sig`) [4] normalises `Sig` values to range [-1 1] # See also `PhasEn`, `SlopEn`, `GridEn`, `MSEn`, `cMSEn` # References: [1] Theerasak Chanwimalueang and Danilo Mandic, "Cosine similarity entropy: Self-correlation-based complexity analysis of dynamical systems." Entropy 19.12 (2017): 652. """ function CoSiEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Real=.1, Logx::Real=2, Norm::Int=0) Logx == 0 ? Logx = exp(1) : nothing N = size(Sig,1) (N > 10) ? nothing : error("Sig: must be a numeric vector") (m > 1) ? nothing : error("m: must be an integer > 1") (tau>0) ? nothing : error("tau: must be an integer > 0") (0<r<1) ? nothing : error("r: must be a scalar in range [0 1]") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") (Norm in collect(0:4)) ? nothing : error("Norm: must be an integer in range [0 4]") if Norm == 1 Xi = Sig .- median(Sig); elseif Norm == 2 Xi = Sig .- mean(Sig); elseif Norm == 3 Xi = (Sig .- mean(Sig))/std(Sig,corrected=false) elseif Norm == 4 Xi = (2*(Sig .- minimum(Sig))/(maximum(Sig)-minimum(Sig))) .- 1; else Xi = Sig; end Nx = N-((m-1)*tau); Zm = zeros(Nx,m); for n = 1:m Zm[:,n] = Xi[(n-1)*tau+1:Nx+(n-1)*tau] end Num = Zm*transpose(Zm); Mag = sqrt.(sum(Diagonal(Num),dims=1))[:] Den = Mag*transpose(Mag) AngDis = round.(acos.(round.(Num./Den,digits=8))/pi,digits=6) if maximum(imag.(AngDis)) < (10^-5) Bm = (sum(UpperTriangular(AngDis .< r))-Nx)/(Nx*(Nx-1)/2) else Bm = (sum(UpperTriangular(real.(AngDis) .< r))-Nx)/(Nx*(Nx-1)/2) @warn("Complex values ignored.") end if Bm == 1 || Bm == 0 CoSi = NaN else CoSi = -(Bm*log(Logx, Bm)) - ((1-Bm)*log(Logx, 1-Bm)) end return CoSi, Bm end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
4165
module _CondEn export CondEn using Statistics: std, mean using StatsBase: Histogram, fit """ Cond, SEw, SEz = CondEn(Sig) Returns the corrected conditional entropy estimates (`Cond`) and the corresponding Shannon entropies (m: `SEw`, m+1: `SEz`) for m = [1,2] estimated from the data sequence (`Sig`) using the default parameters: embedding dimension = 2, time delay = 1, symbols = 6, logarithm = natural, normalisation = false *Note: CondEn(m=1) returns the Shannon entropy of `Sig`.* Cond, SEw, SEz = CondEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, c::Int=6, Logx::Real=exp(1), Norm::Bool=false) Returns the corrected conditional entropy estimates (`Cond`) from the data sequence (`Sig`) using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, an integer > 1 \n `tau` - Time Delay, a positive integer \n `c` - # of symbols, an integer > 1 \n `Logx` - Logarithm base, a positive scalar \n `Norm` - Normalisation of CondEn value: \n [false] no normalisation - default [true] normalises w.r.t Shannon entropy of data sequence `Sig` # See also `XCondEn`, `MSEn`, `PermEn`, `DistEn`, `XPermEn` # References: [1] Alberto Porta, et al., "Measuring regularity by means of a corrected conditional entropy in sympathetic outflow." Biological cybernetics 78.1 (1998): 71-78. """ function CondEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, c::Int=6, Logx::Real=exp(1), Norm::Bool=false) (size(Sig)[1] > 10) ? nothing : error("Sig: must be a numeric vector") (m > 1) ? nothing : error("m: must be an integer > 1") (tau > 0) ? nothing : error("tau: must be an integer > 0") (Logx > 0) ? nothing : error("Logx: must be a positive number > 0") (c > 1) ? nothing : error("c: must be an integer > 1") Edges = range(minimum(Sig),maximum(Sig),length=c+1) Sx = map(x -> sum(Edges[1:c].<=x), Sig) N = size(Sx)[1] SEw = zeros(m-1) SEz = zeros(m-1) Prcm = zeros(m-1) Xi = zeros(N,m) Xi[:,m] = Sx for k = 1:m-1 Nx = N-(k*tau) Xi[1:Nx,end-k] = Sx[(k*tau)+1:N] Wi = Xi[1:Nx,m-k+1:m] * (c.^collect(k-1:-1:0)) # Maybe dot notation here??? Zi = Xi[1:Nx,m-k:m] * (c.^collect(k:-1:0)) Pw = fit(Histogram, Wi, minimum(Wi)-.5:maximum(Wi)+.5).weights Pz = fit(Histogram, Zi, minimum(Zi)-.5:maximum(Zi)+.5).weights Prcm[k] = sum(Pw.==1)/Nx if sum(Pw)!= Nx || sum(Pz)!= Nx @warn("Potential error estimating probabilities.") end Pw = Pw[Pw.!=0]; Pw /= N; Pz = Pz[Pz.!=0]; Pz /= N; SEw[k] = -transpose(Pw)*log.(Logx, Pw) SEz[k] = -transpose(Pz)*log.(Logx, Pz) end Temp = fit(Histogram,Sx,.5:c+.5).weights/N; Temp = Temp[Temp.!=0] S1 = -transpose(Temp)*log.(Logx, Temp) Cond = SEz - SEw + Prcm*S1; Cond = vcat(S1, Cond); if Norm Cond = Cond/S1; end return Cond, SEw, SEz end end #= Sig = (Sig.-mean(Sig))./std(Sig,corrected=false); Edges = range(minimum(Sig),maximum(Sig),length=c+1) #Edges[1] -= .1; Edges[end] += .1 Sx = map(x -> searchsortedfirst(Edges,x), Sig) .- 1 Sx[Sx.==0] .= 1 =# """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
7118
module _DispEn export DispEn using Clustering: kmeans, assignments using Statistics: std, mean using StatsFuns: normcdf """ Dispx, RDE = DispEn(Sig) Returns the dispersion entropy (`Dispx`) and the reverse dispersion entropy (`RDE`) estimated from the data sequence (`Sig`) using the default parameters: embedding dimension = 2, time delay = 1, symbols = 3, logarithm = natural, data transform = normalised cumulative density function (ncdf) Dispx, RDE = DispEn(Sig::AbstractArray{T,1} where T<:Real; c::Int=3, m::Int=2, tau::Int=1, Typex::String="ncdf", Logx::Real=exp(1), Fluct::Bool=false, Norm::Bool=false, rho::Real=1) Returns the dispersion entropy (`Dispx`) and the reverse dispersion entropy (`RDE`) estimated from the data sequence (`Sig`) using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, a positive integer\n `tau` - Time Delay, a positive integer\n `c` - Number of symbols, an integer > 1\n `Typex` - Type of data-to-symbolic sequence transform, one of the following: {`"linear", "kmeans" ,"ncdf", "finesort", "equal"`}\n See the EntropyHub guide for more info on these transforms.\n `Logx` - Logarithm base, a positive scalar\n `Fluct` - When Fluct == true, DispEn returns the fluctuation-based Dispersion entropy. [default: false]\n `Norm` - Normalisation of Dispx and RDE value: [false] no normalisation - default [true] normalises w.r.t number of possible dispersion patterns (c^m or (2c -1)^m-1 if Fluct == true).\n `rho` - *If Typex == 'finesort', rho is the tuning parameter* (default: 1)\n # See also `PermEn`, `SyDyEn`, `MSEn` # References: [1] Mostafa Rostaghi and Hamed Azami, "Dispersion entropy: A measure for time-series analysis." IEEE Signal Processing Letters 23.5 (2016): 610-614. [2] Hamed Azami and Javier Escudero, "Amplitude-and fluctuation-based dispersion entropy." Entropy 20.3 (2018): 210. [3] Li Yuxing, Xiang Gao and Long Wang, "Reverse dispersion entropy: A new complexity measure for sensor signal." Sensors 19.23 (2019): 5203. [4] Wenlong Fu, et al., "Fault diagnosis for rolling bearings based on fine-sorted dispersion entropy and SVM optimized with mutation SCA-PSO." Entropy 21.4 (2019): 404. """ function DispEn(Sig::AbstractArray{T,1} where T<:Real; c::Int=3, m::Int=2, tau::Int=1, Typex::String="ncdf", Logx::Real=exp(1), Fluct::Bool=false, Norm::Bool=false, rho::Real=1) N = size(Sig)[1] (N > 10) ? nothing : error("Sig: must be a numeric vector") (c > 1) ? nothing : error("c: must be an integer > 1") (m > 0) ? nothing : error("m: must be an integer > 0") (tau > 0) ? nothing : error("tau: must be an integer > 0") (lowercase(Typex) in ["linear", "kmeans", "ncdf", "finesort","equal"]) ? nothing : error("Typex: must be one of the following strings - 'linear','kmeans','ncdf','finesort','equal'") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") (rho>=0) ? nothing : error("rho: must be a positive scalar.") if lowercase(Typex) == "linear" Edges = range(minimum(Sig),maximum(Sig),length=c+1) Zi = map(x -> sum(Edges[1:c].<=x), Sig) elseif lowercase(Typex) == "kmeans" Temp = kmeans(transpose(Sig), c; maxiter=200) Zx = assignments(Temp) Clux = Temp.centers xx = sortperm(Clux[:]); Zi = zeros(N) for k = 1:c Zi[Zx.==xx[k]] .= k; end elseif lowercase(Typex) == "ncdf" Zx = normcdf.(mean(Sig),std(Sig,corrected=false),Sig); #= Zi= map(x -> searchsortedfirst(range(0,1,length=c+1),x), Zx) .- 1 Zi[Zi.==0] .= 1 =# Zi = map(x -> sum(range(0,1,length=c+1)[1:c].<=x), Zx) elseif lowercase(Typex) == "finesort" Zx = normcdf.(mean(Sig),std(Sig,corrected=false),Sig) Zi = map(x -> sum(range(0,1,length=c+1)[1:c].<=x), Zx) Ym = zeros(N-(m-1)*tau, m) for n = 1:m Ym[:,n] = Zx[1+(n-1)*tau:N-((m-n)*tau)] end Yi = floor.(maximum(abs.(diff(Ym,dims=2)),dims=2)./(rho*std(abs.(diff(Sig)),corrected=false))) elseif lowercase(Typex) == "equal" ix = sortperm(Sig,alg=MergeSort); xx = Int.(round.(range(0,N,length=c+1))) Zi = zeros(N) for k = 1:c Zi[ix[xx[k]+1:xx[k+1]]] .= k end end Zm = zeros(N-(m-1)*tau, m) for n = 1:m Zm[:,n] = Zi[1+(n-1)*tau:N-((m-n)*tau)] end (lowercase(Typex) == "finesort") ? Zm = hcat(Zm, Yi) : nothing if Fluct Zm = diff(Zm,dims=2) (m < 2) ? @warn(["Fluctuation-based Dispersion Entropy is undefined for m = 1. "... "An embedding dimension (m) > 1 should be used."]) : nothing end T = unique(Zm,dims=1) Nx = size(T)[1] Counter = zeros(Nx) for n = 1:Nx Counter[n] = sum(all(Zm .- transpose(T[n,:]) .==0, dims=2)) end Ppi = Counter[Counter.!= 0]/size(Zm)[1] if Fluct RDE = sum((Ppi .- (1/((2*c - 1)^(m-1)))).^2) else RDE = sum((Ppi .- (1/(c^m))).^2) end #RDE = sum(Ppi.^2) - (1/Nx) if round(sum(Ppi)) != 1 @warn("Potential Error calculating probabilities") end Dispx = -sum(Ppi.*log.(Logx, Ppi)) if Norm #Dispx = Dispx/log(Logx, Nx) #RDE = RDE/(1 - (1/Nx)) if Fluct Dispx = Dispx/(log(Logx, (2*c - 1)^(m-1))) RDE = RDE/(1 - (1/((2*c - 1)^(m-1)))) else Dispx = Dispx/(log(Logx, c^m)) RDE = RDE/(1 - (1/(c^m))) end end return Dispx, RDE end end #= for n = 1:m Zm[:,n] = Zi[1+(n-1)*tau:N-((m-n)*tau)] T[:,n] = repeat(1:c,inner=(c^(n-1),1),outer=(c^(m-n),1)) end if lowercase(Typex) == "finesort" Zm = hcat(Zm, Yi) temp = sort(unique(Yi)) T = repeat(T,outer=(length(temp),1)) T = hcat(T,repeat(temp,inner=Nx)) Counter = repeat(Counter,outer=length(Yi)) Nx = length(Counter) end if Fluct Zm = diff(Zm,dims=2) T = unique(Zm,dims=1) Nx = size(T,1) Counter = zeros(Nx) end =# """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
7052
module _DispEn2D export DispEn2D using Clustering: kmeans, assignments using Statistics: std, mean using StatsFuns: normcdf """ Disp2D, RDE = DispEn2D(Mat) Returns the bidimensional dispersion entropy estimate (`Disp2D`) and reverse bidimensional dispersion entropy (`RDE`) estimated for the data matrix (`Mat`) using the default parameters: time delay = 1, symbols = 3, logarithm = natural, data transform = normalised cumulative density function (`'ncdf'`), logarithm = natural, template matrix size = [floor(H/10) floor(W/10)], (where H and W represent the height (rows) and width (columns) of the data matrix `Mat`) \n ** The minimum number of rows and columns of Mat must be > 10.** Disp2D, RDE = DispEn2D(Mat::AbstractArray{T,2} where T<:Real; m::Union{Int,Tuple{Int,Int}}=floor.(Int, size(Mat)./10), tau::Int=1, c::Int=3, Typex::String="ncdf", Logx::Real=exp(1), Norm::Bool=false, Lock::Bool=true) Returns the bidimensional dispersion entropy (`Disp2D`) and reverse bidimensional distribution entropy (`RDE`) estimate for the data matrix (`Mat`) using the specified 'keyword' arguments: # Arguments: `m` - Template submatrix dimensions, an integer scalar (i.e. the same height and width) or a two-element tuple of integers [height, width] with a minimum value > 1. [default: [floor(H/10) floor(W/10)]] \n `tau` - Time Delay, a positive integer [default: 1] \n `c` - Number of symbols, an integer > 1 `Typex` - Type of symbolic mapping transform, one of the following: {`linear`, `kmeans`, `ncdf`, `equal`} See the `EntropyHub Guide` for more info on these transforms. `Logx` - Logarithm base, a positive scalar [default: natural]\n ** enter 0 for natural logarithm.**\n `Norm` - Normalisation of `Disp2D` value, a boolean: - [false] no normalisation - default - [true] normalises w.r.t number of possible dispersion patterns. `Lock` - By default, DispEn2D only permits matrices with a maximum size of 128 x 128 to prevent memory errors when storing data on RAM. e.g. For Mat = [200 x 200], m = 3, and tau = 1, DispEn2D creates a vector of 753049836 elements. To enable matrices greater than [128 x 128] elements, set `Lock` to false. [default: 'true'] `WARNING: unlocking the permitted matrix size may cause your Julia IDE to crash.` # See also `DispEn`, `DistEn2D`, `SampEn2D`, `FuzzEn2D`, `MSEn` # References: [1] Hamed Azami, et al., "Two-dimensional dispersion entropy: An information-theoretic method for irregularity analysis of images." Signal Processing: Image Communication, 75 (2019): 178-187. """ function DispEn2D(Mat::AbstractArray{T,2} where T<:Real; m::Union{Int,Tuple{Int,Int}}=floor.(Int, size(Mat)./10), tau::Int=1, c::Int=3, Typex::String="ncdf", Logx::Real=exp(1), Norm::Bool=false, Lock::Bool=true) Logx == 0 ? Logx = exp(1) : nothing NL, NW = size(Mat) ((NL > 128 || NW > 128) && Lock) ? error("To prevent memory errors, matrix width & length must have <= 128 elements. To estimatDispEn2D for the current matrix ($NL,$NW) change Lock to 'false'. Caution: unlocking the safe matrix size may cause the Julia IDE to crash.") : nothing length(m)==1 ? (mL = m; mW = m) : (mL = m[1]; mW = m[2]) (NL > 10 && NW > 10) ? nothing : error("Number of rows and columns in Mat must be > 10") (minimum(m) > 1) ? nothing : error("m: must be an integer > 1, or 2-element integer tuple w/ values > 1") (tau > 0) ? nothing : error("tau: must be an integer > 0") (c > 1) ? nothing : error("c: must be an integer > 1") (lowercase(Typex) in ["linear", "kmeans", "ncdf", "equal"]) ? nothing : error("Typex: must be one of the following strings - 'linear','kmeans','ncdf','equal'") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") if lowercase(Typex) == "linear" Edges = range(minimum(Mat),maximum(Mat),length=c+1) Zi = map(x -> sum(Edges[1:c].<=x), Mat) elseif lowercase(Typex) == "kmeans" Temp = kmeans(transpose(Mat[:]), c; maxiter=200) Zx = assignments(Temp) Clux = Temp.centers xx = sortperm(Clux[:]); Zi = zeros(Int,length(Mat)) for k = 1:c Zi[Zx.==xx[k]] .= k; end Zi = reshape(Zi,size(Mat)) elseif lowercase(Typex) == "ncdf" Zx = normcdf.(mean(Mat),std(Mat,corrected=false),Mat); Zi = map(x -> sum(range(0,1,length=c+1)[1:c].<=x), Zx); elseif lowercase(Typex) == "equal" ix = sortperm(Mat'[:],alg=MergeSort); xx = Int.(round.(range(0,length(Mat),length=c+1))) Zi = zeros(Int, length(Mat)) for k = 1:c Zi[ix[xx[k]+1:xx[k+1]]] .= k end Zi = reshape(Zi,size(Mat'))' end NL = NL - (mL-1)*tau NW = NW - (mW-1)*tau X = zeros(Int,NL*NW,mL*mW) p = 0 for k = 1:NL for n = 1:NW p += 1 X[p,:] = Zi[k:tau:(mL-1)*tau+k,n:tau:(mW-1)*tau+n][:] end end p != NL*NW ? @warn("Potential error with submatrix division.") : nothing T = unique(X,dims=1) Nx = size(T)[1] Counter = zeros(Nx) for n = 1:Nx Counter[n] = sum(all(X .- transpose(T[n,:]) .==0, dims=2)) end Ppi = Counter[Counter.!= 0]/size(X)[1] big(c)^(mL*mW) > 10^16 ? error("RDE cannot be estimated with c = $c and a submatrix of size $mL x $mW. Required floating point precision exceeds 10^16. Consider reducing the template submatrix size (m) or the number of symbols (c).") : nothing #RDE = sum(Ppi.^2) - (1/Nx) RDE = sum((Ppi .- (1/(c^(mL*mW)))).^2); if round(sum(Ppi),digits=4) != 1 @warn("Potential Error calculating probabilities") end Disp2D = -sum(Ppi.*log.(Logx, Ppi)) if Norm Disp2D = Disp2D/log(Logx, c^(mL*mW)) RDE = RDE./(1 - (1/(c^(mL*mW)))) end return Disp2D, RDE end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
4833
module _DistEn export DistEn using StatsBase: Histogram, fit, skewness """ Dist, Ppi = DistEn(Sig) Returns the distribution entropy estimate (`Dist`) and the corresponding distribution probabilities (`Ppi`) estimated from the data sequence (`Sig`) using the default parameters: embedding dimension = 2, time delay = 1, binning method = 'Sturges', logarithm = base 2, normalisation = w.r.t # of histogram bins Dist, Ppi = DistEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, Bins::Union{Int,String}="Sturges", Logx::Real=2, Norm::Bool=true) Returns the distribution entropy estimate (`Dist`) estimated from the data sequence (`Sig`) using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, a positive integer \n `tau` - Time Delay, a positive integer \n `Bins` - Histogram bin selection method for distance distribution, one of the following: \n an integer > 1 indicating the number of bins, or one of the following strings {'sturges','sqrt','rice','doanes'} [default: 'sturges'] `Logx` - Logarithm base, a positive scalar (enter 0 for natural log) \n `Norm` - Normalisation of DistEn value: \n [false] no normalisation. [true] normalises w.r.t # of histogram bins - default # See also `XDistEn`, `DistEn2D`, `MSEn`, `K2En` # References: [1] Li, Peng, et al., "Assessing the complexity of short-term heartbeat interval series by distribution entropy." Medical & biological engineering & computing 53.1 (2015): 77-87. """ function DistEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, Bins::Union{Int,String}="Sturges", Logx::Real=2, Norm::Bool=true) Logx == 0 ? Logx = exp(1) : nothing N = size(Sig)[1] (N>10) ? nothing : error("Sig: must be a numeric vector") (m > 0) ? nothing : error("m: must be an integer > 0") (tau > 0) ? nothing : error("tau: must be an integer > 0") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") if typeof(Bins)<:Int (Bins>1) ? nothing : error("Bins: must be an integer > 1 (or name of binning method)") elseif typeof(Bins)<:String (lowercase(Bins) in ["sturges","sqrt","rice","doanes"]) ? nothing : error("Bins: must be one of the following strings 'sturges', 'sqrt', 'rice', 'doanes' (or an integer >1)") end Nx = size(Sig)[1] - ((m-1)*tau) Zm = zeros(Nx,m) for n = 1:m Zm[:,n] = Sig[(n-1)*tau + 1:Nx+(n-1)*tau] end DistMat = zeros(Int(Nx*(Nx-1)/2)) for k = 1:Nx-1 Ix = [Int((k-1)*(Nx - k/2)+1), Int(k*(Nx-((k+1)/2)))] DistMat[Ix[1]:Ix[2]] = maximum(abs.(transpose(Zm[k,:]) .- Zm[k+1:end,:]),dims=2) # DistMat[Ix[1]:Ix[2]] = maximum(abs.(repeat(Zm[k,:],outer=(1,Nx-k)) .- Zm[k+1:end,:]'),dims=2) end Ny = size(DistMat)[1] if eltype(Bins)<:Char if lowercase(Bins) == "sturges" Bx = ceil(log2(Ny) + 1) elseif lowercase(Bins) == "rice" Bx = ceil(2*(Ny^(1/3))) elseif lowercase(Bins) == "sqrt" Bx = ceil(sqrt(Ny)) elseif lowercase(Bins) == "doanes" sigma = sqrt(6*(Ny-2)/((Ny+1)*(Ny+3))) Bx = ceil(1+log2(Ny)+log2(1+abs(skewness(DistMat)/sigma))) else error("Please enter a valid binning method") end else Bx = Bins end By = collect(range(minimum(DistMat),maximum(DistMat),length=Int(Bx+1))) By[end] += 1; By[1]-= 1 Ppi = fit(Histogram, DistMat, By).weights/Ny if round(sum(Ppi),digits=6) != 1 @warn("Potential error estimating probabilities (p = $(sum(Ppi))") Ppi = Ppi[Ppi.!=0] elseif any(Ppi.==0) print("Note: $(sum(Ppi.==0))/$(length(Ppi)) bins were empty \n") Ppi = Ppi[Ppi.!=0] end Dist = -sum(Ppi.*log.(Logx, Ppi)) if Norm Dist = Dist/(log(Logx, Bx)); end return Dist, Ppi end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
7157
module _DistEn2D export DistEn2D using StatsBase: fit, Histogram, skewness """ Dist2D = DistEn2D(Mat) Returns the bidimensional distribution entropy estimate (`Dist2D`) estimated for the data matrix (`Mat`) using the default parameters: time delay = 1, histogram binning method = "sturges", logarithm = natural, template matrix size = [floor(H/10) floor(W/10)], (where H and W represent the height (rows) and width (columns) of the data matrix `Mat`) \n ** The minimum number of rows and columns of Mat must be > 10.** Dist2D = DistEn2D(Mat::AbstractArray{T,2} where T<:Real; m::Union{Int,Tuple{Int,Int}}=floor.(Int, size(Mat)./10), tau::Int=1, Bins::Union{Int,String}="Sturges", Logx::Real=2, Norm::Int=2, Lock::Bool=true) Returns the bidimensional distribution entropy (`Dist2D`) estimate for the data matrix (`Mat`) using the specified 'keyword' arguments: # Arguments: `m` - Template submatrix dimensions, an integer scalar (i.e. the same height and width) or a two-element tuple of integers [height, width] with a minimum value > 1. [default: [floor(H/10) floor(W/10)]] \n `tau` - Time Delay, a positive integer [default: 1] \n `Bins` - Histogram bin selection method for distance distribution, an integer > 1 indicating the number of bins, or one of the following strings {`"sturges", "sqrt", "rice", "doanes"``} [default: 'sturges'] \n `Logx` - Logarithm base, a positive scalar [default: natural]\n ** enter 0 for natural logarithm.**\n `Norm` - Normalisation of `Dist2D` value, one of the following integers: [0] no normalisation. [1] normalises values of data matrix (`Mat`) to range [0 1]. [2] normalises values of data matrix (`Mat`) to range [0 1], and normalises the distribution entropy value (`Dist2D`) w.r.t the number of histogram bins. [default] [3] normalises the distribution entropy value w.r.t the number of histogram bins, without normalising data matrix values. \n `Lock` - By default, DistEn2D only permits matrices with a maximum size of 128 x 128 to prevent memory errors when storing data on RAM. e.g. For Mat = [200 x 200], m = 3, and tau = 1, DistEn2D creates a vector of 753049836 elements. To enable matrices greater than [128 x 128] elements, set `Lock` to false. [default: 'true'] `WARNING: unlocking the permitted matrix size may cause your Julia IDE to crash.` # See also `DistEn`, `XDistEn`, `SampEn2D`, `FuzzEn2D`, `MSEn` # References: [1] Hamed Azami, Javier Escudero and Anne Humeau-Heurtier, "Bidimensional distribution entropy to analyze the irregularity of small-sized textures." IEEE Signal Processing Letters 24.9 (2017): 1338-1342. """ function DistEn2D(Mat::AbstractArray{T,2} where T<:Real; m::Union{Int,Tuple{Int,Int}}=floor.(Int, size(Mat)./10), tau::Int=1, Bins::Union{Int,String}="Sturges", Logx::Real=2, Norm::Int=2, Lock::Bool=true) Logx == 0 ? Logx = exp(1) : nothing NL, NW = size(Mat) ((NL > 128 || NW > 128) && Lock) ? error("To prevent memory errors, matrix width & length must have <= 128 elements. To estimate DistEn2D for the current matrix ($NL,$NW) change Lock to 'false'. Caution: unlocking the safe matrix size may cause the Julia IDE to crash.") : nothing length(m)==1 ? (mL = m; mW = m) : (mL = m[1]; mW = m[2]) (NL > 10 && NW > 10) ? nothing : error("Number of rows and columns in Mat must be > 10") (minimum(m) > 1) ? nothing : error("m: must be an integer > 1") (tau >0) ? nothing : error("tau: must be an integer > 0") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") if typeof(Bins)<:Int (Bins>1) ? nothing : error("Bins: must be an integer > 1 (or name of binning method)") elseif typeof(Bins)<:String (lowercase(Bins) in ["sturges","sqrt","rice","doanes"]) ? nothing : error("Bins: must be one of the following strings 'sturges', 'sqrt', 'rice', 'doanes' (or an integer >1)") end (Norm in [0, 1, 2, 3]) ? nothing : error("Norm: must be an integer in the range [0 3]") Norm in [1, 2] ? Mat = (Mat.-minimum(Mat))./maximum(Mat.-minimum(Mat)) : nothing NL = NL - (mL-1)*tau NW = NW - (mW-1)*tau X = zeros(mL,mW,NL*NW) p = 0 for k = 1:NL for n = 1:NW p += 1 X[:,:,p] = Mat[k:tau:(mL-1)*tau+k,n:tau:(mW-1)*tau+n] end end p = size(X,3) p != NL*NW ? @warn("Potential error with submatrix division.") : nothing Ny = Int(p*(p-1)/2) Ny > 300000000 ? @warn("Number of pairwise distance calculations is $Ny") : nothing Y = zeros(Ny) for k = 1:p-1 Ix = Int.([(k-1)*(p - k/2)+1, k*(p-((k+1)/2))]) Y[Ix[1]:Ix[2]] = maximum(abs.(X[:,:,k+1:end] .- X[:,:,k]),dims=(1,2)) end if eltype(Bins)<:Char if lowercase(Bins) == "sturges" Bx = ceil(log2(Ny) + 1) elseif lowercase(Bins) == "rice" Bx = ceil(2*(Ny^(1/3))) elseif lowercase(Bins) == "sqrt" Bx = ceil(sqrt(Ny)) elseif lowercase(Bins) == "doanes" sigma = sqrt(6*(Ny-2)/((Ny+1)*(Ny+3))) Bx = ceil(1+log2(Ny)+log2(1+abs(skewness(convert(Array{Float64,1},Y))/sigma))) else error("Please enter a valid binning method") end else Bx = Bins end By = collect(range(minimum(Y),maximum(Y),length=Int(Bx+1))) By[end] += 1; By[1] -= 1 Ppi = fit(Histogram, Y[:], By).weights/Ny if round(sum(Ppi),digits=6) != 1 @warn("Potential error estimating probabilities (p = $(sum(Ppi)))") Ppi = Ppi[Ppi.!=0] elseif any(Ppi.==0) print("Note: $(sum(Ppi.==0))/$(length(Ppi)) bins were empty \n") Ppi = Ppi[Ppi.!=0] end Dist2D = -sum(Ppi.*log.(Logx, Ppi)) Norm >= 2 ? Dist2D /= (log(Logx, Bx)) : nothing return Dist2D end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """ #= Y = [] for k = 1:p-1 append!(Y,maximum(abs.(X[:,:,k+1:end] .- X[:,:,k]),dims=(1,2))) end =#
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
4317
module _DivEn export DivEn using StatsBase: Histogram, fit """ Div, CDEn, Bm = DivEn(Sig) Returns the diversity entropy (`Div`), the cumulative diversity entropy (`CDEn`), and the corresponding probabilities (`Bm`) estimated from the data sequence (`Sig`) using the default parameters: embedding dimension = 2, time delay = 1, #bins = 5, logarithm = natural, Div, CDEn, Bm = DivEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Int=5, Logx::Real=exp(1)) Returns the diversity entropy (`Div`) estimated from the data sequence (`Sig`) using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, an integer > 1 \n `tau` - Time Delay, a positive integer \n `r` - Histogram bins #: either \n * an integer [1 < `r`] representing the number of bins * a list/numpy array of 3 or more increasing values in range [-1 1] representing the bin edges including the rightmost edge.\n `Logx` - Logarithm base, a positive scalar (Enter 0 for natural logarithm) # See also `CoSiEn`, `PhasEn`, `SlopEn`, `GridEn`, `MSEn` # References: [1] X. Wang, S. Si and Y. Li, "Multiscale Diversity Entropy: A Novel Dynamical Measure for Fault Diagnosis of Rotating Machinery," IEEE Transactions on Industrial Informatics, vol. 17, no. 8, pp. 5419-5429, Aug. 2021 [2] Y. Wang, M. Liu, Y. Guo, F. Shu, C. Chen and W. Chen, "Cumulative Diversity Pattern Entropy (CDEn): A High-Performance, Almost-Parameter-Free Complexity Estimator for Nonstationary Time Series," IEEE Transactions on Industrial Informatics vol. 19, no. 9, pp. 9642-9653, Sept. 2023 """ function DivEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Union{Int, Vector, StepRangeLen, Tuple}=5, Logx::Real=exp(1)) Logx == 0 ? Logx = exp(1) : nothing N = size(Sig,1) (N > 10) ? nothing : error("Sig: must be a numeric vector") (m > 1) ? nothing : error("m: must be an integer > 1") (tau>0) ? nothing : error("tau: must be an integer > 0") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") r isa Union{Vector, StepRangeLen, Tuple} ? r = collect(r) : nothing if r isa Int (r<1) ? error("r: must be an int > 1 or a vector of 3 or more increasing values in range [-1 1]") : r = collect(LinRange(-1,1,r+1)) elseif r isa Vector (r isa Vector && length(r) > 2 && minimum(r) >= -1 && maximum(r)<= 1 && minimum(diff(r))>0) ? nothing : error("r: must be an int > 1 or a vector of 3 or more increasing values in range [-1 1]") else error("r: must be an int > 1 or a vector of 3 or more increasing values in range [-1 1]") end Nx = N - (m-1)*tau Zm = zeros((Nx,m)) for n = 1:m Zm[:,n] = Sig[1 + (n-1)*tau:Nx+((n-1)*tau)] end Num = sum(Zm[1:end-1,:].*Zm[2:end,:],dims=2) Den = sqrt.(sum(Zm[2:end,:].^2,dims=2)).*sqrt.(sum(Zm[1:end-1,:].^2,dims=2)) Di = (Num./Den)[:] Bm = fit(Histogram, Di, r).weights Bm = Bm[Bm.>0]/sum(Bm) round(sum(Bm),digits = 6) != 1.0 ? (@warn "Warning: Potential error is probability estimation! Sum(Pi) == " round(sum(Bm),digits=6)) : nothing r = length(r)-1 Pj = 1 .- cumsum(Bm) Pj = (Pj./sum(Pj))[1:end-1] CDEn = -sum(Pj.*log.(Pj)./log(Logx))./(log(r)/log(Logx)) Div = -sum(Bm.*log.(Bm)./log(Logx))./(log(r)/log(Logx)) return Div, CDEn, Bm end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
3465
module _EnofEn export EnofEn using StatsBase: countmap, Histogram, fit """ EoE, AvEn, S2 = EnofEn(Sig) Returns the entropy of entropy (`EoE`), the average Shannon entropy (`AvEn`), and the number of levels (`S2`) across all windows estimated from the data sequence (`Sig`) using the default parameters: window length (samples) = 10, slices = 10, logarithm = natural, heartbeat interval range (xmin, xmax) = (min(Sig), max(Sig)) EoE, AvEn, S2 = EnofEn(Sig::AbstractArray{T,1} where T<:Real; tau::Int=10, S::Int=10, Xrange::Tuple{Real,REal}, Logx::Real=exp(1)) Returns the entropy of entropy (`EoE`) estimated from the data sequence (`Sig`) using the specified 'keyword' arguments: # Arguments: `tau` - Window length, an integer > 1 \n `S` - Number of slices (s1,s2), a two-element tuple of integers > 2 \n `Xrange` - The min and max heartbeat interval, a two-element tuple where X[1] <= X[2]\n `Logx` - Logarithm base, a positive scalar \n # See also `SampEn`, `MSEn`, `ApEn` # References: [1] Chang Francis Hsu, et al., "Entropy of entropy: Measurement of dynamical complexity for biological systems." Entropy 19.10 (2017): 550. """ function EnofEn(Sig::AbstractArray{T,1} where T<:Real; tau::Int=10, S::Int=10, Xrange::Tuple{Real,Real}=(minimum(Sig),maximum(Sig)), Logx::Real=exp(1)) N = size(Sig,1) (N > 10) ? nothing : error("Sig: must be a numeric vector") (tau > 1 && tau < length(Sig)) ? nothing : error("tau: must be an integer > 1") (S > 1) ? nothing : error("S: must be an integer > 1") (length(Xrange)==2 && (Xrange[1]<=Xrange[2])) ? nothing : error("Xrange: must be a two-element numeric tuple where Xrange[1]<Xrange[2]") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Wn = Int(floor(N/tau)) Wj = transpose(reshape(Sig[1:Wn*tau],tau,Wn)) Yj = zeros(Wn) #Edges = collect(range(minimum(Sig),maximum(Sig),length=(S[1]+1))) Edges = collect(range(Xrange[1],Xrange[2],length=(S+1))) Edges[1] -= .1; Edges[end] += .1 for n = 1:Wn Temp = fit(Histogram,Wj[n,:],Edges).weights/tau Temp = Temp[Temp.>0] Yj[n] = -sum(Temp.*log.(Logx, Temp)) end AvEn = sum(Yj)/Wn #Edges = collect(range(minimum(Yj),maximum(Yj),length=(S[2]+1))) #Edges[1] -= .1; Edges[end] += .1 #Pjl = fit(Histogram,Yj,Edges).weights/Wn #Pjl = Pjl[Pjl.>0] Pjl = collect(values(countmap(round.(Yj,digits=12))))./Wn S2 = length(Pjl) if round(sum(Pjl),digits=5) != 1 @warn("Possible error estimating probabilities") end EoE = -sum(Pjl.*log.(Logx, Pjl)) return EoE, AvEn, S2 end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
4802
module _EspEn2D export EspEn2D """ Esp2D, = EspEn2D(Mat) Returns the bidimensional Espinosa entropy estimate (`Esp2D`) estimated for the data matrix (`Mat`) using the default parameters: time delay = 1, tolerance threshold = 20, percentage similarity = 0.7 logarithm = natural, matrix template size = [floor(H/10) floor(W/10)], (where H and W represent the height (rows) and width (columns) of the data matrix `Mat`) ** The minimum number of rows and columns of `Mat` must be > 10. Esp2D = EspEn2D(Mat::AbstractArray{T,2} where T<:Real; m::Union{Int,Tuple{Int,Int}}=floor.(Int, size(Mat)./10), tau::Int=1, r::Real=20, ps::Float=.7, Logx::Real=exp(1), Lock::Bool=true) Returns the bidimensional Espinosa entropy (`Esp2D`) estimates for the data matrix (`Mat`) using the specified 'keyword' arguments: # Arguments: `m` - Template submatrix dimensions, an integer scalar (i.e. the same height and width) or a two-element vector of integers [height, width] with a minimum value > 1. (default: [floor(H/10) floor(W/10)]) \n `tau` - Time Delay, a positive integer (default: 1) \n `r` - Tolerance threshold, a positive scalar (default: 20) \n `ps` - Percentage similarity, a value in range [0 1], (default: 0.7) \n `Logx` - Logarithm base, a positive scalar (default: natural) \n `Lock` - By default, EspEn2D only permits matrices with a maximum size of 128 x 128 to prevent memory errors when storing data on RAM. e.g. For Mat = [200 x 200], m = 3, and tau = 1, EspEn2D creates a vector of 753049836 elements. To enable matrices greater than [128 x 128] elements, set `Lock` to false. (default: true) \n `WARNING: unlocking the permitted matrix size may cause your Julia IDE to crash.` # See also `SampEn2D`, `FuzzEn2D`, `DispEn2D`, `DistEn2D`, `PermEn2D` # References: [1] Ricardo Espinosa, et al., "Two-dimensional EspEn: A New Approach to Analyze Image Texture by Irregularity." Entropy, 23:1261 (2021) """ function EspEn2D(Mat::AbstractArray{T,2} where T<:Real; m::Union{Int,Tuple{Int,Int}}=floor.(Int, size(Mat)./10), tau::Int=1, r::Real=20, ps::Real=0.7, Logx::Real=exp(1), Lock::Bool=true) NL, NW = size(Mat) ((NL > 128 || NW > 128) && Lock) ? error("To prevent memory errors, matrix width & length must have <= 128 elements. To estimate EspEn2D for the current matrix ($NL,$NW) change Lock to 'false'. Caution: unlocking the safe matrix size may cause the Julia IDE to crash.") : nothing length(m)==1 ? (mL = m; mW = m) : (mL = m[1]; mW = m[2]) (NL > 10 && NW > 10) ? nothing : error("Number of rows and columns in Mat must be > 10") (minimum(m)>1) ? nothing : error("m: must be an integer > 1, or a 2 element tuple of integer values > 1") (tau > 0) ? nothing : error("tau: must be an integer > 0") (r >= 0) ? nothing : error("r: must be a positive value") ((ps >= 0) && (ps <= 1)) ? nothing : error("ps: must be a value in range [0 1]") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") NL = NL - (mL-1)*tau NW = NW - (mW-1)*tau X = zeros(mL,mW,NL*NW) p = 0 for k = 1:NL for n = 1:NW p += 1 X[:,:,p] = Mat[k:tau:(mL-1)*tau+k,n:tau:(mW-1)*tau+n] end end p = size(X,3) p != NL*NW ? @warn("Potential error with submatrix division.") : nothing Ny = p*(p-1)/2 Ny > 300000000 ? @warn("Number of pairwise distance calculations is $Ny") : nothing Cij = -ones(p-1,p-1) for k = 1:p-1 Temp = abs.(X[:,:,k+1:p] .- X[:,:,k]) .<= r Cij[1:(end-k+1),k] = sum(Temp,dims=(1,2)) end Dm = sum((Cij[:]/(mL*mW)).>=ps)/(p*(p-1)/2) Esp2D = -log(Logx, Dm) return Esp2D end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
3942
module _ExampleData export ExampleData using DelimitedFiles using HTTP """ Data = ExampleData(SigName::String) Imports sample data time series with specific properties that are commonly used as benchmarks for assessing the performance of various entropy methods. The datasets returned by ExampleData() are used in the examples provided in documentation on www.EntropyHub.xyz and elsewhere. ***Note*** ExampleData() requires an internet connection to download and import the required datasets! `Data`is the sample dataset imported corresponding to the string input `SigName` which can be one of the following string: # Arguments: `SigName` - \n `uniform` - uniformly distributed random number sequence in range [0 1], N = 5000 `randintegers` - randomly distributed integer sequence in range [1 8], N = 4096 `gaussian` - normally distributed number sequence [mean: 0, SD: 1], N = 5000 `henon` - X and Y components of the Henon attractor [alpha: 1.4, beta: .3, Xo = 0, Yo = 0], N = 4500 `lorenz` - X, Y, and Z components of the Lorenz attractor [sigma: 10, beta: 8/3, rho: 28, Xo = 10, Yo = 20, Zo = 10], N = 5917 `chirp` - chirp signal (f0 = .01, t1 = 4000, f1 = .025), N = 5000 `uniform2` - two uniformly distributed random number sequences in range [0,1], N = 4096 `gaussian2` - two normally distributed number sequences [mean: 0, SD: 1], N = 3000 `randintegers2` - two uniformly distributed pseudorandom integer sequences in range [1 8], N = 3000 `uniform_Mat` - matrix of uniformly distributed random numbers in range [0 1], N = 50 x 50 `gaussian_Mat` - matrix of normally distributed numbers [mean: 0, SD: 1], N = 60 x 120 `randintegers_Mat` - matrix of randomly distributed integers in range [1 8], N = 88 x 88 `mandelbrot_Mat` - matrix representing a Mandelbrot fractal image with values in range [0 255], N = 92 x 115 `entropyhub_Mat` - matrix representing the EntropyHub logo with values in range [0 255], N = 127 x 95 For further info on these graining procedures see the `EntropyHub guide <https://github.com/MattWillFlood/EntropyHub/blob/main/EntropyHub%20Guide.pdf>`_. """ function ExampleData(SigName) Chk = ["uniform","uniform2","randintegers2","randintegers", "henon","chirp","gaussian","gaussian2","lorenz", "uniform_Mat", "gaussian_Mat", "entropyhub_Mat", "mandelbrot_Mat","randintegers_Mat"] SigName in Chk ? nothing : error("SigName must be one of the following:\n$Chk") url = "https://raw.githubusercontent.com/MattWillFlood/EntropyHub/main/ExampleData/" * SigName * ".txt" Temp = HTTP.get(url).body if (SigName in ["henon","lorenz"]) || (SigName[end] == '2') || (SigName[end-2:end] == "Mat") X = readdlm(Temp, skipstart=2) else X = readdlm(Temp, skipstart=2); size(X)[1] < size(X)[2] ? X = X[1,:] : X = X[:,1] end return X end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
10094
module _FuzzEn export FuzzEn using Statistics: mean, std using LinearAlgebra: UpperTriangular, I, inv """ Fuzz, Ps1, Ps2 = FuzzEn(Sig) Returns the fuzzy entropy estimates `Fuzz` and the average fuzzy distances (`m`:Ps1, `m+1`:Ps2) for `m` = [1,2] estimated from the data sequence `Sig` using the default parameters: embedding dimension = 2, time delay = 1, fuzzy function (`Fx`) = "default", fuzzy function parameters (`r`) = [0.2, 2], logarithm = natural Fuzz, Ps1, Ps2 = FuzzEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Union{Real,Tuple{Real,Real}}=(.2,2), Fx::String="default", Logx::Real=exp(1)) Returns the fuzzy entropy estimates `Fuzz` for dimensions = [1,...,`m`] estimated for the data sequence `Sig` using the specified keyword arguments: # Arguments: `m` - Embedding Dimension, a positive integer [default: 2]\n `tau` - Time Delay, a positive integer [default: 1]\n `Fx` - Fuzzy function name, one of the following: {`"sigmoid", "modsampen", "default", "gudermannian",` `"bell", "triangular", "trapezoidal1", "trapezoidal2",` `"z_shaped", "gaussian", "constgaussian"`}\n `r` - Fuzzy function parameters, a 1 element scalar or a 2 element tuple of positive values. The `r` parameters for each fuzzy function are defined as follows: [default: [.2 2]]\n default: r(1) = divisor of the exponential argument r(2) = argument exponent (pre-division) sigmoid: r(1) = divisor of the exponential argument r(2) = value subtracted from argument (pre-division) modsampen: r(1) = divisor of the exponential argument r(2) = value subtracted from argument (pre-division) gudermannian: r = a scalar whose value is the numerator of argument to gudermannian function: GD(x) = atan(tanh(`r`/x)) triangular: r = a scalar whose value is the threshold (corner point) of the triangular function. trapezoidal1: r = a scalar whose value corresponds to the upper (2r) and lower (r) corner points of the trapezoid. trapezoidal2: r(1) = a value corresponding to the upper corner point of the trapezoid. r(2) = a value corresponding to the lower corner point of the trapezoid. z_shaped: r = a scalar whose value corresponds to the upper (2r) and lower (r) corner points of the z-shape. bell: r(1) = divisor of the distance value r(2) = exponent of generalized bell-shaped function gaussian: r = a scalar whose value scales the slope of the Gaussian curve. constgaussian: r = a scalar whose value defines the lower threshod and shape of the Gaussian curve. [DEPRICATED] linear: r = an integer value. When r = 0, the argument of the exponential function is normalised between [0 1]. When r = 1, the minimuum value of the exponential argument is set to 0. \n `Logx` - Logarithm base, a positive scalar [default: natural] ## For further information on keyword arguments, see the EntropyHub guide. # See also `SampEn`, `ApEn`, `PermEn`, `DispEn`, `XFuzzEn`, `FuzzEn2D`, `MSEn` # References: [1] Weiting Chen, et al. "Characterization of surface EMG signal based on fuzzy entropy." IEEE Transactions on neural systems and rehabilitation engineering 15.2 (2007): 266-272. [2] Hong-Bo Xie, Wei-Xing He, and Hui Liu "Measuring time series regularity using nonlinear similarity-based sample entropy." Physics Letters A 372.48 (2008): 7140-7146. [3] Hamed Azami, et al. "Fuzzy Entropy Metrics for the Analysis of Biomedical Signals: Assessment and Comparison" IEEE Access 7 (2019): 104833-104847 """ function FuzzEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Union{Real,Tuple{Real,Real}}=(.2,2.0), Fx::String="default", Logx::Real=exp(1)) N = size(Sig)[1] (N>10) ? nothing : error("Sig: must be a numeric vector") (m > 0) ? nothing : error("m: must be an integer > 0") (tau > 0) ? nothing : error("tau: must be an integer > 0") (minimum(r)>=0 && length(r)<=2) ? nothing : error("r: must be a scalar or 2 element tuple of positive values") (lowercase(Fx) in ["default","sigmoid","modsampen","gudermannian","bell", "z_shaped", "triangular", "trapezoidal1","trapezoidal2","gaussian","constgaussian"]) ? nothing : error("Fx: must be one of the following strings - 'default', 'sigmoid', 'modsampen', 'gudermannian', 'bell', 'z_shaped', 'triangular', 'trapezoidal1','trapezoidal2','gaussian','constgaussian'") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") if length(r) == 2 && lowercase(Fx)=="linear" r = 0; print("Multiple values for r entered. Default value (0) used.\n") elseif length(r) == 2 && lowercase(Fx)=="gudermannian" r = r[1] print("Multiple values for r entered. First value used.\n") end m += 1 Fun = getfield(_FuzzEn,Symbol(lowercase(Fx))) Sx = zeros(N,m) for k = 1:m Sx[1:N-(k-1)*tau,k] = Sig[1+(k-1)*tau:end] end Ps1 = zeros(m) Ps2 = zeros(m-1) Ps1[1] = .5 for k = 2:m N1 = N - k*tau; N2 = N - (k-1)*tau; T2 = Sx[1:N2,1:k] .- mean(Sx[1:N2,1:k],dims=2) d2 = zeros(N2-1,N2-1) for p = 1:N2-1 Mu2 = maximum(abs.(repeat(transpose(T2[p,:]),N2-p) - T2[p+1:end,:]),dims=2) d2[p,p:end] = Fun(Mu2[:],r) end d1 = d2[1:N1-1,1:N1-1] Ps1[k] = sum(d1)/(N1*(N1-1)) Ps2[k-1] = sum(d2)/(N2*(N2-1)) end Fuzz = (log.(Logx, Ps1[1:end-1]) - log.(Logx,Ps2)) return Fuzz, Ps1, Ps2 end function sigmoid(x,r) if length(r) == 1 error("When Fx = 'Sigmoid', r must be a two-element tuple.") end y = inv.(1 .+ exp.((x.-r[2])/r[1])) return y end function modsampen(x,r) if length(r) == 1 error("When Fx = 'Modsampen', r must be a two-element tuple.") end y = inv.(1 .+ exp.((x.-r[2])/r[1])) return y end function default(x,r) if length(r) == 1 error("When Fx = 'Default', r must be a two-element tuple.") end y = exp.(-(x.^r[2])/r[1]) return y end function gudermannian(x,r) if r <= 0 error("When Fx = 'Gudermannian', r must be a scalar > 0.") end y = atan.(tanh.(r[1]./x)) y ./= maximum(y) return y end """ function linear(x,r) if r == 0 && length(x)>1 y = exp.(-(x .- minimum(x))/(maximum(x)-minimum(x))) elseif r == 1 y = exp.(-(x .- minimum(x))) elseif r == 0 && length(x)==1 y = [0] else error("When Fx = 'Linear', r must be 0 or 1.") end return y end """ function triangular(x,r) length(r)==1 ? nothing : error("When Fx = 'Triangular', r must be a scalar > 0.") y = 1 .- (x./r) y[x .> r] .= 0 return y end function trapezoidal1(x, r) length(r)==1 ? nothing : error("When Fx = 'Trapezoidal1', r must be a scalar > 0.") y = zeros(length(x)) y[x .<= r*2] = 2 .- (x[x .<= r*2]./r) y[x .<= r] .= 1 return y end function trapezoidal2(x, r) (r isa Tuple) && (length(r)==2) ? nothing : error("When Fx = 'Trapezoidal2', r must be a two-element tuple.") y = zeros(length(x)) y[x .<= maximum(r)] = 1 .- (x[x .<= maximum(r)] .- minimum(r))./(maximum(r)-minimum(r)) y[x .<= minimum(r)] .= 1 return y end function z_shaped(x, r) length(r)==1 ? nothing : error("When Fx = 'Z_shaped', r must be a scalar > 0.") y = zeros(length(x)) y[x .<= 2*r] = 2*(((x[x .<= 2*r] .- 2*r)./r).^2) y[x .<= 1.5*r] = 1 .- (2*(((x[x .<= 1.5*r] .- r)/r).^2)) y[x .<= r] .= 1 return y end function bell(x, r) (r isa Tuple) && length(r)==2 ? nothing : error("When Fx = 'Bell', r must be a two-element tuple.") y = inv.(1 .+ abs.(x./r[1]).^(2*r[2])) return y end function gaussian(x, r) length(r)==1 ? nothing : error("When Fx = 'Gaussian', r must be a scalar > 0.") y = exp.(-((x.^2)./(2*(r.^2)))) return y end function constgaussian(x, r) length(r)==1 ? nothing : error("When Fx = 'ConstGaussian', r must be a scalar > 0.") y = ones(length(x)) y[x .> r] = exp.(-log(2)*((x[x .> r] .- r)./r).^2) return y end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
11651
module _FuzzEn2D export FuzzEn2D using Statistics: mean, std """ Fuzz2D = FuzzEn2D(Mat) Returns the bidimensional fuzzy entropy estimate (`Fuzz2D`) estimated for the data matrix (`Mat`) using the default parameters: time delay = 1, fuzzy function (Fx) = 'default', fuzzy function parameters (r) = [0.2, 2], logarithm = natural, template matrix size = [floor(H/10) floor(W/10)], (where H and W represent the height and width of the data matrix 'Mat') \n ** The minimum dimension size of Mat must be > 10.** Fuzz2D = FuzzEn2D(Mat::AbstractArray{T,2} where T<:Real; m::Union{Int,Tuple{Int,Int}}=floor.(Int, size(Mat)./10), tau::Int=1, r::Union{Real,Tuple{Real,Real}}=(.2*std(Mat, corrected=false),2), Fx::String="default", Logx::Real=exp(1), Lock::Bool=true) Returns the bidimensional fuzzy entropy (`Fuzz2D`) estimates for the data matrix (`Mat`) using the specified 'keyword' arguments: # Arguments: `m` - Template submatrix dimensions, an integer scalar (i.e. the same height and width) or a two-element vector of integers [height, width] with a minimum value > 1. (default: [floor(H/10) floor(W/10)]) \n `tau` - Time Delay, a positive integer (default: 1) \n `Fx` - Fuzzy function name, one of the following: {`"sigmoid", "modsampen", "default", "gudermannian",` `"bell", "triangular", "trapezoidal1", "trapezoidal2",` `"z_shaped", "gaussian", "constgaussian"`}\n `r` - Fuzzy function parameters, a 1 element scalar or a 2 element vector of positive values. The 'r' parameters for each fuzzy function are defined as follows:\n sigmoid: r(1) = divisor of the exponential argument r(2) = value subtracted from argument (pre-division) modsampen: r(1) = divisor of the exponential argument r(2) = value subtracted from argument (pre-division) default: r (1) = divisor of the exponential argument r(2) = argument exponent (pre-division) gudermannian: r = a scalar whose value is the numerator of argument to gudermannian function: GD(x) = atan(tanh(r/x)) triangular: r = a scalar whose value is the threshold (corner point) of the triangular function. trapezoidal1: r = a scalar whose value corresponds to the upper (2r) and lower (r) corner points of the trapezoid. trapezoidal2: r(1) = a value corresponding to the upper corner point of the trapezoid. r(2) = a value corresponding to the lower corner point of the trapezoid. z_shaped: r = a scalar whose value corresponds to the upper (2r) and lower (r) corner points of the z-shape. bell: r(1) = divisor of the distance value r(2) = exponent of generalized bell-shaped function gaussian: r = a scalar whose value scales the slope of the Gaussian curve. constgaussian: r = a scalar whose value defines the lower threshod and shape of the Gaussian curve. [DEPRICATED] linear: r = an integer value. When r = 0, the argument of the exponential function is normalised between [0 1]. When r = 1, the minimuum value of the exponential argument is set to 0. \n `Logx` - Logarithm base, a positive scalar (default: natural)\n `Lock` - By default, FuzzEn2D only permits matrices with a maximum size of 128 x 128 to prevent memory errors when storing data on RAM. e.g. For Mat = [200 x 200], m = 3, and tau = 1, FuzzEn2D creates a vector of 753049836 elements. To enable matrices greater than [128 x 128] elements, set `Lock` to false. (default: true)\n ` WARNING: unlocking the permitted matrix size may cause your Julia IDE to crash.` \n # See also `SampEn2D`, `FuzzEn`, `XFuzzEn` # References: [1] Luiz Fernando Segato Dos Santos, et al., "Multidimensional and fuzzy sample entropy (SampEnMF) for quantifying H&E histological images of colorectal cancer." Computers in biology and medicine 103 (2018): 148-160. [2] Mirvana Hilal and Anne Humeau-Heurtier, "Bidimensional fuzzy entropy: Principle analysis and biomedical applications." 41st Annual International Conference of the IEEE (EMBC) Society 2019. [3] Hamed Azami, et al. "Fuzzy Entropy Metrics for the Analysis of Biomedical Signals: Assessment and Comparison" IEEE Access 7 (2019): 104833-104847 """ function FuzzEn2D(Mat::AbstractArray{T,2} where T<:Real; m::Union{Int,Tuple{Int,Int}}=floor.(Int, size(Mat)./10), tau::Int=1, r::Union{Real,Tuple{Real,Real}}=(.2*std(Mat,corrected=false),2), Fx::String="default", Logx::Real=exp(1), Lock::Bool=true) NL, NW = size(Mat) ((NL > 128 || NW > 128) && Lock) ? error("To prevent memory errors, matrix width & length must have <= 128 elements. To estimate FuzzEn2D for the current matrix ($NL,$NW) change Lock to 'false'. Caution: unlocking the safe matrix size may cause the Julia IDE to crash.") : nothing length(m)==1 ? (mL = m; mW = m) : (mL = m[1]; mW = m[2]) (NL > 10 && NW > 10) ? nothing : error("Number of rows and columns in Mat must be > 10") (minimum(m)>1) ? nothing : error("m: must be an integer > 1, or a 2 element integer tuple > 1") (tau > 0) ? nothing : error("tau: must be an integer > 0") (minimum(r)>=0) ? nothing : error("r: must be a positive value") #error("r: must be 2 element tuple of positive values") (lowercase(Fx) in ["default","sigmoid","modsampen","gudermannian","bell", "z_shaped", "triangular", "trapezoidal1","trapezoidal2","gaussian","constgaussian"]) ? nothing : error("Fx: must be one of the following strings - 'default', 'sigmoid', 'modsampen', 'gudermannian', 'bell', 'z_shaped', 'triangular', 'trapezoidal1','trapezoidal2','gaussian','constgaussian'") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") if length(r) == 2 && lowercase(Fx)=="linear" r = 0; print("Multiple values for r entered. Default value (0) used.\n") elseif length(r) == 2 && lowercase(Fx)=="gudermannian" r = r[1] print("Multiple values for r entered. First value used.\n") end Fun = getfield(_FuzzEn2D,Symbol(lowercase(Fx))) NL = NL - mL*tau NW = NW - mW*tau X1 = zeros(mL,mW,NL*NW) X2 = zeros(mL+1,mW+1,NL*NW) p = 0; for k = 1:NL for n = 1:NW p += 1 Temp2 = Mat[k:tau:(mL)*tau+k,n:tau:(mW)*tau+n] Temp1 = Temp2[1:end-1,1:end-1] X1[:,:,p] = Temp1 .- mean(Temp1) X2[:,:,p] = Temp2 .- mean(Temp2) end end p = size(X1,3) p != NL*NW ? @warn("Potential error with submatrix division.") : nothing Ny = p*(p-1)/2; Ny > 300000000 ? @warn("Number of pairwise distance calculations is $Ny") : nothing Y1 = zeros(p-1) Y2 = zeros(p-1) for k = 1:p-1 Temp1 = maximum(abs.(X1[:,:,k+1:end] .- X1[:,:,k]),dims=(1,2)) Y1[k] = sum(Fun(Temp1[:], r)) Temp2 = maximum(abs.(X2[:,:,k+1:end] .- X2[:,:,k]),dims=(1,2)) Y2[k] = sum(Fun(Temp2[:], r)) end Fuzz2D = -log(Logx, sum(Y2)/sum(Y1)) return Fuzz2D end function sigmoid(x,r) if length(r) == 1 error("When Fx = 'Sigmoid', r must be a two-element vector.") end y = inv.(1 .+ exp.((x.-r[2])/r[1])) return y end function modsampen(x,r) if length(r) == 1 error("When Fx = 'Modsampen', r must be a two-element vector.") end y = inv.(1 .+ exp.((x.-r[2])/r[1])) return y end function default(x,r) if length(r) == 1 error("When Fx = 'Default', r must be a two-element vector.") end y = exp.(-(x.^r[2])/r[1]) return y end function gudermannian(x,r) if r <= 0 error("When Fx = 'Gudermannian', r must be a scalar > 0.") end y = atan.(tanh.(r[1]./x)) y ./= maximum(y) return y end """ function linear(x,r) if r == 0 && length(x)>1 y = exp.(-(x .- minimum(x))/(maximum(x)-minimum(x))) elseif r == 1 y = exp.(-(x .- minimum(x))) elseif r == 0 && length(x)==1 y = [0] else error("When Fx = 'Linear', r must be 0 or 1.") end return y end """ function triangular(x,r) length(r)==1 ? nothing : error("When Fx = 'Triangular', r must be a scalar > 0.") y = 1 .- (x./r) y[x .> r] .= 0 return y end function trapezoidal1(x, r) length(r)==1 ? nothing : ("When Fx = 'Trapezoidal1', r must be a scalar > 0.") y = zeros(length(x)) y[x .<= r*2] = 2 .- (x[x .<= r*2]./r) y[x .<= r] .= 1 return y end function trapezoidal2(x, r) (r isa Tuple) && (length(r)==2) ? nothing : error("When Fx = 'Trapezoidal2', r must be a two-element tuple.") y = zeros(length(x)) y[x .<= maximum(r)] = 1 .- (x[x .<= maximum(r)] .- minimum(r))./(maximum(r)-minimum(r)) y[x .<= minimum(r)] .= 1 return y end function z_shaped(x, r) length(r)==1 ? nothing : error("When Fx = 'Z_shaped', r must be a scalar > 0.") y = zeros(length(x)) y[x .<= 2*r] .= 2*(((x[x .<= 2*r] .- 2*r)./r).^2) y[x .<= 1.5*r] .= 1 .- (2*(((x[x .<= 1.5*r] .- r)/r).^2)) y[x .<= r] .= 1 return y end function bell(x, r) (r isa Tuple) && length(r)==2 ? nothing : error("When Fx = 'Bell', r must be a two-element tuple.") y = inv.(1 .+ abs.(x./r[1]).^(2*r[2])) return y end function gaussian(x, r) length(r)==1 ? nothing : error("When Fx = 'Gaussian', r must be a scalar > 0.") y = exp.(-((x.^2)./(2*(r.^2)))) return y end function constgaussian(x, r) length(r)==1 ? nothing : error("When Fx = 'ConstGaussian', r must be a scalar > 0.") y = ones(length(x)) y[x .> r] = exp.(-log(2)*((x[x .> r] .- r)./r).^2) return y end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
5549
module _GridEn export GridEn using Plots using Plots.PlotMeasures using StatsBase: Histogram, fit """ GDE, GDR, _ = GridEn(Sig) Returns the gridded distribution entropy (`GDE`) and the gridded distribution rate (`GDR`) estimated from the data sequence (`Sig`) using the default parameters: grid coarse-grain = 3, time delay = 1, logarithm = base 2 GDE, GDR, PIx, GIx, SIx, AIx = GridEn(Sig) In addition to GDE and GDR, GridEn returns the following indices estimated for the data sequence (`Sig`) using the default parameters: [`PIx`] - Percentage of points below the line of identity (LI) [`GIx`] - Proportion of point distances above the LI [`SIx`] - Ratio of phase angles (w.r.t. LI) of the points above the LI [`AIx`] - Ratio of the cumulative area of sectors of points above the LI GDE, GDR, ..., = GridEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=3, tau::Int=1, Logx::Real=exp(1), Plotx::Bool=false) Returns the gridded distribution entropy (`GDE`) estimated from the data sequence (`Sig`) using the specified 'keyword' arguments: # Arguments: `m` - Grid coarse-grain (m x m sectors), an integer > 1 \n `tau` - Time Delay, a positive integer \n `Logx` - Logarithm base, a positive scalar \n `Plotx` - When Plotx == true, returns gridded Poicaré plot and a bivariate histogram of the grid point distribution (default: false) \n # See also `PhasEn`, `CoSiEn`, `SlopEn`, `BubbEn`, `MSEn` # References: [1] Chang Yan, et al., "Novel gridded descriptors of poincaré plot for analyzing heartbeat interval time-series." Computers in biology and medicine 109 (2019): 280-289. [2] Chang Yan, et al. "Area asymmetry of heart rate variability signal." Biomedical engineering online 16.1 (2017): 1-14. [3] Alberto Porta, et al., "Temporal asymmetries of short-term heart period variability are linked to autonomic regulation." American Journal of Physiology-Regulatory, Integrative and Comparative Physiology 295.2 (2008): R550-R557. [4] C.K. Karmakar, A.H. Khandoker and M. Palaniswami, "Phase asymmetry of heart rate variability signal." Physiological measurement 36.2 (2015): 303. """ function GridEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=3, tau::Int=1, Logx::Real=exp(1), Plotx::Bool=false) N = size(Sig,1) (N > 10) ? nothing : error("Sig: must be a numeric vector") (m > 1) ? nothing : error("m: must be an integer > 1") (tau >0) ? nothing : error("tau: must be an integer > 0") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Sig_n = (Sig.-minimum(Sig))/(maximum(Sig)-minimum(Sig)) Temp = hcat(Sig_n[1:end-tau], Sig_n[1+tau:end]) Edges = collect(0:1/m:1); Edges[end] = 1.1 N = fit(Histogram,(Temp[:,1],Temp[:,2]),(Edges,Edges)).weights Pj = reverse(transpose(N),dims=1)/size(Temp,1); Ppi = Pj[Pj.>0]; if round(sum(Ppi),digits=4) != 1 @warn("Potential error of estimated probabilities: P = $(sum(Ppi))") end GDE = -sum(Ppi.*(log.(Ppi)/log(Logx))); GDR = sum(N.!=0)/(m*m); T2 = atand.(Temp[:,2]./Temp[:,1]) Dup = sum(abs.(diff(Temp[T2.>45,:],dims=2))) Dtot = sum(abs.(diff(Temp[T2.!=45,:],dims=2))) Sup = sum((T2[T2.>45].-45)) Stot = sum(abs.(T2[T2.!=45].-45)) Aup = sum(abs.((T2[T2.>45].-45).*sqrt.(sum(Temp[T2.>45,:].^2,dims=2)))) Atot = sum(abs.((T2[T2.!=45].-45).*sqrt.(sum(Temp[T2.!=45,:].^2,dims=2)))) PIx = 100*sum(T2.<45)/sum(T2.!=45) GIx = 100*Dup/Dtot SIx = 100*Sup/Stot AIx = 100*Aup/Atot if Plotx ntrvl = range(0,1,length=m+1) p1 = plot(Sig_n[1:end-tau],Sig_n[tau+1:end],seriestype =:scatter, c=:magenta, markerstrokecolor=:magenta, markersize = 2) plot!(hcat(ntrvl,ntrvl)',hcat(zeros(m+1),ones(m+1))',c=:cyan,lw=3) plot!(hcat(zeros(m+1),ones(m+1))',hcat(ntrvl,ntrvl)',c=:cyan,lw=3) plot!([0, 1],[0, 1],c=:black, legend=false, aspect_ratio=:equal, xlim = (0, 1), ylim = (0, 1), xticks=[0, 1], yticks=[0, 1], xlabel= "X ₙ" , ylabel="X ₙ₊ₜ") p2 = histogram2d(Temp[:,1],Temp[:,2], nbins=ntrvl, xticks=[0, 1], yticks=[0, 1], xlabel= "X ₙ" , ylabel="X ₙ₊ₜ", xlim = (0, 1), ylim = (0, 1), aspect_ratio=:equal, colorbar_entry=false, seriescolor=:cool,show_empty_bins=true) xx = plot(p1,p2,layout=(1,2),legend=false, framestyle=:grid, margin=7mm) display(xx) end return GDE, GDR, PIx, GIx, SIx, AIx end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
3694
module _IncrEn export IncrEn using Statistics: std """ Incr = IncrEn(Sig) Returns the increment entropy (`Incr`) estimate of the data sequence (`Sig`) using the default parameters: embedding dimension = 2, time delay = 1, quantifying resolution = 4, logarithm = base 2, Incr = IncrEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, R::Int=4, Logx::Real=2, Norm::Bool=false) Returns the increment entropy (`Incr`) estimate of the data sequence (`Sig`) using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, an integer > 1 \n `tau` - Time Delay, a positive integer \n `R` - Quantifying resolution, a positive scalar \n `Logx` - Logarithm base, a positive scalar (enter 0 for natural log) \n `Norm` - Normalisation of IncrEn value: \n [false] no normalisation - default [true] normalises w.r.t embedding dimension (m-1). # See also `PermEn`, `SyDyEn`, `MSEn` # References: [1] Xiaofeng Liu, et al., "Increment entropy as a measure of complexity for time series." Entropy 18.1 (2016): 22.1. *** "Correction on Liu, X.; Jiang, A.; Xu, N.; Xue, J. - Increment Entropy as a Measure of Complexity for Time Series, Entropy 2016, 18, 22." Entropy 18.4 (2016): 133. [2] Xiaofeng Liu, et al., "Appropriate use of the increment entropy for electrophysiological time series." Computers in biology and medicine 95 (2018): 13-23. """ function IncrEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, R::Int=4, Logx::Real=2, Norm::Bool=false) Logx == 0 ? Logx = exp(1) : nothing (size(Sig,1) > 10) ? nothing : error("Sig: must be a numeric vector") (m > 1) ? nothing : error("m: must be an integer > 1") (tau>0) ? nothing : error("tau: must be an integer > 0") (R > 0) ? nothing : error("R: must be a positive integer > 0") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Vi = diff(Sig) N = size(Vi,1)-((m-1)*tau) Vk = zeros(N,m) for k = 1:m Vk[:,k] = Vi[1+(k-1)*tau:N+(k-1)*tau] end Sk = sign.(Vk) Temp = std(Vk,dims=2)[:] Qk = min.(R, floor.((abs.(Vk)*R)./repeat(Temp,outer=(1,m)))) Qk[any(Temp.==0,dims=2), :] .= 0 #should that be all() Wk = Sk.*Qk Wk[Wk.==-0] .= 0 Px = unique(Wk,dims=1) Counter = zeros(Int,size(Px,1)); for k = 1:size(Px,1) Counter[k] = sum(all(Wk .- transpose(Px[k,:]) .==0 ,dims=2)) end Ppi = Counter/N if size(Px,1) > (2*R + 1)^m @warn("Error with probability estimation'") elseif round(sum(Ppi),digits=5) != 1 @warn("Error with probability estimation") end Incr = -sum(Ppi.*(log.(Logx, Ppi))) if Norm Incr = Incr/(m-1); end return Incr end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
2999
module _K2En export K2En using Statistics: std """ K2, Ci = K2En(Sig) Returns the Kolmogorov entropy estimates `K2` and the correlation integrals `Ci` for `m` = [1,2] estimated from the data sequence `Sig` using the default parameters: embedding dimension = 2, time delay = 1, r = 0.2*SD(`Sig`), logarithm = natural K2, Ci = K2En(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Real=0.2*std(Sig,corrected=false), Logx::Real=exp(1)) Returns the Kolmogorov entropy estimates `K2` for dimensions = [1,...,`m`] estimated from the data sequence `Sig` using the 'keyword' arguments: # Arguments: `m` - Embedding Dimension, a positive integer\n `tau` - Time Delay, a positive integer\n `r` - Radius, a positive scalar \n `Logx` - Logarithm base, a positive scalar\n # See also `DistEn`, `XK2En`, `MSEn` # References: [1] Peter Grassberger and Itamar Procaccia, "Estimation of the Kolmogorov entropy from a chaotic signal." Physical review A 28.4 (1983): 2591. [2] Lin Gao, Jue Wang and Longwei Chen "Event-related desynchronization and synchronization quantification in motor-related EEG by Kolmogorov entropy" J Neural Eng. 2013 Jun;10(3):03602 """ function K2En(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Real=0.2*std(Sig,corrected=false), Logx::Real=exp(1)) N = size(Sig)[1] (N>10) ? nothing : error("Sig: must be a numeric vector") (m > 0) ? nothing : error("m: must be an integer > 0") (tau > 0) ? nothing : error("tau: must be an integer > 0") (r>0) ? nothing : error("r: must be a positive scalar > 0") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") m = m+1 Zm = zeros(N,m) Ci = zeros(m) for n = 1:m N2 = N-(n-1)*tau Zm[1:N2,n] = Sig[(n-1)*tau + 1:N] Norm = Inf*ones(N2-1,N2-1) for k = 1:N2-1 Temp = repeat(transpose(Zm[k,1:n]),N2-k,1) - Zm[k+1:N2,1:n] Norm[k,k:N2-1] = sqrt.(sum(Temp.^2, dims=2)) end Ci[n] = 2*sum(Norm .< r)/(N2*(N2-1)) end K2 = log.(Logx, Ci[1:m-1]./Ci[2:m])/tau K2[isinf.(K2)] .= NaN return K2, Ci end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
13283
module _MSEn export MSEn, EMD using Statistics: std, mean, median, var using DataInterpolations: CubicSpline #using Dierckx: Spline1D using Plots using DSP: conv #=function __init__() @warn("\n\n Methodx option IMF (Intrinisic Mode Function) is not stable. Random or highly aperiodic signals may not decompose fully. Access to the IMFs decomposed by the empirical mode decomposition (EMD) function can be found by calling EntropyHub.EMD(`Sig`,`MaxIMFs`). A stable EMD function will be included in future releases.\n\n") end=# """ MSx, CI = MSEn(Sig, Mobj) Returns a vector of multiscale entropy values `MSx` and the complexity index `CI` of the data sequence `Sig` using the parameters specified by the multiscale object `Mobj` over 3 temporal scales with coarse- graining (default). MSx, CI = MSEn(Sig::AbstractArray{T,1} where T<:Real, Mobj::NamedTuple; Scales::Int=3, Methodx::String="coarse", RadNew::Int=0, Plotx::Bool=false) Returns a vector of multiscale entropy values `MSx` and the complexity index `CI` of the data sequence `Sig` using the parameters specified by the multiscale object `Mobj` and the following 'keyword' arguments: # Arguments: `Scales` - Number of temporal scales, an integer > 1 (default: 3) \n `Method` - Graining method, one of the following: {`coarse`,`modified`,`imf`,`timeshift`,`generalized`} [default = `coarse`] For further info on these graining procedures, see the EntropyHub guide. \n `RadNew` - Radius rescaling method, an integer in the range [1 4]. When the entropy specified by `Mobj` is `SampEn` or `ApEn`, RadNew allows the radius threshold to be updated at each time scale (Xt). If a radius value is specified by `Mobj` (`r`), this becomes the rescaling coefficient, otherwise it is set to 0.2 (default). The value of RadNew specifies one of the following methods:\n [1] Standard Deviation - r*std(Xt)\n [2] Variance - r*var(Xt) \n [3] Mean Absolute Deviation - r*mean_ad(Xt) \n [4] Median Absolute Deviation - r*med_ad(Xt)\n `Plotx` - When Plotx == true, returns a plot of the entropy value at each time scale (i.e. the multiscale entropy curve) [default: false]\n `For further info on these graining procedures see the EntropyHub guide.` # See also `MSobject`, `rMSEn`, `cMSEn`, `hMSEn`, `SampEn`, `ApEn`, `XMSEn` # References: [1] Madalena Costa, Ary Goldberger, and C-K. Peng, "Multiscale entropy analysis of complex physiologic time series." Physical review letters 89.6 (2002): 068102. [2] Vadim V. Nikulin, and Tom Brismar, "Comment on “Multiscale entropy analysis of complex physiologic time series”." Physical review letters 92.8 (2004): 089803. [3] Madalena Costa, Ary L. Goldberger, and C-K. Peng. "Costa, Goldberger, and Peng reply." Physical Review Letters 92.8 (2004): 089804. [4] Madalena Costa, Ary L. Goldberger and C-K. Peng, "Multiscale entropy analysis of biological signals." Physical review E 71.2 (2005): 021906. [5] Ranjit A. Thuraisingham and Georg A. Gottwald, "On multiscale entropy analysis for physiological data." Physica A: Statistical Mechanics and its Applications 366 (2006): 323-332. [6] Meng Hu and Hualou Liang, "Intrinsic mode entropy based on multivariate empirical mode decomposition and its application to neural data analysis." Cognitive neurodynamics 5.3 (2011): 277-284. [7] Anne Humeau-Heurtier "The multiscale entropy algorithm and its variants: A review." Entropy 17.5 (2015): 3110-3123. [8] Jianbo Gao, et al., "Multiscale entropy analysis of biological signals: a fundamental bi-scaling law." Frontiers in computational neuroscience 9 (2015): 64. [9] Paolo Castiglioni, et al., "Multiscale Sample Entropy of cardiovascular signals: Does the choice between fixed-or varying-tolerance among scales influence its evaluation and interpretation?." Entropy 19.11 (2017): 590. [10] Tuan D Pham, "Time-shift multiscale entropy analysis of physiological signals." Entropy 19.6 (2017): 257. [11] Hamed Azami and Javier Escudero, "Coarse-graining approaches in univariate multiscale sample and dispersion entropy." Entropy 20.2 (2018): 138. [12] Madalena Costa and Ary L. Goldberger, "Generalized multiscale entropy analysis: Application to quantifying the complex volatility of human heartbeat time series." Entropy 17.3 (2015): 1197-1203. """ function MSEn(Sig::AbstractArray{T,1} where T<:Real, Mobj::NamedTuple; Scales::Int=3, Methodx::String="coarse", RadNew::Int=0, Plotx::Bool=false) (size(Sig,1)>10) ? nothing : error("Sig: must be a numeric vector" ) (length(Mobj) >= 1) ? nothing : error("Mobj: must be a multiscale entropy object created with the function EntropyHub.MSobject") (Scales>1) ? nothing : error("Scales: must be an integer > 1") (lowercase(Methodx) in ["coarse","modified","imf","timeshift","generalized"]) ? nothing : error("Method: must be one of the following string names - 'coarse','modified','imf','timeshift','generalized'") (RadNew==0 || (RadNew in 1:4 && String(Symbol(Mobj.Func)) in ("SampEn","ApEn"))) ? nothing : error("RadNew: must be 0, or an integer in range [1 4] with entropy function 'SampEn' or 'ApEn'") lowercase(String(Symbol(Mobj.Func))[1]) == 'x' ? error("Base entropy estimator is a cross-entropy method. To perform multiscale CROSS-entropy estimation, use rXMSEn.") : nothing String(Symbol(Mobj.Func))=="SampEn" ? Mobj = merge(Mobj,(Vcp=false,)) : nothing if lowercase(Methodx)=="imf" Sig, _ = EMD(Sig,Scales-1) # sum(all(Sig.==0,dims=2))==0 ? nothing : Sig = Sig[all(Sig.!=0,dims=2),:] #Scales >= size(Sig,1) ? nothing : #@warn("Max number of IMF's decomposed from EMD is less than number of Scales. # MSEn evaluated over $(size(Sig,1)) scales instead of $Scales.") #Scales = size(Sig,1) sum(all(Sig.==0,dims=2))==0 ? Tp1 = ones(Int,size(Sig,1)) : Tp1 = vec(collect(all(Sig .!= 0, dims=2))); if !all(Bool.(Tp1)) || (size(Sig,1)<Scales) Sig = Sig[Bool.(Tp1),:] @warn("Max number of IMF's decomposed from EMD is less than number of Scales. MSEn evaluated over $(size(Sig,1)) scales instead of $Scales.") Scales = size(Sig,1); end end MSx = zeros(Scales) Args = NamedTuple{keys(Mobj)[2:end]}(Mobj) Func2 = getfield(_MSEn,Symbol(lowercase(Methodx))) if RadNew > 0 if RadNew == 1 Rnew = x -> std(x, corrected=false) elseif RadNew == 2 Rnew = x -> var(x, corrected=false) elseif RadNew == 3 Rnew = x -> mean(abs.(x .- mean(x))) elseif RadNew == 4 Rnew = x -> median(abs.(x .- median(x))) end if haskey(Mobj,:r) Cx = Mobj.r else Cy = ("Standard Deviation","Variance","Mean Abs Deviation", "Median Abs Deviation") @warn("No radius value provided in Mobj. Default set to 0.2*$(Cy[RadNew]) of each new time-series.") Cx = .2 end end for T = 1:Scales print(". ") Temp = Func2(Sig,T) if lowercase(Methodx) == "timeshift" Tempx = zeros(T) for k = 1:T RadNew > 0 ? Args = (Args..., r=Cx*Rnew(Temp[k,:])) : nothing Tempy = Mobj.Func(Temp[k,:]; Args...) typeof(Tempy)<:Tuple ? Tempx[k] = Tempy[1][end] : Tempx[k] = Tempy[end] # Tempx[k] = Tempy[end] end Temp2 = mean(Tempx) else RadNew > 0 ? Args = (Args..., r=Cx*Rnew(Temp[:])) : nothing Tempx = Mobj.Func(Temp[:]; Args...) typeof(Tempx)<:Tuple ? Temp2 = Tempx[1][end] : Temp2 = Tempx[end] #Temp2 = Tempx[1][end] end MSx[T] = Temp2 end CI = sum(MSx) print("\n") if any(isnan.(MSx)) println("Some entropy values may be undefined.") end if Plotx p1 = plot(1:Scales, MSx, c=RGB(8/255, 63/255, 77/255), lw=3) scatter!(1:Scales, MSx, markersize=6, c=RGB(1, 0, 1), xlabel = "Scale Factor", ylabel = "Entropy Value", guidefont = font(12, "arial", RGB(7/255, 54/255, 66/255)), tickfontsize = 10, tickfontfamily="arial", legend=false, title = "Multiscale $(Mobj.Func) ($(titlecase(Methodx))-graining method)", plot_titlefontsize=16, plot_titlefontcolor=RGB(7/255, 54/255, 66/255)) #ylim=(0,maximum(MSx)+.2), display(p1) end return MSx, CI end function coarse(Z,sx) Ns = Int(floor(size(Z,1)/sx)) Y = mean(reshape(Z[1:sx*Ns],sx,Ns),dims=1) return Y end function modified(Z,sx) #= Ns = size(Z,1) - sx + 1 Y = zeros(Ns) for k = 1:Ns Y[k] = mean(Z[k:k+sx-1]) end=# Y = (conv(Z,ones(Int,sx))/sx)[sx:end-sx+1] return Y end function imf(Z,sx) Y = sum(Z[1:sx,:],dims=1) return Y end function timeshift(Z,sx) Y = reshape(Z[1:Int(sx*floor(length(Z)/sx))], (sx,Int(floor(length(Z)/sx)))) return Y end function generalized(Z,sx) Ns = floor(Int, length(Z)/sx) Y = var(reshape(Z[1:sx*Ns],sx,Ns)',corrected=false,dims=2) return Y end function PkFind(X) Nx = length(X) Indx = zeros(Int,Nx); for n = 2:Nx-1 if X[n-1]< X[n] > X[n+1] Indx[n] = n elseif X[n-1] < X[n] == X[n+1] k = 1 Indx[n] = n while (n+k)<Nx && X[n] == X[n+k] Indx[n+k] = n+k k+=1 end n+=k end end Indx = Indx[Indx.!==0] return Indx end function EMD(X, Scales::Int) Xt = copy(X); N = size(Xt,1); n=1; IMFs = zeros(Scales+1,N) MaxER = 20; MinTN = 2; #Xt .-= mean(Xt) r1 = Xt while n <= Scales r0 = Xt x = 0; Upx = PkFind(r0); Lwx = PkFind(-r0) UpEnv = CubicSpline(r0[Upx], Upx) #Spline1D(Upx,r0[Upx],k=3,bc="nearest") LwEnv = CubicSpline(r0[Lwx], Lwx) #Spline1D(Lwx,r0[Lwx],k=3,bc="nearest") r1 = r0.- (UpEnv(1:N) .+ LwEnv(1:N))./2 #r0.- (UpEnv.(1:N) .+ LwEnv.(1:N))./2 RT = (sum(r0.*r0) - sum(r1.*r1))/sum(r0.*r0) length(vcat(Upx,Lwx)) <= MinTN ? (LOG = "Decomposition hit minimal extrema criteria."; break) : nothing while x < 100 && RT > 0.2 r0 = 1*r1 Upx = PkFind(r0); Lwx = PkFind(-r0) UpEnv = CubicSpline(r0[Upx], Upx) #Spline1D(Upx,r0[Upx],k=3,bc="nearest") LwEnv = CubicSpline(r0[Lwx], Lwx) #Spline1D(Lwx,r0[Lwx],k=3,bc="nearest") r1 = r0.- (UpEnv(1:N) .+ LwEnv(1:N))./2 #r0.- (UpEnv.(1:N) .+ LwEnv.(1:N))./2 RT = (sum(r0.*r0) - sum(r1.*r1))/sum(r0.*r0) x += 1; 10*log10(sqrt(sum(r0.*r0))/sqrt(sum(r1.*r1))) > MaxER ? (LOG = "Decomposition hit energy ratio criteria."; break) : nothing end IMFs[n,:] = r1 Xt .-= r1 IMFs[Scales+1,:] = r0 .+ mean(X) n+=1 end LOG = "All went well :) " return IMFs, LOG end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
4418
module _MSobject export MSobject """ Mobj = MSobject() Returns a multiscale entropy object (`Mobj`) based on that originally proposed by Costa et. al. (2002) using the following default parameters: EnType = SampEn(), embedding dimension = 2, time delay = 1, radius = 0.2*SD(`Sig`), logarithm = natural Mobj = MSobject(EnType::Function) Returns a multiscale entropy object by passing the entropy function (`EnType`) and the specifying default parameters for that entropy function. To see the default parameters for a particular entropy method, type: `? EntropyHub.EnType` \n (e.g. `? EntropyHub.SampEn`) Mobj = MSobject(EnType::Function; kwargs...) Returns a multiscale entropy object using the specified entropy method (`EnType`) and the 'keyword' parameters for that particular method. To see the default parameters for a particular entropy method, type: ? EntropyHub.EnType (e.g. ? EntropyHub.SampEn) EnType can be any of the following entropy functions: # Base Entropies: ----------------- `ApEn` - Approximate Entropy \n `SampEn` - Sample Entropy \n `FuzzEn` - Fuzzy Entropy \n `K2En` - Kolmogorov Entropy \n `PermEn` - Permutation Entropy \n `CondEn` - Conditional Entropy \n `DistEn` - Distribution Entropy \n `DispEn` - Dispersion Entropy \n `SpecEn` - Spectral Entropy \n `SyDyEn` - Symbolic Dynamic Entropy \n `IncrEn` - Increment Entropy \n `CoSiEn` - Cosine Similarity Entropy \n `PhasEn` - Phase Entropy \n `SlopEn` - Slope Entropy \n `BubbEn` - Bubble Entropy \n `GridEn` - Gridded Distribution Entropy \n `EnofEn` - Entropy of Entropy \n `AttnEn` - Attention Entropy \n `DivEn` - Diversity Entropy \n `RangEn` - Range Entropy \n # Cross Entropies: ------------------ `XApEn` - Cross-Approximate Entropy \n `XSampEn` - Cross-Sample Entropy \n `XFuzzEn` - Cross-Fuzzy Entropy \n `XK2En` - Cross-Kolmogorov Entropy \n `XPermEn` - Cross-Permutation Entropy \n `XCondEn` - Cross-Conditional Entropy \n `XDistEn` - Cross-Distribution Entropy \n `XSpecEn` - Cross-Spectral Entropy \n # Multivariate Entropies: ------------------ `MvSampEn` - Multivariate Sample Entropy \n `MvFuzzEn` - Multivariate Fuzzy Entropy \n `MvPermEn` - Multivariate Permutation Entropy \n `MvCoSiEn` - Multivariate Cosine Similarity Entropy \n `MvDispEn` - Multivariate Dispersion Entropy \n # See also `MSEn`, `XMSEn`, `MvMSEn`, `rMSEn`, `cMSEn`, `hMSEn`, `rXMSEn`, `cXMSEn`, `hXMSEn`, `cMvMSEn` """ function MSobject(EnType::Function=SampEn; kwargs...) Chk = ["ApEn";"SampEn";"FuzzEn";"K2En";"PermEn";"CondEn";"DistEn";"DivEn"; "DispEn";"SyDyEn";"IncrEn";"CoSiEn";"PhasEn";"SpecEn";"SlopEn";"RangEn"; "GridEn";"BubbEn";"EnofEn";"AttnEn"; "XApEn";"XSampEn";"XFuzzEn";"XPermEn"; "XCondEn";"XDistEn";"XSpecEn";"XK2En"; "MvSampEn";"MvFuzzEn";"MvPermEn"; "MvCoSiEn";"MvDispEn"] (String(Symbol(EnType)) in Chk) ? nothing : error("EnType: must be a valid entropy function name. For more info, type: julia> ? EntropyHub.MSobject") #Mobj = (Func=getfield(Main.EntropyHub, Symbol(EnType)), kwargs...) Mobj = (Func= EnType, kwargs...) return Mobj end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
5947
module _MvCoSiEn export MvCoSiEn using Statistics: std, mean, median using LinearAlgebra: Diagonal, UpperTriangular """ MCoSi, Bm = MvCoSiEn(Data) Returns the multivariate cosine similarity entropy estimate (`MCoSi`) and the corresponding global probabilities (`Bm`) estimated for the M multivariate sequences in `Data` using the default parameters: embedding dimension = 2*ones(M), time delay = ones(M), angular threshold = 0.1, logarithm = 2, data normalization = none, !!! note To maximize the number of points in the embedding process, this algorithm uses N-max(m * tau) delay vectors and _*not*_ N-max(m) * max(tau) as employed in [1][2]. ------------------------------------------------------------- MCoSi, Bm = MvCoSiEn(Data::AbstractArray{T,2} where T<:Real; m::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, tau::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, r::Real=.1, Logx::Real=2, Norm::Int=0) Returns the multivariate cosine similarity entropy estimates (`MSamp`) estimated from the M multivariate data sequences in `Data` using the specified keyword arguments: # Arguments: `Data` - Multivariate dataset, NxM matrix of N (>10) observations (rows) and M (cols) univariate data sequences\n `m` - Embedding Dimension, a vector of M positive integers\n `tau` - Time Delay, a vector of M positive integers\n `r` - Angular threshold, a value in range [0 < r < 1] \n `Logx` - Logarithm base, a positive scalar (enter 0 for natural log) \n `Norm` - Normalisation of `Data`, one of the following integers:\n * [0] no normalisation - default * [1] remove median(`Data`) to get zero-median series * [2] remove mean(`Data`) to get zero-mean series * [3] normalises each sequence in `Data` to unit variance and zero mean * [4] normalises each sequence in `Data` values to range [-1 1] # See also `CoSiEn`, `MvDispEn`, `MvSampEn`, `MvFuzzEn`, `MvPermEn`, `MSEn` # References: [1] H. Xiao, T. Chanwimalueang and D. P. Mandic, "Multivariate Multiscale Cosine Similarity Entropy" IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP), pp. 5997-6001, doi: 10.1109/ICASSP43922.2022.9747282. [2] Xiao, H.; Chanwimalueang, T.; Mandic, D.P., "Multivariate Multiscale Cosine Similarity Entropy and Its Application to Examine Circularity Properties in Division Algebras." Entropy 2022, 24, 1287. [3] Ahmed Mosabber Uddin, Danilo P. Mandic "Multivariate multiscale entropy: A tool for complexity analysis of multichannel data." Physical Review E 84.6 (2011): 061918. [4] Theerasak Chanwimalueang and Danilo Mandic, "Cosine similarity entropy: Self-correlation-based complexity analysis of dynamical systems." Entropy 19.12 (2017): 652. """ function MvCoSiEn(Data::AbstractArray{T,2} where T<:Real; m::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, tau::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, r::Real=.1, Logx::Real=2, Norm::Int=0) N, Dn = size(Data) isnothing(m) ? m = 2*ones(Int, Dn) : nothing isnothing(tau) ? tau = ones(Int, Dn) : nothing Logx==0 ? Logx = exp(1) : nothing (N>10) && (Dn>1) ? nothing : error("Data: must be an NxM matrix where N>10 and M>1") ndims(m)==1 && length(m)==Dn && all(m.>0) && eltype(m)<:Int ? nothing : error("m: vector of M positive integers") ndims(tau)==1 && length(tau)==Dn && all(tau.>0) && eltype(tau)<:Int ? nothing : error("tau: vector of M positive integers") (0<r<1) ? nothing : error("r: must be a scalar in range 0 < r < 1") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") (Norm in collect(0:4)) ? nothing : error("Norm: must be an integer in range [0 4]") if Norm == 1 Xi = Data .- median(Data,dims=1) elseif Norm == 2 Xi = Data .- mean(Data,dims=1) elseif Norm == 3 Xi = (Data .- mean(Data, dims=1))./std(Data,corrected=false, dims=1) elseif Norm == 4 Xi = (2*(Data .- minimum(Data, dims=1))./(maximum(Data,dims=1).-minimum(Data, dims=1))) .- 1; else Xi = Data; end Nx = N-maximum((m.-1).*tau) Zm = zeros(Nx,sum(m)); q=1 for k = 1:Dn for p = 1:m[k] Zm[:,q] = Xi[1+(p-1)*tau[k]:Nx+(p-1)*tau[k], k] q += 1 end end Num = Zm*transpose(Zm); Mag = sqrt.(sum(Diagonal(Num),dims=1))[:] Den = Mag*transpose(Mag) AngDis = round.(acos.(round.(Num./Den,digits=8))/pi,digits=6) if maximum(imag.(AngDis)) < (10^-5) Bm = (sum(UpperTriangular(AngDis .< r))-Nx)/(Nx*(Nx-1)/2) else Bm = (sum(UpperTriangular(real.(AngDis) .< r))-Nx)/(Nx*(Nx-1)/2) @warn("Complex values ignored.") end Bm == 1 || Bm == 0 ? MCoSi = NaN : MCoSi = -(Bm*log(Logx, Bm)) - ((1-Bm)*log(Logx, 1-Bm)) return MCoSi, Bm end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
8706
module _MvDispEn export MvDispEn using Clustering: kmeans, assignments using Statistics: std, mean using StatsFuns: normcdf using Combinatorics: combinations """ MDisp, RDE = MvDispEn(Data) Returns the multivariate dispersion entropy estimate (`MDisp`) and the reverse dispersion entropy (`RDE`) for the M multivariate sequences in `Data` using the default parameters: embedding dimension = 2*ones(M,1), time delay = ones(M,1), # symbols = 3, algorithm method = "v1" (see below), data transform = normalised cumulative density function (ncdf) logarithm = natural, data normalization = true, !!! note By default, `MvDispEn` uses the method termed `mvDEii` in [1], which follows the original multivariate embedding approach of Ahmed & Mandic [2]. The `v1` method therefore returns a singular entropy estimate. If the `v2` method is selected (`Methodx=="v2"`), the main method outlined in [1] termed `mvDE` is applied. In this case, entropy is estimated using each combination of multivariate delay vectors with lengths 1:max(m), with each entropy value returned accordingly. See [1] for more info. ------------------------------------------------------------- MDisp, RDE = MvDispEn(Data::AbstractArray{T,2} where T<:Real; m::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, tau::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, c::Int=3, Methodx::String="v1", Typex::String="NCDF", Norm::Bool=false, Logx::Real=exp(1)) Returns the multivariate dispersion entropy estimate (`MDisp`) for the M multivariate data sequences in `Data` using the specified keyword arguments: # Arguments: `Data` - Multivariate dataset, NxM matrix of N (>10) observations (rows) and M (cols) univariate data sequences\n `m` - Embedding Dimension, a vector of M positive integers\n `tau` - Time Delay, a vector of M positive integers\n `c` - Number of symbols in transform, an integer > 1 \n `Methodx` - The method of multivariate dispersion entropy estimation as outlined in [1], either:\n * `"v1"` - employs the method consistent with the original multivariate embedding approach of Ahmed & Mandic [2], termed `mvDEii` in [1]. (default) * `"v2"` - employs the main method derived in [1], termed `mvDE`. `Typex` - Type of data-to-symbolic sequence transform, one of the following:\n {`'linear'`, `'kmeans'`, `'ncdf'`, `'equal'`} See the `EntropyHub Guide` for more info on these transforms. `Norm` - Normalisation of `MDisp` and `RDE` values, a boolean:\n * [false] no normalisation (default) * [true] normalises w.r.t number of possible dispersion patterns (`c^m`). `Logx` - Logarithm base, a positive scalar \n # See also `DispEn`, `DispEn2D`, `MvSampEn`, `MvFuzzEn`, `MvPermEn`, `MSEn` # References: [1] H Azami, A Fernández, J Escudero "Multivariate Multiscale Dispersion Entropy of Biomedical Times Series" Entropy 2019, 21, 913. [2] Ahmed Mosabber Uddin, Danilo P. Mandic "Multivariate multiscale entropy: A tool for complexity analysis of multichannel data." Physical Review E 84.6 (2011): 061918. [3] Mostafa Rostaghi and Hamed Azami, "Dispersion entropy: A measure for time-series analysis." IEEE Signal Processing Letters 23.5 (2016): 610-614. [4] Hamed Azami and Javier Escudero, "Amplitude-and fluctuation-based dispersion entropy." Entropy 20.3 (2018): 210. [5] Li Yuxing, Xiang Gao and Long Wang, "Reverse dispersion entropy: A new complexity measure for sensor signal." Sensors 19.23 (2019): 5203. """ function MvDispEn(Data::AbstractArray{T,2} where T<:Real; m::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, tau::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, c::Int=3, Methodx::String="v1", Typex::String="NCDF", Norm::Bool=false, Logx::Real=exp(1)) N, Dn = size(Data) isnothing(m) ? m = 2*ones(Int, Dn) : nothing isnothing(tau) ? tau = ones(Int, Dn) : nothing Logx==0 ? Logx = exp(1) : nothing (N>10) && (Dn>1) ? nothing : error("Data: must be an NxM matrix where N>10 and M>1") ndims(m)==1 && length(m)==Dn && all(m.>0) && eltype(m)<:Int ? nothing : error("m: vector of M positive integers") ndims(tau)==1 && length(tau)==Dn && all(tau.>0) && eltype(tau)<:Int ? nothing : error("tau: vector of M positive integers") (c > 1) ? nothing : error("c: must be an integer > 1") (lowercase(Typex) in ["linear", "kmeans", "ncdf","equal"]) ? nothing : error("Typex: must be one of the following strings - 'linear','kmeans','ncdf','equal'") (lowercase(Methodx) in ["v1", "v2"]) ? nothing : error("Methodx: must be either 'v1' or 'v2'") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Sx = zeros(Int8, N, Dn) for q in eachindex(1:Dn) Sig = Data[:,q] if lowercase(Typex) == "linear" Edges = range(minimum(Sig),maximum(Sig),length=c+1) Zi = map(x -> sum(Edges[1:c].<=x), Sig) elseif lowercase(Typex) == "kmeans" Temp = kmeans(transpose(Sig), c; maxiter=200) Zx = assignments(Temp) Clux = Temp.centers xx = sortperm(Clux[:]); Zi = zeros(N) for k = 1:c Zi[Zx.==xx[k]] .= k; end elseif lowercase(Typex) == "ncdf" Zx = normcdf.(mean(Sig),std(Sig,corrected=false),Sig); Zi = map(x -> sum(range(0,1,length=c+1)[1:c].<=x), Zx) elseif lowercase(Typex) == "equal" ix = sortperm(Sig,alg=MergeSort); xx = Int.(round.(range(0,N,length=c+1))) Zi = zeros(N) for k = 1:c Zi[ix[xx[k]+1:xx[k+1]]] .= k end end Sx[:,q] = Zi[:] end Nx = N-maximum((m.-1).*tau) Vex = zeros(Int8, Nx, sum(m)) q=1 for k = 1:Dn for p = 1:m[k] Vex[:,q] = Sx[1+(p-1)*tau[k]:Nx+(p-1)*tau[k], k] q += 1 end end if lowercase(Methodx) == "v1" Px = unique(Vex,dims=1) Counter = map(n -> sum(all((Vex .- Px[n:n,:]).==0, dims=2)), 1:size(Px,1)) Counter = Counter[Counter.!=0] Ppi = Counter/sum(Counter) if round(sum(Ppi),digits=5) != 1 @warn ("Potential error with probability calculation") end MDisp = -sum(Ppi.*log.(Logx,Ppi)) RDE = sum((Ppi .- (1/(c^sum(m)))).^2) if Norm MDisp = MDisp/log(Logx, c^sum(m)) RDE = RDE/(1-(1/(c^sum(m)))) end #return MDisp, RDE elseif lowercase(Methodx) == "v2" P = sum(m) MDisp = zeros(maximum(m)) RDE = zeros(maximum(m)) for k in eachindex(1:maximum(m)) print(" . ") Temp = collect(combinations(1:P,k)) Vez = zeros(Int8, Nx*binomial(P,k),k) for q in eachindex(1:size(Temp,1)) # Vez[q*Nx:(q+1)*Nx-1,:] = Vex[:,Temp[q][:]] Vez[1+(q-1)*Nx:q*Nx,:] = Vex[:,Temp[q]] end Px = unique(Vez, dims=1) Counter = map(n -> sum(all((Vez .- Px[n:n,:]).==0,dims=2)), 1:size(Px,1)) Counter = Counter[Counter.!=0] Ppi = Counter/sum(Counter) if round(sum(Ppi),digits=5) != 1 @warn ("Potential error with probability calculation") end MDisp[k] = -sum(Ppi.*log.(Logx,Ppi)) RDE[k] = sum((Ppi .- (1/(c^k))).^2) if Norm MDisp[k] = MDisp[k]/log(Logx, c^k) RDE[k] = RDE[k]/(1-(1/(c^k))) end end end return MDisp, RDE end end """Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub"""
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
11052
module _MvFuzzEn export MvFuzzEn using Statistics: std, mean """ MFuzz, B0, Bt, B1 = MvFuzzEn(Data) Returns the multivariate fuzzy entropy estimate (`MFuzz`) and the average vector distances (`m`: `B0`; joint total `m+1` subspace: `Bt`; all possible `m+1` subspaces: `B1`), from the M multivariate sequences in `Data` using the default parameters: embedding dimension = 2*ones(M,1), time delay = ones(M,1), fuzzy membership function = "default", fuzzy function parameters= [0.2, 2], logarithm = natural, data normalization = false, !!! note The entropy value returned as `MFuzz` is estimated using the "full" method [i.e. -log(Bt/B0)] which compares delay vectors across all possible `m+1` expansions of the embedding space as applied in [1][3]. Contrary to conventional definitions of sample entropy, this method does not provide a lower bound of 0!! Thus, it is possible to obtain negative entropy values for multivariate fuzzy entropy, even for stochastic processes... Alternatively, one can calculate `MFuzz` via the "naive" method, which ensures a lower bound of 0, by using the average vector distances for an individual `m+1` subspace (B1) [e.g. -log(B1(1)/B0)], or the average for all `m+1` subspaces [i.e. -log(mean(B1)/B0)]. To maximize the number of points in the embedding process, this algorithm uses N - max(m * tau) delay vectors and _*not*_ N - max(m) * max(tau) as employed in [1] and [3]. ------------------------------------------------------------- MFuzz, B0, Bt, B1 = MvFuzzEn(Data::AbstractArray{T} where T<:Real; m::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, tau::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, r::Union{Real,Tuple{Real,Real}}=(.2,2.0), Fx::String="default", Logx::Real=exp(1), Norm::Bool=false) Returns the multivariate sample entropy estimates (`MSamp`) estimated from the M multivariate data sequences in `Data` using the specified keyword arguments: # Arguments: `Data` - Multivariate dataset, NxM matrix of N (>10) observations (rows) and M (cols) univariate data sequences\n `m` - Embedding Dimension, a vector of M positive integers\n `tau` - Time Delay, a vector of M positive integers\n `Fx` - Fuzzy function name, one of the following: {`"sigmoid", "modsampen", "default", "gudermannian",` `"bell", "triangular", "trapezoidal1", "trapezoidal2",` `"z_shaped", "gaussian", "constgaussian"`}\n `r` - Fuzzy function parameters, a 1 element scalar or a 2 element tuple of positive values. The `r` parameters for each fuzzy function are defined as follows: [default: [.2 2]]\n default: r(1) = divisor of the exponential argument r(2) = argument exponent (pre-division) sigmoid: r(1) = divisor of the exponential argument r(2) = value subtracted from argument (pre-division) modsampen: r(1) = divisor of the exponential argument r(2) = value subtracted from argument (pre-division) gudermannian: r = a scalar whose value is the numerator of argument to gudermannian function: GD(x) = atan(tanh(`r`/x)) triangular: r = a scalar whose value is the threshold (corner point) of the triangular function. trapezoidal1: r = a scalar whose value corresponds to the upper (2r) and lower (r) corner points of the trapezoid. trapezoidal2: r(1) = a value corresponding to the upper corner point of the trapezoid. r(2) = a value corresponding to the lower corner point of the trapezoid. z_shaped: r = a scalar whose value corresponds to the upper (2r) and lower (r) corner points of the z-shape. bell: r(1) = divisor of the distance value r(2) = exponent of generalized bell-shaped function gaussian: r = a scalar whose value scales the slope of the Gaussian curve. constgaussian: r = a scalar whose value defines the lower threshod and shape of the Gaussian curve.\n `Logx` - Logarithm base, a positive scalar \n `Norm` - Normalisation of all M sequences to unit variance, a boolean\n # See also `MvSampEn`, `FuzzEn`, `XFuzzEn`, `FuzzEn2D`, `MSEn`, `MvPermEn` # References: [1] Ahmed, Mosabber U., et al. "A multivariate multiscale fuzzy entropy algorithm with application to uterine EMG complexity analysis." Entropy 19.1 (2016): 2. [2] Azami, Alberto Fernández, Javier Escudero. "Refined multiscale fuzzy entropy based on standard deviation for biomedical signal analysis." Medical & biological engineering & computing 55 (2017): 2037-2052. [3] Ahmed Mosabber Uddin, Danilo P. Mandic "Multivariate multiscale entropy analysis." IEEE signal processing letters 19.2 (2011): 91-94. """ function MvFuzzEn(Data::AbstractArray{T,2} where T<:Real; m::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, tau::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, r::Union{Real,Tuple{Real,Real}}=(.2,2.0), Fx::String="default", Logx::Real=exp(1), Norm::Bool=false) N, Dn = size(Data) isnothing(m) ? m = 2*ones(Int, Dn) : nothing isnothing(tau) ? tau = ones(Int, Dn) : nothing Norm ? Data = Data./std(Data, dims=1, corrected=false) : nothing (N>10) && (Dn>1) ? nothing : error("Data: must be an NxM matrix where N>10 and M>1") ndims(m)==1 && length(m)==Dn && all(m.>0) && eltype(m)<:Int ? nothing : error("m: vector of M positive integers") ndims(tau)==1 && length(tau)==Dn && all(tau.>0) && eltype(tau)<:Int ? nothing : error("tau: vector of M positive integers") (minimum(r)>=0 && length(r)<=2) ? nothing : error("r: must be a scalar or 2 element tuple of positive values") (lowercase(Fx) in ["default","sigmoid","modsampen","gudermannian","bell", "z_shaped", "triangular", "trapezoidal1","trapezoidal2","gaussian","constgaussian"]) ? nothing : error("Fx: must be one of the following strings - 'default', 'sigmoid', 'modsampen', 'gudermannian', 'bell', 'z_shaped', 'triangular', 'trapezoidal1','trapezoidal2','gaussian','constgaussian'") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Fun = getfield(_MvFuzzEn,Symbol(lowercase(Fx))) Nx = N - maximum((m.-1).*tau) Ny = N - maximum(m.*tau) Vex = zeros(Nx,sum(m)) q = 1; for k = 1:Dn for p = 1:m[k] Vex[:,q] = Data[1+(p-1)*tau[k]:Nx+(p-1)*tau[k], k] q += 1 end end Count0 = Distx(Vex .- mean(Vex,dims=2), r, Fun) B0 = sum(Count0)/(Nx*(Nx-1)/2) B1 = zeros(Dn) Temp = cumsum(m) Vez = Inf.*ones(1,sum(m)+1) for k = 1:Dn Sig = Data[1+m[k]*tau[k]:Ny+m[k]*tau[k], k] Vey = hcat(Vex[1:Ny, 1:Temp[k]], Sig, Vex[1:Ny, Temp[k]+1:end]) Vez = vcat(Vez, Vey) Count1 = Distx(Vey .- mean(Vey,dims=2), r, Fun); B1[k] = sum(Count1)/(Ny*(Ny-1)/2) end Vez = Vez[2:end,:] Count1 = Distx(Vez .- mean(Vez,dims=2), r, Fun) Bt = sum(Count1)/(Dn*Ny*((Dn*Ny)-1)/2) MFuzz = -log(Bt/B0)/log(Logx) return MFuzz, B0, Bt, B1 end function Distx(Vex, r, Fun) Nt = size(Vex)[1] Counter = zeros(Nt-1,Nt-1) for x=1:Nt-1 Counter[x,x:end] = Fun(maximum(abs.(Vex[x+1:end,:] .- Vex[x:x,:]), dims=2)[:], r) end return Counter end function sigmoid(x,r) if length(r) == 1 error("When Fx = 'Sigmoid', r must be a two-element tuple.") end y = inv.(1 .+ exp.((x.-r[2])/r[1])) return y end function modsampen(x,r) if length(r) == 1 error("When Fx = 'Modsampen', r must be a two-element tuple.") end y = inv.(1 .+ exp.((x.-r[2])/r[1])) return y end function default(x,r) if length(r) == 1 error("When Fx = 'Default', r must be a two-element tuple.") end y = exp.(-(x.^r[2])/r[1]) return y end function gudermannian(x,r) if r <= 0 error("When Fx = 'Gudermannian', r must be a scalar > 0.") end y = atan.(tanh.(r[1]./x)) y ./= maximum(y) return y end function triangular(x,r) length(r)==1 ? nothing : error("When Fx = 'Triangular', r must be a scalar > 0.") y = 1 .- (x./r) y[x .> r] .= 0 return y end function trapezoidal1(x, r) length(r)==1 ? nothing : error("When Fx = 'Trapezoidal1', r must be a scalar > 0.") y = zeros(length(x)) y[x .<= r*2] = 2 .- (x[x .<= r*2]./r) y[x .<= r] .= 1 return y end function trapezoidal2(x, r) (r isa Tuple) && (length(r)==2) ? nothing : error("When Fx = 'Trapezoidal2', r must be a two-element tuple.") y = zeros(length(x)) y[x .<= maximum(r)] = 1 .- (x[x .<= maximum(r)] .- minimum(r))./(maximum(r)-minimum(r)) y[x .<= minimum(r)] .= 1 return y end function z_shaped(x, r) length(r)==1 ? nothing : error("When Fx = 'Z_shaped', r must be a scalar > 0.") y = zeros(length(x)) y[x .<= 2*r] = 2*(((x[x .<= 2*r] .- 2*r)./r).^2) y[x .<= 1.5*r] = 1 .- (2*(((x[x .<= 1.5*r] .- r)/r).^2)) y[x .<= r] .= 1 return y end function bell(x, r) (r isa Tuple) && length(r)==2 ? nothing : error("When Fx = 'Bell', r must be a two-element tuple.") y = inv.(1 .+ abs.(x./r[1]).^(2*r[2])) return y end function gaussian(x, r) length(r)==1 ? nothing : error("When Fx = 'Gaussian', r must be a scalar > 0.") y = exp.(-((x.^2)./(2*(r.^2)))) return y end function constgaussian(x, r) length(r)==1 ? nothing : error("When Fx = 'ConstGaussian', r must be a scalar > 0.") y = ones(length(x)) y[x .> r] = exp.(-log(2)*((x[x .> r] .- r)./r).^2) return y end end """Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub"""
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
6813
module _MvMSEn export MvMSEn using Statistics: std, mean, median, var using Plots using DSP: conv """ MSx, CI = MvMSEn(Data, Mobj) Returns a vector of multivariate multiscale entropy values (`MSx`) and the complexity index (`CI`) of the data sequences in `Data` using the parameters specified by the multiscale object (`Mobj`) over 3 temporal scales with coarse- graining (default). !!! note By default, the `MvSampEn` and `MvFuzzEn` multivariate entropy algorithms estimate entropy values using the "full" method by comparing delay vectors across all possible `m+1` expansions of the embedding space as applied in [1]. These methods are not lower-bounded to 0, like most entropy algorithms, so `MvMSEn` may return negative entropy values if the base multivariate entropy function is `MvSampEn` and `MvFuzzEn`, even for stochastic processes... ------------------------------------------------------------- MSx, CI = MSEn(Data::AbstractArray{T,2} where T<:Real, Mobj::NamedTuple; Scales::Int=3, Methodx::String="coarse", Plotx::Bool=false) Returns a vector of multivariate multiscale entropy values (`MSx`) and the complexity index (`CI`) of the data sequences in `Data` using the parameters specified by the multiscale object (`Mobj`) and the following keyword arguments: # Arguments: `Scales` - Number of temporal scales, an integer > 1 (default: 3) \n `Method` - Graining method, one of the following: \n {`coarse`,`modified`,`generalized`} [default = `coarse`] For further info on these graining procedures, see the EntropyHub guide. \n `Plotx` - When Plotx == true, returns a plot of the entropy value at each time scale (i.e. the multiscale entropy curve) [default: false] !!! tip For further info on these graining procedures see the EntropyHub guide. # See also `MSobject`, `cMvMSEn`, `MvFuzzEn`, `MvSampEn`, `MvPermEn`, `MvCoSiEn`, `MvDispEn` # References: [1] Ahmed Mosabber Uddin, Danilo P. Mandic "Multivariate multiscale entropy analysis." IEEE signal processing letters 19.2 (2011): 91-94. [2] Madalena Costa, Ary Goldberger, and C-K. Peng, "Multiscale entropy analysis of complex physiologic time series." Physical review letters 89.6 (2002): 068102. [3] Vadim V. Nikulin, and Tom Brismar, "Comment on “Multiscale entropy analysis of complex physiologic time series”." Physical Review Letters 92.8 (2004): 089803. [4] Madalena Costa, Ary L. Goldberger, and C-K. Peng. "Costa, Goldberger, and Peng reply." Physical Review Letters 92.8 (2004): 089804. [5] Madalena Costa, Ary L. Goldberger and C-K. Peng, "Multiscale entropy analysis of biological signals." Physical review E 71.2 (2005): 021906. [6] Ranjit A. Thuraisingham and Georg A. Gottwald, "On multiscale entropy analysis for physiological data." Physica A: Statistical Mechanics and its Applications 366 (2006): 323-332. [7] Ahmed Mosabber Uddin, Danilo P. Mandic "Multivariate multiscale entropy: A tool for complexity analysis of multichannel data." Physical Review E 84.6 (2011): 061918. """ function MvMSEn(Data::AbstractArray{T,2} where T<:Real, Mobj::NamedTuple; Scales::Int=3, Methodx::String="coarse", Plotx::Bool=false) N, Dn = size(Data) (N>10) && (Dn>1) ? nothing : error("Data: must be an NxM matrix where N>10 and M>1") (length(Mobj) >= 1) ? nothing : error("Mobj: must be a multiscale entropy object created with the function EntropyHub.MSobject") (Scales>1) ? nothing : error("Scales: must be an integer > 1") (lowercase(Methodx) in ["coarse","modified","generalized"]) ? nothing : error("Method: must be one of the following string names - 'coarse','modified','generalized'") String(Symbol(Mobj.Func))[1:2] != "Mv" ? error("Base entropy estimator must be a multivariate entropy method. ", "To perform univariate multiscale entropy estimation, use MSEn().") : nothing MSx = zeros(Scales) Args = NamedTuple{keys(Mobj)[2:end]}(Mobj) Func2 = getfield(_MvMSEn,Symbol(lowercase(Methodx))) for T = 1:Scales print(". ") Temp = Func2(Data,T,Dn) Tempx = Mobj.Func(Temp; Args...) typeof(Tempx)<:Tuple ? Temp2 = mean(Tempx[1]) : Temp2 = mean(Tempx) MSx[T] = Temp2 end CI = sum(MSx) print("\n") if any(isnan.(MSx)) println("Some entropy values may be undefined.") end if Plotx p1 = plot(1:Scales, MSx, c=RGB(8/255, 63/255, 77/255), lw=3) scatter!(1:Scales, MSx, markersize=6, c=RGB(1, 0, 1), xlabel = "Scale Factor", ylabel = "Entropy Value", guidefont = font(12, "arial", RGB(7/255, 54/255, 66/255)), tickfontsize = 10, tickfontfamily="arial", legend=false, title = "Multivariate Multiscale $(string(Mobj.Func)[3:end]) ($(titlecase(Methodx))-graining method)", plot_titlefontsize=16, plot_titlefontcolor=RGB(7/255, 54/255, 66/255)) #ylim=(0,maximum(MSx)+.2), display(p1) end return MSx, CI end function coarse(Z, sx, Dn) Ns = Int(floor(size(Z,1)/sx)) Y = zeros(Ns,Dn) for k in 1:Dn Y[:,k] = mean(reshape(Z[1:sx*Ns,k],sx,Ns),dims=1) end return Y end function modified(Z, sx, Dn) Y = (conv(Z,ones(Int,sx))/sx)[sx:end-sx+1,:] return Y end function generalized(Z, sx, Dn) Ns = Int(floor(size(Z,1)/sx)) Y = zeros(Ns,Dn) for k in 1:Dn Y[:,k] = var(reshape(Z[1:sx*Ns, k],sx,Ns)',corrected=false,dims=2) end return Y end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
9846
module _MvPermEn export MvPermEn using Combinatorics: permutations using Statistics: var, mean using DSP: hilbert, unwrap, angle """ MPerm, MPnorm = MvPermEn(Data) Returns the multivariate permutation entropy estimate (`MPerm`) and the normalized permutation entropy for the M multivariate sequences in `Data` using the default parameters: embedding dimension = 2*ones(M,1), time delay = ones(M,1), logarithm = 2, normalisation = w.r.t #symbols (sum(`m-1`)) !!! note The multivariate permutation entropy algorithm implemented here uses multivariate embedding based on Takens' embedding theorem, and follows the methods for multivariate entropy estimation through shared spatial reconstruction as originally presented by Ahmed & Mandic [1]. This function does _*NOT*_ use the multivariate permutation entropy algorithm of Morabito et al. (Entropy, 2012) where the entropy values of individual univariate sequences are averaged because such methods do not follow the definition of multivariate embedding and therefore do not consider cross-channel statistical complexity. To maximize the number of points in the embedding process, this algorithm uses N- max(tau * m) delay vectors and _*not*_ N-max(m) * max(tau) as employed in [1]. ------------------------------------------------------------- MPerm, MPnorm = MvPermEn(Data::AbstractArray{T} where T<:Real; m::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, tau::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, Typex::String="none", tpx::Union{Int,Nothing}=nothing, Norm::Bool=false, Logx::Real=2) Returns the multivariate permutation entropy estimate (`MPerm`) for the M multivariate data sequences in `Data` using the specified keyword arguments: # Arguments: `Data` - Multivariate dataset, NxM matrix of N (>10) observations (rows) and M (cols) univariate data sequences\n `m` - Embedding Dimension, a vector of M positive integers\n `tau` - Time Delay, a vector of M positive integers\n `Typex` - Permutation entropy variation, can be one of the following strings:\n {`'modified'`, `'ampaware'`, `'weighted'`, `'edge'`, `'phase'`} See the `EntropyHub guide <https://github.com/MattWillFlood/EntropyHub/blob/main/EntropyHub%20Guide.pdf>`_ for more info on MvPermEn variants. `tpx` - Tuning parameter for associated permutation entropy variation. \n * [ampaware] `tpx` is the A parameter, a value in range [0 1]; default = 0.5 * [edge] `tpx` is the r sensitivity parameter, a scalar > 0; default = 1 * [phase] `tpx` is the option to unwrap the phase angle of Hilbert-transformed signal, either [] or 1 (default = 0)\n `Norm` - Normalisation of MPnorm value, a boolean operator:\n * false - normalises w.r.t log(# of permutation symbols [sum(m)-1]) - default * true - normalises w.r.t log(# of all possible permutations [sum(m)!]) `Logx` - Logarithm base, a positive scalar \n # See also `PermEn`, `PermEn2D`, `XPermEn`, `MSEn`, `MvFuzzEn`, `MvSampEn` # References: [1] Ahmed Mosabber Uddin, Danilo P. Mandic "Multivariate multiscale entropy: A tool for complexity analysis of multichannel data." Physical Review E 84.6 (2011): 061918. [2] Christoph Bandt and Bernd Pompe, "Permutation entropy: A natural complexity measure for time series." Physical Review Letters, 88.17 (2002): 174102. [3] Chunhua Bian, et al., "Modified permutation-entropy analysis of heartbeat dynamics." Physical Review E 85.2 (2012) : 021906 [4] Bilal Fadlallah, et al., "Weighted-permutation entropy: A complexity measure for time series incorporating amplitude information." Physical Review E 87.2 (2013): 022911. [5] Hamed Azami and Javier Escudero, "Amplitude-aware permutation entropy: Illustration in spike detection and signal segmentation." Computer methods and programs in biomedicine, 128 (2016): 40-51. [6] Zhiqiang Huo, et al., "Edge Permutation Entropy: An Improved Entropy Measure for Time-Series Analysis," 45th Annual Conference of the IEEE Industrial Electronics Soc, (2019), 5998-6003 [7] Maik Riedl, Andreas Müller, and Niels Wessel, "Practical considerations of permutation entropy." The European Physical Journal Special Topics 222.2 (2013): 249-262. [8] Kang Huan, Xiaofeng Zhang, and Guangbin Zhang, "Phase permutation entropy: A complexity measure for nonlinear time series incorporating phase information." Physica A: Statistical Mechanics and its Applications 568 (2021): 125686. """ function MvPermEn(Data::AbstractArray{T,2} where T<:Real; m::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, tau::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, Typex::String="none", tpx::Union{Real,Nothing}=nothing, Norm::Bool=false, Logx::Real=2) N, Dn = size(Data) isnothing(m) ? m = 2*ones(Int, Dn) : nothing isnothing(tau) ? tau = ones(Int, Dn) : nothing Logx==0 ? Logx = exp(1) : nothing (N>10) && (Dn>1) ? nothing : error("Data: must be an NxM matrix where N>10 and M>1") ndims(m)==1 && length(m)==Dn && all(m.>0) && eltype(m)<:Int ? nothing : error("m: vector of M positive integers") ndims(tau)==1 && length(tau)==Dn && all(tau.>0) && eltype(tau)<:Int ? nothing : error("tau: vector of M positive integers") (lowercase(Typex) in ["none","modified","ampaware","weighted","edge","phase"]) ? nothing : error("Typex: must be one of the following strings - 'modified','ampaware','weighted','edge','phase'") (isnothing(tpx) || tpx>0) ? nothing : error("tpx: the value of tpx relates to 'Type'. See the EntropyHub guide for further info on the 'tpx' value.") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") if lowercase(Typex) == "phase" Data = angle.(hilbert(Data)) tpx == 1 ? Data = unwrap(Data) : nothing end Nx = N-maximum((m.-1).*tau) Sx = zeros(Nx,sum(m)) q=1 for k = 1:Dn for p = 1:m[k] Sx[:,q] = Data[1+(p-1)*tau[k]:Nx+(p-1)*tau[k], k] q += 1 end end Temp = sortind(Sx) #Px = collect(permutations(collect(1:sum(m)))) Px = unique(Temp,dims=1) #Counter = zeros(Int, size(Px,1)) if lowercase(Typex) == "modified" Tx = (diff(sort(Sx,dims=2),dims=2).==0) for km = 1:sum(m)-1 Temp[Tx[:,km],km+1] = Temp[Tx[:,km],km]; end Px = unique(Temp,dims=1) Counter = map(n -> sum(all(Temp .- transpose(Px[n,:]) .==0,dims=2)), 1:size(Px,1)) Counter = Counter[Counter.!=0] Ppi = Counter/sum(Counter) elseif lowercase(Typex) == "weighted" Wj = var(Sx,corrected=false,dims=2) Counter = map(n -> sum(Wj[all(Temp .- transpose(Px[n,:]) .==0,dims=2)]), 1:size(Px,1)) Counter = Counter[Counter.!=0] Ppi = Counter/sum(Wj) #=for n = 1:size(Px,1) Counter[n] = sum(Wj[all(Temp .- transpose(Px[n]) .==0,dims=2)]) end=# elseif lowercase(Typex) == "ampaware" isnothing(tpx) ? tpx = 0.5 : nothing tpx<0 || tpx>1 ? error("When Typex = 'ampaware', the A parameter must be in the range [0 1]") : nothing AA = sum(abs.(Sx),dims=2) AB = sum(abs.(diff(Sx,dims=2)),dims=2) Ax = (tpx*AA/sum(m)) + ((1-tpx)*AB/(sum(m)-1)); #= for n = 1:size(Px,1) Counter[n] = sum(Ax[all(Temp.-transpose(Px[n]).==0,dims=2)]) end =# Counter = map(n -> sum(Ax[all(Temp .- transpose(Px[n,:]) .==0,dims=2)]), 1:size(Px,1)) Counter = Counter[Counter.!=0] Ppi = Counter/sum(Ax); elseif lowercase(Typex) == "edge" isnothing(tpx) ? tpx = 1 : nothing tpx <=0 ? error("When Typex = 'Edge', the r sensitivity parameter (tpx) must be > 0") : nothing Counter = zeros(size(Px,1)) for n in eachindex(1:size(Px,1)) Tx = diff(Sx[all(Temp .- transpose(Px[n,:]) .==0,dims=2)[:],:],dims=2) Counter[n] = sum(mean(hypot.(Tx,1),dims=2).^tpx) end Counter = Counter[Counter.!=0] Ppi = Counter/sum(Counter) else Counter = map(n -> sum(all(Temp .- transpose(Px[n,:]) .==0,dims=2)), 1:size(Px,1)) Counter = Counter[Counter.!=0] Ppi = Counter/sum(Counter) end if round(sum(Ppi),digits=5) != 1 @warn ("Potential error with probability calculation") end MPerm = -sum(Ppi.*(log.(Logx, Ppi))); Norm ? Pnorm = MPerm/(log(Logx, factorial(sum(m)))) : Pnorm = MPerm/(sum(m)-1) return MPerm, Pnorm end function sortind(X) Y = zeros(Int, size(X)) for k = 1:length(X[:,1]) Y[k,:] = sortperm(X[k,:]) end return Y end end """Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub"""
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
5509
module _MvSampEn export MvSampEn using Statistics: std # using LinearAlgebra: UpperTriangular, I """ MSamp, B0, Bt, B1 = MvSampEn(Data) Returns the multivariate sample entropy estimate (`MSamp`) and the average number of matched delay vectors (`m`: `B0`; joint total `m+1` subspace: `Bt`; all possible `m+1` subspaces: `B1`), from the M multivariate sequences in `Data` using the default parameters: embedding dimension = 2*ones(M), time delay = ones(M), radius threshold = 0.2, logarithm = natural, data normalization = false !!! note The entropy value returned as `MSamp` is estimated using the "full" method [i.e. -log(Bt/B0)] which compares delay vectors across all possible `m+1` expansions of the embedding space as applied in [1][2]. Contrary to conventional definitions of sample entropy, this method does not provide a lower bound of 0!! Thus, it is possible to obtain negative entropy values for multivariate sample entropy, even for stochastic processes... Alternatively, one can calculate `MSamp` via the "naive" method, which ensures a lower bound of 0, by using the average number of matched vectors for an individual `m+1` subspace (B1) [e.g. -log(B1(1)/B0)], or the average for all `m+1` subspaces [i.e. -log(mean(B1)/B0)]. To maximize the number of points in the embedding process, this algorithm uses N - max(m * tau) delay vectors and _**not**_ N-max(m) * max(tau) as employed in [1][2]. ------------------------------------------------------------- MSamp, B0, Bt, B1 = MvSampEn(Data::AbstractArray{T} where T<:Real; m::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, tau::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, r::Real=0.2, Logx::Real=exp(1), Norm::Bool=false) Returns the multivariate sample entropy estimates (`MSamp`) estimated from the M multivariate data sequences in `Data` using the specified keyword arguments: # Arguments: `Data` - Multivariate dataset, NxM matrix of N (>10) observations (rows) and M (cols) univariate data sequences\n `m` - Embedding Dimension, a vector of M positive integers\n `tau` - Time Delay, a vector of M positive integers\n `r` - Radius Distance Threshold, a positive scalar \n `Logx` - Logarithm base, a positive scalar \n `Norm` - Normalisation of all M sequences to unit variance, a boolean\n # See also `SampEn`, `XSampEn`, `SampEn2D`, `MSEn`, `MvFuzzEn`, `MvPermEn` # References: [1] Ahmed Mosabber Uddin, Danilo P. Mandic "Multivariate multiscale entropy: A tool for complexity analysis of multichannel data." Physical Review E 84.6 (2011): 061918. [2] Ahmed Mosabber Uddin, Danilo P. Mandic "Multivariate multiscale entropy analysis." IEEE signal processing letters 19.2 (2011): 91-94. """ function MvSampEn(Data::AbstractArray{T,2} where T<:Real; m::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, tau::Union{AbstractArray{T} where T<:Int, Nothing}=nothing, r::Real=0.2, Logx::Real=exp(1), Norm::Bool=false) N, Dn = size(Data) isnothing(m) ? m = 2*ones(Int, Dn) : nothing isnothing(tau) ? tau = ones(Int, Dn) : nothing Norm ? Data = Data./std(Data, dims=1, corrected=false) : nothing (N>10) && (Dn>1) ? nothing : error("Data: must be an NxM matrix where N>10 and M>1") ndims(m)==1 && length(m)==Dn && all(m.>0) && eltype(m)<:Int ? nothing : error("m: vector of M positive integers") ndims(tau)==1 && length(tau)==Dn && all(tau.>0) && eltype(tau)<:Int ? nothing : error("tau: vector of M positive integers") (r>=0) ? nothing : error("r: must be a positive scalar value") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Nx = N - maximum((m.-1).*tau) Ny = N - maximum(m.*tau) Vex = zeros(Nx,sum(m)) q = 1; for k = 1:Dn for p = 1:m[k] Vex[:,q] = Data[1+(p-1)*tau[k]:Nx+(p-1)*tau[k], k] q += 1 end end Count0 = Distx(Vex,r) B0 = sum(Count0)/(Nx*(Nx-1)/2) B1 = zeros(Dn) Temp = cumsum(m) Vez = Inf.*ones(1,sum(m)+1) for k = 1:Dn Sig = Data[1+m[k]*tau[k]:Ny+m[k]*tau[k], k] Vey = hcat(Vex[1:Ny, 1:Temp[k]], Sig, Vex[1:Ny, Temp[k]+1:end]) Vez = vcat(Vez, Vey) Count1 = Distx(Vey, r); B1[k] = sum(Count1)/(Ny*(Ny-1)/2) end Vez = Vez[2:end,:] Count1 = Distx(Vez, r); Bt = sum(Count1)/(Dn*Ny*((Dn*Ny)-1)/2) MSamp = -log(Bt/B0)/log(Logx) return MSamp, B0, Bt, B1 end function Distx(Vex, r) Nt = size(Vex)[1] Counter = zeros(Bool, Nt-1,Nt-1) for x=1:Nt-1 Counter[x,x:end] = all(abs.(Vex[x+1:end,:] .- Vex[x:x,:]) .<= r, dims=2) end return Counter end end """Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub"""
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
12530
module _PermEn export PermEn using Combinatorics: permutations using Statistics: std, var, mean using DSP: hilbert, unwrap, angle """ Perm, Pnorm, cPE = PermEn(Sig) Returns the permuation entropy estimates `Perm`, the normalised permutation entropy `Pnorm` and the conditional permutation entropy `cPE` for `m` = [1,2] estimated from the data sequence `Sig` using the default parameters: embedding dimension = 2, time delay = 1, logarithm = base 2, normalisation = w.r.t #symbols (`m`-1) Note: using the standard PermEn estimation, `Perm` = 0 when `m` = 1. Note: It is recommeneded that signal length > 5m! (see [8] and Amigo et al., Europhys. Lett. 83:60005, 2008) Perm, Pnorm, cPE = PermEn(Sig, m) Returns the permutation entropy estimates `Perm` estimated from the data sequence `Sig` using the specified embedding dimensions = [1,...,`m`] with other default parameters as listed above. Perm, Pnorm, cPE = PermEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, Typex::String="none", tpx::Union{Real,Nothing}=nothing, Logx::Real=2, Norm::Bool=false) Returns the permutation entropy estimates `Perm` for dimensions = [1,...,`m`] estimated from the data sequence `Sig` using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, an integer > 1 \n `tau` - Time Delay, a positive integer\n `Logx` - Logarithm base, a positive scalar (enter 0 for natural log) \n `Norm` - Normalisation of PermEn value:\n false - normalises w.r.t log(# of permutation symbols [m-1]) - default true - normalises w.r.t log(# of all possible permutations [m!]) * Note: Normalised permutation entropy is undefined for m = 1. ** Note: When Typex = 'uniquant' and Norm = true, normalisation is calculated w.r.t. log(tpx^m)\n `Typex` - Permutation entropy variation, one of the following: {`"none", "uniquant", "finegrain", "modified", "ampaware", "weighted", "edge", "phase"} See the EntropyHub guide for more info on PermEn variations. \n `tpx` - Tuning parameter for associated permutation entropy variation.\n [uniquant] 'tpx' is the L parameter, an integer > 1 (default = 4). [finegrain] 'tpx' is the alpha parameter, a positive scalar (default = 1) [ampaware] 'tpx' is the A parameter, a value in range [0 1] (default = 0.5) [edge] 'tpx' is the r sensitivity parameter, a scalar > 0 (default = 1) [phase] 'tpx' unwraps the instantaneous phase (angle of analytic signal) when tpx==1 (default = 0) See the EntropyHub guide for more info on PermEn variations. \n # See also `XPermEn`, `MSEn`, `XMSEn`, `SampEn`, `ApEn`, `CondEn` # References: [1] Christoph Bandt and Bernd Pompe, "Permutation entropy: A natural complexity measure for time series." Physical Review Letters, 88.17 (2002): 174102. [2] Xiao-Feng Liu, and Wang Yue, "Fine-grained permutation entropy as a measure of natural complexity for time series." Chinese Physics B 18.7 (2009): 2690. [3] Chunhua Bian, et al., "Modified permutation-entropy analysis of heartbeat dynamics." Physical Review E 85.2 (2012) : 021906 [4] Bilal Fadlallah, et al., "Weighted-permutation entropy: A complexity measure for time series incorporating amplitude information." Physical Review E 87.2 (2013): 022911. [5] Hamed Azami and Javier Escudero, "Amplitude-aware permutation entropy: Illustration in spike detection and signal segmentation." Computer methods and programs in biomedicine, 128 (2016): 40-51. [6] Zhiqiang Huo, et al., "Edge Permutation Entropy: An Improved Entropy Measure for Time-Series Analysis," 45th Annual Conference of the IEEE Industrial Electronics Soc, (2019), 5998-6003 [7] Zhe Chen, et al. "Improved permutation entropy for measuring complexity of time series under noisy condition." Complexity 1403829 (2019). [8] Maik Riedl, Andreas Müller, and Niels Wessel, "Practical considerations of permutation entropy." The European Physical Journal Special Topics 222.2 (2013): 249-262. [9] Kang Huan, Xiaofeng Zhang, and Guangbin Zhang, "Phase permutation entropy: A complexity measure for nonlinear time series incorporating phase information." Physica A: Statistical Mechanics and its Applications 568 (2021): 125686. """ function PermEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, Typex::String="none", tpx::Union{Real,Nothing}=nothing, Logx::Real=2, Norm::Bool=false) Logx == 0 ? Logx = exp(1) : nothing N = size(Sig)[1] (N>10) ? nothing : error("Sig: must be a numeric vector") (m > 1) ? nothing : error("m: must be an integer > 1") (tau > 0) ? nothing : error("tau: must be an integer > 0") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") (lowercase(Typex) in ["none","uniquant","finegrain","modified","ampaware","weighted","edge","phase"]) ? nothing : error("Typex: must be one of the following strings - 'uniquant','finegrain','modified','ampaware','weighted','edge','phase'") (isnothing(tpx) || tpx>0) ? nothing : error("tpx: the value of tpx relates to 'Type'. See the EntropyHub guide for further info on the 'tpx' value.") if lowercase(Typex) == "phase" Sig = angle.(hilbert(Sig)) tpx == 1 ? Sig = unwrap(Sig) : nothing end Sx = zeros(N,m) Perm = zeros(m) Pnorm = zeros(m) for k = 1:m Nx = N-(k-1)*tau Sx[1:Nx,k] = Sig[1+(k-1)*tau:N] Temp = sortind(Sx[1:Nx,1:k]) Px = collect(permutations(collect(1:k))) Counter = zeros(length(Px)) if lowercase(Typex) == "uniquant" Temp = sort(Sx[1:Nx,1:k], dims=2) S = zeros(size(Temp)) if isnothing(tpx) tpx = 4; elseif tpx <= 1 || typeof(tpx)!=Int error("When Typex = 'Uniquant', L parameter (tpx) must be an integer > 1") end delta = (maximum(Sig)-minimum(Sig))/tpx S[:,1] = map(x -> searchsortedfirst( minimum(Sig):delta:maximum(Sig),x), Temp[:,1]) .- 1 #S[findall(S[:,1].==0),1] .+= 1 S[S[:,1].==0,1] .+= 1 if k > 1 S[:,2:k] = S[:,1] .+ floor.((Temp[:,2:k] .- Temp[:,1])/delta) end Px = unique(S,dims=1) Counter = zeros(size(Px,1)) for n = 1:size(Px,1) Counter[n] = sum(all(S .- transpose(Px[n,:]).==0,dims=2)) end Counter = Counter[Counter.!=0] Ppi = Counter/sum(Counter) Norm = true # Might need to change back to 3 elseif lowercase(Typex) == "finegrain" if k > 1 if isnothing(tpx) tpx = 1; elseif tpx <= 0 error("When Typex = 'finegrain', Alpha parameter (tpx) must be greater than 0") end q = floor.(maximum(abs.(diff(Sx[1:Nx,1:k],dims=2)),dims=2)./ (tpx*std(abs.(diff(Sig)),corrected=false))) Temp = hcat(Temp, q) Px = unique(Temp,dims=1) Counter = zeros(size(Px,1)) for n = 1:size(Px,1) Counter[n] = sum(all(Temp .- transpose(Px[n,:]).== 0,dims=2)) end Counter = Counter[Counter.!=0] Ppi = Counter./sum(Counter) #clear q n qt else Ppi = 1 end elseif lowercase(Typex) == "modified" Tx = (diff(sort(Sx[1:Nx,1:k],dims=2),dims=2).==0) for km = 1:k-1 Temp[Tx[:,km],km+1] = Temp[Tx[:,km],km]; end Px = unique(Temp,dims=1) Counter = zeros(size(Px,1)) for n = 1:size(Px,1) Counter[n] = sum(all(Temp .- transpose(Px[n,:]) .==0,dims=2)) end Counter = Counter[Counter.!=0] Ppi = Counter/sum(Counter) #clear Tx km elseif lowercase(Typex) == "weighted" if k > 1 Wj = var(Sx[1:Nx,1:k],corrected=false,dims=2) for n = 1:size(Px,1) Counter[n] = sum(Wj[all(Temp .- transpose(Px[n]) .==0,dims=2)]) end Counter = Counter[Counter.!=0] Ppi = Counter/sum(Wj) #clear Wj n else Ppi = 1; end elseif lowercase(Typex) == "ampaware" if k > 1 if isnothing(tpx) tpx = 0.5; elseif tpx<0 || tpx>1 error("When Typex = 'ampaware', the A parameter must be in the range [0 1]") end AA = sum(abs.(Sx[1:Nx,1:k]),dims=2) AB = sum(abs.(diff(Sx[1:Nx,1:k],dims=2)),dims=2) Ax = (tpx*AA/k) + ((1-tpx)*AB/(k-1)); for n = 1:size(Px,1) Counter[n] = sum(Ax[all(Temp.-transpose(Px[n]).==0,dims=2)]) end Counter = Counter[Counter.!=0] Ppi = Counter/sum(Ax); else Ppi = 1; end #clear AA AB Ax elseif lowercase(Typex) == "edge" if isnothing(tpx) tpx = 1; elseif tpx <=0 error("When Typex = 'Edge', the r sensitivity parameter (tpx) must be > 0") end if k > 1 for n = 1:size(Px,1) Sy = Sx[1:Nx,1:k] Tx = diff(Sy[all(Temp .- transpose(Px[n]) .==0,dims=2)[:],:],dims=2) Counter[n] = sum(mean(hypot.(Tx,1),dims=2).^tpx) end Counter = Counter[Counter.!=0] Ppi = Counter/sum(Counter) else Ppi = 1; end else for n = 1:size(Px,1) Counter[n] = sum(all(Temp .- transpose(Px[n]).==0,dims=2)); #sum(all(Temp .- transpose(Px[n]).==0,dims=2)); end Counter = Counter[Counter.!=0] Ppi = Counter/sum(Counter) end if round(sum(Ppi),digits=3) != 1 @warn ("Potential error with probability calculation") end Perm[k] = -sum(Ppi.*(log.(Logx, Ppi))); if Norm if Norm && lowercase(Typex)=="uniquant" Pnorm[k] = Perm[k]/(log(Logx, tpx^k)); else Pnorm[k] = Perm[k]/(log(Logx, factorial(k))); end else Pnorm[k] = Perm[k]/(k-1); end end cPE = diff(Perm); return Perm, Pnorm, cPE end function sortind(X) Y = zeros(Int, size(X)) for k = 1:length(X[:,1]) Y[k,:] = sortperm(X[k,:]) end return Y end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
6715
module _PermEn2D export PermEn2D """ Perm2D = PermEn2D(Mat) Returns the bidimensional permutation entropy estimate (`Perm2D`) estimated for the data matrix (`Mat`) using the default parameters: time delay = 1, logarithm = natural, template matrix size = [floor(H/10) floor(W/10)], (where H and W represent the height (rows) and width (columns) of the data matrix `Mat`) \n ** The minimum dimension size of Mat must be > 10.** Perm2D = PermEn2D(Mat::AbstractArray{T,2} where T<:Real; m::Union{Int,Tuple{Int,Int}}=floor.(Int, size(Mat)./10), tau::Int=1, Norm::Bool=true, Logx::Real=exp(1), Lock::Bool=true) Returns the bidimensional permutation entropy (`Perm2D`) estimates for the data matrix (`Mat`) using the specified 'keyword' arguments: # Arguments: `m` - Template submatrix dimensions, an integer scalar (i.e. the same height and width) or a two-element vector of integers [height, width] with a minimum value > 1. (default: [floor(H/10) floor(W/10)]) \n `tau` - Time Delay, a positive integer (default: 1) \n `Norm` - Normalization of permutation entropy estimate, a boolean (default: true) \n `Logx` - Logarithm base, a positive scalar (default: natural) \n `Lock` - By default, PermEn2D only permits matrices with a maximum size of 128 x 128 to prevent memory errors when storing data on RAM. e.g. For Mat = [200 x 200], m = 3, and tau = 1, SampEn2D creates a vector of 753049836 elements. To enable matrices greater than [128 x 128] elements, set `Lock` to false. (default: true) \n `WARNING: unlocking the permitted matrix size may cause your Julia IDE to crash.`\n\n **NOTE** - The original bidimensional permutation entropy algorithms [1][2] do not account for equal-valued elements of the embedding matrices. To overcome this, `PermEn2D` uses the lowest common rank for such instances. For example, given an embedding matrix A where, A = [3.4 5.5 7.3] |2.1 6 9.9| [7.3 1.1 2.1] would normally be mapped to an ordinal pattern like so, [3.4 5.5 7.3 2.1 6 9.9 7.3 1.1 2.1] => [ 8 4 9 1 2 5 3 7 6 ] However, indices 4 & 9, and 3 & 7 have the same values, 2.1 and 7.3 respectively. Instead, PermEn2D uses the ordinal pattern [ 8 4 4 1 2 5 3 3 6 ] where the lowest rank (4 & 3) are used instead (of 9 & 7). Therefore, the number of possible permutations is no longer (mx*my)!, but (mx*my)^(mx*my). Here, the PermEn2D value is normalized by the maximum Shannon entropy (Smax = log((mx*my)!) ``assuming that no equal values are found in the permutation motif matrices``, as presented in [1]. # See also `SampEn2D`, `FuzzEn2D`, `DispEn2D`, `DistEn2D` # References: [1] Haroldo Ribeiro et al., "Complexity-Entropy Causality Plane as a Complexity Measure for Two-Dimensional Patterns" PLoS ONE (2012), 7(8):e40689, [2] Luciano Zunino and Haroldo Ribeiro, "Discriminating image textures with the multiscale two-dimensional complexity-entropy causality plane" Chaos, Solitons and Fractals, 91:679-688 (2016) [3] Matthew Flood and Bernd Grimm, "EntropyHub: An Open-source Toolkit for Entropic Time Series Analysis" PLoS ONE (2021) 16(11): e0259448. """ function PermEn2D(Mat::AbstractArray{T,2} where T<:Real; m::Union{Int,Tuple{Int,Int}}=floor.(Int, size(Mat)./10), tau::Int=1, Norm::Bool=true, Logx::Real=exp(1), Lock::Bool=true) NL, NW = size(Mat) ((NL > 128 || NW > 128) && Lock) ? error("To prevent memory errors, matrix width & length must have <= 128 elements. To estimate SampEn2D for the current matrix ($NL,$NW) change Lock to 'false'. Caution: unlocking the safe matrix size may cause the Julia IDE to crash.") : nothing length(m)==1 ? (mL = m; mW = m) : (mL = m[1]; mW = m[2]) (NL > 10 && NW > 10) ? nothing : error("Number of rows and columns in Mat must be > 10") (minimum(m)>1) ? nothing : error("m: must be an integer > 1, or a 2 element tuple of integer values > 1") (tau > 0) ? nothing : error("tau: must be an integer > 0") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") NL = NL - (mL-1)*tau NW = NW - (mW-1)*tau Temp = Mat[1:tau:(mL-1)*tau+1,1:tau:(mW-1)*tau+1] Sord = sort(Temp[:]) Dix = sortperm(Temp[:]) if any(diff(Sord).==0) for x in findall(diff(Sord).==0).+1 Dix[x] = Dix[x-1] end end Counter = [0] for k in 1:NL for n in 1:NW Temp = Mat[k:tau:(mL-1)*tau+k,n:tau:(mW-1)*tau+n] Sord = sort(Temp[:]) Dx = sortperm(Temp[:]) if any(diff(Sord).==0) for x in findall(diff(Sord).==0).+1 Dx[x] = Dx[x-1] end end if any(all((Dix .- Dx).==0,dims=1)) Counter .+= all((Dix .- Dx).==0,dims=1).*1 else Dix = [Dix Dx] Counter = [Counter 1] end end end sum(Counter) != NL*NW ? @warn("Potential error with permutation comparisons.") : nothing Pi = Counter/sum(Counter) Perm2D = -sum(Pi.*log.(Logx, Pi)) Norm ? Perm2D /= log(Logx, factorial(big(mL*mW))) : nothing return Perm2D end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
4185
module _PhasEn export PhasEn using Plots using Random: randperm """ Phas = PhasEn(Sig) Returns the phase entropy (`Phas`) estimate of the data sequence (`Sig`) using the default parameters: angular partitions = 4, time delay = 1, logarithm = natural, Phas = PhasEn(Sig::AbstractArray{T,1} where T<:Real; K::Int=4, tau::Int=1, Logx::Real=exp(1), Norm::Bool=true, Plotx::Bool=false) Returns the phase entropy (`Phas`) estimate of the data sequence (`Sig`) using the specified 'keyword' arguments: # Arguments: `K` - Angular partitions (coarse graining), an integer > 1 \n *Note: Division of partitions begins along the positive x-axis. As this point is somewhat arbitrary, it is recommended to use even-numbered (preferably multiples of 4) partitions for sake of symmetry. \n `tau` - Time Delay, a positive integer \n `Logx` - Logarithm base, a positive scalar \n `Norm` - Normalisation of `Phas` value: \n [false] no normalisation [true] normalises w.r.t. the number of partitions Log(`K`) `Plotx` - When `Plotx` == true, returns Poincaré plot (default: false) \n # See also `SampEn`, `ApEn`, `GridEn`, `MSEn`, `SlopEn`, `CoSiEn`, `BubbEn` # References: [1] Ashish Rohila and Ambalika Sharma, "Phase entropy: a new complexity measure for heart rate variability." Physiological measurement 40.10 (2019): 105006. """ function PhasEn(Sig::AbstractArray{T,1} where T<:Real; K::Int=4, tau::Int=1, Logx::Real=exp(1), Norm::Bool=true, Plotx::Bool=false) N = size(Sig,1) (N > 10) ? nothing : error("Sig: must be a numeric vector") (K > 1) ? nothing : error("K: must be an integer > 1") (tau >0) ? nothing : error("tau: must be an integer > 0") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Yn = Sig[1+2*tau:end] .- Sig[tau+1:end-tau] Xn = Sig[tau+1:end-tau] .- Sig[1:end-2*tau] Theta_r = atan.(Yn./Xn) Theta_r[(Yn.<0) .& (Xn.<0)] .+= pi Theta_r[(Yn.<0) .& (Xn.>0)] .+= 2*pi Theta_r[(Yn.>0) .& (Xn.<0)] .+= pi Limx = ceil.(maximum(abs.(vcat(Yn, Xn)))) Angs = range(0,2*pi,length=K+1) Tx = zeros(Int, K, length(Theta_r)) Si = zeros(K) for n = 1:K Temp = (Theta_r .> Angs[n]) .& (Theta_r .< Angs[n+1]); Tx[n,Temp] .= 1 Si[n] = sum(Theta_r[Temp]) end Si = Si[Si.!=0] Phas = -sum((Si./sum(Si)).*(log.(Logx, Si./sum(Si)))) if Norm Phas = Phas/(log(Logx, K)) end if Plotx Ys = sin.(Angs)*Limx*sqrt(2); Xs = cos.(Angs)*Limx*sqrt(2); Cols = hcat(zeros(K), repeat(randperm(K)/K,outer=(1,2))) Tx = Bool.(Tx) xx = plot() for n = 1:K plot!(Xn[Tx[n,:]], Yn[Tx[n,:]], seriestype =:scatter, markersize = 2, markercolor=RGB(Cols[n,:]...,), markerstrokecolor=RGB(Cols[n,:]...,)) end #plot!(hcat(zeros(K+1), Xs), hcat(Ys,zeros(K+1)),c=:magenta, plot!(hcat(Xs,zeros(K+1))', hcat(Ys,zeros(K+1))',c=:magenta, xlim = (-Limx, Limx), ylim = (-Limx, Limx), size = (400, 400), legend=false, xticks = [-Limx, 0, Limx], yticks = [-Limx, 0 ,Limx], grid = false) xlabel!("X ₙ₊ₜ - X ₙ") ylabel!("X ₙ₊₂ₜ - X ₙ₊ₜ") display(xx) end return Phas end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
5285
module _RangEn export RangEn using Statistics: mean """ Rangx, A, B = RangEn(Sig) Returns the range entropy estimate (`Rangx`) and the number of matched state vectors (`m: B`, `m+1: A`) estimated from the data sequence (`Sig`) using the sample entropy algorithm and the following default parameters: embedding dimension = 2, time delay = 1, radius threshold = 0.2, logarithm = natural. Rangx, A, B = RangEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Real=0.2, Methodx::String="SampEn", Logx::Real=exp(1)) Returns the range entropy estimates (`Rangx`) for dimensions = `m` estimated for the data sequence (`Sig`) using the specified keyword arguments: # Arguments: `m` - Embedding Dimension, a positive integer\n `tau` - Time Delay, a positive integer\n `r` - Radius Distance Threshold, a positive value between 0 and 1\n `Methodx` - Base entropy method, either 'SampEn' [default] or 'ApEn'\n `Logx` - Logarithm base, a positive scalar \n # See also `ApEn`, `SampEn`, `FuzzEn`, `MSEn` # References: [1] Omidvarnia, Amir, et al. "Range entropy: A bridge between signal complexity and self-similarity" Entropy 20.12 (2018): 962. [2] Joshua S Richman and J. Randall Moorman. "Physiological time-series analysis using approximate entropy and sample entropy." American Journal of Physiology-Heart and Circulatory Physiology 2000 """ function RangEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Real=0.2, Methodx::String="SampEn", Logx::Real=exp(1)) N = length(Sig) (N>10) ? nothing : error("Sig: must be a numeric vector") (m > 0) ? nothing : error("m: must be an integer > 0") (tau > 0) ? nothing : error("tau: must be an integer > 0") (r>=0) && (r<=1) ? nothing : error("r: must be a scalar must be a value between 0 and 1") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") (lowercase(Methodx) in ["sampen", "apen"]) ? nothing : error("Methodx must be either 'ApEn' or 'SampEn'") if lowercase(Methodx) == "sampen" Nx = N - m*tau Sx = zeros(Nx,m+1) for k = 1:m+1 Sx[:,k] = Sig[1 + (k-1)*tau:Nx + (k-1)*tau] end A = zeros(Int, Nx) B = zeros(Int, Nx) for k = 1:(Nx - 1) Dxy = abs.(repeat(Sx[k,1:end-1],1,Nx-k) .- Sx[k+1:end,1:end-1]')' Mx = maximum(Dxy,dims=2) Mn = minimum(Dxy,dims=2) RR = (Mx .- Mn)./(Mx .+ Mn) .<= r B[k] = sum(RR) if B[k]>0 Dxy2 = abs.(repeat(Sx[k,:],1,B[k]) .- Sx[k+1:end,:][RR[:],:]')'#Sx[k+1:end,:][all.(eachrow(RR)),:]')' Mx = maximum(Dxy2,dims=2) Mn = minimum(Dxy2,dims=2) RR2 = (Mx .- Mn)./(Mx .+ Mn) .<= r A[k] = sum(RR2) end end Rangx = -log(sum(A)/sum(B))/log(Logx) return Rangx, A, B elseif lowercase(Methodx) == "apen" Nx = N - (m-1)*tau Sx = zeros(Nx,m) for k = 1:m Sx[:,k] = Sig[1 + (k-1)*tau:Nx + (k-1)*tau] end Sx = hcat(Sx, vcat(Sig[m*tau + 1:end],zeros(tau))) B = zeros(Int, Nx) A = zeros(Int, Nx-tau) for k in 1:Nx Dxy = abs.(repeat(Sx[k,1:end-1],1,Nx)' .- Sx[:,1:end-1]) Mx = maximum(Dxy,dims=2) Mn = minimum(Dxy,dims=2) RR = (Mx .- Mn)./(Mx .+ Mn) .<= r B[k] = sum(RR) if k <= (Nx - tau) RR[end-tau+1:end] .= false Dxy2 = abs.(repeat(Sx[k,:],1,sum(RR))' .- Sx[RR[:],:]) #Sx[all.(eachrow(RR)),:]) Mx2 = maximum(Dxy2,dims=2) Mn2 = minimum(Dxy2,dims=2) RR2 = (Mx2 .- Mn2)./(Mx2 .+ Mn2) .<= r A[k] = sum(RR2) end end Ax = mean(log.(A./(Nx-tau))/log(Logx)) Bx = mean(log.(B./Nx)/log(Logx)) Ap = Bx - Ax return Ap, A, B else error("Methodx must be either 'ApEn' or 'SampEn'") end end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
5679
module _SampEn export SampEn using Statistics: mean, std using LinearAlgebra: UpperTriangular, I """ Samp, A, B = SampEn(Sig) Returns the sample entropy estimates `Samp` and the number of matched state vectors (`m`:B, `m+1`:A) for `m` = [0,1,2] estimated from the data sequence `Sig` using the default parameters: embedding dimension = 2, time delay = 1, radius threshold = 0.2*SD(`Sig`), logarithm = natural Samp, A, B, (Vcp, Ka, Kb) = SampEn(Sig, ..., Vcp = true) If `Vcp == true`, an additional tuple `(Vcp, Ka, Kb)` is returned with the sample entropy estimates (`Samp`) and the number of matched state vectors (`m: B`, `m+1: A`). `(Vcp, Ka, Kb)` contains the variance of the conditional probabilities (`Vcp`), i.e. CP = A/B, and the number of **overlapping** matching vector pairs of lengths m+1 (`Ka`) and m (`Kb`), respectively. Note `Vcp` is undefined for the zeroth embedding dimension (m = 0) and due to the computational demand, **will take substantially more time to return function outputs.** See Appendix B in [2] for more info. Samp, A, B = SampEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Real=0.2*std(Sig,corrected=false), Logx::Real=exp(1), Vcp::Bool=false) Returns the sample entropy estimates `Samp` for dimensions = [0,1,...,`m`] estimated from the data sequence `Sig` using the specified keyword arguments: # Arguments: `m` - Embedding Dimension, a positive integer\n `tau` - Time Delay, a positive integer\n `r` - Radius Distance Threshold, a positive scalar \n `Logx` - Logarithm base, a positive scalar \n `Vcp` - Option to return the variance of the conditional probabilities and the number of overlapping matching vector pairs of lengths \n # See also `ApEn`, `FuzzEn`, `PermEn`, `CondEn`, `XSampEn`, `SampEn2D`, `MSEn` # References: [1] Joshua S Richman and J. Randall Moorman. "Physiological time-series analysis using approximate entropy and sample entropy." American Journal of Physiology-Heart and Circulatory Physiology (2000). [2] Douglas E Lake, Joshua S Richman, M.P. Griffin, J. Randall Moorman "Sample entropy analysis of neonatal heart rate variability." American Journal of Physiology-Regulatory, Integrative and Comparative Physiology 283, no. 3 (2002): R789-R797. """ function SampEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, r::Real=0.2*std(Sig,corrected=false), Logx::Real=exp(1), Vcp::Bool=false) N = length(Sig) (N>10) ? nothing : error("Sig: must be a numeric vector") (m > 0) ? nothing : error("m: must be an integer > 0") (tau > 0) ? nothing : error("tau: must be an integer > 0") (r>=0) ? nothing : error("r: must be a positive scalar value") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Counter = 1*(abs.(Sig .- transpose(Sig)) .<= r).*UpperTriangular(ones(N,N)) - I(N) M = Int.([m*ones(N-m*tau); repeat(collect(m-1:-1:1),inner=tau)]) A = zeros(m + 1) B = zeros(m + 1) A[1] = sum(Counter) B[1] = N*(N-1)/2 for n = 1:N-tau ix = findall(Counter[n, :] .== 1) for k = 1:M[n] ix = ix[ix .+ (k*tau) .<= N] p1 = repeat(transpose(Sig[n:tau:n+(tau*k)]), length(ix)) p2 = Sig[ix .+ transpose(collect(0:tau:(k*tau)))] ix = ix[findall(maximum(abs.(p1 - p2),dims=2) .<= r)] if length(ix)>0 Counter[n, ix] .+= 1 else break end end end for k = 1:m A[k+1] = sum(Counter.>k) B[k+1] = sum(Counter[:,1:N-(k*tau)].>=k) end Samp = -log.(Logx, A./B) if Vcp Temp = hcat(getindex.(findall(Counter.>m),1), getindex.(findall(Counter.>m),2)) if length(Temp[:,1])>1 Ka = zeros(Int, length(Temp[:,1]) -1) for k = 1:size(Temp,1)-1 # (length(Temp[:,1])-1) TF = (abs.(Temp[k+1:end,:] .- Temp[k,1]) .<= m*tau) .+ (abs.(Temp[k+1:end,:] .- Temp[k,2]) .<= m*tau) Ka[k] = sum(any(TF.>0, dims=2)) end else Ka = 0 end Temp = hcat(getindex.(findall(Counter[:,1:end-m*tau].>=m),1), getindex.(findall(Counter[:,1:end-m*tau].>=m),2)) if length(Temp[:,1])>1 Kb = zeros(Int, length(Temp[:,1]) -1) for k = 1:size(Temp,1)-1 # (length(Temp[:,1]) -1) TF = (abs.(Temp[k+1:end,:] .- Temp[k,1]) .<= (m-1)*tau) + (abs.(Temp[k+1:end,:] .- Temp[k,2]) .<= (m-1)*tau) Kb[k] = sum(any(TF.>0, dims=2)) end else Kb = 0 end Ka = sum(Ka) Kb = sum(Kb) CP = A[end]/B[end] Vcp = (CP*(1-CP)/B[end]) + (Ka - Kb*(CP^2))/(B[end]^2) return Samp, A, B, (Vcp, Ka, Kb) else return Samp, A, B # return Samp, A, B end end end """Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub"""
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
4916
module _SampEn2D export SampEn2D using Statistics: mean, std """ SE2D, Phi1, Phi2 = SampEn2D(Mat) Returns the bidimensional sample entropy estimate (`SE2D`) and the number of matched sub-matricess (m:Phi1, m+1:Phi2) estimated for the data matrix (`Mat`) using the default parameters: time delay = 1, radius distance threshold = 0.2*SD(`Mat`), logarithm = natural matrix template size = [floor(H/10) floor(W/10)], (where H and W represent the height (rows) and width (columns) of the data matrix `Mat`) \n ** The minimum dimension size of Mat must be > 10.** SE2D, Phi1, Phi2 = SampEn2D(Mat::AbstractArray{T,2} where T<:Real; m::Union{Int,Tuple{Int,Int}}=floor.(Int, size(Mat)./10), tau::Int=1, r::Real=0.2*std(Mat,corrected=false), Logx::Real=exp(1), Lock::Bool=true) Returns the bidimensional sample entropy (`SE2D`) estimates for the data matrix (`Mat`) using the specified 'keyword' arguments: # Arguments: `m` - Template submatrix dimensions, an integer scalar (i.e. the same height and width) or a two-element vector of integers [height, width] with a minimum value > 1. (default: [floor(H/10) floor(W/10)]) \n `tau` - Time Delay, a positive integer (default: 1) \n `r` - Distance Threshold, a positive scalar (default: 0.2*SD(Mat)) \n `Logx` - Logarithm base, a positive scalar (default: natural) \n `Lock` - By default, SampEn2D only permits matrices with a maximum size of 128 x 128 to prevent memory errors when storing data on RAM. e.g. For Mat = [200 x 200], m = 3, and tau = 1, SampEn2D creates a vector of 753049836 elements. To enable matrices greater than [128 x 128] elements, set `Lock` to false. (default: true) \n `WARNING: unlocking the permitted matrix size may cause your Julia IDE to crash.` # See also `SampEn`, `FuzzEn2D`, `XSampEn`, `MSEn` # References: [1] Luiz Eduardo Virgili Silva, et al., "Two-dimensional sample entropy: Assessing image texture through irregularity." Biomedical Physics & Engineering Express 2.4 (2016): 045002. """ function SampEn2D(Mat::AbstractArray{T,2} where T<:Real; m::Union{Int,Tuple{Int,Int}}=floor.(Int, size(Mat)./10), tau::Int=1, r::Real=0.2*std(Mat,corrected=false), Logx::Real=exp(1), Lock::Bool=true) NL, NW = size(Mat) ((NL > 128 || NW > 128) && Lock) ? error("To prevent memory errors, matrix width & length must have <= 128 elements. To estimate SampEn2D for the current matrix ($NL,$NW) change Lock to 'false'. Caution: unlocking the safe matrix size may cause the Julia IDE to crash.") : nothing length(m)==1 ? (mL = m; mW = m) : (mL = m[1]; mW = m[2]) (NL > 10 && NW > 10) ? nothing : error("Number of rows and columns in Mat must be > 10") (minimum(m)>1) ? nothing : error("m: must be an integer > 1, or a 2 element tuple of integer values > 1") (tau > 0) ? nothing : error("tau: must be an integer > 0") (r >= 0) ? nothing : error("r: must be a positive value") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") NL = NL - mL*tau NW = NW - mW*tau X = zeros(mL+1,mW+1,NL*NW) p = 0 for k = 1:NL for n = 1:NW p += 1 X[:,:,p] = Mat[k:tau:(mL)*tau+k,n:tau:(mW)*tau+n] end end p = size(X,3) p != NL*NW ? @warn("Potential error with submatrix division.") : nothing Ny = p*(p-1)/2 Ny > 300000000 ? @warn("Number of pairwise distance calculations is $Ny") : nothing Y1 = zeros(p-1) Y2 = zeros(p-1) for k = 1:p-1 Temp = maximum(abs.(X[1:mL,1:mW,k+1:p] .- X[1:mL,1:mW,k]), dims=(1,2))[:] .< r Y1[k] = sum(Temp); Temp = findall(Temp.>0) .+ k Y2[k] = sum(maximum(abs.(X[:,:,Temp] .- X[:,:,k]),dims=(1,2)) .< r) end Phi1 = sum(Y1)/Ny Phi2 = sum(Y2)/Ny SE2D = -log(Logx, Phi2/Phi1) return SE2D, Phi1, Phi2 end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
3814
module _SlopEn export SlopEn using GroupSlices """ Slop = SlopEn(Sig) Returns the slope entropy (`Slop`) estimates for embedding dimensions [2, ..., m] of the data sequence (`Sig`) using the default parameters: embedding dimension = 2, time delay = 1, angular thresholds = [5 45], logarithm = base 2 Slop = SlopEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, Lvls::AbstractArray{T,1} where T<:Real=[5, 45], Logx::Real=2, Norm::Bool=true) Returns the slope entropy (`Slop`) estimate of the data sequence (`Sig`) using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, an integer > 1 \n SlopEn returns estimates for each dimension [2,...,m] `tau` - Time Delay, a positive integer \n `Lvls` - Angular thresolds, a vector of monotonically increasing values in the range [0 90] degrees.\n `Logx` - Logarithm base, a positive scalar (enter 0 for natural log) \n `Norm` - Normalisation of SlopEn value, a boolean operator: \n [false] no normalisation [true] normalises w.r.t. the number of patterns found (default) # See also `PhasEn`, `GridEn`, `MSEn`, `CoSiEn`, `SampEn`, `ApEn` # References: [1] David Cuesta-Frau, "Slope Entropy: A New Time Series Complexity Estimator Based on Both Symbolic Patterns and Amplitude Information." Entropy 21.12 (2019): 1167. """ function SlopEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, Lvls::AbstractArray{T,1} where T<:Real=[5, 45], Logx::Real=2, Norm::Bool=true) Logx == 0 ? Logx = exp(1) : nothing (size(Sig,1) >10) ? nothing : error("Sig: must be a numeric vector") (m > 1) ? nothing : error("m: must be an integer > 1") (tau>0) ? nothing : error("tau: must be an integer > 0") (length(Lvls)>1 && all(diff(Lvls).>0) && all(0 .< Lvls .< 90)) ? nothing : error("Lvls: must be a vector of 2 or more monotonically increasing values in the range [0 90] degrees") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") m = m-1; Tx = atand.(Sig[1+tau:end] .- Sig[1:end-tau]) N = size(Tx,1) Sx = zeros(Int,N,m) Symbx = zeros(Int,size(Tx)); Slop = zeros(m) sort!(Lvls) for q = 2:length(Lvls) Symbx[(Tx.<= Lvls[q]) .& (Tx .> Lvls[q-1])] .= q-1 Symbx[(Tx.>=-Lvls[q]) .& (Tx .<-Lvls[q-1])] .= -(q-1) if q == length(Lvls) Symbx[Tx.> Lvls[q]] .= q Symbx[Tx.<-Lvls[q]] .= -q end end for k = 1:m Sx[1:N-k+1,k] = Symbx[k:N] Locs = groupslices(Sx[1:N-k+1,1:k]) p = [] [push!(p, sum(Locs.==n)) for n in unique(Locs)] Norm ? p ./=(N-k+1) : p./= length(p) if Norm && round(sum(p)) != 1 @warn("Potential Error: Some permutations not accounted for!") print(round(sum(p))) end Slop[k] = -sum(p.*log.(Logx, p)) end return Slop end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
4171
module _SpecEn export SpecEn using FFTW: fft using DSP: conv """ Spec, BandEn = SpecEn(Sig) Returns the spectral entropy estimate of the full spectrum (`Spec`) and the within-band entropy (`BandEn`) estimated from the data sequence (`Sig`) using the default parameters: N-point FFT = 2*len(`Sig`) + 1, normalised band edge frequencies = [0 1], logarithm = base 2, normalisation = w.r.t # of spectrum/band frequency values. Spec, BandEn = SpecEn(Sig::AbstractArray{T,1} where T<:Real; N::Int=1 + (2*size(Sig,1)), Freqs::Tuple{Real,Real}=(0,1), Logx::Real=exp(1), Norm::Bool=true) Returns the spectral entropy (`Spec`) and the within-band entropy (`BandEn`) estimate for the data sequence (`Sig`) using the specified 'keyword' arguments: # Arguments: `N` - Resolution of spectrum (N-point FFT), an integer > 1 \n `Freqs` - Normalised band edge frequencies, a 2 element tuple with values \n in range [0 1] where 1 corresponds to the Nyquist frequency (Fs/2). Note: When no band frequencies are entered, BandEn == SpecEn `Logx` - Logarithm base, a positive scalar (enter 0 for natural log) \n `Norm` - Normalisation of `Spec` value:\n [false] no normalisation. [true] normalises w.r.t # of spectrum/band frequency values - default. For more info, see the EntropyHub guide. # See also `XSpecEn`, `fft`, `MSEn`, `XMSEn` # References: [1] G.E. Powell and I.C. Percival, "A spectral entropy method for distinguishing regular and irregular motion of Hamiltonian systems." Journal of Physics A: Mathematical and General 12.11 (1979): 2053. [2] Tsuyoshi Inouye, et al., "Quantification of EEG irregularity by use of the entropy of the power spectrum." Electroencephalography and clinical neurophysiology 79.3 (1991): 204-210. """ function SpecEn(Sig::AbstractArray{T,1} where T<:Real; N::Int=1 + (2*size(Sig,1)), Freqs::Tuple{Real,Real}=(0,1), Logx::Real=exp(1), Norm::Bool=true) (size(Sig)[1] > 4) ? nothing : error("Sig: must be a numeric vector") (N > 1) ? nothing : error("N: must be an integer > 1") (0<=Freqs[1]<1 && 0<Freqs[2]<=1 && Freqs[1]<Freqs[2]) ? nothing : error("Freq: must be a two element tuple with values in range [0 1]. The values must be in increasing order.") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Freqs = collect(Freqs) Fx = Int(ceil(N/2)) Freqs = Int.(round.(Freqs.*Fx)) Freqs[Freqs.==0] .= 1 if Freqs[1] > Freqs[2] error("Lower band frequency must come first.") elseif Freqs[2]-Freqs[1]<1 error("Spectrum resoution too low to determine bandwidth.") elseif minimum(Freqs)<0 || maximum(Freqs)>Fx error("Freqs must be normalized w.r.t sampling frequency [0 1].") end Temp = conv(Sig,Sig) N <= size(Temp,1) ? Temp = Temp[1:N] : Temp = vcat(Temp,zeros(N-size(Temp)[1])) Pt = abs.(fft(Temp)) Pxx = Pt[1:Fx]/sum(Pt[1:Fx]) Spec = -(transpose(Pxx)*log.(Logx, Pxx)) Pband = (Pxx[Freqs[1]:Freqs[2]])/sum(Pxx[Freqs[1]:Freqs[2]]) BandEn = -(transpose(Pband)*log.(Logx, Pband)) if Norm Spec = Spec/(log(Logx, Fx)); BandEn = BandEn/(log(Logx, Freqs[2]-Freqs[1]+1)); end return Spec, BandEn end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
5520
module _SyDyEn export SyDyEn using Clustering: kmeans, assignments using StatsBase: Histogram, fit using Statistics: mean """ SyDy, Zt = SyDyEn(Sig) Returns the symbolic dynamic entropy (`SyDy`) and the symbolic sequence (`Zt`) of the data sequence (`Sig`) using the default parameters: embedding dimension = 2, time delay = 1, symbols = 3, logarithm = natural, symbolic partition type = maximum entropy partitioning (`MEP`), normalisation = normalises w.r.t # possible vector permutations (c^m) SyDy, Zt = SyDyEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, c::Int=3, Typex::String="MEP", Logx::Real=exp(1), Norm::Bool=true) Returns the symbolic dynamic entropy (`SyDy`) and the symbolic sequence (`Zt`) of the data sequence (`Sig`) using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, a positive integer \n `tau` - Time Delay, a positive integer \n `c` - Number of symbols, an integer > 1 \n `Typex` - Type of symbolic sequnce partitioning method, one of the following: \n {"linear","uniform","MEP"(default),"kmeans"} `Logx` - Logarithm base, a positive scalar \n `Norm` - Normalisation of SyDyEn value: \n [false] no normalisation [true] normalises w.r.t # possible vector permutations (c^m+1) - default See the EntropyHub guide for more info on these parameters. # See also `DispEn`, `PermEn`, `CondEn`, `SampEn`, `MSEn` # References: [1] Yongbo Li, et al., "A fault diagnosis scheme for planetary gearboxes using modified multi-scale symbolic dynamic entropy and mRMR feature selection." Mechanical Systems and Signal Processing 91 (2017): 295-312. [2] Jian Wang, et al., "Fault feature extraction for multiple electrical faults of aviation electro-mechanical actuator based on symbolic dynamics entropy." IEEE International Conference on Signal Processing, Communications and Computing (ICSPCC), 2015. [3] Venkatesh Rajagopalan and Asok Ray, "Symbolic time series analysis via wavelet-based partitioning." Signal processing 86.11 (2006): 3309-3320. """ function SyDyEn(Sig::AbstractArray{T,1} where T<:Real; m::Int=2, tau::Int=1, c::Int=3, Typex::String="MEP", Logx::Real=exp(1), Norm::Bool=true) N = size(Sig,1) (N > 10) ? nothing : error("Sig: must be a numeric vector") (m > 0) ? nothing : error("m: must be an integer > 0") (tau > 0) ? nothing : error("tau: must be an integer > 0") (c > 1) ? nothing : error("c: must be an integer > 1") (lowercase(Typex) in ["linear", "kmeans", "uniform","mep"]) ? nothing : error("Typex: must be one of the following strings - 'linear','kmeans','uniform','MEP'") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Nx = N-((m-1)*tau) Zt = zeros(N) if lowercase(Typex) == "linear" Edges = range(minimum(Sig),maximum(Sig),length=c+1) Zt = map(x -> sum(Edges[1:c].<=x), Sig) elseif lowercase(Typex) == "uniform" Ix = sortperm(Sig) Edges = range(1,N,length=c+1) z = map(x -> sum(Edges[1:c].<=x), 1:N) Zt[Ix] .= z elseif lowercase(Typex) == "kmeans" Tx = kmeans(transpose(Sig), c; maxiter=200) z = Int.(assignments(Tx)) ix = sortperm(Tx.centers[:]); Zt = zeros(Int,N) for k = 1:c Zt[z.==ix[k]] .= k; end else Tx = sort(Sig) Edges = Tx[vcat(1, Int.(ceil.((1:c-1)*N/c)),N)] Zt = map(x -> sum(Edges[1:end-1].<=x), Sig) end Zm = zeros(Int,Nx,m); for n = 1:m Zm[:,n] = Zt[(n-1)*tau + 1:Nx+(n-1)*tau] end T = unique(Zm,dims=1) Counter = zeros(size(T,1)) Counter2 = zeros(size(T,1),c) Bins = range(0.5,c+.5,step=1) for n = 1:size(T,1) Ordx = all(Zm .- transpose(T[n,:]).==0,dims=2) Counter[n] = mean(Ordx) Temp = Zm[vcat(falses(m*tau), Ordx[1:end-(m*tau)]),1] Counter2[n,:] = fit(Histogram,Temp,Bins).weights end Counter2 ./= sum(Counter2,dims=2) Counter2[isnan.(Counter2)] .= 0 P1 = -sum(Counter.*log.(Logx, Counter)) P2 = log.(Logx, repeat(Counter,outer=(1,c)).*Counter2) P2[isinf.(P2)] .= 0 SyDy = P1 .- transpose(Counter)*(sum(P2,dims=2)) if round(sum(Counter),digits=4) != 1 || maximum(round.(sum(Counter2,dims=2),digits=4)) != 1 print(maximum(sum(Counter2,dims=2))) @warn("Potential Error calculating probabilities") end if Norm SyDy = SyDy/(log(Logx, c^(m+1))) end return SyDy, Zt end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
4152
module _WindowData export WindowData """ WinData, Log = WindowData(Data) Windows the sequence(s) given in `Data` into a collection of subsequnces of floor(N/5) elements with no overlap, excluding any remainder elements that do not fill the final window. If `Data` is a univariate sequence (vector), `Windata` is a vector of 5 vectors. If `Data` is a set of multivariate sequences (NxM matrix), each of M columns is treated as a sequence with N elements and `WinData` is a vector of 5 matrices of size [(floor*N,5), M]. The `Log` dictionary contains information about the windowing process, including: `DataType` - The type of data sequence passed as `Data`\n `DataLength` - The number of sequence elements in `Data`\n `WindowLength` - The number of elements in each window of `WinData`\n `WindowOverlap` - The number of overlapping elements between windows\n `TotalWindows` - The number of windows extracted from `Data`\n `Mode` - Decision to include or exclude any remaining sequence elements (`< WinLen`) that do not fill the window.\n WinData, Log = WindowData(Data::AbstractArray{T} where T<:Real, WinLen::Union{Nothing,Int}=nothing, Overlap::Int=0, Mode::String="exclude") Windows the sequence(s) given in `Data` into a collection of subsequnces using the specified keyword arguments: # Arguments: `WinLen` - Number of elements in each window, a positive integer (>10)\n `Overlap` - Number of overlapping elements between windows, a positive integer (< WinLen)\n `Mode` - Decision to include or exclude any remaining sequence elements (< `WinLen`) that do not fill the window, a string - either `"include"` or `"exclude"` (default).\n # See also `ExampleData` """ function WindowData(Data::AbstractArray{T} where T<:Real; WinLen::Union{Nothing,Int}=nothing, Overlap::Int=0, Mode::String="exclude") if ndims(Data)==1 DataType = "single univariate vector (1 sequence)" N = length(Data) Dn = 0 elseif ndims(Data)==2 N, Dn = size(Data) DataType = "multivariate matrix ("*string(Dn)*" vectors)" else error("Only a vector or a Matrix can be passed as Data!") end (N>10) ? nothing : error("Data: must be a numpy Vector (length N) or an NxM numpy matrix where N>10 and M>1") (isnothing(WinLen)) ? WinLen = Int(floor(N/5)) : nothing (10<WinLen<N) ? nothing : error("WinLen: must be an integer such that 10 < WinLen < N") (0<=Overlap<WinLen) ? nothing : error("Overlap: The number of overlapping window samples such that 0 <= Overlap < WinLen") (lowercase(Mode) in ["exclude","include"]) ? nothing : error("Mode: Option to include/exclude samples that do not fill final window, either 'exclude' or 'include'") M = Int(floor((N - Overlap)/(WinLen - Overlap))) Step = Int(WinLen-Overlap) Xout = [] map(k -> push!(Xout, Data[k:k+WinLen-1,:]), 1:Step:M*Step) (lowercase(Mode)=="include" && (length(Xout)-1)*Step+WinLen!=N) ? (push!(Xout, Data[1+M*Step:end,:]); M+=1) : nothing Log = Dict("DataType" => DataType, "DataLength" => N, "WindowLength" => WinLen, "WindowOverlap" => Overlap, "TotalWindows" => M, "Mode" => Mode) return Xout, Log end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
4890
module _XApEn export XApEn using Statistics: mean, std, var """ XAp, Phi = XApEn(Sig1, Sig2) Returns the cross-approximate entropy estimates (`XAp`) and the average number of matched vectors (`Phi`) for m = [0,1,2], estimated for the data sequences contained in `Sig1` and `Sig2` using the default parameters: embedding dimension = 2, time delay = 1, radius distance threshold= 0.2*SDpooled(`Sig1`,`Sig2`), logarithm = natural **NOTE**: XApEn is direction-dependent. Thus, `Sig1` is used as the template data sequence, and `Sig2` is the matching sequence.`` XAp, Phi = XApEn(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; m::Int=2, tau::Int=1, r::Union{Real,Nothing}=nothing, Logx::Real=exp(1)) Returns the cross-approximate entropy estimates (`XAp`) between the data sequences contained in `Sig1` and `Sig2` using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, a positive integer [default: 2] \n `tau` - Time Delay, a positive integer [default: 1] \n `r` - Radius Distance Threshold, a positive scalar [default: 0.2*SDpooled(`Sig1`,`Sig2`)] \n `Logx` - Logarithm base, a positive scalar [default: natural] \n # See also `XSampEn`, `XFuzzEn`, `XMSEn`, `ApEn`, `SampEn`, `MSEn` # References: [1] Steven Pincus and Burton H. Singer, "Randomness and degrees of irregularity." Proceedings of the National Academy of Sciences 93.5 (1996): 2083-2088. [2] Steven Pincus, "Assessing serial irregularity and its implications for health." Annals of the New York Academy of Sciences 954.1 (2001): 245-267. """ function XApEn(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; m::Int=2, tau::Int=1, r::Union{Real,Nothing}=nothing, Logx::Real=exp(1)) if all(isa.((Sig1,Sig2), AbstractVector)) N1 = size(Sig1,1); N2 = size(Sig2,1) S1 = copy(Sig1); S2 = copy(Sig2) elseif (minimum(size(Sig1))==2 && (Sig2 isa Nothing)) argmin(size(Sig1)) == 2 ? nothing : Sig1 = Sig1' S1 = Sig1[:,1]; S2 = Sig1[:,2]; N1 = maximum(size(Sig1)); N2 = maximum(size(Sig1)); else error("""Sig1 and Sig2 must be 2 separate vectors \t\t\t - OR - Sig1 must be 2-column matrix and Sig2 nothing""") end r isa Nothing ? r = 0.2*sqrt((var(S1,corrected=false)*(N1-1) + var(S2,corrected=false)*(N2-1))/(N1+N2-1)) : nothing (N1>=10 && N2>=10) ? nothing : error("Sig1/Sig2: sequences must have >= 10 values") (m > 0) ? nothing : error("m: must be an integer > 0") (tau>0) ? nothing : error("tau: must be an integer > 0") (r >=0) ? nothing : error("r: must be a positive value") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Counter = 1*(abs.(S1 .- transpose(S2)) .<= r) M = vcat(m*ones(Int,N1-(m*tau)), repeat((m-1):-1:1,inner=tau)) XAp = zeros(m+1) Phi = zeros(m+2) for n = 1:N1 - tau ix = findall(Counter[n, :] .== 1) for k = 1:M[n] ix = ix[ix .+ (k*tau) .<= N2] isempty(ix) ? break : nothing p1 = repeat(transpose(S1[n:tau:n+(tau*k)]), outer=length(ix)) p2 = S2[ix .+ transpose(collect(0:tau:(k*tau)))] ix = ix[findall(maximum(abs.(p1 - p2),dims=2) .<= r)] Counter[n, ix] .+= 1 end end #Phi[1] = log(Logx, N1)/N1 #Phi[2] = mean(log.(Logx, sum(Counter.>0,dims=1)/N)) Temp = sum(Counter.>0,dims=1); Temp = Temp[Temp.!=0] Phi[2] = mean(log.(Logx, Temp/N1)) XAp[1] = Phi[1] - Phi[2] for k = 0:m-1 ai = sum(Counter.>(k+1),dims=1)/(N1-(k+1)*tau) bi = sum(Counter.>k,dims=1)/(N1-(k*tau)) ai = ai[ai.!=0] bi = bi[bi.!=0] Phi[k+3] = sum(log.(Logx, ai))/(N1-(k+1)*tau) XAp[k+2]= sum(log.(Logx, bi))/(N1-(k*tau)) - Phi[k+3] end return XAp, Phi end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
5286
module _XCondEn export XCondEn using StatsBase: fit, Histogram using Statistics: mean, std """ XCond, SEw, SEz = XCondEn(Sig1, Sig2) Returns the corrected cross-conditional entropy estimates (`XCond`) and the corresponding Shannon entropies (m: SEw, m+1: SEz) for m = [1,2] estimated for the data sequences contained in `Sig1` and `Sig2` using the default parameters: embedding dimension = 2, time delay = 1, number of symbols = 6, logarithm = natural ** Note: XCondEn is direction-dependent. Therefore, the order of the data sequences `Sig1` and `Sig2` matters. If `Sig1` is the sequence 'y', and `Sig2` is the second sequence 'u', the `XCond` is the amount of information carried by y(i) when the pattern u(i) is found.** XCond, SEw, SEz = XCondEn(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; m::Int=2, tau::Int=1, c::Int=6, Logx::Real=exp(1), Norm::Bool=false) Returns the corrected cross-conditional entropy estimates (`XCond`) for the data sequences contained in `Sig1` and `Sig2` using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, an integer > 1 [default: 2] \n `tau` - Time Delay, a positive integer [default: 1] \n `c` - Number of symbols, an integer > 1 [default: 6] \n `Logx` - Logarithm base, a positive scalar [default: natural] \n `Norm` - Normalisation of `XCond` values: [false] no normalisation [default]\n [true] normalises w.r.t cross-Shannon entropy. \n # See also `XFuzzEn`, `XSampEn`, `XApEn`, `XPermEn`, `CondEn`, `XMSEn` # References: [1] Alberto Porta, et al., "Conditional entropy approach for the evaluation of the coupling strength." Biological cybernetics 81.2 (1999): 119-129. """ function XCondEn(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; m::Int=2, tau::Int=1, c::Int=6, Logx::Real=exp(1), Norm::Bool=false) if all(isa.((Sig1,Sig2), AbstractVector)) N = size(Sig1,1); S1 = (Sig1 .- mean(Sig1))/std(Sig1,corrected=false) S2 = (Sig2 .- mean(Sig2))/std(Sig2,corrected=false) elseif (minimum(size(Sig1))==2 && (Sig2 isa Nothing)) argmin(size(Sig1)) == 2 ? nothing : Sig1 = Sig1' S1 = (Sig1[:,1] .- mean(Sig1[:,1]))/std(Sig1[:,1],corrected=false) S2 = (Sig2[:,2] .- mean(Sig2[:,2]))/std(Sig2[:,2],corrected=false) N = maximum(size(Sig1)); else error("""Sig1 and Sig2 must be 2 separate vectors \t\t\t - OR - Sig1 must be 2-column matrix and Sig2 nothing""") end length(S2)==N ? nothing : error("Sig1 and Sig2 must be the same length!") (N>=10) ? nothing : error("Sig1/Sig2: sequences must have >= 10 values") (m > 1) ? nothing : error("m: must be an integer > 1") (tau>0) ? nothing : error("tau: must be an integer > 0") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") (c>1) ? nothing : error("c: must be an integer > 1") Edges = range(minimum(S1),maximum(S1),length=c+1) Sx1 = map(x -> sum(Edges[1:c].<=x), S1) Edges = range(minimum(S2),maximum(S2),length=c+1) Sx2 = map(x -> sum(Edges[1:c].<=x), S2) SEw = zeros(m-1) SEz = zeros(m-1) Prcm = zeros(m-1) Xi = zeros(Int,N,m) for k = 1:m-1 Nx = N-(k-1)*tau Xi[1:Nx,m-(k-1)] = Sx1[(k-1)*tau+1:N] #Wi = transpose(c.^(k-1:-1:0))*transpose(Xi[1:Nx,m-k+1:m]) Wi = Xi[1:Nx,m-k+1:m]*(c.^(k-1:-1:0)) #Zi = (c^k)*transpose(Sx2[(k-1)*tau+1:N]) .+ Wi Zi = (c^k)*Sx2[(k-1)*tau+1:N] + Wi Pw = fit(Histogram, Wi[:], minimum(Wi)-.5:maximum(Wi)+.5).weights Pz = fit(Histogram, Zi[:], minimum(Zi)-.5:maximum(Zi)+.5).weights Prcm[k] = sum(Pz.==1)/Nx (sum(Pw)!= Nx || sum(Pz)!= Nx) ? @warn("Potential error estimating probabilities.") : nothing Pw = Pw[Pw.!=0]; Pw = Pw/N Pz = Pz[Pz.!=0]; Pz = Pz/N SEw[k] = -transpose(Pw)*log.(Logx, Pw) SEz[k] = -transpose(Pz)*log.(Logx, Pz) end Temp = fit(Histogram,Sx2,nbins=c).weights Temp = Temp[Temp.!=0]./N Sy = -transpose(Temp)*log.(Logx, Temp) XC = SEz - SEw + Prcm*Sy XC = vcat(Sy, XC) Norm ? XC = XC/Sy : nothing return XC, SEw, SEz end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
5736
module _XDistEn export XDistEn using StatsBase: fit, Histogram, skewness using Statistics: mean, std """ XDist, Ppi = XDistEn(Sig1, Sig2) Returns the cross-distribution entropy estimate (`XDist`) and the corresponding distribution probabilities (`Ppi`) estimated between the data sequences contained in `Sig1` and `Sig2` using the default parameters: embedding dimension = 2, time delay = 1, binning method = 'Sturges', logarithm = base 2, normalisation = w.r.t # of histogram bins XDist, Ppi = XDistEn(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; m::Int=2, tau::Int=1, Bins::Union{Int,String}="Sturges", Logx::Real=2, Norm::Bool=true) Returns the cross-distribution entropy estimate (`XDist`) estimated between the data sequences contained in `Sig1` and `Sig2` using the specified 'keyword' = arguments: # Arguments: `m` - Embedding Dimension, a positive integer [default: 2] \n `tau` - Time Delay, a positive integer [default: 1] \n `Bins` - Histogram bin selection method for distance distribution, an integer > 1 indicating the number of bins, or one of the following strings {'sturges','sqrt','rice','doanes'} [default: 'sturges'] \n `Logx` - Logarithm base, a positive scalar [default: 2] ** enter 0 for natural log**\n `Norm` - Normalisation of DistEn value: [false] no normalisation. [true] normalises w.r.t # of histogram bins [default] \n # See also `XSampEn`, `XApEn`, `XPermEn`, `XCondEn`, `DistEn`, `DistEn2D`, `XMSEn` # References: [1] Yuanyuan Wang and Pengjian Shang, "Analysis of financial stock markets through the multiscale cross-distribution entropy based on the Tsallis entropy." Nonlinear Dynamics 94.2 (2018): 1361-1376. """ function XDistEn(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; m::Int=2, tau::Int=1, Bins::Union{Int,String}="Sturges", Logx::Real=2, Norm::Bool=true) if all(isa.((Sig1,Sig2), AbstractVector)) N1 = size(Sig1,1); N2 = size(Sig2,1) S1 = copy(Sig1); S2 = copy(Sig2) elseif (minimum(size(Sig1))==2 && (Sig2 isa Nothing)) argmin(size(Sig1)) == 2 ? nothing : Sig1 = Sig1' S1 = Sig1[:,1]; S2 = Sig1[:,2]; N1 = maximum(size(Sig1)); N2 = maximum(size(Sig1)); else error("""Sig1 and Sig2 must be 2 separate vectors \t\t\t - OR - Sig1 must be 2-column matrix and Sig2 nothing""") end Logx == 0 ? Logx = exp(1) : nothing (N1>=10 && N2>=10) ? nothing : error("Sig1/Sig2: sequences must have >= 10 values") (m > 0) ? nothing : error("m: must be an integer > 0") (tau>0) ? nothing : error("tau: must be an integer > 0") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") if typeof(Bins)<:Int (Bins>1) ? nothing : error("Bins: must be an integer > 1 (or name of binning method)") elseif typeof(Bins)<:String (lowercase(Bins) in ["sturges","sqrt","rice","doanes"]) ? nothing : error("Bins: must be one of the following strings 'sturges', 'sqrt', 'rice', 'doanes' (or an integer >1)") end Nx1 = N1 - ((m-1)*tau) Nx2 = N2 - ((m-1)*tau) Zm1 = zeros(Nx1,m) Zm2 = zeros(Nx2,m) for n = 1:m Zm1[:,n] = S1[(n-1)*tau + 1:Nx1+(n-1)*tau] Zm2[:,n] = S2[(n-1)*tau + 1:Nx2+(n-1)*tau] end DistMat = zeros(Nx1,Nx2); for k = 1:Nx1 DistMat[k,:] = maximum(abs.(repeat(transpose(Zm1[k,:]),outer=Nx2) - Zm2),dims=2) end Ny = Nx1*Nx2 DistMat = reshape(DistMat,1,Ny) if eltype(Bins)<:Char if lowercase(Bins) == "sturges" Bx = ceil(log2(Ny) + 1) elseif lowercase(Bins) == "rice" Bx = ceil(2*(Ny^(1/3))); elseif lowercase(Bins) == "sqrt" Bx = ceil(sqrt(Ny)); elseif lowercase(Bins) == "doanes" sigma = sqrt(6*(Ny-2)/((Ny+1)*(Ny+3))); Bx = ceil(1+log2(Ny)+log2(1+abs(skewness(DistMat)/sigma))); else error("Please enter a valid binning method") end else Bx = Bins end By = collect(range(minimum(DistMat),maximum(DistMat),length=Int(Bx+1))) By[end] += 1; By[1] -= 1 # Ppi = fit(Histogram, transpose(DistMat), By).weights/Ny Ppi = fit(Histogram, DistMat[:], By).weights/Ny if round(sum(Ppi),digits=6) != 1 @warn("Potential error estimating probabilities (p = $(sum(Ppi))") Ppi = Ppi[Ppi.!=0] elseif any(Ppi.==0) print("Note: $(sum(Ppi.==0))/$(length(Ppi)) bins were empty") Ppi = Ppi[Ppi.!=0] end XDist = -sum(Ppi.*log.(Logx, Ppi)) Norm ? XDist = XDist/log(Logx, Bx) : nothing return XDist, Ppi end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
10619
module _XFuzzEn export XFuzzEn using Statistics: mean, std """ XFuzz, Ps1, Ps2 = XFuzzEn(Sig1, Sig2) Returns the cross-fuzzy entropy estimates (`XFuzz`) and the average fuzzy distances (m:Ps1, m+1:Ps2) for m = [1,2] estimated for the data sequences contained in `Sig1` and `Sig2`, using the default parameters: embedding dimension = 2, time delay = 1, fuzzy function (Fx) = 'default', fuzzy function parameters (r) = [0.2, 2], logarithm = natural XFuzz, Ps1, Ps2 = XFuzzEn(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; m::Int=2, tau::Int=1, r::Union{Real,Tuple{Real,Real}}=(.2,2), Fx::String="default", Logx::Real=exp(1)) Returns the cross-fuzzy entropy estimates (`XFuzz`) for dimensions = [1,...,m] estimated for the data sequences in `Sig1` and `Sig2` using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, a positive integer [default: 2] \n `tau` - Time Delay, a positive integer [default: 1] \n `Fx` - Fuzzy function name, one of the following: {`"sigmoid", "modsampen", "default", "gudermannian",` `"bell", "triangular", "trapezoidal1", "trapezoidal2",` `"z_shaped", "gaussian", "constgaussian"`}\n `r` - Fuzzy function parameters, a scalar or a 2 element tuple of positive values. The `r` parameters for each fuzzy function are defined as follows:\n sigmoid: r(1) = divisor of the exponential argument r(2) = value subtracted from argument (pre-division) modsampen: r(1) = divisor of the exponential argument r(2) = value subtracted from argument (pre-division) default: r(1) = divisor of the exponential argument r(2) = argument exponent (pre-division) gudermannian: r = a scalar whose value is the numerator of argument to gudermannian function: GD(x) = atan(tanh(`r`/x)). triangular: r = a scalar whose value is the threshold (corner point) of the triangular function. trapezoidal1: r = a scalar whose value corresponds to the upper (2r) and lower (r) corner points of the trapezoid. trapezoidal2: r(1) = a value corresponding to the upper corner point of the trapezoid. r(2) = a value corresponding to the lower corner point of the trapezoid. z_shaped: r = a scalar whose value corresponds to the upper (2r) and lower (r) corner points of the z-shape. bell: r(1) = divisor of the distance value r(2) = exponent of generalized bell-shaped function gaussian: r = a scalar whose value scales the slope of the Gaussian curve. constgaussian: r = a scalar whose value defines the lower threshod and shape of the Gaussian curve. [DEPRICATED] linear: r = an integer value. When r = 0, the argument of the exponential function is normalised between [0 1]. When r = 1, the minimuum value of the exponential argument is set to 0. \n `Logx` - Logarithm base, a positive scalar \n For further information on the 'keyword' arguments, see the EntropyHub guide. # See also `FuzzEn`, `XSampEn`, `XApEn`, `FuzzEn2D`, `XMSEn`, `MSEn` # References: [1] Hong-Bo Xie, et al., "Cross-fuzzy entropy: A new method to test pattern synchrony of bivariate time series." Information Sciences 180.9 (2010): 1715-1724. [3] Hamed Azami, et al. "Fuzzy Entropy Metrics for the Analysis of Biomedical Signals: Assessment and Comparison" IEEE Access 7 (2019): 104833-104847 """ function XFuzzEn(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; m::Int=2, tau::Int=1, r::Union{Real,Tuple{Real,Real}}=(.2,2.0), Fx::String="default", Logx::Real=exp(1)) if all(isa.((Sig1,Sig2), AbstractVector)) N1 = size(Sig1,1); N2 = size(Sig2,1) S1 = copy(Sig1); S2 = copy(Sig2) elseif (minimum(size(Sig1))==2 && (Sig2 isa Nothing)) argmin(size(Sig1)) == 2 ? nothing : Sig1 = Sig1' S1 = Sig1[:,1]; S2 = Sig1[:,2]; N1 = maximum(size(Sig1)); N2 = maximum(size(Sig1)); else error("""Sig1 and Sig2 must be 2 separate vectors \t\t\t - OR - Sig1 must be 2-column matrix and Sig2 nothing""") end (N1>=10 && N2>=10) ? nothing : error("Sig1/Sig2: sequences must have >= 10 values") (m > 0) ? nothing : error("m: must be an integer > 0") (tau>0) ? nothing : error("tau: must be an integer > 0") (minimum(r)>=0 && length(r)<=2) ? nothing : error("r: must be a scalar or 2 element vector of positive values") (lowercase(Fx) in ["default","sigmoid","modsampen","gudermannian","bell", "z_shaped", "triangular", "trapezoidal1","trapezoidal2","gaussian","constgaussian"]) ? nothing : error("Fx: must be one of the following strings - 'default', 'sigmoid', 'modsampen', 'gudermannian', 'bell', 'z_shaped', 'triangular', 'trapezoidal1','trapezoidal2','gaussian','constgaussian'") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") if length(r) == 2 && lowercase(Fx)=="linear" r = 0; print("Multiple values for r entered. Default value (0) used.\n") elseif length(r) == 2 && lowercase(Fx)=="gudermannian" r = r[1] print("Multiple values for r entered. First value used.\n") end m += 1 Fun = getfield(_XFuzzEn,Symbol(lowercase(Fx))) Sx1 = zeros(N1,m) Sx2 = zeros(N2,m) for k = 1:m Sx1[1:N1-(k-1)*tau,k] = S1[1 + (k-1)*tau:N1] Sx2[1:N2-(k-1)*tau,k] = S2[1 + (k-1)*tau:N2] end Ps1 = zeros(m) Ps2 = zeros(m-1) Ps1[1] = 1 for k = 2:m N1x = N1 - k*tau N2x = N1 - (k-1)*tau N1y = N2 - k*tau N2y = N2 - (k-1)*tau A = Sx1[1:N2x,1:k] .- mean(Sx1[1:N2x,1:k],dims=2) B = Sx2[1:N2y,1:k] .- mean(Sx2[1:N2y,1:k],dims=2) d2 = zeros(N2x,N2y) for p = 1:N2x Mu2 = maximum(abs.(transpose(A[p,:]) .- B),dims=2) d2[p,:] = Fun(Mu2[:],r) end Ps1[k] = mean(d2[1:N1x,1:N1y]) Ps2[k-1] = mean(d2) end XFuzz = log.(Logx, Ps1[1:end-1]) .- log.(Logx, Ps2) return XFuzz, Ps1, Ps2 end function sigmoid(x,r) if length(r) == 1 error("When Fx = 'Sigmoid', r must be a two-element vector.") end y = inv.(1 .+ exp.((x.-r[2])/r[1])) return y end function modsampen(x,r) if length(r) == 1 error("When Fx = 'Modsampen', r must be a two-element vector.") end y = inv.(1 .+ exp.((x.-r[2])/r[1])) return y end function default(x,r) if length(r) == 1 error("When Fx = 'Default', r must be a two-element vector.") end y = exp.(-(x.^r[2])/r[1]) return y end function gudermannian(x,r) if r <= 0 error("When Fx = 'Gudermannian', r must be a scalar > 0.") end y = atan.(tanh.(r[1]./x)) y ./= maximum(y) return y end """ function linear(x,r) if r == 0 && length(x)>1 y = exp.(-(x .- minimum(x))/(maximum(x)-minimum(x))) elseif r == 1 y = exp.(-(x .- minimum(x))) elseif r == 0 && length(x)==1 y = [0] else error("When Fx = 'Linear', r must be 0 or 1.") end return y end """ function triangular(x,r) length(r)==1 ? nothing : error("When Fx = 'Triangular', r must be a scalar > 0.") y = 1 .- (x./r) y[x .> r] .= 0 return y end function trapezoidal1(x, r) length(r)==1 ? nothing : error("When Fx = 'Trapezoidal1', r must be a scalar > 0.") y = zeros(length(x)) y[x .<= r*2] = 2 .- (x[x .<= r*2]./r) y[x .<= r] .= 1 return y end function trapezoidal2(x, r) (r isa Tuple) && (length(r)==2) ? nothing : error("When Fx = 'Trapezoidal2', r must be a two-element tuple.") y = zeros(length(x)) y[x .<= maximum(r)] = 1 .- (x[x .<= maximum(r)] .- minimum(r))./(maximum(r)-minimum(r)) y[x .<= minimum(r)] .= 1 return y end function z_shaped(x, r) length(r)==1 ? nothing : error("When Fx = 'Z_shaped', r must be a scalar > 0.") y = zeros(length(x)) y[x .<= 2*r] .= 2*(((x[x .<= 2*r] .- 2*r)./r).^2) y[x .<= 1.5*r] .= 1 .- (2*(((x[x .<= 1.5*r] .- r)/r).^2)) y[x .<= r] .= 1 return y end function bell(x, r) (r isa Tuple) && length(r)==2 ? nothing : error("When Fx = 'Bell', r must be a two-element tuple.") y = inv.(1 .+ abs.(x./r[1]).^(2*r[2])) return y end function gaussian(x, r) length(r)==1 ? nothing : error("When Fx = 'Gaussian', r must be a scalar > 0.") y = exp.(-((x.^2)./(2*(r.^2)))) return y end function constgaussian(x, r) length(r)==1 ? nothing : error("When Fx = 'ConstGaussian', r must be a scalar > 0.") y = ones(length(x)) y[x .> r] = exp.(-log(2)*((x[x .> r] .- r)./r).^2) return y end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
3886
module _XK2En export XK2En using Statistics: std, mean, var """ XK2, Ci = XK2En(Sig1, Sig2) Returns the cross-Kolmogorov entropy estimates (`XK2`) and the correlation integrals (`Ci`) for m = [1,2] estimated between the data sequences contained in `Sig1` and `Sig2` using the default parameters: embedding dimension = 2, time delay = 1, distance threshold (r) = 0.2*SDpooled(Sig1, Sig2), logarithm = natural XK2, Ci = XK2En(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; m::Int=2, tau::Int=1, r::Union{Real,Nothing}=nothing, Logx::Real=exp(1)) Returns the cross-Kolmogorov entropy estimates (`XK2`) estimated between the data sequences contained in `Sig1` and `Sig2` using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, a positive integer [default: 2] \n `tau` - Time Delay, a positive integer [default: 1] \n `r` - Radius Distance Threshold, a positive scalar [default: 0.2*SDpooled(`Sig1`,`Sig2`)] \n `Logx` - Logarithm base, a positive scalar [default: natural] \n # See also `XSampEn`, `XFuzzEn`, `XApEn`, `K2En`, `XMSEn`, `XDistEn` # References: [1] Matthew W. Flood, "XK2En - EntropyHub Project" (2021) https://github.com/MattWillFlood/EntropyHub """ function XK2En(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; m::Int=2, tau::Int=1, r::Union{Real,Nothing}=nothing, Logx::Real=exp(1)) if all(isa.((Sig1,Sig2), AbstractVector)) N1 = size(Sig1,1); N2 = size(Sig2,1) S1 = copy(Sig1); S2 = copy(Sig2) elseif (minimum(size(Sig1))==2 && (Sig2 isa Nothing)) argmin(size(Sig1)) == 2 ? nothing : Sig1 = Sig1' S1 = Sig1[:,1]; S2 = Sig1[:,2]; N1 = maximum(size(Sig1)); N2 = maximum(size(Sig1)); else error("""Sig1 and Sig2 must be 2 separate vectors \t\t\t - OR - Sig1 must be 2-column matrix and Sig2 nothing""") end r isa Nothing ? r = 0.2*sqrt((var(S1,corrected=false)*(N1-1) + var(S2,corrected=false)*(N2-1))/(N1+N2-1)) : nothing (N1>=10 && N2>=10) ? nothing : error("Sig1/Sig2: sequences must have >= 10 values") (m > 0) ? nothing : error("m: must be an integer > 0") (tau>0) ? nothing : error("tau: must be an integer > 0") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") (r>0) ? nothing : error("r: must be 2 element tuple of positive values") m += 1 Zm1 = zeros(N1,m) Zm2 = zeros(N2,m) Ci = zeros(m) for n = 1:m Nx = N1-(n-1)*tau Zm1[1:Nx,n] = S1[(n-1)*tau + 1:N1] Ny = N2-(n-1)*tau Zm2[1:Ny,n] = S2[(n-1)*tau + 1:N2] Norm = zeros(Nx,Ny) for k = 1:Nx Temp = repeat(transpose(Zm1[k,1:n]),outer=Ny) .- Zm2[1:Ny,1:n] Norm[k,:] = sqrt.(sum(Temp.*Temp,dims=2)) end Ci[n] = mean(Norm .< r) end XK2 = log.(Logx, Ci[1:m-1]./Ci[2:m])/tau XK2[isinf.(XK2)] .= NaN return XK2, Ci end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
12829
module _XMSEn export XMSEn, EMD using Statistics: std, mean, median, var # using Dierckx: Spline1D using DataInterpolations: CubicSpline using Plots using DSP: conv #=function __init__() @warn("\n\n Methodx option IMF (Intrinisic Mode Function) is not stable. Random or highly aperiodic signals may not decompose fully. Access to the IMFs decomposed by the empirical mode decomposition (EMD) function can be found by calling _MSEn.EMD(`Sig`,`MaxIMFs`). A stable EMD function will be included in future releases.\n\n") end=# """ MSx, CI = XMSEn(Sig1, Sig2, Mobj) Returns a vector of multiscale cross-entropy values `MSx` and the complexity index `CI` between the data sequences contained in `Sig1` and `Sig2` using the parameters specified by the multiscale object `Mobj` over 3 temporal scales with coarse- graining `default`. MSx,CI = MSEn(Sig1::AbstractVector{T} where T<:Real, Sig2::AbstractVector{T} where T<:Real, Mobj::NamedTuple; Scales::Int=3, Methodx::String="coarse", RadNew::Int=0, Plotx::Bool=false) Returns a vector of multiscale cross-entropy values `MSx` and the complexity index `CI` of the data sequences contained in `Sig1` and `Sig2` using the parameters specified by the multiscale object `Mobj` and the following 'keyword' arguments: # Arguments: `Scales` - Number of temporal scales, an integer > 1 (default: 3) \n `Method` - Graining method, one of the following:\n {`"coarse", "modified", "imf", "timeshift","generalized"`} [default: 'coarse'] For further info on graining procedures, see the Entropyhub guide. \n `RadNew` - Radius rescaling method, an integer in the range [1 4]. When the entropy specified by `Mobj` is `XSampEn` or `XApEn`, `RadNew` allows the radius threshold to be updated at each time scale (Xt). If a radius value is specified by `Mobj` (`r`), this becomes the rescaling coefficient, otherwise it is set to 0.2 (default). The value of `RadNew` specifies one of the following methods: \n [1] Pooled Standard Deviation - r*std(Xt) \n [2] Pooled Variance - r*var(Xt) \n [3] Total Mean Absolute Deviation - r*mean_ad(Xt) \n [4] Total Median Absolute Deviation - r*med_ad(Xt) \n `Plotx` - When `Plotx` == true, returns a plot of the entropy value at each time scale (i.e. the multiscale entropy curve) [default: false] `For further info on these graining procedures see the EntropyHub guide.` # See also `MSobject`, `MSEn`, `cXMSEn`, `rXMSEn`, `hXMSEn`, `XSampEn`, `XApEn`, `XFuzzEn` # References: [1] Rui Yan, Zhuo Yang, and Tao Zhang, "Multiscale cross entropy: a novel algorithm for analyzing two time series." 5th International Conference on Natural Computation. Vol. 1, pp: 411-413 IEEE, 2009. [2] Madalena Costa, Ary Goldberger, and C-K. Peng, "Multiscale entropy analysis of complex physiologic time series." Physical review letters 89.6 (2002): 068102. [3] Vadim V. Nikulin, and Tom Brismar, "Comment on “Multiscale entropy analysis of complex physiologic time series”." Physical review letters 92.8 (2004): 089803. [4] Madalena Costa, Ary L. Goldberger, and C-K. Peng. "Costa, Goldberger, and Peng reply." Physical Review Letters 92.8 (2004): 089804. [5] Antoine Jamin, et al, "A novel multiscale cross-entropy method applied to navigation data acquired with a bike simulator." 41st annual international conference of the IEEE EMBC IEEE, 2019. [6] Antoine Jamin and Anne Humeau-Heurtier. "(Multiscale) Cross-Entropy Methods: A Review." Entropy 22.1 (2020): 45. """ function XMSEn(Sig1::AbstractVector{T} where T<:Real, Sig2::AbstractVector{T} where T<:Real, Mobj::NamedTuple; Scales::Int=3, Methodx::String="coarse", RadNew::Int=0, Plotx::Bool=false) (size(Sig1,1)>=10) && (size(Sig2,1)>=10) ? nothing : error("Sig1/Sig2: sequences must have >= 10 values") (length(Mobj) >= 1) ? nothing : error("Mobj: must be a multiscale entropy object created with the function EntropyHub.MSobject") (Scales>1) ? nothing : error("Scales: must be an integer > 1") (lowercase(Methodx) in ["coarse","modified","imf","timeshift","generalized"]) ? nothing : error("Method: must be one of the following string names - 'coarse','modified','imf','timeshift','generalized'") (RadNew==0 || (RadNew in 1:4 && String(Symbol(Mobj.Func)) in ("XSampEn","XApEn"))) ? nothing : error("RadNew: must be 0, or an integer in range [1 4] with entropy function 'XSampEn' or 'XApEn'") String(Symbol(Mobj.Func))=="XSampEn" ? Mobj = merge(Mobj,(Vcp=false,)) : nothing if lowercase(Methodx)=="imf" Imfx, _ = EMD(Sig1,Scales-1) Imfy, _ = EMD(Sig2,Scales-1) Sig1 = Imfx # [1:Scales,:]' Sig2 = Imfy # [1:Scales,:]' # If any of the IMFs are just zeros, then take only the IMFs that aren't sum(all(Sig1.==0,dims=2))==0 ? Tp1 = ones(Int,size(Imfx,1)) : Tp1 = vec(collect(all(Sig1 .!= 0, dims=2))); sum(all(Sig2.==0,dims=2))==0 ? Tp2 = ones(Int,size(Imfy,1)) : Tp2 = vec(collect(all(Sig2 .!= 0, dims=2))); if !all(Bool.(Tp1.+Tp2.-1)) || (size(Imfx,1)<Scales || size(Imfy,1)<Scales) Sig1 = Sig1[Bool.(Tp1.+Tp2.-1),:] Sig2 = Sig2[Bool.(Tp1.+Tp2.-1),:] @warn("Max number of IMF's decomposed from EMD is less than number of Scales. MSEn evaluated over $(size(Sig,1)) scales instead of $Scales.") Scales = size(Sig1,1); end end MSx = zeros(Scales) Args = NamedTuple{keys(Mobj)[2:end]}(Mobj) Func2 = getfield(_XMSEn,Symbol(lowercase(Methodx))) if RadNew > 0 if RadNew == 1 Rnew = (x,y) -> sqrt((var(x)*(size(x,1)-1) + var(y)*(size(y,1)-1))/(size(x,1)+size(y,1)-1)) elseif RadNew == 2 Rnew = (x,y) -> ((var(x)*(size(x,1)-1) + var(y)*(size(y,1)-1))/(size(x,1)+size(y,1)-1)) elseif RadNew == 3 Rnew = (x,y) -> mean(abs.(vcat(x,y) .- mean(vcat(x,y)))) elseif RadNew == 4 Rnew = (x,y) -> median(abs.(vcat(x,y) .- median(vcat(x,y)))) end if haskey(Mobj,:r) Cx = Mobj.r else Cy = ("Pooled Standard Deviation","Pooled Variance","Total Mean Abs Deviation", "Total Median Abs Deviation") @warn("No radius value provided in Mobj. Default set to 0.2*$(Cy[RadNew]) of each new time-series.") Cx = .2 end end for T = 1:Scales print(" .") TempA, TempB = Func2(Sig1, Sig2, T) if lowercase(Methodx) == "timeshift" Tempx = zeros(T) for k = 1:T RadNew > 0 ? Args = (Args..., r=Cx*Rnew(TempA[k,:], TempB[k,:])) : nothing Tempy = Mobj.Func(TempA[k,:], TempB[k,:]; Args...) typeof(Tempy)<:Tuple ? Tempx[k] = Tempy[1][end] : Tempx[k] = Tempy[end] # Tempx[k] = Tempy[1][end] end Temp2 = mean(Tempx) else RadNew > 0 ? Args = (Args..., r=Cx*Rnew(TempA,TempB)) : nothing Tempx = Mobj.Func(TempA, TempB; Args...) typeof(Tempx)<:Tuple ? Temp2 = Tempx[1][end] : Temp2 = Tempx[end] # Temp2 = Tempx[1][end] end MSx[T] = Temp2 end CI = sum(MSx) print("\n") if any(isnan.(MSx)) println("Some entropy values may be undefined.") end if Plotx p1 = plot(1:Scales, MSx, c=RGB(8/255, 63/255, 77/255), lw=3) scatter!(1:Scales, MSx, markersize=6, c=RGB(1, 0, 1), xlabel = "Scale Factor", ylabel = "Entropy Value", guidefont = font(12, "arial", RGB(7/255, 54/255, 66/255)), tickfontsize = 10, tickfontfamily="arial", legend=false, title = "Multiscale $(Mobj.Func) ($(titlecase(Methodx))-graining method)", plot_titlefontsize=16, plot_titlefontcolor=RGB(7/255, 54/255, 66/255)) display(p1) end return MSx, CI end function coarse(Za, Zb, sx) Na = Int(floor(size(Za,1)/sx)) Nb = Int(floor(size(Zb,1)/sx)) Y1 = mean(reshape(Za[1:sx*Na],sx,Na),dims=1)[:] Y2 = mean(reshape(Zb[1:sx*Nb],sx,Nb),dims=1)[:] return Y1, Y2 end function modified(Za, Zb, sx) #= Ns = size(Z,1) - sx + 1 Y = zeros(Ns,2) for k = 1:Ns Y[k,1] = mean(Z[k:k+sx-1,1]) Y[k,2] = mean(Z[k:k+sx-1,2]) end=# Y1 = (conv(Za,ones(Int, sx))/sx)[sx:end-sx+1][:] Y2 = (conv(Zb,ones(Int, sx))/sx)[sx:end-sx+1][:] return Y1, Y2 end function imf(Za, Zb, sx) Y1 = sum(Za[1:sx,:],dims=1)[:] Y2 = sum(Zb[1:sx,:],dims=1)[:] return Y1, Y2 end function timeshift(Za, Zb, sx) # Y1 = zeros(sx,Int(floor(size(Za,1)/sx))) # Y2 = zeros(sx,Int(floor(size(Zb,1)/sx))) Y1 = reshape(Za[1:Int(sx*floor(size(Za,1)/sx))], (sx,Int(floor(size(Za,1)/sx)))) Y2 = reshape(Zb[1:Int(sx*floor(size(Zb,1)/sx))], (sx,Int(floor(size(Zb,1)/sx)))) return Y1, Y2 end function generalized(Za, Zb, sx) Na = floor(Int, size(Za,1)/sx) Nb = floor(Int, size(Zb,1)/sx) Y1 = var(reshape(Za[1:sx*Na],sx,Na)', corrected=false, dims=2)[:] Y2 = var(reshape(Zb[1:sx*Nb],sx,Nb)', corrected=false, dims=2)[:] return Y1, Y2 end function PkFind(X) Nx = length(X) Indx = zeros(Int,Nx); for n = 2:Nx-1 if X[n-1]< X[n] > X[n+1] Indx[n] = n elseif X[n-1] < X[n] == X[n+1] k = 1 Indx[n] = n while (n+k)<Nx && X[n] == X[n+k] Indx[n+k] = n+k k+=1 end n+=k end end Indx = Indx[Indx.!==0] return Indx end function EMD(X, Scales::Int) Xt = copy(X); N = size(Xt,1); n=1; IMFs = zeros(Scales+1,N) MaxER = 20; MinTN = 2; #Xt .-= mean(Xt) r1 = Xt while n <= Scales r0 = Xt; x = 0; Upx = PkFind(r0); Lwx = PkFind(-r0) UpEnv = CubicSpline(r0[Upx], Upx) #Spline1D(Upx,r0[Upx],k=3,bc="nearest") LwEnv = CubicSpline(r0[Lwx], Lwx) #Spline1D(Lwx,r0[Lwx],k=3,bc="nearest") r1 = r0.- (UpEnv(1:N) .+ LwEnv(1:N))./2 #r0.- (UpEnv.(1:N) .+ LwEnv.(1:N))./2 RT = (sum(r0.*r0) - sum(r1.*r1))/sum(r0.*r0) length(vcat(Upx,Lwx)) <= MinTN ? (LOG = "Decomposition hit minimal extrema criteria."; break) : nothing while x < 100 && RT > 0.2 r0 = 1*r1 Upx = PkFind(r0); Lwx = PkFind(-r0) UpEnv = CubicSpline(r0[Upx], Upx) #Spline1D(Upx,r0[Upx],k=3,bc="nearest") LwEnv = CubicSpline(r0[Lwx], Lwx) #Spline1D(Lwx,r0[Lwx],k=3,bc="nearest") r1 = r0.- (UpEnv(1:N) .+ LwEnv(1:N))./2 # r0.- (UpEnv.(1:N) .+ LwEnv.(1:N))./2 RT = (sum(r0.*r0) - sum(r1.*r1))/sum(r0.*r0) x += 1; 10*log10(sqrt(sum(r0.*r0))/sqrt(sum(r1.*r1))) > MaxER ? (LOG = "Decomposition hit energy ratio criteria."; break) : nothing end IMFs[n,:] = r1 Xt .-= r1 IMFs[Scales+1,:] = r0 .+ mean(X) n+=1 end LOG = "All went well :) " return IMFs, LOG end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
4129
module _XPermEn export XPermEn using StatsBase: fit, Histogram using Combinatorics: permutations """ XPerm = XPermEn(Sig1, Sig2) Returns the cross-permuation entropy estimates (`XPerm`) estimated betweeen the data sequences contained in `Sig1` and `Sig2` using the default parameters: embedding dimension = 3, time delay = 1, logarithm = base 2, XPerm = XPermEn(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; m::Int=3, tau::Int=1, Logx::Real=exp(1)) Returns the permutation entropy estimates (`XPerm`) estimated between the data sequences contained in `Sig1` and `Sig2` using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, an integer > 2 [default: 3] \n **Note: XPerm is undefined for embedding dimensions < 3.**\n `tau` - Time Delay, a positive integer [default: 1] \n `Logx` - Logarithm base, a positive scalar [default: 2] ** enter 0 for natural log.** \n # See also `PermEn`, `XApEn`, `XSampEn`, `XFuzzEn`, `XMSEn` # References: [1] Wenbin Shi, Pengjian Shang, and Aijing Lin, "The coupling analysis of stock market indices based on cross-permutation entropy." Nonlinear Dynamics 79.4 (2015): 2439-2447. """ function XPermEn(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; m::Int=3, tau::Int=1, Logx::Real=exp(1)) if all(isa.((Sig1,Sig2), AbstractVector)) N = size(Sig1,1); S1 = copy(Sig1); S2 = copy(Sig2) elseif (minimum(size(Sig1))==2 && (Sig2 isa Nothing)) argmin(size(Sig1)) == 2 ? nothing : Sig1 = Sig1' S1 = Sig1[:,1]; S2 = Sig1[:,2]; N = maximum(size(Sig1)); else error("""Sig1 and Sig2 must be 2 separate vectors of same length \t\t\t - OR - Sig1 must be 2-column matrix and Sig2 nothing""") end length(S2)==N ? nothing : error("Sig1 and Sig2 must be the same length!") (N>=10) ? nothing : error("Sig1/Sig2: sequences must have >= 10 values") (m > 2) ? nothing : error("m: must be an integer > 1") (tau>0) ? nothing : error("tau: must be an integer > 0") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") N = length(S1)-(m-1)*tau Sx1 = zeros(N,m) Sx2 = zeros(N,m) for k = 1:m Sx1[:,k] = S1[1+(k-1)*tau:N+(k-1)*tau] Sx2[:,k] = S2[1+(k-1)*tau:N+(k-1)*tau] end Temp = sortind(Sx1[1:N,1:m]) Gx = zeros(N,m) for k = 1:N Gx[k,:] = Sx2[k,Temp[k,:]] end Kt = zeros(m-2,m-2,N) for k = 1:m-2 for j = k+1:m-1 G1 = Gx[:,j+1] .- Gx[:,k] G2 = Gx[:,k] .- Gx[:,j] Kt[k,j-1,:] = (G1.*G2 .> 0) end end Di = sum(Kt,dims=(1,2))[:] Ppi = fit(Histogram, Di, -.5:((m-2)*(m-1) + 1)/2).weights/N Ppi = Ppi[Ppi.!=0] XPerm = -sum(Ppi.*log.(Logx,Ppi)) if round(sum(Ppi),digits=6)!=1 @warn("Potential error with probability calculation") end return XPerm end function sortind(X) Y = zeros(Int, size(X)) for k = 1:length(X[:,1]) Y[k,:] = sortperm(X[k,:]) end return Y end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
6215
module _XSampEn export XSampEn using Statistics: std, var using LinearAlgebra: UpperTriangular, I """ XSamp, A, B = XSampEn(Sig1, Sig2) Returns the cross-sample entropy estimates (`XSamp`) and the number of matched vectors (m:B, m+1:A) for m = [0,1,2] estimated for the two univariate data sequences contained in `Sig1` and `Sig2` using the default parameters: embedding dimension = 2, time delay = 1, radius distance threshold= 0.2*SDpooled(`Sig1`,`Sig2`), logarithm = natural XSamp, A, B, (Vcp, Ka, Kb) = XSampEn(Sig1, Sig2, ..., Vcp = true) If `Vcp == true`, an additional tuple `(Vcp, Ka, Kb)` is returned with the cross-sample entropy estimates (`XSamp`) and the number of matched state vectors (`m: B`, `m+1: A`). `(Vcp, Ka, Kb)` contains the variance of the conditional probabilities (`Vcp`), i.e. CP = A/B, and the number of **overlapping** matching vector pairs of lengths m+1 (`Ka`) and m (`Kb`), respectively. Note `Vcp` is undefined for the zeroth embedding dimension (m = 0) and due to the computational demand, **will take substantially more time to return function outputs.** See Appendix B in [2] for more info. XSamp, A, B = XSampEn(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; m::Int=2, tau::Int=1, r::Union{Real,Nothing}=nothing, Logx::Real=exp(1), Vcp::Bool=false) Returns the cross-sample entropy estimates (`XSamp`) for dimensions [0,1,...,m] estimated between the data sequences in `Sig1` and `Sig2` using the specified 'keyword' arguments: # Arguments: `m` - Embedding Dimension, a positive integer [default: 2] \n `tau` - Time Delay, a positive integer [default: 1] \n `r` - Radius Distance Threshold, a positive scalar [default: 0.2*SDpooled(`Sig1`,`Sig2`)] \n `Logx` - Logarithm base, a positive scalar [default: natural] \n `Vcp` - Option to return the variance of the conditional probabilities and the number of overlapping matching vector pairs of lengths \n See also `XFuzzEn`, `XApEn`, `SampEn`, `SampEn2D`, `XMSEn`, `ApEn` # References: [1] Joshua S Richman and J. Randall Moorman. "Physiological time-series analysis using approximate entropy and sample entropy." American Journal of Physiology-Heart and Circulatory Physiology (2000) [2] Douglas E Lake, Joshua S Richman, M.P. Griffin, J. Randall Moorman "Sample entropy analysis of neonatal heart rate variability." American Journal of Physiology-Regulatory, Integrative and Comparative Physiology 283, no. 3 (2002): R789-R797. """ function XSampEn(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; m::Int=2, tau::Int=1, r::Union{Nothing,Real}=nothing, Logx::Real=exp(1), Vcp::Bool=false) if all(isa.((Sig1,Sig2), AbstractVector)) N1 = size(Sig1,1); N2 = size(Sig2,1) S1 = copy(Sig1); S2 = copy(Sig2) elseif (minimum(size(Sig1))==2 && (Sig2 isa Nothing)) argmin(size(Sig1)) == 2 ? nothing : Sig1 = Sig1' S1 = Sig1[:,1]; S2 = Sig1[:,2]; N1 = maximum(size(Sig1)); N2 = maximum(size(Sig1)); else error("""Sig1 and Sig2 must be 2 separate vectors \t\t\t - OR - Sig1 must be 2-column matrix and Sig2 nothing""") end r isa Nothing ? r = 0.2*sqrt((var(S1,corrected=false)*(N1-1) + var(S2,corrected=false)*(N2-1))/(N1+N2-1)) : nothing (N1>=10 && N2>=10) ? nothing : error("Sig1/Sig2: sequences must have >= 10 values") (m > 0) ? nothing : error("m: must be an integer > 0") (tau>0) ? nothing : error("tau: must be an integer > 0") (r >=0) ? nothing : error("r: must be a positive value") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Counter = 1*(abs.(S1 .- transpose(S2)) .<= r) M = vcat(m*ones(Int,N1-(m*tau)), repeat((m-1):-1:1,inner=tau)) A = zeros(Int,m+1) B = zeros(Int,m+1) A[1] = sum(Counter); B[1] = N1*N2; for n = 1:N1 - tau ix = findall(Counter[n, :] .== 1) for k = 1:M[n] ix = ix[ix .+ (k*tau) .<= N2] isempty(ix) ? break : nothing p1 = repeat(transpose(S1[n:tau:n+(tau*k)]), size(ix,1)) p2 = S2[ix .+ transpose(collect(0:tau:(k*tau)))] ix = ix[findall(maximum(abs.(p1 - p2),dims=2) .<= r)] Counter[n, ix] .+= 1 end end for k = 1:m A[k+1] = sum(Counter.>k) B[k+1] = sum(Counter.>=k) end XSamp = -log.(Logx, A./B) #return XSamp, A, B if Vcp T1 = getindex.(findall(Counter.>m),1) T2 = getindex.(findall(Counter.>m),2) Ka = UpperTriangular(((abs.(T1.-T1').<=m*tau) .+ (abs.(T2.-T2').<=m*tau))[1:end-1,2:end]) T1 = getindex.(findall(Counter[:,1:end-m*tau].>=m),1) T2 = getindex.(findall(Counter[:,1:end-m*tau].>=m),2) Kb = UpperTriangular(((abs.(T1.-T1').<=(m-1)*tau) .+ (abs.(T2.-T2').<=(m-1)*tau))[1:end-1,2:end]) Ka = sum(Ka.>0) Kb = sum(Kb.>0) CP = A[end]/B[end] Vcp = (CP*(1-CP)/B[end]) + (Ka - Kb*(CP^2))/(B[end]^2) return XSamp, A, B, (Vcp, Ka, Kb) else return XSamp, A, B end end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
4739
module _XSpecEn export XSpecEn using FFTW: fft using DSP: conv """ XSpec, BandEn = XSpecEn(Sig) Returns the cross-spectral entropy estimate (`XSpec`) of the full cross- spectrum and the within-band entropy (`BandEn`) estimated between the data sequences contained in `Sig` using the default parameters: N-point FFT = 2 * max(length(`Sig1`/`Sig2`)) + 1, normalised band edge frequencies = [0 1], logarithm = base 2, normalisation = w.r.t # of spectrum/band frequency values. XSpec, BandEn = XSpecEn(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; N::Union{Nothing,Int}=nothing, Freqs::Tuple{Real,Real}=(0,1), Logx::Real=exp(1), Norm::Bool=true) Returns the cross-spectral entropy (`XSpec`) and the within-band entropy (`BandEn`) estimate between the data sequences contained in `Sig1` and `Sig2` using the following specified 'keyword' arguments: # Arguments: `N` - Resolution of spectrum (N-point FFT), an integer > 1 \n `Freqs` - Normalised band edge frequencies, a scalar in range [0 1] where 1 corresponds to the Nyquist frequency (Fs/2). **Note: When no band frequencies are entered, BandEn == SpecEn** \n `Logx` - Logarithm base, a positive scalar [default: base 2] ** enter 0 for natural log** \n `Norm` - Normalisation of `XSpec` value: [false] no normalisation. [true] normalises w.r.t # of spectrum/band frequency values [default] \n For more info, see the EntropyHub guide # See also `SpecEn`, `fft`, `XDistEn`, `periodogram`, `XSampEn`, `XApEn` # References: [1] Matthew W. Flood, "XSpecEn - EntropyHub Project" (2021) https://github.com/MattWillFlood/EntropyHub """ function XSpecEn(Sig1::Union{AbstractMatrix{T}, AbstractVector{T}} where T<:Real, Sig2::Union{AbstractVector{T} where T<:Real, Nothing} = nothing; N::Union{Nothing,Int}=nothing, Freqs::Tuple{Real,Real}=(0,1), Logx::Real=exp(1), Norm::Bool=true) if all(isa.((Sig1,Sig2), AbstractVector)) N1 = size(Sig1,1); N2 = size(Sig2,1) S1 = copy(Sig1); S2 = copy(Sig2) elseif (minimum(size(Sig1))==2 && (Sig2 isa Nothing)) argmin(size(Sig1)) == 2 ? nothing : Sig1 = Sig1' S1 = Sig1[:,1]; S2 = Sig1[:,2]; N1 = maximum(size(Sig1)); N2 = maximum(size(Sig1)); else error("""Sig1 and Sig2 must be 2 separate vectors \t\t\t - OR - Sig1 must be 2-column matrix and Sig2 nothing""") end N isa Nothing ? N = 2*max(N1,N2) + 1 : N = 2*N1 + 1; (N1>=10 && N2>=10) ? nothing : error("Sig1/Sig2: sequences must have >= 10 values") (N > 1) ? nothing : error("N: must be an integer > 1") (0<=Freqs[1]<1 && 0<Freqs[2]<=1 && Freqs[1]<Freqs[2]) ? nothing : error("Freq: must be a two element tuple with values in range [0 1]. The values must be in increasing order.") (Logx>0) ? nothing : error("Logx: must be a positive number > 0") Freqs = collect(Freqs) Fx = Int(ceil(N/2)) Freqs = Int.(round.(Freqs.*Fx)) Freqs[Freqs.==0] .= 1 if Freqs[1] > Freqs[2] error("Lower band frequency must come first.") elseif Freqs[2]-Freqs[1]<1 error("Spectrum resoution too low to determine bandwidth.") elseif minimum(Freqs)<0 || maximum(Freqs)>Fx error("Freqs must be normalized w.r.t sampling frequency [0 1].") end Temp = conv(S1,S2) N <= size(Temp,1) ? Temp = Temp[1:N] : Temp = vcat(Temp,zeros(N-size(Temp,1))) Pt = abs.(fft(Temp)); Pxx = Pt[1:Fx]/sum(Pt[1:Fx]); XSpec = -transpose(Pxx)*log.(Logx, Pxx) Pband = (Pxx[Freqs[1]:Freqs[2]])/sum(Pxx[Freqs[1]:Freqs[2]]); BandEn = -transpose(Pband)*log.(Logx, Pband) if Norm XSpec = XSpec/log(Logx, Fx) BandEn = BandEn/log(Logx, Freqs[2]-Freqs[1]+1) end return XSpec, BandEn end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
8368
module _cMSEn export cMSEn using Statistics: std, mean, median, var using Plots using DSP: conv """ MSx, CI = cMSEn(Sig, Mobj) Returns a vector of composite multiscale entropy values (`MSx`) for the data sequence (`Sig`) using the parameters specified by the multiscale object (`Mobj`) using the composite multiscale entropy method over 3 temporal scales. MSx, CI = cMSEn(Sig::AbstractArray{T,1} where T<:Real, Mobj::NamedTuple; Scales::Int=3, RadNew::Int=0, Refined::Bool=false, Plotx::Bool=false) Returns a vector of composite multiscale entropy values (`MSx`) of the data sequence (`Sig`) using the parameters specified by the multiscale object (`Mobj`) and the following 'keyword' arguments: # Arguments: `Scales` - Number of temporal scales, an integer > 1 (default: 3) \n `RadNew` - Radius rescaling method, an integer in the range [1 4]. When the entropy specified by `Mobj` is `SampEn` or `ApEn`, RadNew allows the radius threshold to be updated at each time scale (Xt). If a radius value is specified by `Mobj` (`r`), this becomes the rescaling coefficient, otherwise it is set to 0.2 (default). The value of RadNew specifies one of the following methods:\n [1] Standard Deviation - r*std(Xt)\n [2] Variance - r*var(Xt) \n [3] Mean Absolute Deviation - r*mean_ad(Xt) \n [4] Median Absolute Deviation - r*med_ad(Xt)\n `Refined` - Refined-composite MSEn method. When `Refined == true` and the entropy function specified by Mobj is `SampEn` or `FuzzEn`, cMSEn returns the refined-composite multiscale entropy (rcMSEn) [default: false]\n `Plotx` - When `Plotx` == true, returns a plot of the entropy value at each time scale (i.e. the multiscale entropy curve) [default: false]\n # See also `MSobject`, `rMSEn`, `MSEn`, `hMSEn`, `SampEn`, `ApEn`, `XMSEn` # References: [1] Madalena Costa, Ary Goldberger, and C-K. Peng, "Multiscale entropy analysis of complex physiologic time series." Physical review letters 89.6 (2002): 068102. [2] Vadim V. Nikulin, and Tom Brismar, "Comment on “Multiscale entropy analysis of complex physiologic time series”." Physical review letters 92.8 (2004): 089803. [3] Madalena Costa, Ary L. Goldberger, and C-K. Peng. "Costa, Goldberger, and Peng reply." Physical Review Letters 92.8 (2004): 089804. [4] Shuen-De Wu, et al., "Time series analysis using composite multiscale entropy." Entropy 15.3 (2013): 1069-1084. [5] Shuen-De Wu, et al., "Analysis of complex time series using refined composite multiscale entropy." Physics Letters A 378.20 (2014): 1369-1374. [6] Azami, Hamed, Alberto Fernández, and Javier Escudero. "Refined multiscale fuzzy entropy based on standard deviation for biomedical signal analysis." Medical & biological engineering & computing 55 (2017): 2037-2052. """ function cMSEn(Sig::AbstractArray{T,1} where T<:Real, Mobj::NamedTuple; Scales::Int=3, RadNew::Int=0, Refined::Bool=false, Plotx::Bool=false) (size(Sig,1)>10) ? nothing : error("Sig: must be a numeric vector" ) (length(Mobj) >= 1) ? nothing : error("Mobj: must be a multiscale entropy object created with the function EntropyHub.MSobject") (Scales>1) ? nothing : error("Scales: must be an integer > 1") (RadNew==0 || (RadNew in 1:4 && String(Symbol(Mobj.Func)) in ("SampEn","ApEn"))) ? nothing : error("RadNew: must be 0, or an integer in range [1 4] with entropy function 'SampEn' or 'ApEn'") (Refined && String(Symbol(Mobj.Func)) in ("SampEn","FuzzEn")) || Refined==false ? nothing : error("Refined: If Refined == true, the base entropy function must be 'SampEn' or 'FuzzEn'") lowercase(String(Symbol(Mobj.Func))[1]) == 'x' ? error("Base entropy estimator is a cross-entropy method. To perform (refined-)composite multiscale CROSS-entropy estimation, use cXMSEn.") : nothing String(Symbol(Mobj.Func))=="SampEn" ? Mobj = merge(Mobj,(Vcp=false,)) : nothing if Refined && String(Symbol(Mobj.Func))=="FuzzEn" Tx = 1; "Logx" in String.(Symbol.(keys(Mobj))) ? Logx = Mobj.Logx : Logx = exp(1); elseif Refined && String(Symbol(Mobj.Func))=="SampEn" Tx = 0; "Logx" in String.(Symbol.(keys(Mobj))) ? Logx = Mobj.Logx : Logx = exp(1); else Tx = 0; end MSx = zeros(Scales) Args = NamedTuple{keys(Mobj)[2:end]}(Mobj) if RadNew > 0 if RadNew == 1 Rnew = x -> std(x, corrected=false) elseif RadNew == 2 Rnew = x -> var(x, corrected=false) elseif RadNew == 3 Rnew = x -> mean(abs.(x .- mean(x))) elseif RadNew == 4 Rnew = x -> median(abs.(x .- median(x))) end if haskey(Mobj,:r) Cx = Mobj.r else Cy = ("Standard Deviation","Variance","Mean Abs Deviation", "Median Abs Deviation") @warn("No radius value provided in Mobj. Default set to 0.2*$(Cy[RadNew]) of each new time-series.") Cx = .2 end end for T = 1:Scales Temp = modified(Sig,T,Tx) N = Int(T*floor(length(Temp)/T)) Temp2 = zeros(T) Temp3 = zeros(T) for k = 1:T print(". ") RadNew > 0 ? Args = (Args..., r=Cx*Rnew(Temp[k:T:N])) : nothing if Refined _, Ma, Mb = Mobj.Func(Temp[k:T:N]; Args...) Temp2[k] = Ma[end] Temp3[k] = Mb[end] else Temp2 = Mobj.Func(Temp[k:T:N]; Args...) typeof(Temp2)<:Tuple ? Temp3[k] = Temp2[1][end] : Temp3[k] = Temp2[end] #Temp3[k] = Temp2[1][end] end end #Refined ? MSx[T] = -log(sum(Temp2)/sum(Temp3)) : MSx[T] = mean(Temp3) if Refined && Tx==0 MSx[T] = -log(sum(Temp2)/sum(Temp3))/log(Logx) elseif Refined && Tx==1 MSx[T] = -log(sum(Temp3)/sum(Temp2))/log(Logx) else MSx[T] = mean(Temp3) end end CI = sum(MSx) print("\n") if any(isnan.(MSx)) println("Some entropy values may be undefined.") end if Plotx Refined ? strx = "Refined-Composite" : strx = "Composite" p1 = plot(1:Scales, MSx, c=RGB(8/255, 63/255, 77/255), lw=3) scatter!(1:Scales, MSx, markersize=6, c=RGB(1, 0, 1), xlabel = "Scale Factor", ylabel = "Entropy Value", guidefont = font(12, "arial", RGB(7/255, 54/255, 66/255)), tickfontsize = 10, tickfontfamily="arial", legend=false, title = strx*" Multiscale $(Mobj.Func)", plot_titlefontsize=16, plot_titlefontcolor=RGB(7/255, 54/255, 66/255)) #ylim=(0,maximum(MSx)+.2), display(p1) end return MSx, CI end function modified(Z,sx, Tx) Tx == 0 ? Y = (conv(Z,ones(Int,sx))/sx)[sx:end-sx+1] : Y = [std(Z[x:x+sx-1], corrected=false) for x in 1:(length(Z)-sx+1)] return Y end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
7337
module _cMvMSEn export cMvMSEn using Statistics: std, mean, median, var using Plots using DSP: conv """ MSx, CI = cMvMSEn(Data, Mobj) Returns a vector of composite multivariate multiscale entropy values (`MSx`) and the complexity index (`CI`) of the data sequences in `Data` using the parameters specified by the multiscale object (`Mobj`) over 3 temporal scales with coarse-graining (default). !!! note By default, the `MvSampEn` and `MvFuzzEn` multivariate entropy algorithms estimate entropy values using the "full" method by comparing delay vectors across all possible `m+1` expansions of the embedding space as applied in [1]. These methods are not lower-bounded to 0, like most entropy algorithms, so `MvMSEn` may return negative entropy values if the base multivariate entropy function is `MvSampEn` and `MvFuzzEn`, even for stochastic processes... ------------------------------------------------------------- MSx, CI = cMvMSEn(Data, Mobj, Refined = True) Returns a vector of refined-composite multiscale entropy values (`MSx`) for the data sequences in (`Data`) using the parameters specified by the multiscale object (`Mobj`) using the refined-composite multivariate multiscale entropy method (rcMSE) over 3 temporal scales. When `Refined == true`, the base entropy method must be `MvSampEn` or `MvFuzzEn`. If the entropy method is `MvSampEn`, cMvMSEn employs the method described in [1]. If the entropy method is `MvFuzzEn`, cMvMSEn employs the method described in [5]. MSx, CI = cMVMSEn(Data::AbstractArray{T,2} where T<:Real, Mobj::NamedTuple; Scales::Int=3, Refined::Bool="false", Plotx::Bool=false) Returns a vector of multivariate multiscale entropy values (`MSx`) and the complexity index (`CI`) of the data sequences in `Data` using the parameters specified by the multiscale object (`Mobj`) and the following keyword arguments: # Arguments: `Scales` - Number of temporal scales, an integer > 1 (default: 3) \n `Refined` - Refined-composite MvMSEn method. \nWhen `Refined == True` and the entropy function specified by `Mobj` is `MvSampEn` or `MvFuzzEn`, `cMvMSEn` returns the refined-composite multivariate multiscale entropy (rcMSEn) [default: False]\n `Plotx` - When Plotx == true, returns a plot of the entropy value at each time scale (i.e. the multiscale entropy curve) [default: false] # See also `MvMSEn`, `MSobject`, `MvFuzzEn`, `MvSampEn`, `MvPermEn`, `MvCoSiEn`, `MvDispEn` # References: [1] Shuen-De Wu, et al., "Time series analysis using composite multiscale entropy." Entropy 15.3 (2013): 1069-1084. [2] Shuen-De Wu, et al., "Analysis of complex time series using refined composite multiscale entropy." Physics Letters A 378.20 (2014): 1369-1374. [3] Ahmed Mosabber Uddin, Danilo P. Mandic "Multivariate multiscale entropy: A tool for complexity analysis of multichannel data." Physical Review E 84.6 (2011): 061918. [4] Ahmed Mosabber Uddin, Danilo P. Mandic "Multivariate multiscale entropy analysis." IEEE signal processing letters 19.2 (2011): 91-94. [5] Azami, Alberto Fernández, Javier Escudero. "Refined multiscale fuzzy entropy based on standard deviation for biomedical signal analysis." Medical & biological engineering & computing 55 (2017): 2037-2052. """ function cMvMSEn(Data::AbstractArray{T,2} where T<:Real, Mobj::NamedTuple; Scales::Int=3, Refined::Bool=false, Plotx::Bool=false) N, Dn = size(Data) (N>10) && (Dn>1) ? nothing : error("Data: must be an NxM matrix where N>10 and M>1") (length(Mobj) >= 1) ? nothing : error("Mobj: must be a multiscale entropy object created with the function EntropyHub.MSobject") (Scales>1) ? nothing : error("Scales: must be an integer > 1") (Refined && String(Symbol(Mobj.Func)) in ("MvSampEn","MvFuzzEn")) || Refined==false ? nothing : error("Refined: If Refined == true, the base entropy function must be 'MvSampEn' or 'MvFuzzEn'") String(Symbol(Mobj.Func))[1:2] != "Mv" ? error("Base entropy estimator must be a multivariate entropy method. ", "To perform univariate multiscale entropy estimation, use MSEn().") : nothing if Refined if string(Mobj.Func)== "MvFuzzEn" Tx = 1 elseif string(Mobj.Func) == "MvSampEn" Tx = 0 end "Logx" in String.(Symbol.(keys(Mobj))) ? Logx = Mobj.Logx : Logx = exp(1) else Tx = 0 end MSx = zeros(Scales) Args = NamedTuple{keys(Mobj)[2:end]}(Mobj) for T = 1:Scales print(". ") Temp = modified(Data,T,Tx,Dn) N = Int(T*floor(size(Temp,1)/T)) Ma = zeros(T) Mb = zeros(T) for k = 1:T print(". ") if Refined _, Ma[k], Mb[k], _ = Mobj.Func(Temp[k:T:N,:]; Args...) else Ma[k], _, _, _ = Mobj.Func(Temp[k:T:N,:]; Args...) end end Refined ? MSx[T] = -log(Logx, sum(Mb)/sum(Ma)) : MSx[T] = mean(Ma) end CI = sum(MSx) print("\n") if any(isnan.(MSx)) println("Some entropy values may be undefined.") end if Plotx Refined ? strx = "Refined-Composite" : strx = "Composite" p1 = plot(1:Scales, MSx, c=RGB(8/255, 63/255, 77/255), lw=3) scatter!(1:Scales, MSx, markersize=6, c=RGB(1, 0, 1), xlabel = "Scale Factor", ylabel = "Entropy Value", guidefont = font(12, "arial", RGB(7/255, 54/255, 66/255)), tickfontsize = 10, tickfontfamily="arial", legend=false, title = "$(strx) Multivariate Multiscale $(string(Mobj.Func)[3:end])", plot_titlefontsize=16, plot_titlefontcolor=RGB(7/255, 54/255, 66/255)) #ylim=(0,maximum(MSx)+.2), display(p1) end return MSx, CI end function modified(Z, sx, Tx, Dn) if Tx==0 Y = (conv(Z,ones(Int,sx))/sx)[sx:end-sx+1,:] else Ns = size(Z,1)-sx+1 Y = zeros(Ns,Dn) for k in 1:Dn Y[:,k] = map(x -> std(Z[x:x+sx-1,k], corrected=false), 1:Ns) #Y[:,k] = std(reshape(Z[1:sx*Ns, k],Ns,sx),corrected=false,dims=2) end end return Y end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
8858
module _cXMSEn export cXMSEn using Statistics: std, mean, median, var using Plots using DSP: conv """ MSx, CI = cXMSEn(Sig1, Sig2, Mobj) Returns a vector of composite multiscale cross-entropy values (`MSx`) between two univariate data sequences contained in `Sig1` and `Sig2` using the parameters specified by the multiscale object (`Mobj`) using the composite multiscale method (cMSE) over 3 temporal scales. MSx, CI = cXMSEn(Sig1::AbstractVector{T} where T<:Real, Sig2::AbstractVector{T} where T<:Real, Mobj::NamedTuple; Scales::Int=3, RadNew::Int=0, Refined::Bool=false, Plotx::Bool=false) Returns a vector of composite multiscale cross-entropy values (`MSx`) between the data sequences contained in `Sig1` and `Sig2` using the parameters specified by the multiscale object (`Mobj`) and the following keyword arguments: # Arguments: `Scales` - Number of temporal scales, an integer > 1 (default: 3)\n `RadNew` - Radius rescaling method, an integer in the range [1 4]. When the entropy specified by Mobj is `XSampEn` or `XApEn`, RadNew rescales the radius threshold of the sub-sequences at each time scale (Ykj). If a radius value is specified by `Mobj` (`r`), this becomes the rescaling coefficient, otherwise it is set to 0.2 (default). The value of RadNew specifies one of the following methods:\n [1] Pooled Standard Deviation - r*std(Ykj)\n [2] Pooled Variance - r*var(Ykj)\n [3] Total Mean Absolute Deviation - r*mean_ad(Ykj)\n [4] Total Median Absolute Deviation - r*med_ad(Ykj,1)\n `Refined` - Refined-composite XMSEn method. When `Refined` == true and the entropy function specified by `Mobj` is `XSampEn` or `XFuzzEn`, cXMSEn returns the refined-composite multiscale entropy (rcXMSEn). (default: false) `Plotx` - When `Plotx` == true, returns a plot of the entropy value at each time scale (i.e. the multiscale entropy curve) [default: false] # See also `MSobject`, `XMSEn`, `rXMSEn`, `hXMSEn`, `XSampEn`, `XApEn`, `cMSEn` # References: [1] Rui Yan, Zhuo Yang, and Tao Zhang, "Multiscale cross entropy: a novel algorithm for analyzing two time series." 5th International Conference on Natural Computation. Vol. 1, pp: 411-413 IEEE, 2009. [2] Yi Yin, Pengjian Shang, and Guochen Feng, "Modified multiscale cross-sample entropy for complex time series." Applied Mathematics and Computation 289 (2016): 98-110. [3] Madalena Costa, Ary Goldberger, and C-K. Peng, "Multiscale entropy analysis of complex physiologic time series." Physical review letters 89.6 (2002): 068102. [4] Antoine Jamin, et al, "A novel multiscale cross-entropy method applied to navigation data acquired with a bike simulator." 41st annual international conference of the IEEE EMBC IEEE, 2019. [5] Antoine Jamin and Anne Humeau-Heurtier. "(Multiscale) Cross-Entropy Methods: A Review." Entropy 22.1 (2020): 45. [6] Shuen-De Wu, et al., "Time series analysis using composite multiscale entropy." Entropy 15.3 (2013): 1069-1084. """ function cXMSEn(Sig1::AbstractVector{T} where T<:Real, Sig2::AbstractVector{T} where T<:Real, Mobj::NamedTuple; Scales::Int=3, RadNew::Int=0, Refined::Bool=false, Plotx::Bool=false) (size(Sig1,1)>=10) && (size(Sig2,1)>=10) ? nothing : error("Sig1/Sig2: sequences must have >= 10 values") (length(Mobj) >= 1) ? nothing : error("Mobj: must be a multiscale entropy object created with the function EntropyHub.MSobject") (Scales>1) ? nothing : error("Scales: must be an integer > 1") (RadNew==0 || (RadNew in 1:4 && String(Symbol(Mobj.Func)) in ("XSampEn","XApEn"))) ? nothing : error("RadNew: must be 0, or an integer in range [1 4] with entropy function 'XSampEn' or 'XApEn'") (Refined && String(Symbol(Mobj.Func)) in ("XSampEn","XFuzzEn")) || Refined==false ? nothing : error("Refined: If Refined == true, the base entropy function must be 'XSampEn' or 'XFuzzEn'") String(Symbol(Mobj.Func))=="XSampEn" ? Mobj = merge(Mobj,(Vcp=false,)) : nothing if Refined && String(Symbol(Mobj.Func))=="XFuzzEn" Tx = 1; "Logx" in String.(Symbol.(keys(Mobj))) ? Logx = Mobj.Logx : Logx = exp(1); elseif Refined && String(Symbol(Mobj.Func))=="XSampEn" Tx = 0; "Logx" in String.(Symbol.(keys(Mobj))) ? Logx = Mobj.Logx : Logx = exp(1); else Tx = 0; end MSx = zeros(Scales) Args = NamedTuple{keys(Mobj)[2:end]}(Mobj) if RadNew > 0 if RadNew == 1 Rnew = (x,y) -> sqrt((var(x)*(size(x,1)-1) + var(y)*(size(y,1)-1))/(size(x,1)+size(y,1)-1)) elseif RadNew == 2 Rnew = (x,y) -> ((var(x)*(size(x,1)-1) + var(y)*(size(y,1)-1))/(size(x,1)+size(y,1)-1)) elseif RadNew == 3 Rnew = (x,y) -> mean(abs.(vcat(x,y) .- mean(vcat(x,y)))) elseif RadNew == 4 Rnew = (x,y) -> median(abs.(vcat(x,y) .- median(vcat(x,y)))) end if haskey(Mobj,:r) Cx = Mobj.r else Cy = ("Pooled Standard Deviation","Pooled Variance","Total Mean Abs Deviation", "Total Median Abs Deviation") @warn("No radius value provided in Mobj. Default set to 0.2*$(Cy[RadNew]) of each new time-series.") Cx = .2 end end for T = 1:Scales TempA, TempB = modified(Sig1, Sig2, T, Tx) N1 = Int(T*floor(size(TempA,1)/T)) N2 = Int(T*floor(size(TempB,1)/T)) Temp3 = zeros(T) Temp2 = zeros(T) for k = 1:T print(" .") RadNew > 0 ? Args = (Args..., r=Cx*Rnew(TempA[k:T:N1], TempB[k:T:N2])) : nothing if Refined == 1 _, Ma, Mb = Mobj.Func(TempA[k:T:N1], TempB[k:T:N2]; Args...) Temp2[k] = Ma[end] Temp3[k] = Mb[end] else Temp2 = Mobj.Func(TempA[k:T:N1], TempB[k:T:N2]; Args...) typeof(Temp2)<:Tuple ? Temp3[k] = Temp2[1][end] : Temp3[k] = Temp2[end] #Temp3[k] = Temp2[1][end] end end # Refined == 1 ? MSx[T] = -log(sum(Temp2)/sum(Temp3)) : MSx[T] = mean(Temp3) if Refined && Tx==0 MSx[T] = -log(sum(Temp2)/sum(Temp3))/log(Logx) elseif Refined && Tx==1 MSx[T] = -log(sum(Temp3)/sum(Temp2))/log(Logx) else MSx[T] = mean(Temp3) end end CI = sum(MSx) print("\n") if any(isnan.(MSx)) println("Some entropy values may be undefined.") end if Plotx Refined ? strx = "Refined-Composite" : strx = "Composite" p1 = plot(1:Scales, MSx, c=RGB(8/255, 63/255, 77/255), lw=3) scatter!(1:Scales, MSx, markersize=6, c=RGB(1, 0, 1), xlabel = "Scale Factor", ylabel = "Entropy Value", guidefont = font(12, "arial", RGB(7/255, 54/255, 66/255)), tickfontsize = 10, tickfontfamily="arial", legend=false, title = strx*" Multiscale $(Mobj.Func)", plot_titlefontsize=16, plot_titlefontcolor=RGB(7/255, 54/255, 66/255)) display(p1) end return MSx, CI end function modified(Za, Zb, sx, Tx) if Tx==1 Y1 = [std(Za[x:x+sx-1], corrected=false) for x in 1:(length(Za)-sx+1)] Y2 = [std(Zb[x:x+sx-1], corrected=false) for x in 1:(length(Zb)-sx+1)] else Y1 = (conv(Za,ones(Int, sx))/sx)[sx:end-sx+1][:] Y2 = (conv(Zb,ones(Int, sx))/sx)[sx:end-sx+1][:] end return Y1, Y2 end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
9261
module _hMSEn export hMSEn using Statistics: std, mean, median, var using Plots """ MSx, Sn, CI = hMSEn(Sig, Mobj) Returns a vector of entropy values (`MSx`) calculated at each node in the hierarchical tree, the average entropy value across all nodes at each scale (Sn), and the complexity index (`CI`) of the hierarchical tree (i.e. sum(Sn)) for the data sequence (`Sig`) using the parameters specified by the multiscale object (`Mobj`) over 3 temporal scales (default). The entropy values in MSx are ordered from the root node (S.00) to the Nth subnode at scale T (S.TN): i.e. S.00, S.10, S.11, S.20, S.21, S.22, S.23, S.30, S.31, S.32, S.33, S.34, S.35, S.36, S.37, S.40, ... , S.TN. The average entropy values in Sn are ordered in the same way, with the value of the root node given first: i.e. S0, S1, S2, ..., ST MSx, Sn, CI = hMSEn(Sig::AbstractArray{T,1} where T<:Real, Mobj::NamedTuple; Scales::Int=3, RadNew::Int=0, Plotx::Bool=false) Returns a vector of entropy values (`MSx`) calculated at each node in the hierarchical tree, the average entropy value across all nodes at each scale (Sn), and the complexity index (CI) of the entire hierarchical tree for the data sequence (`Sig`) using the following 'keyword' arguments: # Arguments: `Scales` - Number of temporal scales, an integer > 1 (default: 3) At each scale (T), entropy is estimated for 2^(T-1) nodes.\n `RadNew` - Radius rescaling method, an integer in the range [1 4]. When the entropy specified by `Mobj` is `SampEn` or `ApEn`, `RadNew` allows the radius threshold to be updated at each node in the tree. If a radius value is specified by `Mobj` (`r`), this becomes the rescaling coefficient, otherwise it is set to 0.2 (default). The value of `RadNew` specifies one of the following methods:\n [1] Standard Deviation - r*std(Xt)\n [2] Variance - r*var(Xt)\n [3] Mean Absolute Deviation - r*mean_ad(Xt)\n [4] Median Absolute Deviation - r*med_ad(Xt,1)\n `Plotx` - When `Plotx` == true, returns a plot of the average entropy value at each time scale (i.e. the multiscale entropy curve) and a hierarchical graph showing the entropy value of each node in the hierarchical tree decomposition. (default: false)\n # See also `MSobject`, `MSEn`, `cMSEn`, `rMSEn`, `SampEn`, `ApEn`, `XMSEn` # References: [1] Ying Jiang, C-K. Peng and Yuesheng Xu, "Hierarchical entropy analysis for biological signals." Journal of Computational and Applied Mathematics 236.5 (2011): 728-742. """ function hMSEn(Sig::AbstractArray{T,1} where T<:Real, Mobj::NamedTuple; Scales::Int=3, RadNew::Int=0, Plotx::Bool=false) (size(Sig,1)>10) ? nothing : error("Sig: must be a numeric vector" ) (length(Mobj) >= 1) ? nothing : error("Mobj: must be a multiscale entropy object created with the function EntropyHub.MSobject") (Scales>1) ? nothing : error("Scales: must be an integer > 1") (RadNew==0 || (RadNew in 1:4 && String(Symbol(Mobj.Func)) in ("SampEn","ApEn"))) ? nothing : error("RadNew: must be 0, or an integer in range [1 4] with entropy function `SampEn` or `ApEn`") lowercase(String(Symbol(Mobj.Func))[1]) == 'x' ? error("Base entropy estimator is a cross-entropy method. To perform heirarchical multiscale CROSS-entropy estimation, use hXMSEn.") : nothing String(Symbol(Mobj.Func))=="SampEn" ? Mobj = merge(Mobj,(Vcp=false,)) : nothing if RadNew > 0 if RadNew == 1 Rnew = x -> std(x, corrected=false) elseif RadNew == 2 Rnew = x -> var(x, corrected=false) elseif RadNew == 3 Rnew = x -> mean(abs.(x .- mean(x))) elseif RadNew == 4 Rnew = x -> median(abs.(x .- median(x))) end if haskey(Mobj,:r) Cx = Mobj.r else Cy = ("Standard Deviation","Variance","Mean Abs Deviation", "Median Abs Deviation") @warn("No radius value provided in Mobj. Default set to 0.2*$(Cy[RadNew]) of each new time-series.") Cx = .2 end end XX, N = Hierarchy(Sig, Scales) MSx = zeros(size(XX,1)) Args = NamedTuple{keys(Mobj)[2:end]}(Mobj) for T in eachindex(XX[:,1]) # 1:size(XX,1) print(". ") Temp = XX[T,1:Int(N/(2^(floor(log2(T)))))] RadNew > 0 ? Args = (Args..., r=Cx*Rnew(Temp[:])) : nothing Temp2 = Mobj.Func(Temp[:]; Args...) typeof(Temp2)<:Tuple ? MSx[T] = Temp2[1][end] : MSx[T] = Temp2[end] end Sn = zeros(Scales) for t = 1:Scales Sn[t] = mean(MSx[2^(t-1):(2^t)-1]) end CI = sum(Sn) print("\n") if any(isnan.(MSx)) println("Some entropy values may be undefined.") end if Plotx p1 = plot(1:Scales, Sn, c=RGB(8/255, 63/255, 77/255), lw=3) scatter!(1:Scales, Sn, markersize=6, c=RGB(1, 0, 1), xlabel = "Scale Factor", ylabel = "Entropy Value", guidefont = font(12, "arial", RGB(7/255, 54/255, 66/255)), tickfontsize = 10, tickfontfamily="arial", legend=false, title = "Hierarchical Multiscale $(Mobj.Func) Entropy", grid=false, xlim=(0.5,Scales+.5), ylim=(minimum(Sn)-.25,maximum(Sn)+.25), plot_titlefontsize=16, plot_titlefontcolor=RGB(7/255, 54/255, 66/255)) N = 2^(Scales-1) x = zeros(2*N - 1) x[1] = N y = Scales.*(Scales .- floor.(Int, log2.(1:(2*N)-1))) for k = 1:2*N-1 Q = floor(Int, log2(k)) P = floor(Int,k/2) if k>1 Bool(k%2) ? x[k] = x[P] + N/(2^Q) : x[k] = x[P] - N/(2^Q) end end Edges = hcat(repeat(1:N-1,inner=2),2:2*N-1) labx = [k for k in string.(round.(MSx,digits=3))] p2 = scatter(x,y,markersize=10*(MSx.-(minimum(MSx)).+1)./(abs(minimum(MSx))+1), c=RGB(1,0,1), legend=false, xticks=false, yticks=false) #, txt=labx, markerfontsize=8) annotate!(x, y.+1, labx, 12-Scales) for k = 1:length(x)-1 plot!(x[Edges[k,:]],y[Edges[k,:]],c=RGB(8/255,63/255,77/255), lw=2.5, ylim=(Scales-1, maximum(y)+1), xlim=(0,2*N), grid=false) end px = plot() pt = plot(p1, px, p2, layout = grid(3,1, heights=[0.2,0.1, 0.7])) display(pt) end return MSx, Sn, CI end function Hierarchy(Z,sx) N = Int(2^floor(log2(size(Z,1)))) if mod(log2(size(Z,1)),1) != 0 @warn("Only first $(N) samples were used in hierarchical decomposition. The last $(length(Z)-N) samples of the data sequence were ignored.") end if N/(2^(sx-1)) < 8 error("Data length ($(N)) is too short to estimate entropy at the lowest subtree. Consider reducing the number of scales.") end Z = Z[1:N] U = zeros((2^sx)-1,N) U[1,:] = Z; p=2 for k = 1:sx-1 for n = 1:2^(k-1) Temp = U[2^(k-1)+n-1,:] U[p,1:Int(N/2)] = (Temp[1:2:end] + Temp[2:2:end])/2 U[p+1,1:Int(N/2)]= (Temp[1:2:end] - Temp[2:2:end])/2 p=p+2 end end return U, N end end """ MM = zeros(2*Scales - 1,T) mid = Int(ceil(T/2)) for t = 1:Scales MM[2*t -1, mid-(2^(t-1))+1:2:mid-1+(2^(t-1))] = MSx[2^(t-1):(2^t)-1] end b = bar3(MM) zlim([min(MSx(MSx>0)) max(MSx)]); cmap = colormap('cool'); colormap([1 1 1; cmap]) for k = 1:length(b) zdata = b(k).ZData; b(k).CData = zdata; b(k).FaceColor = 'interp'; end axis square, view([30 55]) yticks(1:2:(2*T -1)); yticklabels(0:T-1) xticks(''); % xticks(1:2:(2*p.Results.Scales - 1)) xlabel('Subtree Nodes','FontSize',12,'FontWeight','bold','Color',[7 54 66]/255) ylabel('Scale Factor','FontSize',12,'FontWeight','bold','Color',[7 54 66]/255) zlabel('Entropy','FontSize',12,'FontWeight','bold','Color',[7 54 66]/255) title(sprintf('Hierarchical Multiscale (%s) Entropy',func2str(Y{1})),... 'FontSize',16,'FontWeight','bold','Color',[7 54 66]/255) """ """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
11063
module _hXMSEn export hXMSEn using Statistics: std, mean, median, var using Plots """ MSx, Sn, CI = hXMSEn(Sig1, Sig2, Mobj) Returns a vector of cross-entropy values (`MSx`) calculated at each node in the hierarchical tree, the average cross-entropy value across all nodes at each scale (`Sn`), and the complexity index (`CI`) of the hierarchical tree (i.e. sum(`Sn`)) between the data sequences contained in `Sig1` and `Sig2` using the parameters specified by the multiscale object (`Mobj`) over 3 temporal scales (default). The entropy values in `MSx` are ordered from the root node (S.00) to the Nth subnode at scale T (S.TN): i.e. S.00, S.10, S.11, S.20, S.21, S.22, S.23, S.30, S.31, S.32, S.33, S.34, S.35, S.36, S.37, S.40, ... , S.TN. The average cross-entropy values in Sn are ordered in the same way, with the value of the root node given first: i.e. S0, S1, S2, ..., ST MSx, Sn, CI = hXMSEn(Sig1::AbstractVector{T} where T<:Real, Sig2::AbstractVector{T} where T<:Real, Mobj::NamedTuple; Scales::Int=3, RadNew::Int=0, Plotx::Bool=false) Returns a vector of cross-entropy values (`MSx`) calculated at each node in the hierarchical tree, the average cross-entropy value across all nodes at each scale (`Sn`), and the complexity index (`CI`) of the entire hierarchical tree between the data sequences contained in `Sig1` and `Sig2` using the following name/value pair arguments: # Arguments: `Scales` - Number of temporal scales, an integer > 1 (default: 3) At each scale (T), entropy is estimated for 2^(T-1) nodes. \n `RadNew` - Radius rescaling method, an integer in the range [1 4]. When the entropy specified by `Mobj` is `XSampEn` or `XApEn`, `RadNew` allows the radius threshold to be updated at each node in the tree. If a radius value is specified by `Mobj` (`r`), this becomes the rescaling coefficient, otherwise it is set to 0.2 (default). The value of `RadNew` specifies one of the following methods: \n [1] Pooled Standard Deviation - r*std(Xt) \n [2] Pooled Variance - r*var(Xt) \n [3] Total Mean Absolute Deviation - r*mean_ad(Xt) \n [4] Total Median Absolute Deviation - r*med_ad(Xt) \n `Plotx` - When `Plotx` == true, returns a plot of the average cross-entropy value at each time scale (i.e. the multiscale entropy curve) and a hierarchical graph showing the entropy value of each node in the hierarchical tree decomposition. (default: false) \n # See also `MSobject`, `XMSEn`, `rXMSEn`, `cXMSEn`, `XSampEn`, `XApEn`, `hMSEn` # References: [1] Matthew W. Flood (2021), "EntropyHub - An open source toolkit for entropic time series analysis" PLoS ONE 16(11):e0295448, DOI: 10.1371/journal.pone.0259448 https://www.EntropyHub.xyz [2] Rui Yan, Zhuo Yang, and Tao Zhang, "Multiscale cross entropy: a novel algorithm for analyzing two time series." 5th International Conference on Natural Computation. Vol. 1, pp: 411-413 IEEE, 2009. [3] Ying Jiang, C-K. Peng and Yuesheng Xu, "Hierarchical entropy analysis for biological signals." Journal of Computational and Applied Mathematics 236.5 (2011): 728-742. """ function hXMSEn(Sig1::AbstractVector{T} where T<:Real, Sig2::AbstractVector{T} where T<:Real, Mobj::NamedTuple; Scales::Int=3, RadNew::Int=0, Plotx::Bool=false) (size(Sig1,1)>=10) && (size(Sig2,1)>=10) ? nothing : error("Sig1/Sig2: sequences must have >= 10 values") (length(Mobj) >= 1) ? nothing : error("Mobj: must be a multiscale entropy object created with the function EntropyHub.MSobject") (Scales>1) ? nothing : error("Scales: must be an integer > 1") (RadNew==0 || (RadNew in 1:4 && String(Symbol(Mobj.Func)) in ("XSampEn","XApEn"))) ? nothing : error("RadNew: must be 0, or an integer in range [1 4] with entropy function `XSampEn` or `XApEn`") String(Symbol(Mobj.Func))=="XSampEn" ? Mobj = merge(Mobj,(Vcp=false,)) : nothing Args = NamedTuple{keys(Mobj)[2:end]}(Mobj) if RadNew > 0 if RadNew == 1 Rnew = (x,y) -> sqrt((var(x)*(size(x,1)-1) + var(y)*(size(y,1)-1))/(size(x,1)+size(y,1)-1)) elseif RadNew == 2 Rnew = (x,y) -> ((var(x)*(size(x,1)-1) + var(y)*(size(y,1)-1))/(size(x,1)+size(y,1)-1)) elseif RadNew == 3 Rnew = (x,y) -> mean(abs.(vcat(x,y) .- mean(vcat(x,y)))) elseif RadNew == 4 Rnew = (x,y) -> median(abs.(vcat(x,y) .- median(vcat(x,y)))) end if haskey(Mobj,:r) Cx = Mobj.r else Cy = ("Pooled Standard Deviation","Pooled Variance","Total Mean Abs Deviation", "Total Median Abs Deviation") @warn("No radius value provided in Mobj. Default set to 0.2*$(Cy[RadNew]) of each new time-series.") Cx = .2 end end XX, YY, Na, Nb = Hierarchy(Sig1, Sig2, Scales) MSx = zeros(size(XX,1)) for T in eachindex(XX[:,1]) # = 1:size(XX,1) print(" .") TempA = XX[T,1:Int(Na/(2^(floor(log2(T)))))] TempB = YY[T,1:Int(Nb/(2^(floor(log2(T)))))] RadNew > 0 ? Args = (Args..., r=Cx*Rnew(TempA, TempB)) : nothing Temp2 = Mobj.Func(TempA, TempB; Args...) typeof(Temp2)<:Tuple ? MSx[T] = Temp2[1][end] : MSx[T] = Temp2[end] end Sn = zeros(Scales) for t = 1:Scales Sn[t] = mean(MSx[2^(t-1):(2^t)-1]) end CI = sum(Sn) print("\n") if any(isnan.(MSx)) println("Some entropy values may be undefined.") end if Plotx p1 = plot(1:Scales, Sn, c=RGB(8/255, 63/255, 77/255), lw=3) scatter!(1:Scales, Sn, markersize=6, c=RGB(1, 0, 1), xlabel = "Scale Factor", ylabel = "Entropy Value", guidefont = font(12, "arial", RGB(7/255, 54/255, 66/255)), tickfontsize = 10, tickfontfamily="arial", legend=false, title = "Hierarchical Multiscale $(Mobj.Func) Entropy", grid=false, xlim=(0.5,Scales+.5), ylim=(minimum(Sn)-.25,maximum(Sn)+.25), plot_titlefontsize=16, plot_titlefontcolor=RGB(7/255, 54/255, 66/255)) N = 2^(Scales-1) x = zeros(2*N - 1) x[1] = N y = Scales.*(Scales .- floor.(Int, log2.(1:(2*N)-1))) for k = 1:2*N-1 Q = floor(Int, log2(k)) P = floor(Int,k/2) if k>1 Bool(k%2) ? x[k] = x[P] + N/(2^Q) : x[k] = x[P] - N/(2^Q) end end Edges = hcat(repeat(1:N-1,inner=2),2:2*N-1) labx = [k for k in string.(round.(MSx,digits=3))] p2 = scatter(x,y,markersize=10*(MSx.-(minimum(MSx)).+1)./(abs(minimum(MSx))+1), c=RGB(1,0,1), legend=false, xticks=false, yticks=false) #, txt=labx, markerfontsize=8) annotate!(x, y.+1, labx, 12-Scales) for k = 1:length(x)-1 plot!(x[Edges[k,:]],y[Edges[k,:]],c=RGB(8/255,63/255,77/255), lw=2.5, ylim=(Scales-1, maximum(y)+1), xlim=(0,2*N), grid=false) end px = plot() pt = plot(p1, px, p2, layout = grid(3,1, heights=[0.2,0.1, 0.7])) display(pt) end return MSx, Sn, CI end function Hierarchy(Za, Zb,sx) Na = Int(2^floor(log2(size(Za,1)))) Nb = Int(2^floor(log2(size(Zb,1)))) if mod(log2(size(Za,1)),1) != 0 @warn("Only first $(Na) samples were used in hierarchical decomposition. The last $(size(Za,1)-Na) samples of the data sequence were ignored.") end if mod(log2(size(Zb,1)),1) != 0 @warn("Only first $(Nb) samples were used in hierarchical decomposition. The last $(size(Zb,1)-Nb) samples of the data sequence were ignored.") end if Na/(2^(sx-1)) < 8 error("Data length ($(Na)) of Sig1 is too short to estimate entropy at the lowest subtree. Consider reducing the number of scales.") elseif Nb/(2^(sx-1)) < 8 error("Data length ($(Nb)) of Sig2 is too short to estimate entropy at the lowest subtree. Consider reducing the number of scales.") end Za = Za[1:Na,:] Zb = Zb[1:Nb,:] U1 = zeros((2^sx)-1,Na); U2 = zeros((2^sx)-1,Nb); U1[1,:] = Za; U2[1,:] = Zb; p=2 for k = 1:sx-1 for n = 1:2^(k-1) Temp = U1[2^(k-1)+n-1,:] U1[p,1:Int(Na/2)] = (Temp[1:2:end] + Temp[2:2:end])/2 U1[p+1,1:Int(Na/2)]= (Temp[1:2:end] - Temp[2:2:end])/2 p +=2 end end p=2 for k = 1:sx-1 for n = 1:2^(k-1) Temp = U2[2^(k-1)+n-1,:] U2[p,1:Int(Nb/2)] = (Temp[1:2:end] + Temp[2:2:end])/2 U2[p+1,1:Int(Nb/2)]= (Temp[1:2:end] - Temp[2:2:end])/2 p +=2 end end return U1, U2, Na, Nb end end """ MM = zeros(2*Scales - 1,T) mid = Int(ceil(T/2)) for t = 1:Scales MM[2*t -1, mid-(2^(t-1))+1:2:mid-1+(2^(t-1))] = MSx[2^(t-1):(2^t)-1] end b = bar3(MM) zlim([min(MSx(MSx>0)) max(MSx)]); cmap = colormap('cool'); colormap([1 1 1; cmap]) for k = 1:length(b) zdata = b(k).ZData; b(k).CData = zdata; b(k).FaceColor = 'interp'; end axis square, view([30 55]) yticks(1:2:(2*T -1)); yticklabels(0:T-1) xticks(''); % xticks(1:2:(2*p.Results.Scales - 1)) xlabel('Subtree Nodes','FontSize',12,'FontWeight','bold','Color',[7 54 66]/255) ylabel('Scale Factor','FontSize',12,'FontWeight','bold','Color',[7 54 66]/255) zlabel('Entropy','FontSize',12,'FontWeight','bold','Color',[7 54 66]/255) title(sprintf('Hierarchical Multiscale (%s) Entropy',func2str(Y{1})),... 'FontSize',16,'FontWeight','bold','Color',[7 54 66]/255) """ """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
7594
module _rMSEn export rMSEn using Statistics: std, mean, median, var using DSP.Filters: filtfilt, Butterworth, Lowpass, digitalfilter using Plots """ MSx, CI = rMSEn(Sig, Mobj) Returns a vector of refined multiscale entropy values (`MSx`) and the complexity index (`CI`) of the data sequence (`Sig`) using the parameters specified by the multiscale object (`Mobj`) and the following default parameters: Scales = 3, Butterworth LPF Order = 6, Butterworth LPF cutoff frequency at scale (T): Fc = 0.5/T. If the entropy function specified by `Mobj` is SampEn or ApEn, rMSEn updates the threshold radius of the data sequence (Xt) at each scale to 0.2std(Xt) if no `r` value is provided by Mobj, or r.std(Xt) if `r` is specified. MSx, CI = rMSEn(Sig::AbstractArray{T,1} where T<:Real, Mobj::NamedTuple; Scales::Int=3, F_Order::Int=6, F_Num::Float64=0.5, RadNew::Int=0, Plotx::Bool=false) Returns a vector of refined multiscale entropy values (`MSx`) and the complexity index (`CI`) of the data sequence (`Sig`) using the parameters specified by the multiscale object (`Mobj`) and the following 'keyword' arguments: # Arguments: `Scales` - Number of temporal scales, an integer > 1 (default = 3) \n `F_Order` - Butterworth low-pass filter order, a positive integer (default: 6) \n `F_Num` - Numerator of Butterworth low-pass filter cutoff frequency, a scalar value in range [0 < `F_Num` < 1]. The cutoff frequency at each scale (T) becomes: Fc = `F_Num/T. (default: 0.5) \n `RadNew` - Radius rescaling method, an integer in the range [1 4]. When the entropy specified by `Mobj` is `SampEn` or `ApEn`, `RadNew` allows the radius threshold to be updated at each time scale (Xt). If a radius value is specified by `Mobj` (`r`), this becomes the rescaling coefficient, otherwise it is set to 0.2 (default). The value of `RadNew` specifies one of the following methods:\n [1] Standard Deviation - r*std(Xt)\n [2] Variance - r*var(Xt) \n [3] Mean Absolute Deviation - r*mean_ad(Xt) \n [4] Median Absolute Deviation - r*med_ad(Xt)\n `Plotx` - When `Plotx` == true, returns a plot of the entropy value at each time scale (i.e. the multiscale entropy curve) [default: false] \n # See also `MSobject`, `MSEn`, `cMSEn`, `hMSEn`, `SampEn`, `ApEn`, `XMSEn` # References: [1] Madalena Costa, Ary Goldberger, and C-K. Peng, "Multiscale entropy analysis of complex physiologic time series." Physical review letters 89.6 (2002): 068102. [2] Vadim V. Nikulin, and Tom Brismar, "Comment on “Multiscale entropy analysis of complex physiologic time series”." Physical review letters 92.8 (2004): 089803. [3] Madalena Costa, Ary L. Goldberger, and C-K. Peng. "Costa, Goldberger, and Peng reply." Physical Review Letters 92.8 (2004): 089804. [4] José Fernando Valencia, et al., "Refined multiscale entropy: Application to 24-h holter recordings of heart period variability in healthy and aortic stenosis subjects." IEEE Transactions on Biomedical Engineering 56.9 (2009): 2202-2213. [5] Puneeta Marwaha and Ramesh Kumar Sunkaria, "Optimal selection of threshold value ‘r’for refined multiscale entropy." Cardiovascular engineering and technology 6.4 (2015): 557-576. """ function rMSEn(Sig::AbstractArray{T,1} where T<:Real, Mobj::NamedTuple; Scales::Int=3, F_Order::Int=6, F_Num::Float64=0.5, RadNew::Int=0, Plotx::Bool=false) (size(Sig,1)>10) ? nothing : error("Sig: must be a numeric vector" ) (length(Mobj) >= 1) ? nothing : error("Mobj: must be a multiscale entropy object created with the function EntropyHub.MSobject") (Scales>1) ? nothing : error("Scales: must be an integer > 1") (F_Order>1) ? nothing : error("F_Order: must be an integer > 1") (0 < F_Num < 1) ? nothing : error("F_Num: must be a scalar in range 0 < F_Num < 1") (RadNew==0 || (RadNew in 1:4 && String(Symbol(Mobj.Func)) in ("SampEn","ApEn"))) ? nothing : error("RadNew: must be 0, or an integer in range [1 4] with entropy function `SampEn` or `ApEn`") lowercase(String(Symbol(Mobj.Func))[1]) == 'x' ? error("Base entropy estimator is a cross-entropy method. To perform refined multiscale CROSS-entropy estimation, use rXMSEn.") : nothing String(Symbol(Mobj.Func))=="SampEn" ? Mobj = merge(Mobj,(Vcp=false,)) : nothing MSx = zeros(Scales) Args = NamedTuple{keys(Mobj)[2:end]}(Mobj) (RadNew==0 && String(Symbol(Mobj.Func)) in ("SampEn","ApEn")) ? RadNew=1 : nothing if RadNew > 0 if RadNew == 1 Rnew = x -> std(x, corrected=false) elseif RadNew == 2 Rnew = x -> var(x, corrected=false) elseif RadNew == 3 Rnew = x -> mean(abs.(x .- mean(x))) elseif RadNew == 4 Rnew = x -> median(abs.(x .- median(x))) end if haskey(Mobj,:r) Cx = Mobj.r else Cy = ("Standard Deviation","Variance","Mean Abs Deviation", "Median Abs Deviation") @warn("No radius value provided in Mobj. Default set to 0.2*$(Cy[RadNew]) of each new time-series.") Cx = .2 end end for T = 1:Scales print(". ") Temp = refined(Sig,T,F_Order,F_Num) RadNew > 0 ? Args = (Args..., r=Cx*Rnew(Temp[:])) : nothing Tempx = Mobj.Func(Temp[:]; Args...) #MSx[T] = Tempx[1][end] typeof(Tempx)<:Tuple ? MSx[T] = Tempx[1][end] : MSx[T] = Tempx[end] end CI = sum(MSx) print("\n") if any(isnan.(MSx)) println("Some entropy values may be undefined.") end if Plotx p1 = plot(1:Scales, MSx, c=RGB(8/255, 63/255, 77/255), lw=3) scatter!(1:Scales, MSx, markersize=6, c=RGB(1, 0, 1), xlabel = "Scale Factor", ylabel = "Entropy Value", guidefont = font(12, "arial", RGB(7/255, 54/255, 66/255)), tickfontsize = 10, tickfontfamily="arial", legend=false, title = "Refined Multiscale $(Mobj.Func)", plot_titlefontsize=16, plot_titlefontcolor=RGB(7/255, 54/255, 66/255)) display(p1) end return MSx, CI end function refined(Z,sx,P1,P2) Yt = filtfilt(digitalfilter(Lowpass(P2/sx), Butterworth(P1)), Z) return Yt[1:sx:end] end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
8528
module _rXMSEn export rXMSEn using DSP.Filters: filtfilt, Butterworth, Lowpass, digitalfilter using Statistics: std, mean, median, var using Plots """ MSx, CI = rXMSEn(Sig1, Sig2, Mobj) Returns a vector of refined multiscale cross-entropy values (`MSx`) and the complexity index (`CI`) between the data sequences contained in `Sig1` and `Sig2` using the parameters specified by the multiscale object (`Mobj`) and the following default parameters: Scales = 3, Butterworth LPF Order = 6, Butterworth LPF cutoff frequency at scale (T): Fc = 0.5/T. If the entropy function specified by `Mobj` is `XSampEn` or `XApEn`, `rMSEn` updates the threshold radius of the data sequences (Xt) at each scale to 0.2*SDpooled(Xa, Xb) when no `r` value is provided by `Mobj`, or `r`*SDpooled(Xa, Xb) if `r` is specified. MSx, CI = rXMSEn(Sig1::AbstractVector{T} where T<:Real, Sig2::AbstractVector{T} where T<:Real, Mobj::NamedTuple; Scales::Int=3, F_Order::Int=6, F_Num::Float64=0.5, RadNew::Int=0, Plotx::Bool=false) Returns a vector of refined multiscale cross-entropy values (`MSx`) and the complexity index (`CI`) between the data sequences contained in `Sig1` and `Sig2` using the parameters specified by the multiscale object (`Mobj`) and the following keyword arguments: # Arguments: `Scales` - Number of temporal scales, an integer > 1 (default: 3) \n `F_Order` - Butterworth low-pass filter order, a positive integer (default: 6) \n `F_Num` - Numerator of Butterworth low-pass filter cutoff frequency, a scalar value in range [0 < `F_Num` < 1]. The cutoff frequency at each scale (T) becomes: Fc = `F_Num`/T. (default: 0.5) \n `RadNew` - Radius rescaling method, an integer in the range [1 4]. When the entropy specified by `Mobj` is `XSampEn` or `XApEn`, `RadNew` allows the radius threshold to be updated at each time scale (Xt). If a radius value is specified by `Mobj` (`r`), this becomes the rescaling coefficient, otherwise it is set to 0.2 (default). The value of `RadNew` specifies one of the following methods: \n [1] Pooled Standard Deviation - r*std(Xt) \n [2] Pooled Variance - r*var(Xt) \n [3] Total Mean Absolute Deviation - r*mean_ad(Xt) \n [4] Total Median Absolute Deviation - r*med_ad(Xt) \n `Plotx` - When `Plotx` == true, returns a plot of the entropy value at each time scale (i.e. the multiscale entropy curve) [default = false] \n # See also `MSobject`, `XMSEn`, `cXMSEn`, `hXMSEn`, `XSampEn`, `XApEn`, `MSEn` # References: [1] Matthew W. Flood (2021), "EntropyHub - An open source toolkit for entropic time series analysis" PLoS ONE 16(11):e0295448, DOI: 10.1371/journal.pone.0259448 https://www.EntropyHub.xyz [2] Rui Yan, Zhuo Yang, and Tao Zhang, "Multiscale cross entropy: a novel algorithm for analyzing two time series." 5th International Conference on Natural Computation. Vol. 1, pp: 411-413 IEEE, 2009. [3] José Fernando Valencia, et al., "Refined multiscale entropy: Application to 24-h holter recordings of heart period variability in healthy and aortic stenosis subjects." IEEE Transactions on Biomedical Engineering 56.9 (2009): 2202-2213. [4] Puneeta Marwaha and Ramesh Kumar Sunkaria, "Optimal selection of threshold value ‘r’for refined multiscale entropy." Cardiovascular engineering and technology 6.4 (2015): 557-576. [5] Yi Yin, Pengjian Shang, and Guochen Feng, "Modified multiscale cross-sample entropy for complex time series." Applied Mathematics and Computation 289 (2016): 98-110. [6] Antoine Jamin, et al, "A novel multiscale cross-entropy method applied to navigation data acquired with a bike simulator." 41st annual international conference of the IEEE EMBC IEEE, 2019. [7] Antoine Jamin and Anne Humeau-Heurtier. "(Multiscale) Cross-Entropy Methods: A Review." Entropy 22.1 (2020): 45. """ function rXMSEn(Sig1::AbstractVector{T} where T<:Real, Sig2::AbstractVector{T} where T<:Real, Mobj::NamedTuple; Scales::Int=3, F_Order::Int=6, F_Num::Float64=0.5, RadNew::Int=0, Plotx::Bool=false) (size(Sig1,1)>=10) && (size(Sig2,1)>=10) ? nothing : error("Sig1/Sig2: sequences must have >= 10 values") (length(Mobj) >= 1) ? nothing : error("Mobj: must be a multiscale entropy object created with the function EntropyHub.MSobject") (Scales>1) ? nothing : error("Scales: must be an integer > 1") (F_Order>1) ? nothing : error("F_Order: must be an integer > 1") (0 < F_Num < 1) ? nothing : error("F_Num: must be a scalar in range 0 < F_Num < 1") (RadNew==0 || (RadNew in 1:4 && String(Symbol(Mobj.Func)) in ("XSampEn","XApEn"))) ? nothing : error("RadNew: must be 0, or an integer in range [1 4] with entropy function `XSampEn` or `XApEn`") String(Symbol(Mobj.Func))=="XSampEn" ? Mobj = merge(Mobj,(Vcp=false,)) : nothing MSx = zeros(Scales) Args = NamedTuple{keys(Mobj)[2:end]}(Mobj) (RadNew==0 && String(Symbol(Mobj.Func)) in ("XSampEn","XApEn")) ? RadNew=1 : nothing if RadNew > 0 if RadNew == 1 Rnew = (x,y) -> sqrt((var(x)*(size(x,1)-1) + var(y)*(size(y,1)-1))/(size(x,1)+size(y,1)-1)) elseif RadNew == 2 Rnew = (x,y) -> ((var(x)*(size(x,1)-1) + var(y)*(size(y,1)-1))/(size(x,1)+size(y,1)-1)) elseif RadNew == 3 Rnew = (x,y) -> mean(abs.(vcat(x,y) .- mean(vcat(x,y)))) elseif RadNew == 4 Rnew = (x,y) -> median(abs.(vcat(x,y) .- median(vcat(x,y)))) end if haskey(Mobj,:r) Cx = Mobj.r else Cy = ("Pooled Standard Deviation","Pooled Variance","Total Mean Abs Deviation", "Total Median Abs Deviation") @warn("No radius value provided in Mobj. Default set to 0.2*$(Cy[RadNew]) of each new time-series.") Cx = .2 end end for T = 1:Scales print(" .") TempA, TempB = refined(Sig1, Sig2,T,F_Order,F_Num) RadNew > 0 ? Args = (Args..., r=Cx*Rnew(TempA, TempB)) : nothing Tempx = Mobj.Func(TempA, TempB; Args...) typeof(Tempx)<:Tuple ? MSx[T] = Tempx[1][end] : MSx[T] = Tempx[end] #MSx[T] = Tempx[1][end] end CI = sum(MSx) print("\n") if any(isnan.(MSx)) println("Some entropy values may be undefined.") end if Plotx p1 = plot(1:Scales, MSx, c=RGB(8/255, 63/255, 77/255), lw=3) scatter!(1:Scales, MSx, markersize=6, c=RGB(1, 0, 1), xlabel = "Scale Factor", ylabel = "Entropy Value", guidefont = font(12, "arial", RGB(7/255, 54/255, 66/255)), tickfontsize = 10, tickfontfamily="arial", legend=false, title = "Refined Multiscale $(Mobj.Func)", plot_titlefontsize=16, plot_titlefontcolor=RGB(7/255, 54/255, 66/255)) display(p1) end return MSx, CI end function refined(Za, Zb,sx,P1,P2) Y1 = filtfilt(digitalfilter(Lowpass(P2/sx), Butterworth(P1)), Za)[:] Y2 = filtfilt(digitalfilter(Lowpass(P2/sx), Butterworth(P1)), Zb)[:] return Y1, Y2 end end """ Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub """
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
code
102
using EntropyHub using Test @testset "EntropyHub.jl" begin #@test EntropyHub.ApEn(rand(100)) end
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
docs
14075
# EntropyHub: An open-source toolkit for entropic data analysis __*Julia Edition*__ <p align="center"> <img src="https://github.com/MattWillFlood/EntropyHub/blob/main/Graphics/EntropyHub_JuliaLogo.png" alt = "EntropyHub Git" width="250" height="340" /> </p> ## Latest Update ### v2.0 __*----- New multivariate methods -----*__ Five new multivariate entropy functions incorporating several method-specific variations > [Multivariate Sample Entropy](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.84.061918) > [Multivariate Fuzzy Entropy](https://www.mdpi.com/1099-4300/19/1/2) [++ many fuzzy functions] > [Multivariate Dispersion Entropy](https://www.mdpi.com/1099-4300/21/9/913) [++ many symbolic sequence transforms] > [Multivariate Cosine Similarity Entropy](https://www.mdpi.com/1099-4300/24/9/1287) > Multivariate Permutation Entropy [++ *amplitude-aware*, *edge*, *phase*, *weighted* and *modified* variants] __*----- New multivariate multiscale methods -----*__ Two new multivariate multiscale entropy functions > [Multivariate Multiscale Entropy](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.84.061918) [++ coarse, modified and generalized graining procedures] > [Composite and Refined-composite Multivariate Multiscale Entropy](https://link.springer.com/article/10.1007/s11517-017-1647-5) __*----- Extra signal processing tools -----*__ **WindowData()** is a new function that allows users to segment data (univariate or multivariate time series) into windows with/without overlapping samples! This allows users to calculate entropy on subsequences of their data to perform analyses with greater time resolution. *Other little fixes...* __*----- Docs edits -----*__ - Examples in the www.EntropyHub.xyz documentation were updated to match the latest package syntax. ## Welcome This toolkit provides a wide range of functions to calculate different entropy statistics. There is an ever-growing range of information-theoretic and dynamical systems entropy measures presented in the scientific literature. The goal of EntropyHub is to integrate the many established entropy methods in one open-source package. ## About Information and uncertainty can be regarded as two sides of the same coin: the more uncertainty there is, the more information we gain by removing that uncertainty. In the context of information and probability theory, ***Entropy*** quantifies that uncertainty. Attempting to analyse the analog world around us requires that we measure time in discrete steps, but doing so compromises our ability to measure entropy accurately. Various measures have been derived to estimate entropy (uncertainty) from discrete time series, each seeking to best capture the uncertainty of the system under examination. This has resulted in many entropy statistics from approximate entropy and sample entropy, to multiscale sample entropy and refined-composite multiscale cross-sample entropy. The goal of EntropyHub is to provide a comprehensive set of functions with a simple and consistent syntax that allows the user to augment parameters at the command line, enabling a range from basic to advanced entropy methods to be implemented with ease. ***It is important to clarify that the entropy functions herein described estimate entropy in the context of probability theory and information theory as defined by Shannon, and not thermodynamic or other entropies from classical physics.*** ## Installation There are two ways to install EntropyHub for Julia. #### Method 1: 1. In Julia, open the package REPL by typing `]`. The command line should appear as: `@vX.Y. pkg> ` Where X and Y refer to your version of Julia. 2. Type: `add EntropyHub` (Note: this is __case sensitive__) Alternatively, one can use the Pkg module to perform the same procedure: `using Pkg` `Pkg.add("EntropyHub")` #### Method 2: 1. In Julia, open the package REPL by typing `]`. The command line should appear as: `@vX.Y. pkg> ` Where X and Y refer to your version of Julia. 2. Type: `add https://github.com/MattWillFlood/EntropyHub.jl` (Note: this is __case sensitive__) ### System Requirements There are several package dependencies which will be installed alongside EntropyHub (if not already installed): DSP, FFTW, HTTP, Random, Plots, StatsBase, StatsFuns, GroupSlices, Statistics, DelimitedFiles, Combinatorics, LinearAlgebra, DataInterpolations, Clustering EntropyHub was designed using Julia 1.5 and is intended for use with Julia versions >= 1.2. ## Documentation & Help A key advantage of EntropyHub is the comprehensive documentation available to help users to make the most of the toolkit. To learn more about a specific function, one can do so easily from the command line by typing: `?`, which will open the julia help system, and then typing the function name. For example: julia> ? help?> SampEn # Documentation on sample entropy function julia> ? help?> XSpecEn # Documentation on cross-spectral entropy function julia> ? help?> hXMSEn # Documentation on hierarchical multiscale cross-entropy function All information on the EntropyHub package is detailed in the *EntropyHub Guide*, a .pdf document available [here](https://github.com/MattWillFlood/EntropyHub/blob/main/EntropyHub%20Guide.pdf). ## Functions EntropyHub functions fall into 8 categories: * Base functions for estimating the entropy of a single univariate time series. * Cross functions for estimating the entropy between two univariate time series. * Multivariate functions for estimating the entropy of a multivariate dataset. * Bidimensional functions for estimating the entropy of a two-dimensional univariate matrix. * Multiscale functions for estimating the multiscale entropy of a single univariate time series using any of the Base entropy functions. * Multiscale Cross functions for estimating the multiscale entropy between two univariate time series using any of the Cross-entropy functions. * Multivariate Multiscale functions for estimating the multivariate multiscale entropy of multivariate dataset using any of the Multivariate-entropy functions. * Other Supplementary functions for various tasks related to EntropyHub and signal processing. #### The following tables outline the functions available in the EntropyHub package. *When new entropies are published in the scientific literature, efforts will be made to incorporate them in future releases.* ### Base Entropies: Entropy Type | Function Name ---|--- Approximate Entropy | ApEn Sample Entropy | SampEn Fuzzy Entropy | FuzzEn Kolmogorov Entropy | K2En Permutation Entropy | PermEn Conditional Entropy | CondEn Distribution Entropy | DistEn Spectral Entropy | SpecEn Dispersion Entropy | DispEn Symbolic Dynamic Entropy | SyDyEn Increment Entropy | IncrEn Cosine Similarity Entropy | CoSiEn Phase Entropy | PhasEn Slope Entropy | SlopEn Bubble Entropy | BubbEn Gridded Distribution Entropy | GridEn Entropy of Entropy | EnofEn Attention Entropy | AttnEn Range Entropy | RangEn Diversity Entropy | DivEn _______________________________________________________________________ ### Cross Entropies: Entropy Type | Function Name --|-- Cross Sample Entropy | XSampEn Cross Approximate Entropy | XApEn Cross Fuzzy Entropy | XFuzzEn Cross Permutation Entropy | XPermEn Cross Conditional Entropy | XCondEn Cross Distribution Entropy | XDistEn Cross Spectral Entropy | XSpecEn Cross Kolmogorov Entropy | XK2En _______________________________________________________________________ ### Multivariate Entropies: Entropy Type | Function Name --|-- Multivariate Sample Entropy | MvSampEn Multivariate Fuzzy Entropy | MvFuzzEn Multivariate Permutation Entropy | MvPermEn Multivariate Dispersion Entropy | MvDispEn Multivariate Cosine Similarity Entropy | MvCoSiEn _______________________________________________________________________ ### Bidimensional Entropies Entropy Type | Function Name --|-- Bidimensional Sample Entropy | SampEn2D Bidimensional Fuzzy Entropy | FuzzEn2D Bidimensional Distribution Entropy | DistEn2D Bidimensional Dispersion Entropy | DispEn2D Bidimensional Permutation Entropy | PermEn2D Bidimensional Espinosa Entropy | EspEn2D _________________________________________________________________________ ### Multiscale Entropy Functions Entropy Type | Function Name --|-- Multiscale Entropy | MSEn Composite/Refined-Composite Multiscale Entropy | cMSEn Refined Multiscale Entropy | rMSEn Hierarchical Multiscale Entropy | hMSEn _________________________________________________________________________ ### Multiscale Cross-Entropy Functions Entropy Type | Function Name --|-- Multiscale Cross-Entropy | XMSEn Composite/Refined-Composite Multiscale Cross-Entropy | cXMSEn Refined Multiscale Cross-Entropy | rXMSEn Hierarchical Multiscale Cross-Entropy | hXMSEn _________________________________________________________________________ ### Multivariate Multiscale Entropy Functions Entropy Type | Function Name --|-- Multivariate Multiscale Entropy | MvMSEn Composite/Refined-Composite Multivariate Multiscale Entropy | cMvMSEn _________________________________________________________________________ ### Other Functions Entropy Type | Function Name --|-- Example Data Import Tool | ExampleData Window Data Tool | WindowData Multiscale Entropy Object | MSobject ## License and Terms of Use EntropyHub is licensed under the Apache License (Version 2.0) and is free to use by all on condition that the following reference be included on any outputs realized using the software: Matthew W. Flood (2021), EntropyHub: An Open-Source Toolkit for Entropic Time Series Analysis, PLoS ONE 16(11):e0259448 DOI: 10.1371/journal.pone.0259448 www.EntropyHub.xyz __________________________________________________________________ © Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub ## Contact If you find this package useful, please consider starring it on GitHub, MatLab File Exchange, PyPI or Julia Packages as this helps us to gauge user satisfaction. If you have any questions about the package, please do not hesitate to contact us at: [email protected] If you identify any bugs, please contact us at: [email protected] If you need any help installing or using the toolkit, please contact us at: [email protected] ***Thank you*** for using EntropyHub. Matt ___ _ _ _____ _____ ____ ____ _ _ | _|| \ | ||_ _|| \| || || \ / | ___________ | \_ | \| | | | | __/| || __| \ \_/ / / _______ \ | _|| \ \ | | | | \ | || | \ / | / ___ \ | | \_ | |\ | | | | |\ \ | || | | | | | / \ | | |___||_| \_| |_| |_| \_||____||_| |_| _|_|__\___/ | | _ _ _ _ ____ / |__\______\/ | | | | || | | || \ An open-source | /\______\__|_/ | |_| || | | || | toolkit for | | / \ | | | _ || | | || \ entropic time- | | \___/ | | | | | || |_| || \ series analysis | \_______/ | |_| |_|\_____/|_____/ \___________/ <p align="center"> <img src="https://github.com/MattWillFlood/EntropyHub/blob/main/Graphics/EntropyHubLogo3.png" width="250" height="350"/> </p>
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
docs
7963
```@meta CurrentModule = EntropyHub ``` ![EH4J](./assets/logo.png) # EntropyHub __*An Open-Source Toolkit For Entropic Time Series Analysis*__ ## Latest Updates ### v2.0 *----- New multivariate methods -----* Five new multivariate entropy functions incorporating several method-specific variations + [Multivariate Sample Entropy](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.84.061918) + [Multivariate Fuzzy Entropy](https://www.mdpi.com/1099-4300/19/1/2) [++ many fuzzy functions] + [Multivariate Dispersion Entropy](https://www.mdpi.com/1099-4300/21/9/913) [++ many symbolic sequence transforms] + [Multivariate Cosine Similarity Entropy](https://www.mdpi.com/1099-4300/24/9/1287) + Multivariate Permutation Entropy [++ *amplitude-aware*, *edge*, *phase*, *weighted* and *modified* variants] *----- New multivariate multiscale methods -----* Two new multivariate multiscale entropy functions + [Multivariate Multiscale Entropy](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.84.061918) [++ coarse, modified and generalized graining procedures] + [Composite and Refined-composite Multivariate Multiscale Entropy](https://link.springer.com/article/10.1007/s11517-017-1647-5) *----- Extra signal processing tools -----* [`WindowData()`](@ref) is a new function that allows users to segment data (univariate or multivariate time series) into windows with/without overlapping samples! This allows users to calculate entropy on subsequences of their data to perform analyses with greater time resolution. __**Other little fixes...**__ *----- Docs edits -----* - Examples in the www.EntropyHub.xyz documentation were updated to match the latest package syntax. _________________________________________________________ ## Introduction This toolkit provides a wide range of functions to calculate different entropy statistics. There is an ever-growing range of information-theoretic and dynamical systems entropy measures presented in the scientific literature. The goal of **EntropyHub.jl** is to integrate the many established entropy methods in one open-source package with an extensive documentation and consistent syntax [that is also accessible in multiple programming languages ([Matlab](https://www.entropyhub.xyz/matlab/EHmatlab.html), [Python](https://www.entropyhub.xyz/python/EHpython.html))]. ### About Information and uncertainty can be regarded as two sides of the same coin: the more uncertainty there is, the more information we gain by removing that uncertainty. In the context of information and probability theory, **Entropy** quantifies that uncertainty. Various measures have been derived to estimate entropy (uncertainty) from discrete time series, each seeking to best capture the uncertainty of the system under examination. This has resulted in many entropy statistics from approximate entropy and sample entropy, to multiscale sample entropy and refined-composite multiscale cross-sample entropy. The goal of EntropyHub is to provide a comprehensive set of functions with a simple and consistent syntax that allows the user to augment parameters at the command line, enabling a range from basic to advanced entropy methods to be implemented with ease. !!! warning "NOTE:" It is important to clarify that the entropy functions herein described estimate entropy in the context of probability theory and information theory as defined by Shannon, and not thermodynamic or other entropies from classical physics. ## Installation Using the Julia REPL: ``` julia> using Pkg; Pkg.add("EntropyHub") ``` or ``` julia> ] pkg> add EntropyHub ``` To get the latest version of EntropyHub directly from GitHub: ``` julia> ] pkg> add https://github.com/MattWillFlood/EntropyHub.jl ``` ## Citing EntropyHub is licensed under the Apache License (Version 2.0) and is free to use by all on condition that the following reference be included on any outputs realized using the software: ``` Matthew W. Flood (2021), EntropyHub: An Open-Source Toolkit for Entropic Time Series Analysis, PLoS ONE 16(11):e0259448 DOI: 10.1371/journal.pone.0259448 www.EntropyHub.xyz ``` __________________________________________________________________ © Copyright 2024 Matthew W. Flood, EntropyHub Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For Terms of Use see https://github.com/MattWillFlood/EntropyHub If you find this package useful, please consider starring it on [GitHub](https://github.com/MattWillFlood/EntropyHub.jl) and Julia Packages (or MatLab File Exchange and PyPI). This helps us to gauge user satisfaction. ## Contact For general queries and information about EntropyHub, contact: `[email protected]` If you have any questions or need help using the package, please contact us at: `[email protected]` If you notice or identify any issues, please do not hesitate to contact us at: `[email protected]` We will do our best to help you with any relevant issues that you may have. If you come across any errors or technical issues, you can raise these under the issues tab on the EntropyHub.jl GitHub page. Similarly, if you have any suggestions or recommendations on how this package can be improved, please let us know. __Thank you for using EntropyHub,__ Matt ## Function List EntropyHub functions fall into 8 categories: * `Base` functions for estimating the entropy of a single univariate time series. * `Cross` functions for estimating the entropy between two univariate time series. * `Bidimensional` functions for estimating the entropy of a two-dimensional univariate matrix. * `Multiscale` functions for estimating the multiscale entropy of a single univariate time series using any of the Base entropy functions. * `Multiscale Cross` functions for estimating the multiscale entropy between two univariate time series using any of the Cross-entropy functions. * `Multivariate Multiscale` functions for estimating the multivariate multiscale entropy of multivariate dataset using any of the Multivariate-entropy functions. * `Other` Supplementary functions for various tasks related to EntropyHub and signal processing. ```@index ``` ___ _ _ _____ _____ ____ ____ _ _ | _|| \ | ||_ _|| \| || || \ / | ___________ | \_ | \| | | | | __/| || __| \ \_/ / / _______ \ | _|| \ \ | | | | \ | || | \ / | / ___ \ | | \_ | |\ | | | | |\ \ | || | | | | | / \ | | |___||_| \_| |_| |_| \_||____||_| |_| _|_|__\___/ | | _ _ _ _ ____ / |__\______\/ | | | | || | | || \ An open-source | /\______\__|_/ | |_| || | | || | toolkit for | | / \ | | | _ || | | || \ entropic time- | | \___/ | | | | | || |_| || \ series analysis | \_______/ | |_| |_|\_____/|_____/ \___________/ Documentation for [EntropyHub](https://github.com/MattWillFlood/EntropyHub.jl).
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
docs
1314
# Example 1: Sample Entropy Import a signal of normally distributed random numbers [mean = 0; SD = 1], and calculate the sample entropy for each embedding dimension (m) from 0 to 4. ```@example using EntropyHub # hide X = ExampleData("gaussian"); Samp, _ = SampEn(X, m = 4); Samp # hide ``` Select the last value to get the sample entropy for m = 4. ```@example using EntropyHub # hide X = ExampleData("gaussian"); # hide Samp, _ = SampEn(X, m = 4); # hide Samp[end] ``` Calculate the sample entropy for each embedding dimension (m) from 0 to 4 with a time delay (tau) of 2 samples. ```@example using EntropyHub # hide X = ExampleData("gaussian"); # hide Samp, Phi1, Phi2 = SampEn(X, m = 4, tau = 2) ``` Import a signal of uniformly distributed random numbers in the range [-1, 1] and calculate the sample entropy for an embedding dimension (m) of 5, a time delay of 2, and a threshold radius of 0.075. Return the conditional probability (Vcp) and the number of overlapping matching vector pairs of lengths m+1 (Ka) and m (Kb), respectively. ```@example using EntropyHub # hide X = ExampleData("uniform"); # hide Samp, _, _, Vcp_Ka_Kb = SampEn(X, m = 5, tau = 2, r = 0.075, Vcp = true) Vcp, Ka, Kb = Vcp_Ka_Kb println("Vcp = ", Vcp) # hide println("Ka = ", Ka) # hide println("Kb = ", Kb) # hide ```
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
docs
595
# Example 10: Bidimensional Fuzzy Entropy Import an image of a Mandelbrot fractal as a matrix. ``` X = ExampleData("mandelbrot_Mat"); using Plots heatmap(X, background_color="black") ``` ![AlmondBread](../assets/mandelbrotjl.png) Calculate the bidimensional fuzzy entropy in trits (logarithm base 3) with a template matrix of size [8 x 5], and a time delay (`tau`) of 2 using a `'constgaussian'` fuzzy membership function (r=24). ```@example using EntropyHub # hide X = ExampleData("mandelbrot_Mat"); # hide FE2D = FuzzEn2D(X, m = (8, 5), tau = 2, Fx = "constgaussian", r = 24, Logx = 3) ```
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
docs
1948
# Example 11: Multivariate Dispersion Entropy Import a vector of 4096 uniformly distributed random integers in range [1 8] and convert it to a multivariate set of 4 sequences with 1024 samples each. ```@example using EntropyHub # hide X = ExampleData("randintegers"); Data = reshape(X, 1024, 4); Data # hide ``` Calculate the multivariate dispersion entropy and reverse dispersion entropy for embedding dimensions (m) = [1,1,2,3], using a 7-symbol transform. ```@example using EntropyHub # hide X = ExampleData("randintegers"); # hide Data = reshape(X, 1024, 4); # hide MDisp, RDE = MvDispEn(Data, m = [1,1,2,3], c = 7); MDisp # hide ``` ```@example using EntropyHub # hide X = ExampleData("randintegers"); # hide Data = reshape(X, 1024, 4); # hide MDisp, RDE = MvDispEn(Data, m = [1,1,2,3], c = 7); # hide RDE # hide ``` Perform the same calculation but normalize the output entropy estimate w.r.t the number of unique dispersion patterns ```@example using EntropyHub # hide X = ExampleData("randintegers"); # hide Data = reshape(X, 1024, 4); # hide MDisp, RDE = MvDispEn(Data, m = [1,1,2,3], c = 7, Norm = true); MDisp # hide ``` ```@example using EntropyHub # hide X = ExampleData("randintegers"); # hide Data = reshape(X, 1024, 4); # hide MDisp, RDE = MvDispEn(Data, m = [1,1,2,3], c = 7, Norm = true); # hide RDE # hide ``` Compare the results above (``Methodx == 'v1'``) with those obtained using the *mvDE* method (``Methodx=='v2'``), returning estimates for each value from 1, ..., max(m) ```@example using EntropyHub # hide X = ExampleData("randintegers"); # hide Data = reshape(X, 1024, 4); # hide MDisp, RDE = MvDispEn(Data, m = [1,1,2,3], c = 7, Norm = true, Methodx = "v2") MDisp # hide ``` ```@example using EntropyHub # hide X = ExampleData("randintegers"); # hide Data = reshape(X, 1024, 4); # hide MDisp, RDE = MvDispEn(Data, m = [1,1,2,3], c = 7, Norm = true, Methodx = "v2") # hide RDE # hide ```
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
docs
1796
# Example 12: [Generalized] Refined-composite Multivariate Multiscale Fuzzy Entropy Import the x, y, and z components of the Lorenz system of equations. ``` Data = ExampleData("lorenz"); using Plots scatter(Data[:,1], Data[:,2], Data[:,3], markercolor = "green", markerstrokecolor = "black", markersize = 3, background_color = "black", grid = false) ``` ![Lorenz](../assets/lorenzjl.png) Create a multiscale entropy object with the following parameters: EnType = MvFuzzEn(), fuzzy membership function = 'constgaussian', fuzzy function parameter = 1.75, normalized data to unit variance = true. ```@example using EntropyHub # hide Mobj = MSobject(MvFuzzEn, Fx = "constgaussian", r = 1.75, Norm = true) ``` Calculate the generalized refined-composite multivariate multiscale fuzzy entropy over 5 scales and plotting the output. !!! tip When the multivariate entropy method is multivariate fuzzy entropy (``MvFuzzEn``), **cMvMSEn** by default employs a generalized graining procedure with the standard deviation (not the variance like in MvMSEn). This follows the method presented in [1]. [1] Azami, Fernández and Escudero. " *Refined multiscale fuzzy entropy based on standard deviation for biomedical signal analysis* " Medical & biological engineering & computing 55 (2017): 2037-2052 !!! warning As with conventional generalized multiscale entropy, the multiscale entropy value for the first scale will always == 0, as the variance or standard deviation of a singular value is 0! ```@example using EntropyHub # hide Data = ExampleData("lorenz"); # hide Mobj = MSobject(MvFuzzEn, Fx = "constgaussian", r = 1.75, Norm = true) # hide MSx, CI = cMvMSEn(Data, Mobj, Scales = 5, Refined = true, Plotx = true) ``` ![rcMvMSEn](../assets/rcMvMSEnjl.png)
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
docs
2972
# Example 13: Window Data Tool This example shows how to use the [`WindowData()`](@ref) function to divide univariate/multivariate data into subsequences. _______________________________________________________________________________ ### Ex. 1 Import a sequence of uniformly distributed random numbers. ``` X = ExampleData("uniform"); ``` Extract a series of subsequences by dividing the sequence into windows of length 1024 with no overlap. ```@example using EntropyHub # hide X = ExampleData("uniform"); # hide WinData, Log = WindowData(X, WinLen = 1024); WinData # hide ``` ```@example using EntropyHub # hide X = ExampleData("uniform"); # hide WinData, Log = WindowData(X, WinLen = 1024); # hide Log # hide ``` Repeat the previous step but change the number of overlapping window samples to 256. ```@example using EntropyHub # hide X = ExampleData("uniform"); # hide WinData, Log = WindowData(X, WinLen = 1024, Overlap = 256); WinData # hide ``` ```@example using EntropyHub # hide X = ExampleData("uniform"); # hide WinData, Log = WindowData(X, WinLen = 1024, Overlap = 256); # hide Log # hide ``` _______________________________________________________________________________ ### Ex. 2 Window a range of numbers (1:1234) into 5 windows. ```@example using EntropyHub # hide WinData, Log = WindowData(1:1234); WinData # hide ``` ```@example using EntropyHub # hide WinData, Log = WindowData(1:1234); # hide Log # hide ``` Repeat the previous step, but this time retain any remaining samples that do not fill the last window. ```@example using EntropyHub # hide WinData, Log = WindowData(1:1234, Mode="include"); WinData # hide ``` ```@example using EntropyHub # hide _, Log = WindowData(1:1234); # hide Log # hide ``` Note that the last vector in `WinData` contains only 4 values. ```@example using EntropyHub # hide WinData, _ = WindowData(1:1234, Mode="include"); # hide WinData[end] # hide ``` _______________________________________________________________________________ ### Ex. 3 Generate a multivariate dataset of 5 uniformly-distributed random number sequences (N=3333) and divide the dataset into subsets of 777 samples. ```@example using EntropyHub # hide using Random X = rand(MersenneTwister(0), 3333, 5) WinData, Log = WindowData(X, WinLen = 777) WinData # hide ``` ```@example using EntropyHub # hide using Random # hide X = rand(MersenneTwister(0), 3333, 5) # hide WinData, Log = WindowData(X, WinLen = 777) # hide Log # hide ``` Repeat the previous step including 55 samples of overlap and retain any remaining samples that do not fill a window. ```@example using EntropyHub # hide using Random # hide X = rand(MersenneTwister(0), 3333, 5) # hide WinData, Log = WindowData(X, WinLen = 777, Overlap = 55, Mode = "include") WinData # hide ``` ```@example using EntropyHub # hide using Random # hide X = rand(MersenneTwister(0), 3333, 5) # hide WinData, Log = WindowData(X, WinLen = 777, Overlap = 55, Mode = "include") # hide Log # hide ```
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
docs
865
# Example 2: (Fine-grained) Permutation Entropy Import the x, y, and z components of the Lorenz system of equations. ``` Data = ExampleData("lorenz"); using Plots scatter(Data[:,1], Data[:,2], Data[:,3], markercolor = "green", markerstrokecolor = "black", markersize = 3, background_color = "black", grid = false) ``` ![Lorenz](../assets/lorenzjl.png) Calculate fine-grained permutation entropy of the z component in dits (logarithm base 10) with an embedding dimension of 3, time delay of 2, an alpha parameter of 1.234. Return Pnorm normalised w.r.t the number of all possible permutations (m!) and the condition permutation entropy (cPE) estimate. ```@example using EntropyHub # hide Data = ExampleData("lorenz"); # hide Z = Data[:,3]; Perm, Pnorm, cPE = PermEn(Z, m = 3, tau = 2, Typex = "finegrain", tpx = 1.234, Logx = 10, Norm = false) ```
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
docs
1018
# Example 3: Phase Entropy w/ Second Order Difference Plot Import the x and y components of the Henon system of equations. ``` Data = ExampleData("henon"); using Plots scatter(Data[:,1], Data[:,2], markercolor = "green", markerstrokecolor = "black", markersize = 3, background_color = "black",grid = false) ``` ![Henon](../assets/henonjl.png) Calculate the phase entropy of the y-component in bits (logarithm base 2) without normalization using 7 angular partitions and return the second-order difference plot. ```@example using EntropyHub # hide Data = ExampleData("henon"); # hide Y = Data[:,2]; Phas = PhasEn(Y, K = 7, Norm = false, Logx = 2, Plotx = true) ``` ![Phas1](../assets/phasx1jl.png) Calculate the phase entropy of the x-component using 11 angular partitions, a time delay of 2, and return the second-order difference plot. ```@example using EntropyHub # hide Data = ExampleData("henon"); # hide X = Data[:,1]; Phas = PhasEn(X, K = 11, tau = 2, Plotx = true) ``` ![Phas2](../assets/phasx2jl.png)
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
docs
779
# Example 4: Cross-Distribution Entropy w/ Different Binning Methods Import a signal of pseudorandom integers in the range [1, 8] and calculate the cross- distribution entropy with an embedding dimension of 5, a time delay (`tau`) of 3, and 'Sturges' bin selection method. ```@example using EntropyHub # hide X = ExampleData("randintegers2"); XDist, _ = XDistEn(X[:,1], X[:,2], m = 5, tau = 3); println(" ") # hide println("XDist = ", XDist) # hide ``` Use Rice's method to determine the number of histogram bins and return the probability of each bin (`Ppi`). ```@example using EntropyHub # hide X = ExampleData("randintegers2"); # hide XDist, Ppi = XDistEn(X[:,1], X[:,2], m = 5, tau = 3, Bins = "rice") println("XDist = ", XDist) # hide println("Ppi = ", Ppi) #hide ```
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
docs
839
# Example 5: Multiscale Entropy Object - MSobject() !!! warning "Note:" The base and cross- entropy functions used in the multiscale entropy calculation are declared by passing EntropyHub functions to MSobject(), not string names. Create a multiscale entropy object (`Mobj`) for multiscale fuzzy entropy, calculated with an embedding dimension of 5, a time delay (`tau`) of 2, using a sigmoidal fuzzy function with the `r` scaling parameters (3, 1.2). ```@example using EntropyHub # hide Mobj = MSobject(FuzzEn, m = 5, tau = 2, Fx = "sigmoid", r = (3, 1.2)) ``` Create a multiscale entropy object (`Mobj`) for multiscale corrected-cross-conditional entropy, calculated with an embedding dimension of 6 and using a 11-symbolic data transform. ```@example using EntropyHub # hide Mobj = MSobject(XCondEn, m = 6, c = 11) ```
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
docs
1284
# Example 6: Multiscale Increment Entropy Import a signal of uniformly distributed pseudorandom integers in the range [1 8] and create a multiscale entropy object with the following parameters: `EnType` = IncrEn(), embedding dimension = 3, a quantifying resolution = 6, normalization = true. ```@example using EntropyHub # hide X = ExampleData("randintegers"); Mobj = MSobject(IncrEn, m = 3, R = 6, Norm = true) ``` Calculate the multiscale increment entropy over 5 temporal scales using the modified graining procedure where: ``y_j^{(\tau)} =\frac{1}{\tau } \sum_{i=\left(j-1\right)\tau +1}^{j\tau } x{_i}, 1<= j <= \frac{N}{\tau }`` ```@example using EntropyHub # hide X = ExampleData("randintegers"); # hide Mobj = MSobject(IncrEn, m = 3, R = 6, Norm = true) # hide MSx, _ = MSEn(X, Mobj, Scales = 5, Methodx = "modified"); MSx # hide ``` Change the graining method to return generalized multiscale increment entropy. ``y_j^{(\tau)} =\frac{1}{\tau } \sum_{i=\left(j-1\right)\tau +1}^{j\tau } \left( x{_i} - \bar{x} \right)^{2}, 1<= j <= \frac{N}{\tau }`` ```@example using EntropyHub # hide X = ExampleData("randintegers"); # hide Mobj = MSobject(IncrEn, m = 3, R = 6, Norm = true) # hide MSx, _ = MSEn(X, Mobj, Scales = 5, Methodx = "generalized"); MSx # hide ```
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git
[ "Apache-2.0" ]
2.0.0
c4c17ff5a1c4186a68e6cd8e504f830a8bd25890
docs
951
# Example 7: Refined Multiscale Sample Entropy Import a signal of uniformly distributed pseudorandom integers in the range [1, 8] and create a multiscale entropy object with the following parameters: `EnType` = SampEn(), embedding dimension = 4, radius threshold = 1.25 ```@example using EntropyHub # hide X = ExampleData("randintegers"); Mobj = MSobject(SampEn, m = 4, r = 1.25) Mobj # hide ``` Calculate the refined multiscale sample entropy and the complexity index (`Ci`) over 5 temporal scales using a 3rd order Butterworth filter with a normalised corner frequency of at each temporal scale (τ), where the radius threshold value (`r`) specified by `Mobj` becomes scaled by the median absolute deviation of the filtered signal at each scale. ```@example using EntropyHub # hide X = ExampleData("randintegers"); # hide Mobj = MSobject(SampEn, m = 4, r = 1.25) # hide MSx, Ci = rMSEn(X, Mobj, Scales = 5, F_Order = 3, F_Num = 0.6, RadNew = 4) ```
EntropyHub
https://github.com/MattWillFlood/EntropyHub.jl.git