Skip to content

utils

Overview

Shared utilities for fatigue stress arrays, plotting, and numerical calculations.

py_fatigue.utils

The py_fatigue.utils module collects all the utility functions and classes.

Classes

ArrayArray

Bases: NamedTuple

Represents a pair of arrays, namely the mean and range bin edge values

Parameters:

Name Type Description Default
NamedTuple NamedTuple
required
Source code in py_fatigue/utils.py
211
212
213
214
215
216
217
218
219
220
221
class ArrayArray(NamedTuple):  # pragma: no cover
    """Represents a pair of arrays, namely the mean and range bin edge
    values

    Parameters
    ----------
    NamedTuple : NamedTuple
    """

    mean_bin_edges: np.ndarray
    range_bin_edges: np.ndarray

ArrayInt

Bases: NamedTuple

Represents an array and an integer, namely the number of bins for range and mean bin edge values

Parameters:

Name Type Description Default
NamedTuple NamedTuple
required
Source code in py_fatigue/utils.py
237
238
239
240
241
242
243
244
245
246
247
class ArrayInt(NamedTuple):
    """Represents an array and an integer, namely the number of bins
    for range and mean bin edge values

    Parameters
    ----------
    NamedTuple : NamedTuple
    """

    mean_bin_edges: np.ndarray
    range_bin_edges: int

CustomFormatter

Bases: Formatter

Logging Formatter to add colors and count warning / errors

Source code in py_fatigue/utils.py
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
class CustomFormatter(logging.Formatter):
    """Logging Formatter to add colors and count warning / errors"""

    grey = "\033[38m"
    blue = "\033[34m"
    yellow = "\033[33m"
    red = "\033[31m"
    bold = "\033[1m"
    italic = "\033[3m"
    reset = "\033[0m"
    level = "\033[1m%(levelname)-8s → \033[22m"
    lineofile = "\033[3m%(filename)s:%(lineno)d\033[0m - "
    newline = "\n"
    message = "%(message)s"

    FORMATS = {
        logging.DEBUG: grey + "🐞 " + level + italic + message + reset,
        logging.INFO: blue + "ℹ️ " + level + italic + message + reset,
        logging.WARNING: yellow
        + "⚠️ "
        + level
        + newline
        + lineofile
        + italic
        + newline
        + message
        + reset,
        logging.ERROR: red
        + "⛔ "
        + level
        + newline
        + lineofile
        + italic
        + newline
        + message
        + reset,
        logging.CRITICAL: red
        + "🆘 "
        + level
        + newline
        + lineofile
        + bold
        + italic
        + newline
        + message
        + reset,
    }

    def format(self, record):
        log_fmt = self.FORMATS.get(record.levelno)
        formatter = logging.Formatter(log_fmt)
        return formatter.format(record)

FatigueStress dataclass

Fatigue stress class. Mean stress, range, maximum, and minimum can inherit from this class that defines the following properties:

- `bin_edges`: the bin edges for the histogram
- `bin_centers`: the bin centers for the histogram
- `full`: the full cycles
- `full_counts`: the counts of the full cycles
- `half`: the half cycles
- `half_counts`: the counts of the half cycles
- `bins_idx`: the index of the full cycles bins
- `binned_values`: the binned full cycles
Source code in py_fatigue/utils.py
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
@dataclass(repr=False)
class FatigueStress:
    """Fatigue stress class. Mean stress, range, maximum, and minimum
    can inherit from this class that defines the following properties:

        - `bin_edges`: the bin edges for the histogram
        - `bin_centers`: the bin centers for the histogram
        - `full`: the full cycles
        - `full_counts`: the counts of the full cycles
        - `half`: the half cycles
        - `half_counts`: the counts of the half cycles
        - `bins_idx`: the index of the full cycles bins
        - `binned_values`: the binned full cycles
    """

    category: ClassVar[str]
    _counts: np.ndarray
    _values: np.ndarray
    bin_width: float
    _bin_lb: Optional[float] = None
    _bin_ub: Optional[float] = None
    # @properties
    # bin_edges: np.ndarray
    # bin_centers: np.ndarray
    # full: np.ndarray
    # half: np.ndarray
    # half_counts: np.ndarray
    # bins_idx: np.ndarray
    # binned_values: np.ndarray

    def __post_init__(self):
        if len(self._counts) == 0 or len(self._values) == 0:
            raise ValueError("No data provided")
        if len(self._counts) != len(self._values):
            raise ValueError("counts and values must have the same length")
        self._counts = np.asarray(self._counts)
        self._values = np.asarray(self._values)
        if self._bin_lb is None:
            self._bin_lb = (
                round(min(self._values) / self.bin_width) * self.bin_width
                - self.bin_width / 2
            )
        if self._bin_ub is None:
            self._bin_ub = bin_upper_bound(
                self._bin_lb,  # type: ignore
                self.bin_width,
                max(self.full) if len(self.full) > 0 else max(self._values),
            )

    @property
    def bin_lb(self) -> float:
        """The lower bound of the bins. Casting resolves mypy error"""
        return cast(float, self._bin_lb)

    @bin_lb.setter
    def bin_lb(self, value: float) -> None:
        self._bin_lb = value

    @property
    def bin_ub(self) -> float:
        """The upper bound of the bins. Casting resolves mypy error"""
        return cast(float, self._bin_ub)

    @bin_ub.setter
    def bin_ub(self, value: float) -> None:
        self._bin_ub = value

    @property
    def counts(self) -> np.ndarray:
        """The number of cycles.

        Returns
        -------
        counts : np.ndarray
        """
        return self._counts

    # val setter function
    @counts.setter
    def counts(self, val: np.ndarray) -> None:
        """Setter for the counts.

        Parameters
        ----------
        val : np.ndarray
            The new counts.

        Returns
        -------
        counts : np.ndarray
        """
        self._counts = val

    @property
    def values(self) -> np.ndarray:
        """The stress values.

        Returns
        -------
        values : np.ndarray
        """
        return self._values

    # val setter function
    @values.setter
    def values(self, val: np.ndarray) -> None:
        """Setter for the values.

        Parameters
        ----------
        val : np.ndarray
            The new values.
        """
        self._values = val

    @property
    def bin_edges(self) -> np.ndarray:
        """The bin edges.

        Returns
        -------
        bin_edges : np.ndarray
        """
        return calc_bin_edges(self.bin_lb, self.bin_ub, self.bin_width)

    @property
    def bin_centers(self):
        """The bin centers.

        Returns
        -------
        bin_centers : np.ndarray
        """
        return self.bin_edges[:-1] + self.bin_width / 2

    @property
    def full(self):
        """The full cycles stresses.

        Returns
        -------
        full : np.ndarray
        """
        return calc_full_cycles(self.values, self.counts)

    @property
    def half(self):
        """The half cycles stresses.

        Returns
        -------
        half : np.ndarray
        """
        return calc_half_cycles(self.values, self.counts)

    @property
    def bins_idx(self):
        """The index of the full cycles bins.

        Returns
        -------
        bins_idx : np.ndarray
        """
        digitized = np.digitize(self.full, self.bin_edges, right=True)
        digitized[np.where(digitized > 0)] -= 1
        return digitized

    @property
    def binned_values(self):
        """The binned full cycles.

        Returns
        -------
        binned_values : np.ndarray
        """
        return self.bin_centers[self.bins_idx]
Attributes
bin_centers property
bin_centers

The bin centers.

Returns:

Name Type Description
bin_centers ndarray
bin_edges property
bin_edges

The bin edges.

Returns:

Name Type Description
bin_edges ndarray
bin_lb property writable
bin_lb

The lower bound of the bins. Casting resolves mypy error

bin_ub property writable
bin_ub

The upper bound of the bins. Casting resolves mypy error

binned_values property
binned_values

The binned full cycles.

Returns:

Name Type Description
binned_values ndarray
bins_idx property
bins_idx

The index of the full cycles bins.

Returns:

Name Type Description
bins_idx ndarray
counts property writable
counts

The number of cycles.

Returns:

Name Type Description
counts ndarray
full property
full

The full cycles stresses.

Returns:

Name Type Description
full ndarray
half property
half

The half cycles stresses.

Returns:

Name Type Description
half ndarray
values property writable
values

The stress values.

Returns:

Name Type Description
values ndarray

IntArray

Bases: NamedTuple

Represents an integer and an array, namely the number of bins for mean and range bin edge values

Parameters:

Name Type Description Default
NamedTuple NamedTuple
required
Source code in py_fatigue/utils.py
224
225
226
227
228
229
230
231
232
233
234
class IntArray(NamedTuple):
    """Represents an integer and an array, namely the number of bins
    for mean and range bin edge values

    Parameters
    ----------
    NamedTuple : NamedTuple
    """

    mean_bin_nr: int
    range_bin_edges: np.ndarray

