Skip to content

mean_stress

Overview

Represent cycle mean stresses and apply the DNVGL-RP-C203, Walker, SWT, or Goodman–Haigh correction.

MeanStress

py_fatigue.mean_stress.mean_stress.MeanStress dataclass

Bases: FatigueStress

Mean stress class.

Source code in py_fatigue/mean_stress/mean_stress.py
13
14
15
16
class MeanStress(FatigueStress):
    """Mean stress class."""

    category: ClassVar[str] = "mean"

corrections

py_fatigue.mean_stress.corrections

The py_fatigue.mean_stress.corrections module collects all the mean stress corrections implemented in py_fatigue. classes.

Functions:

__goodman_equation

__goodman_equation(
    amp_out_val,
    amp_in_val,
    r_in_val,
    r_out_val,
    ult_s,
    correction_exponent,
)

Implicit equation to solve for amp_out.

\[ \sigma_{amp, \text{out}} =  \frac{1}{ \frac{1 - \left( \frac{(1 + R_{\text{in}}) \cdot \sigma_{amp, \text{in}}} {(1 - R_{\text{in}}) \cdot \sigma_{ult}} \right)^{n}}{\sigma_{amp, \text{in}}} + \sigma_{amp, \text{out}}^{n-1} \cdot \left( \frac{(1 + R_{\text{out}})}{(1 - R_{\text{out}}) \cdot \sigma_{ult}} \right)^{n}} \]

The quantities are:

  • \(R_{in} = \sigma_{min}/\sigma_{max}\) is the input stress ratio.
  • \(R_{out}\) is the output stress ratio.
  • \(\sigma_{amp,in}\) is the input amplitude.
  • \(\sigma_{amp,out}\) is the output amplitude.
  • \(\sigma_{ult}\) is the ultimate material strength.
  • \(n\) is the correction exponent.

Parameters:

Name Type Description Default
amp_out_val float

The output amplitude value.

required
amp_in_val float

The input amplitude value.

required
r_in_val float

The input load ratio value.

required
r_out_val float

The output load ratio value.

required
ult_s float

The ultimate strength of the material.

required
correction_exponent float

The correction exponent value.

required

Returns:

Type Description
float

The difference between the left-hand side and right-hand side of the equation.

Source code in py_fatigue/mean_stress/corrections.py
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
def __goodman_equation(
    amp_out_val: float,
    amp_in_val: float,
    r_in_val: float,
    r_out_val: float,
    ult_s: float,
    correction_exponent: float,
) -> float:
    """Implicit equation to solve for amp_out.

    $$
    \\sigma_{amp, \\text{out}} =  \\frac{1}{ \\frac{1 - \\left(
        \\frac{(1 + R_{\\text{in}}) \\cdot \\sigma_{amp, \\text{in}}}
        {(1 - R_{\\text{in}}) \\cdot \\sigma_{ult}}
        \\right)^{n}}{\\sigma_{amp, \\text{in}}}
        + \\sigma_{amp, \\text{out}}^{n-1} \\cdot \\left(
        \\frac{(1 + R_{\\text{out}})}{(1 - R_{\\text{out}})
        \\cdot \\sigma_{ult}} \\right)^{n}}
    $$

    The quantities are:

    - $R_{in} = \\sigma_{min}/\\sigma_{max}$ is the input stress ratio.
    - $R_{out}$ is the output stress ratio.
    - $\\sigma_{amp,in}$ is the input amplitude.
    - $\\sigma_{amp,out}$ is the output amplitude.
    - $\\sigma_{ult}$ is the ultimate material strength.
    - $n$ is the correction exponent.
    Parameters
    ----------
    amp_out_val : float
        The output amplitude value.
    amp_in_val : float
        The input amplitude value.
    r_in_val : float
        The input load ratio value.
    r_out_val : float
        The output load ratio value.
    ult_s : float
        The ultimate strength of the material.
    correction_exponent : float
        The correction exponent value.
    Returns
    -------
    float
        The difference between the left-hand side and right-hand side of the
        equation.
    """
    assert r_in_val != 1, "Input load ratio equals 1, meaning static load."
    # if r_in_val == 1:
    # fmt: off
    # raise ValueError(f"Input load ratio equals 1 at amp_in={amp_in_val}"
    #                   ", meaning static load. Revise input data.")
    # fmt: on
    trm1 = (1 + r_in_val) / (1 - r_in_val) * amp_in_val / ult_s
    trm2 = (1 + r_out_val) / (1 - r_out_val) / ult_s

    lhs = amp_out_val
    # fmt: off
    rhs = (1 - trm1**correction_exponent) / amp_in_val + \
            amp_out_val**(correction_exponent - 1) * trm2**correction_exponent
    # fmt: on
    return lhs - rhs**-1

