funcsim 0.2.4__tar.gz → 0.2.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. {funcsim-0.2.4/funcsim.egg-info → funcsim-0.2.5}/PKG-INFO +2 -2
  2. {funcsim-0.2.4 → funcsim-0.2.5}/README.md +1 -1
  3. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/__init__.py +2 -2
  4. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/dependence.py +81 -9
  5. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/nearby.py +2 -2
  6. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/shrinkage.py +26 -11
  7. {funcsim-0.2.4 → funcsim-0.2.5/funcsim.egg-info}/PKG-INFO +2 -2
  8. {funcsim-0.2.4 → funcsim-0.2.5}/setup.py +1 -1
  9. {funcsim-0.2.4 → funcsim-0.2.5}/LICENSE +0 -0
  10. {funcsim-0.2.4 → funcsim-0.2.5}/MANIFEST.in +0 -0
  11. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/addist.py +0 -0
  12. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/conversions.py +0 -0
  13. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/copfit.py +0 -0
  14. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/core.py +0 -0
  15. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/cpt.py +0 -0
  16. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/cvmdist.py +0 -0
  17. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/distfit.py +0 -0
  18. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/ecdfgof.py +0 -0
  19. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/edf.py +0 -0
  20. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/eut.py +0 -0
  21. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/imanconover.py +0 -0
  22. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/kde.py +0 -0
  23. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/ksdist.py +0 -0
  24. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/multicore.py +0 -0
  25. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/plotting.py +0 -0
  26. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/rdarrays.py +0 -0
  27. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/screen.py +0 -0
  28. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/shapiro.py +0 -0
  29. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/testsim.py +0 -0
  30. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/utests.py +0 -0
  31. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim/vect.py +0 -0
  32. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim.egg-info/SOURCES.txt +0 -0
  33. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim.egg-info/dependency_links.txt +0 -0
  34. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim.egg-info/requires.txt +0 -0
  35. {funcsim-0.2.4 → funcsim-0.2.5}/funcsim.egg-info/top_level.txt +0 -0
  36. {funcsim-0.2.4 → funcsim-0.2.5}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: funcsim
3
- Version: 0.2.4
3
+ Version: 0.2.5
4
4
  Summary: functional, simple stochastic simulation
5
5
  Home-page: https://github.com/h-bryant/funcsim
6
6
  Author: Henry Bryant
@@ -54,7 +54,7 @@ Features:
54
54
  - stratified/Latin hypercube sampling
55
55
  - painless multi-core simulations
56
56
  - fitting and comparison of univariate distributions, kernel density estimates, and goodness-of-fit tests
57
- - multivariate normal and KDE distributions; Gaussian, Student's t, Clayton, Gumbel, and Frank copulas (implemented natively, no additional packages required); Iman-Conover
57
+ - multivariate normal and KDE distributions; Gaussian, Student's t, Clayton, Gumbel, and Frank copulas (implemented natively, no additional packages required); Iman-Conover; covariance shrinkage
58
58
  - expected utility and cumulative prospect theory calculations
59
59
  - plotly-based fan charts and diagnostic plots
60
60
  - highly flexible, and as simple as possible (but no more)
@@ -9,7 +9,7 @@ Features:
9
9
  - stratified/Latin hypercube sampling
10
10
  - painless multi-core simulations
11
11
  - fitting and comparison of univariate distributions, kernel density estimates, and goodness-of-fit tests
12
- - multivariate normal and KDE distributions; Gaussian, Student's t, Clayton, Gumbel, and Frank copulas (implemented natively, no additional packages required); Iman-Conover
12
+ - multivariate normal and KDE distributions; Gaussian, Student's t, Clayton, Gumbel, and Frank copulas (implemented natively, no additional packages required); Iman-Conover; covariance shrinkage
13
13
  - expected utility and cumulative prospect theory calculations
14
14
  - plotly-based fan charts and diagnostic plots
15
15
  - highly flexible, and as simple as possible (but no more)
@@ -46,6 +46,6 @@ def version():
46
46
  Returns
47
47
  -------
48
48
  str
49
- The version string of the package (e.g., '0.2.4').
49
+ The version string of the package (e.g., '0.2.5').
50
50
  """
51
- return "0.2.4"
51
+ return "0.2.5"
@@ -2,7 +2,7 @@ import math
2
2
  import numpy as np
3
3
  import pandas as pd
4
4
  from scipy import stats
5
- from typing import Generator, Optional, Tuple
5
+ from typing import Generator, Optional, Sequence, Tuple
6
6
  import warnings
7
7
  from . import conversions
8
8
  from . import copfit
@@ -284,10 +284,12 @@ class MvKde():
284
284
 
285
285
  class MvNorm():
286
286
  """
287
- A multivariate normal distribution object. A vector of means
288
- and a covariance matrix are computed from the input data. If the sample
289
- covariance matrix is not positive definite, the Higham
290
- method is used to calculate the nearest positive definite matrix.
287
+ A multivariate normal distribution object. Constructed from data, a
288
+ vector of means and a covariance matrix are computed from the input.
289
+ Constructed with :meth:`from_params`, the mean vector and covariance
290
+ matrix are supplied directly. Either way, if the covariance matrix is
291
+ not positive definite, the Higham method is used to calculate the
292
+ nearest positive definite matrix.
291
293
 
