You're right to be concerned about the range handling. Let me provide a more precise and efficient solution that properly handles the range calculation and edge cases. Here's an improved version:
import numpy as np
# Load the arrays
scores_10 = np.load('sliding_scores-10-pos.npy')
scores_35 = np.load('sliding_scores-35-pos.npy')
# Initialize the result array
result = np.copy(scores_10)
# Calculate the valid range for each position in scores_10
for i in range(len(scores_10)):
# Calculate the corresponding range in scores_35 (21-27 positions down)
start = i + 21 # 21 positions down from current
end = i + 27 # 27 positions down from current
# Check if the range is valid (within bounds of scores_35)
if start < len(scores_35) and end < len(scores_35):
# Extract the window and find the maximum
window = scores_35[start:end+1] # +1 because end is inclusive
if window.size > 0:
result[i] += np.max(window)
# If out of bounds, keep the original value (no addition)
# Save the result
np.save('sliding_scores-1035max-pos.npy', result)
Key Improvements:
-
Correct Range Calculation:
- Now properly calculates the range as "21-27 positions down" from each position in
scores_10
- Uses
i + 21 to i + 27 (inclusive) for the range in scores_35
-
Better Boundary Handling:
- Explicitly checks if both start and end indices are within bounds
- Only processes valid ranges
-
More Efficient:
- Avoids unnecessary calculations when ranges are invalid
- Uses proper array slicing with
end+1 to include the end index
-
Clearer Logic:
- The code now more directly represents the operation you described
- Comments explain each step clearly
Alternative Vectorized Approach:
If you prefer a more NumPy-optimized solution without explicit loops:
import numpy as np
scores_10 = np.load('sliding_scores-10-pos.npy')
scores_35 = np.load('sliding_scores-35-pos.npy')
# Create an array of max values from the windows
max_values = np.array([np.max(scores_35[i+21:i+28]) if (i+27 < len(scores_35)) else 0
for i in range(len(scores_10))])
# Add to original scores
result = scores_10 + max_values
np.save('sliding_scores-1035max-pos.npy', result)
This version is more concise but might be slightly less readable. The first version is generally preferred for clarity unless performance is critical with very large arrays.