summation.cxx 67.8 KB
Newer Older
1
#include "summation.h"
2 3 4 5 6 7 8 9
#include "../scaling/strp_tsr.h"
#include "../mapping/mapping.h"
#include "../mapping/distribution.h"
#include "../tensor/untyped_tensor.h"
#include "../shared/util.h"
#include "../shared/memcontrol.h"
#include "sym_seq_sum.h"
#include "sum_tsr.h"
10 11
#include "../symmetry/sym_indices.h"
#include "../symmetry/symmetrization.h"
12
#include "../redistribution/nosym_transp.h"
13
#include "../redistribution/redist.h"
solomon's avatar
solomon committed
14
#include "../scaling/scaling.h"
15 16 17

namespace CTF_int {

18 19
  using namespace CTF;

20
  summation::~summation(){
solomon's avatar
solomon committed
21 22
    if (idx_A != NULL) cdealloc(idx_A);
    if (idx_B != NULL) cdealloc(idx_B);
23 24
  }

solomon's avatar
solomon committed
25
  summation::summation(summation const & other){
26
    A     = other.A;
27
    idx_A = (int*)alloc(sizeof(int)*other.A->order);
28
    memcpy(idx_A, other.idx_A, sizeof(int)*other.A->order);
29
    B     = other.B;
30
    idx_B = (int*)alloc(sizeof(int)*other.B->order);
31
    memcpy(idx_B, other.idx_B, sizeof(int)*other.B->order);
solomon's avatar
solomon committed
32
    if (other.is_custom){
33
      func      = other.func;
solomon's avatar
solomon committed
34
      is_custom = 1;
35 36 37
    } else is_custom = 0; 
    alpha = other.alpha;
    beta  = other.beta;
solomon's avatar
solomon committed
38 39
  }

40 41 42 43 44 45 46 47 48
  summation::summation(tensor *     A_,
                       int const *  idx_A_,
                       char const * alpha_,
                       tensor *     B_,
                       int const *  idx_B_,
                       char const * beta_){
    A         = A_;
    alpha     = alpha_;
    B         = B_;
49 50 51
    beta      = beta_;
    is_custom = 0;

52 53
    idx_A     = (int*)alloc(sizeof(int)*A->order);
    idx_B     = (int*)alloc(sizeof(int)*B->order);
54 55

    memcpy(idx_A, idx_A_, sizeof(int)*A->order);
56
    memcpy(idx_B, idx_B_, sizeof(int)*B->order);
57 58 59 60 61 62 63 64 65 66 67
  }

  summation::summation(tensor *     A_,
                       char const * cidx_A,
                       char const * alpha_,
                       tensor *     B_,
                       char const * cidx_B,
                       char const * beta_){
    A         = A_;
    alpha     = alpha_;
    B         = B_;
68
    beta      = beta_;
69
    is_custom = 0;
70 71
    
    conv_idx(A->order, cidx_A, &idx_A, B->order, cidx_B, &idx_B);
72
  }
73

74
 
75 76 77 78 79 80 81
  summation::summation(tensor *                A_,
                       int const *             idx_A_,
                       char const *            alpha_,
                       tensor *                B_,
                       int const *             idx_B_,
                       char const *            beta_,
                       univar_function const * func_){
82
    A         = A_;
83
    alpha     = alpha_;
84
    B         = B_;
85 86 87 88
    beta      = beta_;
    func      = func_;
    is_custom = 1;

89 90
    idx_A     = (int*)alloc(sizeof(int)*A->order);
    idx_B     = (int*)alloc(sizeof(int)*B->order);
91 92

    memcpy(idx_A, idx_A_, sizeof(int)*A->order);
93
    memcpy(idx_B, idx_B_, sizeof(int)*B->order);
94 95 96
  }

 
97 98 99 100 101 102 103
  summation::summation(tensor *                A_,
                       char const *            cidx_A,
                       char const *            alpha_,
                       tensor *                B_,
                       char const *            cidx_B,
                       char const *            beta_,
                       univar_function const * func_){
104 105 106
    A         = A_;
    alpha     = alpha_;
    B         = B_;
107
    beta      = beta_;
108
    func      = func_;
109
    is_custom = 1;
110 111

    conv_idx(A->order, cidx_A, &idx_A, B->order, cidx_B, &idx_B);
112 113
  }

114
  void summation::execute(bool run_diag){
115 116 117 118
#if DEBUG >= 2
    if (A->wrld->cdt.rank == 0) printf("Summation::execute (head):\n");
    print();
#endif
119
    if (A->is_sparse || B->is_sparse){
120 121
      int stat = sym_sum_tsr(run_diag);
      assert(stat == SUCCESS); 
122 123 124 125
    } else {
      int stat = home_sum_tsr(run_diag);
      assert(stat == SUCCESS); 
    }
126 127 128 129 130 131 132
  }
  
  double summation::estimate_time(){
    assert(0); //FIXME
    return 0.0;
  }

133 134
  void summation::get_fold_indices(int *  num_fold,
                                   int ** fold_idx){
135 136 137
    int i, in, num_tot, nfold, broken;
    int iA, iB, inA, inB, iiA, iiB;
    int * idx_arr, * idx;
138 139
    inv_idx(A->order, idx_A,
            B->order, idx_B,
140
            &num_tot, &idx_arr);
141
    CTF_int::alloc_ptr(num_tot*sizeof(int), (void**)&idx);
142 143 144 145 146

    for (i=0; i<num_tot; i++){
      idx[i] = 1;
    }
    
147
    for (iA=0; iA<A->order; iA++){
148 149
      i      = idx_A[iA];
      iB     = idx_arr[2*i+1];
150
      broken = 0;
151
      inA    = iA;
152
      do {
153
        in = idx_A[inA];
154 155 156
        inB = idx_arr[2*in+1];
        if (((inA>=0) + (inB>=0) != 2) ||
            (iB != -1 && inB - iB != in-i) ||
157
            (iB != -1 && A->sym[inA] != B->sym[inB])){
158
          broken = 1;
159
          //printf("index in = %d inA = %d inB = %d is broken symA = %d symB = %d\n",in, inA, inB, A->sym[inA], B->sym[inB]);
160 161
        }
        inA++;
162
      } while (A->sym[inA-1] != NS);
163 164
      if (broken){
        for (iiA=iA;iiA<inA;iiA++){
165
          idx[idx_A[iiA]] = 0;
166 167 168 169
        }
      }
    }

170
    for (iB=0; iB<B->order; iB++){
171 172
      i      = idx_B[iB];
      iA     = idx_arr[2*i+0];
173
      broken = 0;
174
      inB    = iB;
175
      do {
176
        in = idx_B[inB];
177 178 179
        inA = idx_arr[2*in+0];
        if (((inB>=0) + (inA>=0) != 2) ||
            (iA != -1 && inA - iA != in-i) ||
180
            (iA != -1 && B->sym[inB] != A->sym[inA])){
181 182 183
          broken = 1;
        }
        inB++;
184
      } while (B->sym[inB-1] != NS);
185 186
      if (broken){
        for (iiB=iB;iiB<inB;iiB++){
187
          idx[idx_B[iiB]] = 0;
188 189 190 191 192 193 194 195 196 197 198 199 200 201
        }
      }
    }
    

    nfold = 0;
    for (i=0; i<num_tot; i++){
      if (idx[i] == 1){
        idx[nfold] = i;
        nfold++;
      }
    }
    *num_fold = nfold;
    *fold_idx = idx;
solomon's avatar
solomon committed
202
    CTF_int::cdealloc(idx_arr);
203 204 205 206
  }

  int summation::can_fold(){
    int i, j, nfold, * fold_idx;
207 208 209
    for (i=0; i<A->order; i++){
      for (j=i+1; j<A->order; j++){
        if (idx_A[i] == idx_A[j]) return 0;
210 211
      }
    }
212 213 214
    for (i=0; i<B->order; i++){
      for (j=i+1; j<B->order; j++){
        if (idx_B[i] == idx_B[j]) return 0;
215 216
      }
    }
217
    get_fold_indices(&nfold, &fold_idx);
solomon's avatar
solomon committed
218
    CTF_int::cdealloc(fold_idx);
219 220 221
    /* FIXME: 1 folded index is good enough for now, in the future model */
    return nfold > 0;
  }
222 223 224 225 226 227 228
 
  void summation::get_fold_sum(summation *& fold_sum,
                               int &        all_fdim_A,
                               int &        all_fdim_B,
                               int *&       all_flen_A,
                               int *&       all_flen_B){
    int i, j, nfold, nf;
229 230 231 232 233
    int * fold_idx, * fidx_map_A, * fidx_map_B;
    tensor * ftsr_A, * ftsr_B;

    get_fold_indices(&nfold, &fold_idx);
    if (nfold == 0){
solomon's avatar
solomon committed
234
      CTF_int::cdealloc(fold_idx);
235
      assert(0);
236 237 238
    }

    /* overestimate this space to not bother with it later */
239 240
    CTF_int::alloc_ptr(nfold*sizeof(int), (void**)&fidx_map_A);
    CTF_int::alloc_ptr(nfold*sizeof(int), (void**)&fidx_map_B);
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


    A->fold(nfold, fold_idx, idx_A, 
            &all_fdim_A, &all_flen_A);
    B->fold(nfold, fold_idx, idx_B, 
            &all_fdim_B, &all_flen_B);

    nf = 0;
    for (i=0; i<A->order; i++){
      for (j=0; j<nfold; j++){
        if (A->sym[i] == NS && idx_A[i] == fold_idx[j]){
          fidx_map_A[nf] = j;
          nf++;
        }
      }
    }
    nf = 0;
    for (i=0; i<B->order; i++){
      for (j=0; j<nfold; j++){
        if (B->sym[i] == NS && idx_B[i] == fold_idx[j]){
          fidx_map_B[nf] = j;
          nf++;
        }
      }
    }

    ftsr_A = A->rec_tsr;
    ftsr_B = B->rec_tsr;

270
    int * sidx_A, * sidx_B;
271
    CTF_int::conv_idx<int>(ftsr_A->order, fidx_map_A, &sidx_A,
Edgar Solomonik's avatar
Edgar Solomonik committed
272 273 274 275 276
                           ftsr_B->order, fidx_map_B, &sidx_B);
    
    cdealloc(fidx_map_A);
    cdealloc(fidx_map_B);
    cdealloc(fold_idx);
277

278
    fold_sum = new summation(A->rec_tsr, sidx_A, alpha, B->rec_tsr, sidx_B, beta);
solomon's avatar
solomon committed
279 280
    cdealloc(sidx_A);
    cdealloc(sidx_B);
281 282 283 284 285 286 287 288 289 290 291
  }

  int summation::map_fold(){
    int i, all_fdim_A, all_fdim_B;
    int nvirt_A, nvirt_B;
    int * fnew_ord_A, * fnew_ord_B;
    int * all_flen_A, * all_flen_B;
    int inr_stride;

    summation * fold_sum;
    get_fold_sum(fold_sum, all_fdim_A, all_fdim_B, all_flen_A, all_flen_B);
292
  #if DEBUG>=2
293
    if (A->wrld->rank == 0){
294 295
      printf("Folded summation type:\n");
    }
296
    fold_sum->print();//print_sum(&fold_type,0.0,0.0);
297 298 299
  #endif
   
    //for type order 1 to 3 
300 301 302
    fold_sum->get_len_ordering(&fnew_ord_A, &fnew_ord_B); 
    permute_target(fold_sum->A->order, fnew_ord_A, A->inner_ordering);
    permute_target(fold_sum->B->order, fnew_ord_B, B->inner_ordering);
303 304
    

solomon's avatar
solomon committed
305
    nvirt_A = A->calc_nvirt();
306
    for (i=0; i<nvirt_A; i++){
solomon's avatar
solomon committed
307
      nosym_transpose(all_fdim_A, A->inner_ordering, all_flen_A, 
308
                      A->data + A->sr->el_size*i*(A->size/nvirt_A), 1, A->sr);
309
    }
solomon's avatar
solomon committed
310
    nvirt_B = B->calc_nvirt();
311
    for (i=0; i<nvirt_B; i++){
solomon's avatar
solomon committed
312
      nosym_transpose(all_fdim_B, B->inner_ordering, all_flen_B, 
313
                      B->data + B->sr->el_size*i*(B->size/nvirt_B), 1, B->sr);
314 315 316
    }

    inr_stride = 1;
317 318
    for (i=0; i<fold_sum->A->order; i++){
      inr_stride *= fold_sum->A->pad_edge_len[i];
319 320
    }

solomon's avatar
solomon committed
321 322 323 324
    CTF_int::cdealloc(fnew_ord_A);
    CTF_int::cdealloc(fnew_ord_B);
    CTF_int::cdealloc(all_flen_A);
    CTF_int::cdealloc(all_flen_B);
325

Edgar Solomonik's avatar
Edgar Solomonik committed
326 327
    delete fold_sum;

solomon's avatar
solomon committed
328
    return inr_stride; 
329 330
  }

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
  double summation::est_time_fold(){
    int all_fdim_A, all_fdim_B;
    int * fnew_ord_A, * fnew_ord_B;
    int * all_flen_A, * all_flen_B;
    int * tAiord, * tBiord;

    summation * fold_sum;
    get_fold_sum(fold_sum, all_fdim_A, all_fdim_B, all_flen_A, all_flen_B);
    fold_sum->get_len_ordering(&fnew_ord_A, &fnew_ord_B); 
    CTF_int::alloc_ptr(all_fdim_A*sizeof(int), (void**)&tAiord);
    CTF_int::alloc_ptr(all_fdim_B*sizeof(int), (void**)&tBiord);
    memcpy(tAiord, A->inner_ordering, all_fdim_A*sizeof(int));
    memcpy(tBiord, B->inner_ordering, all_fdim_B*sizeof(int));

    permute_target(fold_sum->A->order, fnew_ord_A, tAiord);
    permute_target(fold_sum->B->order, fnew_ord_B, tBiord);
  
    A->is_folded = 0; 
    delete A->rec_tsr; 
    cdealloc(A->inner_ordering); 
    B->is_folded = 0; 
    delete B->rec_tsr; 
    cdealloc(B->inner_ordering); 

    double esttime = 0.0;

    esttime += A->calc_nvirt()*est_time_transp(all_fdim_A, tAiord, all_flen_A, 1, A->sr);
    esttime += 2.*B->calc_nvirt()*est_time_transp(all_fdim_B, tBiord, all_flen_B, 1, B->sr);
Edgar Solomonik's avatar
Edgar Solomonik committed
359 360 361 362 363 364 365 366 367

    delete fold_sum;

    cdealloc(all_flen_A);
    cdealloc(all_flen_B);
    cdealloc(tAiord);
    cdealloc(tBiord);
    cdealloc(fnew_ord_A);
    cdealloc(fnew_ord_B);
368 369 370 371 372
    return esttime;
  }


 
373 374
  void summation::get_len_ordering(int ** new_ordering_A,
                                   int ** new_ordering_B){
375
    int num_tot;
376 377
    int * ordering_A, * ordering_B, * idx_arr;
    
378 379
    CTF_int::alloc_ptr(sizeof(int)*A->order, (void**)&ordering_A);
    CTF_int::alloc_ptr(sizeof(int)*B->order, (void**)&ordering_B);
380

381 382
    inv_idx(A->order, idx_A,
            B->order, idx_B,
383
            &num_tot, &idx_arr);
384 385 386
    ASSERT(num_tot == A->order);
    ASSERT(num_tot == B->order);
    /*for (i=0; i<num_tot; i++){
387 388
      ordering_A[i] = idx_arr[2*i];
      ordering_B[i] = idx_arr[2*i+1];
389 390 391 392 393 394 395
    }*/
    for (int i=0; i<num_tot; i++){
      ordering_B[i] = i;
      for (int j=0; j<num_tot; j++){
        if (idx_A[j] == idx_B[i])
          ordering_A[i] = j;
      }
396
    }
solomon's avatar
solomon committed
397
    CTF_int::cdealloc(idx_arr);
398 399 400 401
    *new_ordering_A = ordering_A;
    *new_ordering_B = ordering_B;
  }

402 403 404 405 406 407 408
  tsum * summation::construct_sum(int inner_stride){
    int nvirt, i, iA, iB, order_tot, is_top, sA, sB, need_rep, i_A, i_B, j, k;
    int64_t blk_sz_A, blk_sz_B, vrt_sz_A, vrt_sz_B;
    int nphys_dim;
    int * idx_arr, * virt_dim, * phys_mapped;
    int * virt_blk_len_A, * virt_blk_len_B;
    int * blk_len_A, * blk_len_B;
solomon's avatar
solomon committed
409
    tsum * htsum = NULL , ** rec_tsum = NULL;
410
    mapping * map;
solomon's avatar
solomon committed
411
    strp_tsr * str_A, * str_B;
412 413

    is_top = 1;
solomon's avatar
solomon committed
414 415
    inv_idx(A->order, idx_A,
            B->order, idx_B,
416 417
            &order_tot, &idx_arr);

solomon's avatar
solomon committed
418
    nphys_dim = A->topo->order;
419

420 421 422 423 424 425
    CTF_int::alloc_ptr(sizeof(int)*A->order,    (void**)&blk_len_A);
    CTF_int::alloc_ptr(sizeof(int)*B->order,    (void**)&blk_len_B);
    CTF_int::alloc_ptr(sizeof(int)*A->order,    (void**)&virt_blk_len_A);
    CTF_int::alloc_ptr(sizeof(int)*B->order,    (void**)&virt_blk_len_B);
    CTF_int::alloc_ptr(sizeof(int)*order_tot,   (void**)&virt_dim);
    CTF_int::alloc_ptr(sizeof(int)*nphys_dim*2, (void**)&phys_mapped);
426 427 428 429
    memset(phys_mapped, 0, sizeof(int)*nphys_dim*2);


    /* Determine the block dimensions of each local subtensor */
solomon's avatar
solomon committed
430 431 432
    blk_sz_A = A->size;
    blk_sz_B = B->size;
    calc_dim(A->order, blk_sz_A, A->pad_edge_len, A->edge_map,
433
             &vrt_sz_A, virt_blk_len_A, blk_len_A);
solomon's avatar
solomon committed
434
    calc_dim(B->order, blk_sz_B, B->pad_edge_len, B->edge_map,
435 436 437
             &vrt_sz_B, virt_blk_len_B, blk_len_B);

    /* Strip out the relevant part of the tensor if we are contracting over diagonal */
solomon's avatar
solomon committed
438 439
    sA = strip_diag(A->order, order_tot, idx_A, vrt_sz_A,
                           A->edge_map, A->topo, A->sr,
440
                           blk_len_A, &blk_sz_A, &str_A);
solomon's avatar
solomon committed
441 442
    sB = strip_diag(B->order, order_tot, idx_B, vrt_sz_B,
                           B->edge_map, B->topo, B->sr,
443 444
                           blk_len_B, &blk_sz_B, &str_B);
    if (sA || sB){
solomon's avatar
solomon committed
445
      if (A->wrld->cdt.rank == 0)
446
        DPRINTF(1,"Stripping tensor\n");
solomon's avatar
solomon committed
447 448 449
      strp_sum * ssum = new strp_sum;
      ssum->sr_A = A->sr;
      ssum->sr_B = B->sr;
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
      htsum = ssum;
      is_top = 0;
      rec_tsum = &ssum->rec_tsum;

      ssum->rec_strp_A = str_A;
      ssum->rec_strp_B = str_B;
      ssum->strip_A = sA;
      ssum->strip_B = sB;
    }

    nvirt = 1;
    for (i=0; i<order_tot; i++){
      iA = idx_arr[2*i];
      iB = idx_arr[2*i+1];
      if (iA != -1){
solomon's avatar
solomon committed
465
        map = &A->edge_map[iA];
466 467 468 469 470 471 472 473
        while (map->has_child) map = map->child;
        if (map->type == VIRTUAL_MAP){
          virt_dim[i] = map->np;
          if (sA) virt_dim[i] = virt_dim[i]/str_A->strip_dim[iA];
        }
        else virt_dim[i] = 1;
      } else {
        ASSERT(iB!=-1);
solomon's avatar
solomon committed
474
        map = &B->edge_map[iB];
475 476 477 478 479 480 481 482 483 484
        while (map->has_child) map = map->child;
        if (map->type == VIRTUAL_MAP){
          virt_dim[i] = map->np;
          if (sB) virt_dim[i] = virt_dim[i]/str_B->strip_dim[iA];
        }
        else virt_dim[i] = 1;
      }
      nvirt *= virt_dim[i];
    }

solomon's avatar
solomon committed
485 486
    for (i=0; i<A->order; i++){
      map = &A->edge_map[i];
487 488 489 490 491 492 493 494 495 496
      if (map->type == PHYSICAL_MAP){
        phys_mapped[2*map->cdt+0] = 1;
      }
      while (map->has_child) {
        map = map->child;
        if (map->type == PHYSICAL_MAP){
          phys_mapped[2*map->cdt+0] = 1;
        }
      }
    }
solomon's avatar
solomon committed
497 498
    for (i=0; i<B->order; i++){
      map = &B->edge_map[i];
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
      if (map->type == PHYSICAL_MAP){
        phys_mapped[2*map->cdt+1] = 1;
      }
      while (map->has_child) {
        map = map->child;
        if (map->type == PHYSICAL_MAP){
          phys_mapped[2*map->cdt+1] = 1;
        }
      }
    }
    need_rep = 0;
    for (i=0; i<nphys_dim; i++){
      if (phys_mapped[2*i+0] == 0 ||
          phys_mapped[2*i+1] == 0){
        need_rep = 1;
        break;
      }
    }
    if (need_rep){
solomon's avatar
solomon committed
518
      if (A->wrld->cdt.rank == 0)
519 520
        DPRINTF(1,"Replicating tensor\n");

solomon's avatar
solomon committed
521 522 523
      tsum_replicate * rtsum = new tsum_replicate;
      rtsum->sr_A = A->sr;
      rtsum->sr_B = B->sr;
524 525 526 527 528 529
      if (is_top){
        htsum = rtsum;
        is_top = 0;
      } else {
        *rec_tsum = rtsum;
      }
530
      rec_tsum      = &rtsum->rec_tsum;
531 532 533 534
      rtsum->ncdt_A = 0;
      rtsum->ncdt_B = 0;
      rtsum->size_A = blk_sz_A;
      rtsum->size_B = blk_sz_B;
535 536
      rtsum->cdt_A  = NULL;
      rtsum->cdt_B  = NULL;
537 538 539 540 541 542 543 544 545
      for (i=0; i<nphys_dim; i++){
        if (phys_mapped[2*i+0] == 0 && phys_mapped[2*i+1] == 1){
          rtsum->ncdt_A++;
        }
        if (phys_mapped[2*i+1] == 0 && phys_mapped[2*i+0] == 1){
          rtsum->ncdt_B++;
        }
      }
      if (rtsum->ncdt_A > 0)
546
        CTF_int::alloc_ptr(sizeof(CommData*)*rtsum->ncdt_A, (void**)&rtsum->cdt_A);
547
      if (rtsum->ncdt_B > 0)
548
        CTF_int::alloc_ptr(sizeof(CommData*)*rtsum->ncdt_B, (void**)&rtsum->cdt_B);
549 550 551 552
      rtsum->ncdt_A = 0;
      rtsum->ncdt_B = 0;
      for (i=0; i<nphys_dim; i++){
        if (phys_mapped[2*i+0] == 0 && phys_mapped[2*i+1] == 1){
553 554 555
          rtsum->cdt_A[rtsum->ncdt_A] = &A->topo->dim_comm[i];
/*          if (rtsum->cdt_A[rtsum->ncdt_A].alive == 0)
            rtsum->cdt_A[rtsum->ncdt_A].activate(A->wrld->comm);*/
556 557 558
          rtsum->ncdt_A++;
        }
        if (phys_mapped[2*i+1] == 0 && phys_mapped[2*i+0] == 1){
559 560 561
          rtsum->cdt_B[rtsum->ncdt_B] = &B->topo->dim_comm[i];
/*          if (rtsum->cdt_B[rtsum->ncdt_B].alive == 0)
            rtsum->cdt_B[rtsum->ncdt_B].activate(B->wrld->comm);*/
562 563 564 565 566 567 568
          rtsum->ncdt_B++;
        }
      }
      ASSERT(rtsum->ncdt_A == 0 || rtsum->cdt_B == 0);
    }

    int * new_sym_A, * new_sym_B;
569
    CTF_int::alloc_ptr(sizeof(int)*A->order, (void**)&new_sym_A);
solomon's avatar
solomon committed
570
    memcpy(new_sym_A, A->sym, sizeof(int)*A->order);
571
    CTF_int::alloc_ptr(sizeof(int)*B->order, (void**)&new_sym_B);
solomon's avatar
solomon committed
572
    memcpy(new_sym_B, B->sym, sizeof(int)*B->order);
573 574 575

    /* Multiply over virtual sub-blocks */
    if (nvirt > 1){
solomon's avatar
solomon committed
576 577 578
      tsum_virt * tsumv = new tsum_virt;
      tsumv->sr_A = A->sr;
      tsumv->sr_B = B->sr;
579 580 581 582 583 584
      if (is_top) {
        htsum = tsumv;
        is_top = 0;
      } else {
        *rec_tsum = tsumv;
      }
585 586 587 588 589 590 591 592 593 594 595
      rec_tsum         = &tsumv->rec_tsum;

      tsumv->num_dim   = order_tot;
      tsumv->virt_dim  = virt_dim;
      tsumv->order_A   = A->order;
      tsumv->blk_sz_A  = vrt_sz_A;
      tsumv->idx_map_A = idx_A;
      tsumv->order_B   = B->order;
      tsumv->blk_sz_B  = vrt_sz_B;
      tsumv->idx_map_B = idx_B;
      tsumv->buffer    = NULL;
solomon's avatar
solomon committed
596
    } else CTF_int::cdealloc(virt_dim);
597

solomon's avatar
solomon committed
598 599 600
    seq_tsr_sum * tsumseq = new seq_tsr_sum;
    tsumseq->sr_A = A->sr;
    tsumseq->sr_B = B->sr;
601 602 603 604 605
    if (inner_stride == -1){
      tsumseq->is_inner = 0;
    } else {
      tsumseq->is_inner = 1;
      tsumseq->inr_stride = inner_stride;
solomon's avatar
solomon committed
606 607
      tensor * itsr;
      itsr = A->rec_tsr;
608
      i_A = 0;
solomon's avatar
solomon committed
609 610
      for (i=0; i<A->order; i++){
        if (A->sym[i] == NS){
611
          for (j=0; j<itsr->order; j++){
solomon's avatar
solomon committed
612
            if (A->inner_ordering[j] == i_A){
613 614 615
              j=i;
              do {
                j--;
solomon's avatar
solomon committed
616
              } while (j>=0 && A->sym[j] != NS);
617 618 619 620 621 622 623 624 625 626
              for (k=j+1; k<=i; k++){
                virt_blk_len_A[k] = 1;
                new_sym_A[k] = NS;
              }
              break;
            }
          }
          i_A++;
        }
      }
solomon's avatar
solomon committed
627
      itsr = B->rec_tsr;
628
      i_B = 0;
solomon's avatar
solomon committed
629 630
      for (i=0; i<B->order; i++){
        if (B->sym[i] == NS){
631
          for (j=0; j<itsr->order; j++){
solomon's avatar
solomon committed
632
            if (B->inner_ordering[j] == i_B){
633 634 635
              j=i;
              do {
                j--;
solomon's avatar
solomon committed
636
              } while (j>=0 && B->sym[j] != NS);
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
              for (k=j+1; k<=i; k++){
                virt_blk_len_B[k] = 1;
                new_sym_B[k] = NS;
              }
              break;
            }
          }
          i_B++;
        }
      }
    }
    if (is_top) {
      htsum = tsumseq;
      is_top = 0;
    } else {
      *rec_tsum = tsumseq;
    }
654 655 656 657 658 659 660 661 662
    tsumseq->order_A    = A->order;
    tsumseq->idx_map_A  = idx_A;
    tsumseq->edge_len_A = virt_blk_len_A;
    tsumseq->sym_A      = new_sym_A;
    tsumseq->order_B    = B->order;
    tsumseq->idx_map_B  = idx_B;
    tsumseq->edge_len_B = virt_blk_len_B;
    tsumseq->sym_B      = new_sym_B;
    tsumseq->is_custom  = is_custom;
solomon's avatar
solomon committed
663
    if (is_custom){
664
      tsumseq->is_inner = 0;
solomon's avatar
solomon committed
665 666
      tsumseq->func     = func;
    }
667 668
    htsum->alpha        = alpha;
    htsum->beta         = beta;
669

670 671
    htsum->A = A->data;
    htsum->B = B->data;
672

solomon's avatar
solomon committed
673 674 675 676
    CTF_int::cdealloc(idx_arr);
    CTF_int::cdealloc(blk_len_A);
    CTF_int::cdealloc(blk_len_B);
    CTF_int::cdealloc(phys_mapped);
677 678 679 680 681 682

    return htsum;
  }

