Skip to content

cycle_count

Overview

Build a CycleCount from a stress history or existing cycles. Combine counts and resolve residuals before calculating damage.

py_fatigue.cycle_count.cycle_count

The py_fatigue.cycle_count.cycle_count module collects all functions related to cycle-counting(s) definition. The main class is CycleCount.

Classes

CycleCount dataclass

Bases: PlotMixin

Cycle-counting class.

The class heavily relies on the py_fatigue.cycle_count.rainflow and py_fatigue.cycle_count.histogram modules.

Create a count from existing rainflow cycles, a stress history, or a timeseries from an external source:

  • [from_rainflow] [py_fatigue.cycle_count.cycle_count.CycleCount.from_rainflow]
  • [from_timeseries] [py_fatigue.cycle_count.cycle_count.CycleCount.from_timeseries]
  • [from_sep005] [py_fatigue.cycle_count.cycle_count.CycleCount.from_sep005]
  • [from_pyexsi] [py_fatigue.cycle_count.cycle_count.CycleCount.from_pyexsi]
Source code in py_fatigue/cycle_count/cycle_count.py
 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
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 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
 512
 513
 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
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
@dataclass(repr=False)
class CycleCount(PlotMixin):
    """Cycle-counting class.

    The class heavily relies on the [`py_fatigue.cycle_count.rainflow`][] and
    [`py_fatigue.cycle_count.histogram`][] modules.

    Create a count from existing rainflow cycles, a stress history, or
    a timeseries from an external source:

    - [`from_rainflow`]
      [py_fatigue.cycle_count.cycle_count.CycleCount.from_rainflow]
    - [`from_timeseries`]
      [py_fatigue.cycle_count.cycle_count.CycleCount.from_timeseries]
    - [`from_sep005`]
      [py_fatigue.cycle_count.cycle_count.CycleCount.from_sep005]
    - [`from_pyexsi`]
      [py_fatigue.cycle_count.cycle_count.CycleCount.from_pyexsi]
    """

    # pylint: disable=too-many-instance-attributes
    # pylint: disable=too-many-public-methods
    # pylint: disable=too-many-arguments
    # pylint: disable=too-many-positional-arguments
    # 16 is reasonable in this case.

    count_cycle: np.ndarray[Any, np.dtype[np.float64]]
    stress_range: np.ndarray[Any, np.dtype[np.float32]]
    mean_stress: np.ndarray[Any, np.dtype[np.float64]]
    timestamp: Union[ADT, NDT] = ADT(dt.datetime.now(dt.timezone.utc))
    unit: str = "MPa"
    range_bin_lower_bound: float = 0.2
    range_bin_width: float = 0.05
    _mean_bin_lower_bound: Optional[float] = None
    mean_bin_width: float = 10
    nr_small_cycles: float = 0
    residuals_sequence: np.ndarray[Any, Any] = field(
        default_factory=lambda: np.empty(0)
    )
    _min_max_sequence: np.ndarray[Any, Any] = field(
        default_factory=lambda: np.empty(0)
    )
    lffd_solved: bool = False
    mean_stress_corrected: str = "No"
    stress_concentration_factor: float = 1.0
    name: Optional[str] = None
    _time_sequence: Optional[np.ndarray] = None

    def __post_init__(self):
        if not np.isnan(np.min(self.mean_stress)):
            if self._mean_bin_lower_bound is None:
                self._mean_bin_lower_bound = (
                    round(min(self.mean_stress) / self.mean_bin_width)
                    * self.mean_bin_width
                    - self.mean_bin_width / 2
                )
            if self.time_sequence is None:
                self.time_sequence = np.asarray(self.timestamp)

    @classmethod
    def from_rainflow(
        cls,
        data: dict,
        timestamp: Union[ADT, NDT] = ADT(dt.datetime.now(dt.timezone.utc)),
        round_decimals: int = 4,
        name: Optional[str] = None,
        mean_stress_corrected: str = "No",
        lffd_solved: bool = False,
        unit: str = "MPa",
    ) -> "CycleCount":
        """Create a cycle-counting object from rainflow cycles.

        Parameters
        ----------
        *args
            Positional arguments passed to `py_fatigue.rainflow.rainflow`.
        **kwargs
            Keyword arguments passed to `py_fatigue.rainflow.rainflow`.

        Returns
        -------
        CycleCount
            A cycle-counting object.
        """
        df = _build_input_data_from_json(
            data,
            timestamp,
            round_decimals,
            name,
            mean_stress_corrected,
            lffd_solved,
        )
        df["unit"] = unit
        return cls(**df)

    @classmethod
    def from_timeseries(
        cls,
        data: np.ndarray,
        time: Optional[np.ndarray] = None,
        timestamp: Union[ADT, NDT] = ADT(dt.datetime.now(dt.timezone.utc)),
        range_bin_lower_bound: float = 0.2,
        range_bin_width: float = 0.05,
        mean_bin_lower_bound: Optional[float] = None,
        mean_bin_width: float = 10,
        name: Optional[str] = None,
        unit: str = "MPa",
        rainflow_method: str = "astm",
    ) -> "CycleCount":
        """Generate a cycle-count from a timeseries.

        Parameters
        ----------
        *args
            Positional arguments passed to `_build_input_data_from_json`.
        **kwargs
            Keyword arguments passed to `_build_input_data_from_json`.
        """
        cc = calc_rainflow(
            data=data, time=time, method=rainflow_method, extended_output=True
        )
        if cc[0].size == 0:
            raise ValueError("The stress history contains no rainflow cycles.")
        stress_range = 2 * cc[0][:, 0]
        mean_stress = cc[0][:, 1]
        count_cycle = cc[0][:, 2]
        residuals_sequence = cc[1]
        df = {
            "count_cycle": count_cycle,
            "mean_stress": mean_stress,
            "stress_range": stress_range,
            "timestamp": timestamp,
            "range_bin_lower_bound": range_bin_lower_bound,
            "range_bin_width": range_bin_width,
            "_mean_bin_lower_bound": mean_bin_lower_bound,
            "mean_bin_width": mean_bin_width,
            "residuals_sequence": residuals_sequence,
            "name": name,
            "unit": unit,
        }
        return cls(**df)

    @classmethod
    def from_sep005(
        cls,
        signals: Mapping[str, Any] | Sequence[Mapping[str, Any]],
        **kwargs: Any,
    ) -> CycleCount | list[CycleCount]:
        """Rainflow-count stress histories in the SDyPy SEP005 format.

        Parameters
        ----------
        signals : mapping or sequence of mappings
            Each record contains `data` (samples or rows of channels) and
            `fs` in Hz or an increasing `time` vector in seconds. An empty
            or absent `quantity` is treated as stress, as are `"s"` and
            `"stress"`. Supply `unit_str` in Pa, kPa, MPa or GPa. An empty
            or absent unit means Pa. Use `channel_name` and `unit_str`
            lists for per-channel metadata, or strings shared by all rows.
            Supply an ISO 8601 `start_timestamp`, or include a matching
            `start_timestamp_format` for a custom date-time string.
        **kwargs
            Rainflow options passed to `from_timeseries`. Bin settings are
            in MPa. The `name` and `timestamp` options override metadata.

        Returns
        -------
        CycleCount or list of CycleCount
            One count for a 1D record, or a flat list in input order for
            2D data or a sequence of records. All counts use MPa.

        Examples
        --------
        >>> record = {"data": [0, 2e6, 0, 4e6, 0], "fs": 20, "quantity": "s"}
        >>> CycleCount.from_sep005(record).unit
        'MPa'
        """
        if "unit" in kwargs or "time" in kwargs:
            raise TypeError(
                "Specify units and sample times in the SEP005 data."
            )
        if not isinstance(signals, Mapping):
            counts = []
            for signal in signals:
                if not isinstance(signal, Mapping):
                    raise TypeError("Each SEP005 signal must be a mapping.")
                result = cls.from_sep005(signal, **kwargs)
                counts.extend(result if isinstance(result, list) else [result])
            return counts

        if signals.get("quantity") not in (None, "", "s", "stress"):
            raise ValueError("The SEP005 quantity must be stress ('s').")
        data = np.asarray(signals.get("data"))
        if (
            data.ndim not in (1, 2)
            or not data.size
            or data.dtype.kind not in "fiu"
        ):
            raise ValueError("SEP005 data must contain real stress samples.")
        channels = np.atleast_2d(data)
        time = sep005_sample_times(signals, channels.shape[1])

        units = signals.get("unit_str")
        names = signals.get("channel_name")
        if not isinstance(units, (list, tuple)):
            units = [units] * len(channels)
        if not isinstance(names, (list, tuple)):
            names = [names or signals.get("name")] * len(channels)
        if len(units) != len(channels) or len(names) != len(channels):
            raise ValueError("Supply one unit and name per SEP005 channel.")

        if (
            "timestamp" not in kwargs
            and signals.get("start_timestamp") is not None
        ):
            kwargs["timestamp"] = sep005_start_timestamp(signals)

        to_mpa = {
            None: 1e-6,
            "": 1e-6,
            "Pa": 1e-6,
            "kPa": 1e-3,
            "MPa": 1.0,
            "GPa": 1e3,
        }
        counts = []
        for samples, unit, name in zip(channels, units, names):
            if not isinstance(unit, (str, type(None))) or unit not in to_mpa:
                raise ValueError(
                    "SEP005 stress units must be Pa, kPa, MPa or GPa."
                )
            if name is not None and not isinstance(name, str):
                raise TypeError("SEP005 channel names must be strings.")
            stress = samples.astype(float, copy=False) * to_mpa[unit]
            if not np.all(np.isfinite(stress)):
                raise ValueError("SEP005 stress samples must be finite.")
            options = {"name": name, **kwargs}
            counts.append(cls.from_timeseries(stress, time=time, **options))
        return counts[0] if data.ndim == 1 else counts

    @classmethod
    def from_pyexsi(
        cls, data: ArrayLike, *, fs: float, unit: str, **kwargs: Any
    ) -> CycleCount:
        """Rainflow-count a stress signal generated with pyExSi.

        Parameters
        ----------
        data : array-like
            One-dimensional stress samples. When the generator represents
            acceleration or force, convert it to stress before calling.
        fs : float
            Sampling frequency in Hz used to generate the signal.
        unit : str
            Stress unit of the samples (Pa, kPa, MPa or GPa).
        **kwargs
            Options passed to `from_timeseries`, such as `name` or bin widths.

        Returns
        -------
        CycleCount
            Rainflow counts with stress ranges and means in MPa.

        Examples
        --------
        >>> CycleCount.from_pyexsi([0, 2, 0, 4, 0], fs=20, unit="MPa").unit
        'MPa'
        """
        samples = np.asarray(data)
        if samples.ndim != 1 or not unit:
            raise ValueError("Supply one stress signal and its stress unit.")
        return cast(
            CycleCount,
            cls.from_sep005(
                {"data": samples, "fs": fs, "unit_str": unit}, **kwargs
            ),
        )

    # ! Instance managed attributes
    @property
    def mean_bin_lower_bound(self) -> float:
        """The stress values.

        Returns
        -------
        values : np.ndarray
        """
        return cast(float, self._mean_bin_lower_bound)

    @mean_bin_lower_bound.setter
    def mean_bin_lower_bound(self, value: float) -> None:
        self._mean_bin_lower_bound = value

    @property
    def time_sequence(self) -> np.ndarray:
        """The sequence of timestamps possibly added.

        Returns
        -------
        time_sequence : np.ndarray
        """
        if self._time_sequence is None:
            return np.asarray([self.timestamp])
        return self._time_sequence

    @property
    def min_max_sequence(self) -> np.ndarray:
        """The minimum and maximum of the residuals
        (half-cycles) sequence.

        Returns
        -------
        np.ndarray, shape=(2, )
            The minimum and maximum of the half-cycles sequence.
        """
        if self.residuals_sequence is None:
            return self._min_max_sequence
        if (
            len(self._min_max_sequence) == 0
            and len(self.residuals_sequence) >= 2
        ):
            return np.hstack(
                [
                    min(self.residuals_sequence),
                    max(self.residuals_sequence),
                ]
            )
        return self._min_max_sequence

    @property
    def residuals(self) -> np.ndarray:
        """Extracts the residuals, also known as half
        cycles, from mean-range couples of the cycle-counting object.

        Returns
        -------
        np.ndarray, shape (n, 2)
            Array containing mean stresses and stress ranges of the residuals.
            - residual_mean_stresses = array[:, 0]
            - residual_stress_ranges = array[:, 1]
        """
        _, idx = pfu.split_full_cycles_and_residuals(self.count_cycle)
        return np.asarray([self.mean_stress[idx], self.stress_range[idx]]).T

    @property
    def full_cycles(self) -> np.ndarray:
        """Extracts the full cycles only from mean-range couples.

        Returns
        -------
        np.ndarray, shape (n, 2)
            Array containing mean stresses and stress ranges of the full
            cycles.
            - full_cycles_mean_stresses = array[:, 0]
            - full_cycles_stress_ranges = array[:, 1]
        """
        full_mean = pfu.calc_full_cycles(self.mean_stress, self.count_cycle)
        full_range = pfu.calc_full_cycles(self.stress_range, self.count_cycle)
        return np.asarray([full_mean, full_range]).T

    @property
    def half_cycles(self) -> np.ndarray:
        """Symlink to residuals

        See also
        --------
        [`residuals`][py_fatigue.cycle_count.cycle_count.CycleCount.residuals]
        """
        return self.residuals

    @property
    def mean_bin_upper_bound(self) -> float:
        """Returns the upper bound of the mean stress bin edges.

        Returns
        -------
        float
            The upper bound of the mean stress bins (highest mean bin edge).
        """
        return pfu.bin_upper_bound(
            self.mean_bin_lower_bound,
            self.mean_bin_width,
            max(self.full_cycles[:, 0]),
        )

    @property
    def range_bin_upper_bound(self) -> float:
        """Returns the upper bound of the stress range bins.

        Returns
        -------
        float
            The upper bound of the stress range bins (highest range bin edge).
        """
        return pfu.bin_upper_bound(
            self.range_bin_lower_bound,
            self.range_bin_width,
            max(self.full_cycles[:, 1]),
        )

    @property
    def bin_centers(self) -> tuple:
        """Extracts the bin centers from the cycle-counting object.

        Returns
        -------
        tuple
            Tuple containing mean stresses and stress ranges of the bin
            centers.
            - bin_centers_mean_stresses = tuple[0]
            - bin_centers_stress_ranges = tuple[1]
        """
        mean_bin_centers = (
            pfu.calc_bin_edges(
                self.mean_bin_lower_bound,
                self.mean_bin_upper_bound,
                self.mean_bin_width,
            )[:-1]
            + self.mean_bin_width / 2
        )

        range_bin_centers = (
            pfu.calc_bin_edges(
                self.range_bin_lower_bound,
                self.range_bin_upper_bound,
                self.range_bin_width,
            )[:-1]
            + self.range_bin_width / 2
        )
        return mean_bin_centers, range_bin_centers

    @property
    def bin_edges(self) -> tuple:
        """Extracts the bin edges from the cycle-counting object.

        Returns
        -------
        ht.tuple
            Tuple containing mean stresses and stress ranges of the bin edges.
            - bin_edges_mean_stresses = tuple[0]
            - bin_edges_stress_ranges = tuple[1]
        """
        mean_bin_edges = pfu.calc_bin_edges(
            self.mean_bin_lower_bound,
            self.mean_bin_upper_bound,
            self.mean_bin_width,
        )

        range_bin_edges = pfu.calc_bin_edges(
            self.range_bin_lower_bound,
            self.range_bin_upper_bound,
            self.range_bin_width,
        )
        return mean_bin_edges, range_bin_edges

    @property
    def stress_amplitude(self) -> np.ndarray:
        """Extracts the stress amplitude from the cycle-counting object.

        Returns
        -------
        np.ndarray
            Array containing the stress amplitude.
        """
        return self.stress_range / 2

    @property
    def min_stress(self) -> np.ndarray:
        """Extracts the min stress from the cycle-counting object.

        Returns
        -------
        np.ndarray
            Array containing the min stresses.
        """
        return self.mean_stress - self.stress_amplitude

    @property
    def max_stress(self) -> np.ndarray:
        """Extracts the max stress from the cycle-counting object.

        Returns
        -------
        np.ndarray
            Array containing the max stresses.
        """
        return self.mean_stress + self.stress_amplitude

    @property
    def statistical_moments(self) -> tuple[float, float, float]:
        """Calculate the spectral moments from the cycle-counting object.

        Returns
        -------
        tuple[float, float, float]
            Tuple containing the spectral moments.
            - mean = tuple[0]
            - coefficient of variance = tuple[1]
            - skewness = tuple[2]
        """
        stress_range = np.hstack(
            [self.half_cycles[:, 1], self.full_cycles[:, 1]]
        )
        m_1 = np.mean(stress_range)
        std_dev = np.sqrt(np.mean((stress_range - np.mean(stress_range)) ** 2))
        m_2 = std_dev / m_1
        m_3 = np.mean((stress_range - np.mean(stress_range)) ** 3) / (m_1**3)

        return m_1, m_2, m_3

    # ! Representations
    def as_dict(
        self,
        damage_tolerance_for_binning: float = 0.001,
        damage_exponent: float = 5.0,
        round_decimals: int = 4,
        max_consecutive_zeros: int = 32,
        legacy_export: bool = False,
        debug_mode=False,
    ) -> dict:
        """Convert the cycle-counting object to a dictionary.

        Parameters
        ----------
        damage_tolerance_for_binning : float, optional
            Tolerance for large-cycles calculation when binning,
            by default 0.001
        damage_exponent : float, optional
            SN curve exponent used to define large cycles. Higher means more
            conservative, 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 after comma, by default 4

        Returns
        -------
        dict
            Dictionary containing the following keys:
            - "hist"
            - "range_bin_lower_bound"
            - "range_bin_width"
            - "mean_bin_lower_bound"
            - "mean_bin_width"
            - "nr_small_cycles"
            - "res_sig"
            - "res"
            - "lg_c"

        See also
        --------
        [`rainflow_binner`][py_fatigue.cycle_count.histogram.rainflow_binner]
        """
        stress_ranges = StressRange(
            _counts=self.count_cycle,
            _values=self.stress_range,
            bin_width=self.range_bin_width,
            _bin_lb=self.range_bin_lower_bound,
        )

        mean_stresses = MeanStress(
            _counts=self.count_cycle,
            _values=self.mean_stress,
            bin_width=self.mean_bin_width,
            _bin_lb=self.mean_bin_lower_bound,
        )

        output_dict = ht.rainflow_binner(
            stress_ranges,
            mean_stresses if not legacy_export else None,
            damage_tolerance_for_binning=damage_tolerance_for_binning,
            damage_exponent=damage_exponent,
            max_consecutive_zeros=max_consecutive_zeros,
            round_decimals=round_decimals,
            debug_mode=debug_mode,
        )
        output_dict["res_sig"] = np.asarray(
            np.round(self.residuals_sequence, round_decimals)
        ).tolist()
        return output_dict

    def summary(self) -> pd.DataFrame:
        """
        Summary Dataframe of the most important properties of the cycle-counting
        object.

        Returns
        -------
        pd.DataFrame
        """

        df = pd.DataFrame()
        df["Cycle counting object"] = [
            f"largest full stress range, {self.unit}",
            f"largest stress range, {self.unit}",
            "number of full cycles",
            "number of residuals",
            "number of small cycles",
            "stress concentration factor",
            "residuals resolved",
            "mean stress-corrected",
        ]

        df[self.name] = [
            (
                max(self.full_cycles[:, 1])
                if max(self.count_cycle) > 0.5
                and max(self.full_cycles[:, 1]) > self.range_bin_lower_bound
                else None
            ),
            max(self.stress_range),
            int(sum(self.count_cycle) - int(len(self.residuals[:, 1])) / 2),
            int(len(self.residuals[:, 1])),
            int(self.nr_small_cycles),
            (
                "N/A"
                if self.stress_concentration_factor == 1
                else self.stress_concentration_factor
            ),
            bool(self.lffd_solved),
            self.mean_stress_corrected,
        ]
        df = df.set_index("Cycle counting object")

        return df

    def _repr_html_(self) -> str:  # pragma: no cover
        """HTML representation of the cycle-counting object.

        Returns
        -------
        str
        """

        return self.summary()._repr_html_()  # pylint: disable=protected-access

    def __str__(self) -> str:
        """String representation of the cycle-counting object.

        Returns
        -------
        str
        """
        strng = f"CC_{self.name}"
        if len(self.time_sequence) == 1:
            strng = "".join(
                (
                    f"CC_{self.name} (",
                    f"{self.timestamp.strftime('%d %b %Y, %H:%M')} - ",
                    "",
                )
            )
        if len(self.time_sequence) > 1:
            strng = "".join(
                (
                    f"CC_ {self.name} (from ",
                    f"{self.time_sequence[0].strftime('%d %b %Y, %H:%M')} to ",
                    f"{self.time_sequence[-1].strftime('%d %b %Y, %H:%M')})",
                )
            )
        return str(strng)

    def to_df(self) -> pd.DataFrame:  # pragma: no cover
        """
        Represent the [`CycleCount`]
        [py_fatigue.cycle_count.cycle_count.CycleCount] instance as a pandas
        dataframe.

        Returns
        -------
        pandas.DataFrame
            dataframe containing relevant fatigue information
        """

        df = pd.DataFrame.from_dict(
            {
                "count_cycle": self.count_cycle,
                "mean_stress": self.mean_stress,
                "stress_range": self.stress_range,
            }
        )
        df._metadata = {
            "name": self.name,
            "timestamp": self.timestamp,
            "time_sequence": self.time_sequence,
            "residuals_sequence": self.residuals_sequence,
            "mean_stress_corrected": self.mean_stress_corrected,
            "stress_concentration_factor": self.stress_concentration_factor,
            "nr_small_cycles": self.nr_small_cycles,
            "lffd_solved": self.lffd_solved,
            "unit": self.unit,
        }

        return df

    # ! Operators
    def __eq__(self, other: object) -> bool:
        """Equality operation for [`CycleCount`]
        [py_fatigue.cycle_count.cycle_count.CycleCount] instances.

        Parameters
        ----------
        other : object
            object to compare to

        Returns
        -------
        bool
            True if the objects are equal, False otherwise
        """
        if not isinstance(other, CycleCount):
            return False

        return pfu.compare(self.__dict__, other.__dict__)

    def __add__(  # fgh - noqa: _C901_
        self, other: "CycleCount"
    ) -> "CycleCount":
        """Sum operation for [`CycleCount`]
        [py_fatigue.cycle_count.cycle_count.CycleCount] instances.

        Parameters
        ----------
        other : Union[CycleCount, None]
            CycleCount object to be added to the current object.

        Returns
        -------
        CycleCount
            Summed cycle-count object.

        Raises
        ------
        TypeError
            Trying to add a non-CycleCount object.
        TypeError
            Trying to add a CycleCount object with different names.
        ValueError
            Timestamps must be defined for CycleCount sum.
        UserWarning
            Different bin widths.
        TypeError
            Timestamps must be sorted ascending.
        UserWarning
            Adding-up instances having different stress concentration factors.
        TypeError
            residuals_sequence is not iterable.
        UserWarning
            No residuals_sequence attribute found.
        """

        # Running initial checks
        if not _cycle_count_add_checks(self, other):
            return self

        # Performing actual sum
        # added_counts = np.hstack([self.count_cycle, other.count_cycle])
        # added_range = np.hstack([self.stress_range, other.stress_range])
        # added_mean = np.hstack([self.mean_stress, other.mean_stress])
        (
            added_mean_bin_lower_bound,
            added_mean_bin_width,
            added_range_bin_lower_bound,
            added_range_bin_width,
        ) = _handling_different_bins_in_sum(self, other)

        # added_nr_small_cycles = self.nr_small_cycles + other.nr_small_cycles
        # added_timestamp = np.hstack([self.timestamp, other.timestamp])
        added_scf = np.average(
            [
                self.stress_concentration_factor,
                other.stress_concentration_factor,
            ]
        )
        # added_as_duration = self.as_duration + other.as_duration
        # ? Residuals sequence management
        # 1) Residuals sequence is defined in both self and other
        if hasattr(self, "residuals_sequence") and hasattr(
            other, "residuals_sequence"
        ):
            # 1a) Residuals sequence is ok in both self and other
            if isinstance(self.residuals_sequence, Iterable) and isinstance(
                other.residuals_sequence, Iterable
            ):
                added_res_seq = np.hstack(
                    [self.residuals_sequence, other.residuals_sequence]
                )
                added_min_max = np.hstack(
                    [self.min_max_sequence, other.min_max_sequence]
                )
            # 1b) Residuals sequence is ok in self, but not in other
            elif isinstance(
                self.residuals_sequence, Iterable
            ) and not isinstance(other.residuals_sequence, Iterable):
                w_msg = "".join(
                    (
                        f"No residuals_sequence found on {TermColors.CRED}",
                        f"{other.timestamp.strftime('%d %B %Y, %H:%M')}",
                        f"{TermColors.CYELLOW2}.",
                    )
                )
                warnings.warn(w_msg, UserWarning)
                added_res_seq = self.residuals_sequence
                added_min_max = self.min_max_sequence
            # 1c) Residuals sequence is ok in other, but not in self
            elif not isinstance(
                self.residuals_sequence, Iterable
            ) and isinstance(other.residuals_sequence, Iterable):
                w_msg = "".join(
                    (
                        f"No residuals_sequence found on {TermColors.CRED}",
                        f"{self.timestamp.strftime('%d %B %Y, %H:%M')}",
                        f"{TermColors.CYELLOW2}.",
                    )
                )
                warnings.warn(w_msg, UserWarning)
                added_res_seq = other.residuals_sequence
                added_min_max = other.min_max_sequence
            # 1d) Residuals sequence is neither defined in self nor in other
            else:
                w_msg = "No residuals_sequence attribute found."
                warnings.warn(w_msg, UserWarning)
                added_res_seq = np.empty(0)
                added_min_max = np.empty(0)
        # 2) Residuals sequence is defined in self but not in other
        elif hasattr(self, "residuals_sequence") and not hasattr(
            other, "residuals_sequence"
        ):
            w_msg = "".join(
                (
                    f"No residuals_sequence found on {TermColors.CRED}",
                    f"{other.timestamp.strftime('%d %B %Y, %H:%M')}",
                    f"{TermColors.CYELLOW2}.",
                )
            )
            warnings.warn(w_msg, UserWarning)
            added_res_seq = self.residuals_sequence
            added_min_max = self.min_max_sequence
        # 3) Residuals sequence is defined in other but not in self
        elif not hasattr(self, "residuals_sequence") and hasattr(
            other, "residuals_sequence"
        ):
            w_msg = "".join(
                (
                    f"No residuals_sequence found on {TermColors.CRED}",
                    f"{self.timestamp.strftime('%d %B %Y, %H:%M')}",
                    f"{TermColors.CYELLOW2}.",
                )
            )
            warnings.warn(w_msg, UserWarning)
            added_res_seq = other.residuals_sequence
            added_min_max = other.min_max_sequence
        # 4) Neither self nor other have Residuals sequence
        else:
            w_msg = "No residuals_sequence attribute found."
            warnings.warn(w_msg, UserWarning)
            added_res_seq = np.empty(0)
            added_min_max = np.empty(0)

        added_cc = CycleCount(
            count_cycle=np.hstack([self.count_cycle, other.count_cycle]),
            mean_stress=np.hstack([self.mean_stress, other.mean_stress]),
            stress_range=np.hstack([self.stress_range, other.stress_range]),
            range_bin_lower_bound=added_range_bin_lower_bound,
            range_bin_width=added_range_bin_width,
            _mean_bin_lower_bound=added_mean_bin_lower_bound,
            mean_bin_width=added_mean_bin_width,
            nr_small_cycles=self.nr_small_cycles + other.nr_small_cycles,
            residuals_sequence=added_res_seq,
            _min_max_sequence=added_min_max,
            lffd_solved=False,
            mean_stress_corrected="No",
            stress_concentration_factor=float(added_scf),
            timestamp=min(self.timestamp, other.timestamp),
            name=self.name,
            unit=self.unit,
            _time_sequence=np.unique(
                np.hstack([self.time_sequence, other.time_sequence])
            ),
        )
        return added_cc

    def __radd__(self, other):
        """
        Reverse add function.
        """
        if other is None or other == 0 or np.isnan(other):
            return self
        return self.__add__(other)

    def __mul__(self, other: Union[float, int]):
        """Left multiplication of [`CycleCount`]
        [py_fatigue.cycle_count.cycle_count.CycleCount] \
        instance by a scalar stress multiplication factor .

        Parameters
        ----------
        other : Union[float, int]
            stress concentration factor

        Raises
        ------
        TypeError: Multiplication by a scalar is the only thing \
        allowed

        Returns
        -------
        [`CycleCount`][py_fatigue.cycle_count.cycle_count.CycleCount]
            [`CycleCount`] [py_fatigue.cycle_count.cycle_count.CycleCount]
            instance with \
        "raised" stresses and stress concentration factor != 1
        """
        return _multiplication_by_scalar(self, other)

    def __rmul__(self, other):
        """Left multiplication of [`CycleCount`]
        [py_fatigue.cycle_count.cycle_count.CycleCount] \
        instance by a scalar stress multiplication factor.

        Parameters
        ----------
        other : Union[float, int]
            stress concentration factor

        Raises
        ------
        TypeError: Multiplication by a scalar is the only thing \
        allowed

        Returns
        -------
        [`CycleCount`][py_fatigue.cycle_count.cycle_count.CycleCount]
            [`CycleCount`] [py_fatigue.cycle_count.cycle_count.CycleCount]
            instance with \
        "raised" stresses and stress concentration factor != 1
        """
        return _multiplication_by_scalar(self, other)

    def solve_lffd(
        self,
        solve_mode: str = "Residuals",
        rainflow_method: str = "astm",
    ) -> "CycleCount":
        """Resolve the LFFD using Marsh et al. (2016) method.

        Parameters
        ----------
        solve_mode : str
            Solve mode. Options are: "Residuals" and "Min-Max".
        rainflow_method : str, optional
            Rainflow counting algorithm to propagate to
            [`rainflow`][py_fatigue.cycle_count.rainflow.rainflow], by default
            "astm".

        Returns
        -------
        [`CycleCount`][py_fatigue.cycle_count.cycle_count.CycleCount]
            [`CycleCount`] [py_fatigue.cycle_count.cycle_count.CycleCount]
            instance with LFFD resolved.
        """
        return _solve_lffd(
            self,
            solve_mode,
            rainflow_method=rainflow_method,
        )

    def resolve_residuals(self, rainflow_method: str = "astm") -> "CycleCount":
        """Resolve the residuals. It is a symlink to [`solve_lffd`]
        [py_fatigue.cycle_count.cycle_count.CycleCount.solve_lffd].

        Returns
        -------
        [`CycleCount`][py_fatigue.cycle_count.cycle_count.CycleCount]
            [`CycleCount`] [py_fatigue.cycle_count.cycle_count.CycleCount]
            instance with LFFD resolved.

        See also
        --------
        [`solve_lffd`][py_fatigue.cycle_count.cycle_count.CycleCount.solve_lffd]
        """
        return self.solve_lffd(rainflow_method=rainflow_method)

    def mean_stress_correction(  # pylint: disable=R0912
        self,
        correction_type: str = "DNVGL-RP-C203",
        plot: bool | Callable[[matplotlib.figure.Figure], None] = False,
        enforce_pulsating_load: bool = False,
        **kwargs,
    ) -> "CycleCount":
        """Calculates the mean stress correction returning a new
        [`CycleCount`] [py_fatigue.cycle_count.cycle_count.CycleCount] instance
        with corrected stress ranges
        at constant load ratio ($R=\\sigma_{min}/\\sigma_{max}$).

        Parameters
        ----------
        correction_type : str, optional
            Type of mean stress correction, by default "DNVGL-RP-C203"
        plot : bool or callable, optional
            Use True for a Matplotlib plot or pass a function that receives
            the figure. Defaults to False.
        enforce_pulsating_load : bool, optional
            Choosing to enforce load ratio equals zero prior
            correction (useful in legacy analyses), by default False

        `correction_types` : list
            * *dnvgl-rp-c203*
            * *Walker*
            * *SWT* or *Smith-Watson-Topper*
            * *Goodman*
            * *Gerber*
            * *Morrow*
            * *Soderberg*
            * *Generic-Haigh*

        **kwargs : dict
            *detail_factor* : float
                See DNVGL-RP-C203, by default 0.8
            *yield_strength* : float
                Yielding stress amplitude
            *gamma* : float
                Exponent for Walker mean stress correction, by default 0.5
            *r_out* : float
                Load ratio at which the correction is performed
            *ult_s* : float
                Ultimate tensile strength for Goodman and Gerber, yield
                strength for Soderberg, and true fracture strength for Morrow
            *correction_exponent* : float
                Exponent for Generic-Haigh mean stress
                correction. It is set to 1 for Goodman, Morrow, and Soderberg,
                and 2 for Gerber.


        Returns
        -------
        CycleCount
            [`CycleCount`] [py_fatigue.cycle_count.cycle_count.CycleCount]
            instance with corrected stress ranges

        Raises
        ------
        ValueError
            `correction_type` must be one of `correction_types`.
        ValueError
            Mean stress correction will not be applied because the
            initial mean stress array is made of zeros. Set
            enforce_load_ratio to True to proceed.
        ValueError
            This correction type is not supported.
        ValueError
            The mean stress correction method requires the 'r_out'
            parameter, i.e. the fixed load ratio at which the correction
            is performed.
        ValueError
            The mean stress correction method requires the 'ult_s'
            parameter, i.e. the ultimate tensile strength for Goodman and
            Gerber, the yield strength for Soderberg, and the true fracture
            strength for Morrow.
        ValueError
            The mean stress correction method requires the
            'correction_exponent' parameter, i.e. the exponent of the
            correction function.

        See also
        --------
        [`dnvgl_mean_stress_correction`][py_fatigue.mean_stress.corrections.dnvgl_mean_stress_correction]
        [`walker_mean_stress_correction`][py_fatigue.mean_stress.corrections.walker_mean_stress_correction]
        [`swt_mean_stress_correction`][py_fatigue.mean_stress.corrections.swt_mean_stress_correction]
        [`goodman_haigh_mean_stress_correction`][py_fatigue.mean_stress.corrections.goodman_haigh_mean_stress_correction]
        """
        correction_types = [
            "dnvgl-rp-c203",
            "walker",
            "swt",
            "smith-watson-topper",
            "goodman",
            "gerber",
            "morrow",
            "soderberg",
            "generic-haigh",
            "haigh",
        ]
        if correction_type.lower() not in correction_types:
            raise ValueError(
                f"'correction_type' must be one of {correction_types}"
            )
        if self.mean_stress_corrected != "No":
            w_msg = "".join(
                (
                    "Cyclecount instance has already been corrected using ",
                    f"{TermColors.CBEIGE2}{self.mean_stress_corrected}",
                    TermColors.CYELLOW2,
                    ".",
                )
            )
            warnings.warn(w_msg, UserWarning)
            return self

        self_ = copy.deepcopy(self) if self.lffd_solved else self.solve_lffd()

        if np.all((self_.mean_stress == 0)) and not enforce_pulsating_load:
            print("cycle_count file", self_.mean_stress)
            e_msg = "".join(
                (
                    f"{correction_type} mean stress correction will not be ",
                    "applied because the mean stress array is made of zeros. ",
                    "Set 'enforce_pulsating_load=True' to override mean ",
                    "stresses to pulsating loading (zero load ratio).",
                )
            )
            raise ValueError(e_msg)
        if np.all((self_.mean_stress == 0)) and enforce_pulsating_load:
            self_.mean_stress = self_.stress_amplitude

        ns = SimpleNamespace(**kwargs)
        if correction_type.lower() == ("dnvgl-rp-c203"):
            if "detail_factor" not in kwargs:
                w_msg = "".join(
                    (
                        "No detail factor provided for DNVGL-RP-C203 ",
                        "mean stress correction. \nPassing detail_factor=0.8 ",
                        "This value is suitable for welded connections ",
                        "without significant residual stresses.",
                    )
                )
                warnings.warn(w_msg, UserWarning)
                ns.detail_factor = 0.8
            stress_ranges_corr = msc.dnvgl_mean_stress_correction(
                self_.mean_stress,
                self_.stress_amplitude,
                ns.detail_factor,
                plot,
            )
            mean_stress_corr = copy.deepcopy(stress_ranges_corr / 2)

        if correction_type.lower() == ("walker"):
            if "gamma" not in kwargs:
                w_msg = "".join(
                    (
                        "No gamma exponent provided for Walker ",
                        "mean stress correction. \nPassing gamma=0.5. ",
                        "This value is suitable for many materials ",
                        "and corresponds to applying SWT correction.",
                    )
                )
                warnings.warn(w_msg, UserWarning)
                ns.gamma = 0.5
            stress_ranges_corr = msc.walker_mean_stress_correction(
                self_.mean_stress,
                self_.stress_amplitude,
                ns.gamma,
                plot,
            )
            mean_stress_corr = np.zeros(len(self_.mean_stress))

        if correction_type.lower() in ["swt", "smith-watson-topper"]:
            stress_ranges_corr = msc.swt_mean_stress_correction(
                self_.mean_stress,
                self_.stress_amplitude,
                plot,
            )
            mean_stress_corr = np.zeros(len(self_.mean_stress))
        if correction_type.lower() in [
            "goodman",
            "gerber",
            "morrow",
            "soderberg",
            "haigh",
            "generic-haigh",
        ]:
            if "r_out" not in kwargs:
                e_msg = "".join(
                    (
                        "The mean stress correction method ",
                        f"{correction_type.upper()} requires the ",
                        "'r_out', i.e. the fixed load ratio at which the ",
                        "correction is performed. ",
                    )
                )
                raise ValueError(e_msg)
            if "ult_s" not in kwargs:
                e_msg = "".join(
                    (
                        "The mean stress correction method ",
                        f"{correction_type.upper()} requires the ",
                        "'ult_s' parameter, i.e. the ultimate tensile "
                        "strength for Goodman and Gerber, the yield strength "
                        "for Soderberg, and the true fracture strength for "
                        "Morrow.",
                    )
                )
                raise ValueError(e_msg)
            if correction_type.lower() in ["goodman", "morrow", "soderberg"]:
                ns.correction_exponent = 1
            if correction_type.lower() in ["gerber"]:
                ns.correction_exponent = 2
            if correction_type.lower() in ["generic-haigh", "haigh"]:
                if "correction_exponent" not in kwargs:
                    e_msg = "".join(
                        (
                            "The mean stress correction method ",
                            f"{correction_type.upper()} requires the ",
                            "'correction_exponent' parameter, i.e. the ",
                            "exponent of the correction function.",
                        )
                    )
                    raise ValueError(e_msg)
            if isinstance(ns.r_out, (list, np.ndarray)) and len(ns.r_out) > 1:
                w_msg = "".join(
                    (
                        "Multiple output load ratios provided!\n",
                        f"Only the first one (r_out={ns.r_out[0]}) will be "
                        "used in the mean stress-corrected CycleCount "
                        "instance creation, while the others will be used "
                        "for plotting purposes.",
                    )
                )
                warnings.warn(w_msg, UserWarning)
                if not plot:
                    ns.r_out = ns.r_out[0]
            s_a_c, mean_stress_corr = msc.goodman_haigh_mean_stress_correction(
                amp_in=self_.stress_amplitude,
                mean_in=self_.mean_stress,
                r_out=ns.r_out,
                ult_s=ns.ult_s,
                correction_exponent=ns.correction_exponent,
                plot=plot,
            )
            stress_ranges_corr = s_a_c[0] * 2
            mean_stress_corr = mean_stress_corr[0]

        # ! Creating the corrected CycleCount instance
        cc_msc = CycleCount(
            count_cycle=self_.count_cycle,
            stress_range=stress_ranges_corr,
            mean_stress=mean_stress_corr,
            timestamp=self_.timestamp,
            range_bin_lower_bound=self_.range_bin_lower_bound,
            range_bin_width=self_.range_bin_width,
            _mean_bin_lower_bound=self_.mean_bin_lower_bound,
            mean_bin_width=self_.mean_bin_width,
            mean_stress_corrected="".join(
                f"{correction_type.upper()}: {ns.__dict__}"
            ),
            lffd_solved=self_.lffd_solved,
            name=self_.name,
            nr_small_cycles=self_.nr_small_cycles,
            residuals_sequence=self_.residuals_sequence,
            stress_concentration_factor=self_.stress_concentration_factor,
            _time_sequence=self_.time_sequence,
        )

        if len(self.time_sequence) == 1:
            w_msg = "".join(
                (
                    "If mean stress correction is performed in the contest ",
                    "of long-term fatigue analysis, please perform the sum ",
                    "of multiple CycleCount instances prior mean stress ",
                    "correction (MSC).\nIn fact, applying the MSC before ",
                    "summing into long-term CycleCount instance results in ",
                    "non-conservative life estimates, as after MSC, ",
                    "low-frequency fatigue cannot be estimated accurately.",
                )
            )

            warnings.warn(w_msg, UserWarning)

        return cc_msc

    # ! Plotting methods
    def plot_histogram(
        self,
        plot_type: str = "min-max",
        mode: str = "mountain",
        bins: Union[int, Sequence[int]] = 50,
        bin_range: Optional[np.ndarray] = None,
        normed: bool = False,
        weights: Optional[np.ndarray] = None,  # np.histogram2d args
        fig: Optional[matplotlib.figure.Figure] = None,
        ax: Optional[matplotlib.axes.Axes] = None,
        dens_func: Optional[Callable] = None,
        **kwargs: dict,
    ) -> tuple:  # pragma: no cover
        """Plot the rainflow histogram of the Cycle-counting instance
        with min and max stress on the x-y axes.

        Parameters
        ----------
        plot_type : str
            Type of plot to be generated, default is "min-max". Possible \
            values are: ["min-max", "mean-range"]
        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]
            The bin specification, by default 50 bins are used:
                - 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.
            The default value is None, in which case all values are tallied
        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``,
            default is False.
        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.
            The default is None, which gives each sample equal weight
        fig : matplotlib.figure.Figure, optional
            a Figure instance to add axes into
        dens_func : function or callable, optional
            A function that modifies (inputs and returns) the dens
            values (e.g., np.log10). The default is to not modify the
            values
        kwargs : these keyword arguments are all passed on to scatter

        Returns
        -------
        figure, paths : (
            `~matplotlib.figure.Figure`,
            `~matplotlib.axes.Axes`
        )
            The figure with scatter instance.
        """
        x = np.hstack([self.full_cycles[:, 0], self.residuals[:, 0]])
        y = np.hstack([self.full_cycles[:, 1], self.residuals[:, 1]])
        plot_types = [
            "min-max",
            "mean-range",
            "counts-range",
            "counts-range-cumsum",
            "counts-range-2D",
        ]
        if plot_type not in plot_types:
            e_msg = f"Invalid plot type. Must be one of {plot_types}."
            raise ValueError(e_msg)
        im = None
        if plot_type == "min-max":
            __tmp_x = x - y / 2
            y = x + y / 2
            x = __tmp_x
            bins = bins if bins is not None else 50
        if "counts-range" in plot_type:
            sor = sorted(
                zip(self.stress_range, self.count_cycle),
                reverse=True,
            )

            xy = np.asarray(list(map(list, sor)))
            x = xy[:, 1]
            y = xy[:, 0]
            bins = bins if bins is not None else self.bin_edges
            fig, axes = ht.make_axes(fig=fig, ax=ax)
            im = axes.scatter(
                np.cumsum(x) if "cumsum" in plot_type else x,
                y,
                # edgecolors="#CCC",
                # linewidths=0.5,
                c=x,
                **kwargs,  # type: ignore
            )
            # axes.set_yscale("log")
            # axes.set_xscale("log")
        if plot_type in ("min-max", "mean-range"):
            fig, axes, im = ht.xy_hist2d(
                x=x,
                y=y,
                mode=mode,
                bins=bins,
                bin_range=bin_range,
                normed=normed,
                weights=weights,
                dens_func=dens_func,
                fig=fig,
                ax=ax,
                **kwargs,
            )
            axes.axis("equal")
        cbar_label = (
            "# of cycles"
            if dens_func is None
            else "# of cycles(" + str(dens_func) + ")"
        )
        axes.set_xlabel(
            f"Min stress, {self.unit}"
            if plot_type == "min-max"
            else (
                f"Mean stress, {self.unit}"
                if plot_type == "mean-range"
                else "# of cycles"
            )
        )
        axes.set_ylabel(
            f"Max stress, {self.unit}"
            if plot_type == "min-max"
            else f"Range, {self.unit}"
        )
        cbar = fig.colorbar(im, ax=axes)
        cbar.set_label(cbar_label, rotation=270)
        cbar.ax.get_yaxis().labelpad = 10

        return fig, axes

    plot = plot_histogram

    def plot_residuals_sequence(
        self,
        fig: Optional[matplotlib.figure.Figure] = None,
        ax: Optional[matplotlib.axes.Axes] = None,
        rainflow_method: str = "astm",
        **kwargs,
    ) -> Tuple[
        matplotlib.figure.Figure, matplotlib.axes.Axes
    ]:  # pragma: no cover
        """Plot the residuals of the stress-strain curve.

        Parameters
        ----------
        fig : Optional[matplotlib.figure.Figure], optional
            a Figure instance to add axes into, by default None
        ax : Optional[matplotlib.axes.Axes], optional
            an Axes instance to add axes into, by default None
        rainflow_method : str, optional
            Rainflow counting algorithm to propagate, by default "astm".
        rainflow_method : str, optional
            Rainflow counting algorithm to propagate, by default "astm".

        Returns
        -------
        Tuple[
            matplotlib.figure.Figure,
            matplotlib.axes.Axes
        ]
            The figure with plot instance.
        """
        _, res_res_seq, res_res_idx = calc_rainflow(
            data=np.asarray(self.residuals_sequence),
            method=rainflow_method,
            extended_output=True,
        )

        fig, axes = ht.make_axes(fig=fig, ax=ax)
        axes.plot(self.residuals_sequence, "#003366", ls=":", **kwargs)
        axes.plot(res_res_idx, res_res_seq, "#FF0080", **kwargs)
        axes.set_xlabel("Residuals sequence")
        axes.set_ylabel("Residuals")
        axes.grid(visible=True, which="major", color="#CCCCCC", linestyle="-")
        axes.minorticks_on()
        axes.grid(visible=True, which="minor", color="#E7E6DD", linestyle=":")
        axes.xaxis.grid(False, which="minor")
        axes.spines["right"].set_visible(False)
        axes.spines["top"].set_visible(False)
        return fig, axes

    def plot_half_cycles_sequence(
        self,
        fig: Optional[matplotlib.figure.Figure] = None,
        ax: Optional[matplotlib.axes.Axes] = None,
        rainflow_method: str = "astm",
        **kwargs,
    ) -> Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]:
        """A symlink to plot_residuals_sequence.

        Parameters
        ----------
        fig : Optional[matplotlib.figure.Figure], optional
            a Figure instance to add axes into, by default None
        ax : Optional[matplotlib.axes.Axes], optional
            an Axes instance to add axes into, by default None

        Returns
        -------
        Tuple[
            matplotlib.figure.Figure,
            matplotlib.axes.Axes
        ]
            The figure with plot instance.
        """
        return self.plot_residuals_sequence(
            fig=fig,
            ax=ax,
            rainflow_method=rainflow_method,
            **kwargs,
        )
Attributes
bin_centers property
bin_centers

Extracts the bin centers from the cycle-counting object.

Returns:

Type Description
tuple

Tuple containing mean stresses and stress ranges of the bin centers. - bin_centers_mean_stresses = tuple[0] - bin_centers_stress_ranges = tuple[1]

bin_edges property
bin_edges

Extracts the bin edges from the cycle-counting object.

Returns:

Type Description
tuple

Tuple containing mean stresses and stress ranges of the bin edges. - bin_edges_mean_stresses = tuple[0] - bin_edges_stress_ranges = tuple[1]

full_cycles property
full_cycles

Extracts the full cycles only from mean-range couples.

Returns:

Type Description
(ndarray, shape(n, 2))

Array containing mean stresses and stress ranges of the full cycles. - full_cycles_mean_stresses = array[:, 0] - full_cycles_stress_ranges = array[:, 1]

half_cycles property
half_cycles

Symlink to residuals

See also

residuals

max_stress property
max_stress

Extracts the max stress from the cycle-counting object.

Returns:

Type Description
ndarray

Array containing the max stresses.

mean_bin_lower_bound property writable
mean_bin_lower_bound

The stress values.

Returns:

Name Type Description
values ndarray
mean_bin_upper_bound property
mean_bin_upper_bound

Returns the upper bound of the mean stress bin edges.

Returns:

Type Description
float

The upper bound of the mean stress bins (highest mean bin edge).

min_max_sequence property
min_max_sequence

The minimum and maximum of the residuals (half-cycles) sequence.

Returns:

Type Description
np.ndarray, shape=(2, )

The minimum and maximum of the half-cycles sequence.

min_stress property
min_stress

Extracts the min stress from the cycle-counting object.

Returns:

Type Description
ndarray

Array containing the min stresses.

range_bin_upper_bound property
range_bin_upper_bound

Returns the upper bound of the stress range bins.

Returns:

Type Description
float

The upper bound of the stress range bins (highest range bin edge).

residuals property
residuals

Extracts the residuals, also known as half cycles, from mean-range couples of the cycle-counting object.

Returns:

Type Description
(ndarray, shape(n, 2))

Array containing mean stresses and stress ranges of the residuals. - residual_mean_stresses = array[:, 0] - residual_stress_ranges = array[:, 1]

statistical_moments property
statistical_moments

Calculate the spectral moments from the cycle-counting object.

Returns:

Type Description
tuple[float, float, float]

Tuple containing the spectral moments. - mean = tuple[0] - coefficient of variance = tuple[1] - skewness = tuple[2]

stress_amplitude property
stress_amplitude

Extracts the stress amplitude from the cycle-counting object.

Returns:

Type Description
ndarray

Array containing the stress amplitude.

time_sequence property
time_sequence

The sequence of timestamps possibly added.

Returns:

Name Type Description
time_sequence ndarray
Methods:
__add__
__add__(other)

Sum operation for CycleCount instances.

Parameters:

Name Type Description Default
other Union[CycleCount, None]

CycleCount object to be added to the current object.

required

Returns:

Type Description
CycleCount

Summed cycle-count object.

Raises:

Type Description
TypeError

Trying to add a non-CycleCount object.

TypeError

Trying to add a CycleCount object with different names.

ValueError

Timestamps must be defined for CycleCount sum.

UserWarning

Different bin widths.

TypeError

Timestamps must be sorted ascending.

UserWarning

Adding-up instances having different stress concentration factors.

TypeError

residuals_sequence is not iterable.

UserWarning

No residuals_sequence attribute found.

Source code in py_fatigue/cycle_count/cycle_count.py
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
def __add__(  # fgh - noqa: _C901_
    self, other: "CycleCount"
) -> "CycleCount":
    """Sum operation for [`CycleCount`]
    [py_fatigue.cycle_count.cycle_count.CycleCount] instances.

    Parameters
    ----------
    other : Union[CycleCount, None]
        CycleCount object to be added to the current object.

    Returns
    -------
    CycleCount
        Summed cycle-count object.

    Raises
    ------
    TypeError
        Trying to add a non-CycleCount object.
    TypeError
        Trying to add a CycleCount object with different names.
    ValueError
        Timestamps must be defined for CycleCount sum.
    UserWarning
        Different bin widths.
    TypeError
        Timestamps must be sorted ascending.
    UserWarning
        Adding-up instances having different stress concentration factors.
    TypeError
        residuals_sequence is not iterable.
    UserWarning
        No residuals_sequence attribute found.
    """

    # Running initial checks
    if not _cycle_count_add_checks(self, other):
        return self

    # Performing actual sum
    # added_counts = np.hstack([self.count_cycle, other.count_cycle])
    # added_range = np.hstack([self.stress_range, other.stress_range])
    # added_mean = np.hstack([self.mean_stress, other.mean_stress])
    (
        added_mean_bin_lower_bound,
        added_mean_bin_width,
        added_range_bin_lower_bound,
        added_range_bin_width,
    ) = _handling_different_bins_in_sum(self, other)

    # added_nr_small_cycles = self.nr_small_cycles + other.nr_small_cycles
    # added_timestamp = np.hstack([self.timestamp, other.timestamp])
    added_scf = np.average(
        [
            self.stress_concentration_factor,
            other.stress_concentration_factor,
        ]
    )
    # added_as_duration = self.as_duration + other.as_duration
    # ? Residuals sequence management
    # 1) Residuals sequence is defined in both self and other
    if hasattr(self, "residuals_sequence") and hasattr(
        other, "residuals_sequence"
    ):
        # 1a) Residuals sequence is ok in both self and other
        if isinstance(self.residuals_sequence, Iterable) and isinstance(
            other.residuals_sequence, Iterable
        ):
            added_res_seq = np.hstack(
                [self.residuals_sequence, other.residuals_sequence]
            )
            added_min_max = np.hstack(
                [self.min_max_sequence, other.min_max_sequence]
            )
        # 1b) Residuals sequence is ok in self, but not in other
        elif isinstance(
            self.residuals_sequence, Iterable
        ) and not isinstance(other.residuals_sequence, Iterable):
            w_msg = "".join(
                (
                    f"No residuals_sequence found on {TermColors.CRED}",
                    f"{other.timestamp.strftime('%d %B %Y, %H:%M')}",
                    f"{TermColors.CYELLOW2}.",
                )
            )
            warnings.warn(w_msg, UserWarning)
            added_res_seq = self.residuals_sequence
            added_min_max = self.min_max_sequence
        # 1c) Residuals sequence is ok in other, but not in self
        elif not isinstance(
            self.residuals_sequence, Iterable
        ) and isinstance(other.residuals_sequence, Iterable):
            w_msg = "".join(
                (
                    f"No residuals_sequence found on {TermColors.CRED}",
                    f"{self.timestamp.strftime('%d %B %Y, %H:%M')}",
                    f"{TermColors.CYELLOW2}.",
                )
            )
            warnings.warn(w_msg, UserWarning)
            added_res_seq = other.residuals_sequence
            added_min_max = other.min_max_sequence
        # 1d) Residuals sequence is neither defined in self nor in other
        else:
            w_msg = "No residuals_sequence attribute found."
            warnings.warn(w_msg, UserWarning)
            added_res_seq = np.empty(0)
            added_min_max = np.empty(0)
    # 2) Residuals sequence is defined in self but not in other
    elif hasattr(self, "residuals_sequence") and not hasattr(
        other, "residuals_sequence"
    ):
        w_msg = "".join(
            (
                f"No residuals_sequence found on {TermColors.CRED}",
                f"{other.timestamp.strftime('%d %B %Y, %H:%M')}",
                f"{TermColors.CYELLOW2}.",
            )
        )
        warnings.warn(w_msg, UserWarning)
        added_res_seq = self.residuals_sequence
        added_min_max = self.min_max_sequence
    # 3) Residuals sequence is defined in other but not in self
    elif not hasattr(self, "residuals_sequence") and hasattr(
        other, "residuals_sequence"
    ):
        w_msg = "".join(
            (
                f"No residuals_sequence found on {TermColors.CRED}",
                f"{self.timestamp.strftime('%d %B %Y, %H:%M')}",
                f"{TermColors.CYELLOW2}.",
            )
        )
        warnings.warn(w_msg, UserWarning)
        added_res_seq = other.residuals_sequence
        added_min_max = other.min_max_sequence
    # 4) Neither self nor other have Residuals sequence
    else:
        w_msg = "No residuals_sequence attribute found."
        warnings.warn(w_msg, UserWarning)
        added_res_seq = np.empty(0)
        added_min_max = np.empty(0)

    added_cc = CycleCount(
        count_cycle=np.hstack([self.count_cycle, other.count_cycle]),
        mean_stress=np.hstack([self.mean_stress, other.mean_stress]),
        stress_range=np.hstack([self.stress_range, other.stress_range]),
        range_bin_lower_bound=added_range_bin_lower_bound,
        range_bin_width=added_range_bin_width,
        _mean_bin_lower_bound=added_mean_bin_lower_bound,
        mean_bin_width=added_mean_bin_width,
        nr_small_cycles=self.nr_small_cycles + other.nr_small_cycles,
        residuals_sequence=added_res_seq,
        _min_max_sequence=added_min_max,
        lffd_solved=False,
        mean_stress_corrected="No",
        stress_concentration_factor=float(added_scf),
        timestamp=min(self.timestamp, other.timestamp),
        name=self.name,
        unit=self.unit,
        _time_sequence=np.unique(
            np.hstack([self.time_sequence, other.time_sequence])
        ),
    )
    return added_cc
__eq__
__eq__(other)

Equality operation for CycleCount instances.

Parameters:

Name Type Description Default
other object

object to compare to

required

Returns:

Type Description
bool

True if the objects are equal, False otherwise

Source code in py_fatigue/cycle_count/cycle_count.py
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
def __eq__(self, other: object) -> bool:
    """Equality operation for [`CycleCount`]
    [py_fatigue.cycle_count.cycle_count.CycleCount] instances.

    Parameters
    ----------
    other : object
        object to compare to

    Returns
    -------
    bool
        True if the objects are equal, False otherwise
    """
    if not isinstance(other, CycleCount):
        return False

    return pfu.compare(self.__dict__, other.__dict__)
__mul__
__mul__(other)

Left multiplication of CycleCount instance by a scalar stress multiplication factor .

Parameters:

Name Type Description Default
other Union[float, int]

stress concentration factor

required

Raises:

Type Description
TypeError: Multiplication by a scalar is the only thing allowed

Returns:

Type Description
[`CycleCount`][py_fatigue.cycle_count.cycle_count.CycleCount]

CycleCount instance with "raised" stresses and stress concentration factor != 1

Source code in py_fatigue/cycle_count/cycle_count.py
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
def __mul__(self, other: Union[float, int]):
    """Left multiplication of [`CycleCount`]
    [py_fatigue.cycle_count.cycle_count.CycleCount] \
    instance by a scalar stress multiplication factor .

    Parameters
    ----------
    other : Union[float, int]
        stress concentration factor

    Raises
    ------
    TypeError: Multiplication by a scalar is the only thing \
    allowed

    Returns
    -------
    [`CycleCount`][py_fatigue.cycle_count.cycle_count.CycleCount]
        [`CycleCount`] [py_fatigue.cycle_count.cycle_count.CycleCount]
        instance with \
    "raised" stresses and stress concentration factor != 1
    """
    return _multiplication_by_scalar(self, other)
__radd__
__radd__(other)

Reverse add function.

Source code in py_fatigue/cycle_count/cycle_count.py
1167
1168
1169
1170
1171
1172
1173
def __radd__(self, other):
    """
    Reverse add function.
    """
    if other is None or other == 0 or np.isnan(other):
        return self
    return self.__add__(other)
__rmul__
__rmul__(other)

Left multiplication of CycleCount instance by a scalar stress multiplication factor.

Parameters:

Name Type Description Default
other Union[float, int]

stress concentration factor

required

Raises:

Type Description
TypeError: Multiplication by a scalar is the only thing allowed

Returns:

Type Description
[`CycleCount`][py_fatigue.cycle_count.cycle_count.CycleCount]

CycleCount instance with "raised" stresses and stress concentration factor != 1

Source code in py_fatigue/cycle_count/cycle_count.py
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
def __rmul__(self, other):
    """Left multiplication of [`CycleCount`]
    [py_fatigue.cycle_count.cycle_count.CycleCount] \
    instance by a scalar stress multiplication factor.

    Parameters
    ----------
    other : Union[float, int]
        stress concentration factor

    Raises
    ------
    TypeError: Multiplication by a scalar is the only thing \
    allowed

    Returns
    -------
    [`CycleCount`][py_fatigue.cycle_count.cycle_count.CycleCount]
        [`CycleCount`] [py_fatigue.cycle_count.cycle_count.CycleCount]
        instance with \
    "raised" stresses and stress concentration factor != 1
    """
    return _multiplication_by_scalar(self, other)
__str__
__str__()

String representation of the cycle-counting object.

Returns:

Type Description
str
Source code in py_fatigue/cycle_count/cycle_count.py
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
def __str__(self) -> str:
    """String representation of the cycle-counting object.

    Returns
    -------
    str
    """
    strng = f"CC_{self.name}"
    if len(self.time_sequence) == 1:
        strng = "".join(
            (
                f"CC_{self.name} (",
                f"{self.timestamp.strftime('%d %b %Y, %H:%M')} - ",
                "",
            )
        )
    if len(self.time_sequence) > 1:
        strng = "".join(
            (
                f"CC_ {self.name} (from ",
                f"{self.time_sequence[0].strftime('%d %b %Y, %H:%M')} to ",
                f"{self.time_sequence[-1].strftime('%d %b %Y, %H:%M')})",
            )
        )
    return str(strng)
as_dict
as_dict(
    damage_tolerance_for_binning=0.001,
    damage_exponent=5.0,
    round_decimals=4,
    max_consecutive_zeros=32,
    legacy_export=False,
    debug_mode=False,
)

Convert the cycle-counting object to a dictionary.

Parameters:

Name Type Description Default
damage_tolerance_for_binning float

Tolerance for large-cycles calculation when binning, by default 0.001

0.001
damage_exponent float

SN curve exponent used to define large cycles. Higher means more conservative, 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

32
round_decimals int

Number of decimals after comma, by default 4

4

Returns:

Type Description
dict

Dictionary containing the following keys: - "hist" - "range_bin_lower_bound" - "range_bin_width" - "mean_bin_lower_bound" - "mean_bin_width" - "nr_small_cycles" - "res_sig" - "res" - "lg_c"

See also

rainflow_binner

Source code in py_fatigue/cycle_count/cycle_count.py
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
def as_dict(
    self,
    damage_tolerance_for_binning: float = 0.001,
    damage_exponent: float = 5.0,
    round_decimals: int = 4,
    max_consecutive_zeros: int = 32,
    legacy_export: bool = False,
    debug_mode=False,
) -> dict:
    """Convert the cycle-counting object to a dictionary.

    Parameters
    ----------
    damage_tolerance_for_binning : float, optional
        Tolerance for large-cycles calculation when binning,
        by default 0.001
    damage_exponent : float, optional
        SN curve exponent used to define large cycles. Higher means more
        conservative, 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 after comma, by default 4

    Returns
    -------
    dict
        Dictionary containing the following keys:
        - "hist"
        - "range_bin_lower_bound"
        - "range_bin_width"
        - "mean_bin_lower_bound"
        - "mean_bin_width"
        - "nr_small_cycles"
        - "res_sig"
        - "res"
        - "lg_c"

    See also
    --------
    [`rainflow_binner`][py_fatigue.cycle_count.histogram.rainflow_binner]
    """
    stress_ranges = StressRange(
        _counts=self.count_cycle,
        _values=self.stress_range,
        bin_width=self.range_bin_width,
        _bin_lb=self.range_bin_lower_bound,
    )

    mean_stresses = MeanStress(
        _counts=self.count_cycle,
        _values=self.mean_stress,
        bin_width=self.mean_bin_width,
        _bin_lb=self.mean_bin_lower_bound,
    )

    output_dict = ht.rainflow_binner(
        stress_ranges,
        mean_stresses if not legacy_export else None,
        damage_tolerance_for_binning=damage_tolerance_for_binning,
        damage_exponent=damage_exponent,
        max_consecutive_zeros=max_consecutive_zeros,
        round_decimals=round_decimals,
        debug_mode=debug_mode,
    )
    output_dict["res_sig"] = np.asarray(
        np.round(self.residuals_sequence, round_decimals)
    ).tolist()
    return output_dict
from_pyexsi classmethod
from_pyexsi(data, *, fs, unit, **kwargs)

Rainflow-count a stress signal generated with pyExSi.

Parameters:

Name Type Description Default
data array - like

One-dimensional stress samples. When the generator represents acceleration or force, convert it to stress before calling.

required
fs float

Sampling frequency in Hz used to generate the signal.

required
unit str

Stress unit of the samples (Pa, kPa, MPa or GPa).

required
**kwargs Any

Options passed to from_timeseries, such as name or bin widths.

{}

Returns:

Type Description
CycleCount

Rainflow counts with stress ranges and means in MPa.

Examples:

>>> CycleCount.from_pyexsi([0, 2, 0, 4, 0], fs=20, unit="MPa").unit
'MPa'
Source code in py_fatigue/cycle_count/cycle_count.py
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
@classmethod
def from_pyexsi(
    cls, data: ArrayLike, *, fs: float, unit: str, **kwargs: Any
) -> CycleCount:
    """Rainflow-count a stress signal generated with pyExSi.

    Parameters
    ----------
    data : array-like
        One-dimensional stress samples. When the generator represents
        acceleration or force, convert it to stress before calling.
    fs : float
        Sampling frequency in Hz used to generate the signal.
    unit : str
        Stress unit of the samples (Pa, kPa, MPa or GPa).
    **kwargs
        Options passed to `from_timeseries`, such as `name` or bin widths.

    Returns
    -------
    CycleCount
        Rainflow counts with stress ranges and means in MPa.

    Examples
    --------
    >>> CycleCount.from_pyexsi([0, 2, 0, 4, 0], fs=20, unit="MPa").unit
    'MPa'
    """
    samples = np.asarray(data)
    if samples.ndim != 1 or not unit:
        raise ValueError("Supply one stress signal and its stress unit.")
    return cast(
        CycleCount,
        cls.from_sep005(
            {"data": samples, "fs": fs, "unit_str": unit}, **kwargs
        ),
    )
from_rainflow classmethod
from_rainflow(
    data,
    timestamp=ADT(now(utc)),
    round_decimals=4,
    name=None,
    mean_stress_corrected="No",
    lffd_solved=False,
    unit="MPa",
)

Create a cycle-counting object from rainflow cycles.

Parameters:

Name Type Description Default
*args

Positional arguments passed to py_fatigue.rainflow.rainflow.

required
**kwargs

Keyword arguments passed to py_fatigue.rainflow.rainflow.

required

Returns:

Type Description
CycleCount

A cycle-counting object.

Source code in py_fatigue/cycle_count/cycle_count.py
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
@classmethod
def from_rainflow(
    cls,
    data: dict,
    timestamp: Union[ADT, NDT] = ADT(dt.datetime.now(dt.timezone.utc)),
    round_decimals: int = 4,
    name: Optional[str] = None,
    mean_stress_corrected: str = "No",
    lffd_solved: bool = False,
    unit: str = "MPa",
) -> "CycleCount":
    """Create a cycle-counting object from rainflow cycles.

    Parameters
    ----------
    *args
        Positional arguments passed to `py_fatigue.rainflow.rainflow`.
    **kwargs
        Keyword arguments passed to `py_fatigue.rainflow.rainflow`.

    Returns
    -------
    CycleCount
        A cycle-counting object.
    """
    df = _build_input_data_from_json(
        data,
        timestamp,
        round_decimals,
        name,
        mean_stress_corrected,
        lffd_solved,
    )
    df["unit"] = unit
    return cls(**df)
from_sep005 classmethod
from_sep005(signals, **kwargs)

Rainflow-count stress histories in the SDyPy SEP005 format.

Parameters:

Name Type Description Default
signals mapping or sequence of mappings

Each record contains data (samples or rows of channels) and fs in Hz or an increasing time vector in seconds. An empty or absent quantity is treated as stress, as are "s" and "stress". Supply unit_str in Pa, kPa, MPa or GPa. An empty or absent unit means Pa. Use channel_name and unit_str lists for per-channel metadata, or strings shared by all rows. Supply an ISO 8601 start_timestamp, or include a matching start_timestamp_format for a custom date-time string.

required
**kwargs Any

Rainflow options passed to from_timeseries. Bin settings are in MPa. The name and timestamp options override metadata.

{}

Returns:

Type Description
CycleCount or list of CycleCount

One count for a 1D record, or a flat list in input order for 2D data or a sequence of records. All counts use MPa.

Examples:

>>> record = {"data": [0, 2e6, 0, 4e6, 0], "fs": 20, "quantity": "s"}
>>> CycleCount.from_sep005(record).unit
'MPa'
Source code in py_fatigue/cycle_count/cycle_count.py
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
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
512
513
514
515
516
517
518
519
520
521
@classmethod
def from_sep005(
    cls,
    signals: Mapping[str, Any] | Sequence[Mapping[str, Any]],
    **kwargs: Any,
) -> CycleCount | list[CycleCount]:
    """Rainflow-count stress histories in the SDyPy SEP005 format.

    Parameters
    ----------
    signals : mapping or sequence of mappings
        Each record contains `data` (samples or rows of channels) and
        `fs` in Hz or an increasing `time` vector in seconds. An empty
        or absent `quantity` is treated as stress, as are `"s"` and
        `"stress"`. Supply `unit_str` in Pa, kPa, MPa or GPa. An empty
        or absent unit means Pa. Use `channel_name` and `unit_str`
        lists for per-channel metadata, or strings shared by all rows.
        Supply an ISO 8601 `start_timestamp`, or include a matching
        `start_timestamp_format` for a custom date-time string.
    **kwargs
        Rainflow options passed to `from_timeseries`. Bin settings are
        in MPa. The `name` and `timestamp` options override metadata.

    Returns
    -------
    CycleCount or list of CycleCount
        One count for a 1D record, or a flat list in input order for
        2D data or a sequence of records. All counts use MPa.

    Examples
    --------
    >>> record = {"data": [0, 2e6, 0, 4e6, 0], "fs": 20, "quantity": "s"}
    >>> CycleCount.from_sep005(record).unit
    'MPa'
    """
    if "unit" in kwargs or "time" in kwargs:
        raise TypeError(
            "Specify units and sample times in the SEP005 data."
        )
    if not isinstance(signals, Mapping):
        counts = []
        for signal in signals:
            if not isinstance(signal, Mapping):
                raise TypeError("Each SEP005 signal must be a mapping.")
            result = cls.from_sep005(signal, **kwargs)
            counts.extend(result if isinstance(result, list) else [result])
        return counts

    if signals.get("quantity") not in (None, "", "s", "stress"):
        raise ValueError("The SEP005 quantity must be stress ('s').")
    data = np.asarray(signals.get("data"))
    if (
        data.ndim not in (1, 2)
        or not data.size
        or data.dtype.kind not in "fiu"
    ):
        raise ValueError("SEP005 data must contain real stress samples.")
    channels = np.atleast_2d(data)
    time = sep005_sample_times(signals, channels.shape[1])

    units = signals.get("unit_str")
    names = signals.get("channel_name")
    if not isinstance(units, (list, tuple)):
        units = [units] * len(channels)
    if not isinstance(names, (list, tuple)):
        names = [names or signals.get("name")] * len(channels)
    if len(units) != len(channels) or len(names) != len(channels):
        raise ValueError("Supply one unit and name per SEP005 channel.")

    if (
        "timestamp" not in kwargs
        and signals.get("start_timestamp") is not None
    ):
        kwargs["timestamp"] = sep005_start_timestamp(signals)

    to_mpa = {
        None: 1e-6,
        "": 1e-6,
        "Pa": 1e-6,
        "kPa": 1e-3,
        "MPa": 1.0,
        "GPa": 1e3,
    }
    counts = []
    for samples, unit, name in zip(channels, units, names):
        if not isinstance(unit, (str, type(None))) or unit not in to_mpa:
            raise ValueError(
                "SEP005 stress units must be Pa, kPa, MPa or GPa."
            )
        if name is not None and not isinstance(name, str):
            raise TypeError("SEP005 channel names must be strings.")
        stress = samples.astype(float, copy=False) * to_mpa[unit]
        if not np.all(np.isfinite(stress)):
            raise ValueError("SEP005 stress samples must be finite.")
        options = {"name": name, **kwargs}
        counts.append(cls.from_timeseries(stress, time=time, **options))
    return counts[0] if data.ndim == 1 else counts
from_timeseries classmethod
from_timeseries(
    data,
    time=None,
    timestamp=ADT(now(utc)),
    range_bin_lower_bound=0.2,
    range_bin_width=0.05,
    mean_bin_lower_bound=None,
    mean_bin_width=10,
    name=None,
    unit="MPa",
    rainflow_method="astm",
)

Generate a cycle-count from a timeseries.

Parameters:

Name Type Description Default
*args

Positional arguments passed to _build_input_data_from_json.

required
**kwargs

Keyword arguments passed to _build_input_data_from_json.

required
Source code in py_fatigue/cycle_count/cycle_count.py
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
@classmethod
def from_timeseries(
    cls,
    data: np.ndarray,
    time: Optional[np.ndarray] = None,
    timestamp: Union[ADT, NDT] = ADT(dt.datetime.now(dt.timezone.utc)),
    range_bin_lower_bound: float = 0.2,
    range_bin_width: float = 0.05,
    mean_bin_lower_bound: Optional[float] = None,
    mean_bin_width: float = 10,
    name: Optional[str] = None,
    unit: str = "MPa",
    rainflow_method: str = "astm",
) -> "CycleCount":
    """Generate a cycle-count from a timeseries.

    Parameters
    ----------
    *args
        Positional arguments passed to `_build_input_data_from_json`.
    **kwargs
        Keyword arguments passed to `_build_input_data_from_json`.
    """
    cc = calc_rainflow(
        data=data, time=time, method=rainflow_method, extended_output=True
    )
    if cc[0].size == 0:
        raise ValueError("The stress history contains no rainflow cycles.")
    stress_range = 2 * cc[0][:, 0]
    mean_stress = cc[0][:, 1]
    count_cycle = cc[0][:, 2]
    residuals_sequence = cc[1]
    df = {
        "count_cycle": count_cycle,
        "mean_stress": mean_stress,
        "stress_range": stress_range,
        "timestamp": timestamp,
        "range_bin_lower_bound": range_bin_lower_bound,
        "range_bin_width": range_bin_width,
        "_mean_bin_lower_bound": mean_bin_lower_bound,
        "mean_bin_width": mean_bin_width,
        "residuals_sequence": residuals_sequence,
        "name": name,
        "unit": unit,
    }
    return cls(**df)
mean_stress_correction
mean_stress_correction(
    correction_type="DNVGL-RP-C203",
    plot=False,
    enforce_pulsating_load=False,
    **kwargs
)

Calculates the mean stress correction returning a new CycleCount instance with corrected stress ranges at constant load ratio (\(R=\sigma_{min}/\sigma_{max}\)).

Parameters:

Name Type Description Default
correction_type str

Type of mean stress correction, by default "DNVGL-RP-C203"

'DNVGL-RP-C203'
plot bool or callable

Use True for a Matplotlib plot or pass a function that receives the figure. Defaults to False.

False
enforce_pulsating_load bool

Choosing to enforce load ratio equals zero prior correction (useful in legacy analyses), by default False

False
**kwargs dict

detail_factor : float See DNVGL-RP-C203, by default 0.8 yield_strength : float Yielding stress amplitude gamma : float Exponent for Walker mean stress correction, by default 0.5 r_out : float Load ratio at which the correction is performed ult_s : float Ultimate tensile strength for Goodman and Gerber, yield strength for Soderberg, and true fracture strength for Morrow correction_exponent : float Exponent for Generic-Haigh mean stress correction. It is set to 1 for Goodman, Morrow, and Soderberg, and 2 for Gerber.

{}

Returns:

Type Description
CycleCount

CycleCount instance with corrected stress ranges

Raises:

Type Description
ValueError

correction_type must be one of correction_types.

ValueError

Mean stress correction will not be applied because the initial mean stress array is made of zeros. Set enforce_load_ratio to True to proceed.

ValueError

This correction type is not supported.

ValueError

The mean stress correction method requires the 'r_out' parameter, i.e. the fixed load ratio at which the correction is performed.

ValueError

The mean stress correction method requires the 'ult_s' parameter, i.e. the ultimate tensile strength for Goodman and Gerber, the yield strength for Soderberg, and the true fracture strength for Morrow.

ValueError

The mean stress correction method requires the 'correction_exponent' parameter, i.e. the exponent of the correction function.

See also

dnvgl_mean_stress_correction walker_mean_stress_correction swt_mean_stress_correction goodman_haigh_mean_stress_correction

Source code in py_fatigue/cycle_count/cycle_count.py
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
def mean_stress_correction(  # pylint: disable=R0912
    self,
    correction_type: str = "DNVGL-RP-C203",
    plot: bool | Callable[[matplotlib.figure.Figure], None] = False,
    enforce_pulsating_load: bool = False,
    **kwargs,
) -> "CycleCount":
    """Calculates the mean stress correction returning a new
    [`CycleCount`] [py_fatigue.cycle_count.cycle_count.CycleCount] instance
    with corrected stress ranges
    at constant load ratio ($R=\\sigma_{min}/\\sigma_{max}$).

    Parameters
    ----------
    correction_type : str, optional
        Type of mean stress correction, by default "DNVGL-RP-C203"
    plot : bool or callable, optional
        Use True for a Matplotlib plot or pass a function that receives
        the figure. Defaults to False.
    enforce_pulsating_load : bool, optional
        Choosing to enforce load ratio equals zero prior
        correction (useful in legacy analyses), by default False

    `correction_types` : list
        * *dnvgl-rp-c203*
        * *Walker*
        * *SWT* or *Smith-Watson-Topper*
        * *Goodman*
        * *Gerber*
        * *Morrow*
        * *Soderberg*
        * *Generic-Haigh*

    **kwargs : dict
        *detail_factor* : float
            See DNVGL-RP-C203, by default 0.8
        *yield_strength* : float
            Yielding stress amplitude
        *gamma* : float
            Exponent for Walker mean stress correction, by default 0.5
        *r_out* : float
            Load ratio at which the correction is performed
        *ult_s* : float
            Ultimate tensile strength for Goodman and Gerber, yield
            strength for Soderberg, and true fracture strength for Morrow
        *correction_exponent* : float
            Exponent for Generic-Haigh mean stress
            correction. It is set to 1 for Goodman, Morrow, and Soderberg,
            and 2 for Gerber.


    Returns
    -------
    CycleCount
        [`CycleCount`] [py_fatigue.cycle_count.cycle_count.CycleCount]
        instance with corrected stress ranges

    Raises
    ------
    ValueError
        `correction_type` must be one of `correction_types`.
    ValueError
        Mean stress correction will not be applied because the
        initial mean stress array is made of zeros. Set
        enforce_load_ratio to True to proceed.
    ValueError
        This correction type is not supported.
    ValueError
        The mean stress correction method requires the 'r_out'
        parameter, i.e. the fixed load ratio at which the correction
        is performed.
    ValueError
        The mean stress correction method requires the 'ult_s'
        parameter, i.e. the ultimate tensile strength for Goodman and
        Gerber, the yield strength for Soderberg, and the true fracture
        strength for Morrow.
    ValueError
        The mean stress correction method requires the
        'correction_exponent' parameter, i.e. the exponent of the
        correction function.

    See also
    --------
    [`dnvgl_mean_stress_correction`][py_fatigue.mean_stress.corrections.dnvgl_mean_stress_correction]
    [`walker_mean_stress_correction`][py_fatigue.mean_stress.corrections.walker_mean_stress_correction]
    [`swt_mean_stress_correction`][py_fatigue.mean_stress.corrections.swt_mean_stress_correction]
    [`goodman_haigh_mean_stress_correction`][py_fatigue.mean_stress.corrections.goodman_haigh_mean_stress_correction]
    """
    correction_types = [
        "dnvgl-rp-c203",
        "walker",
        "swt",
        "smith-watson-topper",
        "goodman",
        "gerber",
        "morrow",
        "soderberg",
        "generic-haigh",
        "haigh",
    ]
    if correction_type.lower() not in correction_types:
        raise ValueError(
            f"'correction_type' must be one of {correction_types}"
        )
    if self.mean_stress_corrected != "No":
        w_msg = "".join(
            (
                "Cyclecount instance has already been corrected using ",
                f"{TermColors.CBEIGE2}{self.mean_stress_corrected}",
                TermColors.CYELLOW2,
                ".",
            )
        )
        warnings.warn(w_msg, UserWarning)
        return self

    self_ = copy.deepcopy(self) if self.lffd_solved else self.solve_lffd()

    if np.all((self_.mean_stress == 0)) and not enforce_pulsating_load:
        print("cycle_count file", self_.mean_stress)
        e_msg = "".join(
            (
                f"{correction_type} mean stress correction will not be ",
                "applied because the mean stress array is made of zeros. ",
                "Set 'enforce_pulsating_load=True' to override mean ",
                "stresses to pulsating loading (zero load ratio).",
            )
        )
        raise ValueError(e_msg)
    if np.all((self_.mean_stress == 0)) and enforce_pulsating_load:
        self_.mean_stress = self_.stress_amplitude

    ns = SimpleNamespace(**kwargs)
    if correction_type.lower() == ("dnvgl-rp-c203"):
        if "detail_factor" not in kwargs:
            w_msg = "".join(
                (
                    "No detail factor provided for DNVGL-RP-C203 ",
                    "mean stress correction. \nPassing detail_factor=0.8 ",
                    "This value is suitable for welded connections ",
                    "without significant residual stresses.",
                )
            )
            warnings.warn(w_msg, UserWarning)
            ns.detail_factor = 0.8
        stress_ranges_corr = msc.dnvgl_mean_stress_correction(
            self_.mean_stress,
            self_.stress_amplitude,
            ns.detail_factor,
            plot,
        )
        mean_stress_corr = copy.deepcopy(stress_ranges_corr / 2)

    if correction_type.lower() == ("walker"):
        if "gamma" not in kwargs:
            w_msg = "".join(
                (
                    "No gamma exponent provided for Walker ",
                    "mean stress correction. \nPassing gamma=0.5. ",
                    "This value is suitable for many materials ",
                    "and corresponds to applying SWT correction.",
                )
            )
            warnings.warn(w_msg, UserWarning)
            ns.gamma = 0.5
        stress_ranges_corr = msc.walker_mean_stress_correction(
            self_.mean_stress,
            self_.stress_amplitude,
            ns.gamma,
            plot,
        )
        mean_stress_corr = np.zeros(len(self_.mean_stress))

    if correction_type.lower() in ["swt", "smith-watson-topper"]:
        stress_ranges_corr = msc.swt_mean_stress_correction(
            self_.mean_stress,
            self_.stress_amplitude,
            plot,
        )
        mean_stress_corr = np.zeros(len(self_.mean_stress))
    if correction_type.lower() in [
        "goodman",
        "gerber",
        "morrow",
        "soderberg",
        "haigh",
        "generic-haigh",
    ]:
        if "r_out" not in kwargs:
            e_msg = "".join(
                (
                    "The mean stress correction method ",
                    f"{correction_type.upper()} requires the ",
                    "'r_out', i.e. the fixed load ratio at which the ",
                    "correction is performed. ",
                )
            )
            raise ValueError(e_msg)
        if "ult_s" not in kwargs:
            e_msg = "".join(
                (
                    "The mean stress correction method ",
                    f"{correction_type.upper()} requires the ",
                    "'ult_s' parameter, i.e. the ultimate tensile "
                    "strength for Goodman and Gerber, the yield strength "
                    "for Soderberg, and the true fracture strength for "
                    "Morrow.",
                )
            )
            raise ValueError(e_msg)
        if correction_type.lower() in ["goodman", "morrow", "soderberg"]:
            ns.correction_exponent = 1
        if correction_type.lower() in ["gerber"]:
            ns.correction_exponent = 2
        if correction_type.lower() in ["generic-haigh", "haigh"]:
            if "correction_exponent" not in kwargs:
                e_msg = "".join(
                    (
                        "The mean stress correction method ",
                        f"{correction_type.upper()} requires the ",
                        "'correction_exponent' parameter, i.e. the ",
                        "exponent of the correction function.",
                    )
                )
                raise ValueError(e_msg)
        if isinstance(ns.r_out, (list, np.ndarray)) and len(ns.r_out) > 1:
            w_msg = "".join(
                (
                    "Multiple output load ratios provided!\n",
                    f"Only the first one (r_out={ns.r_out[0]}) will be "
                    "used in the mean stress-corrected CycleCount "
                    "instance creation, while the others will be used "
                    "for plotting purposes.",
                )
            )
            warnings.warn(w_msg, UserWarning)
            if not plot:
                ns.r_out = ns.r_out[0]
        s_a_c, mean_stress_corr = msc.goodman_haigh_mean_stress_correction(
            amp_in=self_.stress_amplitude,
            mean_in=self_.mean_stress,
            r_out=ns.r_out,
            ult_s=ns.ult_s,
            correction_exponent=ns.correction_exponent,
            plot=plot,
        )
        stress_ranges_corr = s_a_c[0] * 2
        mean_stress_corr = mean_stress_corr[0]

    # ! Creating the corrected CycleCount instance
    cc_msc = CycleCount(
        count_cycle=self_.count_cycle,
        stress_range=stress_ranges_corr,
        mean_stress=mean_stress_corr,
        timestamp=self_.timestamp,
        range_bin_lower_bound=self_.range_bin_lower_bound,
        range_bin_width=self_.range_bin_width,
        _mean_bin_lower_bound=self_.mean_bin_lower_bound,
        mean_bin_width=self_.mean_bin_width,
        mean_stress_corrected="".join(
            f"{correction_type.upper()}: {ns.__dict__}"
        ),
        lffd_solved=self_.lffd_solved,
        name=self_.name,
        nr_small_cycles=self_.nr_small_cycles,
        residuals_sequence=self_.residuals_sequence,
        stress_concentration_factor=self_.stress_concentration_factor,
        _time_sequence=self_.time_sequence,
    )

    if len(self.time_sequence) == 1:
        w_msg = "".join(
            (
                "If mean stress correction is performed in the contest ",
                "of long-term fatigue analysis, please perform the sum ",
                "of multiple CycleCount instances prior mean stress ",
                "correction (MSC).\nIn fact, applying the MSC before ",
                "summing into long-term CycleCount instance results in ",
                "non-conservative life estimates, as after MSC, ",
                "low-frequency fatigue cannot be estimated accurately.",
            )
        )

        warnings.warn(w_msg, UserWarning)

    return cc_msc
plot_half_cycles_sequence
plot_half_cycles_sequence(
    fig=None, ax=None, rainflow_method="astm", **kwargs
)

A symlink to plot_residuals_sequence.

Parameters:

Name Type Description Default
fig Optional[Figure]

a Figure instance to add axes into, by default None

None
ax Optional[Axes]

an Axes instance to add axes into, by default None

None

Returns:

Type Description
Tuple[

matplotlib.figure.Figure, matplotlib.axes.Axes

]

The figure with plot instance.

Source code in py_fatigue/cycle_count/cycle_count.py
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
def plot_half_cycles_sequence(
    self,
    fig: Optional[matplotlib.figure.Figure] = None,
    ax: Optional[matplotlib.axes.Axes] = None,
    rainflow_method: str = "astm",
    **kwargs,
) -> Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]:
    """A symlink to plot_residuals_sequence.

    Parameters
    ----------
    fig : Optional[matplotlib.figure.Figure], optional
        a Figure instance to add axes into, by default None
    ax : Optional[matplotlib.axes.Axes], optional
        an Axes instance to add axes into, by default None

    Returns
    -------
    Tuple[
        matplotlib.figure.Figure,
        matplotlib.axes.Axes
    ]
        The figure with plot instance.
    """
    return self.plot_residuals_sequence(
        fig=fig,
        ax=ax,
        rainflow_method=rainflow_method,
        **kwargs,
    )
plot_histogram
plot_histogram(
    plot_type="min-max",
    mode="mountain",
    bins=50,
    bin_range=None,
    normed=False,
    weights=None,
    fig=None,
    ax=None,
    dens_func=None,
    **kwargs
)

Plot the rainflow histogram of the Cycle-counting instance with min and max stress on the x-y axes.

Parameters:

Name Type Description Default
plot_type str

Type of plot to be generated, default is "min-max". Possible values are: ["min-max", "mean-range"]

'min-max'
mode [None | 'mountain' | 'valley' | 'clip']
'mountain'
Possible
  • 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
required
bins int or array_like or [int, int] or [array, array]

The bin specification, by default 50 bins are used: - 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

50
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. The default value is None, in which case all values are tallied

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, default is False.

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. The default is None, which gives each sample equal weight

None
fig Figure

a Figure instance to add axes into

None
dens_func function or callable

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

None
kwargs these keyword arguments are all passed on to scatter
{}

Returns:

Type Description
figure, paths : (

~matplotlib.figure.Figure, ~matplotlib.axes.Axes

)

The figure with scatter instance.

Source code in py_fatigue/cycle_count/cycle_count.py
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
def plot_histogram(
    self,
    plot_type: str = "min-max",
    mode: str = "mountain",
    bins: Union[int, Sequence[int]] = 50,
    bin_range: Optional[np.ndarray] = None,
    normed: bool = False,
    weights: Optional[np.ndarray] = None,  # np.histogram2d args
    fig: Optional[matplotlib.figure.Figure] = None,
    ax: Optional[matplotlib.axes.Axes] = None,
    dens_func: Optional[Callable] = None,
    **kwargs: dict,
) -> tuple:  # pragma: no cover
    """Plot the rainflow histogram of the Cycle-counting instance
    with min and max stress on the x-y axes.

    Parameters
    ----------
    plot_type : str
        Type of plot to be generated, default is "min-max". Possible \
        values are: ["min-max", "mean-range"]
    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]
        The bin specification, by default 50 bins are used:
            - 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.
        The default value is None, in which case all values are tallied
    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``,
        default is False.
    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.
        The default is None, which gives each sample equal weight
    fig : matplotlib.figure.Figure, optional
        a Figure instance to add axes into
    dens_func : function or callable, optional
        A function that modifies (inputs and returns) the dens
        values (e.g., np.log10). The default is to not modify the
        values
    kwargs : these keyword arguments are all passed on to scatter

    Returns
    -------
    figure, paths : (
        `~matplotlib.figure.Figure`,
        `~matplotlib.axes.Axes`
    )
        The figure with scatter instance.
    """
    x = np.hstack([self.full_cycles[:, 0], self.residuals[:, 0]])
    y = np.hstack([self.full_cycles[:, 1], self.residuals[:, 1]])
    plot_types = [
        "min-max",
        "mean-range",
        "counts-range",
        "counts-range-cumsum",
        "counts-range-2D",
    ]
    if plot_type not in plot_types:
        e_msg = f"Invalid plot type. Must be one of {plot_types}."
        raise ValueError(e_msg)
    im = None
    if plot_type == "min-max":
        __tmp_x = x - y / 2
        y = x + y / 2
        x = __tmp_x
        bins = bins if bins is not None else 50
    if "counts-range" in plot_type:
        sor = sorted(
            zip(self.stress_range, self.count_cycle),
            reverse=True,
        )

        xy = np.asarray(list(map(list, sor)))
        x = xy[:, 1]
        y = xy[:, 0]
        bins = bins if bins is not None else self.bin_edges
        fig, axes = ht.make_axes(fig=fig, ax=ax)
        im = axes.scatter(
            np.cumsum(x) if "cumsum" in plot_type else x,
            y,
            # edgecolors="#CCC",
            # linewidths=0.5,
            c=x,
            **kwargs,  # type: ignore
        )
        # axes.set_yscale("log")
        # axes.set_xscale("log")
    if plot_type in ("min-max", "mean-range"):
        fig, axes, im = ht.xy_hist2d(
            x=x,
            y=y,
            mode=mode,
            bins=bins,
            bin_range=bin_range,
            normed=normed,
            weights=weights,
            dens_func=dens_func,
            fig=fig,
            ax=ax,
            **kwargs,
        )
        axes.axis("equal")
    cbar_label = (
        "# of cycles"
        if dens_func is None
        else "# of cycles(" + str(dens_func) + ")"
    )
    axes.set_xlabel(
        f"Min stress, {self.unit}"
        if plot_type == "min-max"
        else (
            f"Mean stress, {self.unit}"
            if plot_type == "mean-range"
            else "# of cycles"
        )
    )
    axes.set_ylabel(
        f"Max stress, {self.unit}"
        if plot_type == "min-max"
        else f"Range, {self.unit}"
    )
    cbar = fig.colorbar(im, ax=axes)
    cbar.set_label(cbar_label, rotation=270)
    cbar.ax.get_yaxis().labelpad = 10

    return fig, axes
plot_residuals_sequence
plot_residuals_sequence(
    fig=None, ax=None, rainflow_method="astm", **kwargs
)

Plot the residuals of the stress-strain curve.

Parameters:

Name Type Description Default
fig Optional[Figure]

a Figure instance to add axes into, by default None

None
ax Optional[Axes]

an Axes instance to add axes into, by default None

None
rainflow_method str

Rainflow counting algorithm to propagate, by default "astm".

'astm'
rainflow_method str

Rainflow counting algorithm to propagate, by default "astm".

'astm'

Returns:

Type Description
Tuple[

matplotlib.figure.Figure, matplotlib.axes.Axes

]

The figure with plot instance.

Source code in py_fatigue/cycle_count/cycle_count.py
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
def plot_residuals_sequence(
    self,
    fig: Optional[matplotlib.figure.Figure] = None,
    ax: Optional[matplotlib.axes.Axes] = None,
    rainflow_method: str = "astm",
    **kwargs,
) -> Tuple[
    matplotlib.figure.Figure, matplotlib.axes.Axes
]:  # pragma: no cover
    """Plot the residuals of the stress-strain curve.

    Parameters
    ----------
    fig : Optional[matplotlib.figure.Figure], optional
        a Figure instance to add axes into, by default None
    ax : Optional[matplotlib.axes.Axes], optional
        an Axes instance to add axes into, by default None
    rainflow_method : str, optional
        Rainflow counting algorithm to propagate, by default "astm".
    rainflow_method : str, optional
        Rainflow counting algorithm to propagate, by default "astm".

    Returns
    -------
    Tuple[
        matplotlib.figure.Figure,
        matplotlib.axes.Axes
    ]
        The figure with plot instance.
    """
    _, res_res_seq, res_res_idx = calc_rainflow(
        data=np.asarray(self.residuals_sequence),
        method=rainflow_method,
        extended_output=True,
    )

    fig, axes = ht.make_axes(fig=fig, ax=ax)
    axes.plot(self.residuals_sequence, "#003366", ls=":", **kwargs)
    axes.plot(res_res_idx, res_res_seq, "#FF0080", **kwargs)
    axes.set_xlabel("Residuals sequence")
    axes.set_ylabel("Residuals")
    axes.grid(visible=True, which="major", color="#CCCCCC", linestyle="-")
    axes.minorticks_on()
    axes.grid(visible=True, which="minor", color="#E7E6DD", linestyle=":")
    axes.xaxis.grid(False, which="minor")
    axes.spines["right"].set_visible(False)
    axes.spines["top"].set_visible(False)
    return fig, axes
resolve_residuals
resolve_residuals(rainflow_method='astm')

Resolve the residuals. It is a symlink to solve_lffd.

Returns:

Type Description
[`CycleCount`][py_fatigue.cycle_count.cycle_count.CycleCount]

CycleCount instance with LFFD resolved.

See also

solve_lffd

Source code in py_fatigue/cycle_count/cycle_count.py
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
def resolve_residuals(self, rainflow_method: str = "astm") -> "CycleCount":
    """Resolve the residuals. It is a symlink to [`solve_lffd`]
    [py_fatigue.cycle_count.cycle_count.CycleCount.solve_lffd].

    Returns
    -------
    [`CycleCount`][py_fatigue.cycle_count.cycle_count.CycleCount]
        [`CycleCount`] [py_fatigue.cycle_count.cycle_count.CycleCount]
        instance with LFFD resolved.

    See also
    --------
    [`solve_lffd`][py_fatigue.cycle_count.cycle_count.CycleCount.solve_lffd]
    """
    return self.solve_lffd(rainflow_method=rainflow_method)
solve_lffd
solve_lffd(solve_mode='Residuals', rainflow_method='astm')

Resolve the LFFD using Marsh et al. (2016) method.

Parameters:

Name Type Description Default
solve_mode str

Solve mode. Options are: "Residuals" and "Min-Max".

'Residuals'
rainflow_method str

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

'astm'

Returns:

Type Description
[`CycleCount`][py_fatigue.cycle_count.cycle_count.CycleCount]

CycleCount instance with LFFD resolved.

Source code in py_fatigue/cycle_count/cycle_count.py
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
def solve_lffd(
    self,
    solve_mode: str = "Residuals",
    rainflow_method: str = "astm",
) -> "CycleCount":
    """Resolve the LFFD using Marsh et al. (2016) method.

    Parameters
    ----------
    solve_mode : str
        Solve mode. Options are: "Residuals" and "Min-Max".
    rainflow_method : str, optional
        Rainflow counting algorithm to propagate to
        [`rainflow`][py_fatigue.cycle_count.rainflow.rainflow], by default
        "astm".

    Returns
    -------
    [`CycleCount`][py_fatigue.cycle_count.cycle_count.CycleCount]
        [`CycleCount`] [py_fatigue.cycle_count.cycle_count.CycleCount]
        instance with LFFD resolved.
    """
    return _solve_lffd(
        self,
        solve_mode,
        rainflow_method=rainflow_method,
    )
summary
summary()

Summary Dataframe of the most important properties of the cycle-counting object.

Returns:

Type Description
DataFrame
Source code in py_fatigue/cycle_count/cycle_count.py
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
def summary(self) -> pd.DataFrame:
    """
    Summary Dataframe of the most important properties of the cycle-counting
    object.

    Returns
    -------
    pd.DataFrame
    """

    df = pd.DataFrame()
    df["Cycle counting object"] = [
        f"largest full stress range, {self.unit}",
        f"largest stress range, {self.unit}",
        "number of full cycles",
        "number of residuals",
        "number of small cycles",
        "stress concentration factor",
        "residuals resolved",
        "mean stress-corrected",
    ]

    df[self.name] = [
        (
            max(self.full_cycles[:, 1])
            if max(self.count_cycle) > 0.5
            and max(self.full_cycles[:, 1]) > self.range_bin_lower_bound
            else None
        ),
        max(self.stress_range),
        int(sum(self.count_cycle) - int(len(self.residuals[:, 1])) / 2),
        int(len(self.residuals[:, 1])),
        int(self.nr_small_cycles),
        (
            "N/A"
            if self.stress_concentration_factor == 1
            else self.stress_concentration_factor
        ),
        bool(self.lffd_solved),
        self.mean_stress_corrected,
    ]
    df = df.set_index("Cycle counting object")

    return df
to_df
to_df()

Represent the CycleCount instance as a pandas dataframe.

Returns:

Type Description
DataFrame

dataframe containing relevant fatigue information

Source code in py_fatigue/cycle_count/cycle_count.py
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
def to_df(self) -> pd.DataFrame:  # pragma: no cover
    """
    Represent the [`CycleCount`]
    [py_fatigue.cycle_count.cycle_count.CycleCount] instance as a pandas
    dataframe.

    Returns
    -------
    pandas.DataFrame
        dataframe containing relevant fatigue information
    """

    df = pd.DataFrame.from_dict(
        {
            "count_cycle": self.count_cycle,
            "mean_stress": self.mean_stress,
            "stress_range": self.stress_range,
        }
    )
    df._metadata = {
        "name": self.name,
        "timestamp": self.timestamp,
        "time_sequence": self.time_sequence,
        "residuals_sequence": self.residuals_sequence,
        "mean_stress_corrected": self.mean_stress_corrected,
        "stress_concentration_factor": self.stress_concentration_factor,
        "nr_small_cycles": self.nr_small_cycles,
        "lffd_solved": self.lffd_solved,
        "unit": self.unit,
    }

    return df

Functions:

pbar_sum

pbar_sum(cc_list)

Sum a list of CycleCount objects using a progress bar.

Parameters:

Name Type Description Default
cc_list list

The list of CycleCount objects to sum.

required

Returns:

Type Description
CycleCount

The sum of the CycleCount objects.

Source code in py_fatigue/cycle_count/cycle_count.py
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
def pbar_sum(cc_list: Sequence[CycleCount]) -> CycleCount:
    """Sum a list of CycleCount objects using a progress bar.

    Parameters
    ----------
    cc_list : list
        The list of CycleCount objects to sum.

    Returns
    -------
    py_fatigue.CycleCount
        The sum of the CycleCount objects.
    """

    if len(cc_list) == 1:
        if hasattr(cc_list, "iloc"):
            return cc_list.iloc[0]  # type: ignore[return-value]
        return cc_list[0]

    chunk_size = int(np.sqrt(len(cc_list)))
    cc_list = [cc for cc in cc_list if cc is not None]

    sleep(0.15)
    chunked_cc_list = list(pfu.chunks(cc_list, chunk_size))
    l_c = len(chunked_cc_list)

    cc_sum: CycleCount = chunked_cc_list[0]  # type: ignore
    cc_sum_list: list[CycleCount] = []

    for j, chunked_cc_sublist in enumerate(chunked_cc_list):
        k = j + 1
        # try:
        blocks = int(k / l_c * 32)
        # except ZeroDivisionError:
        #     blocks = int(k / l_c * 32)
        underscores = 32 - blocks
        pbar = f"{k * len(chunked_cc_sublist)}/{len(cc_list)} -> "
        pbar += TermColors.CBLUE2 + "|" + "".join(["█"] * blocks)
        pbar += "".join(["_"] * underscores) + "|" + TermColors.CEND
        # try:
        pbar += f" -> {min(int(k / l_c * 100), 100)}% completed... "
        # except ZeroDivisionError:
        #     pbar += f" -> { min(int(k / l_c * 100), 100)}% completed... "
        print(pbar, end="\r")

        if len(chunked_cc_sublist) == 1:
            cc_sum_list.append(chunked_cc_sublist[0])
            cc_sum = (
                cc_sum_list[-1]
                if len(cc_sum_list) == 1
                else cc_sum + cc_sum_list[-1]
            )
            continue
        cc_sum_list.append(chunked_cc_sublist[0])
        for cc in chunked_cc_sublist[1::]:
            if cc is None:
                continue
            cc_sum_list[-1] += cc
        cc_sum = (
            cc_sum_list[-1]
            if len(cc_sum_list) == 1
            else cc_sum + cc_sum_list[-1]
        )
    return cc_sum

sep005_sample_times

sep005_sample_times(signal, sample_count)

Validate SEP005 sampling metadata and return explicit sample times.

Source code in py_fatigue/cycle_count/cycle_count.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def sep005_sample_times(
    signal: Mapping[str, Any], sample_count: int
) -> np.ndarray | None:
    """Validate SEP005 sampling metadata and return explicit sample times."""
    time = signal.get("time")
    if time is None:
        fs = signal.get("fs")
        if (
            not isinstance(fs, Real)
            or isinstance(fs, bool)
            or not np.isfinite(fs)
            or fs <= 0
        ):
            raise ValueError("Supply SEP005 time or a positive fs in Hz.")
        return None
    time = np.asarray(time)
    if (
        time.shape != (sample_count,)
        or time.dtype.kind not in "fiu"
        or not np.all(np.isfinite(time))
        or not np.all(time[1:] > time[:-1])
    ):
        raise ValueError("Supply one increasing time per stress sample.")
    return time

sep005_start_timestamp

sep005_start_timestamp(signal)

Parse the optional SEP005 start timestamp when supplied.

Source code in py_fatigue/cycle_count/cycle_count.py
86
87
88
89
90
91
92
93
94
95
96
def sep005_start_timestamp(signal: Mapping[str, Any]) -> dt.datetime:
    """Parse the optional SEP005 start timestamp when supplied."""
    start = signal["start_timestamp"]
    if isinstance(start, dt.datetime):
        return start
    if not isinstance(start, str):
        raise TypeError("SEP005 start_timestamp must be a date-time.")
    date_format = signal.get("start_timestamp_format")
    if date_format:
        return dt.datetime.strptime(start, date_format)
    return dt.datetime.fromisoformat(start.replace("Z", "+00:00"))