IntInt

Bases: NamedTuple

Represents a pair of integers, namely the number of bins for mean and ranges

Parameters:

Name Type Description Default
NamedTuple NamedTuple
required
Source code in py_fatigue/utils.py
198
199
200
201
202
203
204
205
206
207
208
class IntInt(NamedTuple):
    """Represents a pair of integers, namely the number of bins for
    mean and ranges

    Parameters
    ----------
    NamedTuple : NamedTuple
    """

    mean_bin_nr: int
    range_bin_nr: int

TypedArray

Bases: ndarray, Generic[DType]

Wrapper class for numpy arrays that stores and validates type information. This can be used in place of a numpy array, but when used in a pydantic BaseModel or with pydantic.validate_arguments, its dtype will be coerced at runtime to the declared type.

Source code in py_fatigue/utils.py
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
class TypedArray(np.ndarray, Generic[DType]):
    """Wrapper class for numpy arrays that stores and validates type
    information. This can be used in place of a numpy array, but when
    used in a pydantic BaseModel or with pydantic.validate_arguments,
    its dtype will be *coerced* at runtime to the declared type.
    """

    def __new__(cls, input_array: Any, dtype: Optional[np.dtype] = None):
        """Create a new TypedArray viewing the input numpy array."""
        obj = np.array(input_array, dtype=dtype).view(cls)
        return obj

    def __array_finalize__(self, obj):
        # Nothing to finalize for now; keep method for subclassing correctness
        pass

    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, val, field):
        """Validate the value of the field."""
        dtype_field = field.sub_fields[0]  # type: ignore
        actual_dtype = dtype_field.type_.__args__[0]
        # If numpy cannot create an array with the request dtype,
        # an error will be raised and correctly bubbled up.
        np_array = np.array(val, dtype=actual_dtype)
        return np_array
Methods:
__new__
__new__(input_array, dtype=None)

Create a new TypedArray viewing the input numpy array.

Source code in py_fatigue/utils.py
612
613
614
615
def __new__(cls, input_array: Any, dtype: Optional[np.dtype] = None):
    """Create a new TypedArray viewing the input numpy array."""
    obj = np.array(input_array, dtype=dtype).view(cls)
    return obj
validate classmethod
validate(val, field)

Validate the value of the field.

Source code in py_fatigue/utils.py
625
626
627
628
629
630
631
632
633
@classmethod
def validate(cls, val, field):
    """Validate the value of the field."""
    dtype_field = field.sub_fields[0]  # type: ignore
    actual_dtype = dtype_field.type_.__args__[0]
    # If numpy cannot create an array with the request dtype,
    # an error will be raised and correctly bubbled up.
    np_array = np.array(val, dtype=actual_dtype)
    return np_array

Functions:

bin_upper_bound

bin_upper_bound(bin_lower_bound, bin_width, max_val)

Returns the upper bound of the bin edges, given the lower bound, bin width and maximum value of the array. If the maximum value is not a multiple of the bin width, the upper bound is rounded up to the next multiple of the bin width. Also, if the maximum value is smaller than the lower bound, the upper bound is set to the lower bound.

Parameters:

Name Type Description Default
bin_lower_bound float

Left edge of the first bin

required
bin_width float

Bin width

required
max_val float

Maximum value of the array to be binned

required

Returns:

Type Description
float

The upper bound of the bin edges

Source code in py_fatigue/utils.py
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
def bin_upper_bound(
    bin_lower_bound: float, bin_width: float, max_val: float
) -> float:
    """Returns the upper bound of the bin edges, given the lower bound,
    bin width and maximum value of the array. If the maximum value is
    not a multiple of the bin width, the upper bound is rounded up to
    the next multiple of the bin width.
    Also, if the maximum value is smaller than the lower bound, the
    upper bound is set to the lower bound.

    Parameters
    ----------
    bin_lower_bound : float
        Left edge of the first bin
    bin_width : float
        Bin width
    max_val : float
        Maximum value of the array to be binned

    Returns
    -------
    float
        The upper bound of the bin edges
    """
    upper = bin_lower_bound + bin_width * np.ceil(
        (max_val - bin_lower_bound) / bin_width
    )
    return max(upper, bin_lower_bound)

calc_bin_edges

calc_bin_edges(bin_lb, bin_ub, bin_width)