dnvgl_mean_stress_correction

dnvgl_mean_stress_correction(
    mean_stress,
    stress_amplitude,
    detail_factor=0.8,
    plot=False,
)

Calculates the mean stress correction according to par. 2.5 of DNVGL-RP-C203, which includes an attenuation factor \(p\) for the stress ranges if the following cases:

  • base material without significant residual stresses \(\rightarrow p = 0.6\). This option neglects fully compressive cycles.
  • welded connections without significant residual stresses \(\rightarrow p = 0.8\). This option multiplies the stress range of fully compressive cycles by p.

Given that the stress ranges are \(\Delta \sigma\), the corrected stress ranges are:

\[ \Delta \sigma_{corr} = f_m \cdot \Delta \sigma \]

where:

\[ f_m = \frac{\sigma_{max} + p \cdot \vert \sigma_{min} \vert}{\sigma_{max} + \vert\sigma_{min} \vert} \]

with:

\[ \frac{\sigma_{amp}}{\vert \sigma_m \vert} \leq 1, \quad \sigma_{amp} = \frac{\sigma_{max} - \sigma_{min}}{2} \,\land \, \sigma_m = \frac{\sigma_{max} + \sigma_{min}}{2} \]

Parameters:

Name Type Description Default
mean_stress ndarray

The mean stress of the fatigue test (\(\sigma_m\)).

required
stress_amplitude ndarray

The stress amplitude of the fatigue test (\(\sigma_{amp}\)).

required
detail_factor float

mean stress attenuation factor (\(p\)), defaults to 0.8 in welded connections without significant residual stresses.

0.8
plot bool or callable

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

False

Returns:

Type Description
ndarray

The mean stress corrected ranges (\(\Delta \sigma_{corr}\)).

