aboutsummaryrefslogtreecommitdiff
path: root/Carpet/Carpet/src/Recompose.cc
blob: 9ec0714af4d786cb2008e9e95cff1a5d7f644fa1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
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
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <algorithm>
#include <fstream>
#include <iomanip>
#include <list>
#include <sstream>
#include <string>
#include <vector>

#include "cctk.h"
#include "cctk_Parameters.h"

#include "CactusBase/IOUtil/src/ioGH.h"

#include "bbox.hh"
#include "bboxset.hh"
#include "defs.hh"
#include "gh.hh"
#include "vect.hh"

#include "carpet.hh"

extern "C" {
  static const char* rcsid = "$Header: /home/eschnett/C/carpet/Carpet/Carpet/Carpet/src/Recompose.cc,v 1.47 2003/11/05 16:18:37 schnetter Exp $";
  CCTK_FILEVERSION(Carpet_Carpet_Recompose_cc);
}

#define DEBUG false             // false or true



namespace Carpet {
  
  using namespace std;
  
  
  
  typedef vect<bool,dim> bvect;
  
  typedef vect<int,dim> ivect;
  typedef bbox<int,dim> ibbox;
  
  typedef vect<double,dim> dvect;
  
  typedef vect<vect<bool,2>,dim> bbvect;
  
  
  
  static int (*regrid_routine) (const cGH * cckgGH,
				gh<dim>::rexts& bbsss,
				gh<dim>::rbnds& obss,
				gh<dim>::rprocs& pss) = 0;
  
  
  
  static void CheckRegions (const gh<dim>::rexts& bbsss,
			    const gh<dim>::rbnds& obss,
			    const gh<dim>::rprocs& pss);
  static void Adapt (const cGH* cgh, int reflevels, gh<dim>* hh);
  
  static void Output (const cGH* cgh, const gh<dim>* hh);
  
  static void OutputGridStructure (const cGH *cgh,
				   const gh<dim>::rexts& bbsss,
				   const gh<dim>::rbnds& obss,
				   const gh<dim>::rprocs& pss);
  
  
  
  void SplitRegions (const cGH* cgh,
                     vector<ibbox>& bbs,
                     vector<bbvect>& obs);
  void SplitRegions_AlongZ (const cGH* cgh,
                            vector<ibbox>& bbs,
                            vector<bbvect>& obs);
  void SplitRegions_AlongDir (const cGH* cgh,
                              vector<ibbox>& bbs,
                              vector<bbvect>& obs,
                              const int dir);
  static void SplitRegions_Automatic_Recursively (bvect const & dims,
                                                  int const nprocs,
                                                  dvect const dshape,
                                                  ibbox const & bb,
                                                  bbvect const & ob,
                                                  vector<ibbox> & bbs,
                                                  vector<bbvect> & obs);
  void SplitRegions_Automatic (const cGH* cgh,
                               vector<ibbox>& bbs,
                               vector<bbvect>& obs);
  static void SplitRegions_AsSpecified (const cGH* cgh,
                                        vector<ibbox>& bbs,
                                        vector<bbvect>& obs);
  
  static void MakeProcessors_RoundRobin (const cGH* cgh,
					 const gh<dim>::rexts& bbss,
					 gh<dim>::rprocs& pss);
  
  
  
  void CheckRegions (const gh<dim>::rexts& bbsss, const gh<dim>::rbnds& obss,
		     const gh<dim>::rprocs& pss)
  {
    // At least one level
    if (bbsss.size() == 0) {
      CCTK_WARN (0, "I cannot set up a grid hierarchy with zero refinement levels.");
    }
    assert (bbsss.size() > 0);
    // At most maxreflevels levels
    if ((int)bbsss.size() > maxreflevels) {
      CCTK_VWarn (0, __LINE__, __FILE__, CCTK_THORNSTRING,
		  "I cannot set up a grid hierarchy with more than Carpet::max_refinement_levels refinement levels.  I found Carpet::max_refinement_levels=%d, while %d levels were requested.",
		  (int)maxreflevels, (int)bbsss.size());
    }
    assert ((int)bbsss.size() <= maxreflevels);
    for (int rl=0; rl<(int)bbsss.size(); ++rl) {
      // No empty levels
      assert (bbsss[rl].size() > 0);
      for (int c=0; c<(int)bbsss[rl].size(); ++c) {
	// At least one multigrid level
	assert (bbsss[rl][c].size() > 0);
	for (int ml=0; ml<(int)bbsss[rl][c].size(); ++ml) {
	  // Check sizes
	  // Do allow processors with zero grid points
// 	  assert (all(bbsss[rl][c][ml].lower() <= bbsss[rl][c][ml].upper()));
	  // Check strides
	  const int str = ipow(reffact, maxreflevels-rl-1) * ipow(mgfact, ml);
	  assert (all(bbsss[rl][c][ml].stride() == str));
	  // Check alignments
	  assert (all(bbsss[rl][c][ml].lower() % str == 0));
	  assert (all(bbsss[rl][c][ml].upper() % str == 0));
	}
      }
    }
    
    assert (pss.size() == bbsss.size());
    assert (obss.size() == bbsss.size());
    for (int rl=0; rl<(int)bbsss.size(); ++rl) {
      assert (obss[rl].size() == bbsss[rl].size());
      assert (pss[rl].size() == bbsss[rl].size());
    }
  }
  
  
  
  void RegisterRegridRoutine (int (*routine)(const cGH * cckgGH,
					     gh<dim>::rexts& bbsss,
					     gh<dim>::rbnds& obss,
					     gh<dim>::rprocs& pss))
  {
    assert (!regrid_routine);
    regrid_routine = routine;
  }
  
  
  
  void Regrid (const cGH* cgh,
               const int initialise_from, const bool do_prolongate)
  {
    assert (mglevel == -1);
    assert (component == -1);
    
    if (!regrid_routine) {
      static bool didtell = false;
      if (!didtell) {
	CCTK_WARN (1, "No regridding routine has been registered.  There will be no regridding.  (Maybe you forgot to activate the regridding thorn?)");
	didtell = true;
      }
      return;
    }
    
    // Check whether to recompose
    gh<dim>::rexts bbsss;
    gh<dim>::rbnds obss;
    gh<dim>::rprocs pss;
    int do_recompose = (*regrid_routine) (cgh, bbsss, obss, pss);
    assert (do_recompose >= 0);
    if (do_recompose == 0) return;
    Recompose (cgh, bbsss, obss, pss, initialise_from, do_prolongate);
  }
  
  
  
  void Recompose (const cGH* const cgh,
		  const gh<dim>::rexts& bbsss,
		  const gh<dim>::rbnds& obss,
		  const gh<dim>::rprocs& pss,
                  const int initialise_from,
                  const bool do_prolongate)
  {
    assert (mglevel == -1);
    assert (component == -1);
    
    // Check the regions
    CheckRegions (bbsss, obss, pss);
    
    // Write grid structure to file
    OutputGridStructure (cgh, bbsss, obss, pss);
    
    // Recompose
    hh->recompose (bbsss, obss, pss, initialise_from, do_prolongate);
    
    Output (cgh, hh);
  }
  
  
  
