Skip to content

Commit

Permalink
Merge pull request #8 from UniStuttgart-VISUS/organized_imports
Browse files Browse the repository at this point in the history
Organization of import statements
  • Loading branch information
marinaevers authored Jul 25, 2024
2 parents e3c24a2 + f659ecb commit 2569f56
Show file tree
Hide file tree
Showing 16 changed files with 297 additions and 183 deletions.
14 changes: 7 additions & 7 deletions example.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
import uadapy as ua
from uadapy import distribution
from uadapy.dr import uamds
import uadapy.data as data
import uadapy.dr.uamds as uamds
from uadapy.data import load_iris_normal
import uadapy.plotting.plots1D as plots1D
import uadapy.plotting.plots2D as plots2D
import uadapy.plotting.plotsND as plotsND
import numpy as np
import matplotlib.pyplot as plt



def example_uamds():
distribs_hi = data.load_iris_normal()
plots1D.plot_1d_distribution(distribs_hi, num_samples=100, plot_types='boxplot')
distribs_lo = uamds.uamds(distribs_hi, dims=2)
distribs_lo = uamds(distribs_hi, dims=2)
plots2D.plot_contour(distribs_lo)
#plots2D.plot_contour_bands(distribs_lo, 10000, 128, None, [5, 25, 55, 75, 95])
#plotsND.plot_contour(distribs_lo, 10000, 128, None, [5, 25, 50, 75, 95])
#plotsND.plot_contour_samples(distribs_lo, 10000, 128, None, [5, 25, 50, 75, 95])

def example_kde():
samples = np.random.randn(1000, 2)
distr = ua.distribution.distribution(samples)
samples = np.random.randn(1000,2)
distr = distribution(samples)
plots2D.plot_contour(distr)

def example_uamds_1d():
distribs_hi = data.load_iris_normal()
distribs_lo = uamds.uamds(distribs_hi, dims=4)
distribs_lo = uamds(distribs_hi, dims=4)
labels = ['setosa','versicolor','virginica']
titles = ['sepal length','sepal width','petal length','petal width']
colors = ['red','green', 'blue']
Expand Down
102 changes: 59 additions & 43 deletions examples/ownData.ipynb

Large diffs are not rendered by default.

135 changes: 83 additions & 52 deletions examples/uamds.ipynb

Large diffs are not rendered by default.

124 changes: 73 additions & 51 deletions examples/uapca.ipynb

Large diffs are not rendered by default.

39 changes: 39 additions & 0 deletions tests/api_consistency_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# This file is to test consistency of uadapy's API.
# It calls most commonly used functions with default arguments and named arguments
# as the corrsponding documentation suggests. If calling a function errors, it is
# due to a change in the API or changes that result in breaking previously working
# functionality. If an API change was intentional, the test calls in this file need
# to be updated accordingly. In any case, this script should never error.

# make script aware of parent directory where uadapy is located
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

def test_data_module():
import uadapy.data
uadapy.data.load_iris()
uadapy.data.load_iris_normal()


def test_dr_module():
import uadapy.dr
import uadapy.distribution
import numpy as np
# list of distributions (normal distributions estimated from random data
distribs = [uadapy.distribution(np.random.rand(10, 3), name='Normal') for _ in range(4)]
uadapy.dr.uapca(distributions=distribs, dims=2)
uadapy.dr.uamds(distributions=distribs, dims=2)


def test_plotting_module():
# TODO
pass


def main():
test_data_module()
test_dr_module()


if __name__ == '__main__':
main()
14 changes: 7 additions & 7 deletions uadapy/test_distrib.py → tests/test_distrib.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import traceback
# make script aware of parent directory where uadapy is located
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import traceback
from uadapy import distribution
import numpy as np
import scipy as sp
import scipy.stats as st
import distribution as ds



Expand Down Expand Up @@ -68,11 +71,11 @@ def test_distrib_class():

