kat_knm_mirror.c 81.2 KB
Newer Older
1 2 3
#include "kat.h"
#include "kat_inline.c"
#include "kat_io.h"
4
#include "kat_mem.h"
5 6 7 8 9
#include "kat_fortran.h"
#include "kat_optics.h"
#include "kat_aux.h"
#include "kat_dump.h"
#include "kat_check.h"
10
#include "kat_aa.h"
11
#include "kat_knm_int.h"
12
#include "kat_knm_mirror.h"
13
#include "kat_knm_aperture.h"
Daniel Brown's avatar
Daniel Brown committed
14
#if INCLUDE_CUBA == 1
15
#include "cuba.h"
Daniel Brown's avatar
Daniel Brown committed
16
#endif
17
#include <gsl/gsl_cblas.h>
18 19 20 21 22 23

extern init_variables_t init;
extern interferometer_t inter;
extern options_t options;
extern local_var_t vlocal;
extern FILE *fp_log;
24

Daniel Brown's avatar
Daniel Brown committed
25
mirror_knm_t mrtmap;
26

27
extern FILE * ipfile, * idfile;
28 29 30 31 32 33

extern const complex_t complex_i; //!< sqrt(-1) or 0 + i
extern const complex_t complex_1; //!< 1 but in complex space: 1 + 0i
extern const complex_t complex_m1; //!< -1 but in complex space: -1 + 0i
extern const complex_t complex_0; //!< 0 but in complex space: 0 + 0i

34 35 36 37
static u_nm_accel_t *acc_11_nr1_1, *acc_11_nr1_2;
static u_nm_accel_t *acc_22_nr2_1, *acc_22_nr2_2;
static u_nm_accel_t *acc_21_nr2_1, *acc_21_nr1_2;
static u_nm_accel_t *acc_12_nr1_1, *acc_12_nr2_2;
38

Daniel Brown's avatar
Daniel Brown committed
39
void alloc_knm_accel_mirror_mem(long *bytes) {
40

41
    // need to pick out the maximum number order for allocating memory
Daniel Brown's avatar
Daniel Brown committed
42
    int max_m=mem.hg_mode_order, max_n=mem.hg_mode_order;
43

Daniel Brown's avatar
Daniel Brown committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    // make sure they are null before allocating new memory
    assert(acc_11_nr1_1 == NULL);
    assert(acc_11_nr1_2 == NULL);
    assert(acc_12_nr1_1 == NULL);
    assert(acc_12_nr2_2 == NULL);
    assert(acc_21_nr2_1 == NULL);
    assert(acc_21_nr1_2 == NULL);
    assert(acc_22_nr2_1 == NULL);
    assert(acc_22_nr2_2 == NULL);

    // allocate memory for all the accelerators
    acc_11_nr1_1 = u_nm_accel_alloc(max_n, max_m, bytes);
    acc_11_nr1_2 = u_nm_accel_alloc(max_n, max_m, bytes);
    acc_22_nr2_1 = u_nm_accel_alloc(max_n, max_m, bytes);
    acc_22_nr2_2 = u_nm_accel_alloc(max_n, max_m, bytes);
    acc_12_nr1_1 = u_nm_accel_alloc(max_n, max_m, bytes);
    acc_12_nr2_2 = u_nm_accel_alloc(max_n, max_m, bytes);
    acc_21_nr2_1 = u_nm_accel_alloc(max_n, max_m, bytes);
    acc_21_nr1_2 = u_nm_accel_alloc(max_n, max_m, bytes);
63 64
}

Daniel Brown's avatar
Daniel Brown committed
65 66
void mirror_knm_free(mirror_knm_t* knm) {
    assert(knm != NULL);
67

Daniel Brown's avatar
Daniel Brown committed
68
    if (!IS_MIRROR_KNM_ALLOCD(knm))
69 70
        bug_error("We have tried to free memory that has not been allocated");

71
    int num_fields = mem.num_fields;
72 73 74
    int field_index;

    for (field_index = 0; field_index < num_fields; field_index++) {
Daniel Brown's avatar
Daniel Brown committed
75 76 77 78
        free(knm->k11[field_index]);
        free(knm->k12[field_index]);
        free(knm->k21[field_index]);
        free(knm->k22[field_index]);
79
        // remembering to NULL any loose pointers...
Daniel Brown's avatar
Daniel Brown committed
80 81 82 83
        knm->k11[field_index] = NULL;
        knm->k21[field_index] = NULL;
        knm->k12[field_index] = NULL;
        knm->k22[field_index] = NULL;
84 85
    }

Daniel Brown's avatar
Daniel Brown committed
86 87 88 89
    free(knm->k11);
    free(knm->k12);
    free(knm->k21);
    free(knm->k22);
90

Daniel Brown's avatar
Daniel Brown committed
91 92 93 94
    knm->k11 = NULL;
    knm->k21 = NULL;
    knm->k12 = NULL;
    knm->k22 = NULL;
95 96
}

Daniel Brown's avatar
Daniel Brown committed
97 98 99
void mirror_knm_alloc(mirror_knm_t* knm, long *bytes) {
    if (knm == NULL)
        bug_error("mirror_knm_t pointer is nulled");
100

Daniel Brown's avatar
Daniel Brown committed
101 102
    if (IS_MIRROR_KNM_ALLOCD(knm))
        bug_error("We have tried to allocate memory to a mirror_knm when it is already allocated, that or we have not initialised the pointers to be NULL");
103

104 105 106 107
    allocate_zmatrix(&knm->k11, mem.num_fields, bytes);
    allocate_zmatrix(&knm->k12, mem.num_fields, bytes);
    allocate_zmatrix(&knm->k21, mem.num_fields, bytes);
    allocate_zmatrix(&knm->k22, mem.num_fields, bytes);
108 109 110 111
}

// multiply A*B then put result in new matrix

Daniel Brown's avatar
Daniel Brown committed
112
void mirror_knm_matrix_mult(mirror_knm_t* A, mirror_knm_t* B, mirror_knm_t *result) {
113 114 115 116 117 118 119 120 121
    assert(result != NULL && A != NULL && B != NULL);
    assert(result->k11 != NULL && A->k11 != NULL && B->k11 != NULL);
    assert(result->k12 != NULL && A->k12 != NULL && B->k12 != NULL);
    assert(result->k21 != NULL && A->k21 != NULL && B->k21 != NULL);
    assert(result->k22 != NULL && A->k22 != NULL && B->k22 != NULL);

    int num_fields = (int) (inter.tem + 1) * (inter.tem + 2) / 2;
    int l, n, m;

Daniel Brown's avatar
Daniel Brown committed
122
    mirror_knm_t *tmp;
123 124 125 126

    // if A or B are just identity matrices then just copy them into result
    if (A->IsIdentities) {
        if (B != result)
Daniel Brown's avatar
Daniel Brown committed
127
            mirror_knm_matrix_copy(B, result);
128 129 130

    } else if (B->IsIdentities) {
        if (A != result)
Daniel Brown's avatar
Daniel Brown committed
131
            mirror_knm_matrix_copy(A, result);
132 133 134 135 136

    } else {
        // if result != A | B then no need to use a temporary matrix to store result 
        // just bung it in the result matrix
        if ((result == A) || (result == B))
Daniel Brown's avatar
Daniel Brown committed
137
            tmp = &mrtmap;
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
        else
            tmp = result;

        for (n = 0; n < num_fields; n++) {
            for (m = 0; m < num_fields; m++) {
                // initialise to 0 here just incase some other data is there
                tmp->k11[n][m] = complex_0;
                tmp->k12[n][m] = complex_0;
                tmp->k21[n][m] = complex_0;
                tmp->k22[n][m] = complex_0;

                for (l = 0; l < num_fields; l++) {
                    tmp->k11[n][m] = z_pl_z(tmp->k11[n][m], z_by_z(A->k11[n][l], B->k11[l][m]));
                    tmp->k12[n][m] = z_pl_z(tmp->k12[n][m], z_by_z(A->k12[n][l], B->k12[l][m]));
                    tmp->k21[n][m] = z_pl_z(tmp->k21[n][m], z_by_z(A->k21[n][l], B->k21[l][m]));
                    tmp->k22[n][m] = z_pl_z(tmp->k22[n][m], z_by_z(A->k22[n][l], B->k22[l][m]));
                }
            }
        }

        if ((result == A) || (result == B))
Daniel Brown's avatar
Daniel Brown committed
159
            mirror_knm_matrix_copy(&mrtmap, result);
160 161 162 163 164
    }
}

// Should copy one matrix into another

Daniel Brown's avatar
Daniel Brown committed
165
void mirror_knm_matrix_copy(mirror_knm_t* src, mirror_knm_t* dest) {
166 167 168 169 170
    assert(src != NULL);
    assert(dest != NULL);

    int num_fields = (int) (inter.tem + 1) * (inter.tem + 2) / 2;
    int i;
Daniel Brown's avatar
Daniel Brown committed
171 172 173 174 175 176 177 178 179 180
    
    assert(dest->k11 != NULL);
    assert(dest->k12 != NULL);
    assert(dest->k21 != NULL);
    assert(dest->k22 != NULL);
    assert(src->k11 != NULL);
    assert(src->k12 != NULL);
    assert(src->k21 != NULL);
    assert(src->k22 != NULL);
    
181 182 183 184 185 186 187 188 189 190
    for (i = 0; i < num_fields; i++) {
        memcpy(dest->k11[i], src->k11[i], num_fields * sizeof (complex_t));
        memcpy(dest->k12[i], src->k12[i], num_fields * sizeof (complex_t));
        memcpy(dest->k21[i], src->k21[i], num_fields * sizeof (complex_t));
        memcpy(dest->k22[i], src->k22[i], num_fields * sizeof (complex_t));
    }
}

// sets matrix to identity matrix

Daniel Brown's avatar
Daniel Brown committed
191
void mirror_knm_matrix_ident(mirror_knm_t* M) {
192
    assert(M != NULL);
193
    
194 195 196 197 198 199 200 201 202 203 204 205 206 207
    int i;
    
    // zero the matrices, this can be done in a memset call because
    // knm matrices are stored in a 1D array
    memset(&(M->k11[0][0]), 0, inter.num_fields * inter.num_fields * sizeof(complex_t));
    memset(&(M->k12[0][0]), 0, inter.num_fields * inter.num_fields * sizeof(complex_t));
    memset(&(M->k21[0][0]), 0, inter.num_fields * inter.num_fields * sizeof(complex_t));
    memset(&(M->k22[0][0]), 0, inter.num_fields * inter.num_fields * sizeof(complex_t));
    
    for (i = 0; i < inter.num_fields; i++) {
        M->k11[i][i] = complex_1;
        M->k12[i][i] = complex_1;
        M->k21[i][i] = complex_1;
        M->k22[i][i] = complex_1;
208 209 210
    }
}

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
bool knm_q_cmp(mirror_knm_q_t *q1, mirror_knm_q_t *q2) {
   if(!ceq(q1->qxt1_11, q2->qxt1_11)) return false;
   if(!ceq(q1->qxt1_12, q2->qxt1_12)) return false;
   if(!ceq(q1->qxt1_21, q2->qxt1_21)) return false;
   if(!ceq(q1->qxt1_22, q2->qxt1_22)) return false;
   if(!ceq(q1->qxt2_11, q2->qxt2_11)) return false;
   if(!ceq(q1->qxt2_12, q2->qxt2_12)) return false;
   if(!ceq(q1->qxt2_21, q2->qxt2_21)) return false;
   if(!ceq(q1->qxt2_22, q2->qxt2_22)) return false;
   if(!ceq(q1->qyt1_11, q2->qyt1_11)) return false;
   if(!ceq(q1->qyt1_12, q2->qyt1_12)) return false;
   if(!ceq(q1->qyt1_21, q2->qyt1_21)) return false;
   if(!ceq(q1->qyt1_22, q2->qyt1_22)) return false;
   if(!ceq(q1->qyt2_11, q2->qyt2_11)) return false;
   if(!ceq(q1->qyt2_12, q2->qyt2_12)) return false;
   if(!ceq(q1->qyt2_21, q2->qyt2_21)) return false;
   if(!ceq(q1->qyt2_22, q2->qyt2_22)) return false;
   
   return true;
}

232 233 234
/** q values passed to this should have been turned depending on the direction of
 *  incoming and outgoing beam
 */ 
Daniel Brown's avatar
Daniel Brown committed
235
void calculate_mirror_qt_qt2(KNM_MIRROR_NODE_DIRECTION_t KNM, mirror_knm_q_t *knm_q, complex_t qx1,
236 237 238 239 240 241 242
        complex_t qy1, complex_t qx2, complex_t qy2, double nr1, double nr2, int n1idx, int n2idx, int cidx) {

    ABCD_t trans1;

    switch (KNM) {
        case MR11:
            component_matrix(&trans1, cidx, n1idx, n1idx, TANGENTIAL);
Daniel Brown's avatar
Daniel Brown committed
243
            knm_q->qxt1_11 = q1_q2(trans1, qx1, nr1, nr1);
244
            component_matrix(&trans1, cidx, n1idx, n1idx, SAGITTAL);
Daniel Brown's avatar
Daniel Brown committed
245 246 247
            knm_q->qyt1_11 = q1_q2(trans1, qy1, nr1, nr1);
            knm_q->qxt2_11 = cminus(cconj(qx1));
            knm_q->qyt2_11 = cminus(cconj(qy1));
248 249 250
            break;
        case MR22:
            component_matrix(&trans1, cidx, n2idx, n2idx, TANGENTIAL);
Daniel Brown's avatar
Daniel Brown committed
251
            knm_q->qxt1_22 = q1_q2(trans1, cminus(cconj(qx2)), nr2, nr2);
252
            component_matrix(&trans1, cidx, n2idx, n2idx, SAGITTAL);
Daniel Brown's avatar
Daniel Brown committed
253 254 255
            knm_q->qyt1_22 = q1_q2(trans1, cminus(cconj(qy2)), nr2, nr2);
            knm_q->qxt2_22 = qx2;
            knm_q->qyt2_22 = qy2;
256 257 258
            break;
        case MR12:
            component_matrix(&trans1, cidx, n1idx, n2idx, TANGENTIAL);
Daniel Brown's avatar
Daniel Brown committed
259
            knm_q->qxt1_12 = q1_q2(trans1, qx1, nr1, nr2);
260
            component_matrix(&trans1, cidx, n1idx, n2idx, SAGITTAL);
Daniel Brown's avatar
Daniel Brown committed
261 262 263
            knm_q->qyt1_12 = q1_q2(trans1, qy1, nr1, nr2);
            knm_q->qxt2_12 = qx2;
            knm_q->qyt2_12 = qy2;
264 265 266
            break;
        case MR21:
            component_matrix(&trans1, cidx, n2idx, n1idx, TANGENTIAL);
Daniel Brown's avatar
Daniel Brown committed
267
            knm_q->qxt1_21 = q1_q2(trans1, cminus(cconj(qx2)), nr2, nr1);
268
            component_matrix(&trans1, cidx, n2idx, n1idx, SAGITTAL);
Daniel Brown's avatar
Daniel Brown committed
269 270 271
            knm_q->qyt1_21 = q1_q2(trans1, cminus(cconj(qy2)), nr2, nr1);
            knm_q->qxt2_21 = cminus(cconj(qx1));
            knm_q->qyt2_21 = cminus(cconj(qy1));
272 273 274 275 276 277
            break;
        default:
            bug_error("calculate_qt_qt2 cannot handle a KNM value of %i\n", KNM);
    }
}

278
void calc_mirror_limit_ws(double *wx1,double *wx2,double *wy1,double *wy2, KNM_MIRROR_NODE_DIRECTION_t knum, mr_knm_map_int_params_t *p){
Daniel Brown's avatar
Daniel Brown committed
279
    mirror_knm_q_t *kq = p->knm_q;
280 281 282 283
    
    switch(knum){
        case MR11:
            *wx1 = w_size(kq->qxt1_11, p->nr1);
284 285
            *wx2 = w_size(kq->qxt2_11, p->nr1);            
            *wy1 = w_size(kq->qyt1_11, p->nr1);
286 287 288 289
            *wy2 = w_size(kq->qyt2_11, p->nr1);
            break;
        case MR12:
            *wx1 = w_size(kq->qxt1_12, p->nr1);
290 291
            *wx2 = w_size(kq->qxt2_12, p->nr2);            
            *wy1 = w_size(kq->qyt1_12, p->nr1);
292 293 294 295
            *wy2 = w_size(kq->qyt2_12, p->nr2);
            break;
        case MR21:
            *wx1 = w_size(kq->qxt1_21, p->nr2);
296 297
            *wx2 = w_size(kq->qxt2_21, p->nr1);            
            *wy1 = w_size(kq->qyt1_21, p->nr2);
298 299 300 301
            *wy2 = w_size(kq->qyt2_21, p->nr1);
            break;
        case MR22:
            *wx1 = w_size(kq->qxt1_22, p->nr2);
302 303
            *wx2 = w_size(kq->qxt2_22, p->nr2);            
            *wy1 = w_size(kq->qyt1_22, p->nr2);
304 305 306 307 308
            *wy2 = w_size(kq->qyt2_22, p->nr2);
            break;
    }
}

309
/**
Daniel Brown's avatar
Daniel Brown committed
310
 * Returns true of false depending on if the aperture knm should be integrated or not
311 312 313 314 315 316
 * 
 * @param mirror mirror component
 * @param mismatch whether mismatch present
 * @param astigmatism whether beam is astigmatic
 * @return True or false depending on if the aperture should be integrated or analytically calculated
 */
Daniel Brown's avatar
Daniel Brown committed
317
bool should_integrate_mirror_aperture_knm(mirror_t *mirror, int mismatch, int astigmatism) {
Daniel Brown's avatar
Daniel Brown committed
318
    
319 320 321 322
    //check if an aperture has even been defined
    if (mirror->r_aperture > 0) {
        // check if we should integrate the aperture coupling coefficients rather
        // than computing them analytically
Daniel Brown's avatar
Daniel Brown committed
323
        if (mirror->knm_flags & INT_APERTURE || astigmatism || mismatch) {
324 325 326

            // if using any of the Riemann methods, these currently do not support 
            // aperture integration without using a map
327
            if ((init.mapintmethod == RIEMANN_SUM_NEW) || (init.mapintmethod == NEWTON_COTES)) {
328
                
329 330 331 332 333
                if(mirror->map_merged.usermessages & APERTURE_RIEMANN ) {
                    warn("Aperture calculation using Riemann integrators is not currently supported.\n"
                         "   Please use an aperture map or a Cuba integrating routine.\n");
                    mirror->map_merged.usermessages |= APERTURE_RIEMANN;
                }              
334
                                
335 336 337 338 339 340 341 342 343
                // return false as with these methods no aperture coupling coefficient
                // can be integrated.
                return false;
            } else {
                return true;
            }

        } else {
            // otherwise we need to calculate the aperture coupling coefficient matrix here analytically
344 345
            if(!(mirror->map_merged.usermessages & APERTURE_NO_ANALYTIC )&& mirror->aperture_type == CIRCULAR){
                warn("Analytic circular aperture coupling coefficient calculation not completely implemented yet, becareful!\n");
346 347 348 349 350
                mirror->map_merged.usermessages |= APERTURE_NO_ANALYTIC;
            }

            if (inter.debug && !options.quiet)
               message("* Calculating aperture Knm analytically\n");
351
            
352
            // return false to state that no aperture integration is needed
Daniel Brown's avatar
Daniel Brown committed
353
            // as we have done it analytically
354 355 356 357 358 359 360
            return false;
        }
    }

    return false;
}

361
void check_mirror_knm_mismatch_astig(bitflag knm_calc_flags, mirror_knm_q_t *knm_q, bitflag *mismatch, bitflag *astigmatism){
362 363
    // calculate the individual q values for each KNM and if we should even
    // bother calculating them    
364 365
    if ((knm_calc_flags & MR11Calc) == MR11Calc){
        if (!ceq(knm_q->qxt1_11, knm_q->qxt2_11)
366
                || !ceq(knm_q->qyt1_11, knm_q->qyt2_11)) {
367
            *mismatch = *mismatch | 1;
368
        }
369

370 371
        if (!ceq(knm_q->qxt1_11, knm_q->qyt1_11)
                || !ceq(knm_q->qxt2_11, knm_q->qyt2_11))
372 373 374
            *astigmatism = *astigmatism | 1;
    }
    
375 376 377
    if ((knm_calc_flags & MR12Calc) == MR12Calc){
        if (!ceq(knm_q->qxt1_12, knm_q->qxt2_12)
                || !ceq(knm_q->qyt1_12, knm_q->qyt2_12))
378
            *mismatch = *mismatch | 4;
379

380 381
        if (!ceq(knm_q->qxt1_12, knm_q->qyt1_12)
                || !ceq(knm_q->qxt2_12, knm_q->qyt2_12))
382
            *astigmatism = *astigmatism | 4;
383 384
    }

385 386 387
    if ((knm_calc_flags & MR21Calc) == MR21Calc){
        if (!ceq(knm_q->qxt1_21, knm_q->qxt2_21)
                || !ceq(knm_q->qyt1_21, knm_q->qyt2_21))
388
            *mismatch = *mismatch | 8;
389

390 391
        if (!ceq(knm_q->qxt1_21, knm_q->qyt1_21)
                || !ceq(knm_q->qxt2_21, knm_q->qyt2_21))
392
            *astigmatism = *astigmatism | 8;
393 394
    }
    
395 396 397
    if ((knm_calc_flags & MR22Calc) == MR22Calc){
        if (!ceq(knm_q->qxt1_22, knm_q->qxt2_22)
                || !ceq(knm_q->qyt1_22, knm_q->qyt2_22))
398 399
            *mismatch = *mismatch | 2;

400 401
        if (!ceq(knm_q->qxt1_22, knm_q->qyt1_22)
                || !ceq(knm_q->qxt2_22, knm_q->qyt2_22))
402 403 404 405
            *astigmatism = *astigmatism | 2;
    }
}

Daniel Brown's avatar
Daniel Brown committed
406 407 408 409 410 411 412 413 414 415
// Scale the integration limits slightly depending on the beam mode
// as the beam tends to get larger at higher modes. If a mirror aperture
// has been specified then polar coordinates are used for the integration
// so r and theta limits are set.
//
// If the Riemann integration method is being used then cartesian coords
// are used by default. Polar limits are only set when using the new integration
// methods Cuba parallel and serial.
//
// if the beam is much smaller than the aperture, cartesian coordinates are used.
416
void get_mirror_int_limit(mr_knm_map_int_params_t *p, int knum) {
Daniel Brown's avatar
Daniel Brown committed
417 418 419 420 421 422 423 424 425 426
    if (p->aperture_radius < 0)
        bug_error("get_int_limit(*p): Mirror aperture cannot be negative\n");

    double wx1=0,wx2=0,wy1=0,wy2=0;
    double _wx1,_wx2,_wy1,_wy2;
    
    switch(knum){
        case 0:
            // used by cuba parallel, find the largest w values out of all the
            // different 
427
            if(CALC_MR_KNM(p,11)){
Daniel Brown's avatar
Daniel Brown committed
428 429 430 431 432 433
                calc_mirror_limit_ws(&_wx1,&_wx2,&_wy1,&_wy2,MR11,p);
                wx1 = max(wx1,_wx1);
                wx2 = max(wx2,_wx2);
                wy1 = max(wy1,_wy1);
                wy2 = max(wy2,_wy2);                
            }
434
            if(CALC_MR_KNM(p,12)){
Daniel Brown's avatar
Daniel Brown committed
435 436 437 438 439 440
                calc_mirror_limit_ws(&_wx1,&_wx2,&_wy1,&_wy2,MR12,p);
                wx1 = max(wx1,_wx1);
                wx2 = max(wx2,_wx2);
                wy1 = max(wy1,_wy1);
                wy2 = max(wy2,_wy2);                
            }
441
            if(CALC_MR_KNM(p,21)){
Daniel Brown's avatar
Daniel Brown committed
442 443 444 445 446 447
                calc_mirror_limit_ws(&_wx1,&_wx2,&_wy1,&_wy2,MR21,p);
                wx1 = max(wx1,_wx1);
                wx2 = max(wx2,_wx2);
                wy1 = max(wy1,_wy1);
                wy2 = max(wy2,_wy2);                
            }
448
            if(CALC_MR_KNM(p,22)){
Daniel Brown's avatar
Daniel Brown committed
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
                calc_mirror_limit_ws(&_wx1,&_wx2,&_wy1,&_wy2,MR22,p);
                wx1 = max(wx1,_wx1);
                wx2 = max(wx2,_wx2);
                wy1 = max(wy1,_wy1);
                wy2 = max(wy2,_wy2);                
            }
            break;
        case MR11:
            calc_mirror_limit_ws(&wx1,&wx2,&wy1,&wy2,MR11,p);
            break;
        case MR12:
            calc_mirror_limit_ws(&wx1,&wx2,&wy1,&wy2,MR12,p);
            break;
        case MR21:
            calc_mirror_limit_ws(&wx1,&wx2,&wy1,&wy2,MR21,p);
            break;
        case MR22:
            calc_mirror_limit_ws(&wx1,&wx2,&wy1,&wy2,MR22,p);
            break;
        default:
            bug_error("Cannot handle a knum input of %i\n",knum);
    }
    
    p->xmax[0] = 5 * max(sqrt(p->n1 + 0.5) * wx1, sqrt(p->n2 + 0.5) * wx2);
    p->xmin[0] = -p->xmax[0];
    p->xmax[1] = 5 * max(sqrt(p->m1 + 0.5) * wy1, sqrt(p->m2 + 0.5) * wy2);
    p->xmin[1] = -p->xmax[1];

    double r = p->aperture_radius;
    
    // if using the Riemann just stick to the Cartesian coordinates
    // if r == 0 then the mirror is infinitely big
    // if r > max(...) then the beam size is smaller than the aperture so Cartesian will do
    // also check if we should be integrating to calculate the aperture with inter.knm, if we're not
    // then there is no need to use polar coordinates as polar coordinates are only used for aperture
    // calculations.
485 486 487 488 489 490 491 492 493 494 495 496 497 498
    if (p->mirror->aperture_type == CIRCULAR) {
        if ((p->merged_map->integration_method == NEWTON_COTES 
                || p->merged_map->integration_method == RIEMANN_SUM_NEW)
                || !(p->mirror->knm_flags & INT_APERTURE)
                || ((r == 0) || (r > min(p->xmax[0], p->xmax[1])))) {
            p->polar_limits_used = false;
        } else {
            //[0] is r, [1] is theta
            p->xmin[0] = 0;
            p->xmin[1] = 0;
            p->xmax[0] = r;
            p->xmax[1] = TWOPI;
            p->polar_limits_used = true;
        }
Daniel Brown's avatar
Daniel Brown committed
499
    } else {
500 501 502 503 504
        p->polar_limits_used = false;
        p->xmin[0] = max(-r, p->xmin[0]);
        p->xmin[1] = max(-r, p->xmin[1]);
        p->xmax[0] = min(r, p->xmax[0]);
        p->xmax[1] = min(r, p->xmax[1]);
Daniel Brown's avatar
Daniel Brown committed
505 506
    }
    
507 508
    if (inter.debug & 64){
        if (p->polar_limits_used) {
509 510 511
            message("* Map %s limits, r: %g %g phi: %g %g\n", p->merged_map->name,p->xmin[0],p->xmax[0],p->xmin[1],p->xmax[1]);
        } else{
            message("* Map %s limits, x: %g %g y: %g %g\n", p->merged_map->name,p->xmin[0],p->xmax[0],p->xmin[1],p->xmax[1]);
512 513 514
        }
    }
    
Daniel Brown's avatar
Daniel Brown committed
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
    unsigned int *usermessages = &(p->merged_map->usermessages);
    
    if(inter.debug && !options.quiet && !(*usermessages & USING_POLAR)){
        if(p->polar_limits_used)
           message("* Polar coordinates used to integrate map %s\n",p->merged_map->name);
        else
           message("* Cartesian coordinates used to integrate map %s\n",p->merged_map->name);
            
        *usermessages = *usermessages | USING_POLAR;
    }
    
    if(p->usingMap && !(*usermessages & MAP_TOO_SMALL)){        
        surface_merged_map_t *map = p->merged_map;
        // here we check to see if the map size is smaller than the limits. if so
        // you could probably do with a bigger map
        if(p->polar_limits_used){
            bool a = (map->cols-map->x0) * map->xstep < p->xmax[0]*(1-1e-15);
            bool b = (map->rows-map->y0) * map->ystep < p->xmax[0]*(1-1e-15);
533 534
            bool c = (map->x0-map->cols) * map->xstep > -p->xmax[0];
            bool d = (map->y0-map->rows) * map->ystep > -p->xmax[0];
Daniel Brown's avatar
Daniel Brown committed
535 536 537 538 539 540
            if( (a || b || c || d) && inter.debug && !options.quiet){
                warn("The map %s is smaller than the dimensions of the integration limits\n"
                     "   You should use a bigger map or a smaller beam for more accurate results,\n"
                     "   and make sure that the map is correctly centred using the x0 and y0\n"
                     "   (aperture diameter:%e, map width:%e, map height: %e)\n"
                        , p->merged_map->filename
541
                        , 2.0*p->xmax[0] 
Daniel Brown's avatar
Daniel Brown committed
542 543 544 545 546
                        , (map->cols-1) * map->xstep
                        , (map->rows-1) * map->ystep);
                
                *usermessages = *usermessages | MAP_TOO_SMALL;
            }
547 548
        }
        else {
Daniel Brown's avatar
Daniel Brown committed
549 550
            if( (((map->cols-map->x0) * map->xstep < p->xmax[0]) 
             || ((map->x0-map->cols) * map->xstep < p->xmin[0]) 
551 552
             || ((map->rows-map->y0) * map->ystep > p->xmax[1]) 
             || ((map->y0-map->rows) * map->ystep > p->xmin[1])
Daniel Brown's avatar
Daniel Brown committed
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
                ) && inter.debug && !options.quiet){
                warn("The map %s is smaller than the dimensions of the integration limits\n"
                     "   You should use a bigger map or a smaller beam for more accurate results,\n"
                     "   and make sure that the map is correctly centred using the x0 and y0\n"
                     "   (x range=%e, y range=%e, map width=%e map height=%e)\n"
                        , p->merged_map->filename
                        , p->xmax[0] - p->xmin[0]
                        , p->xmax[1] - p->xmin[1]
                        , (map->cols-1) * map->xstep
                        , (map->rows-1) * map->ystep);
            
                
                *usermessages = *usermessages | MAP_TOO_SMALL;
            }
        }
    }
    
    if(p->usingMap && !(*usermessages & MAP_RES_TOO_LOW )
            && p->merged_map->integration_method == RIEMANN_SUM_NEW){
        if((min(wx1,wx2)/p->merged_map->xstep < 5.0) || (min(wy1,wy2)/p->merged_map->ystep < 5.0) ){
            warn("The map %s might not have a high enough resolution. Currently\n"
              "   the beam size samples less than 10 points on the map. This can\n"
              "   cause large errors when using higher orders.\n", p->merged_map->name);
            *usermessages |= MAP_RES_TOO_LOW;
        }
    }
579
    
Daniel Brown's avatar
Daniel Brown committed
580
}
581 582 583 584 585 586 587

typedef struct knm_surf_cuba_params {
    surface_map_t *map;
    int n1, n2, m1, m2;
    double xmin, xrange;
    double ymin, yrange;
    double xfac, yfac;
588
    double constant;
589 590
} knm_surf_cuba_params_t;

591 592 593
/** A bilinear interpolation of a maps data, x and y are real values of distance
 * from the maps centre.
 */
594
double eval_surface_map(surface_map_t *map, double x, double y){
595 596 597 598 599 600 601 602 603
    // get index space position of (x,y) coord
    double px = map->x0 + x/map->xstep;
    double py = map->y0 + y/map->ystep;
    
    if(py < 0 || px < 0 || px > map->cols-1 || py > map->rows-1) return 0;
    
    size_t x1 = (size_t)floor(px);
    size_t y1 = (size_t)floor(py);
    
604 605
    if((int)x1 == map->cols-1) x1--;
    if((int)y1 == map->rows-1) y1--;
606 607 608 609 610 611 612 613 614 615
    
    size_t x2 = x1 + 1;
    size_t y2 = y1 + 1;
    
    double dx1 = px - x1;
    double dy1 = py - y1;
    double dx2 = x2 - px;
    double dy2 = y2 - py;
    
    double f = map->data[y1][x1] * dx2 * dy2;
616 617
    f += map->data[y2][x1] * dx2 * dy1;
    f += map->data[y1][x2] * dx1 * dy2;
618 619 620 621
    f += map->data[y2][x2] * dx1 * dy1;
    
    f /= ((x2-x1)*(y2-y1));
    
622
    return f;
623 624
}