Calculate the bin edges for a fatigue histogram using the given bin width, lower bound and upper bound.

Parameters:

Name Type Description Default
bin_lb float

Lowest bin edge value

required
bin_ub float

Uppest bin edge value

required
bin_width float

Bin width

required

Returns:

Type Description
ndarray

Bin edges

Source code in py_fatigue/utils.py
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
def calc_bin_edges(
    bin_lb: float, bin_ub: float, bin_width: float
) -> np.ndarray:
    """Calculate the bin edges for a fatigue histogram using the given
    bin width, lower bound and upper bound.

    Parameters
    ----------
    bin_lb : float
        Lowest bin edge value
    bin_ub : float
        Uppest bin edge value
    bin_width : float
        Bin width

    Returns
    -------
    np.ndarray
        Bin edges
    """
    bin_ub = bin_upper_bound(bin_lb, bin_width, bin_ub)

    n_bins = int(np.round((bin_ub + bin_width - bin_lb) / bin_width))

    bin_edges = np.around(
        np.linspace(start=bin_lb, stop=bin_ub, num=n_bins),
        decimals=5,
    )
    return bin_edges

calc_full_cycles

calc_full_cycles(stress, count_cycle, debug_mode=False)

Returns the stress ranges or mean stresses from only the full cycles.

Source code in py_fatigue/utils.py
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
def calc_full_cycles(
    stress: np.ndarray, count_cycle: np.ndarray, debug_mode: bool = False
) -> np.ndarray:
    """
    Returns the stress ranges or
    mean stresses from only the full cycles.
    """
    full_idx, _ = split_full_cycles_and_residuals(count_cycle)
    # integer_count = np.delete(count_cycle, half_idx).astype(int)
    integer_count = count_cycle[full_idx].astype(int)
    integer_stress = stress[full_idx]
    if debug_mode:
        print("full cycles idx", full_idx)
        print("count_cycle[full_idx]", integer_count)
        print("stress[full_idx]", integer_stress)
        print("len integer_count", len(integer_count))
        print("len integer_stress", len(integer_stress))
    return np.repeat(integer_stress, integer_count)

calc_half_cycles

calc_half_cycles(stress, count_cycle, debug_mode=False)

Returns the stress ranges or mean stresses from only the half cycles.

Source code in py_fatigue/utils.py
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
def calc_half_cycles(
    stress: np.ndarray, count_cycle: np.ndarray, debug_mode: bool = False
) -> np.ndarray:
    """
    Returns the stress ranges or
    mean stresses from only the half cycles.
    """
    _, half_idx = split_full_cycles_and_residuals(count_cycle)

    half_stress = stress[half_idx]
    if debug_mode:
        half_count = count_cycle[half_idx]
        print("half cycles idx", half_idx)
        print("count_cycle[half_idx]", half_count)
        print("len half_count", len(half_count))
        print("len half_stress", len(half_stress))
    return half_stress

calc_slope_intercept

calc_slope_intercept(x, y)

Given a series of (x, y) knee point coordinates, return the slope and intercept of the line that passes through the knee point and the previous point.

Equation of the line:

\[ y = mx + c \]

where:

  • \(m\) is the slope of the line, calculated as \(\frac{y_2 - y_1}{x_2 - x_1}\)
  • \(c\) is the intercept of the line, calculated as \(\exp(y_2 - m \times x_2)\)

Parameters:

Name Type Description Default
x ArrayLike

The x-coordinates of the knee points.

required
y ArrayLike

The y-coordinates of the knee points.

required

Returns:

Type Description
tuple[ArrayLike, ArrayLike]

The slope and intercept of the line that passes through the knee point and the previous point.

Source code in py_fatigue/utils.py
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
def calc_slope_intercept(
    x: Union[np.ndarray, List[float]],
    y: Union[np.ndarray, List[float]],
) -> tuple[np.ndarray, np.ndarray]:
    """
    Given a series of (x, y) knee point coordinates, return the slope and
    intercept of the line that passes through the knee point and the previous
    point.

    Equation of the line:

    $$
    y = mx + c
    $$

    where:

    * $m$ is the slope of the line, calculated as
      $\\frac{y_2 - y_1}{x_2 - x_1}$
    * $c$ is the intercept of the line, calculated as
      $\\exp(y_2 - m \\times x_2)$

    Parameters
    ----------
    x : ArrayLike
        The x-coordinates of the knee points.
    y : ArrayLike
        The y-coordinates of the knee points.

    Returns
    -------
    tuple[ArrayLike, ArrayLike]
        The slope and intercept of the line that passes through the knee
        point and the previous point.
    """
    assert len(x) == len(y), "x and y must have the same length"
    assert len(x) >= 2, "x and y must have at least two points"
    x = np.sort(np.array(x))
    y = np.array(y)[np.argsort(x)]

    # Check that the y values are strictly increasing
    # assert np.all(np.diff(y) > 0), "x values must be strictly increasing"
    # Find the slope and intercept for each pair of points, meaning that
    # x and y have at least to be of length 2.
    slopes = (y[1:] - y[:-1]) / (x[1:] - x[:-1])  # type: ignore
    intercepts = y[1:] - slopes * x[1:]
    return slopes, intercepts