# initialize distribution object for each of the scipy distribs (univariate)
for scipi_distrib in model_1D:
distrib = ds.distribution(scipi_distrib)
distrib = distribution(scipi_distrib)
# initialize distribution object for each of the scipy distribs (multivariate)
for scipi_distrib in model_nD:
try:
distrib = ds.distribution(scipi_distrib)
distrib = distribution(scipi_distrib)
cov = distrib.cov()
if cov.shape[0] != n or cov.shape[1] != n:
raise RuntimeError(f"shape expected to be {n} x {n}, but was {cov.shape}")
Expand All @@ -83,9 +86,6 @@ def test_distrib_class():
traceback.print_exception(e)





if __name__ == '__main__':
test_distrib_class()

Expand Down
3 changes: 3 additions & 0 deletions uadapy/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .distribution import distribution

__all__ = ['distribution']
1 change: 1 addition & 0 deletions uadapy/data/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .data import *
6 changes: 3 additions & 3 deletions uadapy/data.py → uadapy/data/data.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from sklearn import datasets
import numpy as np
import uadapy.distribution as ua
from uadapy import distribution

def load_iris_normal():
"""
Expand All @@ -10,7 +10,7 @@ def load_iris_normal():
iris = datasets.load_iris()
dist = []
for c in np.unique(iris.target):
dist.append(ua.distribution(np.array(iris.data[iris.target == c]), "Normal"))
dist.append(distribution(np.array(iris.data[iris.target == c]), "Normal"))
return dist

def load_iris():
Expand All @@ -21,5 +21,5 @@ def load_iris():
iris = datasets.load_iris()
dist = []
for c in np.unique(iris.target):
dist.append(ua.distribution(np.array(iris.data[iris.target == c])))
dist.append(distribution(np.array(iris.data[iris.target == c])))
return dist
4 changes: 2 additions & 2 deletions uadapy/distribution.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def pdf(self, x: np.ndarray | float) -> np.ndarray | float:
if isinstance(self.model, np.ndarray):
return self.kde.pdf(x.T)
if not hasattr(self.model, 'pdf'):
raise AttributeError(f"The model has no pdf.{self.model.__class__.__name__}")
raise AttributeError(f"The model has no pdf. {self.model.__class__.__name__}")
else:
return self.model.pdf(x)

Expand Down Expand Up @@ -90,7 +90,7 @@ def skew(self) -> np.ndarray | float:
return stats.skew(self.model)
if hasattr(self.model, 'stats') and callable(self.model.stats):
return self.model.stats(moments='s')
if isinstance(self.model, multivariate_t_frozen):
if isinstance(self.model, mv.multivariate_t_frozen):
return 0

def kurt(self) -> np.ndarray | float:
Expand Down
2 changes: 2 additions & 0 deletions uadapy/dr/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from .uamds import *
from .uapca import *
4 changes: 2 additions & 2 deletions uadapy/dr/uamds.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
import numpy as np
from scipy.spatial import distance_matrix
from scipy.optimize import minimize
import uadapy as ua
from scipy.stats import multivariate_normal
from uadapy import distribution


def precalculate_constants(normal_distr_spec: np.ndarray) -> tuple:
Expand Down Expand Up @@ -546,7 +546,7 @@ def uamds(distributions: list, dims: int=2):
result = apply_uamds(means, covs, dims)
distribs_lo = []
for (m, c) in zip(result['means'], result['covs']):
distribs_lo.append(ua.distribution.distribution(multivariate_normal(m, c)))
distribs_lo.append(distribution(multivariate_normal(m, c)))
return distribs_lo
except Exception as e:
raise Exception(f'Something went wrong. Did you input normal distributions? Exception:{e}')
Expand Down
4 changes: 2 additions & 2 deletions uadapy/dr/uapca.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import numpy as np
import uadapy as ua
from uadapy import distribution
from scipy.stats import multivariate_normal

def uapca(distributions, dims: int):
Expand All @@ -18,7 +18,7 @@ def uapca(distributions, dims: int):
means_pca, covs_pca = transform_uapca(means, covs, dims)
dist_pca = []
for (m, c) in zip(means_pca, covs_pca):
dist_pca.append(ua.distribution.distribution(multivariate_normal(m, c)))
dist_pca.append(distribution(multivariate_normal(m, c)))
return dist_pca
except Exception as e:
raise Exception(f'Something went wrong. Did you input normal distributions? Exception:{e}')
Expand Down
4 changes: 2 additions & 2 deletions uadapy/plotting/plots1D.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import numpy as np
import uadapy.distribution as dist
from uadapy import distribution
import matplotlib.pyplot as plt
from math import ceil, sqrt
import glasbey as gb
Expand Down Expand Up @@ -67,7 +67,7 @@ def setup_plot(distributions, num_samples, seed, fig=None, axs=None, colors=None

samples = []

if isinstance(distributions, dist.distribution):
if isinstance(distributions, distribution):
distributions = [distributions]

# Calculate the layout of subplots
Expand Down
16 changes: 8 additions & 8 deletions uadapy/plotting/plots2D.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import matplotlib.pyplot as plt
import numpy as np
import uadapy.distribution as dist
from uadapy import distribution
from numpy import ma
from matplotlib import ticker

def plot_samples(distribution, num_samples, **kwargs):
def plot_samples(distributions, num_samples, **kwargs):
"""
Plot samples from the given distribution. If several distributions should be
plotted together, an array can be passed to this function
:param distribution: Distributions to plot
:param distributions: Distributions to plot
:param num_samples: Number of samples per distribution
:param kwargs: Optional other arguments to pass:
xlabel for label of x-axis
ylabel for label of y-axis
:return:
"""
if isinstance(distribution, dist.distribution):
distribution = [distribution]
for d in distribution:
if isinstance(distributions, distribution):
distributions = [distributions]
for d in distributions:
samples = d.sample(num_samples)
plt.scatter(x=samples[:,0], y=samples[:,1])
if 'xlabel' in kwargs:
Expand Down Expand Up @@ -56,7 +56,7 @@ def plot_contour(distributions, resolution=128, ranges=None, quantiles:list=None
If a quantile is not between 0 and 100 (exclusive), or if a quantile results in an index that is out of bounds.
"""