Source code in py_fatigue/mean_stress/corrections.py
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def dnvgl_mean_stress_correction(
    mean_stress: np.ndarray,
    stress_amplitude: np.ndarray,
    detail_factor: float | int = 0.8,
    plot: bool | Callable[[Figure], None] = False,
) -> np.ndarray:
    """Calculates the mean stress correction according to par.
    2.5 of DNVGL-RP-C203, which includes
    an attenuation factor $p$ for the stress ranges if the
    following cases:

    * base material without significant residual stresses \
    $\\rightarrow p = 0.6$. This option neglects fully \
    compressive cycles.
    * welded connections without significant residual stresses \
    $\\rightarrow p = 0.8$. This option multiplies the \
    stress range of fully compressive cycles by p.

    Given that the stress ranges are $\\Delta \\sigma$,
    the corrected stress ranges are:

    $$
    \\Delta \\sigma_{corr} = f_m \\cdot \\Delta \\sigma
    $$

    where:

    $$
    f_m = \\frac{\\sigma_{max} + p \\cdot \\vert \\sigma_{min}
    \\vert}{\\sigma_{max} + \\vert\\sigma_{min} \\vert}
    $$

    with:

    $$
    \\frac{\\sigma_{amp}}{\\vert \\sigma_m \\vert} \\leq 1, \\quad
    \\sigma_{amp} = \\frac{\\sigma_{max} - \\sigma_{min}}{2} \\,\\land
    \\, \\sigma_m = \\frac{\\sigma_{max} + \\sigma_{min}}{2}
    $$

    Parameters
    ----------
    mean_stress : np.ndarray
        The mean stress of the fatigue test ($\\sigma_m$).
    stress_amplitude : np.ndarray
        The stress amplitude of the fatigue test ($\\sigma_{amp}$).
    detail_factor : float, optional
        mean stress attenuation factor ($p$), defaults to 0.8
        in welded connections without significant residual stresses.
    plot : bool or callable, optional
        Use True for a Matplotlib plot or pass a function that receives the
        figure. Defaults to False.

    Returns
    -------
    np.ndarray
        The mean stress corrected ranges
        ($\\Delta \\sigma_{corr}$).
    """

    max_stress = mean_stress + stress_amplitude
    min_stress = mean_stress - stress_amplitude

    f_m = (max_stress + detail_factor * np.abs(min_stress)) / (
        max_stress + np.abs(min_stress)
    )

    f_m[f_m > 1] = 1
    f_m[min_stress > 0] = 1
    if detail_factor == 0.8:
        f_m[f_m < detail_factor] = detail_factor
    elif detail_factor == 0.6:
        f_m[f_m < detail_factor] = 0
    else:
        raise ValueError(
            f"Detail factor = {str(detail_factor)} is not allowed in "
            + "DNVGL-RP-C203. Only 0.6 and 0.8 are permitted."
        )

    stress_range_corr = 2 * f_m * stress_amplitude

    # NOTE: next plot has been included for testing purposes
    if plot:  # pragma: no cover
        # from matplotlib.ticker import MaxNLocator
        fig, axes = make_axes()
        xp, yp = zip(*sorted(zip(min_stress / max_stress, f_m)))
        axes.plot(
            xp,
            yp,
            linestyle=":",
            linewidth=1,
            color="#000000",
            marker=".",
            markersize=6,
            markerfacecolor="#000000",
            markeredgewidth=0.5,
            markeredgecolor="#666666",
        )
        plt.rcParams.update({"mathtext.default": "regular"})

        axes.set_xlabel("load ratio, $\\sigma_{min}/ \\sigma_{max}$")
        axes.set_ylabel("$f_m$")
        axes.spines["right"].set_visible(False)
        axes.spines["top"].set_visible(False)
        axes.set_xlim((-20, 20))
        if callable(plot):
            plot(fig)

    return stress_range_corr

goodman_haigh_mean_stress_correction

goodman_haigh_mean_stress_correction(
    amp_in,
    mean_in,
    r_out,
    ult_s,
    correction_exponent,
    initial_guess=None,
    plot=False,
    logger=None,
)

This function extends the standard Goodman-Haigh correction formula which computes the corrected stress amplitude at zero mean stress (\(R=-1\)) for a given set of input stress amplitudes and mean stresses.

\[ \sigma_{amp, \text{out}} =  \frac{\sigma_{amp, \text{in}}} {1 - \left(\frac{\sigma_{mean, \text{in}}}{\sigma_{ult}} \right)^{n}} \]

The correction exponent \(n\) is a material property that can be obtained from experimental data.

The current implementation extends the standard Goodman-Haigh formula by correcting the stress amplitude from an initial load ratio \(R_{in}\) to any other load ratio \(R_{out}\), as long as the material's ultimate strength is known. The corrected stress amplitude \(\sigma_{amp, \text{out}}\) is computed using the following implicit nonlinear equation:

\[ \sigma_{amp, \text{out}} =  \frac{1}{ \frac{1 - \left( \frac{(1 + R_{\text{in}}) \cdot \sigma_{amp, \text{in}}} {(1 - R_{\text{in}}) \cdot \sigma_{ult}} \right)^{n}}{\sigma_{amp, \text{in}}} + \sigma_{amp, \text{out}}^{n-1} \cdot \left( \frac{(1 + R_{\text{out}})}{(1 - R_{\text{out}}) \cdot \sigma_{ult}} \right)^{n}} \]