292
294
  Parameters
293
295
  ----------
@@ -323,10 +325,80 @@ class MvNorm():
323
325
  swp = shapiro.swtest(self._data[:, k])[1]
324
326
  if not swp > 0.05:
325
327
  msg = (f"variable '{self._names[k]}' may not be "
326
- f" normally distributed. (Shapiro-Wilk p-value"
328
+ f"normally distributed. (Shapiro-Wilk p-value"
327
329
  f"={swp:.3f})")
328
330
  warnings.warn(msg, UserWarning)
329
331
 
332
+ @classmethod
333
+ def from_params(cls,
334
+ mu: conversions.VectorLike,
335
+ sigma: conversions.ArrayLike,
336
+ names: Optional[Sequence[str]] = None,
337
+ ) -> "MvNorm":
338
+ """
339
+ Create a multivariate normal distribution object from a mean vector
340
+ and a covariance matrix, rather than from data.
341
+
342
+ Parameters
343
+ ----------
344
+ mu : VectorLike
345
+ Mean vector of length K.
346
+ sigma : ArrayLike
347
+ K-by-K covariance matrix (a nested list is also accepted). It
348
+ must be symmetric. If it is not positive definite, the nearest
349
+ positive definite matrix (Higham, 1988) is substituted with a
350
+ warning.
351
+ names : sequence of str, optional
352
+ Variable names, length K. If omitted, the index of `mu` (if it
353
+ is a pandas Series) or the column labels of `sigma` (if it is a
354
+ pandas DataFrame) are used; otherwise the variables are named
355
+ 'v0', 'v1', ....
356
+
357
+ Returns
358
+ -------
359
+ MvNorm
360
+ A distribution object whose :meth:`draw` method returns joint
361
+ draws with the given means and covariances.
362
+
363
+ Notes
364
+ -----
365
+ No normality check is performed, since there are no data to check.
366
+
367
+ Examples
368
+ --------
369
+ >>> dist = fs.MvNorm.from_params([3.0, 4.0], [[1.0, 0.5], [0.5, 1.0]])
370
+ """
371
+ muA = np.asarray(conversions.vlToArray(mu), dtype=float)
372
+ if isinstance(sigma, (list, tuple)):
373
+ sigmaA = np.asarray(sigma, dtype=float)
374
+ else:
375
+ sigmaA = np.asarray(conversions.alToArray(sigma), dtype=float)
376
+ K = muA.shape[0]
377
+ if sigmaA.shape != (K, K):
378
+ raise ValueError(f"sigma must be {K}-by-{K} to match mu; "
379
+ f"got shape {sigmaA.shape}")
380
+ if not np.allclose(sigmaA, sigmaA.T):
381
+ raise ValueError("sigma must be symmetric")
382
+ if names is not None:
383
+ nms = pd.Index(list(names))
384
+ elif isinstance(mu, pd.Series):
385
+ nms = pd.Index(mu.index)
386
+ elif isinstance(sigma, pd.DataFrame):
387
+ nms = pd.Index(sigma.columns)
388
+ else:
389
+ nms = pd.Index([f"v{k}" for k in range(K)])
390
+ if len(nms) != K:
391
+ raise ValueError(f"names must have length {K}; got {len(nms)}")
392
+
393
+ obj = cls.__new__(cls)
394
+ obj._data = None
395
+ obj._names = nms
396
+ (obj._M, obj._K) = (0, K)
397
+ obj._mu = muA
398
+ obj._sigma = nearby.nearestpd(sigmaA)
399
+ obj._A = np.linalg.cholesky(obj._sigma)
400
+ return obj
401
+
330
402
  def draw(self,
331
403
  ugen: Generator[float, None, None]
332
404
  ) -> pd.Series:
@@ -344,9 +416,9 @@ class MvNorm():
344
416
  A pandas Series representing a joint draw from the multivariate
345
417
  normal distribution. The index values are the variable names,
346
418
  and the values are the random values. If no variable names were
347
- provided in the input data,
348
- the variables will be named 'v0', 'v1', ..., reflecting the
349
- order of the columns in the input data.
419
+ provided (as column labels of the input data, or through the
420
+ `names` argument of :meth:`from_params`), the variables are
421
+ named 'v0', 'v1', ..., in column order.
350
422
  """
351
423
  uvec = [next(ugen) for i in range(self._K)]
352
424
  retA = self._mu + np.dot(self._A, stats.norm.ppf(uvec))
@@ -72,7 +72,7 @@ def nearestpd(array):
72
72
 
73
73
  if is_positive_definite(A3):
74
74
  msg = ("Higham's (1988) first method was employed to compute "
75
- "the pos. def. matrix nearest to the sample covariance matrix.")
75
+ "the positive definite matrix nearest to the input matrix.")
76
76
  warnings.warn(msg, UserWarning)
77
77
  return repackage(array, A3)
78
78
 
@@ -94,6 +94,6 @@ def nearestpd(array):
94
94
  A3 += Id * (-mineig * k ** 2 + spacing)
95
95
  k += 1
96
96
  msg = ("Higham's (1988) second method was employed to compute "
97
- "the pos. def. matrix nearest to the sample covariance matrix.")
97
+ "the positive definite matrix nearest to the input matrix.")
98
98
  warnings.warn(msg, UserWarning)
99
99
  return repackage(array, A3)
@@ -6,6 +6,7 @@ Genetics and Molecular Biology//, vol 4(2005), issue 1.
6
6
  """