check_iterable

check_iterable(function)

Decorator checking whether function *args are iterable.

Parameters:

Name Type Description Default
function Callable

Generic function

required

Returns:

Type Description
Callable

Generic function output

Source code in py_fatigue/utils.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def check_iterable(function: Callable) -> Callable:
    """Decorator checking whether function ``*args`` are iterable.

    Parameters
    ----------
    function : Callable
        Generic function

    Returns
    -------
    Callable
        Generic function output
    """

    @wraps(function)
    def wrapper(*args):
        iter_args = []
        for arg in args:
            try:
                iter(arg)
            except TypeError:
                iter_args.append(np.asarray([arg], dtype=float))
            else:
                iter_args.append(np.asarray(arg, dtype=float))
        return function(*iter_args)

    return wrapper

check_str

check_str(function)

Decorator that checks whether a variable is string or NoneType.

Parameters:

Name Type Description Default
function Callable

Input function

required

Returns:

Type Description
Input function output
Source code in py_fatigue/utils.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def check_str(function: Callable) -> Callable:
    """Decorator that checks whether a variable is string or NoneType.

    Parameters
    ----------
    function : Callable
        Input function

    Returns
    -------
    Input function output
    """

    @wraps(function)
    def wrapper(*args):
        str_args = []
        for arg in args:
            str_args.append(str(arg or ""))
        return function(*str_args)

    return wrapper

chunks

chunks(lst, n)

Yield successive n-sized chunks from lst.

Source code in py_fatigue/utils.py
636
637
638
639
def chunks(lst: list[Any], n: int) -> Generator[list[Any], None, None]:
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i : i + n]

compare

compare(a, b)

Compare two objects.

Parameters:

Name Type Description Default
a Any
required
b Any
required

Returns:

Type Description
bool

True if the a and b are equal, False otherwise.

Source code in py_fatigue/utils.py
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
def compare(a: Any, b: Any) -> bool:
    """Compare two objects.

    Parameters
    ----------
    a : Any
    b : Any

    Returns
    -------
    bool
        True if the a and b are equal, False otherwise.
    """
    # print(f"a: {a}, b: {b}")
    if not hasattr(a, "__iter__") or isinstance(a, str):
        return a == b

    try:
        if not len(a) == len(b):
            return False
        if isinstance(a, np.ndarray):
            return np.array_equal(a, b)
        if isinstance(a, dict):
            return all(compare(v, b[k]) for k, v in a.items())
        return all(compare(aa, bb) for aa, bb in zip(a, b))
    except (TypeError, KeyError):
        return False

ensure_array

ensure_array(method)

Ensures that the input variable of a class method is an array.

Parameters:

Name Type Description Default
method Callable

Input method

required

Returns:

Type Description
Callable

Input method output

Source code in py_fatigue/utils.py
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
def ensure_array(method: Callable) -> Callable:
    """Ensures that the input variable of a class method is an array.

    Parameters
    ----------
    method : Callable
        Input method

    Returns
    -------
    Callable
        Input method output
    """

    @wraps(method)
    def wrapper(self, x):
        scalar_input = np.isscalar(x)
        if np.isscalar(x):
            xm = np.array([x])
            result = method(self, xm)
        else:
            xm = np.asarray(x)
            result = method(self, xm)
        if scalar_input and isinstance(result, np.ndarray):
            return _as_scalar_coercible_array(result)
        return result

    return wrapper

inplacify

inplacify(method)

Make a method inplace.

Parameters:

Name Type Description Default
method Callable

The method to make inplace.

required

Returns:

Type Description
Callable

The inplace method.

Source code in py_fatigue/utils.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def inplacify(method: Callable) -> Callable:  # pragma: no cover
    """
    Make a method inplace.

    Parameters
    ----------
    method : Callable
        The method to make inplace.

    Returns
    -------
    Callable
        The inplace method.
    """

    def wrap(self, *args, **kwargs):
        inplace = kwargs.pop("inplace", False)
        if inplace:
            return method(self, *args, **kwargs)
        return method(copy.copy(self), *args, **kwargs)

    return wrap

make_axes

make_axes(fig=None, ax=None)

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

Parameters:

Name Type Description Default
fig Optional[Figure]

The figure instance, by default None

None
ax Optional[Axes]

The axes instance, by default None

None

Returns:

Type Description
tuple

The figure and axes instances

Raises:

Type Description
TypeError

If fig is not a matplotlib.figure.Figure instance

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

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

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

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

py_bisect

py_bisect(fun, a, b, tol, mxiter, *args)

A pure Python implementation of the bisection algorithm that accepts extra arguments.

Source code in py_fatigue/utils.py
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
def py_bisect(fun, a, b, tol, mxiter, *args):
    """
    A pure Python implementation of the bisection algorithm that accepts extra
    arguments.
    """
    # print("Using Python bisection")
    its = 0
    fa = fun(a, *args)
    fb = fun(b, *args)

    if abs(fa) < tol:
        return a
    if abs(fb) < tol:
        return b

    c = (a + b) / 2.0
    fc = fun(c, *args)

    while abs(fc) > tol and its < mxiter:
        its += 1
        if fa * fc < 0:
            b = c
            fb = fc
        else:
            a = c
            fa = fc
        c = (a + b) / 2.0
        fc = fun(c, *args)
    # else:
    #     raise ValueError("The bisection algorithm did not converge")
    # print(f"its: {its}, fa: {fa}, fb: {fb}, fc: {fc}, c: {c}")
    return c

py_newton

py_newton(fun, x0, tol, mxiter, *args)

A pure Python Newton–Raphson implementation that uses finite differences to approximate the derivative.

Source code in py_fatigue/utils.py
725
726
727
728
729
730
731
732
733
734
735
736
737
738
def py_newton(fun, x0, tol, mxiter, *args):
    """
    A pure Python Newton–Raphson implementation that uses finite differences
    to approximate the derivative.
    """
    x = x0
    eps = 1e-6
    for _ in range(mxiter):
        fx = fun(x, *args)
        if abs(fx) < tol:
            return x
        dfx = (fun(x + eps, *args) - fun(x - eps, *args)) / (2.0 * eps)
        x = x - fx / dfx
    return x

split

split(what, by)

Split an integer into a list of integers.

Parameters:

Name Type Description Default
what int

The integer to split

required
by int

The number of integers to split the integer into

required

Returns:

Type Description
list

The list of integers

Examples:

>>> split(5, 2)
[3, 2]
>>> split(20, 7)
[3, 3, 3, 3, 3, 3, 2]
Source code in py_fatigue/utils.py
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
def split(what: int, by: int):
    """Split an integer into a list of integers.

    Parameters
    ----------
    what : int
        The integer to split
    by : int
        The number of integers to split the integer into

    Returns
    -------
    list
        The list of integers

    Examples
    --------
    >>> split(5, 2)
    [3, 2]
    >>> split(20, 7)
    [3, 3, 3, 3, 3, 3, 2]
    """
    return [what // by + 1] * (what % by) + [what // by] * (by - what % by)

split_full_cycles_and_residuals

split_full_cycles_and_residuals(count_cycle)

Returns the stress ranges or mean stresses from only the full cycles.

Source code in py_fatigue/utils.py
492
493
494
495
496
497
498
499
500
501
502
503
504
def split_full_cycles_and_residuals(count_cycle: np.ndarray) -> tuple:
    """
    Returns the stress ranges or
    mean stresses from only the full cycles.
    """

    splt = np.asarray(np.modf(count_cycle)).T
    full_idx = np.where((splt[:, 1] % 1 == 0) & (splt[:, 1] > 0))[0]
    half_idx = np.where((splt[:, 0] == 0.5) & (splt[:, 0] > 0))[0]
    # zero_idx = np.where((splt[:, 0] == 0) & (splt[:, 1] == 0))[0]
    # full_idx = np.sort(np.hstack([full_idx, zero_idx]))
    # half_idx = np.sort(np.hstack([half_idx, zero_idx]))
    return full_idx, half_idx