def despeckle_global(M, positions=None, stds=<NUM_LIT:2>):
N = np.array(M, dtype=np.float64)<EOL>n, m = M.shape<EOL>if positions is None:<EOL><INDENT>positions = range(min(n, m))<EOL><DEDENT>lengths = np.abs(np.diff(positions))<EOL>def distance(i, j):<EOL><INDENT>mean_length = (lengths[i] + lengths[j]) / <NUM_LIT><EOL>if positions[i] < positions[j]:<EOL><INDENT>d = ((positions[j] - positions[i] - lengths[i]) + mean_length) /<NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>d = ((positions[i] - positions[j] - lengths[j]) + mean_length) /<NUM_LIT><EOL><DEDENT>return d<EOL><DEDENT>measurements, bins = {}, []<EOL>for i in range(n):<EOL><INDENT>for j in range(<NUM_LIT:1>, i):<EOL><INDENT>d = distance(i, j)<EOL>bins.append(np.abs(d))<EOL>try:<EOL><INDENT>measurements[np.abs(d)].append(M[i, j])<EOL><DEDENT>except KeyError:<EOL><INDENT>measurements[np.abs(d)] = [M[i, j]]<EOL><DEDENT><DEDENT><DEDENT>mean = [np.mean(np.array(measurements[k])) for k in measurements.keys()]<EOL>std = [np.std(np.array(measurements[k])) for k in measurements.keys()]<EOL>for i, j in itertools.product(range(stds, n - stds),<EOL>range(stds, m - stds)):<EOL><INDENT>d = distance(i, j)<EOL>if M[i, j] >= mean[d] + std * stds:<EOL><INDENT>N[i, j] = mean[d]<EOL><DEDENT><DEDENT>return (N + N.T) / <NUM_LIT:2><EOL>
Compute a trend by averaging all contacts of equal
    distance, then sets outstanding values (above stds standard
    deviations) to the expected value from the trend.