forked from thearn/maximum-submatrix-sum
/
algorithms.py
78 lines (68 loc) · 2.38 KB
/
algorithms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
from scipy.signal import fftconvolve as conv
import numpy as np
import itertools
import time
def local_search(A, loc):
"""
Utility function to verify local optimality of a
subarray slice specification 'loc' of array 'A'
Checks the sum of all subarrays generated by perturbing each
index by 1 in value
Needed due to indeterminacy of precise indices corresponding
to maximization of the convolution operation
"""
r1, r2, c1, c2 = loc[0].start, loc[0].stop, loc[1].start, loc[1].stop
mx = A[loc].sum()
for i, j, k, l in itertools.product([-1, 0, 1], repeat=4):
loc_ = (slice(r1 + i, r2 + j), slice(c1 + k, c2 + l))
val = A[loc_].sum()
if val >= mx:
mx = val
loc2 = loc_
return loc2, mx
def brute_submatrix_max(A):
"""
Searches for the rectangular subarray of A with maximum sum
Uses brute force searching
"""
M, N = A.shape
t0 = time.time()
this_location, max_value = ((0, 0), (0, 0)), 0
for m, n in itertools.product(xrange(M), xrange(N)):
for i, k in itertools.product(xrange(M - m + 1), xrange(N - n + 1)):
this_location = (slice(i, i + m), slice(k, k + n))
value = A[this_location].sum()
if value >= max_value:
max_value = value
location = this_location
t = time.time() - t0
return location, max_value, t
def fft_submatrix_max(A):
"""
Searches for the rectangular subarray of A with maximum sum
Uses FFT-based convolution operations
"""
M, N = A.shape
this_location, max_value = ((0, 0), (0, 0)), 0
t0 = time.time()
for m, n in itertools.product(xrange(2, M), xrange(2, N)):
convolved = conv(A, np.ones((m, n)), mode='same')
row, col = np.unravel_index(convolved.argmax(), convolved.shape)
# index offsets for odd dimension length:
if m % 2 == 1:
m_off = 1
else:
m_off = 0
if n % 2 == 1:
n_off = 1
else:
n_off = 0
this_location = (
slice(row - m / 2, row + m / 2 + m_off), slice(col - n / 2, col + n / 2 + n_off))
value = A[this_location].sum()
if value >= max_value:
max_value = value
location = this_location
location, max_value = local_search(A, location)
t = time.time() - t0
return location, max_value, t