Skip to content

histogram

Overview

Bin stress ranges and means and export rainflow counts.

py_fatigue.cycle_count.histogram

The following code is based on the histogram function from the numpy package [4]_.

.. _[4]: https://numpy.org/doc/stable/reference/generated/numpy.histogram2d

Classes

Functions:

binned_rainflow

binned_rainflow(
    data,
    time=None,
    range_bin_lower_bound=0.2,
    range_bin_width=0.05,
    range_bin_upper_bound=None,
    mean_bin_lower_bound=None,
    mean_bin_width=10.0,
    mean_bin_upper_bound=None,
    damage_tolerance_for_binning=0.001,
    max_consetutive_zeros=10,
    damage_exponent=5.0,
    round_decimals=4,
    debug_mode=False,
    rainflow_method="astm",
)

Returns the cycle-count of the input data calculated through the rainflow method.

Parameters:

Name Type Description Default
data ndarray

time series or residuals sequence

required
time Optional[Union[ndarray, list]]

sampled times, by default None

None
range_bin_lower_bound float

lower bound of the range bin, by default 0.2

0.2
range_bin_width float

width of the range bin, by default 0.05

0.05
range_bin_upper_bound Optional[float]

upper bound of the range bin, by default None

None
mean_bin_lower_bound Optional[float]

lower bound of the mean bin, by default None

None
mean_bin_width float

width of the mean bin, by default 10

10.0
mean_bin_upper_bound Optional[float]

upper bound of the mean bin, by default None

None
damage_tolerance_for_binning float

tolerance for the damage when binning large cycles separately, by default 1e-3

0.001
damage_exponent float

exponent for the damage when binning large cycles separately, by default 5.0

5.0
round_decimals int

number of decimals to round the output, by default 4

4
debug_mode bool

if True, print debug messages, by default False

False
rainflow_method str

Rainflow counting algorithm passed to rainflow, by default "astm".

'astm'

Returns:

Type Description
Union[ndarray, tuple]
  • if np.ndarray:
    • rfs : np.ndarray rainflow [ampl ampl_mean nr_of_cycle cycle_begin_time cycle_period_time]
  • if tuple:
    • rfs : np.ndarray rainflow [ampl ampl_mean nr_of_cycle cycle_begin_time cycle_period_time]
    • data[res_tp] : numpy.ndarray the residuals signal
    • res_tp : numpy.ndarray the indices of the residuals signal
    • time[res_tp] : numpy.ndarray the time signal for residuals

Raises:

Type Description
TypeError

data shall be numpy.ndarray or list

See also

calc_rainflow rainflow_binner

Source code in py_fatigue/cycle_count/histogram.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
def binned_rainflow(  # pylint: disable=R0917,R0913
    data: Union[np.ndarray, list],
    time: Optional[Union[np.ndarray, list]] = None,
    range_bin_lower_bound: float = 0.2,
    range_bin_width: float = 0.05,
    range_bin_upper_bound: Optional[float] = None,
    mean_bin_lower_bound: Optional[float] = None,
    mean_bin_width: float = 10.0,
    mean_bin_upper_bound: Optional[float] = None,
    damage_tolerance_for_binning: float = 1e-3,
    max_consetutive_zeros: int = 10,
    damage_exponent: float = 5.0,
    round_decimals: int = 4,
    debug_mode: bool = False,
    rainflow_method: str = "astm",
):
    """
    Returns the cycle-count of the input data calculated through the
    rainflow method.

    Parameters
    ----------
    data : np.ndarray
        time series or residuals sequence
    time : Optional[Union[np.ndarray, list]], optional
        sampled times, by default None
    range_bin_lower_bound : float, optional
        lower bound of the range bin, by default 0.2
    range_bin_width : float, optional
        width of the range bin, by default 0.05
    range_bin_upper_bound : Optional[float], optional
        upper bound of the range bin, by default None
    mean_bin_lower_bound : Optional[float], optional
        lower bound of the mean bin, by default None
    mean_bin_width : float, optional
        width of the mean bin, by default 10
    mean_bin_upper_bound : Optional[float], optional
        upper bound of the mean bin, by default None
    damage_tolerance_for_binning : float, optional
        tolerance for the damage when binning large cycles
        separately, by default 1e-3
    damage_exponent : float, optional
        exponent for the damage when binning large cycles separately, by
        default 5.0
    round_decimals : int, optional
        number of decimals to round the output, by default 4
    debug_mode : bool, optional
        if True, print debug messages, by default False
    rainflow_method : str, optional
        Rainflow counting algorithm passed to
        [`rainflow`] [py_fatigue.cycle_count.rainflow.rainflow], by default
        "astm".
    Returns
    -------
    Union[np.ndarray, tuple]
        - if np.ndarray:
            + rfs : np.ndarray
                rainflow
                [ampl ampl_mean nr_of_cycle cycle_begin_time cycle_period_time]
        - if tuple:
            + rfs : np.ndarray
                rainflow
                [ampl ampl_mean nr_of_cycle cycle_begin_time cycle_period_time]
            + data[res_tp] : numpy.ndarray
                the residuals signal
            + res_tp : numpy.ndarray
                the indices of the residuals signal
            + time[res_tp] : numpy.ndarray
                the time signal for residuals

    Raises
    ------
    TypeError
        data shall be numpy.ndarray or list

    See also
    --------
    calc_rainflow
    rainflow_binner
    """
    rfs, res_seq, _ = calc_rainflow(
        data=data,
        time=time,
        method=rainflow_method,
        extended_output=True,
    )

    # return rfs, data[res_tp], res_tp, time[res_tp]

    means = MeanStress(
        _counts=rfs[:, 2],
        _values=rfs[:, 1],
        bin_width=mean_bin_width,
        _bin_lb=mean_bin_lower_bound,
        _bin_ub=mean_bin_upper_bound,
    )
    ranges = StressRange(
        _counts=rfs[:, 2],
        _values=2 * rfs[:, 0],
        bin_width=range_bin_width,
        _bin_lb=range_bin_lower_bound,
        _bin_ub=range_bin_upper_bound,
    )
    out_dct = rainflow_binner(
        ranges=ranges,
        _means=means,
        damage_tolerance_for_binning=damage_tolerance_for_binning,
        max_consecutive_zeros=max_consetutive_zeros,
        damage_exponent=damage_exponent,
        round_decimals=round_decimals,
        debug_mode=debug_mode,
    )

    out_dct["res_sig"] = res_seq
    if time is not None:
        out_dct["as_dur"] = time[-1] - time[0]

    return out_dct

initialise_binned_rainflow_dict

initialise_binned_rainflow_dict(
    ranges, means, nr_small_cycles, no_mean_stress=False
)

Initialises the binned rainflow dictionary.

Parameters:

Name Type Description Default
ranges StressRange

The stress range object.

required
means MeanStress

The mean stress object.

required
nr_small_cycles int

The number of small cycles.

required
no_mean_stress bool

Whether to ignore mean stress. Defaults to False.

False

Returns:

Type Description
dict

The initialised binned rainflow dictionary.

Source code in py_fatigue/cycle_count/histogram.py
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
def initialise_binned_rainflow_dict(
    ranges: StressRange,
    means: MeanStress,
    nr_small_cycles: int,
    no_mean_stress: bool = False,
) -> dict:
    """Initialises the binned rainflow dictionary.

    Parameters
    ----------
    ranges : StressRange
        The stress range object.
    means : MeanStress
        The mean stress object.
    nr_small_cycles : int
        The number of small cycles.
    no_mean_stress : bool, optional
        Whether to ignore mean stress. Defaults to False.

    Returns
    -------
    dict
        The initialised binned rainflow dictionary.
    """
    out_dct: dict[str, Union[float, list, np.ndarray]] = {}
    out_dct["nr_small_cycles"] = nr_small_cycles
    out_dct["range_bin_lower_bound"] = ranges.bin_lb
    out_dct["range_bin_width"] = ranges.bin_width
    if not no_mean_stress:
        out_dct["mean_bin_lower_bound"] = means.bin_lb
        out_dct["mean_bin_width"] = means.bin_width
    return out_dct

make_axes

make_axes(fig=None, ax=None)

Check if a figure and axes are provided, and if not, create them.

Parameters:

Name Type Description Default
fig Optional[Figure]

The figure instance, by default None

None
ax Optional[Axes]

The axes instance, by default None

None

Returns:

Type Description
tuple

The figure and axes instances

Raises:

Type Description
TypeError

If fig is not a matplotlib.figure.Figure instance

Source code in py_fatigue/utils.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def make_axes(
    fig: Optional[matplotlib.figure.Figure] = None,  # type: ignore
    ax: Optional[matplotlib.axes.Axes] = None,  # type: ignore
) -> Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]:  # type: ignore  # pragma: no cover  # pylint: disable=C0301  # noqa: E501
    """Check if a figure and axes are provided, and if not, create them.

    Parameters
    ----------
    fig : Optional[matplotlib.figure.Figure], optional
        The figure instance, by default None
    ax : Optional[matplotlib.axes.Axes], optional
        The axes instance, by default None

    Returns
    -------
    tuple
        The figure and axes instances

    Raises
    ------
    TypeError
        If fig is not a matplotlib.figure.Figure instance
    """
    if fig is None and ax is not None:
        return ax.figure, ax
    if fig is None:
        fig, axes = plt.subplots()
    else:
        if not isinstance(fig, matplotlib.figure.Figure):  # type: ignore
            raise TypeError("fig must be a matplotlib.figure.Figure instance")
        if ax is None:
            axes = fig.gca()
        else:
            axes = ax
    return fig, axes

make_histogram

make_histogram(
    mean_stress,
    stress_range,
    bins=10,
    bin_range=None,
    normed=False,
    weights=None,
)

Make a scattered-histogram plot.

Parameters:

Name Type Description Default
mean_stress (array_like, shape(n))

Input data

required
stress_range (array_like, shape(n))

Input data

required
bins int or array_like or [int, int] or [array, array]

The bin specification: * If int, the number of bins for the two dimensions (nx=ny=bins). * If array_like, the bin edges for the two dimensions (stress_range_edges=mean_stress_edges=bins). * If [int, int], the number of bins in each dimension (n_stress_range, n_mean_stress = bins). * If [array, array], the bin edges in each dimension (stress_range_edges, mean_stress_edges = bins). * A combination [int, array] or [array, int], where int is the number of bins and array is the bin edges.

10
bin_range (array_like, shape(2, 2))

The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the bins parameters): [[stress_range_min, stress_range_max], [mean_stress_min, mean_stress_max]]. All values outside of this range will be considered outliers and not tallied in the histogram.

None
normed bool

If False, returns the number of samples in each bin. If True, returns the bin density bin_count / sample_count / bin_area.

False
weights (array_like, shape(N))

An array of values w_i weighing each sample (stress_range_i, mean_stress_i). Weights are normalized to 1 if normed is True. If normed is False, the values of the returned histogram are equal to the sum of the weights belonging to the samples falling into each bin.

None

Returns:

Name Type Description
hist `np.ndarray`, shape(m,m)

Histogram matrix.

hist_edges (ArrayArray, (shape(m + 1), shape(m + 1)))

Histogram bin edges.

Source code in py_fatigue/cycle_count/histogram.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 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
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def make_histogram(
    mean_stress: np.ndarray,
    stress_range: np.ndarray,
    bins: Union[int, Sequence[int]] = 10,
    bin_range: Optional[np.ndarray] = None,
    normed: bool = False,
    weights: Optional[np.ndarray] = None,
) -> tuple:
    """
    Make a scattered-histogram plot.

    Parameters
    ----------
    mean_stress, stress_range : array_like, shape (n, )
        Input data
    bins : int or array_like or [int, int] or [array, array], optional
        The bin specification:
          * If int, the number of bins for the two dimensions (nx=ny=bins).
          * If array_like, the bin edges for the two dimensions
            (stress_range_edges=mean_stress_edges=bins).
          * If [int, int], the number of bins in each dimension
            (n_stress_range, n_mean_stress = bins).
          * If [array, array], the bin edges in each dimension
            (stress_range_edges, mean_stress_edges = bins).
          * A combination [int, array] or [array, int], where int
            is the number of bins and array is the bin edges.
    bin_range : array_like, shape(2,2), optional
        The leftmost and rightmost edges of the bins along each dimension
        (if not specified explicitly in the `bins` parameters):
        ``[[stress_range_min, stress_range_max],
        [mean_stress_min, mean_stress_max]]``. All values outside of this
        range will be considered outliers and not tallied in the histogram.
    normed : bool, optional
        If False, returns the number of samples in each bin. If True,
        returns the bin density ``bin_count / sample_count / bin_area``.
    weights : array_like, shape(N,), optional
        An array of values ``w_i`` weighing each sample
        ``(stress_range_i, mean_stress_i)``. Weights are normalized to 1
        if `normed` is True. If `normed` is False, the values of the returned
        histogram are equal to the sum of the weights belonging to the samples
        falling into each bin.

    Returns
    -------
    hist : `np.ndarray`, shape(m,m)
        Histogram matrix.
    hist_edges : ArrayArray, (shape(m+1,), shape(m+1,))
        Histogram bin edges.
    """

    if len(mean_stress) != len(stress_range):
        raise ValueError("Input arrays must be the same length")

    try:
        hist, mean_e, range_e = np.histogram2d(  # type: ignore
            mean_stress,
            stress_range,
            bins=bins,
            range=bin_range,
            normed=normed,
            weights=weights,
        )
    except TypeError as type_error:
        if "normed" in str(type_error):
            hist, mean_e, range_e = np.histogram2d(
                mean_stress,
                stress_range,
                bins=bins,
                range=bin_range,
                weights=weights,
                density=normed,
            )
    hist_bin_edges = (mean_e, range_e)
    return hist, hist_bin_edges

map_hist

map_hist(x, y, h, hist_bin_edges)

Maps the histogram to the original data.

Parameters:

Name Type Description Default
x ndarray

x-axis of the original data

required
y ndarray

y-axis of the original data

required
h ndarray

histogram

required
hist_bin_edges tuple

histogram bin edges

required

Returns:

Type Description
ndarray

mapped histogram

Source code in py_fatigue/cycle_count/histogram.py
113
114
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
142
143
144
145
146
147
148
149
150
151
152
153
154
def map_hist(
    x: np.ndarray,
    y: np.ndarray,
    h: np.ndarray,
    hist_bin_edges: tuple,
) -> np.ndarray:
    """Maps the histogram to the original data.

    Parameters
    ----------
    x : np.ndarray
        x-axis of the original data
    y : np.ndarray
        y-axis of the original data
    h : np.ndarray
        histogram
    hist_bin_edges : tuple
        histogram bin edges

    Returns
    -------
    np.ndarray
        mapped histogram
    """
    x_i = np.digitize(x, hist_bin_edges[0])
    x_i[np.where(x_i > 0)] -= 1
    y_i = np.digitize(y, hist_bin_edges[1])
    y_i[np.where(y_i > 0)] -= 1
    inds = np.ravel_multi_index(
        (x_i, y_i),
        (len(hist_bin_edges[0]) - 1, len(hist_bin_edges[1]) - 1),
        mode="clip",
    )
    vals = h.flatten()[inds]
    bads = (
        (x < hist_bin_edges[0][0])
        | (x > hist_bin_edges[0][-1])
        | (y < hist_bin_edges[1][0])
        | (y > hist_bin_edges[1][-1])
    )
    vals[bads] = np.nan
    return vals

rainflow_binner

rainflow_binner(
    ranges,
    _means,
    damage_tolerance_for_binning=0.001,
    damage_exponent=5.0,
    max_consecutive_zeros=12,
    round_decimals=4,
    debug_mode=True,
)

Binning the rainflow cycles into mean-range bins up to a certain stress range which is based on the damage tolerance index. All the cycles beyond such stress range are saved separately for accuracy reasons as "large cycles".

By default, large cycles are calculated from all the cycles accounting for more than 0.1% of the total damage and that have a discrepancy of more than 0.1% with respect to the damage that would be obtained from the bin center.

Parameters:

Name Type Description Default
ranges StressRange

The stress range object.

required
_means Optional[MeanStress]

The mean stress object. If not provided, the mean stress is set to zero.

required
damage_tolerance_for_binning float

tolerance for the damage when binning large cycles separately, by default 1e-3

0.001
damage_exponent float

exponent for the damage when binning large cycles separately, by default 5.0

5.0
max_consecutive_zeros int

maximum number of consecutive zeros before saving a cycle to large cycles array. This quantity is introduced to save storage space, by default 8

12
round_decimals int

number of decimals to round the output, by default 4

4
debug_mode bool

if True, print debug messages, by default False

True

Returns:

Name Type Description
out_dct dict

A dictionary with the following keys: - "nr_small_cycles": number of small cycles - "range_bin_lower_bound": lower bound of the range bin - "range_bin_width": width of the range bins - "mean_bin_lower_bound": lower bound of the mean bin - "mean_bin_width": width of the mean bins - "hist": histogram of the rainflow cycles - "lg_c": large cycles - "res": residuals - "res_sig": residuals sequence

See Also

make_histogram

Source code in py_fatigue/cycle_count/histogram.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
332
333
334
335
336
337
338
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
def rainflow_binner(
    ranges: StressRange,
    _means: Optional[MeanStress],
    damage_tolerance_for_binning: float = 1e-3,
    damage_exponent: float = 5.0,
    max_consecutive_zeros: int = 12,
    round_decimals: int = 4,
    debug_mode: bool = True,
) -> dict:
    """Binning the rainflow cycles into mean-range bins up to a certain
    stress range which is based on the damage tolerance index. All the
    cycles beyond such stress range are saved separately for accuracy
    reasons as "large cycles".

    By default, large cycles are calculated from all the cycles
    accounting for more than 0.1% of the total damage and that have a
    discrepancy of more than 0.1% with respect to the damage that would
    be obtained from the bin center.

    Parameters
    ----------
    ranges : StressRange
        The stress range object.
    _means : Optional[MeanStress], optional
        The mean stress object. If not provided, the mean stress is
        set to zero.
    damage_tolerance_for_binning : float, optional
        tolerance for the damage when binning large cycles
        separately, by default 1e-3
    damage_exponent : float, optional
        exponent for the damage when binning large cycles separately,
        by default 5.0
    max_consecutive_zeros : int, optional
        maximum number of consecutive zeros before saving a cycle to
        large cycles array. This quantity is introduced to save storage
        space, by default 8
    round_decimals : int, optional
        number of decimals to round the output, by default 4
    debug_mode : bool, optional
        if True, print debug messages, by default False

    Returns
    -------
    out_dct : dict
        A dictionary with the following keys:
        - "nr_small_cycles": number of small cycles
        - "range_bin_lower_bound": lower bound of the range bin
        - "range_bin_width": width of the range bins
        - "mean_bin_lower_bound": lower bound of the mean bin
        - "mean_bin_width": width of the mean bins
        - "hist": histogram of the rainflow cycles
        - "lg_c": large cycles
        - "res": residuals
        - "res_sig": residuals sequence

    See Also
    --------
    make_histogram
    """
    # 1) Type of analysis: if with mean or without mean.
    # If no mean stress is desired, the method creates a dummy array of
    # zero mean stresses.
    no_mean_stress = True
    means = MeanStress(
        ranges.counts,
        np.zeros(len(ranges.values)),
        1,
    )
    if _means is not None:
        means = _means
        no_mean_stress = False

    # 2) Removing mean-range pairs below threshold (lowest bound)
    ranges, means, nr_small_cycles = rainflow_threshold(ranges, means)
    if debug_mode:  # pragma: no cover
        # a) Full cycles
        print("\033[1mInitial values\033[0m\n--------------")
        print("count cycle", ranges.counts, "\n")
        print("mean stress", means.values, "\n")
        print("stress range", ranges.values, "\n")
        # b) Full cycles
        print("\033[1mFull cycles\033[0m\n-----------")
        # print("count full",means.counts)
        print("mean full", means.full, "\n")
        print("range full", ranges.full, "\n")
        print("len mean full", len(means.full))
        print("len range full", len(ranges.full), "\n")
        # c) Residuals
        print("\033[1mResiduals\033[0m\n---------")
        print("Mean :", means.half, "\n")
        print("Range:", ranges.half, "\n")
        print("\033[1mLoop over rainflow-counted data\033[0m")
        print("-------------------------------")
    # 3) Histogram bin edges (all these attributes are in FatigueStress)
    # 3.a) Mean - lower bound
    # 3.b) Mean - upper bound
    # 3.c) Mean - edges
    # 3.d) Range - upper bound
    # 3.e) Range - edges

    # 4) Histogram
    # _, hist_bin_edges = make_histogram(
    #     means.full,
    #     ranges.full,
    #     bins=(means.bin_edges, ranges.bin_edges)
    # )

    # # Test on the edges output from numpy.histogram
    # np.testing.assert_array_equal(mean_bin_edges, hist_bin_edges[0])
    # np.testing.assert_array_equal(range_bin_edges, hist_bin_edges[1])

    # 5) Indices of the bins for mean and range using numpy.digitize, ref.
    # https://numpy.org/doc/stable/reference/generated/numpy.digitize.html
    # -------------------------------------------------------------------------

    binned_sorted = sorted(
        zip(
            means.bins_idx,
            ranges.bins_idx,
            means.binned_values,
            ranges.binned_values,
            means.full,
            ranges.full,
        ),
        reverse=False,
    )

    # 6) Initialising the output dictionary
    out_dct = initialise_binned_rainflow_dict(
        ranges, means, nr_small_cycles, no_mean_stress
    )
    if len(ranges.full) == 0:
        return _build_binned_dict(
            ranges, means, [], [], round_decimals, no_mean_stress, out_dct
        )
    # 6) Reference damage for large cycles
    max_damage = max(ranges.full) ** damage_exponent
    # 7) Initialising output variabies: large cycles and histogram
    lg_c = []
    # the_hist: List[List[int]] = [[] for _ in range(len(means.bin_centers))]
    _hist = np.zeros((len(means.bin_centers), len(ranges.bin_centers)))
    i_ran_1 = binned_sorted[0][1]
    for en, (i_mea, i_ran, b_mea, b_ran, mea, ran) in enumerate(binned_sorted):
        # print(i_ran, i_ran_1)
        if debug_mode:  # pragma: no cover
            print("---------------------------------")
            print(f"\033[96mEnum - {en}\033[0m")
            print(f"\033[96mID   - Mean: {i_mea}, Range: {i_ran}\033[0m")
            print(f"\033[96mBin  - Mean: {b_mea}, Range: {b_ran}\033[0m")
            print(f"\033[96mReal - Mean: {mea}, Range: {ran}\033[0m")
        # 9) Large cycles identification
        ref_damage = ran**damage_exponent
        approx_damage = b_ran**damage_exponent
        if (
            ref_damage / max_damage > damage_tolerance_for_binning
            and np.abs(ref_damage - approx_damage) / ref_damage
            > damage_tolerance_for_binning
        ) or (i_ran - i_ran_1 > max_consecutive_zeros):
            lg_c.append([mea, ran])
            if debug_mode:  # pragma: no cover
                print(
                    f"\033[92mRea: ({np.round(mea, 3)},"
                    + f" {np.round(ran, 3)}),"
                    + f" Bin: ({np.round(b_mea, 3)},"
                    + f" {np.round(b_ran, 3)}"
                    + ")\033[0m Large Cycle"
                )
            continue
        # 10) Histogram identification
        if debug_mode:  # pragma: no cover
            print(
                f"\033[92mRea: ({np.round(mea, 3)},"
                + f" {np.round(ran, 3)}),"
                + f" Bin: ({np.round(b_mea, 3)},"
                + f" {np.round(b_ran, 3)}"
                + ")\033[0m Histogram Cycle"
            )
        _hist[i_mea][i_ran] += 1
        i_ran_1 = i_ran
    # 11) Histogram binning
    the_hist: List[List[float]] = []
    for hst in _hist:
        the_hist.append(np.trim_zeros(hst, trim="b").tolist())
    return _build_binned_dict(
        ranges, means, lg_c, the_hist, round_decimals, no_mean_stress, out_dct
    )

rainflow_threshold

rainflow_threshold(ranges, means)

Removes the rainflow cycles below threshold for a given stress range and mean stress.

Parameters:

Name Type Description Default
ranges StressRange

The stress range object.

required
means MeanStress

The mean stress object.

required

Returns:

Type Description
tuple

The ranges and means above threshold, as well as small cycles.

Source code in py_fatigue/cycle_count/histogram.py
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
def rainflow_threshold(ranges: StressRange, means: MeanStress) -> tuple:
    """Removes the rainflow cycles below threshold for a given
    stress range and mean stress.

    Parameters
    ----------
    ranges : StressRange
        The stress range object.
    means : MeanStress
        The mean stress object.

    Returns
    -------
    tuple
        The ranges and means above threshold, as well as small cycles.
    """
    ranges_gt_lb_idx = np.where(ranges.values >= ranges.bin_lb)[0]
    nr_small_cycles = len(ranges.values) - len(ranges_gt_lb_idx)
    means.counts = means.counts[ranges_gt_lb_idx]
    means.values = means.values[ranges_gt_lb_idx]
    ranges.counts = ranges.counts[ranges_gt_lb_idx]
    ranges.values = ranges.values[ranges_gt_lb_idx]
    return ranges, means, nr_small_cycles

xy_hist2d

xy_hist2d(
    x,
    y,
    mode="mountain",
    bins=10,
    bin_range=None,
    normed=False,
    weights=None,
    fig=None,
    ax=None,
    dens_func=None,
    **kwargs
)

Make a scattered-histogram plot.

Parameters:

Name Type Description Default
x (array_like, shape(n))

Input data

required
y (array_like, shape(n))

Input data

required
marker_size int

Size of the markers

required
mode str

Possible values are: - None : The points are plotted as one scatter object, in the order in-which they are specified at input. - 'mountain' : The points are sorted/plotted in the order of the number of points in their 'bin'. This means that points in the highest density will be plotted on-top of others. This cleans-up the edges a bit, the points near the edges will overlap. - 'valley' : The reverse order of 'mountain'. The low density bins are plotted on top of the high ones.

'mountain'
bins int or array_like or [int, int] or [array, array]

The bin specification: - If int, the number of bins for the two dimensions (nx=ny=bins). - If array_like, the bin edges for the two dimensions (x_edges = y_edges = bins). - If [int, int], the number of bins in each dimension (n_x, n_y = bins). - If [array, array], the bin edges in each dimension (x_edges, y_edges = bins). - A combination [int, array] or [array, int], where int is the number of bins and array is the bin edges.

10
bin_range (array_like, shape(2, 2))

The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the bins parameters): [[x_min, x_max], [y_min, y_max]]. All values outside of this range will be considered outliers and not tallied in the histogram.

None
normed bool

If False, returns the number of samples in each bin. If True, returns the bin density bin_count / sample_count / bin_area.

False
weights (array_like, shape(N))

An array of values w_i weighing each sample (y_i, x_i). Weights are normalized to 1 if normed is True. If normed is False, the values of the returned histogram are equal to the sum of the weights belonging to the samples falling into each bin.

None
fig a figure instance to add.
None
ax an axes instance to plot into.
None
dens_func function or callable (default: None)

A function that modifies (inputs and returns) the dens values (e.g., np.log10). The default is to not modify the values.

None
x_label str

Label for the x-axis

required
y_label str

Label for the y-axis

required
cbar_label str

Label for the colorbar

required
kwargs these are all passed on to scatter.
{}

Returns:

Type Description
figure, paths : (

~matplotlib.figure.Figure, ~matplotlib.collections.PathCollection

)

The figure with scatter instance.

Source code in py_fatigue/cycle_count/histogram.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def xy_hist2d(
    x: FloatArray,
    y: FloatArray,
    mode: str = "mountain",
    bins: Union[int, Sequence[int]] = 10,
    bin_range: Optional[FloatArray] = None,
    normed: bool = False,
    weights: Optional[FloatArray] = None,  # np.histogram2d args
    fig: Optional[matplotlib.figure.Figure] = None,
    ax: Optional[matplotlib.axes.Axes] = None,
    dens_func: Optional[Callable] = None,
    **kwargs: dict,
) -> tuple:
    """
    Make a scattered-histogram plot.

    Parameters
    ----------
    x, y : array_like, shape (n, )
        Input data
    marker_size : int
        Size of the markers
    mode: [None | 'mountain' | 'valley' | 'clip']
        Possible values are:
            - None : The points are plotted as one scatter object, in the
                order in-which they are specified at input.
            - 'mountain' : The points are sorted/plotted in the order of
                the number of points in their 'bin'. This means that points
                in the highest density will be plotted on-top of others. This
                cleans-up the edges a bit, the points near the edges will
                overlap.
            - 'valley' : The reverse order of 'mountain'. The low density
                bins are plotted on top of the high ones.

    bins : int or array_like or [int, int] or [array, array], optional
        The bin specification:
            - If int, the number of bins for the two dimensions (nx=ny=bins).
            - If array_like, the bin edges for the two dimensions
                (x_edges = y_edges = bins).
            - If [int, int], the number of bins in each dimension
                (n_x, n_y = bins).
            - If [array, array], the bin edges in each dimension
                (x_edges, y_edges = bins).
            - A combination [int, array] or [array, int], where int
                is the number of bins and array is the bin edges.

    bin_range : array_like, shape(2,2), optional
        The leftmost and rightmost edges of the bins along each dimension
        (if not specified explicitly in the `bins` parameters):
        ``[[x_min, x_max], [y_min, y_max]]``. \
        All values outside of this range will be considered outliers
        and not tallied in the histogram.
    normed : bool, optional
        If False, returns the number of samples in each bin. If True,
        returns the bin density ``bin_count / sample_count / bin_area``.
    weights : array_like, shape(N,), optional
        An array of values ``w_i`` weighing each sample ``(y_i, x_i)``.
        Weights are normalized to 1 if `normed` is True. If `normed` is
        False, the values of the returned histogram are equal to the sum of
        the weights belonging to the samples falling into each bin.
    fig : a figure instance to add.
    ax : an axes instance to plot into.
    dens_func : function or callable (default: None)
        A function that modifies (inputs and returns) the dens
        values (e.g., np.log10). The default is to not modify the
        values.
    x_label : str, optional
        Label for the x-axis
    y_label : str, optional
        Label for the y-axis
    cbar_label : str, optional
        Label for the colorbar
    kwargs : these are all passed on to scatter.

    Returns
    -------
    figure, paths : (
        `~matplotlib.figure.Figure`,
        `~matplotlib.collections.PathCollection`
    )
        The figure with scatter instance.
    """
    fig, axes = make_axes(fig, ax)
    hist, hist_bin_edges = make_histogram(
        x, y, bins=bins, bin_range=bin_range, normed=normed, weights=weights
    )
    dens = map_hist(x, y, hist, hist_bin_edges)
    if dens_func is not None:
        dens = dens_func(dens)
    # iorder = np.empty(0, dtype=float)
    if mode == "mountain":
        iorder = np.argsort(dens)
    elif mode == "valley":
        iorder = np.argsort(dens)[::-1]
    else:
        raise ValueError("mode must be one of [None, 'mountain', 'valley']")
    x = x[iorder]
    y = y[iorder]
    dens = dens[iorder]
    im = axes.scatter(
        x,
        y,
        # edgecolors="#CCC",
        # linewidths=0.5,
        c=dens,
        **kwargs,  # type: ignore
    )
    return fig, axes, im