if isinstance(distributions, dist.distribution):
if isinstance(distributions, distribution):
distributions = [distributions]
contour_colors = generate_spectrum_colors(len(distributions))

Expand Down Expand Up @@ -136,7 +136,7 @@ def plot_contour_bands(distributions, num_samples, resolution=128, ranges=None,
If a quantile is not between 0 and 100 (exclusive), or if a quantile results in an index that is out of bounds.
"""

if isinstance(distributions, dist.distribution):
if isinstance(distributions, distribution):
distributions = [distributions]

# Sequential and perceptually uniform colormaps
Expand Down
8 changes: 4 additions & 4 deletions uadapy/plotting/plotsND.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import matplotlib.pyplot as plt
import numpy as np
import uadapy.distribution as dist
from uadapy import distribution
import uadapy.plotting.utils as utils

def plot_samples(distributions, num_samples, **kwargs):
Expand All @@ -11,7 +11,7 @@ def plot_samples(distributions, num_samples, **kwargs):
:param kwargs: Optional other arguments to pass:
:return:
"""
if isinstance(distributions, dist.distribution):
if isinstance(distributions, distribution):
distributions = [distributions]
# Create matrix
numvars = distributions[0].dim
Expand Down Expand Up @@ -78,7 +78,7 @@ def plot_contour(distributions, num_samples, resolution=128, ranges=None, quanti
If the dimension of the distribution is less than 2.
"""

if isinstance(distributions, dist.distribution):
if isinstance(distributions, distribution):
distributions = [distributions]
contour_colors = utils.generate_spectrum_colors(len(distributions))
# Create matrix
Expand Down Expand Up @@ -193,7 +193,7 @@ def plot_contour_samples(distributions, num_samples, resolution=128, ranges=None
If the dimension of the distribution is less than 2.
"""

if isinstance(distributions, dist.distribution):
if isinstance(distributions, distribution):
distributions = [distributions]
contour_colors = utils.generate_spectrum_colors(len(distributions))
# Create matrix
Expand Down

0 comments on commit 2569f56

Please sign in to comment.