7
7
 
8
8
  import itertools
9
+ from typing import Tuple, Union
9
10
  import numpy as np
10
11
  import pandas as pd
11
12
  import xarray as xr
@@ -207,7 +208,10 @@ def _target_f(x):
207
208
 
208
209
 
209
210
  def shrink(data: conversions.ArrayLike,
210
- target: str ) -> conversions.ArrayLike:
211
+ target: str,
212
+ return_intensity: bool = False
213
+ ) -> Union[conversions.ArrayLike,
214
+ Tuple[conversions.ArrayLike, float]]:
211
215
  """
212
216
  Covariance shrinkage estimator.
213
217
 
@@ -229,11 +233,18 @@ def shrink(data: conversions.ArrayLike,
229
233
  Targets 'B', 'E', and 'F' originate in Ledoit and Wolf (2003,
230
234
  2004). The shrinkage intensity is estimated analytically in each
231
235
  case.
236
+ return_intensity : bool, optional
237
+ If True, also return the estimated shrinkage intensity. Default is
238
+ False.
232
239
 
233
240
  Returns
234
241
  -------
235
- ArrayLike
236
- The estimated covariance matrix, with a type matching the data array
242
+ ArrayLike or tuple
243
+ The estimated covariance matrix, with a type matching the data
244
+ array. If `return_intensity` is True, a tuple ``(sigma, lam)``,
245
+ where ``lam`` is the shrinkage intensity, a float in [0, 1]: 0
246
+ leaves the sample covariance matrix unchanged and 1 replaces it
247
+ with the target.
237
248
 
238
249
  Raises
239
250
  ------
@@ -259,26 +270,30 @@ def shrink(data: conversions.ArrayLike,
259
270
  'E': _target_e,
260
271
  'F': _target_f}
261
272
 
262
- sig = target_map[target](a_np)[0]
273
+ sig, lam = target_map[target](a_np)
263
274
 
264
275
  # return the same type of array that was passed. the result is a
265
276
  # p-by-p covariance matrix, so both axes are labeled with the
266
277
  # variable (column) labels of the input, not the observation index
267
278
  if isinstance(data, pd.DataFrame):
268
- df = pd.DataFrame(data=sig, index=data.columns, columns=data.columns)
269
- return df
279
+ result = pd.DataFrame(data=sig, index=data.columns,
280
+ columns=data.columns)
270
281
  elif isinstance(data, xr.DataArray):
271
282
  coldim = str(data.dims[-1])
272
283
  if coldim in data.coords:
273
284
  varnames = np.asarray(data.coords[coldim].values)
274
285
  else:
275
286
  varnames = np.arange(sig.shape[0])
276
- da = xr.DataArray(sig,
277
- dims=(coldim, coldim + "_"),
278
- coords={coldim: varnames, coldim + "_": varnames})
279
- return da
287
+ result = xr.DataArray(sig,
288
+ dims=(coldim, coldim + "_"),
289
+ coords={coldim: varnames,
290
+ coldim + "_": varnames})
280
291
  else:
281
- return sig
292
+ result = sig
293
+
294
+ if return_intensity:
295
+ return result, float(lam)
296
+ return result
282
297
 
283
298
 
284
299
  if __name__ == '__main__':
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: funcsim
3
- Version: 0.2.4
3
+ Version: 0.2.5
4
4
  Summary: functional, simple stochastic simulation
5
5
  Home-page: https://github.com/h-bryant/funcsim
6
6
  Author: Henry Bryant
@@ -54,7 +54,7 @@ Features:
54
54
  - stratified/Latin hypercube sampling
55
55
  - painless multi-core simulations
56
56
  - fitting and comparison of univariate distributions, kernel density estimates, and goodness-of-fit tests
57
- - multivariate normal and KDE distributions; Gaussian, Student's t, Clayton, Gumbel, and Frank copulas (implemented natively, no additional packages required); Iman-Conover
57
+ - multivariate normal and KDE distributions; Gaussian, Student's t, Clayton, Gumbel, and Frank copulas (implemented natively, no additional packages required); Iman-Conover; covariance shrinkage
58
58
  - expected utility and cumulative prospect theory calculations
59
59
  - plotly-based fan charts and diagnostic plots
60
60
  - highly flexible, and as simple as possible (but no more)
@@ -5,7 +5,7 @@ with open("README.md", "r") as fh:
5
5
 
6
6
  setuptools.setup(
7
7
  name="funcsim",
8
- version="0.2.4",
8
+ version="0.2.5",
9
9
  license="bsd-3-clause",
10
10
  author="Henry Bryant",
11
11
  author_email="henry@tamu.edu",
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes