summaryrefslogtreecommitdiff
path: root/utils/raspberrypi/ctt/ctt_alsc.py
blob: 89e86469a78e9c9fac7479f56be0d8adcbf16d47 (plain)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# SPDX-License-Identifier: BSD-2-Clause
#
# Copyright (C) 2019, Raspberry Pi (Trading) Limited
#
# ctt_alsc.py - camera tuning tool for ALSC (auto lens shading correction)

from ctt_image_load import *
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D


"""
preform alsc calibration on a set of images
"""
def alsc_all(Cam, do_alsc_colour, plot):
    imgs_alsc = Cam.imgs_alsc
    """
    create list of colour temperatures and associated calibration tables
    """
    list_col = []
    list_cr = []
    list_cb = []
    list_cg = []
    for Img in imgs_alsc:
        col, cr, cb, cg, size = alsc(Cam, Img, do_alsc_colour, plot)
        list_col.append(col)
        list_cr.append(cr)
        list_cb.append(cb)
        list_cg.append(cg)
        Cam.log += '\n'
    Cam.log += '\nFinished processing images'
    w, h, dx, dy = size
    Cam.log += '\nChannel dimensions: w = {}  h = {}'.format(int(w), int(h))
    Cam.log += '\n16x12 grid rectangle size: w = {} h = {}'.format(dx, dy)

    """
    convert to numpy array for data manipulation
    """
    list_col = np.array(list_col)
    list_cr = np.array(list_cr)
    list_cb = np.array(list_cb)
    list_cg = np.array(list_cg)

    cal_cr_list = []
    cal_cb_list = []

    """
    only do colour calculations if required
    """
    if do_alsc_colour:
        Cam.log += '\nALSC colour tables'
        for ct in sorted(set(list_col)):
            Cam.log += '\nColour temperature: {} K'.format(ct)
            """
            average tables for the same colour temperature
            """
            indices = np.where(list_col == ct)
            ct = int(ct)
            t_r = np.mean(list_cr[indices], axis=0)
            t_b = np.mean(list_cb[indices], axis=0)
            """
            force numbers to be stored to 3dp.... :(
            """
            t_r = np.where((100*t_r) % 1 <= 0.05, t_r+0.001, t_r)
            t_b = np.where((100*t_b) % 1 <= 0.05, t_b+0.001, t_b)
            t_r = np.where((100*t_r) % 1 >= 0.95, t_r-0.001, t_r)
            t_b = np.where((100*t_b) % 1 >= 0.95, t_b-0.001, t_b)
            t_r = np.round(t_r, 3)
            t_b = np.round(t_b, 3)
            r_corners = (t_r[0], t_r[15], t_r[-1], t_r[-16])
            b_corners = (t_b[0], t_b[15], t_b[-1], t_b[-16])
            r_cen = t_r[5*16+7]+t_r[5*16+8]+t_r[6*16+7]+t_r[6*16+8]
            r_cen = round(r_cen/4, 3)
            b_cen = t_b[5*16+7]+t_b[5*16+8]+t_b[6*16+7]+t_b[6*16+8]
            b_cen = round(b_cen/4, 3)
            Cam.log += '\nRed table corners: {}'.format(r_corners)
            Cam.log += '\nRed table centre: {}'.format(r_cen)
            Cam.log += '\nBlue table corners: {}'.format(b_corners)
            Cam.log += '\nBlue table centre: {}'.format(b_cen)
            cr_dict = {
                'ct': ct,
                'table': list(t_r)
            }
            cb_dict = {
                'ct': ct,
                'table': list(t_b)
            }
            cal_cr_list.append(cr_dict)
            cal_cb_list.append(cb_dict)
            Cam.log += '\n'
    else:
        cal_cr_list, cal_cb_list = None, None

    """
    average all values for luminance shading and return one table for all temperatures
    """
    lum_lut = np.mean(list_cg, axis=0)
    lum_lut = np.where((100*lum_lut) % 1 <= 0.05, lum_lut+0.001, lum_lut)
    lum_lut = np.where((100*lum_lut) % 1 >= 0.95, lum_lut-0.001, lum_lut)
    lum_lut = list(np.round(lum_lut, 3))

    """
    calculate average corner for lsc gain calculation further on
    """
    corners = (lum_lut[0], lum_lut[15], lum_lut[-1], lum_lut[-16])
    Cam.log += '\nLuminance table corners: {}'.format(corners)
    l_cen = lum_lut[5*16+7]+lum_lut[5*16+8]+lum_lut[6*16+7]+lum_lut[6*16+8]
    l_cen = round(l_cen/4, 3)
    Cam.log += '\nLuminance table centre: {}'.format(l_cen)
    av_corn = np.sum(corners)/4

    return cal_cr_list, cal_cb_list, lum_lut, av_corn


"""
calculate g/r and g/b for 32x32 points arranged in a grid for a single image
"""
def alsc(Cam, Img, do_alsc_colour, plot=False):
    Cam.log += '\nProcessing image: ' + Img.name
    """
    get channel in correct order
    """
    channels = [Img.channels[i] for i in Img.order]
    """
    calculate size of single rectangle.
    -(-(w-1)//32) is a ceiling division. w-1 is to deal robustly with the case
    where w is a multiple of 32.
    """
    w, h = Img.w/2, Img.h/2
    dx, dy = int(-(-(w-1)//16)), int(-(-(h-1)//12))
    """
    average the green channels into one
    """
    av_ch_g = np.mean((channels[1:2]), axis=0)
    if do_alsc_colour:
        """
        obtain 16x12 grid of intensities for each channel and subtract black level
        """
        g = get_16x12_grid(av_ch_g, dx, dy) - Img.blacklevel_16
        r = get_16x12_grid(channels[0], dx, dy) - Img.blacklevel_16
        b = get_16x12_grid(channels[3], dx, dy) - Img.blacklevel_16
        """
        calculate ratios as 32 bit in order to be supported by medianBlur function
        """
        cr = np.reshape(g/r, (12, 16)).astype('float32')
        cb = np.reshape(g/b, (12, 16)).astype('float32')
        cg = np.reshape(1/g, (12, 16)).astype('float32')
        """
        median blur to remove peaks and save as float 64
        """
        cr = cv2.medianBlur(cr, 3).astype('float64')
        cb = cv2.medianBlur(cb, 3).astype('float64')
        cg = cv2.medianBlur(cg, 3).astype('float64')
        cg = cg/np.min(cg)

        """
        debugging code showing 2D surface plot of vignetting. Quite useful for
        for sanity check
        """
        if plot:
            hf = plt.figure(figsize=(8, 8))
            ha = hf.add_subplot(311, projection='3d')
            """
            note Y is plotted as -Y so plot has same axes as image
            """
            X, Y = np.meshgrid(range(16), range(12))
            ha.plot_surface(X, -Y, cr, cmap=cm.coolwarm, linewidth=0)
            ha.set_title('ALSC Plot\nImg: {}\n\ncr'.format(Img.str))
            hb = hf.add_subplot(312, projection='3d')
            hb.plot_surface(X, -Y, cb, cmap=cm.coolwarm, linewidth=0)
            hb.set_title('cb')
            hc = hf.add_subplot(313, projection='3d')
            hc.plot_surface(X, -Y, cg, cmap=cm.coolwarm, linewidth=0)
            hc.set_title('g')
            # print(Img.str)
            plt.show()

        return Img.col, cr.flatten(), cb.flatten(), cg.flatten(), (w, h, dx, dy)

    else:
        """
        only perform calculations for luminance shading
        """
        g = get_16x12_grid(av_ch_g, dx, dy) - Img.blacklevel_16
        cg = np.reshape(1/g, (12, 16)).astype('float32')
        cg = cv2.medianBlur(cg, 3).astype('float64')
        cg = cg/np.min(cg)

        if plot:
            hf = plt.figure(figssize=(8, 8))
            ha = hf.add_subplot(1, 1, 1, projection='3d')
            X, Y = np.meashgrid(range(16), range(12))
            ha.plot_surface(X, -Y, cg, cmap=cm.coolwarm, linewidth=0)
            ha.set_title('ALSC Plot (Luminance only!)\nImg: {}\n\ncg').format(Img.str)
            plt.show()

        return Img.col, None, None, cg.flatten(), (w, h, dx, dy)


"""
Compresses channel down to a 16x12 grid
"""
def get_16x12_grid(chan, dx, dy):
    grid = []
    """
    since left and bottom border will not necessarily have rectangles of
    dimension dx x dy, the 32nd iteration has to be handled separately.
    """
    for i in range(11):
        for j in range(15):
            grid.append(np.mean(chan[dy*i:dy*(1+i), dx*j:dx*(1+j)]))
        grid.append(np.mean(chan[dy*i:dy*(1+i), 15*dx:]))
    for j in range(15):
        grid.append(np.mean(chan[11*dy:, dx*j:dx*(1+j)]))
    grid.append(np.mean(chan[11*dy:, 15*dx:]))
    """
    return as np.array, ready for further manipulation
    """
    return np.array(grid)


"""
obtains sigmas for red and blue, effectively a measure of the 'error'
"""
def get_sigma(Cam, cal_cr_list, cal_cb_list):
    Cam.log += '\nCalculating sigmas'
    """
    provided colour alsc tables were generated for two different colour
    temperatures sigma is calculated by comparing two calibration temperatures
    adjacent in colour space
    """
    """
    create list of colour temperatures
    """
    cts = [cal['ct'] for cal in cal_cr_list]
    # print(cts)
    """
    calculate sigmas for each adjacent cts and return worst one
    """
    sigma_rs = []
    sigma_bs = []
    for i in range(len(cts)-1):
        sigma_rs.append(calc_sigma(cal_cr_list[i]['table'], cal_cr_list[i+1]['table']))
        sigma_bs.append(calc_sigma(cal_cb_list[i]['table'], cal_cb_list[i+1]['table']))
        Cam.log += '\nColour temperature interval {} - {} K'.format(cts[i], cts[i+1])
        Cam.log += '\nSigma red: {}'.format(sigma_rs[-1])
        Cam.log += '\nSigma blue: {}'.format(sigma_bs[-1])

    """
    return maximum sigmas, not necessarily from the same colour temperature
    interval
    """
    sigma_r = max(sigma_rs) if sigma_rs else 0.005
    sigma_b = max(sigma_bs) if sigma_bs else 0.005
    Cam.log += '\nMaximum sigmas: Red = {} Blue = {}'.format(sigma_r, sigma_b)

    # print(sigma_rs, sigma_bs)
    # print(sigma_r, sigma_b)
    return sigma_r, sigma_b


"""
calculate sigma from two adjacent gain tables
"""
def calc_sigma(g1, g2):
    """
    reshape into 16x12 matrix
    """
    g1 = np.reshape(g1, (12, 16))
    g2 = np.reshape(g2, (12, 16))
    """
    apply gains to gain table
    """
    gg = g1/g2
    if np.mean(gg) < 1:
        gg = 1/gg
    """
    for each internal patch, compute average difference between it and its 4
    neighbours, then append to list
    """
    diffs = []
    for i in range(10):
        for j in range(14):
            """
            note indexing is incremented by 1 since all patches on borders are
            not counted
            """
            diff = np.abs(gg[i+1][j+1]-gg[i][j+1])
            diff += np.abs(gg[i+1][j+1]-gg[i+2][j+1])
            diff += np.abs(gg[i+1][j+1]-gg[i+1][j])
            diff += np.abs(gg[i+1][j+1]-gg[i+1][j+2])
            diffs.append(diff/4)

    """
    return mean difference
    """
    mean_diff = np.mean(diffs)
    return(np.round(mean_diff, 5))
t">&cameraMode, [[maybe_unused]] Metadata *metadata) { /* * We're going to start over with the tables if there's any "significant" * change. */ bool resetTables = firstTime_ || compareModes(cameraMode_, cameraMode); /* Believe the colour temperature from the AWB, if there is one. */ ct_ = getCt(metadata, ct_); /* Ensure the other thread isn't running while we do this. */ waitForAysncThread(); cameraMode_ = cameraMode; /* * We must resample the luminance table like we do the others, but it's * fixed so we can simply do it up front here. */ resampleCalTable(config_.luminanceLut, cameraMode_, luminanceTable_); if (resetTables) { /* * Upon every "table reset", arrange for something sensible to be * generated. Construct the tables for the previous recorded colour * temperature. In order to start over from scratch we initialise * the lambdas, but the rest of this code then echoes the code in * doAlsc, without the adaptive algorithm. */ for (int i = 0; i < XY; i++) lambdaR_[i] = lambdaB_[i] = 1.0; double calTableR[XY], calTableB[XY], calTableTmp[XY]; getCalTable(ct_, config_.calibrationsCr, calTableTmp); resampleCalTable(calTableTmp, cameraMode_, calTableR); getCalTable(ct_, config_.calibrationsCb, calTableTmp); resampleCalTable(calTableTmp, cameraMode_, calTableB); compensateLambdasForCal(calTableR, lambdaR_, asyncLambdaR_); compensateLambdasForCal(calTableB, lambdaB_, asyncLambdaB_); addLuminanceToTables(syncResults_, asyncLambdaR_, 1.0, asyncLambdaB_, luminanceTable_, config_.luminanceStrength); memcpy(prevSyncResults_, syncResults_, sizeof(prevSyncResults_)); framePhase_ = config_.framePeriod; /* run the algo again asap */ firstTime_ = false; } } void Alsc::fetchAsyncResults() { LOG(RPiAlsc, Debug) << "Fetch ALSC results"; asyncFinished_ = false; asyncStarted_ = false; memcpy(syncResults_, asyncResults_, sizeof(syncResults_)); } double getCt(Metadata *metadata, double defaultCt) { AwbStatus awbStatus; awbStatus.temperatureK = defaultCt; /* in case nothing found */ if (metadata->get("awb.status", awbStatus) != 0) LOG(RPiAlsc, Debug) << "no AWB results found, using " << awbStatus.temperatureK; else LOG(RPiAlsc, Debug) << "AWB results found, using " << awbStatus.temperatureK; return awbStatus.temperatureK; } static void copyStats(bcm2835_isp_stats_region regions[XY], StatisticsPtr &stats, AlscStatus const &status) { bcm2835_isp_stats_region *inputRegions = stats->awb_stats; double *rTable = (double *)status.r; double *gTable = (double *)status.g; double *bTable = (double *)status.b; for (int i = 0; i < XY; i++) { regions[i].r_sum = inputRegions[i].r_sum / rTable[i]; regions[i].g_sum = inputRegions[i].g_sum / gTable[i]; regions[i].b_sum = inputRegions[i].b_sum / bTable[i]; regions[i].counted = inputRegions[i].counted; /* (don't care about the uncounted value) */ } } void Alsc::restartAsync(StatisticsPtr &stats, Metadata *imageMetadata) { LOG(RPiAlsc, Debug) << "Starting ALSC calculation"; /* * Get the current colour temperature. It's all we need from the * metadata. Default to the last CT value (which could be the default). */ ct_ = getCt(imageMetadata, ct_); /* * We have to copy the statistics here, dividing out our best guess of * the LSC table that the pipeline applied to them. */ AlscStatus alscStatus; if (imageMetadata->get("alsc.status", alscStatus) != 0) { LOG(RPiAlsc, Warning) << "No ALSC status found for applied gains!"; for (int y = 0; y < Y; y++) for (int x = 0; x < X; x++) { alscStatus.r[y][x] = 1.0; alscStatus.g[y][x] = 1.0; alscStatus.b[y][x] = 1.0; } } copyStats(statistics_, stats, alscStatus); framePhase_ = 0; asyncStarted_ = true; { std::lock_guard<std::mutex> lock(mutex_); asyncStart_ = true; } asyncSignal_.notify_one(); } void Alsc::prepare(Metadata *imageMetadata) { /* * Count frames since we started, and since we last poked the async * thread. */ if (frameCount_ < (int)config_.startupFrames) frameCount_++; double speed = frameCount_ < (int)config_.startupFrames ? 1.0 : config_.speed; LOG(RPiAlsc, Debug) << "frame count " << frameCount_ << " speed " << speed; { std::unique_lock<std::mutex> lock(mutex_); if (asyncStarted_ && asyncFinished_) fetchAsyncResults(); } /* Apply IIR filter to results and program into the pipeline. */ double *ptr = (double *)syncResults_, *pptr = (double *)prevSyncResults_; for (unsigned int i = 0; i < sizeof(syncResults_) / sizeof(double); i++) pptr[i] = speed * ptr[i] + (1.0 - speed) * pptr[i]; /* Put output values into status metadata. */ AlscStatus status; memcpy(status.r, prevSyncResults_[0], sizeof(status.r)); memcpy(status.g, prevSyncResults_[1], sizeof(status.g)); memcpy(status.b, prevSyncResults_[2], sizeof(status.b)); imageMetadata->set("alsc.status", status); } void Alsc::process(StatisticsPtr &stats, Metadata *imageMetadata) { /* * Count frames since we started, and since we last poked the async * thread. */ if (framePhase_ < (int)config_.framePeriod) framePhase_++; if (frameCount2_ < (int)config_.startupFrames) frameCount2_++; LOG(RPiAlsc, Debug) << "frame_phase " << framePhase_; if (framePhase_ >= (int)config_.framePeriod || frameCount2_ < (int)config_.startupFrames) { if (asyncStarted_ == false) restartAsync(stats, imageMetadata); } } void Alsc::asyncFunc() { while (true) { { std::unique_lock<std::mutex> lock(mutex_); asyncSignal_.wait(lock, [&] { return asyncStart_ || asyncAbort_; }); asyncStart_ = false; if (asyncAbort_) break; } doAlsc(); { std::lock_guard<std::mutex> lock(mutex_); asyncFinished_ = true; } syncSignal_.notify_one(); } } void getCalTable(double ct, std::vector<AlscCalibration> const &calibrations, double calTable[XY]) { if (calibrations.empty()) { for (int i = 0; i < XY; i++) calTable[i] = 1.0; LOG(RPiAlsc, Debug) << "no calibrations found"; } else if (ct <= calibrations.front().ct) { memcpy(calTable, calibrations.front().table, XY * sizeof(double)); LOG(RPiAlsc, Debug) << "using calibration for " << calibrations.front().ct; } else if (ct >= calibrations.back().ct) { memcpy(calTable, calibrations.back().table, XY * sizeof(double)); LOG(RPiAlsc, Debug) << "using calibration for " << calibrations.back().ct; } else { int idx = 0; while (ct > calibrations[idx + 1].ct) idx++; double ct0 = calibrations[idx].ct, ct1 = calibrations[idx + 1].ct; LOG(RPiAlsc, Debug) << "ct is " << ct << ", interpolating between " << ct0 << " and " << ct1; for (int i = 0; i < XY; i++) calTable[i] = (calibrations[idx].table[i] * (ct1 - ct) + calibrations[idx + 1].table[i] * (ct - ct0)) / (ct1 - ct0); } } void resampleCalTable(double const calTableIn[XY], CameraMode const &cameraMode, double calTableOut[XY]) { /* * Precalculate and cache the x sampling locations and phases to save * recomputing them on every row. */ int xLo[X], xHi[X]; double xf[X]; double scaleX = cameraMode.sensorWidth / (cameraMode.width * cameraMode.scaleX); double xOff = cameraMode.cropX / (double)cameraMode.sensorWidth; double x = .5 / scaleX + xOff * X - .5; double xInc = 1 / scaleX; for (int i = 0; i < X; i++, x += xInc) { xLo[i] = floor(x); xf[i] = x - xLo[i]; xHi[i] = std::min(xLo[i] + 1, X - 1); xLo[i] = std::max(xLo[i], 0); if (!!(cameraMode.transform & libcamera::Transform::HFlip)) { xLo[i] = X - 1 - xLo[i]; xHi[i] = X - 1 - xHi[i]; } } /* Now march over the output table generating the new values. */ double scaleY = cameraMode.sensorHeight / (cameraMode.height * cameraMode.scaleY); double yOff = cameraMode.cropY / (double)cameraMode.sensorHeight; double y = .5 / scaleY + yOff * Y - .5; double yInc = 1 / scaleY; for (int j = 0; j < Y; j++, y += yInc) { int yLo = floor(y); double yf = y - yLo; int yHi = std::min(yLo + 1, Y - 1); yLo = std::max(yLo, 0); if (!!(cameraMode.transform & libcamera::Transform::VFlip)) { yLo = Y - 1 - yLo; yHi = Y - 1 - yHi; } double const *rowAbove = calTableIn + X * yLo; double const *rowBelow = calTableIn + X * yHi; for (int i = 0; i < X; i++) { double above = rowAbove[xLo[i]] * (1 - xf[i]) + rowAbove[xHi[i]] * xf[i]; double below = rowBelow[xLo[i]] * (1 - xf[i]) + rowBelow[xHi[i]] * xf[i]; *(calTableOut++) = above * (1 - yf) + below * yf; } } } /* Calculate chrominance statistics (R/G and B/G) for each region. */ static_assert(XY == AWB_REGIONS, "ALSC/AWB statistics region mismatch"); static void calculateCrCb(bcm2835_isp_stats_region *awbRegion, double cr[XY], double cb[XY], uint32_t minCount, uint16_t minG) { for (int i = 0; i < XY; i++) { bcm2835_isp_stats_region &zone = awbRegion[i]; if (zone.counted <= minCount || zone.g_sum / zone.counted <= minG) { cr[i] = cb[i] = InsufficientData; continue; } cr[i] = zone.r_sum / (double)zone.g_sum; cb[i] = zone.b_sum / (double)zone.g_sum; } } static void applyCalTable(double const calTable[XY], double C[XY]) { for (int i = 0; i < XY; i++) if (C[i] != InsufficientData) C[i] *= calTable[i]; } void compensateLambdasForCal(double const calTable[XY], double const oldLambdas[XY], double newLambdas[XY]) { double minNewLambda = std::numeric_limits<double>::max(); for (int i = 0; i < XY; i++) { newLambdas[i] = oldLambdas[i] * calTable[i]; minNewLambda = std::min(minNewLambda, newLambdas[i]); } for (int i = 0; i < XY; i++) newLambdas[i] /= minNewLambda; } [[maybe_unused]] static void printCalTable(double const C[XY]) { printf("table: [\n"); for (int j = 0; j < Y; j++) { for (int i = 0; i < X; i++) { printf("%5.3f", 1.0 / C[j * X + i]); if (i != X - 1 || j != Y - 1) printf(","); } printf("\n"); } printf("]\n"); } /* * Compute weight out of 1.0 which reflects how similar we wish to make the * colours of these two regions. */ static double computeWeight(double Ci, double Cj, double sigma) { if (Ci == InsufficientData || Cj == InsufficientData) return 0; double diff = (Ci - Cj) / sigma; return exp(-diff * diff / 2); } /* Compute all weights. */ static void computeW(double const C[XY], double sigma, double W[XY][4]) { for (int i = 0; i < XY; i++) { /* Start with neighbour above and go clockwise. */ W[i][0] = i >= X ? computeWeight(C[i], C[i - X], sigma) : 0; W[i][1] = i % X < X - 1 ? computeWeight(C[i], C[i + 1], sigma) : 0; W[i][2] = i < XY - X ? computeWeight(C[i], C[i + X], sigma) : 0; W[i][3] = i % X ? computeWeight(C[i], C[i - 1], sigma) : 0; } } /* Compute M, the large but sparse matrix such that M * lambdas = 0. */ static void constructM(double const C[XY], double const W[XY][4], double M[XY][4]) { double epsilon = 0.001; for (int i = 0; i < XY; i++) { /* * Note how, if C[i] == INSUFFICIENT_DATA, the weights will all * be zero so the equation is still set up correctly. */ int m = !!(i >= X) + !!(i % X < X - 1) + !!(i < XY - X) + !!(i % X); /* total number of neighbours */ /* we'll divide the diagonal out straight away */ double diagonal = (epsilon + W[i][0] + W[i][1] + W[i][2] + W[i][3]) * C[i]; M[i][0] = i >= X ? (W[i][0] * C[i - X] + epsilon / m * C[i]) / diagonal : 0; M[i][1] = i % X < X - 1 ? (W[i][1] * C[i + 1] + epsilon / m * C[i]) / diagonal : 0; M[i][2] = i < XY - X ? (W[i][2] * C[i + X] + epsilon / m * C[i]) / diagonal : 0; M[i][3] = i % X ? (W[i][3] * C[i - 1] + epsilon / m * C[i]) / diagonal : 0; } } /* * In the compute_lambda_ functions, note that the matrix coefficients for the * left/right neighbours are zero down the left/right edges, so we don't need * need to test the i value to exclude them. */ static double computeLambdaBottom(int i, double const M[XY][4], double lambda[XY]) { return M[i][1] * lambda[i + 1] + M[i][2] * lambda[i + X] + M[i][3] * lambda[i - 1]; } static double computeLambdaBottomStart(int i, double const M[XY][4], double lambda[XY]) { return M[i][1] * lambda[i + 1] + M[i][2] * lambda[i + X]; } static double computeLambdaInterior(int i, double const M[XY][4], double lambda[XY]) { return M[i][0] * lambda[i - X] + M[i][1] * lambda[i + 1] +