Skip to content

rainflow

Overview

Extract turning points, count ASTM or four-point cycles, and recover the residual history.

py_fatigue.cycle_count.rainflow

Rainflow cycle counting algorithms for fatigue analysis.

Implements: - ASTM E1049 three-point rainflow. - Four-point rainflow (Amzallag et al. 1994).

Also includes utilities to find turning points and extrema.

References

[1] ASTM E1049, Standard Practices for Cycle Counting in Fatigue [2] Rychlik (1987), "A new definition of the rainflow cycle counting method" [3] Amzallag et al. (1994), "Standardization of the rainflow counting method"

See also

findtp : Find indices to turning points. findextrema : Find indices to local maxima and minima. findcross : Find indices to level crossings.

Functions:

findcross

findcross(x, v=0.0, kind=None)

Return sample indices just before crossings of level v.

A plateau at the crossing level belongs to the preceding side, with the last level sample marking the crossing. Use "u" or "d" to select a direction, or None, "all" or "du" for both.

Examples:

>>> findcross(np.array([-2, 0, 0, 3, 0, -1])).tolist()
[2, 4]
>>> findcross(np.array([-2, 0, 0, 3, 0, -1]), kind="d").tolist()
[4]
Source code in py_fatigue/cycle_count/rainflow.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def findcross(
    x: np.ndarray, v: float = 0.0, kind: str | None = None
) -> np.ndarray:
    """Return sample indices just before crossings of level ``v``.

    A plateau at the crossing level belongs to the preceding side, with
    the last level sample marking the crossing. Use ``"u"`` or ``"d"`` to
    select a direction, or ``None``, ``"all"`` or ``"du"`` for both.

    Examples
    --------
    >>> findcross(np.array([-2, 0, 0, 3, 0, -1])).tolist()
    [2, 4]
    >>> findcross(np.array([-2, 0, 0, 3, 0, -1]), kind="d").tolist()
    [4]
    """
    if len(x) and np.isnan(np.min(x)):
        raise ValueError("data contain NaN")
    sides = np.asarray(np.sign(np.atleast_1d(x).ravel() - v), dtype=np.int8)
    crossings = findcross_indices(sides)
    if crossings.size == 0:
        warnings.warn(f"No level v = {v:0.5g} crossings found in x")
        return crossings
    if kind in (None, "all", "du"):
        return crossings
    if kind not in ("u", "d"):
        raise ValueError(f"Unknown cycle-crossing definition! ({kind})")
    first_is_up = sides[crossings[0] + 1] > 0
    return crossings[int(first_is_up != (kind == "u")) :: 2]

findcross_indices

findcross_indices(xn)

Return indices immediately before zero crossings in signed data.

Source code in py_fatigue/cycle_count/rainflow.py
110
111
112
def findcross_indices(xn: Any) -> np.ndarray:
    """Return indices immediately before zero crossings in signed data."""
    return find_crossings(np.ascontiguousarray(xn, dtype=np.int8))

findextrema

findextrema(x)

Return indices where consecutive sample differences change sign.

Examples:

>>> findextrema(np.array([1, 3, 3, 0, 4])).tolist()
[2, 3]
Source code in py_fatigue/cycle_count/rainflow.py
 98
 99
100
101
102
103
104
105
106
107
def findextrema(x: np.ndarray) -> np.ndarray:
    """Return indices where consecutive sample differences change sign.

    Examples
    --------
    >>> findextrema(np.array([1, 3, 3, 0, 4])).tolist()
    [2, 3]
    """
    differences = np.diff(np.atleast_1d(x).ravel())
    return findcross(differences) + 1

findrfc_astm

findrfc_astm(tp, t=None)

Count cycles in a sequence of reversals using ASTM E1049.

Parameters:

Name Type Description Default
tp array - like

Reversal values in acquisition order.

required
t array - like

Times at the reversals.

None

Returns:

Type Description
ndarray

Amplitude, mean and cycle count (0.5 or 1.0) in each row. If t is provided, the last columns are start time and period. Residual half cycles follow the cycles emitted during the scan.

Examples:

>>> findrfc_astm(np.array([0, 4, 1, 5])).tolist()
[[1.5, 2.5, 1.0], [2.5, 2.5, 0.5]]
Source code in py_fatigue/cycle_count/rainflow.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def findrfc_astm(tp: np.ndarray, t: Optional[np.ndarray] = None) -> np.ndarray:
    """Count cycles in a sequence of reversals using ASTM E1049.

    Parameters
    ----------
    tp : array-like
        Reversal values in acquisition order.
    t : array-like, optional
        Times at the reversals.

    Returns
    -------
    np.ndarray
        Amplitude, mean and cycle count (0.5 or 1.0) in each row.
        If ``t`` is provided, the last columns are start time and period.
        Residual half cycles follow the cycles emitted during the scan.

    Examples
    --------
    >>> findrfc_astm(np.array([0, 4, 1, 5])).tolist()
    [[1.5, 2.5, 1.0], [2.5, 2.5, 0.5]]
    """
    values = np.ascontiguousarray(np.ravel(tp), dtype=float)
    times = (
        None if t is None else np.ascontiguousarray(np.ravel(t), dtype=float)
    )
    return astm_cycles(values, times)

findrfc_fourpoint

findrfc_fourpoint(tp, t=None)

Return rainflow counted cycles using the four-point method.

Parameters:

Name Type Description Default
tp array - like

vector of turning-points (NB! Only values, not sampled times)

required
t array - like

vector of sampled times

None

Returns:

Name Type Description
sig_rfc array - like

array of shape (n,3) or (n, 5) with: sig_rfc[:,0] Cycles amplitude sig_rfc[:,1] Cycles mean value sig_rfc[:,2] Cycle type, half (=0.5) or full (=1.0) sig_rfc[:,3] cycle_begin_time (only if t is given) sig_rfc[:,4] cycle_period_time (only if t is given)