  // This routine is a leftover.  It determines "automatically" how
  // scalars and arrays should be refined.  The user really should
  // have a possibility to define how arrays are to be refined.
  static void Adapt (const cGH* cgh, const int reflevels, gh<dim>* hh)
  {
    const int nprocs   = CCTK_nProcs(cgh);
    vector<vector<ibbox> > bbss(reflevels);
    // note: what this routine calls "ub" is "ub+str" elsewhere
    ivect rstr = hh->baseextent.stride();
    ivect rlb  = hh->baseextent.lower();
    ivect rub  = hh->baseextent.upper() + rstr;
    for (int rl=0; rl<reflevels; ++rl) {
      if (rl>0) {
	// save old values
	const ivect oldrlb = rlb;
	const ivect oldrub = rub;
	// calculate extent
	const ivect rextent = rub - rlb;
	// calculate new extent
	assert (all(rextent % hh->reffact == 0));
	const ivect newrextent = rextent / hh->reffact;
	// refined boxes have smaller stride
	assert (all(rstr%hh->reffact == 0));
	rstr /= hh->reffact;
 	// refine around the lower boundary only
 	rlb = rlb;
	rub = rlb + newrextent;
	// require rub<oldrub because we really want rub-rstr<=oldrub-oldstr
	assert (all(rlb >= oldrlb && rub < oldrub));
      }
      vector<ibbox> bbs(nprocs);
      for (int c=0; c<nprocs; ++c) {
	ivect cstr = rstr;
	ivect clb = rlb;
	ivect cub = rub;
	// split the components along the z axis
	const int glonpz = (rub[dim-1] - rlb[dim-1]) / cstr[dim-1];
	const int locnpz = (glonpz + nprocs - 1) / nprocs;
	const int zstep = locnpz * cstr[dim-1];
	clb[dim-1] = rlb[dim-1] + zstep *  c;
	cub[dim-1] = rlb[dim-1] + zstep * (c+1);
 	if (clb[dim-1] > rub[dim-1]) clb[dim-1] = rub[dim-1];
 	if (cub[dim-1] > rub[dim-1]) cub[dim-1] = rub[dim-1];
	assert (clb[dim-1] <= cub[dim-1]);
	assert (cub[dim-1] <= rub[dim-1]);
	bbs[c] = ibbox(clb, cub-cstr, cstr);
      }
//       bbss[rl] = bbs;
      bbss[rl].clear();
      assert (Carpet::hh->components(rl) % nprocs == 0);
      for (int cc=0; cc<(int)Carpet::hh->components(rl)/nprocs; ++cc) {
	bbss[rl].insert(bbss[rl].end(), bbs.begin(), bbs.end());
      }
    }
    
    vector<vector<vector<ibbox> > > bbsss
      = hh->make_multigrid_boxes(bbss, mglevels);
    
    vector<vector<int> > pss(bbss.size());
    vector<vector<bbvect> > obss(bbss.size());
    for (int rl=0; rl<reflevels; ++rl) {
      pss[rl] = vector<int>(bbss[rl].size());
      obss[rl] = vector<bbvect>(bbss[rl].size());
      // make sure all processors have the same number of components
      assert (bbss[rl].size() % nprocs == 0);
      for (int c=0; c<(int)bbss[rl].size(); ++c) {
	// distribute among processors
	pss[rl][c] = c % nprocs;
	for (int d=0; d<dim; ++d) {
	  // assume the components are split along the z axis
	  obss[rl][c][d][0] = d<dim-1 || c==0;
	  obss[rl][c][d][1] = d<dim-1 || c==(int)bbss[rl].size()-1;
	}
      }
    }
    
    hh->recompose(bbsss, obss, pss, 0, true);
  }
  
  
  
  static void Output (const cGH* cgh, const gh<dim>* hh)
  {
    DECLARE_CCTK_PARAMETERS;
    
    if (verbose) {
      cout << endl;
      cout << "New bounding boxes:" << endl;
      for (int rl=0; rl<hh->reflevels(); ++rl) {
	for (int c=0; c<hh->components(rl); ++c) {
	  for (int ml=0; ml<hh->mglevels(rl,c); ++ml) {
	    cout << "   rl " << rl << "   c " << c << "   ml " << ml
		 << "   bbox " << hh->extents[rl][c][ml] << endl;
	  }
	}
      }
      cout << endl;
      cout << "New processor distribution:" << endl;
      for (int rl=0; rl<hh->reflevels(); ++rl) {
	for (int c=0; c<hh->components(rl); ++c) {
	  cout << "   rl " << rl << "   c " << c
	       << "   processor " << hh->processors[rl][c] << endl;
	}
      }
      cout << endl;
    }
  }
  
  
  
  static void OutputGridStructure (const cGH * const cgh,
				   const gh<dim>::rexts& bbsss,
				   const gh<dim>::rbnds& obss,
				   const gh<dim>::rprocs& pss)
  {
    DECLARE_CCTK_PARAMETERS;
    
    // Output only on the root processor
    if (CCTK_MyProc(cgh) != 0) return;
    
    // Output only if output is desired
    if (strcmp(grid_structure_filename, "") == 0) return;
    
    // Get grid hierarchy extentsion from IOUtil
    const ioGH * const iogh = (const ioGH *)CCTK_GHExtension (cgh, "IO");
    
    // Output only if IO exists and has been initialised
    if (! iogh) return;
    
    assert (iogh);
    
    // Create the output directory
    CCTK_CreateDirectory (0755, out_dir);
    
    ostringstream filenamebuf;
    filenamebuf << out_dir << "/" << grid_structure_filename;
    // we need a persistent temporary here
    string filenamestr = filenamebuf.str();
    const char * filename = filenamestr.c_str();
    
    ofstream file;
    
    static bool do_truncate = true;
    
    if (do_truncate) {
      do_truncate = false;
      struct stat fileinfo;
      if (! iogh->recovered
	  || stat(filename, &fileinfo)!=0) {
	file.open (filename, ios::out | ios::trunc);
	assert (file.good());
	file << "# grid structure" << endl
	     << "# format: reflevel component mglevel   processor bounding-box is-outer-boundary" << endl;
	assert (file.good());
      }
    }
    if (! file.is_open()) {
      file.open (filename, ios::app);
      assert (file.good());
    }
    
    file << "iteration " << cgh->cctk_iteration << endl;
    file << "reflevels " << bbsss.size() << endl;
    for (int rl=0; rl<(int)bbsss.size(); ++rl) {
      file << rl << " components " << bbsss[rl].size() << endl;
      for (int c=0; c<(int)bbsss[rl].size(); ++c) {
	file << rl << " " << c << " mglevels " << bbsss[rl][c].size() << endl;
	for (int ml=0; ml<(int)bbsss[rl][c].size(); ++ml) {
	  file << rl << " " << c << " " << ml << "   " << pss[rl][c] << " " << bbsss[rl][c][ml] << obss[rl][c] << endl;
	}
      }
    }
    file << endl;
    
    file.close();
    assert (file.good());
  }
  
  
  
  // TODO: this routine should go into CarpetRegrid (except maybe
  // SplitRegions_AlongZ for grid arrays)
  void SplitRegions (const cGH* cgh, vector<ibbox>& bbs, vector<bbvect>& obs)
  {
    DECLARE_CCTK_PARAMETERS;
    
    if (CCTK_EQUALS (processor_topology, "along-z")) {
      SplitRegions_AlongZ (cgh, bbs, obs);
    } else if (CCTK_EQUALS (processor_topology, "along-dir")) {
      SplitRegions_AlongDir (cgh, bbs, obs, split_direction);
    } else if (CCTK_EQUALS (processor_topology, "automatic")) {
      SplitRegions_Automatic (cgh, bbs, obs);
    } else if (CCTK_EQUALS (processor_topology, "manual")) {
      SplitRegions_AsSpecified (cgh, bbs, obs);
    } else {
      assert (0);
    }
  }
  
  
  
  void SplitRegions_AlongZ (const cGH* cgh, vector<ibbox>& bbs,
			    vector<bbvect>& obs)
  {
    SplitRegions_AlongDir (cgh, bbs, obs, 2);
  }
  
  
  
  void SplitRegions_AlongDir (const cGH* cgh, vector<ibbox>& bbs,
                              vector<bbvect>& obs,
                              const int dir)
  {
    // Something to do?
    if (bbs.size() == 0) return;
    
    const int nprocs = CCTK_nProcs(cgh);
    
    if (nprocs==1) return;
    
    assert (bbs.size() == 1);
    
    assert (dir>=0 && dir<dim);
    
    const ivect rstr = bbs[0].stride();
    const ivect rlb  = bbs[0].lower();
    const ivect rub  = bbs[0].upper() + rstr;
    const bbvect obnd = obs[0];
    
    bbs.resize(nprocs);
    obs.resize(nprocs);
    for (int c=0; c<nprocs; ++c) {
      ivect cstr = rstr;
      ivect clb = rlb;
      ivect cub = rub;
      const int glonpz = (rub[dir] - rlb[dir]) / cstr[dir];
      const int locnpz = (glonpz + nprocs - 1) / nprocs;
      const int zstep = locnpz * cstr[dir];
      clb[dir] = rlb[dir] + zstep *  c;
      cub[dir] = rlb[dir] + zstep * (c+1);
      if (clb[dir] > rub[dir]) clb[dir] = rub[dir];
      if (cub[dir] > rub[dir]) cub[dir] = rub[dir];
      assert (clb[dir] <= cub[dir]);
      assert (cub[dir] <= rub[dir]);
      bbs[c] = ibbox(clb, cub-cstr, cstr);
      obs[c] = obnd;
      if (c>0)        obs[c][dir][0] = false;
      if (c<nprocs-1) obs[c][dir][1] = false;
    }
  }
  
  
  
  void SplitRegions_Automatic_Recursively (bvect const & dims,
                                           int const nprocs,
                                           dvect const dshape,
                                           ibbox const & bb,
                                           bbvect const & ob,
                                           vector<ibbox> & bbs,
                                           vector<bbvect> & obs)
  {
    if (DEBUG) cout << "SRAR enter" << endl;
    // check preconditions
    assert (nprocs >= 1);
    
    // are we done?
    if (all(dims)) {
      if (DEBUG) cout << "SRAR bottom" << endl;
      
      // check precondition
      assert (nprocs == 1);
      
      // return arguments
      bbs.assign (1, bb);
      obs.assign (1, ob);
      
      // return
      if (DEBUG) cout << "SRAR exit" << endl;
      return;
    }
    
    // choose a direction
    int mydim = -1;
    double mysize = 0;
    int alldims = 0;
    double allsizes = 1;
    for (int d=0; d<dim; ++d) {
      if (! dims[d]) {
        ++ alldims;
        allsizes *= dshape[d];
        if (dshape[d] >= mysize) {
          mydim = d;
          mysize = dshape[d];
        }
      }
    }
    assert (mydim>=0 && mydim<dim);
    assert (mysize>=0);
    if (DEBUG) cout << "SRAR mydim " << mydim << endl;
    if (DEBUG) cout << "SRAR mysize " << mysize << endl;
    
    if (mysize == 0) {
      // the bbox is empty
      if (DEBUG) cout << "SRAR empty" << endl;
      
      // create the bboxes
      bbs.clear();
      obs.clear();
      bbs.reserve(nprocs);
      obs.reserve(nprocs);
      
      // create a new bbox
      assert (bb.empty());
      bbvect const newob (vect<bool,2>(false));
      ibbox const newbb (bb);
      if (DEBUG) cout << "SRAR " << mydim << " newbb " << newbb << endl;
      if (DEBUG) cout << "SRAR " << mydim << " newob " << newob << endl;
      
      // store
      bbs.insert (bbs.end(), nprocs, newbb);
      obs.insert (obs.end(), nprocs, newob);
      
      // check postconditions
      assert (bbs.size() == nprocs);
      assert (obs.size() == nprocs);
      if (DEBUG) cout << "SRAR exit" << endl;
      return;
    }
    
    // mark this direction as done
    assert (! dims[mydim]);
    bvect const newdims = dims.replace(mydim, true);
    
    // choose a number of slices for this direction
    int const nslices = min(nprocs, (int)floor(mysize * pow(nprocs/allsizes, 1.0/alldims) + 0.5));
    assert (nslices <= nprocs);
    if (DEBUG) cout << "SRAR " << mydim << " nprocs " << nprocs << endl;
    if (DEBUG) cout << "SRAR " << mydim << " nslices " << nslices << endl;
    
    // split the remaining processors
    vector<int> mynprocs(nslices);
    int const mynprocs_base = nprocs / nslices;
    int const mynprocs_left = nprocs - nslices * mynprocs_base;
    for (int n=0; n<nslices; ++n) {
      mynprocs[n] = n < mynprocs_left ? mynprocs_base+1 : mynprocs_base;
    }
    int sum_mynprocs = 0;
    for (int n=0; n<nslices; ++n) {
      sum_mynprocs += mynprocs[n];
    }
    assert (sum_mynprocs == nprocs);
    if (DEBUG) cout << "SRAR " << mydim << " mynprocs " << mynprocs << endl;
    
    // split the region
    vector<int> myslice(nslices);
    int slice_left = ((bb.upper() - bb.lower()) / bb.stride())[mydim] + 1;
    int nprocs_left = nprocs;
    for (int n=0; n<nslices; ++n) {
      if (n == nslices-1) {
        myslice[n] = slice_left;
      } else {
        myslice[n] = (int)floor(1.0 * slice_left * mynprocs[n] / nprocs_left + 0.5);
      }
      assert (myslice[n] > 0);
      slice_left -= myslice[n];
      nprocs_left -= mynprocs[n];
    }
    assert (slice_left == 0);
    assert (nprocs_left == 0);
    if (DEBUG) cout << "SRAR " << mydim << " myslice " << myslice << endl;
    
    // create the bboxes and recurse
    if (DEBUG) cout << "SRAR " << mydim << ": create bboxes" << endl;
    bbs.clear();
    obs.clear();
    bbs.reserve(nprocs);
    obs.reserve(nprocs);
    ivect last_up;
    for (int n=0; n<nslices; ++n) {
      if (DEBUG) cout << "SRAR " << mydim << " n " << n << endl;
      
      // create a new bbox
      ivect lo = bb.lower();
      ivect up = bb.upper();
      ivect str = bb.stride();
      bbvect newob = ob;
      if (n > 0) {
        lo[mydim] = last_up[mydim] + str[mydim];
        newob[mydim][0] = false;
      }
      if (n < nslices-1) {
        up[mydim] = lo[mydim] + (myslice[n]-1) * str[mydim];
        newob[mydim][1] = false;
        last_up = up;
      }
      ibbox newbb(lo, up, str);
      if (DEBUG) cout << "SRAR " << mydim << " newbb " << newbb << endl;
      if (DEBUG) cout << "SRAR " << mydim << " newob " << newob << endl;
      
      // recurse
      vector<ibbox> newbbs;
      vector<bbvect> newobs;
      SplitRegions_Automatic_Recursively
        (newdims, mynprocs[n], dshape, newbb, newob, newbbs, newobs);
      if (DEBUG) cout << "SRAR " << mydim << " newbbs " << newbbs << endl;
      if (DEBUG) cout << "SRAR " << mydim << " newobs " << newobs << endl;
      
      // store
      assert (newbbs.size() == mynprocs[n]);
      assert (newobs.size() == mynprocs[n]);
      bbs.insert (bbs.end(), newbbs.begin(), newbbs.end());
      obs.insert (obs.end(), newobs.begin(), newobs.end());
    }
    
    // check postconditions
    assert (bbs.size() == nprocs);
    assert (obs.size() == nprocs);
    if (DEBUG) cout << "SRAR exit" << endl;
  }
  
  void SplitRegions_Automatic (const cGH* cgh, vector<ibbox>& bbs,
                               vector<bbvect>& obs)
  {
    if (DEBUG) cout << "SRA enter" << endl;
    // Something to do?
    if (bbs.size() == 0) return;
    
    const int nprocs = CCTK_nProcs(cgh);
    if (DEBUG) cout << "SRA nprocs " << nprocs << endl;
    
//     if (nprocs==1) return;
    
    // split the processors
    // nslices: number of disjoint bboxes
    int const nslices = bbs.size();
    if (DEBUG) cout << "SRA nslices " << nslices << endl;
    // ncomps: number of components per processor
    int const ncomps = (nslices + nprocs - 1) / nprocs;
    if (DEBUG) cout << "SRA ncomps " << ncomps << endl;
    assert (ncomps > 0);
    vector<int> mysize(nslices);
    for (int c=0; c<nslices; ++c) {
      mysize[c] = bbs[c].size();
    }
    vector<int> mynprocs(nslices);
    {
      if (DEBUG) cout << "SRA: distributing processors to slices" << endl;
      int ncomps_left = nprocs * ncomps;
      for (int c=0; c<nslices; ++c) {
        mynprocs[c] = 1;
        -- ncomps_left;
      }
      while (ncomps_left > 0) {
        if (DEBUG) cout << "SRA ncomps_left " << ncomps_left << endl;
        int maxc = -1;
        double maxratio = -1;
        for (int c=0; c<nslices; ++c) {
          double const ratio = (double)mysize[c] / mynprocs[c];
          if (ratio > maxratio) { maxc=c; maxratio=ratio; }
        }
        assert (maxc>=0 && maxc<nslices);
        ++ mynprocs[maxc];
        if (DEBUG) cout << "SRA maxc " << maxc << endl;
        if (DEBUG) cout << "SRA mynprocs[maxc] " << mynprocs[maxc] << endl;
        -- ncomps_left;
      }
      assert (ncomps_left == 0);
    }
    if (DEBUG) cout << "SRA mynprocs " << mynprocs << endl;
    
    vector<ibbox> allbbs;
    vector<bbvect> allobs;
    
    if (DEBUG) cout << "SRA: splitting regions" << endl;
    for (int c=0; c<nslices; ++c) {
      
      const ibbox bb = bbs[c];
      const bbvect ob = obs[c];
      if (DEBUG) cout << "SRA c " << c << endl;
      if (DEBUG) cout << "SRA bb " << bb << endl;
      if (DEBUG) cout << "SRA ob " << ob << endl;
      
      const ivect rstr = bb.stride();
      const ivect rlb  = bb.lower();
      const ivect rub  = bb.upper() + rstr;
    
      // calculate real shape factors
      dvect dshape;
      if (any(rub == rlb)) {
        // the bbox is empty
        dshape = 0.0;
      } else {
        for (int d=0; d<dim; ++d) {
          dshape[d] = (double)(rub[d]-rlb[d]) / (rub[0]-rlb[0]);
        }
        const double dfact = pow(nprocs / prod(dshape), 1.0/dim);
        dshape *= dfact;
        assert (abs(prod(dshape) - nprocs) < 1e-6);
      }
      if (DEBUG) cout << "SRA shapes " << dshape << endl;
      
      bvect const dims = false;
      
      vector<ibbox> thebbs;
      vector<bbvect> theobs;
      
      SplitRegions_Automatic_Recursively
        (dims, mynprocs[c], dshape, bb, ob, thebbs, theobs);
      if (DEBUG) cout << "SRA thebbs " << thebbs << endl;
      if (DEBUG) cout << "SRA theobs " << theobs << endl;
      
      allbbs.insert(allbbs.end(), thebbs.begin(), thebbs.end());
      allobs.insert(allobs.end(), theobs.begin(), theobs.end());
      
    } // for c
    
    bbs = allbbs;
    obs = allobs;
    
    if (DEBUG) cout << "SRA exit" << endl;
  }
  
  
  
  void SplitRegions_AsSpecified (const cGH* cgh, vector<ibbox>& bbs,
				 vector<bbvect>& obs)
  {
    DECLARE_CCTK_PARAMETERS;
    
    // Something to do?
    if (bbs.size() == 0) return;
    
    const int nprocs = CCTK_nProcs(cgh);
    
    assert (bbs.size() == 1);
    
    const ivect rstr = bbs[0].stride();
    const ivect rlb  = bbs[0].lower();
    const ivect rub  = bbs[0].upper() + rstr;
    const bbvect obnd = obs[0];
    
    const ivect nprocs_dir
      (processor_topology_3d_x, processor_topology_3d_y,
       processor_topology_3d_z);
    assert (all (nprocs_dir > 0));
    if (prod(nprocs_dir) != nprocs) {
      CCTK_VWarn (0, __LINE__, __FILE__, CCTK_THORNSTRING,
		  "The specified processor topology [%d,%d,%d] is inconsistent with the number of processors, which is %d", nprocs_dir[0], nprocs_dir[1], nprocs_dir[2], nprocs);
    }
    assert (prod(nprocs_dir) == nprocs);
    
    if (nprocs==1) return;
    
    bbs.resize(nprocs);
    obs.resize(nprocs);
    const ivect cstr = rstr;
    const ivect glonp = (rub - rlb) / cstr;
//     const ivect locnp = (glonp + nprocs_dir - 1) / nprocs_dir;
    const ivect locnp = glonp / nprocs_dir;
    const ivect rem = glonp % nprocs_dir;
    const ivect step = locnp * cstr;
    assert (dim==3);
    for (int k=0; k<nprocs_dir[2]; ++k) {
      for (int j=0; j<nprocs_dir[1]; ++j) {
	for (int i=0; i<nprocs_dir[0]; ++i) {
	  const int c = i + nprocs_dir[0] * (j + nprocs_dir[1] * k);
	  const ivect ipos (i, j, k);
	  ivect clb = rlb + step *  ipos;
	  ivect cub = rlb + step * (ipos+1);
// 	  clb = min (clb, rub);
// 	  cub = min (cub, rub);
          for (int d=0; d<dim; ++d) {
            if (ipos[d]<rem[d]) {
              clb[d] += cstr[d] * ipos[d];
              cub[d] += cstr[d] * (ipos[d]+1);
            } else {
              clb[d] += cstr[d] * rem[d];
              cub[d] += cstr[d] * rem[d];
            }
          }
	  assert (all (clb >= 0));
	  assert (all (clb <= cub));
	  assert (all (cub <= rub));
          assert (all (! (ipos==0) || clb==rlb));
          assert (all (! (ipos==nprocs_dir-1) || cub==rub));
	  bbs[c] = ibbox(clb, cub-cstr, cstr);
	  obs[c] = obnd;
	  if (i>0) obs[c][0][0] = false;
	  if (j>0) obs[c][1][0] = false;
	  if (k>0) obs[c][2][0] = false;
	  if (i<nprocs_dir[0]-1) obs[c][0][1] = false;
	  if (j<nprocs_dir[1]-1) obs[c][1][1] = false;
	  if (k<nprocs_dir[2]-1) obs[c][2][1] = false;
	}
      }
    }
  }
  
  
  
  void MakeProcessors (const cGH* cgh, const gh<dim>::rexts& bbsss,
		       gh<dim>::rprocs& pss)
  {
    MakeProcessors_RoundRobin (cgh, bbsss, pss);
  }
  
  
  
  // This is a helpful helper routine. The user can use it to define
  // how the hierarchy should be refined.  But the result of this
  // routine is rather arbitrary.
  void MakeProcessors_RoundRobin (const cGH* cgh, const gh<dim>::rexts& bbsss,
				  gh<dim>::rprocs& pss)
  {
    const int nprocs = CCTK_nProcs(cgh);
    
    pss.resize(bbsss.size());
    for (int rl=0; rl<(int)bbsss.size(); ++rl) {
      pss[rl] = vector<int>(bbsss[rl].size());
      // make sure all processors have the same number of components
      assert (bbsss[rl].size() % nprocs == 0);
      for (int c=0; c<(int)bbsss[rl].size(); ++c) {
	pss[rl][c] = c % nprocs; // distribute among processors
      }
    }
  }
  
} // namespace Carpet