Skip to content

utils

Overview

Aggregate cycle counts over time windows and plot the resulting residuals.

py_fatigue.cycle_count.utils

Utilities for the cycle count module.

Classes

Functions:

aggregate_cc

aggregate_cc(
    df,
    aggr_by,
    save_residuals=False,
    rainflow_method="astm",
)

Aggregate a pandas dataframe by time window. The pandas dataframe must have a DatetimeIndex and at least one column whose name starts with 'CC_' containing CycleCount instances, e.g.,

Example dataframe to be aggregated

DateTimeIndex CC_1 CC_2 CC_3 Other
2018-01-01 00:00:00 Count 1 (00:00) Count 2 (00:00) Count 3 (00:00)
...
2018-01-01 01:00:00 Count 1 (01:00) Count 2 (01:00) Count 3 (01:00)
...
2018-01-01 02:00:00 Count 1 (02:00) Count 2 (02:00) Count 3 (02:00)
...
⋮ ⋮ ⋮ ⋮ ⋱

The function performs the following workflow:

  1. Perform initial checks on the input pandas dataframe
  2. Build the aggregation dictionary
  3. Aggregate the dataframe by time window, i.e. the aggregated CycleCounts
  4. Retrieve the low-frequency fatigue dynamics on the aggregated dataframe
  5. Save the residuals sequences of each aggregated CycleCount

Parameters:

Name Type Description Default
df DataFrame

The dataframe to cluster

required
aggr_by str

The time window to cluster the dataframe by. It must be a valid pandas date offset frequency string or 'all'. See the pandas time series documentation for frequency aliases.

required
save_residuals bool

If True, the residuals sequences of each aggregated CycleCount are saved

False
rainflow_method str

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

'astm'

Returns:

Type Description
tuple[DataFrame, dict[str, dict[str, list]]]

The aggregated dataframe and the residuals sequences of each aggregated