Source code in py_fatigue/cycle_count/rainflow.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def findrfc_fourpoint(
    tp: np.ndarray, t: Optional[np.ndarray] = None
) -> np.ndarray:
    """
    Return rainflow counted cycles using the four-point method.

    Parameters
    ----------
    tp : array-like
        vector of turning-points (NB! Only values, not sampled times)
    t : array-like, optional
        vector of sampled times

    Returns
    -------
    sig_rfc : array-like
        array of shape (n,3) or (n, 5) with:
        sig_rfc[:,0] Cycles amplitude
        sig_rfc[:,1] Cycles mean value
        sig_rfc[:,2] Cycle type, half (=0.5) or full (=1.0)
        sig_rfc[:,3] cycle_begin_time (only if t is given)
        sig_rfc[:,4] cycle_period_time (only if t is given)
    """
    sig = np.asarray(tp, dtype=float)
    n = len(sig)
    times: List[Optional[float]] = [None] * n if t is None else list(t)
    seq = [(float(sig[i]), times[i], i) for i in range(n)]

    cycles, residue_seq = _extract_cycles_from_sequence(seq)
    final_cycles = cycles.copy()
    decomposed, residue_seq = _process_residue(residue_seq)
    final_cycles.extend(decomposed)

    # convert leftover residue into half cycles
    for k in range(len(residue_seq) - 1):
        p1, p2 = residue_seq[k], residue_seq[k + 1]
        amp = abs(p2[0] - p1[0]) / 2.0  # amplitude definition
        mean = (p1[0] + p2[0]) / 2.0
        final_cycles.append(
            {
                "amplitude": amp,
                "mean": mean,
                "type": 0.5,
                "i_idx": p1[2],
                "j_idx": p2[2],
                "i_time": p1[1],
                "j_time": p2[1],
            }
        )

    rows: List[List[Any]] = []
    for c in final_cycles:
        if t is None:
            rows.append([c["amplitude"], c["mean"], c["type"]])
        else:
            begin_time = c["i_time"]
            period_time = (
                abs(c["j_time"] - c["i_time"]) * 2
                if c["i_time"] is not None and c["j_time"] is not None
                else None
            )
            rows.append(
                [c["amplitude"], c["mean"], c["type"], begin_time, period_time]
            )
    return np.asarray(rows, dtype=float)

findtp

findtp(x)

Return reversal indices with the first and last samples included.

Fewer than two interior reversals are treated as an empty sequence, following the cycle-counting convention of Py-Fatigue 2.1.1.

Examples:

>>> findtp(np.array([0, 3, 1, 5, 0])).tolist()
[0, 1, 2, 3, 4]
Source code in py_fatigue/cycle_count/rainflow.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def findtp(x: np.ndarray) -> np.ndarray:
    """Return reversal indices with the first and last samples included.

    Fewer than two interior reversals are treated as an empty sequence,
    following the cycle-counting convention of Py-Fatigue 2.1.1.

    Examples
    --------
    >>> findtp(np.array([0, 3, 1, 5, 0])).tolist()
    [0, 1, 2, 3, 4]
    """
    reversals = findextrema(x)
    if reversals.size < 2:
        return np.empty(0, dtype=np.int64)
    return np.r_[0, reversals, len(x) - 1]

rainflow

rainflow(
    data, time=None, method="astm", extended_output=True
)

Returns the cycle-count of the input data calculated through the rainflow method (ASTM or four-point).

Parameters:

Name Type Description Default
data Union[ndarray, list]

time series or residuals sequence

required
time Optional[Union[ndarray, list]]

sampled times, by default None

None
method str

"astm" or "fourpoint"

'astm'
extended_output bool

If True, also return residuals.

True

Returns:

Type Description
Union[ndarray, tuple]
Source code in py_fatigue/cycle_count/rainflow.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def rainflow(
    data: Union[np.ndarray, list],
    time: Optional[Union[np.ndarray, list]] = None,
    method: str = "astm",
    extended_output: bool = True,
) -> Union[np.ndarray, Tuple]:
    """
    Returns the cycle-count of the input data calculated through the
    rainflow method (ASTM or four-point).

    Parameters
    ----------
    data : Union[np.ndarray, list]
        time series or residuals sequence
    time : Optional[Union[np.ndarray, list]], optional
        sampled times, by default None
    method : str, optional
        "astm" or "fourpoint"
    extended_output : bool, optional
        If True, also return residuals.

    Returns
    -------
    Union[np.ndarray, tuple]
    """
    if isinstance(data, list):
        data = np.array(data)
    if not isinstance(data, np.ndarray):
        raise TypeError("data shall be either numpy.1darray or list")
    if time is not None:
        if isinstance(time, list):
            time = np.array(time)
        if not isinstance(time, np.ndarray):
            raise TypeError("time shall be either numpy.1darray or list")
        if len(time) != len(data):
            raise ValueError("time and data must have the same length")
    idx = findtp(data)  # [1:-1]
    tp = data[idx]

    if method.lower() == "astm":
        rfs = findrfc_astm(tp, idx)
    elif method.lower() == "fourpoint":
        rfs = findrfc_fourpoint(tp, idx)
    else:
        raise ValueError(f"Unknown rainflow method: {method}")

    # build residual signal (based on half cycles)
    res = rfs[rfs[:, 2] == 0.5]
    res_tp = res[:, -2].astype(int)
    res_tp = np.append(res_tp, [len(data) - 1])
    if extended_output:
        if time is None:
            return rfs, data[res_tp], res_tp
        return rfs, data[res_tp], res_tp, time[res_tp]
    return rfs