diff --git a/dapper/mods/__init__.py b/dapper/mods/__init__.py index f5cc6d66..c0afec5e 100644 --- a/dapper/mods/__init__.py +++ b/dapper/mods/__init__.py @@ -49,36 +49,37 @@ class HiddenMarkovModel(struct_tools.NicePrint): imports all configurations, which might then unintentionally interact. To avoid this, you should use the `copy` method of the `HMM` before making any changes to it. - - - Parameters - ---------- - Dyn: `Operator` or dict - Operator for the dynamics. - Obs: `Operator` or dict - Operator for the observations - Can also be time-dependent, ref `TimeDependentOperator`. - tseq: [`tools.chronos.Chronology`][] - Time sequence of the HMM process. - X0: [`tools.randvars.RV`][] - Random distribution of initial condition - liveplotters: `list`, optional - A list of tuples. See example use in function `LPs` of [`mods.Lorenz63`][]. - - The first element of the tuple determines if the liveplotter - is shown by default. If `False`, the liveplotter is only shown when - included among the `liveplots` argument of `assimilate` - - The second element in the tuple gives the corresponding liveplotter - function/class. - sectors: `dict`, optional - Labelled indices referring to parts of the state vector. - When defined, field-mean statistics are computed for each sector. - Example use can be found in `examples/param_estim.py` - and `dapper/mods/Lorenz96/miyoshi2011.py` - name: str, optional - Label for the `HMM`. """ def __init__(self, *args, **kwargs): + """Initialize. + + Parameters + ---------- + Dyn : Operator or dict + Operator for the dynamics. + Obs : Operator or dict + Operator for the observations + Can also be time-dependent, ref `TimeDependentOperator`. + tseq : tools.chronos.Chronology + Time sequence of the HMM process. + X0 : tools.randvars.RV + Random distribution of initial condition + liveplotters : list, optional + A list of tuples. See example use in function `LPs` of [`mods.Lorenz63`][]. + - The first element of the tuple determines if the liveplotter + is shown by default. If `False`, the liveplotter is only shown when + included among the `liveplots` argument of `assimilate` + - The second element in the tuple gives the corresponding liveplotter + function/class. + sectors : dict, optional + Labelled indices referring to parts of the state vector. + When defined, field-mean statistics are computed for each sector. + Example use can be found in `examples/param_estim.py` + and `dapper/mods/Lorenz96/miyoshi2011.py` + name : str, optional + Label for the `HMM`. + """ # Expected args/kwargs, along with type and default. attrs = dict( Dyn=(Operator, None), @@ -216,11 +217,11 @@ class Operator(struct_tools.NicePrint): Parameters ---------- - M: int + M : int Length of output vectors. - model: function + model : function The actual operator. - noise: RV, optional + noise : RV, optional The associated additive noise. The noise can also be a scalar or an array, producing `GaussRV(C=noise)`. diff --git a/dapper/mods/utils.py b/dapper/mods/utils.py index 78dbeeb7..1aeb223c 100644 --- a/dapper/mods/utils.py +++ b/dapper/mods/utils.py @@ -116,14 +116,14 @@ def direct_obs_matrix(Nx, obs_inds): Parameters ---------- - Nx: int + Nx : int Length of state vector - obs_inds: ndarray + obs_inds : ndarray Indices of elements of the state vector that are (directly) observed. Returns ------- - H: ndarray + H : ndarray The observation matrix for direct partial observations. """ Ny = len(obs_inds) @@ -143,14 +143,14 @@ def partial_Id_Obs(Nx, obs_inds): Parameters ---------- - Nx: int + Nx : int Length of state vector - obs_inds: ndarray + obs_inds : ndarray The observed indices. Returns ------- - Obs: dict + Obs : dict Observation operator including size of the observation space, observation operator/model and tangent linear observation operator """ @@ -181,12 +181,12 @@ def Id_Obs(Nx): Parameters ---------- - Nx: int + Nx : int Length of state vector Returns ------- - Obs: dict + Obs : dict Observation operator including size of the observation space, observation operator/model and tangent linear observation operator """ @@ -198,18 +198,18 @@ def linspace_int(Nx, Ny, periodic=True): Parameters ---------- - Nx: int + Nx : int Range of integers - Ny: int + Ny : int Number of integers - periodic: bool, optional + periodic : bool, optional Whether the vector is periodic. Determines if `Nx == 0`. Default: True Returns ------- - integers: ndarray + integers : ndarray The list of integers. Examples diff --git a/dapper/stats.py b/dapper/stats.py index ffe6aa4a..4a80aebd 100644 --- a/dapper/stats.py +++ b/dapper/stats.py @@ -631,10 +631,10 @@ def unpack_uqs(uq_list, decimals=None): Parameters ---------- - uq_list: list + uq_list : list List of `uq`s. - decimals: int + decimals : int Desired number of decimals. Used for (only) the columns "val" and "prec". Default: `None`. In this case, the formatting is left to the `uq`s. @@ -707,23 +707,23 @@ def center(E, axis=0, rescale=False): Parameters ---------- - E: ndarray + E : ndarray Ensemble which going to be inflated - axis: int, optional + axis : int, optional The axis to be centered. Default: 0 - rescale: bool, optional + rescale : bool, optional If True, inflate to compensate for reduction in the expected variance. The inflation factor is \(\sqrt{\frac{N}{N - 1}}\) where N is the ensemble size. Default: False Returns ------- - X: ndarray + X : ndarray Ensemble anomaly - x: ndarray + x : ndarray Mean of the ensemble """ x = np.mean(E, axis=axis, keepdims=True) @@ -755,7 +755,7 @@ def inflate_ens(E, factor): E : ndarray Ensemble which going to be inflated - factor: `float` + factor : `float` Inflation factor Returns @@ -777,10 +777,10 @@ def weight_degeneracy(w, prec=1e-10): Parameters ---------- - w: ndarray + w : ndarray Importance weights. Must sum to 1. - prec: float, optional + prec : float, optional Tolerance of the distance between w and one. Default:1e-10 Returns @@ -796,21 +796,21 @@ def unbias_var(w=None, N_eff=None, avoid_pathological=False): Parameters ---------- - w: ndarray, optional + w : ndarray, optional Importance weights. Must sum to 1. Only one of `w` and `N_eff` can be `None`. Default: `None` - N_eff: float, optional + N_eff : float, optional The "effective" size of the weighted ensemble. If not provided, it is computed from the weights. The unbiasing factor is $$ N_{eff} / (N_{eff} - 1) $$. - avoid_pathological: bool, optional + avoid_pathological : bool, optional Avoid weight collapse. Default: `False` Returns ------- - ub: float + ub : float factor used to unbiasing variance Reference diff --git a/dapper/tools/linalg.py b/dapper/tools/linalg.py index c307847c..612951dc 100644 --- a/dapper/tools/linalg.py +++ b/dapper/tools/linalg.py @@ -39,11 +39,11 @@ def tsvd(A, threshold=0.99999, avoid_pathological=True): Parameters ---------- - avoid_pathological: bool + avoid_pathological : bool Avoid truncating (e.g.) the identity matrix. NB: only applies for float threshold. - threshold: float or int + threshold : float or int - if `float`, `< 1.0` then "rank" = lowest number such that the "energy" retained >= threshold diff --git a/dapper/tools/localization.py b/dapper/tools/localization.py index 0cc16c46..f03f0076 100644 --- a/dapper/tools/localization.py +++ b/dapper/tools/localization.py @@ -20,13 +20,13 @@ def pairwise_distances(A, B=None, domain=None): Parameters ---------- - A: array of shape `(nPoints, nDims)`. + A : array of shape `(nPoints, nDims)`. A collection of points. - B: + B : Same as `A`, but `nPoints` can differ. - domain: tuple + domain : tuple Assume the domain is a **periodic** hyper-rectangle whose edges along dimension `i` span from 0 to `domain[i]`. NB: Behaviour not defined if `any(A.max(0) > domain)`, and likewise for `B`. @@ -221,8 +221,8 @@ def rectangular_partitioning(shape, steps, do_ind=True): Parameters ---------- - shape: (len(grid[dim]) for dim in range(ndim)) - steps: (step_len[dim] for dim in range(ndim)) + shape : (len(grid[dim]) for dim in range(ndim)) + steps : (step_len[dim] for dim in range(ndim)) Returns ------- diff --git a/dapper/tools/rounding.py b/dapper/tools/rounding.py index 475160da..550e0bbd 100644 --- a/dapper/tools/rounding.py +++ b/dapper/tools/rounding.py @@ -124,12 +124,12 @@ def np_vectorize(f): Parameters ---------- - f: callable + f : callable Your function. Returns ------- - vectorized: callable + vectorized : callable Your function, now element-wise applicable to an iterable. """ vectorized = np.vectorize(f) @@ -192,7 +192,7 @@ def round2(x, prec=1.0): ---------- x : array_like Value to be rounded. - prec: float + prec : float Precision, before prettify, which is given by $$ \text{prec} = 10^{\text{floor}(-\log_{10}|\text{prec}|)} $$ @@ -259,12 +259,12 @@ def is_whole(x, **kwargs): Parameters ---------- - x: float or ndarray + x : float or ndarray Values to be checked Returns ------- - l: bool + l : bool True if rounded x is close to x, otherwise False """ return np.isclose(x, round(x), **kwargs) diff --git a/dapper/tools/viz.py b/dapper/tools/viz.py index e28635c4..33e14f56 100644 --- a/dapper/tools/viz.py +++ b/dapper/tools/viz.py @@ -27,9 +27,9 @@ def setup_wrapping(M, periodicity=None): Parameters ---------- - M: int + M : int Length of the periodic domain - periodicity: bool, optional + periodicity : bool, optional The mode of the wrapping. "+1": the first element is appended after the last. "+/-05": adding the midpoint of the first and last elements. @@ -37,9 +37,9 @@ def setup_wrapping(M, periodicity=None): Returns ------- - ii: ndarray + ii : ndarray indices of periodic domain - wrap: func + wrap : func transform non-periodic data into periodic data """ if periodicity in (None, True): @@ -77,24 +77,24 @@ def amplitude_animation( Parameters ---------- - EE: ndarray + EE : ndarray Ensemble arry of the shape (K, N, Nx). K is the length of time, N is the ensemble size, and Nx is the length of state vector. - dt: float + dt : float Time interval of each frame. - interval: float, optional + interval : float, optional Delay between frames in milliseconds. Defaults to 200. - periodicity: bool, optional + periodicity : bool, optional The mode of the wrapping. "+1": the first element is appended after the last. "+/-05": adding the midpoint of the first and last elements. Default: "+1" - blit: bool, optional + blit : bool, optional Controls whether blitting is used to optimize drawing. Default: True - fignum: int, optional + fignum : int, optional Figure index. Default: None - repeat: bool, optional + repeat : bool, optional If True, repeat the animation. Default: False """ fig, ax = place.freshfig(fignum or "Amplitude animation") @@ -133,15 +133,15 @@ def xtrema(xx, axis=None): Parameters ---------- - xx: ndarray - axis: int, optional + xx : ndarray + axis : int, optional Specific axis for min and max. Defaults: None Returns ------- - a: float + a : float min value - b: float + b : float max value """ a = np.nanmin(xx, axis) @@ -154,21 +154,21 @@ def stretch(a, b, factor=1, int_=False): Parameters ---------- - a: float + a : float Lower bound of domain. - b: float + b : float Upper bound of domain. - factor: float, optional + factor : float, optional Streching factor. Defaults: 1 - int_: bool, optional + int_ : bool, optional If True, the domain bounds are integer. Defaults: False Returns ------- - a: float + a : float Lower bound of domain. - b: float + b : float Upper bound of domain. """ c = (a + b) / 2 @@ -185,12 +185,12 @@ def set_ilim(ax, i, Min=None, Max=None): Parameters ---------- - ax: matplotlib.axes - i: int + ax : matplotlib.axes + i : int 1: x-axis; 2: y-axis; 3: z-axis - Min: float, optional + Min : float, optional Lower bound limit. Defaults: None - Max: float, optional + Max : float, optional Upper bound limit. Defaults: None """ if i == 0: @@ -210,16 +210,16 @@ def estimate_good_plot_length(xx, tseq=None, mult=100): Parameters ---------- - xx: ndarray + xx : ndarray Plotted array - tseq: [`tools.chronos.Chronology`][], optional + tseq : [`tools.chronos.Chronology`][], optional object with property dko. Defaults: None - mult: int, optional + mult : int, optional Number of waves for plotting. Defaults: 100 Returns ------- - K: int + K : int length for plotting Example @@ -319,9 +319,9 @@ def plot_hovmoller(xx, tseq=None): Parameters ---------- - xx: ndarray + xx : ndarray Plotted array - tseq: [`tools.chronos.Chronology`][], optional + tseq : [`tools.chronos.Chronology`][], optional object with property dko. Defaults: None """ fig, ax = place.freshfig("Hovmoller", figsize=(4, 3.5)) @@ -352,15 +352,15 @@ def integer_hist(E, N, centrd=False, weights=None, **kwargs): Parameters ---------- - E: ndarray + E : ndarray Ensemble array. - N: int + N : int Number of histogram bins. - centrd: bool, optional + centrd : bool, optional If True, each bin is centered in the midpoint. Default: False - weights: float, optional + weights : float, optional Weights for histogram. Default: None - kwargs: dict + kwargs : dict keyword arguments for matplotlib.hist """ ax = plt.gca() @@ -374,10 +374,10 @@ def not_available_text(ax, txt=None, fs=20): Parameters ---------- - ax: matplotlib.axes - txt: str, optional + ax : matplotlib.axes + txt : str, optional Printed text. Defaults: '[Not available]' - fs: float, optional + fs : float, optional Font size. Defaults: 20. """ if txt is None: @@ -401,8 +401,7 @@ def plot_err_components(stats): Parameters ---------- - stats: - [`stats.Stats`][] + stats : stats.Stats Note ---- @@ -468,7 +467,7 @@ def plot_rank_histogram(stats): Parameters ---------- - stats: [`stats.Stats`][] + stats: stats.Stats """ tseq = stats.HMM.tseq @@ -514,12 +513,12 @@ def axis_scale_by_array(ax, arr, axis="y", nbins=3): Parameters ---------- - ax: matplotlib.axes - arr: ndarray + ax : matplotlib.axes + arr : ndarray Array for plotting - axis: str, optional + axis : str, optional Scaled axis, which can be 'x', 'y' or 'z'. Defaults: 'y' - nbins: int, optional + nbins : int, optional Number of major ticks. Defaults: 3 """ yy = array([y for y in arr if y is not None], dtype=float) # rm None diff --git a/dapper/xp_launch.py b/dapper/xp_launch.py index d084ddec..1aa700f6 100644 --- a/dapper/xp_launch.py +++ b/dapper/xp_launch.py @@ -39,9 +39,9 @@ def seed_and_simulate(HMM, xp): Parameters ---------- - HMM: HiddenMarkovModel + HMM : HiddenMarkovModel Container defining the system. - xp: object + xp : object Type: a [`da_methods.da_method`][]-decorated class. !!! warning "`xp.seed` should be set (and `int`)." @@ -86,25 +86,25 @@ def run_experiment( Parameters ---------- - xp: object + xp : object Type: a [`da_methods.da_method`][]-decorated class. - label: str + label : str Name attached to progressbar during assimilation. - savedir: str + savedir : str Path of folder wherein to store the experiment data. - HMM: HiddenMarkovModel + HMM : HiddenMarkovModel Container defining the system. - free: bool + free : bool Whether (or not) to `del xp.stats` after the experiment is done, so as to free up memory and/or not save this data (just keeping `xp.avrgs`). - statkeys: list + statkeys : list A list of names (possibly in the form of abbreviations) of the statistical averages that should be printed immediately afther this xp. - fail_gently: bool + fail_gently : bool Whether (or not) to propagate exceptions. - setup: function + setup : function This function must take two arguments: `HMM` and `xp`, and return the `HMM` to be used by the DA methods (typically the same as the input `HMM`, but could be modified), and the (typically synthetic) truth and obs time series. @@ -218,10 +218,10 @@ class xpList(list): Parameters ---------- - args: entries + args : entries Nothing, or a list of `xp`s. - unique: bool + unique : bool Duplicates won't get appended. Makes `append` (and `__iadd__`) relatively slow. Use `extend` or `__add__` or `combinator` to bypass this validation. @@ -299,7 +299,7 @@ def prep_table(self, nomerge=()): Parameters ---------- - nomerge: list + nomerge : list Attributes that should always be seen as distinct. """ diff --git a/dapper/xp_process.py b/dapper/xp_process.py index e86589d6..7635cf40 100644 --- a/dapper/xp_process.py +++ b/dapper/xp_process.py @@ -90,7 +90,7 @@ def __init__(self, dims): Parameters ---------- - dims: list or tuple + dims : list or tuple The attributes defining the coordinate system. """ # Define coordinate system @@ -587,10 +587,10 @@ def print( Parameters ---------- - statkey: str + statkey : str The statistic to extract from the `xp.avrgs` for each `xp`. Examples: `"rmse.a"` (i.e. `"err.rms.a"`), `"rmse.ocean.a"`, `"duration"`. - dims: dict + dims : dict Allots (maps) the dims of `xpSpace` to different roles in the tables. - The "role" `outer` should list the dims/attributes @@ -610,7 +610,7 @@ def print( Equivalently, use `mean=("seed",)`. It is acceptible to leave this empty: `mean=()` or `mean=None`. - subcols: bool + subcols : bool If `True`, then subcolumns are added to indicate - `1σ`: the confidence interval. If `mean=None` is used, this simply reports @@ -621,16 +621,16 @@ def print( as defined by `costfun`. - `☠`: the number of failures (non-finite values) at that point. - `✓`: the number of successes that go into the value - decimals: int + decimals : int Number of decimals to print. If `None`, this is determined for each statistic by its uncertainty. - costfun: str or function + costfun : str or function Use `'increasing'` (default) or `'decreasing'` to indicate that the optimum is defined as the lowest or highest value of the `statkey` found. - squeeze_labels: bool + squeeze_labels : bool Don't include redundant attributes in the line labels. Caution: `get_style` will not be able to access the eliminated attrs. - colorize: bool + colorize : bool Add color to tables for readability. """ # Title @@ -768,16 +768,16 @@ def plot( Parameters ---------- - get_style: function + get_style : function A function that takes an object, and returns a dict of line styles, usually as a function of the object's attributes. - title1: anything + title1 : anything Figure title (in addition to the the defaults). - title2: anything + title2 : anything Figure title (in addition to the defaults). Goes on a new line. - unique_labels: bool + unique_labels : bool Only show a given line label once, even if it appears in several panels. - squeeze_labels: + squeeze_labels : Don't include redundant attributes in the labels. """