Source code in py_fatigue/cycle_count/utils.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def aggregate_cc(  # pragma: no cover
    df: pd.DataFrame,
    aggr_by: str,
    save_residuals: bool = False,
    rainflow_method: str = "astm",
) -> Union[
    pd.DataFrame,
    tuple[pd.DataFrame, DefaultDict[str, DefaultDict[str, list[float]]]],
]:
    """Aggregate a pandas dataframe by time window.
    The pandas dataframe must have a DatetimeIndex and at least one column
    whose name starts with 'CC\\_' containing [`CycleCount`]
    [py_fatigue.cycle_count.cycle_count.CycleCount]
    instances, e.g.,

    **Example dataframe to be aggregated**

    | DateTimeIndex | CC_1 | CC_2 | CC_3 | Other |
    | --- | --- | --- | --- | --- |
    | 2018-01-01 00:00:00 | Count 1 (00:00) | Count 2 (00:00) | Count 3 (00:00)
    | ... |
    | 2018-01-01 01:00:00 | Count 1 (01:00) | Count 2 (01:00) | Count 3 (01:00)
    | ... |
    | 2018-01-01 02:00:00 | Count 1 (02:00) | Count 2 (02:00) | Count 3 (02:00)
    | ... |
    | ⋮ | ⋮ | ⋮ | ⋮ | ⋱ |

    The function performs the following workflow:

    1. Perform initial checks on the input pandas dataframe
    2. Build the aggregation dictionary
    3. Aggregate the dataframe by time window, i.e. the aggregated CycleCounts
    4. Retrieve the low-frequency fatigue dynamics on the aggregated dataframe
    5. Save the residuals sequences of each aggregated CycleCount

    Parameters
    ----------
    df : pd.DataFrame
        The dataframe to cluster
    aggr_by : str
        The time window to cluster the dataframe by. It must be a valid pandas
        date offset frequency string or 'all'.
        See the pandas time series documentation for frequency aliases.
    save_residuals : bool, optional
        If True, the residuals sequences of each aggregated CycleCount are
        saved
    rainflow_method : str, optional
        Rainflow counting algorithm forwarded to
        [`rainflow`] [py_fatigue.cycle_count.rainflow.rainflow], by default
        "astm".

    Returns
    -------
    tuple[pd.DataFrame, dict[str, dict[str, list]]]
        The aggregated dataframe and the residuals sequences of each aggregated
    """
    start = time.time()

    # Perform initial checks on the input pandas dataframe
    print("\33[36m1. Running checks on \33[1mdf\33[22m.\33[0m")
    if not isinstance(df, pd.DataFrame):
        raise TypeError("df must be a pandas DataFrame")
    if not isinstance(df.index, pd.DatetimeIndex):
        raise TypeError("df must have a DatetimeIndex")
    if not df.index.is_monotonic_increasing:
        raise ValueError("df must have a monotonic increasing DatetimeIndex")
    if not df.index.is_unique:
        raise ValueError("df must have a unique DatetimeIndex")
    if not df.index.inferred_type == "datetime64":
        raise ValueError("df must have a DatetimeIndex containing only dates")

    # Build the aggregation dictionary
    print("\33[36m2. Building the aggregation \33[1mdict\33[22m.")
    agg_list: list[dict[float | str, Any]] = [
        (
            {col: pbar_sum}
            if isinstance(col, str) and col.startswith("CC_")
            else {col: np.nanmean}
        )
        for col in df
    ]
    agg_dict = dict(ChainMap(*agg_list))

    # Aggregate the dataframe by time window
    print(f"3. Aggregate \33[1mdf\33[22m by \33[1m'{aggr_by}'\33[22m.\33[0m")
    if aggr_by.lower() == "all":
        df_agg = df.groupby(lambda _: True).agg(agg_dict)
    else:
        df_agg = df.groupby([df.index.to_period(aggr_by)]).agg(agg_dict)

    # Retrieving the low-frequency fatigue dynamics on the aggregated dataframe
    print("\33[36m4. Retrieving LFFD on aggregated \33[1mdf\33[22m.\33[0m")
    map_cycles = getattr(df_agg, "map", None)
    if map_cycles is None:
        df_agg_rr = df_agg.applymap(
            partial(solve_lffd, rainflow_method=rainflow_method)
        )
    else:
        df_agg_rr = map_cycles(
            partial(solve_lffd, rainflow_method=rainflow_method)
        )

    cc_cols: list[str] = [
        col for col in df_agg_rr.columns if col.startswith("CC_")
    ]

    if not save_residuals:
        end = time.time()
        print(
            f"Elapsed time for \33[36m\33[1m'{aggr_by}'\33[0m aggregation",
            f"is {np.round(end - start, 0)}, s.\n",
        )
        return df_agg_rr
    # Saving the residuals sequences
    print("\33[36m5. Saving the \33[1mresiduals sequences\33[22m.\33[0m")
    residuals_sequence: DefaultDict[str, DefaultDict[str, list[float]]] = (
        defaultdict(lambda: defaultdict(list))
    )
    for col in cc_cols:
        for __, row in df_agg.iterrows():
            if not isinstance(row[col], CycleCount):
                continue
            if not isinstance(row[col].residuals_sequence, Iterable):
                continue
            _, res_res_seq, res_res_idx = calc_rainflow(
                data=np.asarray(row[col].residuals_sequence),
                method=rainflow_method,
                extended_output=True,
            )
            if len(residuals_sequence[col]["idx"]) > 0:
                res_res_idx += residuals_sequence[col]["idx"][-1]
            residuals_sequence[col]["idx"].extend(res_res_idx.tolist())
            residuals_sequence[col]["res"].extend(res_res_seq.tolist())
    end = time.time()
    print(
        f"Elapsed time for \33[36m\33[1m'{aggr_by}'\33[0m aggregation",
        f"is {np.round(end - start, 0)}, s.\n",
    )
    return df_agg_rr, residuals_sequence

calc_aggregated_damage

calc_aggregated_damage(df, sn)

Calculate the damage of each aggregated CycleCount. This function needs the output of aggregate_cc.

Parameters:

Name Type Description Default
df DataFrame

The aggregated CycleCount as returned by aggregate_cc.

required
sn DefaultDict[str, SNCurve]

The S-N curves of each aggregated CycleCount.

required

Returns:

Type Description
DataFrame

The damage of each aggregated CycleCount as a multi-indexed dataframe.

Source code in py_fatigue/cycle_count/utils.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def calc_aggregated_damage(  # pragma: no cover
    df: pd.DataFrame,
    sn: Union[
        dict[str, SNCurve], DefaultDict[str, SNCurve], list[SNCurve], SNCurve
    ],
) -> pd.DataFrame:
    """Calculate the damage of each aggregated CycleCount. This function needs
    the output of [`aggregate_cc`][py_fatigue.cycle_count.utils.aggregate_cc].

    Parameters
    ----------
    df : pd.DataFrame
        The aggregated CycleCount as returned by [`aggregate_cc`]
        [py_fatigue.cycle_count.utils.aggregate_cc].
    sn : DefaultDict[str, SNCurve]
        The S-N curves of each aggregated CycleCount.

    Returns
    -------
    pd.DataFrame
        The damage of each aggregated CycleCount as a multi-indexed dataframe.
    """
    # Check the S-N curves
    if not isinstance(sn, defaultdict) or not isinstance(sn, dict):
        if isinstance(sn, SNCurve):
            sn = {sn.name: sn}
        elif isinstance(sn, list):
            if all(isinstance(s, SNCurve) for s in sn):
                sn = {s.name: s for s in sn}
            else:
                raise TypeError(
                    "The S-N curves must be a dict, a list of SNCurve or a "
                    "SNCurve."
                )

    cc_cols: list[str] = [col for col in df.columns if col.startswith("CC_")]
    damages = pd.DataFrame()
    for _, sn_curve in sn.items():
        map_cycles = getattr(df[cc_cols], "map", None)
        if map_cycles is None:
            df_1 = df[cc_cols].applymap(
                lambda x, sk=sn_curve: np.sum(
                    get_pm(cycle_count=x, sn_curve=sk)
                    if isinstance(x, CycleCount)
                    else 0
                )
            )
        else:
            df_1 = map_cycles(
                lambda x, sk=sn_curve: np.sum(
                    get_pm(cycle_count=x, sn_curve=sk)
                    if isinstance(x, CycleCount)
                    else 0
                )
            )
        df_1["sn_curve"] = f"m={sn_curve.slope}"
        damages = pd.concat([damages, df_1])
        del df_1
    dmg_mi = damages.set_index(["sn_curve", damages.index])  # type: ignore
    return dmg_mi

plot_aggregated_residuals

plot_aggregated_residuals(
    res_dct, plt_prmtr, minor_grid=True
)

Plot the aggregated residuals sequences. T

Parameters:

Name Type Description Default
res_dct dict[str, DefaultDict[str, DefaultDict[str, list[float]]]]

The residuals sequences of each aggregated CycleCount as returned by aggregate_cc.

required
plt_prmtr str

The parameter to plot.

required
labels Collection[str]

The labels of the aggregated CycleCounts.

required
minor_grid bool

Whether to plot the minor grid, by default True

True

Returns:

Type Description
tuple[Figure, Axes]
Source code in py_fatigue/cycle_count/utils.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def plot_aggregated_residuals(  # pragma: no cover
    res_dct: dict[str, DefaultDict[str, DefaultDict[str, list[float]]]],
    plt_prmtr: str,
    minor_grid: bool = True,
) -> tuple:  # pragma: no cover
    """Plot the aggregated residuals sequences. T

    Parameters
    ----------
    res_dct : dict[str, DefaultDict[str, DefaultDict[str, list[float]]]]
        The residuals sequences of each aggregated CycleCount as returned by
        [`aggregate_cc`][py_fatigue.cycle_count.utils.aggregate_cc].
    plt_prmtr : str
        The parameter to plot.
    labels : Collection[str]
        The labels of the aggregated CycleCounts.
    minor_grid : bool, optional
        Whether to plot the minor grid, by default True

    Returns
    -------
    tuple[plt.figure.Figure, plt.axes.Axes]

    """
    fig, axes = plt.subplots()

    for i, (label, res) in enumerate(res_dct.items()):
        alpha = np.round((i + 1) / len(res_dct), 2)
        axes.plot(
            res[plt_prmtr]["idx"],
            res[plt_prmtr]["res"],
            lw=alpha,
            label=label,
            alpha=alpha,
        )
    if minor_grid:
        axes.minorticks_on()
        axes.grid(visible=True, which="minor", color="#E7E6DD", linestyle=":")
    axes.set_xlabel("Residuals sequence")
    axes.set_ylabel("Residuals")
    axes.legend(
        title="Aggregated by",
        loc="lower center",
        fancybox=True,
        bbox_to_anchor=(0.5, -0.44),
        ncol=3,
        shadow=True,
    )
    plt.show()

    return fig, axes

solve_lffd

solve_lffd(x, rainflow_method='astm')

Solve the low-frequency fatigue dynamics of a cycle count or return the object as is.

Parameters:

Name Type Description Default
x Any

The object to evaluate. If it is a CycleCount instance, the low-frequency fatigue dynamics is solved. Otherwise, the object is returned as is.

required

Returns:

Type Description
Any

The object evaluated

Source code in py_fatigue/cycle_count/utils.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def solve_lffd(
    x: Any,
    rainflow_method: str = "astm",
) -> Union[Any, CycleCount]:  # pragma: no cover
    """Solve the low-frequency fatigue dynamics of a cycle count or return the
    object as is.

    Parameters
    ----------
    x : Any
        The object to evaluate. If it is a [`CycleCount`]
        [py_fatigue.cycle_count.cycle_count.CycleCount]
        instance, the low-frequency fatigue dynamics is solved.
        Otherwise, the object is returned as is.

    Returns
    -------
    Any
        The object evaluated
    """
    if isinstance(x, CycleCount) and len(x.time_sequence) > 1:
        return x.solve_lffd(rainflow_method=rainflow_method)
    return x