where:

  • \(R_{in} = \sigma_{min}/\sigma_{max}\) is the input stress ratio.
  • \(R_{out}\) is the output stress ratio.
  • \(\sigma_{amp,in}\) is the input amplitude.
  • \(\sigma_{amp,out}\) is the output amplitude.
  • \(\sigma_{ult}\) is the ultimate material strength.
  • \(n\) is the correction exponent.

The solver is based on the Newton-Raphson method, which is implemented internally at the native solver, the Newton iteration, and __goodman_equation.

Parameters:

Name Type Description Default
amp_in ndarray | list

Input amplitude values.

required
mean_in ndarray | list

Input mean stress values.

required
r_out float | ndarray

Output stress ratio values.

required
ult_s float

Ultimate strength of the material.

required
correction_exponent float

Mean stress correction exponent (n).

required
plot bool or callable

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

False

Returns:

Type Description
tuple[ndarray, ndarray]

Computed amp_out values, and corresponding mean_out values.

See Also

the native solver, the Newton iteration

Raises:

Type Description
ValueError

If the input arrays have different shapes or if there are negative stress amplitude values in amp_in.

Warning

If the number of points in the input arrays is too large for plotting.

Examples:

>>> import numpy as np
>>> from py_fatigue.mean_stress.corrections import (
...     goodman_haigh_mean_stress_correction
... )
>>> amp_in = np.array([100, 200, 300])
>>> mean_in = np.array([0, 0, 0])
>>> r_out = np.array([-1, 0, 0.5, 0.75, 0.9])
>>> ult_s = 1000
>>> correction_exponent = 9
>>> amp_out, mean_out = goodman_haigh_mean_stress_correction(
...     amp_in, mean_in, r_out, ult_s, correction_exponent, plot=True
... )
Source code in py_fatigue/mean_stress/corrections.py
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
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
def goodman_haigh_mean_stress_correction(  # pylint: disable=R0912,R0915 # noqa: C901,E501
    amp_in: np.ndarray | list[float],
    mean_in: np.ndarray | list[float],
    r_out: float | np.ndarray | list[float],
    ult_s: float,
    correction_exponent: float,
    initial_guess: np.ndarray | None = None,
    plot: bool | Callable[[Figure], None] = False,
    logger: logging.Logger | None = None,
) -> tuple[np.ndarray, np.ndarray]:
    """
    This function extends the standard Goodman-Haigh correction formula which
    computes the corrected stress amplitude at zero mean stress ($R=-1$)
    for a given set of input stress amplitudes and mean stresses.

    $$
    \\sigma_{amp, \\text{out}} =  \\frac{\\sigma_{amp, \\text{in}}}
    {1 - \\left(\\frac{\\sigma_{mean, \\text{in}}}{\\sigma_{ult}}
    \\right)^{n}}
    $$

    The correction exponent $n$ is a material property that can
    be obtained from experimental data.

    The current implementation extends the standard Goodman-Haigh formula by
    correcting the stress amplitude from an initial load ratio $R_{in}$
    to any other load ratio $R_{out}$, as long as the material's
    ultimate strength is known.
    The corrected stress amplitude $\\sigma_{amp, \\text{out}}$ is
    computed using the following implicit nonlinear equation:

    $$
    \\sigma_{amp, \\text{out}} =  \\frac{1}{ \\frac{1 - \\left(
        \\frac{(1 + R_{\\text{in}}) \\cdot \\sigma_{amp, \\text{in}}}
        {(1 - R_{\\text{in}}) \\cdot \\sigma_{ult}}
        \\right)^{n}}{\\sigma_{amp, \\text{in}}}
        + \\sigma_{amp, \\text{out}}^{n-1} \\cdot \\left(
        \\frac{(1 + R_{\\text{out}})}{(1 - R_{\\text{out}})
        \\cdot \\sigma_{ult}} \\right)^{n}}
    $$

    where:

    - $R_{in} = \\sigma_{min}/\\sigma_{max}$ is the input stress ratio.
    - $R_{out}$ is the output stress ratio.
    - $\\sigma_{amp,in}$ is the input amplitude.
    - $\\sigma_{amp,out}$ is the output amplitude.
    - $\\sigma_{ult}$ is the ultimate material strength.
    - $n$ is the correction exponent.

    The solver is based on the Newton-Raphson method, which is implemented
    internally at the native solver,
    the Newton iteration, and
    [`__goodman_equation`][py_fatigue.mean_stress.corrections.__goodman_equation].

    Parameters
    ----------
    amp_in : np.ndarray | list
        Input amplitude values.
    mean_in : np.ndarray | list
        Input mean stress values.
    r_out : float | np.ndarray
        Output stress ratio values.
    ult_s : float
        Ultimate strength of the material.
    correction_exponent : float
        Mean stress correction exponent (n).
    plot : bool or callable, optional
        Use True for a Matplotlib plot or pass a function that receives the
        figure. Defaults to False.

    Returns
    -------
    tuple[np.ndarray, np.ndarray]
        Computed amp_out values, and corresponding mean_out values.

    See Also
    --------
    the native solver,
    the Newton iteration

    Raises
    ------
    ValueError
        If the input arrays have different shapes or if there are negative
        stress amplitude values in amp_in.
    Warning
        If the number of points in the input arrays is too large for plotting.

    Examples
    --------
    >>> import numpy as np
    >>> from py_fatigue.mean_stress.corrections import (
    ...     goodman_haigh_mean_stress_correction
    ... )
    >>> amp_in = np.array([100, 200, 300])
    >>> mean_in = np.array([0, 0, 0])
    >>> r_out = np.array([-1, 0, 0.5, 0.75, 0.9])
    >>> ult_s = 1000
    >>> correction_exponent = 9
    >>> amp_out, mean_out = goodman_haigh_mean_stress_correction(
    ...     amp_in, mean_in, r_out, ult_s, correction_exponent, plot=True
    ... )

    """
    # Convert inputs to numpy arrays for element-wise operations
    if isinstance(amp_in, list):
        amp_in = np.asarray(amp_in, dtype=np.float64)
    if isinstance(mean_in, list):
        mean_in = np.asarray(mean_in, dtype=np.float64)
    if np.isscalar(r_out):
        r_out = np.array([r_out], dtype=np.float64)
    r_out = np.asarray(r_out, dtype=np.float64)
    # Check that the input arrays have the same shape
    if amp_in.shape != mean_in.shape:
        raise ValueError("amp_in and mean_in must have the same shape")
    # Check that all values in amp_in are positive
    if np.any(amp_in < 0):
        raise ValueError("You have negative stress amplitude values in amp_in")
    # Check that, if the product of the size of amp_in and r_out is greater
    # than 1,000,000, the user has set plot to False
    if amp_in.size * r_out.size > 1_000_000 and plot:
        if logger is not None:
            # fmt: off
            logger.warning("\033[1mThe number of points in the input arrays "
                           "is too large for plotting\033[0m")
            logger.info("Setting plot to False to avoid matplotlib errors")
        warnings.warn(
            "The number of points in the input arrays is too large "
            "for plotting. Setting plot to False to avoid "
            "matplotlib errors"
        )

        # fmt: on
        plot = False
    # Compute r_in from amp_in and mean_in
    r_in = (mean_in - amp_in) / (mean_in + amp_in)
    # mean_in = amp_in * (1 + r_in) / (1 - r_in)
    # Initial guess for amp_out set to Goodman Correction for r_out = - 1
    if initial_guess is None:
        initial_guess = amp_in / (1 - (mean_in / ult_s) ** correction_exponent)
    # Set initial guess equal to zero wherever r_in > 1
    initial_guess[r_in > 1] = 0

    # Solve for each amp_out using fsolve
    amp_out = np.zeros((len(r_out), len(initial_guess)))
    mean_out = np.zeros((len(r_out), len(initial_guess)))
    # amp_out = []
    # mean_out = []
    for r_out_val in r_out:
        # NOTE: Special cases for r_out = -1 and r_out = 0
        # NOTE: These cases are solved analytically to improve performance
        # NOTE: The case correction_exponent = 1 is also solved
        #       analytically, as the equation becomes linear in amp_out.
        if r_out_val == -1:
            # amp_out.append(
            #     amp_in / (1 - (mean_in / ult_s) ** correction_exponent)
            # )
            # mean_out.append(np.zeros_like(amp_in))
            amp_out[r_out == -1, :] = amp_in / (
                1 - (mean_in / ult_s) ** correction_exponent
            )
            mean_out[r_out == -1, :] = np.zeros_like(amp_in)
            continue
        if correction_exponent == 1:
            r_in_term = (1 + r_in) / (1 - r_in) * amp_in / ult_s
            r_out_term = (1 + r_out_val) / (1 - r_out_val) / ult_s
            amp_out_fsolve = ((1 - r_in_term) / amp_in + r_out_term) ** -1
            amp_out[r_out == r_out_val, :] = np.clip(amp_out_fsolve, 0.0, ult_s)
            mean_out[r_out == r_out_val, :] = (
                amp_out[r_out == r_out_val, :]
                * (1 + r_out_val)
                / (1 - r_out_val)
            )
            continue
        amp_out_fsolve = []
        for i in range(len(initial_guess)):
            # Solve the implicit equation using fsolve
            # fmt: off
            if mean_in[i] + amp_in[i] > 0:
                sol = solve_goodman(initial_guess[i], amp_in[i], r_in[i],
                                    r_out_val, ult_s, correction_exponent)
                # sol = fsolve(__goodman_equation, x0=initial_guess[i],
                #              args=(amp_in[i], r_in[i], r_out_val, ult_s,
                #                    correction_exponent), xtol=1E-6)
            else:
                sol = amp_in[i]
            # Check if fsolve converged or not
            if sol is None:
                if logger is not None:
                    logger.warning(f"fsolve did not converge for amp_in="
                                   f"{amp_in[i]}, r_in={r_in[i]}, r_out="
                                   f"{r_out_val}")
                amp_out_fsolve.append(np.nan)
            else:
                amp_out_fsolve.append(np.clip(sol, 0.0, ult_s))
            # fmt: on
        # amp_out.append(amp_out_fsolve)
        # mean_out.append(
        #     np.array(amp_out_fsolve) * (1 + r_out_val) / (1 - r_out_val)
        # )
        amp_out[r_out == r_out_val, :] = np.asarray(amp_out_fsolve)
        mean_out[r_out == r_out_val, :] = (
            amp_out[r_out == r_out_val, :] * (1 + r_out_val) / (1 - r_out_val)
        )

    # Sort r_out, as well as amp_out and mean_out (by r_out)
    if np.all(r_out[:-1] <= r_out[1:]):
        srt_r_out = r_out.copy()
        srt_amp_out = amp_out.copy()
        srt_mean_out = mean_out.copy()
    else:
        srt_idx = np.argsort(r_out)
        srt_r_out = r_out[srt_idx]
        srt_amp_out = cast(np.ndarray, amp_out[srt_idx, :])
        srt_mean_out = cast(np.ndarray, mean_out[srt_idx, :])
    if plot:
        # Create figure with two subplots
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

        # First subplot: amp_out vs r_out
        # fmt: off
        for i in range(len(amp_in)):
            ax1.plot(srt_r_out, srt_amp_out[:, i],
                    marker='.', markersize=2, linewidth=0.5,
                    label=f"$amp_{{in}}={np.round(amp_in[i], 1)}, "
                        f"r_{{in}}={np.round(r_in[i], 2)}$")
        ax1.plot(r_in, amp_in,
                'o', color='yellow', markersize=4, markeredgecolor='black',
                markeredgewidth=0.5, label='Original Data')
        ax1.set_xlabel("load ratio, $\\sigma_{min}/ \\sigma_{max}$")
        ax1.set_ylabel("MSC stress amplitude, $\\Delta \\sigma_{MSC} / 2$")
        ax1.set_title("Goodman Correction - Amplitude vs R")
        ax1.set_xlim(right=1.25, left=max(-5, min(r_in) - 0.25))
        ax1.set_ylim(top=min(max(amp_in) * 1.5, ult_s))
        ax1.grid(True)

        # Second subplot: mean_out vs amp_out
        for i in range(len(amp_in)):
            ax2.plot(srt_mean_out[:, i], srt_amp_out[:, i],
                    marker='.', markersize=2, linewidth=0.5,
                    label=f"$amp_{{in}}={np.round(amp_in[i], 1)}, "
                        f"r_{{in}}={np.round(r_in[i], 2)}$")
        # stress_amplitude * (1 + load_ratio) / (1 - load_ratio)
        ax2.plot(amp_in * (1 + r_in) / (1 - r_in), amp_in,
                'o', color='yellow', markersize=4, markeredgecolor='black',
                markeredgewidth=0.5, label='Original Data')

        # Set limits to maximum stress amplitude and ultimate strength
        ax2.set_xlim(right=ult_s * 1.1)
        ax2.set_ylim(top=min(max(amp_in) * 1.5, ult_s))
        # draw lines at constant load ratio for better visualization

        for r in [-0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75]:
            sample_mean_out = np.linspace(0, ult_s * i, 2)
            ax2.plot(sample_mean_out, (1 - r) / (1 + r) * sample_mean_out, ':',
                    color='#AAAAAA', linewidth=0.75)
        ax2.set_xlabel("MSC mean stress, $\\sigma_{m,MSC}$")
        ax2.set_ylabel("MSC stress amplitude, $\\Delta \\sigma_{MSC} / 2$")
        ax2.set_title("Goodman Correction - Amplitude vs Mean")
        handles, labels = ax2.get_legend_handles_labels()
        ax2.grid(False)

        # Adjust layout and show legend
        plt.tight_layout()
        if len(handles) < 31:
            fig.legend(handles, labels, bbox_to_anchor=(0.5, -0.05),
                       loc='upper center', ncol=4)
        # fmt: on
        if callable(plot):
            plot(fig)
        else:
            plt.show()
    return amp_out, mean_out

swt_mean_stress_correction

swt_mean_stress_correction(
    mean_stress, stress_amplitude, plot=False
)

Calculates the mean stress correction according to Smith-Watson-Topper model. It is equivalent to the Walker model with gamma = 0.5.

The correction is given by:

\[ \Delta \sigma_{corr} = \sqrt{\sigma_{max} \cdot \sigma_{amp}} \]

with:

\[ \sigma_{max} = \sigma_{mean} + \sigma_{amp} \]

Parameters:

Name Type Description Default
mean_stress ndarray

The mean stress of the fatigue test (\(\sigma_{mean}\)).

required
stress_amplitude ndarray

The stress amplitude of the fatigue test (\(\sigma_{amp}\)).

required
plot bool or callable

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

False

Returns:

Type Description
ndarray

The mean stress corrected ranges (\(\Delta \sigma_{corr}\)).

Source code in py_fatigue/mean_stress/corrections.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def swt_mean_stress_correction(
    mean_stress: np.ndarray,
    stress_amplitude: np.ndarray,
    plot: bool | Callable[[Figure], None] = False,
) -> np.ndarray:
    """Calculates the mean stress correction according to
    Smith-Watson-Topper model. It is equivalent to the Walker model
    with gamma = 0.5.

    The correction is given by:

    $$
    \\Delta \\sigma_{corr} = \\sqrt{\\sigma_{max} \\cdot \\sigma_{amp}}
    $$

    with:

    $$
    \\sigma_{max} = \\sigma_{mean} + \\sigma_{amp}
    $$

    Parameters
    ----------
    mean_stress : np.ndarray
        The mean stress of the fatigue test ($\\sigma_{mean}$).
    stress_amplitude : np.ndarray
        The stress amplitude of the fatigue test ($\\sigma_{amp}$).
    plot : bool or callable, optional
        Use True for a Matplotlib plot or pass a function that receives the
        figure. Defaults to False.

    Returns
    -------
    np.ndarray
        The mean stress corrected ranges ($\\Delta \\sigma_{corr}$).
    """

    return walker_mean_stress_correction(
        mean_stress, stress_amplitude, gamma=0.5, plot=plot
    )

