import numpy as np
from scipy.ndimage import label
def dynamic_find_events(matrix, connection_structure):
num_rows, num_cols = matrix.shape
num_events = 0
events = []
# Dynamic programming table to track events at each cell
event_table = np.zeros_like(matrix, dtype=int)
for i in range(num_rows):
for j in range(num_cols):
if matrix[i, j] == 1:
neighbors = []
for dx, dy in connection_structure:
ni, nj = i - dx, j - dy
if 0 <= ni < num_rows and 0 <= nj < num_cols and matrix[ni, nj] == 1:
neighbors.append(event_table[ni, nj])
if not neighbors:
num_events += 1
event_table[i, j] = num_events
events.append([(i, j), (i, j)]) # Start and end indices
else:
min_event = min(neighbors)
event_table[i, j] = min_event
events[min_event - 1][1] = (i, j)
return num_events, events
# Your 2D matrix
data = np.array([
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
])
connection_structure = [(0, 1), (1, 0), (1, 1)]
num_events, events = dynamic_find_events(data, connection_structure)
print(f"Number of events: {num_events}")
for i, event in enumerate(events):
print(f"Event {i + 1}: Start Index {event[0]}, End Index {event[1]}")