625 626
#if INCLUDE_CUBA == 1

627 628 629 630 631 632 633 634 635 636 637 638
static int integrand_cuba_surf(const int *ndim, const double xx[], const int *ncomp, double ff[], void *userdata) {
    assert(*ndim == 2);
    assert(*ncomp == 1);
    
    // get rid of compiler warnings
    (void) ndim;
    (void) ncomp;
    
    knm_surf_cuba_params_t *p = (knm_surf_cuba_params_t*)userdata;
    
    double x = p->xmin + xx[0] * p->xrange;
    double y = p->ymin + xx[1] * p->yrange;
639 640
    // use factor to change from sqrt{2}x/w(z) - > x'
    double x1 = p->xfac * x;
641 642 643
    double y1 = p->yfac * y;
    
    double Hn1 = hermite(p->n1, x1);
644
    double Hn2 = (p->n1==p->n2) ? Hn1 : hermite(p->n2, x1);
645
    double Hm1 = hermite(p->m1, y1);
646
    double Hm2 = (p->m1==p->m2) ? Hm1 :hermite(p->m2, y1);
647 648 649
    
    double func = eval_surface_map(p->map, x, y);
    
650
    ff[0] = Hn1*Hn2 * Hm1*Hm2* exp(-x1*x1 - y1*y1) * func * p->constant;
651 652 653 654
    
    return 0;
}

655 656
#endif

657 658 659 660 661 662 663
/**
 * Computes the overlap integral or a surface motion. Assumes the coupling
 * is mode matched so that the entire integral is real.
 * 
 * @param result
 * @param p
 */
664 665 666 667 668
void integrate_riemann_sum_surf(double *result, knm_surf_cuba_params_t *p) {
    assert(result != NULL);
    assert(p != NULL);
    
    int i=0, j=0;
669 670
    
    double x=0, y=0;
671 672 673 674 675 676
    double dx = p->map->xstep;
    double dy = p->map->ystep;
    double da = dx*dy;

    *result = 0.0;
    
677 678 679 680 681 682 683 684 685 686 687 688
    for (i = 0; i < p->map->cols; i++) {
        x = (i - p->map->x0) * dx;    
        // use factor to change from sqrt{2}x/w(z) - > x'
        double x1  = x * p->xfac;
        double Hn1 = hermite(p->n1, x1);
        double Hn2 = (p->n1==p->n2) ? Hn1 : hermite(p->n2, x1);
            
        for (j = 0; j < p->map->rows; j++) {
            y = (j - p->map->y0) * dy;
            double y1  = y * p->yfac;
            double Hm1 = hermite(p->m1, y1);
            double Hm2 = (p->m1==p->m2) ? Hm1 : hermite(p->m2, y1);
689
            
690
            double func = p->map->data[j][i];
691
            *result += Hn1*Hn2 * Hm1*Hm2* exp(- x1*x1 - y1*y1) * func;
692 693 694 695 696
        }
    }
   
    // finally multiply by the area of the each pixel in the map to correctly
    // scale the results
697
    *result *= da * p->constant;
698 699
}

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
void calc_mirror_knm_surf_motions_rom(mirror_t *mirror, double nr1, double nr2,
                                      complex_t qx11, complex_t qy11,
                                      complex_t qx22, complex_t qy22,
                                      bitflag astigmatism) {
   
    assert(mirror != NULL);
    
    int timer = startTimer("ROMHOM");
    
    if(mirror->x_off != 0.0 || mirror->y_off != 0.0)
        warn("ROMHOM can't take into account transverse offsets in mirror position, use normal maps for this or include offset in map when making ROM.", mirror->name);
    
    // boolean value that states whether we should calculate knm using knm without
    // having to do the whole integral and just by applying some phase factor
    int calc_knm_transpose = (init.calc_knm_transpose && (astigmatism == 0));
    
    int max_m, max_n;
    get_tem_modes_from_field_index(&max_n, &max_m, inter.num_fields - 1);
    max_m = max_n; // max m is no the m is also the max_n. e.g. we get n=1 m=2 for maxtem 2
    
    // K11
    if (CALC_MR_KNM(mirror,11)) {
        u_nm_accel_get(acc_11_nr1_1, max_n, max_m, qx11, qy11, nr1);
        u_nm_accel_get(acc_11_nr1_2, max_n, max_m, qx11, qy11, nr1);
    }
    
    // K22
    if (CALC_MR_KNM(mirror,22)) {
        u_nm_accel_get(acc_22_nr2_1, max_n, max_m, qx22, qy22, nr2);
        u_nm_accel_get(acc_22_nr2_2, max_n, max_m, qx22, qy22, nr2);
    }
    
    int num_coeffs = inter.num_fields * inter.num_fields;
    int current_coeff = 1;
    
    time_t starttime = time(NULL);
    
    int n, m, n1, m1, n2, m2, l;
    
    set_progress_action_text("Calculating ROMHOM surface knm for %s", mirror->name);
    
    for(l=0; l < mirror->num_surface_motions; l++){
        if(!mirror->surface_motions_isROM[l])
            continue;
            
        rom_map_t *rom = &inter.rom_maps[mirror->surface_motions[l]];
        knm_workspace_t *ws11 = &rom->roq11.knm_ws;
        knm_workspace_t *ws22 = &rom->roq22.knm_ws;

        if (CALC_MR_KNM(mirror, 11) && rom->roq11.enabled){
            double wx11 = w0_size(qx11, nr1);
            double wy11 = w0_size(qy11, nr1);
            double zx11 = fabs(qx11.re);
            double zy11 = fabs(qy11.re);
            
            assert(wx11 <= rom->roq11.w0max && wx11 >= rom->roq11.w0min);
            assert(zx11 <= rom->roq11.zmax && zx11 >= rom->roq11.zmin);
            assert(wy11 <= rom->roq11.w0max && wy11 >= rom->roq11.w0min);
            assert(zy11 <= rom->roq11.zmax && zy11 >= rom->roq11.zmin);
759 760 761 762 763
            
            (void)wx11; //suppressing compiler warnings
            (void)wy11;
            (void)zx11;
            (void)zy11;
764 765 766 767 768 769 770 771 772 773

            fill_unn_cache(&(ws11->ux_cache_11), acc_11_nr1_1->acc_n, acc_11_nr1_2->acc_n, true);
            fill_unn_cache(&(ws11->uy_cache_11), acc_11_nr1_1->acc_m, acc_11_nr1_2->acc_m, true);
        }

        if (CALC_MR_KNM(mirror, 22) && rom->roq22.enabled){
            double wx22 = w0_size(qx22, nr2);
            double wy22 = w0_size(qy22, nr2);
            double zx22 =    fabs(qx22.re);
            double zy22 =    fabs(qy22.re);
774 775 776 777
            (void)wx22; //suppressing compiler warnings
            (void)wy22;
            (void)zx22;
            (void)zy22;
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
            
            assert(wx22 <= rom->roq22.w0max && wx22 >= rom->roq22.w0min);
            assert(zx22 <= rom->roq22.zmax &&  zx22 >= rom->roq22.zmin);
            assert(wy22 <= rom->roq22.w0max && wy22 >= rom->roq22.w0min);
            assert(zy22 <= rom->roq22.zmax &&  zy22 >= rom->roq22.zmin);
            
            fill_unn_cache(&(ws22->ux_cache_22), acc_22_nr2_1->acc_n, acc_22_nr2_2->acc_n, true);
            fill_unn_cache(&(ws22->uy_cache_22), acc_22_nr2_1->acc_m, acc_22_nr2_2->acc_m, true);
        }
        
        // Iterate over each mode to calculate k_n1,m1,n2,m2
        for (n = 0; n < inter.num_fields; n++) {    
            for (m = 0; m < inter.num_fields; m++) {

                // If we are using the knm to calc knm then we do not need to bother
                // with doing all the integrating for any of the lower triangle.
                if (!calc_knm_transpose || (n >= m)) {

                    //Transform linear mode index system into actual TEM_NM mode
                    get_tem_modes_from_field_index(&n1, &m1, n);
                    get_tem_modes_from_field_index(&n2, &m2, m);
                    
                    // compute some constants that are n1,n2,m1,m2 dependant
                    if (CALC_MR_KNM(mirror, 11) && rom->roq11.enabled){
                        complex_t znm1c1 = z_by_zc(z_by_z(acc_11_nr1_1->acc_n->prefac[n1], acc_11_nr1_1->acc_m->prefac[m1]),
                                                   z_by_z(acc_11_nr1_2->acc_n->prefac[n2], acc_11_nr1_2->acc_m->prefac[m2]));

                        mirror->knm_surf_motion_1o[l][n][m] = z_by_z(do_romhom_real_int(&rom->roq11, ws11->d_u_xy, &ws11->ux_cache_11, &ws11->uy_cache_11, n1, m1, n2, m2), znm1c1);
                        
                        // the only difference between the incoming and outgoing computation
                        // is that q_1 = cminus(cconj(q_2)) which means that the gouy phase is
                        // opposite sign, or just the conjugate. As the knm matrix is hermitian
                        // we can compute everything at once from one integral computation.
Daniel Brown's avatar
Daniel Brown committed
811
                        mirror->knm_surf_motion_1i[l][n][m] = cconj(mirror->knm_surf_motion_1o[l][n][m]);
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
                    } else {
                        mirror->knm_surf_motion_1o[l][n][m] = (n1==n2 && m1==m2) ? complex_1 : complex_0;
                        mirror->knm_surf_motion_1i[l][n][m] = (n1==n2 && m1==m2) ? complex_1 : complex_0;
                    }

                    if (CALC_MR_KNM(mirror, 22) && rom->roq22.enabled) {
                        complex_t znm2c2 = z_by_zc(z_by_z(acc_22_nr2_1->acc_n->prefac[n1], acc_22_nr2_1->acc_m->prefac[m1]),
                                                   z_by_z(acc_22_nr2_2->acc_n->prefac[n2], acc_22_nr2_2->acc_m->prefac[m2]));

                        mirror->knm_surf_motion_2o[l][n][m] = z_by_z(do_romhom_real_int(&rom->roq22, ws22->d_u_xy, &ws22->ux_cache_22, &ws22->uy_cache_22, n1, m1, n2, m2), (znm2c2));
                        
                        // the only difference between the incoming and outgoing computation
                        // is that q_1 = cminus(cconj(q_2)) which means that the gouy phase is
                        // opposite sign, or just the conjugate. As the knm matrix is hermitian
                        // we can compute everything at once from one integral computation.
Daniel Brown's avatar
Daniel Brown committed
827
                        mirror->knm_surf_motion_2i[l][n][m] = cconj(mirror->knm_surf_motion_2o[l][n][m]);
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
                    } else {
                        mirror->knm_surf_motion_2o[l][n][m] = (n1==n2 && m1==m2) ? complex_1 : complex_0;
                        mirror->knm_surf_motion_2i[l][n][m] = (n1==n2 && m1==m2) ? complex_1 : complex_0;
                    }

                    if (calc_knm_transpose && !(n1 == n2 && m1 == m2)) {
                        mirror->knm_surf_motion_1i[l][m][n] = cconj(mirror->knm_surf_motion_1i[l][n][m]);
                        mirror->knm_surf_motion_1o[l][m][n] = cconj(mirror->knm_surf_motion_1o[l][n][m]);
                        mirror->knm_surf_motion_2i[l][m][n] = cconj(mirror->knm_surf_motion_2i[l][n][m]);
                        mirror->knm_surf_motion_2o[l][m][n] = cconj(mirror->knm_surf_motion_2o[l][n][m]);
                    }
                }

                current_coeff++;
                print_progress_and_time(num_coeffs, current_coeff, starttime);
            }
        }
    }
    
    endTimer(timer);
}