walker_mean_stress_correction

walker_mean_stress_correction(
    mean_stress, stress_amplitude, gamma=0.5, plot=False
)

Calculates the mean stress correction according to Walker model.

The correction is given by:

\[ \Delta \sigma_{corr} = {\sigma_{max}} ^ {(1 - \gamma)} \, \sigma_{amp} ^ {\gamma} \]

with:

\[ \sigma_{max} = \sigma_{mean} + \sigma_{amp} \]

Parameters:

Name Type Description Default
mean_stress ndarray

The mean stress of the fatigue test (\(\sigma_{mean}\)).

required
stress_amplitude ndarray

The stress amplitude of the fatigue test (\(\sigma_{amp}\)).

required
gamma float

The gamma Walker exponent (\(\gamma\)), defaults to 0.5.

0.5
plot bool or callable

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

False

Returns:

Type Description
ndarray

The mean stress corrected ranges (\(\Delta \sigma_{corr}\)).

Source code in py_fatigue/mean_stress/corrections.py
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def walker_mean_stress_correction(
    mean_stress: np.ndarray,
    stress_amplitude: np.ndarray,
    gamma: float = 0.5,
    plot: bool | Callable[[Figure], None] = False,
) -> np.ndarray:
    """Calculates the mean stress correction according to Walker model.

    The correction is given by:

    $$
    \\Delta \\sigma_{corr} = {\\sigma_{max}} ^ {(1 - \\gamma)} \\,
    \\sigma_{amp} ^ {\\gamma}
    $$

    with:

    $$
    \\sigma_{max} = \\sigma_{mean} + \\sigma_{amp}
    $$

    Parameters
    ----------
    mean_stress : np.ndarray
        The mean stress of the fatigue test ($\\sigma_{mean}$).
    stress_amplitude : np.ndarray
        The stress amplitude of the fatigue test ($\\sigma_{amp}$).
    gamma : float, optional
        The gamma Walker exponent ($\\gamma$), defaults to 0.5.
    plot : bool or callable, optional
        Use True for a Matplotlib plot or pass a function that receives the
        figure. Defaults to False.

    Returns
    -------
    np.ndarray
        The mean stress corrected ranges ($\\Delta \\sigma_{corr}$).
    """

    max_stress = mean_stress + stress_amplitude

    stress_range_corr = np.nan_to_num(
        (max_stress ** (1 - gamma)) * (stress_amplitude**gamma)
    )

    # NOTE: next plot has been included for testing purposes
    if plot:  # pragma: no cover
        # from matplotlib.ticker import MaxNLocator
        fig, axes = make_axes()
        xp, yp = zip(*sorted(zip(2 * stress_amplitude, stress_range_corr)))
        axes.plot(
            xp,
            yp,
            linestyle=":",
            linewidth=1,
            color="#000000",
            marker=".",
            markersize=6,
            markerfacecolor="#000000",
            markeredgewidth=0.5,
            markeredgecolor="#666666",
        )
        plt.rcParams.update({"mathtext.default": "regular"})

        axes.set_xlabel("uncorrected stress range, $\\Delta \\sigma$")
        axes.set_ylabel("MSC stress range, $\\Delta \\sigma_{MSC}$")
        axes.spines["right"].set_visible(False)
        axes.spines["top"].set_visible(False)
        if callable(plot):
            plot(fig)

    return stress_range_corr