  int summation::home_sum_tsr(bool run_diag){
    int ret, was_home_A, was_home_B;
solomon's avatar
solomon committed
683
    tensor * tnsr_A, * tnsr_B;
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
    // code below turns summations into scaling, but never seems to be invoked in AQ or test_suite, so commenting it out for now
/*    if (A==B && !is_custom){
      bool is_scal = true;
      for (int i=0; i<A->order; i++){
        if (idx_A[i] != idx_B[i]) is_scal = false;
      }
      if (is_scal){
        if (alpha == NULL && beta == NULL){
          scaling scl = scaling(A, idx_A, NULL);
          scl.execute();
        } else {
          char nalpha[A->sr->el_size];
          if (alpha == NULL) A->sr->copy(nalpha, A->sr->mulid());
          else A->sr->copy(nalpha, alpha);

          if (beta == NULL) A->sr->add(nalpha, A->sr->mulid(), nalpha);
          else A->sr->add(nalpha, beta, nalpha);

          scaling scl = scaling(A, idx_A, nalpha);
          scl.execute();
        }
        return SUCCESS;
      }
    }*/

solomon's avatar
solomon committed
709 710
    summation osum = summation(*this);
   
711
    CTF_int::contract_mst();
712

713 714
    A->unfold();
    B->unfold();
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
    // FIXME: if custom function, we currently don't know whether its odd, even or neither, so unpack everything
    if (is_custom){
      bool is_nonsym=true;
      for (int i=0; i<A->order; i++){
        if (A->sym[i] != NS){
          is_nonsym = false;
        }
      }
      if (!is_nonsym){
        int sym_A[A->order];
        std::fill(sym_A, sym_A+A->order, NS);
        int idx_A[A->order];
        for (int i=0; i<A->order; i++){
          idx_A[i] = i;
        }
        tensor tA(A->sr, A->order, A->lens, sym_A, A->wrld, 1);
        tA.is_home = 0;
732
        tA.has_home = 0;
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 759 760 761 762 763 764 765 766 767 768 769
        summation st(A, idx_A, A->sr->mulid(), &tA, idx_A, A->sr->mulid());
        st.execute();
        summation stme(*this);
        stme.A = &tA;
        stme.execute();
        return SUCCESS;
      }
    }
    if (is_custom){
      bool is_nonsym=true;
      for (int i=0; i<B->order; i++){
        if (B->sym[i] != NS){
          is_nonsym = false;
        }
      }
      if (!is_nonsym){
        int sym_B[B->order];
        std::fill(sym_B, sym_B+B->order, NS);
        int idx_B[B->order];
        for (int i=0; i<B->order; i++){
          idx_B[i] = i;
        }
        tensor tB(B->sr, B->order, B->lens, sym_B, B->wrld, 1);
        tB.is_home = 0;
        if (!B->sr->isequal(B->sr->addid(), beta)){
          summation st(B, idx_B, B->sr->mulid(), &tB, idx_B, B->sr->mulid());
          st.execute();
        }
        summation stme(*this);
        stme.B = &tB;
        stme.execute();
        summation stme2(&tB, idx_B, B->sr->mulid(), B, idx_B, B->sr->addid());
        stme2.execute();
        return SUCCESS;
      }
    }

770 771
  #ifndef HOME_CONTRACT
    #ifdef USE_SYM_SUM
solomon's avatar
solomon committed
772
      ret = sym_sum_tsr(run_diag);
773 774
      return ret;
    #else
solomon's avatar
solomon committed
775
      ret = sum_tensors(run_diag);
776 777 778
      return ret;
    #endif
  #else
solomon's avatar
solomon committed
779 780
    if (A->has_zero_edge_len || 
        B->has_zero_edge_len){
781
      if (!B->sr->isequal(beta,B->sr->mulid()) && !B->has_zero_edge_len){ 
solomon's avatar
solomon committed
782
        int sub_idx_map_B[B->order];
783
        int sm_idx=0;
solomon's avatar
solomon committed
784
        for (int i=0; i<B->order; i++){
785 786 787
          sub_idx_map_B[i]=sm_idx;
          sm_idx++;
          for (int j=0; j<i; j++){
solomon's avatar
solomon committed
788
            if (idx_B[i]==idx_B[j]){
789 790 791 792 793 794
              sub_idx_map_B[i]=sub_idx_map_B[j];
              sm_idx--;
              break;
            }
          }
        }
solomon's avatar
solomon committed
795 796
        scaling scl = scaling(B, sub_idx_map_B, beta);
        scl.execute();
797
      }
solomon's avatar
solomon committed
798
      return SUCCESS;
799
    }
solomon's avatar
solomon committed
800 801 802 803
    if (A == B){
      tensor * cpy_tsr_A = new tensor(A);
      osum.A = cpy_tsr_A;
      osum.execute();
804
      delete cpy_tsr_A;
solomon's avatar
solomon committed
805
      return SUCCESS;
806
    }
solomon's avatar
solomon committed
807 808
    was_home_A = A->is_home;
    was_home_B = B->is_home;
809
    if (was_home_A){
810 811
      tnsr_A              = new tensor(A,0,0);
      tnsr_A->data        = A->data;
solomon's avatar
solomon committed
812
      tnsr_A->home_buffer = A->home_buffer;
813 814 815
      tnsr_A->is_home     = 1;
      tnsr_A->is_mapped   = 1;
      tnsr_A->topo        = A->topo;
solomon's avatar
solomon committed
816 817
      copy_mapping(A->order, A->edge_map, tnsr_A->edge_map);
      tnsr_A->set_padding();
818
      osum.A              = tnsr_A;
819
    } else tnsr_A = NULL;     
820
    if (was_home_B){
821 822
      tnsr_B              = new tensor(B,0,0);
      tnsr_B->data        = B->data;
solomon's avatar
solomon committed
823
      tnsr_B->home_buffer = B->home_buffer;
824 825 826
      tnsr_B->is_home     = 1;
      tnsr_B->is_mapped   = 1;
      tnsr_B->topo        = B->topo;
solomon's avatar
solomon committed
827 828
      copy_mapping(B->order, B->edge_map, tnsr_B->edge_map);
      tnsr_B->set_padding();
829
      osum.B              = tnsr_B;
830
    } else tnsr_B = NULL;
831
  #if DEBUG >= 1
solomon's avatar
solomon committed
832
    if (A->wrld->cdt.rank == 0)
833 834 835 836
      printf("Start head sum:\n");
  #endif
    
    #ifdef USE_SYM_SUM
solomon's avatar
solomon committed
837
    ret = osum.sym_sum_tsr(run_diag);
838
    #else
solomon's avatar
solomon committed
839
    ret = osum.sum_tensors(run_diag);
840 841
    #endif
  #if DEBUG >= 1
solomon's avatar
solomon committed
842
    if (A->wrld->cdt.rank == 0)
843 844 845
      printf("End head sum:\n");
  #endif

solomon's avatar
solomon committed
846
    if (ret!= SUCCESS) return ret;
847 848
    if (was_home_A) tnsr_A->unfold(); 
    else A->unfold();
solomon's avatar
solomon committed
849
    if (was_home_B) tnsr_B->unfold();
850
    else B->unfold();
851

solomon's avatar
solomon committed
852 853
    if (was_home_B && !tnsr_B->is_home){
      if (A->wrld->cdt.rank == 0)
854
        DPRINTF(2,"Migrating tensor %s back to home\n", B->name);
855
      distribution odst(tnsr_B);
solomon's avatar
solomon committed
856 857
      B->data = tnsr_B->data;
      B->is_home = 0;
858
      TAU_FSTART(redistribute_for_sum_home);
solomon's avatar
solomon committed
859
      B->redistribute(odst);
860
      TAU_FSTOP(redistribute_for_sum_home);
861
      memcpy(B->home_buffer, B->data, B->size*B->sr->el_size);
solomon's avatar
solomon committed
862
      CTF_int::cdealloc(B->data);
solomon's avatar
solomon committed
863 864 865 866
      B->data = B->home_buffer;
      B->is_home = 1;
      tnsr_B->is_data_aliased = 1;
      delete tnsr_B;
867
    } else if (was_home_B){
solomon's avatar
solomon committed
868 869
      if (tnsr_B->data != B->data){
        printf("Tensor %s is a copy of %s and did not leave home but buffer is %p was %p\n", tnsr_B->name, B->name, tnsr_B->data, B->data);
870 871 872
        ABORT;

      }
solomon's avatar
solomon committed
873 874 875
      tnsr_B->has_home = 0;
      tnsr_B->is_data_aliased = 1;
      delete tnsr_B;
876
    }
solomon's avatar
solomon committed
877 878 879
    if (was_home_A && !tnsr_A->is_home){
      tnsr_A->has_home = 0;
      delete tnsr_A;
880
    } else if (was_home_A) {
solomon's avatar
solomon committed
881 882 883
      tnsr_A->has_home = 0;
      tnsr_A->is_data_aliased = 1;
      delete tnsr_A;
884 885 886 887 888 889
    }
    return ret;
  #endif
  }

  int summation::sym_sum_tsr(bool run_diag){
890
    int sidx, i, nst_B, * new_idx_map;
solomon's avatar
solomon committed
891
    int * map_A, * map_B;
892
    int ** dstack_map_B;
893
    tensor * tnsr_A, * tnsr_B, * new_tsr, ** dstack_tsr_B;
solomon's avatar
solomon committed
894
    std::vector<summation> perm_types;
895
    std::vector<int> signs;
solomon's avatar
solomon committed
896
    char const * dbeta;
897 898 899
  #if (DEBUG >= 2 || VERBOSE >= 1)
    print();
  #endif
900
    check_consistency();
901 902 903

    A->unfold();
    B->unfold();
904
    if (A->has_zero_edge_len || B->has_zero_edge_len){
905
      if (!B->sr->isequal(beta, B->sr->mulid()) && !B->has_zero_edge_len){ 
906
        int sub_idx_map_B[B->order];
907
        int sm_idx=0;
908
        for (int i=0; i<B->order; i++){
909 910 911
          sub_idx_map_B[i]=sm_idx;
          sm_idx++;
          for (int j=0; j<i; j++){
912
            if (idx_B[i]==idx_B[j]){
913 914 915 916 917 918
              sub_idx_map_B[i]=sub_idx_map_B[j];
              sm_idx--;
              break;
            }
          }
        }
919 920
        scaling scl = scaling(B, sub_idx_map_B, beta);
        scl.execute();
921
      }
solomon's avatar
solomon committed
922
      return SUCCESS;
923
    }
924 925 926 927 928
    // If we have sparisity, use separate mechanism
    if (A->is_sparse || B->is_sparse){
      sp_sum();
      return SUCCESS;
    }
929 930
    tnsr_A = A;
    tnsr_B = B;
931
    char * new_alpha = (char*)alloc(tnsr_B->sr->el_size);
932 933 934 935
    CTF_int::alloc_ptr(sizeof(int)*tnsr_A->order,     (void**)&map_A);
    CTF_int::alloc_ptr(sizeof(int)*tnsr_B->order,     (void**)&map_B);
    CTF_int::alloc_ptr(sizeof(int*)*tnsr_B->order,    (void**)&dstack_map_B);
    CTF_int::alloc_ptr(sizeof(tensor*)*tnsr_B->order, (void**)&dstack_tsr_B);
936 937 938 939
    memcpy(map_A, idx_A, tnsr_A->order*sizeof(int));
    memcpy(map_B, idx_B, tnsr_B->order*sizeof(int));
    while (!run_diag && tnsr_A->extract_diag(map_A, 1, new_tsr, &new_idx_map) == SUCCESS){
      if (tnsr_A != A) delete tnsr_A;
solomon's avatar
solomon committed
940
      CTF_int::cdealloc(map_A);
941
      tnsr_A = new_tsr;
942 943 944
      map_A = new_idx_map;
    }
    nst_B = 0;
945
    while (!run_diag && tnsr_B->extract_diag(map_B, 1, new_tsr, &new_idx_map) == SUCCESS){
946
      dstack_map_B[nst_B] = map_B;
947
      dstack_tsr_B[nst_B] = tnsr_B;
948
      nst_B++;
949
      tnsr_B = new_tsr;
950 951 952
      map_B = new_idx_map;
    }

Edgar Solomonik's avatar
Edgar Solomonik committed
953 954 955
    summation new_sum = summation(*this);
    new_sum.A = tnsr_A;
    new_sum.B = tnsr_B;
956 957
    memcpy(new_sum.idx_A, map_A, sizeof(int)*tnsr_A->order);
    memcpy(new_sum.idx_B, map_B, sizeof(int)*tnsr_B->order);
958
    if (tnsr_A == tnsr_B){
959
      tensor nnew_tsr = tensor(tnsr_A);
Edgar Solomonik's avatar
Edgar Solomonik committed
960 961
      new_sum.A = &nnew_tsr;
      new_sum.B = tnsr_B;
962
      new_sum.sym_sum_tsr(run_diag);
963 964
      
      /*clone_tensor(ntid_A, 1, &new_tid);
965 966 967 968
      new_type = *type;
      new_type.tid_A = new_tid;
      stat = sym_sum_tsr(alpha_, beta, &new_type, ftsr, felm, run_diag);
      del_tsr(new_tid);
969
      return stat;*/
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
    } else {
      
  /*    new_type.tid_A = ntid_A;
      new_type.tid_B = ntid_B;
      new_type.idx_map_A = map_A;
      new_type.idx_map_B = map_B;*/
  
      //FIXME: make these typefree...
      int sign = align_symmetric_indices(tnsr_A->order,
                                         new_sum.idx_A,
                                         tnsr_A->sym,
                                         tnsr_B->order,
                                         new_sum.idx_B,
                                         tnsr_B->sym);
      int ocfact = overcounting_factor(tnsr_A->order,
985
                                       new_sum.idx_A,
986 987
                                       tnsr_A->sym,
                                       tnsr_B->order,
988
                                       new_sum.idx_B,
989
                                       tnsr_B->sym);
990 991 992 993 994 995 996 997 998 999 1000 1001 1002
  
      if (ocfact != 1 || sign != 1){
        if (ocfact != 1){
          tnsr_B->sr->copy(new_alpha, tnsr_B->sr->addid());
          
          for (int i=0; i<ocfact; i++){
            tnsr_B->sr->add(new_alpha, alpha, new_alpha);
          }
          alpha = new_alpha;
        }
        if (sign == -1){
          tnsr_B->sr->addinv(alpha, new_alpha);
          alpha = new_alpha;
1003 1004
        }
      }
1005
  
1006
      /*if (A->sym[0] == SY && B->sym[0] == AS){
solomon's avatar
solomon committed
1007 1008
        print();
        ASSERT(0); 
1009
      }*/
1010
      if (new_sum.unfold_broken_sym(NULL) != -1){
solomon's avatar
solomon committed
1011
        if (A->wrld->cdt.rank == 0)
1012
          DPRINTF(1, "Permutational symmetry is broken\n");
1013 1014 1015 1016 1017
  
        summation * unfold_sum;
        sidx = new_sum.unfold_broken_sym(&unfold_sum);
        int sy;
        sy = 0;
1018
        int sidx2 = unfold_sum->unfold_broken_sym(NULL);
1019 1020
        if (sidx%2 == 0 && (A->sym[sidx/2] == SY || unfold_sum->A->sym[sidx/2] == SY)) sy = 1;
        if (sidx%2 == 1 && (B->sym[sidx/2] == SY || unfold_sum->B->sym[sidx/2] == SY)) sy = 1;
1021
        //if (sy && sidx%2 == 0){
1022 1023 1024 1025 1026
        if (sidx2 != -1 || 
            (sy && (sidx%2 == 0  || !tnsr_B->sr->isequal(new_sum.beta, tnsr_B->sr->addid())))){
          if (sidx%2 == 0){
            if (unfold_sum->A->sym[sidx/2] == NS){
              if (A->wrld->cdt.rank == 0)
1027
                DPRINTF(1,"Performing operand desymmetrization for summation of A idx=%d\n",sidx/2);
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
              desymmetrize(tnsr_A, unfold_sum->A, 0);
            } else {
              if (A->wrld->cdt.rank == 0)
                DPRINTF(1,"Performing operand symmetrization for summation\n");
              symmetrize(unfold_sum->A, tnsr_A);
            }
            //unfold_sum->B = tnsr_B;
            unfold_sum->sym_sum_tsr(run_diag);
    //        sym_sum_tsr(alpha, beta, &unfold_type, ftsr, felm, run_diag);
            if (tnsr_A != unfold_sum->A){
              unfold_sum->A->unfold();
              tnsr_A->pull_alias(unfold_sum->A);
              delete unfold_sum->A;
            }
          } else {
            //unfold_sum->A = tnsr_A;
            if (A->wrld->cdt.rank == 0)
              DPRINTF(1,"Performing product desymmetrization for summation\n");
            desymmetrize(tnsr_B, unfold_sum->B, 1);
            unfold_sum->sym_sum_tsr(run_diag);
            if (A->wrld->cdt.rank == 0)
              DPRINTF(1,"Performing product symmetrization for summation\n");
            if (tnsr_B->data != unfold_sum->B->data && !tnsr_B->sr->isequal(tnsr_B->sr->mulid(), unfold_sum->beta)){
              int sidx_B[tnsr_B->order];
              for (int iis=0; iis<tnsr_B->order; iis++){
                sidx_B[iis] = iis;
              }
              scaling sscl = scaling(tnsr_B, sidx_B, unfold_sum->beta);
              sscl.execute();
            }
            symmetrize(tnsr_B, unfold_sum->B);

    //        sym_sum_tsr(alpha, beta, &unfold_type, ftsr, felm, run_diag);
            if (tnsr_B != unfold_sum->B){
              unfold_sum->B->unfold();
              tnsr_B->pull_alias(unfold_sum->B);
              delete unfold_sum->B;
            }
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
          }
        } else {
          if (sidx != -1 && sidx%2 == 1){
            delete unfold_sum->B;
          } else if (sidx != -1 && sidx%2 == 0){
            delete unfold_sum->A;
          }
          //get_sym_perms(&new_type, alpha, perm_types, signs);
          get_sym_perms(new_sum, perm_types, signs);
          if (A->wrld->cdt.rank == 0)
            DPRINTF(1,"Performing %d summation permutations\n",
                    (int)perm_types.size());
          dbeta = beta;
          char * new_alpha = (char*)alloc(tnsr_B->sr->el_size);
          for (i=0; i<(int)perm_types.size(); i++){
            if (signs[i] == 1)
              B->sr->copy(new_alpha, alpha);
            else
              tnsr_B->sr->addinv(alpha, new_alpha);
            perm_types[i].alpha = new_alpha;
            perm_types[i].beta = dbeta;
1087
            //perm_types[i].A->zero_out_padding();
1088 1089 1090 1091 1092
            perm_types[i].sum_tensors(run_diag);
            /*sum_tensors(new_alpha, dbeta, perm_types[i].tid_A, perm_types[i].tid_B,
                        perm_types[i].idx_map_A, perm_types[i].idx_map_B, ftsr, felm, run_diag);*/
            dbeta = new_sum.B->sr->mulid();
          }
solomon's avatar
solomon committed
1093
          cdealloc(new_alpha);
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
  /*        for (i=0; i<(int)perm_types.size(); i++){
            free_type(&perm_types[i]);
          }*/
          perm_types.clear();
          signs.clear();
        }
        delete unfold_sum;
      } else {
        new_sum.alpha = alpha;
        new_sum.sum_tensors(run_diag);
  /*      sum_tensors(alpha, beta, new_type.tid_A, new_type.tid_B, new_type.idx_map_A,
                    new_type.idx_map_B, ftsr, felm, run_diag);*/
1106 1107
      }
    }
1108
    if (tnsr_A != A) delete tnsr_A;
1109
    for (i=nst_B-1; i>=0; i--){
1110 1111 1112 1113 1114
//      extract_diag(dstack_tid_B[i], dstack_map_B[i], 0, &ntid_B, &new_idx_map);
      dstack_tsr_B[i]->extract_diag(dstack_map_B[i], 0, tnsr_B, &new_idx_map);
      //del_tsr(ntid_B);
      delete tnsr_B;
      tnsr_B = dstack_tsr_B[i];
1115
    }
1116
    ASSERT(tnsr_B == B);
solomon's avatar
solomon committed
1117 1118 1119 1120 1121
    CTF_int::cdealloc(new_alpha);
    CTF_int::cdealloc(map_A);
    CTF_int::cdealloc(map_B);
    CTF_int::cdealloc(dstack_map_B);
    CTF_int::cdealloc(dstack_tsr_B);
1122

solomon's avatar
solomon committed
1123
    return SUCCESS;
1124 1125 1126 1127 1128 1129 1130 1131
  }