void calc_mirror_knm_surf_motions_map(mirror_t *m, double nr1, double nr2, complex_t qx1, complex_t qy1, complex_t qx2, complex_t qy2) {
    
852 853 854 855
    assert(m!=NULL);
    assert(m->num_surface_motions > 0);
    assert(m->surface_motions != NULL);
    
856 857 858 859 860 861 862 863
    bool compute1 = false, compute2 = false;
    
    if(!ceq(m->last_surf_knm_qx1, qx1)) compute1 |= true;
    if(!ceq(m->last_surf_knm_qy1, qy1)) compute1 |= true;
    
    if(!ceq(m->last_surf_knm_qx2, qx2)) compute2 |= true;
    if(!ceq(m->last_surf_knm_qy2, qy2)) compute2 |= true;
    
864
    //bool equal_q = ceq(qx1, qx2) && ceq(qy1, qy2);
865
   
866 867 868
    node_t *n1 = &inter.node_list[m->node1_index];
    node_t *n2 = &inter.node_list[m->node2_index];
    
869 870 871 872 873
    if(n1->gnd_node) compute1 = false;
    if(n2->gnd_node) compute2 = false;
    
    if(!compute1 && !compute2) return;
    
874 875 876 877 878 879 880
    int max_m, max_n;
    get_tem_modes_from_field_index(&max_n, &max_m, inter.num_fields - 1);
    max_m = max_n; // max m is no the m is also the max_n. e.g. we get n=1 m=2 for maxtem 2
    
    if (!n1->gnd_node) u_nm_accel_get(acc_11_nr1_2, max_n, max_m, qx1, qy1, nr1);
    if (!n2->gnd_node) u_nm_accel_get(acc_22_nr2_2, max_n, max_m, qx2, qy2, nr2);
    
881 882
    knm_surf_cuba_params_t p = (knm_surf_cuba_params_t){0};
		// todo: this creates a compiler warning, would be nice to fix that.
883
    
884
#if INCLUDE_CUBA == 1
885
    int nregions, neval, fail;
886
    double error[1], prob[1];
887 888
    // if the q values are equal on both sides then there is no need to compute
    // the same integral twice.
889
    int NCOMP = 1;
890
    double integral[1];
891 892 893
#endif
    
    int in = 0, out = 0, k;
894
    
895 896 897
    double abs_err = (m->knm_cuba_abs_err != 0) ? m->knm_cuba_abs_err : init.abserr;
    double rel_err = (m->knm_cuba_rel_err != 0) ? m->knm_cuba_rel_err : init.relerr;
    
898 899 900 901 902
    time_t starttime = time(NULL);
    int num_coeffs = inter.num_fields * inter.num_fields;
    int current_coeff = 0;
        
    for(k=0; k<m->num_surface_motions; k++){
903 904 905
        if(m->surface_motions_isROM[k])
            continue;
        
906
        p.map = &inter.surface_motion_map_list[m->surface_motions[k]];
907
        current_coeff = 1;
908
                
909 910 911 912 913 914 915 916 917 918
        set_progress_action_text("Integrating surface motion %i/%i on %s", k+1, m->num_surface_motions, m->name);
        print_progress_and_time(num_coeffs, current_coeff, starttime);
        
        for(in=0; in<inter.num_fields; in++){
            get_tem_modes_from_field_index(&p.n1, &p.m1, in);
            
            // only loop over upper half of matrix
            for(out=in; out<inter.num_fields; out++){
                get_tem_modes_from_field_index(&p.n2, &p.m2, out);
                
919 920 921 922 923 924
                double const_fac = 1.0 / (sqrt(pow(2, p.n1+p.n2+p.m1+p.m2-2) * fac(p.n1) * fac(p.n2) * fac(p.m1) * fac(p.m2)) * PI);
                
                double gx11 = gouy(qx1);
                double gy11 = gouy(qy1);
                double gx22 = gouy(qx2);
                double gy22 = gouy(qy2);
925
                
926
                double value = 0.0;
927
                
928
                if(compute1) {
929 930
                    double wx = w_size(qx1, nr1);
                    double wy = w_size(qy1, nr1);
931 932 933
                    p.constant = const_fac / (wx*wy);
                    p.xfac = SQRTTWO / wx;
                    p.yfac = SQRTTWO / wy;
934
                    
935 936 937
#if INCLUDE_CUBA == 1
                    p.xmin = -5 * sqrt(max(p.n1, p.n2)+1) * wx;
                    p.ymin = -5 * sqrt(max(p.m1, p.m2)+1) * wy;
938 939
                    p.xrange = -2 * p.xmin;
                    p.yrange = -2 * p.ymin;
940
                    
941 942
                    integral[0] = 0;
                    Cuhre(2, NCOMP, integrand_cuba_surf, (void*) &p,
943
                                rel_err, abs_err, 0,
944
                                0, init.maxintcuba, 13, NULL,
945
                                &nregions, &neval, &fail, integral, error, prob);
946 947
                    // scale the integral value due to -1:1 limits in Cuhre
                    value = integral[0] * p.xrange * p.yrange;
948
#else
949
                    integrate_riemann_sum_surf(&value, &p);
950
#endif
951
                    // surface integration is just the real kernel of the hermite
952 953 954
                    // polynomials, have to add in the gouy phase here.
                    // Even though we reverse gouy it later it needs to be in 
                    // here for merging with any static distortions
955 956 957
                    complex_t knm = z_by_xphr(complex_1, value, (p.n1 - p.n2) * gx11 + (p.m1 - p.m2) * gy11);
                    
                    //warn("%i%i->%i%i %s\n", p.n1, p.m1, p.n2, p.m2, complex_form15(knm));
958
                    
959 960 961
                    // the only difference between the incoming and outgoing computation
                    // is that q_1 = cminus(cconj(q_2)) which means that the gouy phase is
                    // opposite sign, or just the conjugate. As the knm matrix is hermitian
962
                    // we can compute everything at once from one integral computation.
963
                    m->knm_surf_motion_1o[k][in][out] = knm;
964
                    m->knm_surf_motion_1i[k][in][out] = cconj(knm);
965
                    
966 967
                    //warn("%i%i->%i%i = %.15g\n",p.n1, p.m1, p.n2, p.m2, zabs(knm));
                    
968 969
                    if(out!=in) {
                        m->knm_surf_motion_1o[k][out][in] = cconj(m->knm_surf_motion_1o[k][in][out]);
970
                        m->knm_surf_motion_1i[k][out][in] = cconj(m->knm_surf_motion_1i[k][in][out]);
971
                    }
972
                }
973
                
974
                if(compute2){
975 976
                    double wx = w_size(qx2, nr2);
                    double wy = w_size(qy2, nr2);
977 978 979
                    p.constant = const_fac / (wx*wy);
                    p.xfac = SQRTTWO / wx;
                    p.yfac = SQRTTWO / wy;
980
                    
981
#if INCLUDE_CUBA == 1
982 983
                    p.xmin = -5 * sqrt(max(p.n1, p.n2)+1) * wx;
                    p.ymin = -5 * sqrt(max(p.m1, p.m2)+1) * wy;
984 985
                    p.xrange = -2 * p.xmin;
                    p.yrange = -2 * p.ymin;
986 987 988
                    
                    integral[0] = 0.0;
                    
989
                    Cuhre(2, NCOMP, integrand_cuba_surf, (void*) &p,
990
                           rel_err, abs_err, 0,
991 992
                            0, init.maxintcuba, 13, NULL,
                            &nregions, &neval, &fail, integral, error, prob);
993 994
                    
                    value = integral[0] * p.xrange * p.yrange;
995
#else
996
                    integrate_riemann_sum_surf(&value, &p);
997
#endif
998
                    
999
                    complex_t knm = z_by_xphr(complex_1, value, (p.n1 - p.n2) * gx22 + (p.m1 - p.m2) * gy22);
1000
                    
1001 1002 1003
                    // use a minus sign (complex_m1) here because the surface motion will appear
                    // opposite from node 2 side, we also have the msign term here because the coord
                    // system of the outgoing beam has a negative x compared to the map coord system
1004
                    m->knm_surf_motion_2o[k][in][out] = knm;
1005
                    m->knm_surf_motion_2i[k][in][out] = cconj(knm);
1006 1007 1008
                    
                    if(out!=in) {
                        m->knm_surf_motion_2o[k][out][in] = cconj(m->knm_surf_motion_2o[k][in][out]);   
1009
                        m->knm_surf_motion_2i[k][out][in] = cconj(m->knm_surf_motion_2i[k][in][out]);
1010
                    }
1011
                } 
1012
                
1013 1014 1015 1016 1017
                if(out!=in) 
                    current_coeff+=2; // add two because we also compute the transposed elements too
                else
                    current_coeff++;
                
1018 1019 1020 1021 1022
                print_progress_and_time(num_coeffs, current_coeff, starttime);
            }
        }
    }
    
1023 1024 1025 1026 1027
    m->last_surf_knm_qx1 = qx1;
    m->last_surf_knm_qy1 = qy1;
    m->last_surf_knm_qx2 = qx2;
    m->last_surf_knm_qy2 = qy2;
    
1028
    set_progress_action_text("Integrating surface motion done on %s", m->name);
1029
    print_progress_and_time(num_coeffs, num_coeffs+1, starttime);
1030 1031
}

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045

/**
 * Computes the ROMHOM map model coupling matrix for a mirror.
 * 
 * @param mirror
 * @param nr1
 * @param nr2
 * @param integrating
 * @param mismatch
 * @param astigmatism
 */
void compute_mirror_knm_romhom(mirror_t *mirror, double nr1, double nr2, int mismatch, int astigmatism) {
    assert(mirror != NULL);
    
1046 1047 1048 1049
    int timer = startTimer("ROMHOM");
    
    if(mirror->map_rom == NULL){
        endTimer(timer);
1050
        return;
1051
    }
1052
    
1053 1054 1055 1056 1057 1058
    mirror_knm_q_t *kq = &(mirror->knm_q);
    
    // If the q values used are the same then no need to recompute HOM
    if(knm_q_cmp(kq, &(mirror->prev_rom_q)))
        return;
    
1059
    mirror_knm_t *knm = &(mirror->knm_romhom);
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
    
    if (!IS_MIRROR_KNM_ALLOCD(knm))
        bug_error("mirror romhom knm has not been allocated");
    
    if(mirror->x_off != 0.0 || mirror->y_off != 0.0)
        warn("ROMHOM can't take into account transverse offsets in mirror position, use normal maps to take this into account.", mirror->name);
    
    // boolean value that states whether we should calculate knm using knm without
    // having to do the whole integral and just by applying some phase factor
    int calc_knm_transpose = (init.calc_knm_transpose && (mismatch == 0) && (astigmatism == 0));
1070
    
1071 1072 1073 1074
    int max_m, max_n;
    get_tem_modes_from_field_index(&max_n, &max_m, inter.num_fields - 1);
    max_m = max_n; // max m is no the m is also the max_n. e.g. we get n=1 m=2 for maxtem 2

1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
    if(!ceq(kq->qxt1_11, kq->qxt2_11) || !ceq(kq->qyt1_11, kq->qyt2_11)) {
        warn("Mismatch on side 1 reflection at %s, can't compute coupling using ROM\n", mirror->name);
        warn("1->1: qx = %s, qx' = %s\n", complex_form15(kq->qxt1_11), complex_form15(kq->qxt2_11));
        warn("1->1: qy = %s, qy' = %s\n", complex_form15(kq->qyt1_11), complex_form15(kq->qyt2_11));
    }
    
    if(!ceq(kq->qxt1_22, kq->qxt2_22) || !ceq(kq->qyt1_22, kq->qyt2_22)) {
        warn("Mismatch on side 2 reflection at %s, can't compute coupling using ROM\n", mirror->name);
        warn("2->2: qx = %s, qx' = %s\n", complex_form15(kq->qxt1_22), complex_form15(kq->qxt2_22));
        warn("2->2: qy = %s, qy' = %s\n", complex_form15(kq->qyt1_22), complex_form15(kq->qyt2_22));
    }
    
    if(!ceq(kq->qxt1_12, kq->qxt2_12) || !ceq(kq->qxt1_21, kq->qxt2_21) 
            || !ceq(kq->qyt1_12, kq->qyt2_12) || !ceq(kq->qyt1_21, kq->qyt2_21)) {
        warn("Mismatch on transmission at %s, can't compute coupling using ROM\n", mirror->name);
        warn("1->2: qx = %s, qx' = %s\n", complex_form15(kq->qxt1_12), complex_form15(kq->qxt2_12));
        warn("1->2: qy = %s, qy' = %s\n", complex_form15(kq->qyt1_12), complex_form15(kq->qyt2_12));
        warn("2->1: qx = %s, qx' = %s\n", complex_form15(kq->qxt1_21), complex_form15(kq->qxt2_21));
        warn("2->1: qy = %s, qy' = %s\n", complex_form15(kq->qyt1_21), complex_form15(kq->qyt2_21));
    }
    
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
    // K11
    if (CALC_MR_KNM(mirror,11)) {
        u_nm_accel_get(acc_11_nr1_1, max_n, max_m, kq->qxt1_11, kq->qyt1_11, nr1);
        u_nm_accel_get(acc_11_nr1_2, max_n, max_m, kq->qxt2_11, kq->qyt2_11, nr1);
    }
    
    // K22
    if (CALC_MR_KNM(mirror,22)) {
        u_nm_accel_get(acc_22_nr2_1, max_n, max_m, kq->qxt1_22, kq->qyt1_22, nr2);
        u_nm_accel_get(acc_22_nr2_2, max_n, max_m, kq->qxt2_22, kq->qyt2_22, nr2);
    }
    
    // K12
    if (CALC_MR_KNM(mirror,12)) {
        u_nm_accel_get(acc_12_nr1_1, max_n, max_m, kq->qxt1_12, kq->qyt1_12, nr1);
        u_nm_accel_get(acc_12_nr2_2, max_n, max_m, kq->qxt2_12, kq->qyt2_12, nr2);
    }
    
    // K21
    if (CALC_MR_KNM(mirror,21)) {
        u_nm_accel_get(acc_21_nr2_1, max_n, max_m, kq->qxt1_21, kq->qyt1_21, nr2);
        u_nm_accel_get(acc_21_nr1_2, max_n, max_m, kq->qxt2_21, kq->qyt2_21, nr1);
    }
    
    int num_coeffs = inter.num_fields * inter.num_fields;
    int current_coeff = 1;
1122
    
1123 1124
    time_t starttime = time(NULL);
    
1125 1126 1127 1128 1129 1130
    rom_map_t *rom = mirror->map_rom;
    
    knm_workspace_t *ws11 = &mirror->map_rom->roq11.knm_ws;
    knm_workspace_t *ws22 = &mirror->map_rom->roq22.knm_ws;
    knm_workspace_t *ws12 = &mirror->map_rom->roq12.knm_ws;
    knm_workspace_t *ws21 = &mirror->map_rom->roq21.knm_ws;
1131 1132 1133 1134 1135 1136 1137
    
    int n, m, n1, m1, n2, m2;
    
    set_progress_action_text("Calculating ROMHOM cache for %s", mirror->name);
    
    print_progress_and_time(num_coeffs, current_coeff, starttime);
   
1138 1139 1140
    if (CALC_MR_KNM(mirror,11) && rom->roq11.enabled){
        fill_unn_cache(&(ws11->ux_cache_11), acc_11_nr1_1->acc_n, acc_11_nr1_2->acc_n, true);
        fill_unn_cache(&(ws11->uy_cache_11), acc_11_nr1_1->acc_m, acc_11_nr1_2->acc_m, true);
1141 1142
    }

1143 1144 1145
    if (CALC_MR_KNM(mirror,12) && rom->roq12.enabled){
        fill_unn_cache(&(ws12->ux_cache_12), acc_12_nr1_1->acc_n, acc_12_nr2_2->acc_n, true);
        fill_unn_cache(&(ws12->uy_cache_12), acc_12_nr1_1->acc_m, acc_12_nr2_2->acc_m, true);
1146 1147
    }

1148 1149 1150
    if (CALC_MR_KNM(mirror,21) && rom->roq21.enabled){
        fill_unn_cache(&(ws21->ux_cache_21), acc_21_nr2_1->acc_n, acc_21_nr1_2->acc_n, true);
        fill_unn_cache(&(ws21->uy_cache_21), acc_21_nr2_1->acc_m, acc_21_nr1_2->acc_m, true);
1151 1152
    }

1153 1154 1155
    if (CALC_MR_KNM(mirror,22) && rom->roq22.enabled){
        fill_unn_cache(&(ws22->ux_cache_22), acc_22_nr2_1->acc_n, acc_22_nr2_2->acc_n, true);
        fill_unn_cache(&(ws22->uy_cache_22), acc_22_nr2_1->acc_m, acc_22_nr2_2->acc_m, true);
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    }
    
    set_progress_action_text("Calculating ROMHOM knm for %s", mirror->name);
    
    complex_t results[4];
    
    // Iterate over each mode to calculate k_n1,m1,n2,m2
    for (n = 0; n < inter.num_fields; n++) {    
        for (m = 0; m < inter.num_fields; m++) {
         
            // If we are using the knm to calc knm then we do not need to bother
            // with doing all the integrating for any of the lower triangle.
            if (!calc_knm_transpose || (n >= m)) {

                //Transform linear mode index system into actual TEM_NM mode
                get_tem_modes_from_field_index(&n1, &m1, n);
                get_tem_modes_from_field_index(&n2, &m2, m);
                
                // Set default values of a unity matrix
                if (n1==n2 && m1==m2){
                    results[0] = complex_1;
                    results[1] = complex_1;
                    results[2] = complex_1;
                    results[3] = complex_1;
                } else {
                    results[0] = complex_0;
                    results[1] = complex_0;
                    results[2] = complex_0;
                    results[3] = complex_0;
                }
                
                // compute some constants that are n1,n2,m1,m2 dependant
1188
                if (CALC_MR_KNM(mirror,11) && rom->roq11.enabled){
1189 1190
                    complex_t znm1c1 = z_by_zc(z_by_z(acc_11_nr1_1->acc_n->prefac[n1], acc_11_nr1_1->acc_m->prefac[m1]),
                                               z_by_z(acc_11_nr1_2->acc_n->prefac[n2], acc_11_nr1_2->acc_m->prefac[m2]));
1191

1192
                    results[0] = z_by_z(do_romhom_real_int(&rom->roq11, ws11->d_u_xy, &ws11->ux_cache_11, &ws11->uy_cache_11, n1, m1, n2, m2), znm1c1);
1193 1194
                }

1195
                // Disable transmission calculation as ROM maps are only for reflection currently
1196
                if (CALC_MR_KNM(mirror,12) && rom->roq12.enabled) {
1197 1198 1199
                    complex_t znm1c2 = z_by_zc(z_by_z(acc_12_nr1_1->acc_n->prefac[n1], acc_12_nr1_1->acc_m->prefac[m1]),
                                               z_by_z(acc_12_nr2_2->acc_n->prefac[n2], acc_12_nr2_2->acc_m->prefac[m2]));
                    
1200
                    results[1] = z_by_z(do_romhom_real_int(&rom->roq12, ws12->d_u_xy, &ws12->ux_cache_12, &ws12->uy_cache_12, n1, m1, n2, m2), znm1c2);
1201 1202
                }

1203
                if (CALC_MR_KNM(mirror,21) && rom->roq21.enabled) {
1204 1205 1206
                    complex_t znm2c1 = z_by_zc(z_by_z(acc_21_nr2_1->acc_n->prefac[n1], acc_21_nr2_1->acc_m->prefac[m1]),
                                               z_by_z(acc_21_nr1_2->acc_n->prefac[n2], acc_21_nr1_2->acc_m->prefac[m2]));
                    
1207
                    results[2] = z_by_z(do_romhom_real_int(&rom->roq21, ws21->d_u_xy, &ws21->ux_cache_21, &ws21->uy_cache_21, n1, m1, n2, m2), znm2c1);
1208
                }
1209

1210
                if (CALC_MR_KNM(mirror,22) && rom->roq22.enabled) {
1211
                    complex_t znm2c2 = z_by_zc(z_by_z(acc_22_nr2_1->acc_n->prefac[n1], acc_22_nr2_1->acc_m->prefac[m1]),
1212
                                               z_by_z(acc_22_nr2_2->acc_n->prefac[n2], acc_22_nr2_2->acc_m->prefac[m2]));
1213
                    
1214
                    results[3] = z_by_z(do_romhom_real_int(&rom->roq22, ws22->d_u_xy, &ws22->ux_cache_22, &ws22->uy_cache_22, n1, m1, n2, m2), znm2c2);
Daniel Brown's avatar