Skip to content

trim.py: zero-stripping loops index before the bounds guard, raising IndexError instead of ValueError #88

Description

@lispandfound

Location: source_modelling/trim.py:210

What happens: The final two loops in trim_array_to_target_length index the array before checking the bounds guard:

while slip_function[left] == 0 and left < right:      # :210
    left += 1

while slip_function[right - 1] == 0 and left < right: # :213
    right -= 1

and short-circuits left-to-right, so slip_function[left] is evaluated first. Once left reaches len(slip_function) the index is out of range and the function raises IndexError instead of the documented ValueError.

Why that's wrong: The docstring promises ValueError for exactly this case — trim.py:177-181: "Raises / ValueError / If the array cannot be trimmed to satisfy the target length" — and trim.py:216-217 implements that contract with if left >= right: raise ValueError(...). The all-zero input never reaches line 216 because line 210 blows up first, so callers catching ValueError see an IndexError escape instead.

How to reproduce:

import numpy as np
from source_modelling.trim import trim_array_to_target_length

trim_array_to_target_length(np.zeros((5, 1)), dx=1.0, target_length=1.0)
# IndexError: index 5 is out of bounds for axis 0 with size 5
# expected: ValueError("Cannot trim array to target length")

With an all-zero array keep_threshold == 0.0, so both boundary tests in the main loop pass and the window stays (0, 5); the loop at :210 then walks left from 0 to 5 and indexes off the end. An all-zero slip array is a realistic input for a fault with no resolved slip.

Suggested direction: Swap the operands so the bounds check comes first — while left < right and slip_function[left] == 0: at :210, and while left < right and slip_function[right - 1] == 0: at :213.

Confidence: high

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ai-sweepFiled by an automated /bug-sweep runquestionFurther information is requestedscope:source_modellingSweep scope: source_modelling package

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions