Source

enzo-3.0 / src / enzo / control / EvolveHierarchy.C

The active_particles branch has multiple heads

  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
/***********************************************************************
/
/  EVOLVE HIERARCHY FUNCTION
/
/  written by: Greg Bryan
/  date:       November, 1994
/  modified1:  February, 1995 by GB
/              Changed to reflect changes in EvolveGrid & EvolveTopGrid.
/  modified2:  July, 1995 by GB
/              Changed to reflect new routine EvolveLevel.
/  modified3:  February, 2006 by Daniel Reynolds
/              Updated call interface to ComputePotentialFieldLevelZero
/  modified4:  February, 2007 by Robert Harkness
/              Group and in-core i/o
/  modified5:  December, 2007 by Robert Harkness
/              Remove calls to ComputePotential to allow use of the
/              Fast Sibling Locator to remedy Ncpu^2 scaling
/  modified6:  February, 2008 by Robert Harkness
/              Conditional calls to MPI_Barrier to force MPICH progress
/  modified7:  October, 2009 by Ji-hoon Kim
/              Added particle splitter routine
/
/  PURPOSE:
/    This routine is responsible for the evolution of the grid hierarchy.
/    It assumes the hierarchy is already constructed and the grids
/    initialized.  The routine then loops over time until one of the
/    stopping criteria is reached.  This routine also handles data dumps,
/    history dumps and restarts dumps (although the later two have not
/    yet been implemented).
/
************************************************************************/
#include "preincludes.h"
 
#ifdef USE_MPI
#include <communicators.h>
#endif
 
#include "preincludes.h"

#include "EnzoTiming.h" 
#include "performance.h"
#include "ErrorExceptions.h"
#include "macros_and_parameters.h"
#include "typedefs.h"
#include "global_data.h"
#include "Fluxes.h"
#include "GridList.h"
#include "ExternalBoundary.h"
#include "Grid.h"
#include "Hierarchy.h"
#include "TopGridData.h"
#include "LevelHierarchy.h"
#include "CosmologyParameters.h"
#include "communication.h"
#include "CommunicationUtilities.h"
#ifdef TRANSFER
#include "ImplicitProblemABC.h"
#endif
 
// function prototypes
 
int RebuildHierarchy(TopGridData *MetaData,
		     LevelHierarchyEntry *LevelArray[], int level);

int EvolveLevel(TopGridData *MetaData, LevelHierarchyEntry *LevelArray[],
		int level, float dtLevelAbove, ExternalBoundary *Exterior
#ifdef TRANSFER
		, ImplicitProblemABC *ImplicitSolver
#endif
		);

int EvolveLevel_RK2(TopGridData *MetaData, LevelHierarchyEntry *LevelArray[],
                    int level, float dtLevelAbove, ExternalBoundary *Exterior, 
#ifdef TRANSFER
		    ImplicitProblemABC *ImplicitSolver, 
#endif
		    FLOAT dt0);

int WriteAllData(char *basename, int filenumber,
		 HierarchyEntry *TopGrid, TopGridData &MetaData,
		 ExternalBoundary *Exterior, 
#ifdef TRANSFER
		 ImplicitProblemABC *ImplicitSolver,
#endif		 
		 FLOAT WriteTime = -1,
		 int RestartDump = FALSE);

int CopyOverlappingZones(grid* CurrentGrid, TopGridData *MetaData,
			 LevelHierarchyEntry *LevelArray[], int level);
int TestGravityCheckResults(LevelHierarchyEntry *LevelArray[]);
int TestGravitySphereCheckResults(LevelHierarchyEntry *LevelArray[]);
int CheckForOutput(HierarchyEntry *TopGrid, TopGridData &MetaData,
		   ExternalBoundary *Exterior, 
#ifdef TRANSFER
		   ImplicitProblemABC *ImplicitSolver,
#endif		 
		   int Restart = FALSE);
int CheckForTimeAction(LevelHierarchyEntry *LevelArray[],
		       TopGridData &MetaData);
int CheckForResubmit(TopGridData &MetaData, int &Stop);
int CosmologyComputeExpansionFactor(FLOAT time, FLOAT *a, FLOAT *dadt);
int OutputLevelInformation(FILE *fptr, TopGridData &MetaData,
			   LevelHierarchyEntry *LevelArray[]);
int PrepareGravitatingMassField(HierarchyEntry *Grid, TopGridData *MetaData,
				LevelHierarchyEntry *LevelArray[], int level);
int ReduceFragmentation(HierarchyEntry &TopGrid, TopGridData &MetaData,
			ExternalBoundary *Exterior,
			LevelHierarchyEntry *LevelArray[]);
int CommunicationReceiveHandler(fluxes **SubgridFluxesEstimate[] = NULL,
				int NumberOfSubgrids[] = NULL,
				int FluxFlag = FALSE,
				TopGridData* MetaData = NULL);
double ReturnWallTime(void);
int Enzo_Dims_create(int nnodes, int ndims, int *dims);
int FOF(TopGridData *MetaData, LevelHierarchyEntry *LevelArray[], 
	int WroteData, int FOFOnly=FALSE);
int StarParticleCountOnly(LevelHierarchyEntry *LevelArray[]);
int CommunicationLoadBalanceRootGrids(LevelHierarchyEntry *LevelArray[], 
				      int TopGridRank, int CycleNumber);
int CommunicationBroadcastValue(Eint32 *Value, int BroadcastProcessor);
int CommunicationBroadcastValue(Eint64 *Value, int BroadcastProcessor);
int ParticleSplitter(LevelHierarchyEntry *LevelArray[], int ThisLevel,
		     TopGridData *MetaData); 
int MagneticFieldResetter(LevelHierarchyEntry *LevelArray[], int ThisLevel,
			  TopGridData *MetaData); 
void PrintMemoryUsage(char *str);
int SetEvolveRefineRegion(FLOAT time);

#ifdef MEM_TRACE
Eint64 mused(void);
#endif
#ifdef USE_PYTHON
int CallPython(LevelHierarchyEntry *LevelArray[],
               HierarchyEntry *Grids[],
               TopGridData *MetaData,
               int level, int from_topgrid);
#endif

 
 
#define NO_REDUCE_FRAGMENTATION
 
 
 
 
int EvolveHierarchy(HierarchyEntry &TopGrid, TopGridData &MetaData,
                    ExternalBoundary *Exterior,
#ifdef TRANSFER
		    ImplicitProblemABC *ImplicitSolver,
#endif
		    LevelHierarchyEntry *LevelArray[], float Initialdt)
{
 
  float dt;
 
  int i, dim, Stop = FALSE;
  int Restart = FALSE;
  double tlev0, tlev1, treb0, treb1, tloop0, tloop1, tentry, texit;
  LevelHierarchyEntry *Temp;
  double LastCPUTime;

  LCAPERF_BEGIN("EL");
  LCAPERF_START("EvolveHierarchy");

#ifdef USE_MPI
  tentry = MPI_Wtime();
#endif
 
  if (MetaData.Time        >= MetaData.StopTime ) Stop = TRUE;
  if (MetaData.CycleNumber >= MetaData.StopCycle) Stop = TRUE;
  MetaData.StartCPUTime = LastCPUTime = ReturnWallTime();
  MetaData.LastCycleCPUTime = 0.0;

  // Reset CPUTime, if it's very large (absolute UNIX time), which
  // was the default from before.
  if (MetaData.CPUTime > 1e2*MetaData.StopCPUTime)
    MetaData.CPUTime = 0.0;
 
  /* Attach RandomForcingFields to BaryonFields temporarily to apply BCs */
 
  if (RandomForcing) { //AK
    Temp = LevelArray[0];
    while (Temp != NULL) {
      Temp->GridData->AppendForcingToBaryonFields();
      Temp = Temp->NextGridThisLevel;
    }
    Exterior->AppendForcingToBaryonFields();
  }
 
  /* Set top grid boundary conditions. */

  Temp = LevelArray[0];

  PrintMemoryUsage("Enter EH");

#ifdef FORCE_MSG_PROGRESS
  CommunicationBarrier();
#endif

  CommunicationReceiveIndex = 0;
  CommunicationDirection = COMMUNICATION_POST_RECEIVE;
  CommunicationReceiveCurrentDependsOn = COMMUNICATION_NO_DEPENDENCE;

  while (Temp != NULL) {
    if (Temp->GridData->SetExternalBoundaryValues(Exterior) == FAIL) {
      //      ENZO_FAIL("Error in grid->SetExternalBoundaryValues.\n");
      Exterior->Prepare(Temp->GridData);

    }
    if (CopyOverlappingZones(Temp->GridData, &MetaData, LevelArray, 0)
	== FAIL)
      ENZO_FAIL("Error in CopyOverlappingZones.");
    Temp = Temp->NextGridThisLevel;
  }
  
  CommunicationDirection = COMMUNICATION_SEND;

  Temp = LevelArray[0];
  while (Temp != NULL) {
    if (CopyOverlappingZones(Temp->GridData, &MetaData, LevelArray, 0)
	== FAIL)
      ENZO_FAIL("Error in CopyOverlappingZones.");
    Temp = Temp->NextGridThisLevel;
  }

#ifdef FORCE_MSG_PROGRESS 
  CommunicationBarrier();
#endif

  CommunicationReceiveHandler();

#ifdef FORCE_MSG_PROGRESS
  CommunicationBarrier();
#endif

  PrintMemoryUsage("Bdry set");
 
  /* Remove RandomForcingFields from BaryonFields when BCs are set. */
 
  if (RandomForcing) { //AK
    LevelHierarchyEntry *Temp = LevelArray[0];
    while (Temp != NULL) {
      Temp->GridData->DetachForcingFromBaryonFields();
      Temp = Temp->NextGridThisLevel;
    }
    Exterior->DetachForcingFromBaryonFields();
  }
 
  /* Check for output. */
 
  CheckForOutput(&TopGrid, MetaData, Exterior, 
#ifdef TRANSFER
		 ImplicitSolver,
#endif		 
		 Restart);

  PrintMemoryUsage("Output");
 
  /* Compute the acceleration field so ComputeTimeStep can find dtAccel.
     (Actually, this is a huge pain-in-the-ass, so only do it if the
      problem really requires it). */
 
/*
  if (ProblemType == 21) {
    PrepareGravitatingMassField(&TopGrid, &MetaData, LevelArray, 0);
    ComputePotentialFieldLevelZero(&MetaData, Grids, NumberOfGrids);
    TopGrid.GridData->ComputeAccelerationField(GRIDS);
  }
*/


  /* Do the first grid regeneration. */
 
  if(CheckpointRestart == FALSE) {
    RebuildHierarchy(&MetaData, LevelArray, 0);
  }

  PrintMemoryUsage("1st rebuild");
 
  /* Particle Splitter. Split particles into 13 (=1+12) child particles */
  
  if (MetaData.FirstTimestepAfterRestart == TRUE &&
      ParticleSplitterIterations > 0)
    ParticleSplitter(LevelArray, 0, &MetaData);

  /* Reset magnetic fields if requested. */
  
  if (MetaData.FirstTimestepAfterRestart == TRUE &&
      ResetMagneticField == TRUE)
    MagneticFieldResetter(LevelArray, 0, &MetaData);

  /* Open the OutputLevelInformation file. */
 
  FILE *LevelInfofptr;
 
  if (MyProcessorNumber == ROOT_PROCESSOR) {
    LevelInfofptr = fopen("OutputLevelInformation.out", "w");
    fclose(LevelInfofptr);
  }

  /* For top-level timestepping with radiative star particles, we want
     to restrict the timesteps.  Collect info here. */

  //StarParticleCountOnly(LevelArray);
 
#ifdef USE_LCAPERF
  Eint32 lcaperf_iter;
#endif

  LCAPERF_STOP("EvolveHierarchy");
  LCAPERF_END("EH");

  /* ====== MAIN LOOP ===== */

  bool FirstLoop = true;
  while (!Stop) {

  TIMER_START("Total");

#ifdef USE_LCAPERF
    lcaperf_iter = MetaData.CycleNumber;
    static bool isFirstCall = true;
    if ((lcaperf_iter % LCAPERF_DUMP_FREQUENCY)==0 || isFirstCall) lcaperf.begin("EL");
    isFirstCall = false;
    lcaperf.attribute ("timestep",&lcaperf_iter, LCAPERF_INT);
    lcaperf.start("EL");
#endif

#ifdef USE_MPI
    tloop0 = MPI_Wtime();
#endif

#ifdef MEM_TRACE
    fprintf(memtracePtr, "==== CYCLE %"ISYM" ====\n", MetaData.CycleNumber);
#endif    
    PrintMemoryUsage("Top");

    /* Load balance the root grids if this isn't the initial call */

    if ((CheckpointRestart == FALSE) && (!FirstLoop))
      CommunicationLoadBalanceRootGrids(LevelArray, MetaData.TopGridRank, 
					MetaData.CycleNumber);

    /* Output level information to log file. */
 
    if (MyProcessorNumber == ROOT_PROCESSOR) {
      LevelInfofptr = fopen("OutputLevelInformation.out", "a");
      if (LevelInfofptr == NULL)
        ENZO_FAIL("Can't open OutputLevelInformation.out!");
    }

    // OutputLevelInformation() only needs to be called by all processors
    // when lcaperf is enabled.

    OutputLevelInformation(LevelInfofptr, MetaData, LevelArray);

    if (MyProcessorNumber == ROOT_PROCESSOR)
      fclose(LevelInfofptr);
 
    /* Compute minimum timestep on the top level. */
 
    float dtProc   = huge_number;
    Temp = LevelArray[0];
 
    // Start skipping
    if(CheckpointRestart == FALSE) {
      while (Temp != NULL) {
        dtProc = min(dtProc, Temp->GridData->ComputeTimeStep());
        Temp = Temp->NextGridThisLevel;
      }

      dt = RootGridCourantSafetyNumber*CommunicationMinValue(dtProc);
      dt = min(MetaData.MaximumTopGridTimeStep, dt);

      if (debug) fprintf(stderr, "dt, Initialdt: %g %g \n", dt, Initialdt);
      if (Initialdt != 0) {
      
	dt = min(dt, Initialdt);
	if (debug) fprintf(stderr, "dt, Initialdt: %g %g \n", dt, Initialdt);
        Initialdt = 0;
      }

      /* Make sure timestep doesn't go past an output. */

      if (ComovingCoordinates)
        for (i = 0; i < MAX_NUMBER_OF_OUTPUT_REDSHIFTS; i++)
          if (CosmologyOutputRedshift[i] != -1)
            dt = min(1.0001*(CosmologyOutputRedshiftTime[i]-MetaData.Time), dt);
      for (i = 0; i < MAX_TIME_ACTIONS; i++)
        if (TimeActionTime[i] > 0 && TimeActionType[i] > 0)
          dt = min(1.0001*(TimeActionTime[i] - MetaData.Time), dt);
      if (MetaData.dtDataDump > 0.0) {
        while (MetaData.TimeLastDataDump+MetaData.dtDataDump < MetaData.Time)
          MetaData.TimeLastDataDump += MetaData.dtDataDump;
        dt = min(1.0001*(MetaData.TimeLastDataDump + MetaData.dtDataDump -
              MetaData.Time), dt);
      }

      /* Set the time step.  If it will cause Time += dt > StopTime, then
         set dt = StopTime - Time */

      dt = min(MetaData.StopTime - MetaData.Time, dt);
    } else { 
      dt = dtThisLevel[0]; 
    }

    /* Set the time step.  If it will cause Time += dt > StopTime, then
       set dt = StopTime - Time */
 
    dt = min(MetaData.StopTime - MetaData.Time, dt);
    Temp = LevelArray[0];
    // Stop skipping

    // Set dt from stored in CheckpointRestart
    while (Temp != NULL) {
      Temp->GridData->SetTimeStep(dt);
      Temp = Temp->NextGridThisLevel;
    }
 
#ifdef CONFIG_TESTING
    if (MyProcessorNumber == ROOT_PROCESSOR) {
      printf("enzo-test: MetaData.CycleNumber %"ISYM"\n", MetaData.CycleNumber);
      printf("enzo-test: dt %.14g\n",dt);
      printf("enzo-test: MetaData.Time %"GOUTSYM"\n", MetaData.Time);
      fflush(stdout);
    }
#endif

    if (MyProcessorNumber == ROOT_PROCESSOR) {
      fprintf(stderr, "TopGrid dt = %"ESYM"     time = %"GOUTSYM"    cycle = %"ISYM,
	     dt, MetaData.Time, MetaData.CycleNumber);

      if (ComovingCoordinates) {
	FLOAT a, dadt;
	CosmologyComputeExpansionFactor(MetaData.Time, &a, &dadt);
	fprintf(stderr, "    z = %"GOUTSYM, (1 + InitialRedshift)/a - 1);
      }
      fprintf(stderr, "\n");
    }
    //}
 
    /* Inline halo finder */

    FOF(&MetaData, LevelArray, MetaData.WroteData);

    /* If provided, set RefineRegion from evolving RefineRegion */
    if ((RefineRegionTimeType == 1) || (RefineRegionTimeType == 0)) {
        if (SetEvolveRefineRegion(MetaData.Time) == FAIL) {
          fprintf(stderr, "Error in SetEvolveRefineRegion.\n");
          return FAIL;
        }
    }
    /* Evolve the top grid (and hence the entire hierarchy). */

#ifdef USE_MPI 
    CommunicationBarrier();
    tlev0 = MPI_Wtime();
#endif

    /* Zeroing out the rootgrid Emissivity before EvolveLevel is called 
       so when rootgrid emissivity values are calculated they are put in 
       clean rootgrid array */
#ifdef EMISSIVITY
/*
    if(StarMakerEmissivityField > 0){
      LevelHierarchyEntry *RootTemp;
      RootTemp = LevelArray[0];
      while (RootTemp != NULL) {
	RootTemp->GridData->ClearEmissivity();
	RootTemp = RootTemp->NextGridThisLevel;
      }
    }
*/
#endif
 
    if (HydroMethod == PPM_DirectEuler || HydroMethod == Zeus_Hydro || 
	HydroMethod == PPM_LagrangeRemap || HydroMethod == HydroMethodUndefined ||
	HydroMethod < 0) {
      if (EvolveLevel(&MetaData, LevelArray, 0, dt, Exterior
#ifdef TRANSFER
		      , ImplicitSolver
#endif
		      ) == FAIL) {
        if (NumberOfProcessors == 1) {
          fprintf(stderr, "Error in EvolveLevel.\n");
          fprintf(stderr, "--> Dumping data (output number %d).\n",
                  MetaData.DataDumpNumber);
	WriteAllData(MetaData.DataDumpName, MetaData.DataDumpNumber,
		     &TopGrid, MetaData, Exterior
#ifdef TRANSFER
		     , ImplicitSolver
#endif		 
		     );
        }
        return FAIL;
      }
    } else {
      if (HydroMethod == HD_RK || HydroMethod == MHD_RK)
	if (EvolveLevel_RK2(&MetaData, LevelArray, 0, dt, Exterior, 
#ifdef TRANSFER
			    ImplicitSolver, 
#endif
			    dt) == FAIL) {
	  if (NumberOfProcessors == 1) {
	    fprintf(stderr, "Error in EvolveLevel_RK2.\n");
	    fprintf(stderr, "--> Dumping data (output number %d).\n",
		    MetaData.DataDumpNumber);
	    WriteAllData(MetaData.DataDumpName, MetaData.DataDumpNumber,
			       &TopGrid, MetaData, Exterior
#ifdef TRANSFER
			       , ImplicitSolver
#endif		 
			       );
	  }
        return FAIL;
      }
    }



#ifdef USE_MPI 
    CommunicationBarrier();
    tlev1 = MPI_Wtime();
#endif
  
    /* Add time and check stopping criteria (steps #21 & #22)
       (note the topgrid is also keeping its own time but this statement will
       keep the two in synch). */
 
    MetaData.Time += dt;
    MetaData.CycleNumber++;
    MetaData.LastCycleCPUTime = ReturnWallTime() - LastCPUTime;
    MetaData.CPUTime += MetaData.LastCycleCPUTime;
    LastCPUTime = ReturnWallTime();

    if (MyProcessorNumber == ROOT_PROCESSOR) {
	
    if (MetaData.Time >= MetaData.StopTime) {
      if (MyProcessorNumber == ROOT_PROCESSOR)
	printf("Stopping on top grid time limit.\n");
      Stop = TRUE;
    } else
    if (MetaData.CycleNumber >= MetaData.StopCycle) {
      if (MyProcessorNumber == ROOT_PROCESSOR)
	printf("Stopping on top grid cycle limit.\n");
      Stop = TRUE;
    } else
    if (MetaData.CPUTime >= MetaData.StopCPUTime) {
      if (MyProcessorNumber == ROOT_PROCESSOR)
	printf("Stopping on CPU time limit.\n");
      Stop = TRUE;
    } else
    if ((ReturnWallTime() - MetaData.StartCPUTime >= MetaData.dtRestartDump &&
	 MetaData.dtRestartDump > 0) ||
	(MetaData.CycleNumber - MetaData.CycleLastRestartDump >= 
	 MetaData.CycleSkipRestartDump &&
	 MetaData.CycleSkipRestartDump > 0)) {
      if (MyProcessorNumber == ROOT_PROCESSOR)
	printf("Stopping to restart.\n");
      Stop = TRUE;
      Restart = TRUE;
    }
    } // ENDIF ROOT_PROCESSOR

    CommunicationBroadcastValue(&Stop, ROOT_PROCESSOR);
    CommunicationBroadcastValue(&Restart, ROOT_PROCESSOR);

    /* If not restarting, rebuild the grids from level 0. */

#ifdef USE_MPI
    treb0 = MPI_Wtime();
#endif

    PrintMemoryUsage("Pre loop rebuild");
 
    if (ProblemType != 25 && Restart == FALSE) {
      RebuildHierarchy(&MetaData, LevelArray, 0);
    }

    PrintMemoryUsage("Post loop rebuild");

#ifdef USE_MPI
    treb1 = MPI_Wtime();
#endif
 
    /* Check for time-actions. */
 
    CheckForTimeAction(LevelArray, MetaData);
 
    /* Check for output. */
 
    CheckForOutput(&TopGrid, MetaData, Exterior, 
#ifdef TRANSFER
		   ImplicitSolver,
#endif		 
		   Restart);

    /* Call inline analysis. */

#ifdef USE_PYTHON
    LCAPERF_START("CallPython");
    CallPython(LevelArray, NULL, &MetaData, 0, 1);
    LCAPERF_STOP("CallPython");
#endif

    /* Check for resubmission */
    
    if (!Restart)
      CheckForResubmit(MetaData, Stop);

    /* If stopping, inline halo finder one more time */

    if (Stop && !Restart)
      FOF(&MetaData, LevelArray, TRUE);

    /* Try to cut down on memory fragmentation. */
 
#ifdef REDUCE_FRAGMENTATION
 
    if (MetaData.WroteData && !Stop)
      ReduceFragmentation(TopGrid, MetaData, Exterior, LevelArray);
 
#endif /* REDUCE_FRAGMENTATION */

#ifdef USE_LCAPERF
    lcaperf.stop("EL");
    if (((lcaperf_iter+1) % LCAPERF_DUMP_FREQUENCY)==0) lcaperf.end("EL");
#endif

    PrintMemoryUsage("Bot");

  for ( i = 0; i < MAX_NUMBER_OF_TASKS; i++ ) {
    TaskMemory[i] = -1;
  }

#ifdef MEM_TRACE

  /*
  MPI_Datatype DataTypeInt = (sizeof(Eint64) == 4) ? MPI_INT : MPI_LONG_LONG_INT;
  MPI_Arg ThisTask;
  MPI_Arg TaskCount;
  MPI_Arg Count = 1;
  MPI_Arg stat;

  stat = MPI_Comm_size(EnzoTopComm, &TaskCount);
  stat = MPI_Comm_rank(EnzoTopComm, &ThisTask);
  stat = MPI_Allgather(&MemInUse, Count, DataTypeInt, TaskMemory, Count, DataTypeInt, EnzoTopComm);

  if (ThisTask == 0 ) {
    for ( i = 0; i < TaskCount; i++) {
      fprintf(stderr, "TaskMemory : Task %"ISYM"  Memory %"ISYM"\n", i, TaskMemory[i]);
    }
  }
*/

#endif /* MEM_TRACE */
#ifdef USE_MPI
    tloop1 = MPI_Wtime();
#endif

    FILE *evlog;

    if (MyProcessorNumber == ROOT_PROCESSOR) {
      evlog = fopen("Evtime", "a");
      fprintf(evlog, "%8"ISYM"  %16.9e  %16.9e  %16.9e\n", MetaData.CycleNumber, tlev1-tlev0, treb1-treb0, tloop1-tloop0);
      fclose(evlog);
    }

#ifdef MEM_TRACE
    Eint64 MemInUse;
    if (MetaData.WroteData) {
      MemInUse = mused();
      MemInUse = CommunicationMaxValue(MemInUse);
      if (MemInUse > MemoryLimit) {
        if (MyProcessorNumber == ROOT_PROCESSOR)
          printf("Stopping due to memory limit.\n");
        Stop = TRUE;
      }
    }
#endif

    TIMER_STOP("Total");
    if ((MetaData.CycleNumber-1) % TimingCycleSkip == 0)
		  TIMER_WRITE(MetaData.CycleNumber);

    FirstLoop = false;
 
  } // ===== end of main loop ====

#ifdef USE_LCAPERF
  if (((lcaperf_iter+1) % LCAPERF_DUMP_FREQUENCY)!=0) lcaperf.end("EL");
  lcaperf.attribute ("timestep",0, LCAPERF_NULL);
#endif

  MetaData.CPUTime = ReturnWallTime() - MetaData.StartCPUTime;
 
  /* Done, so report on current time, etc. */
 
  if (MyProcessorNumber == ROOT_PROCESSOR) {
    printf("Time     = %9"FSYM"   CycleNumber = %6"ISYM"    Wallclock   = %9"FSYM"\n",
	   MetaData.Time, MetaData.CycleNumber, MetaData.CPUTime);
    printf("StopTime = %9"FSYM"   StopCycle   = %6"ISYM"\n",
	   MetaData.StopTime, MetaData.StopCycle);
  }
 
  /* If we are running problem 23, TestGravity, then check the results. */
 
  if (ProblemType == 23)
    TestGravityCheckResults(LevelArray);
  if (ProblemType == 25 && NumberOfProcessors == 0)
    TestGravitySphereCheckResults(LevelArray);
 
  /* if we are doing data dumps, then do one last one */
 
  if ((MetaData.dtDataDump != 0.0 || MetaData.CycleSkipDataDump != 0) &&
      !MetaData.WroteData)
    if (WriteAllData(MetaData.DataDumpName, MetaData.DataDumpNumber,
			   &TopGrid, MetaData, Exterior, 
#ifdef TRANSFER
			   ImplicitSolver, 
#endif		 
			   -666) == FAIL)
      ENZO_FAIL("Error in WriteAllData.");
 
  /* Write a file to indicate that we're finished. */

  FILE *Exit_fptr;
  if (!Restart && MyProcessorNumber == ROOT_PROCESSOR) {
    if ((Exit_fptr = fopen("RunFinished", "w")) == NULL)
      ENZO_FAIL("Error opening RunFinished.");
    fprintf(Exit_fptr, "Finished on cycle %"ISYM"\n", MetaData.CycleNumber);
    fclose(Exit_fptr);
  }

  if (NumberOfProcessors > 1)

    printf("Communication: processor %"ISYM" CommunicationTime = %"FSYM"\n",
	   MyProcessorNumber, CommunicationTime);
 
  /* done */

#ifdef USE_MPI
  texit = MPI_Wtime();
#endif
 
  return SUCCESS;
}