  /**
   * \brief PDAXPY: a*idx_map_A(A) + b*idx_map_B(B) -> idx_map_B(B).
   * \param[in] run_diag if 1 run diagonal sum
   */
  int summation::sum_tensors(bool run_diag){
1132
    int stat, * new_idx_map;
1133
    int * map_A, * map_B;
1134
    int nst_B;
1135
    int ** dstack_map_B;
1136 1137
    tensor * tnsr_A, * tnsr_B, * new_tsr, ** dstack_tsr_B;
//    tsum<dtype> * sumf;
solomon's avatar
solomon committed
1138
    tsum * sumf;
1139 1140 1141
    //check_sum(tid_A, tid_B, idx_map_A, idx_map_B);
    //FIXME: hmm all of the below already takes place in sym_sum
    check_consistency();
1142 1143
    A->unfold();
    B->unfold();
1144
    if (A->has_zero_edge_len || B->has_zero_edge_len){
1145
      if (!B->sr->isequal(beta,B->sr->mulid()) && !B->has_zero_edge_len){ 
1146
    /*    fseq_scl<dtype> fs;
1147 1148
        fs.func_ptr=sym_seq_scl_ref<dtype>;
        fseq_elm_scl<dtype> felm;
1149
        felm.func_ptr = NULL;*/
1150
        int sub_idx_map_B[B->order];
1151
        int sm_idx=0;
1152
        for (int i=0; i<B->order; i++){
1153 1154 1155
          sub_idx_map_B[i]=sm_idx;
          sm_idx++;
          for (int j=0; j<i; j++){
1156
            if (idx_B[i]==idx_B[j]){
1157 1158 1159 1160 1161 1162
              sub_idx_map_B[i]=sub_idx_map_B[j];
              sm_idx--;
              break;
            }
          }
        }
1163 1164
        scaling scl = scaling(B, sub_idx_map_B, beta);
        scl.execute();
1165
      }
solomon's avatar
solomon committed
1166
      return SUCCESS;
1167 1168 1169
    }


1170
    //FIXME: remove all of the below, sum_tensors should never be called without sym_sum
1171 1172 1173 1174
    CTF_int::alloc_ptr(sizeof(int)*A->order,  (void**)&map_A);
    CTF_int::alloc_ptr(sizeof(int)*B->order,  (void**)&map_B);
    CTF_int::alloc_ptr(sizeof(int*)*B->order, (void**)&dstack_map_B);
    CTF_int::alloc_ptr(sizeof(tensor*)*B->order, (void**)&dstack_tsr_B);
1175 1176 1177 1178 1179 1180
    tnsr_A = A;
    tnsr_B = B;
    memcpy(map_A, idx_A, tnsr_A->order*sizeof(int));
    memcpy(map_B, idx_B, tnsr_B->order*sizeof(int));
    while (!run_diag && tnsr_A->extract_diag(map_A, 1, new_tsr, &new_idx_map) == SUCCESS){
      if (tnsr_A != A) delete tnsr_A;
solomon's avatar
solomon committed
1181
      CTF_int::cdealloc(map_A);
1182
      tnsr_A = new_tsr;
1183 1184 1185
      map_A = new_idx_map;
    }
    nst_B = 0;
1186
    while (!run_diag && tnsr_B->extract_diag(map_B, 1, new_tsr, &new_idx_map) == SUCCESS){
1187
      dstack_map_B[nst_B] = map_B;
1188
      dstack_tsr_B[nst_B] = tnsr_B;
1189
      nst_B++;
1190
      tnsr_B = new_tsr;
1191 1192
      map_B = new_idx_map;
    }
Edgar Solomonik's avatar
Edgar Solomonik committed
1193 1194 1195
    summation new_sum = summation(*this);
    new_sum.A = tnsr_A;
    new_sum.B = tnsr_B;
1196
    if (tnsr_A == tnsr_B){
solomon's avatar
solomon committed
1197
      tensor * nnew_tsr = new tensor(tnsr_A);
Edgar Solomonik's avatar
Edgar Solomonik committed
1198 1199
      new_sum.A = nnew_tsr;
      new_sum.B = tnsr_B;
1200
    } else{ 
1201 1202
     //FIXME: remove the below, sum_tensors should never be called without sym_sum
     int sign = align_symmetric_indices(tnsr_A->order,
1203
                                        new_sum.idx_A,
1204 1205
                                        tnsr_A->sym,
                                        tnsr_B->order,
1206
                                        new_sum.idx_B,
1207
                                        tnsr_B->sym);
1208 1209 1210 1211 1212

      #if DEBUG >= 1
        new_sum.print();
      #endif

1213
      ASSERT(sign == 1);
solomon's avatar
solomon committed
1214
/*        if (sign == -1){
1215 1216
          char * new_alpha = (char*)malloc(tnsr_B->sr->el_size);
          tnsr_B->sr->addinv(alpha, new_alpha);
solomon's avatar
solomon committed
1217 1218
          alpha = new_alpha;
        }*/
1219

1220
  #if 0 //VERIFY
1221 1222 1223 1224 1225 1226 1227 1228
      int64_t nsA, nsB;
      int64_t nA, nB;
      dtype * sA, * sB;
      dtype * uA, * uB;
      int order_A, order_B,  i;
      int * edge_len_A, * edge_len_B;
      int * sym_A, * sym_B;
      stat = allread_tsr(ntid_A, &nsA, &sA);
solomon's avatar
solomon committed
1229
      assert(stat == SUCCESS);
1230 1231

      stat = allread_tsr(ntid_B, &nsB, &sB);
solomon's avatar
solomon committed
1232
      assert(stat == SUCCESS);
1233 1234 1235 1236 1237 1238 1239 1240
  #endif

      TAU_FSTART(sum_tensors);

      /* Check if the current tensor mappings can be summed on */
  #if REDIST
      if (1) {
  #else
1241
      if (new_sum.check_mapping() == 0) {
1242 1243
  #endif
        /* remap if necessary */
1244
        stat = new_sum.map();
1245
        if (stat == ERROR) {
1246
          printf("Failed to map tensors to physical grid\n");
1247
          return ERROR;
1248 1249
        }
      } else {
1250
  #if DEBUG > 2
solomon's avatar
solomon committed
1251
        if (A->wrld->cdt.rank == 0){
1252 1253
          printf("Keeping mappings:\n");
        }
1254 1255
        tnsr_A->print_map(stdout);
        tnsr_B->print_map(stdout);
1256 1257 1258
  #endif
      }
      /* Construct the tensor algorithm we would like to use */
1259
      ASSERT(new_sum.check_mapping());
1260
  #if FOLD_TSR
1261
      if (is_custom == false && new_sum.can_fold()){
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
        //FIXME bit of a guess, no?
        double est_time_nofold = 4.*(A->size + B->size)*COST_MEMBW;
        if (new_sum.est_time_fold() + (A->size + B->size)*COST_MEMBW < est_time_nofold){
          /*if (A->wrld->cdt.rank == 0)
            printf("Decided to fold\n");*/
          int inner_stride;
          TAU_FSTART(map_fold);
          inner_stride = new_sum.map_fold();
          TAU_FSTOP(map_fold);
          sumf = new_sum.construct_sum(inner_stride);
        } else {
          /*if (A->wrld->cdt.rank == 0)
            printf("Decided not to fold\n");*/
        
          sumf = new_sum.construct_sum();
        }
1278 1279 1280 1281 1282 1283
      } else{
  #if DEBUG >= 1
        if (A->wrld->cdt.rank == 0){
          printf("Could not fold summation, is_custom = %d, new_sum.can_fold = %d\n", is_custom, new_sum.can_fold());
        }
  #endif
Edgar Solomonik's avatar
Edgar Solomonik committed
1284
        sumf = new_sum.construct_sum();
1285
      }
solomon's avatar
solomon committed
1286 1287
        /*sumf = construct_sum(alpha, beta, ntid_A, map_A, ntid_B, map_B,
                             ftsr, felm);*/
1288
  #else
Edgar Solomonik's avatar
Edgar Solomonik committed
1289
      sumf = new_sum.construct_sum();
solomon's avatar
solomon committed
1290 1291
      /*sumf = construct_sum(alpha, beta, ntid_A, map_A, ntid_B, map_B,
                           ftsr, felm);*/
1292 1293 1294 1295 1296 1297 1298
  #endif
      /*TAU_FSTART(zero_sum_padding);
      stat = zero_out_padding(ntid_A);
      TAU_FSTOP(zero_sum_padding);
      TAU_FSTART(zero_sum_padding);
      stat = zero_out_padding(ntid_B);
      TAU_FSTOP(zero_sum_padding);*/
solomon's avatar
solomon committed
1299
      DEBUG_PRINTF("[%d] performing tensor sum\n", A->wrld->cdt.rank);
1300
  #if DEBUG >=3
1301
      /*if (A->wrld->cdt.rank == 0){
1302 1303 1304 1305 1306 1307
        for (int i=0; i<tensors[ntid_A]->order; i++){
          printf("padding[%d] = %d\n",i, tensors[ntid_A]->padding[i]);
        }
        for (int i=0; i<tensors[ntid_B]->order; i++){
          printf("padding[%d] = %d\n",i, tensors[ntid_B]->padding[i]);
        }
1308
      }*/
1309 1310
  #endif

1311 1312 1313
  #if DEBUG >= 2
      if (tnsr_B->wrld->rank==0)
        sumf->print();
1314 1315
      tnsr_A->print_map();
      tnsr_B->print_map();
1316
  #endif
1317 1318
      TAU_FSTART(sum_func);
      /* Invoke the contraction algorithm */
1319
      tnsr_A->topo->activate();
1320
      MPI_Barrier(tnsr_B->wrld->comm);
1321
      sumf->run();
1322
      /*tnsr_B->unfold();
1323 1324 1325 1326 1327 1328 1329 1330
      tnsr_B->print();
      MPI_Barrier(tnsr_B->wrld->comm);
      if (tnsr_B->wrld->rank==1){
      for (int i=0; i<tnsr_B->size; i++){
        printf("[%d] %dth element  ",tnsr_B->wrld->rank,i);
        tnsr_B->sr->print(tnsr_B->data+i*tnsr_B->sr->el_size);
        printf("\n");
      }
1331 1332
      }*/
      tnsr_A->topo->deactivate();
solomon's avatar
solomon committed
1333 1334
      tnsr_A->unfold();
      tnsr_B->unfold();
1335 1336 1337
#ifndef SEQ
      stat = tnsr_B->zero_out_padding();
#endif
1338
      TAU_FSTOP(sum_func);
1339

1340
  #if 0 //VERIFY
1341
      stat = allread_tsr(ntid_A, &nA, &uA);
solomon's avatar
solomon committed
1342
      assert(stat == SUCCESS);
1343
      stat = get_info(ntid_A, &order_A, &edge_len_A, &sym_A);
solomon's avatar
solomon committed
1344
      assert(stat == SUCCESS);
1345 1346

      stat = allread_tsr(ntid_B, &nB, &uB);
solomon's avatar
solomon committed
1347
      assert(stat == SUCCESS);
1348
      stat = get_info(ntid_B, &order_B, &edge_len_B, &sym_B);
solomon's avatar
solomon committed
1349
      assert(stat == SUCCESS);
1350 1351 1352

      if (nsA != nA) { printf("nsA = " PRId64 ", nA = " PRId64 "\n",nsA,nA); ABORT; }
      if (nsB != nB) { printf("nsB = " PRId64 ", nB = " PRId64 "\n",nsB,nB); ABORT; }
1353
      for (i=0; (int64_t)i<nA; i++){
1354 1355 1356 1357 1358 1359 1360
        if (fabs(uA[i] - sA[i]) > 1.E-6){
          printf("A[i] = %lf, sA[i] = %lf\n", uA[i], sA[i]);
        }
      }

      cpy_sym_sum(alpha, uA, order_A, edge_len_A, edge_len_A, sym_A, map_A,
                  beta, sB, order_B, edge_len_B, edge_len_B, sym_B, map_B);
solomon's avatar
solomon committed
1361
      assert(stat == SUCCESS);
1362

1363
      for (i=0; (int64_t)i<nB; i++){
1364 1365 1366 1367 1368
        if (fabs(uB[i] - sB[i]) > 1.E-6){
          printf("B[%d] = %lf, sB[%d] = %lf\n", i, uB[i], i, sB[i]);
        }
        assert(fabs(sB[i] - uB[i]) < 1.E-6);
      }
solomon's avatar
solomon committed
1369 1370 1371 1372
      CTF_int::cdealloc(uA);
      CTF_int::cdealloc(uB);
      CTF_int::cdealloc(sA);
      CTF_int::cdealloc(sB);
1373 1374 1375
  #endif

      delete sumf;
solomon's avatar
solomon committed
1376
      if (tnsr_A != A) delete tnsr_A;
1377
      for (int i=nst_B-1; i>=0; i--){
solomon's avatar
solomon committed
1378
        int ret = dstack_tsr_B[i]->extract_diag(dstack_map_B[i], 0, tnsr_B, &new_idx_map);
solomon's avatar
solomon committed
1379
        ASSERT(ret == SUCCESS);
solomon's avatar
solomon committed
1380 1381
        delete tnsr_B;
        tnsr_B = dstack_tsr_B[i];
1382
      }
solomon's avatar
solomon committed
1383
      ASSERT(tnsr_B == B);
1384
    }
1385
  //#ifndef SEQ
1386
    //stat = B->zero_out_padding();
1387
  //#endif
solomon's avatar
solomon committed
1388 1389 1390 1391
    CTF_int::cdealloc(map_A);
    CTF_int::cdealloc(map_B);
    CTF_int::cdealloc(dstack_map_B);
    CTF_int::cdealloc(dstack_tsr_B);
1392 1393

    TAU_FSTOP(sum_tensors);
solomon's avatar
solomon committed
1394
    return SUCCESS;
1395 1396
  }

1397 1398 1399
  int summation::unfold_broken_sym(summation ** nnew_sum){
    int sidx, i, num_tot, iA, iA2, iB;
    int * idx_arr;
1400
    int bsym = NS;
solomon's avatar
solomon committed
1401
    summation * new_sum;
1402 1403 1404 1405
   
    if (nnew_sum != NULL){
      new_sum = new summation(*this);
      *nnew_sum = new_sum;
1406
    } else new_sum = NULL;
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417

    inv_idx(A->order, idx_A,
            B->order, idx_B,
            &num_tot, &idx_arr);

    sidx = -1;
    for (i=0; i<A->order; i++){
      if (A->sym[i] != NS){
        iA = idx_A[i];
        if (idx_arr[2*iA+1] != -1){
          if (B->sym[idx_arr[2*iA+1]] == NS ||
1418
              ((B->sym[idx_arr[2*iA+1]] == AS) ^ (A->sym[i] == AS)) ||
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
              idx_arr[2*idx_A[i+1]+1] == -1 ||
              idx_A[i+1] != idx_B[idx_arr[2*iA+1]+1]){
            sidx = 2*i;
            break;
          }
        } else if (idx_arr[2*idx_A[i+1]+1] != -1){
          sidx = 2*i;
          break;
        }
      }
    } 
    if (sidx == -1){
      for (i=0; i<B->order; i++){
        if (B->sym[i] != NS){
          iB = idx_B[i];
          if (idx_arr[2*iB+0] != -1){
            if (A->sym[idx_arr[2*iB+0]] == NS ||
1436
                ((A->sym[idx_arr[2*iB+0]] == AS) ^ (B->sym[i] == AS)) ||
1437 1438 1439 1440
                idx_arr[2*idx_B[i+1]+0] == -1 ||
                idx_B[i+1] != idx_A[idx_arr[2*iB+0]+1]){
              sidx = 2*i+1;
              break;
1441 1442 1443 1444
            } else if (A->sym[idx_arr[2*iB+0]] == NS){
              sidx = 2*i;
              bsym = B->sym[i];
              break;
1445 1446 1447 1448 1449 1450 1451 1452
            }
          } else if (idx_arr[2*idx_B[i+1]+0] != -1){
            sidx = 2*i+1;
            break;
          }
        }
      }
    }
1453
    //if we have e.g. b[""] = A["ij"] with SY A, symmetry preserved bu t need to account for diagonal, this just unpacks (FIXME: suboptimal)
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
    if (sidx == -1){
      for (i=0; i<A->order; i++){
        if (A->sym[i] == SY){
          iA = idx_A[i];
          iA2 = idx_A[i+1];
          if (idx_arr[2*iA+1] == -1 &&
              idx_arr[2*iA2+1] == -1){
            sidx = 2*i;
            break;
          }
        }
      }
    } 
    if (nnew_sum != NULL && sidx != -1){
      if(sidx%2 == 0){
        new_sum->A = new tensor(A, 0, 0);
1470 1471
        int nA_sym[A->order];
        memcpy(nA_sym, new_sum->A->sym, sizeof(int)*new_sum->A->order);
1472
        nA_sym[sidx/2] = bsym;
1473
        new_sum->A->set_sym(nA_sym);
1474 1475
      } else {
        new_sum->B = new tensor(B, 0, 0);
1476 1477 1478 1479
        int nB_sym[B->order];
        memcpy(nB_sym, new_sum->B->sym, sizeof(int)*new_sum->B->order);
        nB_sym[sidx/2] = NS;
        new_sum->B->set_sym(nB_sym);
1480 1481
      }
    }
solomon's avatar
solomon committed
1482
    CTF_int::cdealloc(idx_arr);
1483 1484 1485 1486 1487 1488 1489 1490
    return sidx;
  }

  void summation::check_consistency(){
    int i, num_tot, len;
    int iA, iB;
    int * idx_arr;
       
1491 1492
    inv_idx(A->order, idx_A,
            B->order, idx_B,
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
            &num_tot, &idx_arr);

    for (i=0; i<num_tot; i++){
      len = -1;
      iA = idx_arr[2*i+0];
      iB = idx_arr[2*i+1];
      if (iA != -1){
        len = A->lens[iA];
      }
      if (len != -1 && iB != -1 && len != B->lens[iB]){
solomon's avatar
solomon committed
1503
        if (A->wrld->cdt.rank == 0){
1504
          printf("i = %d Error in sum call: The %dth edge length (%d) of tensor %s does not",
solomon's avatar
solomon committed
1505
                  i, iA, len, A->name);
1506
          printf("match the %dth edge length (%d) of tensor %s.\n",
solomon's avatar
solomon committed
1507
                  iB, B->lens[iB], B->name);
1508 1509 1510 1511
        }
        ABORT;
      }
    }
solomon's avatar
solomon committed
1512
    CTF_int::cdealloc(idx_arr);
1513 1514 1515 1516

  }


1517
  int summation::is_equal(summation const & os){
1518 1519
    int i;

1520 1521
    if (A != os.A) return 0;
    if (B != os.B) return 0;
1522

solomon's avatar
solomon committed
1523
    for (i=0; i<A->order; i++){
1524
      if (idx_A[i] != os.idx_A[i]) return 0;
1525
    }
solomon's avatar
solomon committed
1526
    for (i=0; i<B->order; i++){
1527
      if (idx_B[i] != os.idx_B[i]) return 0;
1528 1529 1530
    }
    return 1;
  }
1531

1532 1533
  int summation::check_mapping(){
    int i, pass, order_tot, iA, iB;
1534
    int * idx_arr; //, * phys_map;
1535
    //mapping * map;
1536 1537 1538 1539 1540 1541 1542 1543

    TAU_FSTART(check_sum_mapping);
    pass = 1;
    
    if (A->is_mapped == 0) pass = 0;
    if (B->is_mapped == 0) pass = 0;
    
    
1544 1545
    if (A->is_folded == 1) pass = 0;
    if (B->is_folded == 1) pass = 0;
1546 1547 1548 1549
    
    if (A->topo != B->topo) pass = 0;

    if (pass==0){
1550
      DPRINTF(4,"failed confirmation here\n");
1551 1552 1553 1554
      TAU_FSTOP(check_sum_mapping);
      return 0;
    }
    
1555 1556
    //CTF_int::alloc_ptr(sizeof(int)*A->topo->order, (void**)&phys_map);
    //memset(phys_map, 0, sizeof(int)*A->topo->order);
1557

1558 1559
    inv_idx(A->order, idx_A,
            B->order, idx_B,
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
            &order_tot, &idx_arr);

    if (!check_self_mapping(A, idx_A))
      pass = 0;
    if (!check_self_mapping(B, idx_B))
      pass = 0;
    if (pass == 0)
      DPRINTF(4,"failed confirmation here\n");

    for (i=0; i<order_tot; i++){
      iA = idx_arr[2*i];
      iB = idx_arr[2*i+1];
      if (iA != -1 && iB != -1) {
        if (!comp_dim_map(&A->edge_map[iA], &B->edge_map[iB])){
          pass = 0;
          DPRINTF(4,"failed confirmation here i=%d\n",i);
        }
      }
1578
      /*if (iA != -1) {
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
        map = &A->edge_map[iA];
        if (map->type == PHYSICAL_MAP)
          phys_map[map->cdt] = 1;
        while (map->has_child) {
          map = map->child;
          if (map->type == PHYSICAL_MAP)
            phys_map[map->cdt] = 1;
        }
      }
      if (iB != -1){
        map = &B->edge_map[iB];
        if (map->type == PHYSICAL_MAP)
          phys_map[map->cdt] = 1;
        while (map->has_child) {
          map = map->child;
          if (map->type == PHYSICAL_MAP)
            phys_map[map->cdt] = 1;
        }
1597
      }*/
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
    }
    /* Ensure that something is mapped to each dimension, since replciation
       does not make sense in sum for all tensors */
  /*  for (i=0; i<topovec[A->itopo].order; i++){
      if (phys_map[i] == 0) {
        pass = 0;
        DPRINTF(3,"failed confirmation here i=%d\n",i);
      }
    }*/

solomon's avatar
solomon committed
1608 1609
    //CTF_int::cdealloc(phys_map);
    CTF_int::cdealloc(idx_arr);
1610 1611 1612 1613 1614 1615

    TAU_FSTOP(check_sum_mapping);

    return pass;
  }

1616 1617 1618
  int summation::map_sum_indices(topology const * topo){
    int tsr_order, isum, iA, iB, i, j, jsum, jX, stat;
    int * tsr_edge_len, * tsr_sym_table, * restricted;
solomon's avatar
solomon committed
1619
    int * idx_arr, * idx_sum;
1620 1621 1622 1623 1624
    int num_sum, num_tot, idx_num;
    idx_num = 2;
    mapping * sum_map;

    TAU_FSTART(map_sum_indices);
solomon's avatar
solomon committed
1625

1626 1627
    inv_idx(A->order, idx_A,
            B->order, idx_B,
solomon's avatar
solomon committed
1628 1629
            &num_tot, &idx_arr);

1630
    CTF_int::alloc_ptr(sizeof(int)*num_tot, (void**)&idx_sum);
solomon's avatar
solomon committed
1631 1632 1633 1634 1635 1636 1637
    
    num_sum = 0;
    for (i=0; i<num_tot; i++){
      if (idx_arr[2*i] != -1 && idx_arr[2*i+1] != -1){
        idx_sum[num_sum] = i;
        num_sum++;
      }
1638
    }
1639 1640 1641 1642

    tsr_order = num_sum;


1643 1644 1645 1646
    CTF_int::alloc_ptr(tsr_order*sizeof(int),           (void**)&restricted);
    CTF_int::alloc_ptr(tsr_order*sizeof(int),           (void**)&tsr_edge_len);
    CTF_int::alloc_ptr(tsr_order*tsr_order*sizeof(int), (void**)&tsr_sym_table);
    CTF_int::alloc_ptr(tsr_order*sizeof(mapping),       (void**)&sum_map);
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725

    memset(tsr_sym_table, 0, tsr_order*tsr_order*sizeof(int));
    memset(restricted, 0, tsr_order*sizeof(int));

    for (i=0; i<tsr_order; i++){ 
      sum_map[i].type             = NOT_MAPPED; 
      sum_map[i].has_child        = 0;
      sum_map[i].np               = 1;
    }
    for (i=0; i<num_sum; i++){
      isum = idx_sum[i];
      iA = idx_arr[isum*2+0];
      iB = idx_arr[isum*2+1];

      if (A->edge_map[iA].type != NOT_MAPPED){
        ASSERT(B->edge_map[iB].type == NOT_MAPPED);
        copy_mapping(1, &A->edge_map[iA], &sum_map[i]);
      } else if (B->edge_map[iB].type != NOT_MAPPED){
        copy_mapping(1, &B->edge_map[iB], &sum_map[i]);
      }
    }

    /* Map a tensor of dimension.
     * Set the edge lengths and symmetries according to those in sum dims of A and B.
     * This gives us a mapping for the common mapped dimensions of tensors A and B. */
    for (i=0; i<num_sum; i++){
      isum = idx_sum[i];
      iA = idx_arr[isum*idx_num+0];
      iB = idx_arr[isum*idx_num+1];

      tsr_edge_len[i] = A->pad_edge_len[iA];

      /* Check if A has symmetry among the dimensions being contracted over.
       * Ignore symmetry with non-contraction dimensions.
       * FIXME: this algorithm can be more efficient but should not be a bottleneck */
      if (A->sym[iA] != NS){
        for (j=0; j<num_sum; j++){
          jsum = idx_sum[j];
          jX = idx_arr[jsum*idx_num+0];
          if (jX == iA+1){
            tsr_sym_table[i*tsr_order+j] = 1;
            tsr_sym_table[j*tsr_order+i] = 1;
          }
        }
      }
      if (B->sym[iB] != NS){
        for (j=0; j<num_sum; j++){
          jsum = idx_sum[j];
          jX = idx_arr[jsum*idx_num+1];
          if (jX == iB+1){
            tsr_sym_table[i*tsr_order+j] = 1;
            tsr_sym_table[j*tsr_order+i] = 1;
          }
        }
      }
    }
    /* Run the mapping algorithm on this construct */
    stat = map_tensor(topo->order,        tsr_order, 
                      tsr_edge_len,       tsr_sym_table,
                      restricted,         topo->dim_comm,
                      NULL,               0,
                      sum_map);

    if (stat == ERROR){
      TAU_FSTOP(map_sum_indices);
      return ERROR;
    }
    
    /* define mapping of tensors A and B according to the mapping of sum dims */
    if (stat == SUCCESS){
      for (i=0; i<num_sum; i++){
        isum = idx_sum[i];
        iA = idx_arr[isum*idx_num+0];
        iB = idx_arr[isum*idx_num+1];

        copy_mapping(1, &sum_map[i], &A->edge_map[iA]);
        copy_mapping(1, &sum_map[i], &B->edge_map[iB]);
      }
    }
solomon's avatar
solomon committed
1726 1727 1728
    CTF_int::cdealloc(restricted);
    CTF_int::cdealloc(tsr_edge_len);
    CTF_int::cdealloc(tsr_sym_table);
1729 1730 1731
    for (i=0; i<num_sum; i++){
      sum_map[i].clear();
    }
solomon's avatar
solomon committed
1732 1733 1734
    CTF_int::cdealloc(sum_map);
    CTF_int::cdealloc(idx_sum);
    CTF_int::cdealloc(idx_arr);
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752

    TAU_FSTOP(map_sum_indices);
    return stat;

  }

  int summation::map(){
    int i, ret, need_remap;
    int need_remap_A, need_remap_B;
    int d;
    topology * old_topo_A, * old_topo_B;
    int btopo;
    int gtopo;

    ASSERT(A->wrld == B->wrld);
    World * wrld = A->wrld;
   
    TAU_FSTART(map_tensor_pair);
solomon's avatar
solomon committed
1753
  #if DEBUG >= 2
1754
    if (wrld->rank == 0)
solomon's avatar
solomon committed
1755
      printf("Initial mappings:\n");
1756
    A->print_map(stdout);
1757
    B->print_map(stdout);
solomon's avatar
solomon committed
1758 1759
  #endif

1760 1761 1762 1763 1764 1765
    //FIXME: try to avoid unfolding immediately, as its not always necessary
    A->unfold();
    B->unfold();
    A->set_padding();
    B->set_padding();

1766

1767 1768
    distribution dA(A);
    distribution dB(B);
1769 1770 1771 1772 1773 1774
    old_topo_A = A->topo;
    old_topo_B = B->topo;
    mapping * old_map_A = new mapping[A->order];
    mapping * old_map_B = new mapping[B->order];
    copy_mapping(A->order, A->edge_map, old_map_A);
    copy_mapping(B->order, B->edge_map, old_map_B);
solomon's avatar
solomon committed
1775
    btopo = -1;
1776 1777
    int64_t size;
    int64_t min_size = INT64_MAX;
solomon's avatar
solomon committed
1778
    /* Attempt to map to all possible permutations of processor topology */
1779
    for (i=A->wrld->cdt.rank; i<2*(int)A->wrld->topovec.size(); i+=A->wrld->cdt.np){
solomon's avatar
solomon committed
1780
  //  for (i=global_comm.rank*topovec.size(); i<2*(int)topovec.size(); i++){
1781 1782 1783 1784
      A->clear_mapping();
      B->clear_mapping();
      A->set_padding();
      B->set_padding();
solomon's avatar
solomon committed
1785

1786 1787 1788 1789
      A->topo = wrld->topovec[i/2];
      B->topo = wrld->topovec[i/2];
      A->is_mapped = 1;
      B->is_mapped = 1;
solomon's avatar
solomon committed
1790 1791

      if (i%2 == 0){
1792 1793
        ret = map_self_indices(A, idx_A);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1794 1795
        else if (ret != SUCCESS) return ret;
      } else {
1796 1797
        ret = map_self_indices(B, idx_B);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1798 1799
        else if (ret != SUCCESS) return ret;
      }
1800 1801
      ret = map_sum_indices(A->topo);
      if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1802 1803 1804 1805
      else if (ret != SUCCESS){
        return ret;
      }
      if (i%2 == 0){
1806 1807
        ret = map_self_indices(A, idx_A);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1808 1809
        else if (ret != SUCCESS) return ret;
      } else {
1810 1811
        ret = map_self_indices(B, idx_B);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1812 1813 1814 1815
        else if (ret != SUCCESS) return ret;
      }

      if (i%2 == 0){
1816 1817
        ret = map_self_indices(A, idx_A);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1818
        else if (ret != SUCCESS) return ret;
1819 1820 1821
        ret = A->map_tensor_rem(A->topo->order, 
                                A->topo->dim_comm);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1822
        else if (ret != SUCCESS) return ret;
1823 1824 1825 1826 1827 1828
        copy_mapping(A->order, B->order,
                     idx_A, A->edge_map, 
                     idx_B, B->edge_map,0);
        ret = B->map_tensor_rem(B->topo->order, 
                                B->topo->dim_comm);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1829 1830
        else if (ret != SUCCESS) return ret;
      } else {
1831 1832
        ret = map_self_indices(B, idx_B);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1833
        else if (ret != SUCCESS) return ret;
1834 1835 1836
        ret = B->map_tensor_rem(B->topo->order, 
                                B->topo->dim_comm);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1837
        else if (ret != SUCCESS) return ret;
1838 1839 1840 1841 1842 1843
        copy_mapping(B->order, A->order,
                     idx_B, B->edge_map, 
                     idx_A, A->edge_map,0);
        ret = A->map_tensor_rem(A->topo->order, 
                                A->topo->dim_comm);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1844 1845 1846
        else if (ret != SUCCESS) return ret;
      }
      if (i%2 == 0){
1847 1848
        ret = map_self_indices(B, idx_B);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1849 1850
        else if (ret != SUCCESS) return ret;
      } else {
1851 1852
        ret = map_self_indices(A, idx_A);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1853 1854 1855
        else if (ret != SUCCESS) return ret;
      }

1856 1857
  /*    ret = map_symtsr(A->order, A->sym_table, A->edge_map);
      ret = map_symtsr(B->order, B->sym_table, B->edge_map);
solomon's avatar
solomon committed
1858 1859 1860
      if (ret!=SUCCESS) return ret;
      return SUCCESS;*/

1861
  #if DEBUG >= 4
1862 1863
      A->print_map(stdout,0);
      B->print_map(stdout,0);
solomon's avatar
solomon committed
1864
  #endif
1865 1866 1867 1868
      if (!check_mapping()) continue;
      A->set_padding();
      B->set_padding();
      size = A->size + B->size;
solomon's avatar
solomon committed
1869 1870 1871 1872

      need_remap_A = 0;
      need_remap_B = 0;

1873 1874 1875
      if (A->topo == old_topo_A){
        for (d=0; d<A->order; d++){
          if (!comp_dim_map(&A->edge_map[d],&old_map_A[d]))
solomon's avatar
solomon committed
1876 1877 1878 1879 1880
            need_remap_A = 1;
        }
      } else
        need_remap_A = 1;
      if (need_remap_A){
1881 1882
        if (can_block_reshuffle(A->order, dA.phase, A->edge_map)){
          size += A->size*log2(wrld->cdt.np);
solomon's avatar
solomon committed
1883
        } else {
1884
          size += 5.*A->size*log2(wrld->cdt.np);
solomon's avatar
solomon committed
1885 1886
        }
      }
1887 1888 1889
      if (B->topo == old_topo_B){
        for (d=0; d<B->order; d++){
          if (!comp_dim_map(&B->edge_map[d],&old_map_B[d]))
solomon's avatar
solomon committed
1890 1891 1892 1893 1894
            need_remap_B = 1;
        }
      } else
        need_remap_B = 1;
      if (need_remap_B){
1895 1896
        if (can_block_reshuffle(B->order, dB.phase, B->edge_map)){
          size += B->size*log2(wrld->cdt.np);
solomon's avatar
solomon committed
1897
        } else {
1898
          size += 5.*B->size*log2(wrld->cdt.np);
solomon's avatar
solomon committed
1899 1900 1901
        }
      }

1902 1903
      /*nvirt = (int64_t)calc_nvirt(A);
      tnvirt = nvirt*(int64_t)calc_nvirt(B);
solomon's avatar
solomon committed
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
      if (tnvirt < nvirt) nvirt = UINT64_MAX;
      else nvirt = tnvirt;
      if (btopo == -1 || nvirt < bnvirt ) {
        bnvirt = nvirt;
        btopo = i;      
      }*/
      if (btopo == -1 || size < min_size){
        min_size = size;
        btopo = i;      
      }
    }
    if (btopo == -1)
1916
      min_size = INT64_MAX;
solomon's avatar
solomon committed
1917
    /* pick lower dimensional mappings, if equivalent */
1918
    gtopo = get_best_topo(min_size, btopo, wrld->cdt);
solomon's avatar
solomon committed
1919 1920 1921 1922 1923 1924 1925
    TAU_FSTOP(map_tensor_pair);
    if (gtopo == -1){
      printf("ERROR: Failed to map pair!\n");
      ABORT;
      return ERROR;
    }
    
1926 1927 1928 1929
    A->clear_mapping();
    B->clear_mapping();
    A->set_padding();
    B->set_padding();
1930

1931 1932
    A->topo = wrld->topovec[gtopo/2];
    B->topo = wrld->topovec[gtopo/2];
1933 1934 1935

    A->is_mapped = 1;
    B->is_mapped = 1;
solomon's avatar
solomon committed
1936 1937
      
    if (gtopo%2 == 0){
1938
      ret = map_self_indices(A, idx_A);
solomon's avatar
solomon committed
1939
      ASSERT(ret == SUCCESS);
1940
    } else {
1941
      ret = map_self_indices(B, idx_B);
solomon's avatar
solomon committed
1942
      ASSERT(ret == SUCCESS);
1943
    }
1944
    ret = map_sum_indices(A->topo);
solomon's avatar
solomon committed
1945
    ASSERT(ret == SUCCESS);
1946 1947 1948 1949 1950 1951 1952
    if (gtopo%2 == 0){
      ret = map_self_indices(A, idx_A);
      ASSERT(ret == SUCCESS);
    } else {
      ret = map_self_indices(B, idx_B);
      ASSERT(ret == SUCCESS);
    }
1953

solomon's avatar
solomon committed
1954
    if (gtopo%2 == 0){
1955
      ret = map_self_indices(A, idx_A);
solomon's avatar
solomon committed
1956
      ASSERT(ret == SUCCESS);
1957 1958
      ret = A->map_tensor_rem(A->topo->order, 
                              A->topo->dim_comm);
solomon's avatar
solomon committed
1959
      ASSERT(ret == SUCCESS);
1960 1961 1962 1963 1964
      copy_mapping(A->order, B->order,
                   idx_A, A->edge_map, 
                   idx_B, B->edge_map,0);
      ret = B->map_tensor_rem(B->topo->order, 
                              B->topo->dim_comm);
solomon's avatar
solomon committed
1965
      ASSERT(ret == SUCCESS);
1966
    } else {
1967
      ret = map_self_indices(B, idx_B);
solomon's avatar
solomon committed
1968
      ASSERT(ret == SUCCESS);
1969 1970
      ret = B->map_tensor_rem(B->topo->order, 
                              B->topo->dim_comm);
solomon's avatar
solomon committed
1971
      ASSERT(ret == SUCCESS);
1972 1973 1974 1975 1976
      copy_mapping(B->order, A->order,
                   idx_B, B->edge_map, 
                   idx_A, A->edge_map,0);
      ret = A->map_tensor_rem(A->topo->order, 
                              A->topo->dim_comm);
solomon's avatar
solomon committed
1977
      ASSERT(ret == SUCCESS);
1978
    }
1979
    if (gtopo%2 == 0){
1980
      ret = map_self_indices(B, idx_B);
1981 1982
      ASSERT(ret == SUCCESS);
    } else {
1983
      ret = map_self_indices(A, idx_A);
1984 1985 1986
      ASSERT(ret == SUCCESS);
    }

1987
    ASSERT(check_mapping());
1988

1989 1990
    A->set_padding();
    B->set_padding();
1991
  #if DEBUG > 2
1992
    if (wrld->cdt.rank == 0)
solomon's avatar
solomon committed
1993
      printf("New mappings:\n");
1994 1995
    A->print_map(stdout);
    B->print_map(stdout);
solomon's avatar
solomon committed
1996
  #endif
1997

solomon's avatar
solomon committed
1998 1999
    TAU_FSTART(redistribute_for_sum);
   
2000 2001
    A->is_cyclic = 1;
    B->is_cyclic = 1;
solomon's avatar
solomon committed
2002
    need_remap = 0;
2003 2004 2005
    if (A->topo == old_topo_A){
      for (d=0; d<A->order; d++){
        if (!comp_dim_map(&A->edge_map[d],&old_map_A[d]))
solomon's avatar
solomon committed
2006
          need_remap = 1;
2007 2008
      }
    } else
solomon's avatar
solomon committed
2009 2010
      need_remap = 1;
    if (need_remap)
2011
      A->redistribute(dA);
solomon's avatar
solomon committed
2012
    need_remap = 0;
2013 2014 2015
    if (B->topo == old_topo_B){
      for (d=0; d<B->order; d++){
        if (!comp_dim_map(&B->edge_map[d],&old_map_B[d]))
solomon's avatar
solomon committed
2016
          need_remap = 1;
2017 2018
      }
    } else
solomon's avatar
solomon committed
2019 2020
      need_remap = 1;
    if (need_remap)
2021
      B->redistribute(dB);
solomon's avatar
solomon committed
2022 2023

    TAU_FSTOP(redistribute_for_sum);
2024 2025
    delete [] old_map_A;
    delete [] old_map_B;
2026

solomon's avatar
solomon committed
2027
    return SUCCESS;
2028
  }
2029 2030 2031 2032 2033 2034 2035 2036 2037 2038

  void summation::print(){
    int i,j,max,ex_A, ex_B;
    max = A->order+B->order;
    CommData global_comm = A->wrld->cdt;
    MPI_Barrier(global_comm.cm);
    if (global_comm.rank == 0){
      printf("Summing Tensor %s into %s\n", A->name, B->name);
      if (alpha != NULL){
        printf("alpha is "); 
2039 2040
        if (beta != NULL) A->sr->print(alpha);
        printf("null"); 
2041
        printf("\nbeta is "); 
2042 2043
        if (beta != NULL) B->sr->print(beta);
        printf("null"); 
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
        printf("\n");
      }
      printf("Summation index table:\n");
      printf("     A     B\n");
      for (i=0; i<max; i++){
        ex_A=0;
        ex_B=0;
        printf("%d:   ",i);
        for (j=0; j<A->order; j++){
          if (idx_A[j] == i){
            ex_A++;
solomon's avatar
solomon committed
2055 2056 2057 2058 2059 2060
            if (A->sym[j] == SY)
              printf("%dY ",j);
            else if (A->sym[j] == SH)
              printf("%dH ",j);
            else if (A->sym[j] == AS)
              printf("%dS ",j);
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
            else
              printf("%d  ",j);
          }
        }
        if (ex_A == 0)
          printf("      ");
        if (ex_A == 1)
          printf("   ");
        for (j=0; j<B->order; j++){
          if (idx_B[j] == i){
            ex_B=1;
solomon's avatar
solomon committed
2072 2073 2074 2075 2076 2077
            if (B->sym[j] == SY)
              printf("%dY ",j);
            else if (B->sym[j] == SH)
              printf("%dH ",j);
            else if (B->sym[j] == AS)
              printf("%dS ",j);
2078 2079 2080 2081 2082 2083 2084 2085 2086
            else
              printf("%d  ",j);
          }
        }
        printf("\n");
        if (ex_A + ex_B== 0) break;
      }
    }
  }
2087
              
2088

2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
  void summation::sp_sum(){
    int64_t num_pair;
    char * mapped_data;
    
    bool is_idx_matched = true;
    if (A->order != B->order)
      is_idx_matched = false;
    else {
      for (int o=0; o<A->order; o++){
        if (idx_A[o] != idx_B[o]){
          is_idx_matched = false;
        }
      }
    }

2104

2105
    //read data from A    
2106
    A->read_local_nnz(&num_pair, &mapped_data);
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135

    if (!is_idx_matched){
      int64_t lda_A[A->order];
      int64_t lda_B[B->order];
      lda_A[0] = 1;
      for (int o=1; o<A->order; o++){
        lda_A[o] = lda_A[o-1]*A->lens[o];
      }
      lda_B[0] = 1;
      for (int o=1; o<B->order; o++){
        lda_B[o] = lda_B[o-1]*B->lens[o];
      }
      PairIterator pi(A->sr, mapped_data);
      #pragma omp parallel for
      for (int i=0; i<num_pair; i++){
        int64_t k = pi[i].k();
        int64_t k_new = 0;
        for (int o=0; o<A->order; o++){
          int64_t kpart = (k/lda_A[o])%A->lens[o];
          //FIXME: slow, but handles diagonal indexing, probably worth having separate versions
          for (int q=0; q<B->order; q++){
            if (idx_A[o] == idx_B[q]){
              k_new += kpart*lda_B[q];
            }
          }
        }
        ((int64_t*)(pi[i].ptr))[0] = k_new;
      }

2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
      // when idx_A has indices idx_B does not, we need to reduce, which can be done partially here since the elements of A should be sorted
      bool is_reduce = false;
      for (int oA=0; oA<A->order; oA++){
        bool inB = false;
        for (int oB=0; oB<B->order; oB++){
          if (idx_A[oA] == idx_B[oB]){
            inB = true;
          }
        }
        if (!inB) is_reduce = true;
      }
  
      if (is_reduce && num_pair > 0){
        pi.sort(num_pair);
        int64_t nuniq=1;
        for (int64_t i=1; i<num_pair; i++){
          if (pi[i].k() != pi[i-1].k()) nuniq++;
        }
        if (nuniq != num_pair){
          char * swap_data = mapped_data;
          alloc_ptr(A->sr->pair_size()*nuniq, (void**)&mapped_data);
          PairIterator pi_new(A->sr, mapped_data);
          int64_t cp_st = 0;
          int64_t acc_st = -1;
          int64_t pfx = 0;
          for (int64_t i=1; i<num_pair; i++){
            if (pi[i].k() == pi[i-1].k()){
              if (cp_st < i){ 
                memcpy(pi_new[pfx].ptr, pi[cp_st].ptr, A->sr->pair_size()*(i-cp_st));
                pfx += i-cp_st;
              }
              cp_st = i+1;

              if (acc_st == -1) acc_st = i;
            } else {
              if (acc_st != -1){
                for (int64_t j=acc_st; j<i; j++){
                  A->sr->add(pi_new[pfx-1].d(), pi[j].d(), pi_new[pfx-1].d());
                }
              }
              acc_st = -1;
            }           
          }
          if (cp_st < num_pair)
            memcpy(pi_new[pfx].ptr, pi[cp_st].ptr, A->sr->pair_size()*(num_pair-cp_st));
          if (acc_st != -1){
            for (int64_t j=acc_st; j<num_pair; j++){
              A->sr->add(pi_new[pfx-1].d(), pi[j].d(), pi_new[pfx-1].d());
            }
          }
          cdealloc(swap_data);
          num_pair = nuniq;
        }
      }

      // if applying custom function, apply immediately on reduced form
      if (is_custom){
        char * swap_data = mapped_data;
        alloc_ptr(B->sr->pair_size()*num_pair, (void**)&mapped_data);
        PairIterator pi_new(B->sr, mapped_data);
#ifdef USE_OMP
        #pragma omp parallel for
#endif
        for (int64_t i=0; i<num_pair; i++){
          if (alpha == NULL)
2201
            func->apply_f(pi[i].d(), pi_new[i].d());
2202 2203 2204
          else  {
            char tmp_A[A->sr->el_size];
            A->sr->mul(pi[i].d(), alpha, tmp_A);
2205
            func->apply_f(tmp_A, pi_new[i].d());
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
          }
        }
        cdealloc(swap_data);
        alpha = NULL;
      }
  
      // when idx_B has indices idx_A does not, we need to map, which we do by replicating the key value pairs of B
      // FIXME this is probably not most efficient, but not entirely stupid, as at least the set of replicated pairs is not expected to be bigger than B
      int nmap_idx = 0;
      int64_t map_idx_len[B->order];
      int64_t map_idx_lda[B->order];
      int map_idx_rev[B->order];
      for (int oB=0; oB<B->order; oB++){
        bool inA = false;
        for (int oA=0; oA<A->order; oA++){
          if (idx_A[oA] == idx_B[oB]){
            inA = true;
          }
        }
        if (!inA){ 
          bool is_rep=false;
          for (int ooB=0; ooB<oB; ooB++){
            if (idx_B[ooB] == idx_B[oB]){
              is_rep = true;
              map_idx_lda[map_idx_rev[ooB]] += lda_B[oB];
              break;
            }
          }
          if (!is_rep){
            map_idx_len[nmap_idx] = B->lens[oB];
            map_idx_lda[nmap_idx] = lda_B[oB];
            map_idx_rev[nmap_idx] = oB;
            nmap_idx++;
          }
        }
      }
      if (nmap_idx > 0){
        int64_t tot_rep=1;
        for (int midx=0; midx<nmap_idx; midx++){
          tot_rep *= map_idx_len[midx];
        }
        char * swap_data = mapped_data;
        alloc_ptr(A->sr->pair_size()*num_pair*tot_rep, (void**)&mapped_data);
        PairIterator pi_new(A->sr, mapped_data);
#ifdef USE_OMP
        #pragma omp parallel for
#endif
        for (int64_t i=0; i<num_pair; i++){
          for (int64_t r=0; r<tot_rep; r++){
            memcpy(pi_new[i*tot_rep+r].ptr, pi[i].ptr, A->sr->pair_size());
          }
        }
#ifdef USE_OMP
        #pragma omp parallel for
#endif
        for (int64_t i=0; i<num_pair; i++){
          int64_t phase=1;
          for (int midx=0; midx<nmap_idx; midx++){
            int64_t stride=phase;
            phase *= map_idx_len[midx];
            for (int64_t r=0; r<tot_rep/phase; r++){
              for (int64_t m=1; m<map_idx_len[midx]; m++){
                for (int64_t s=0; s<stride; s++){
                  ((int64_t*)(pi_new[i*tot_rep + r*phase + m*stride + s].ptr))[0] += m*map_idx_lda[midx];
                }
              }
            }
          }
        }
        cdealloc(swap_data);
        num_pair *= tot_rep;
      }
    }
2279 2280 2281 2282 2283 2284
    
    B->write(num_pair, alpha, beta, mapped_data, 'w');
    cdealloc(mapped_data);

  }

2285
}