Source

enzo-3.0 / src / enzo / control / EvolveLevel.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
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
/***********************************************************************
/
/  EVOLVE LEVEL FUNCTION
/
/  written by: Greg Bryan
/  date:       November, 1994
/  modified1:  February, 1995 by GB
/              Overhauled to make sure that all the subgrid's of a grid
/              advance with in lock step (i.e. with the same timestep and
/              in order).  This was done to allow a subgrid to get it's
/              boundary values from another subgrid (with the same parent).
/              Previously, a subgrid' BVs were always interpolated from its
/              parent.
/  modified2:  August, 1995 by GB
/                1) All grids on a level are processed at the same time
/                 (rather than all the subgrids of one parent).
/                2) C routines are called to loop over subgrids
/                 (so parallelizing C compilers can be used).
/                3) Subgrid timesteps are not constant over top grid step.
/              June, 1999 by GB -- Clean up somewhat
/
/  modified3:  August, 2001 by Alexei Kritsuk
/                Added 2nd call of PrepareDensityField() to compute
/                grav. potential (to be written with other baryon fields).
/  modified4:  January, 2004 by Alexei Kritsuk
/                Added support for RandomForcing
/  modified5:  February, 2006 by Daniel Reynolds
/                Added PotentialBdry to EvolveLevel and 
/                PrepareDensityField calls, so that it can be used
/                within computing isolating BCs for self-gravity.
/  modified6:  January, 2007 by Robert Harkness
/                Group and in-core i/o
/  modified7:  December, 2007 by Robert Harkness
/                Optional StaticSiblingList for root grid
/  modified8:  April, 2009 by John Wise
/                Added star particle class and radiative transfer
/  modified9:  June, 2009 by MJT, DC, JHW, TA
/                Cleaned up error handling and created new routines for
/                computing the timestep, output, handling fluxes
/  modified10: July, 2009 by Sam Skillman
/                Added shock analysis
/
/  PURPOSE:
/    This routine is the main grid evolution function.  It assumes that the
/    grids of level-1 have already been advanced by dt (passed
/    in the argument) and that their boundary values are properly set.
/    We then perform a complete update on all grids on level, including:
/       - for each grid: set the boundary values from parent/subgrids
/       - for each grid: get a list of its subgrids
/       - determine the timestep based on the minimum timestep for all grids
/       - subcycle over the grid timestep and for each grid:
/           - copy the fields to the old fields
/           - solve the hydro equations (and save fluxes around subgrid)
/           - set the boundary values from parent and/or other grids
/           - update time and check dt(min) for that grid against dt(cycle)
/           - call EvolveLevel(level+1)
/           - accumulate flux around this grid
/       - correct the solution on this grid based on subgrid solutions
/       - correct the solution on this grid based on improved subgrid fluxes
/
/    This routine essentially solves (completely) the grids of this level
/       and all finer levels and then corrects the solution of
/       grids on this level based on the improved subgrid solutions/fluxes.
/
/    Note: as a convenience, we store the current grid's fluxes (i.e. the
/          fluxes around the exterior of this grid) as the last entry in
/          the list of subgrids.
/
************************************************************************/
#include "preincludes.h"
 
#ifdef USE_MPI
#include "communicators.h"
#endif /* USE_MPI */
 
#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 "CommunicationUtilities.h"
#ifdef TRANSFER
#include "ImplicitProblemABC.h"
#endif
#ifdef NEW_PROBLEM_TYPES
#include "EventHooks.h"
#include "EventDataContainers.h"
#else
void RunEventHooks(char *, HierarchyEntry *Grids[],
                   TopGridData &MetaData, void *) {};
#endif
 
/* function prototypes */
 
#ifdef TRANSFER
#define IMPLICIT_MACRO , ImplicitSolver
#else
#define IMPLICIT_MACRO 
#endif

#define EXTRA_OUTPUT_MACRO(A) ExtraOutput(A,LevelArray,MetaData,level,Exterior IMPLICIT_MACRO);
int ExtraOutput(int output_flag, LevelHierarchyEntry *LevelArray[],TopGridData *MetaData, int level, ExternalBoundary *Exterior
#ifdef TRANSFER
		, ImplicitProblemABC *ImplicitSolver
#endif
		);

int  RebuildHierarchy(TopGridData *MetaData,
		      LevelHierarchyEntry *LevelArray[], int level);
int  ReportMemoryUsage(char *header = NULL);
int  UpdateParticlePositions(grid *Grid);
int  CheckEnergyConservation(HierarchyEntry *Grids[], int grid,
			     int NumberOfGrids, int level, float dt);
int GenerateGridArray(LevelHierarchyEntry *LevelArray[], int level,
		      HierarchyEntry **Grids[]);
int WriteStreamData(LevelHierarchyEntry *LevelArray[], int level,
		    TopGridData *MetaData, int *CycleCount, int open=FALSE);
int CallProblemSpecificRoutines(TopGridData * MetaData, HierarchyEntry *ThisGrid,
				int GridNum, float *norm, float TopGridTimeStep, 
				int level, int LevelCycleCount[]);  //moo

#ifdef FAST_SIB
int PrepareDensityField(LevelHierarchyEntry *LevelArray[],
			SiblingGridList SiblingList[],
			int level, TopGridData *MetaData, FLOAT When);
#else  // !FAST_SIB
int PrepareDensityField(LevelHierarchyEntry *LevelArray[],
                        int level, TopGridData *MetaData, FLOAT When);
#endif  // end FAST_SIB
 
#ifdef FAST_SIB
int SetBoundaryConditions(HierarchyEntry *Grids[], int NumberOfGrids,
			  SiblingGridList SiblingList[],
			  int level, TopGridData *MetaData,
			  ExternalBoundary *Exterior, LevelHierarchyEntry * Level);
#else
int SetBoundaryConditions(HierarchyEntry *Grids[], int NumberOfGrids,
                          int level, TopGridData *MetaData,
                          ExternalBoundary *Exterior, LevelHierarchyEntry * Level);
#endif



#ifdef SAB
#ifdef FAST_SIB
int SetAccelerationBoundary(HierarchyEntry *Grids[], int NumberOfGrids,
			    SiblingGridList SiblingList[],
			    int level, TopGridData *MetaData,
			    ExternalBoundary *Exterior,
			    LevelHierarchyEntry * Level,
			    int CycleNumber);
#else
int SetAccelerationBoundary(HierarchyEntry *Grids[], int NumberOfGrids,
			    int level, TopGridData *MetaData, 
			    ExternalBoundary *Exterior,
			    LevelHierarchyEntry * Level,
			    int CycleNumber);
#endif
#endif

#ifdef FLUX_FIX
int UpdateFromFinerGrids(int level, HierarchyEntry *Grids[], int NumberOfGrids,
			 int NumberOfSubgrids[],
			 fluxes **SubgridFluxesEstimate[],
			 LevelHierarchyEntry *SUBlingList[],
			 TopGridData *MetaData);
#else
int UpdateFromFinerGrids(int level, HierarchyEntry *Grids[], int NumberOfGrids,
			 int NumberOfSubgrids[],
			 fluxes **SubgridFluxesEstimate[]);
#endif
int CreateFluxes(HierarchyEntry *Grids[],fluxes **SubgridFluxesEstimate[],
		 int NumberOfGrids,int NumberOfSubgrids[]);		 
int FinalizeFluxes(HierarchyEntry *Grids[],fluxes **SubgridFluxesEstimate[],
		 int NumberOfGrids,int NumberOfSubgrids[]);		 
int RadiationFieldUpdate(LevelHierarchyEntry *LevelArray[], int level,
			 TopGridData *MetaData);


int OutputFromEvolveLevel(LevelHierarchyEntry *LevelArray[],TopGridData *MetaData,
			  int level, ExternalBoundary *Exterior
#ifdef TRANSFER
			  , ImplicitProblemABC *ImplicitSolver
#endif
			  );
 
int ComputeRandomForcingNormalization(LevelHierarchyEntry *LevelArray[],
                                      int level, TopGridData *MetaData,
                                      float * norm, float * pTopGridTimeStep);
int CreateSiblingList(HierarchyEntry ** Grids, int NumberOfGrids, 
		      SiblingGridList *SiblingList, 
		      int StaticLevelZero,TopGridData * MetaData,int level);

#ifdef FLUX_FIX
#ifdef FAST_SIB 
int CreateSUBlingList(TopGridData *MetaData,
		      LevelHierarchyEntry *LevelArray[], int level,
		      SiblingGridList SiblingList[],
		      LevelHierarchyEntry ***SUBlingList);
#else
int CreateSUBlingList(TopGridData *MetaData,
		      LevelHierarchyEntry *LevelArray[], int level,
		      LevelHierarchyEntry ***SUBlingList);
#endif /* FAST_SIB */
int DeleteSUBlingList(int NumberOfGrids,
		      LevelHierarchyEntry **SUBlingList);
#endif

int ActiveParticleInitialize(HierarchyEntry *Grids[], TopGridData *MetaData,
			     int NumberOfGrids, LevelHierarchyEntry *LevelArray[], 
			     int ThisLevel);
int ActiveParticleFinalize(HierarchyEntry *Grids[], TopGridData *MetaData,
			   int NumberOfGrids, LevelHierarchyEntry *LevelArray[], 
			   int level, int NumberOfNewActiveParticles[]);
int AdjustRefineRegion(LevelHierarchyEntry *LevelArray[], 
		       TopGridData *MetaData, int EL_level);
int AdjustMustRefineParticlesRefineToLevel(TopGridData *MetaData, int EL_level);

#ifdef TRANSFER
int EvolvePhotons(TopGridData *MetaData, LevelHierarchyEntry *LevelArray[],
		  Star *&AllStars, FLOAT GridTime, int level, int LoopTime = TRUE);
int RadiativeTransferPrepare(LevelHierarchyEntry *LevelArray[], int level,
			     TopGridData *MetaData, Star *&AllStars,
			     float dtLevelAbove);
int RadiativeTransferCallFLD(LevelHierarchyEntry *LevelArray[], int level,
			     TopGridData *MetaData, Star *AllStars, 
			     ImplicitProblemABC *ImplicitSolver);
#endif

int SetLevelTimeStep(HierarchyEntry *Grids[],
        int NumberOfGrids, int level,
        float *dtThisLevelSoFar, float *dtThisLevel,
        float dtLevelAbove);

void my_exit(int status);
 
int CallPython(LevelHierarchyEntry *LevelArray[],
               HierarchyEntry *Grids[],
               TopGridData *MetaData,
               int level, int from_topgrid);
int MovieCycleCount[MAX_DEPTH_OF_HIERARCHY];
double LevelWallTime[MAX_DEPTH_OF_HIERARCHY];
double LevelZoneCycleCount[MAX_DEPTH_OF_HIERARCHY];
double LevelZoneCycleCountPerProc[MAX_DEPTH_OF_HIERARCHY];
 
static float norm = 0.0;            //AK
static float TopGridTimeStep = 0.0; //AK
#ifdef STATIC_SIBLING_LIST
static int StaticLevelZero = 1;
#else
static int StaticLevelZero = 0;
#endif

extern int RK2SecondStepBaryonDeposit;

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

#ifdef NEW_PROBLEM_TYPES
  EvolveLevelEventDataContainer *LocalData = new EvolveLevelEventDataContainer;
  EventDataContainer *LocalDataP = static_cast<EventDataContainer*>(LocalData);
#else
  void *LocalDataP = NULL;
  void *Localata = NULL;
#endif

  int dbx = 0;

  FLOAT When, GridTime;
  //float dtThisLevelSoFar = 0.0, dtThisLevel, dtGrid, dtActual, dtLimit;
  //float dtThisLevelSoFar = 0.0, dtThisLevel;
  int cycle = 0, counter = 0, grid1, subgrid, grid2, ilvl;
  HierarchyEntry *NextGrid;
  int dummy_int;

  char level_name[MAX_LINE_LENGTH];
  sprintf(level_name, "Level_%"ISYM, level);
    
  // Update lcaperf "level" attribute
  Eint32 lcaperf_level = level;
#ifdef USE_LCAPERF
  lcaperf.attribute ("level",&lcaperf_level,LCAPERF_INT);
#endif
  
  /* Create an array (Grids) of all the grids. */

  typedef HierarchyEntry* HierarchyEntryPointer;
  HierarchyEntry **Grids;
  int NumberOfGrids = GenerateGridArray(LevelArray, level, &Grids);
  int *NumberOfNewActiveParticles = new int[NumberOfGrids]();
  int *NumberOfSubgrids = new int[NumberOfGrids];
  int *NumberOfNewParticles = new int[NumberOfGrids];
  fluxes ***SubgridFluxesEstimate = new fluxes **[NumberOfGrids];
  /*RunEventHooks("EvolveLevelTop", Grids, *MetaData, LocalDataP);*/

#ifdef FLUX_FIX
  /* Create a SUBling list of the subgrids */
  LevelHierarchyEntry **SUBlingList;
#endif

  /* Initialize the chaining mesh used in the FastSiblingLocator. */

  if (dbx) fprintf(stderr, "EL: Initialize FSL \n"); 
  SiblingGridList *SiblingList = new SiblingGridList[NumberOfGrids];
  CreateSiblingList(Grids, NumberOfGrids, SiblingList, StaticLevelZero,MetaData,level);
  
  /* Adjust the refine region so that only the finest particles 
     are included.  We don't want the more massive particles
     to contaminate the high-resolution region. */

  AdjustRefineRegion(LevelArray, MetaData, level);

  //EMISSIVITY if cleared here will not reach the FLD solver in 2.0, finding better place
  /* Adjust MustRefineParticlesRefineToLevel parameter if requested */
  AdjustMustRefineParticlesRefineToLevel(MetaData, level);

  /* ================================================================== */
  /* For each grid: a) interpolate boundaries from its parent.
                    b) copy any overlapping zones.  */
 
  if (CheckpointRestart == FALSE) {
#ifdef FAST_SIB
    if (SetBoundaryConditions(Grids, NumberOfGrids, SiblingList,
                  level, MetaData, Exterior, LevelArray[level]) == FAIL)
      ENZO_FAIL("Error in SetBoundaryConditions (FastSib)");
#else
    if (SetBoundaryConditions(Grids, NumberOfGrids, level, MetaData,
                              Exterior, LevelArray[level]) == FAIL)
      ENZO_FAIL("Error in SetBoundaryConditions (SlowSib)");
#endif
  }
 
  /* Clear the boundary fluxes for all Grids (this will be accumulated over
     the subcycles below (i.e. during one current grid step) and used to by the
     current grid to correct the zones surrounding this subgrid (step #18). 

     If we're just coming in off a CheckpointRestart, instead we take the
     fluxes that were stored in the file and then in the Grid object, and we 
     put them into the SubgridFluxesEstimate array. */
 
  if(CheckpointRestart == TRUE) {
    for (grid1 = 0; grid1 < NumberOfGrids; grid1++) {
      if (Grids[grid1]->GridData->FillFluxesFromStorage(
        &NumberOfSubgrids[grid1],
        &SubgridFluxesEstimate[grid1]) != -1) {
        /*fprintf(stderr, "Level: %"ISYM" Grid: %"ISYM" NS: %"ISYM"\n",
            level, grid1, NumberOfSubgrids[grid1]);*/
      }
    }
  } else {
    for (grid1 = 0; grid1 < NumberOfGrids; grid1++)
      Grids[grid1]->GridData->ClearBoundaryFluxes();
  }
 
  /* After we calculate the ghost zones, we can initialize streaming
     data files (only on level 0) */

  if (MetaData->FirstTimestepAfterRestart == TRUE && level == 0)
    WriteStreamData(LevelArray, level, MetaData, MovieCycleCount);


  /* ================================================================== */
  /* Loop over grid timesteps until the elapsed time equals the timestep
     from the level above (or loop once for the top level). */
 
  while ((CheckpointRestart == TRUE)
        || (dtThisLevelSoFar[level] < dtLevelAbove)) {
    if(CheckpointRestart == FALSE) {

    TIMER_START(level_name);
    SetLevelTimeStep(Grids, NumberOfGrids, level, 
        &dtThisLevelSoFar[level], &dtThisLevel[level], dtLevelAbove);

    /* If StarFormationOncePerRootGridTimeStep, stars are only created
    once per root grid time step and only on MaximumRefinementLevel
    grids. The following sets the MakeStars flag for all
    MaximumRefinementLevel grids when level==0. Post star formation,
    MakeStars is unset in Grid::StarParticleHandler() in order to
    prevent further star formation until the next root grid time
    step. */

    /* Currently (April 2012) this is only implemented for H2REG_STAR,
    and MakeStars is completely ignored in all other star makers. */

    if ( (STARMAKE_METHOD(H2REG_STAR)) && 
	 (level==0) && 
	 (StarFormationOncePerRootGridTimeStep) ) {
      /* At top level, set Grid::MakeStars to 1 for all highest
	 refinement level grids. */
      LevelHierarchyEntry *Temp;
      Temp = LevelArray[MaximumRefinementLevel];
      int count=0;
      while (Temp != NULL) {
	Temp->GridData->SetMakeStars();
	Temp = Temp->NextGridThisLevel;
	count++;
      }
      // if(MyProcessorNumber == ROOT_PROCESSOR) 
      // 	fprintf(stderr,"Set MakeStars=1 for %d MaximumRefinementLevel grids.\n",count);

      TopGridTimeStep = LevelArray[0]->GridData->ReturnTimeStep();

    }

    /* Streaming movie output (write after all parent grids are
       updated) */

    WriteStreamData(LevelArray, level, MetaData, MovieCycleCount);

    /* Initialize the star particles */

    Star *AllStars = NULL;
    ActiveParticleInitialize(Grids, MetaData, NumberOfGrids, LevelArray,
	                     level);
    
#ifdef TRANSFER
    /* Initialize the radiative transfer */

    RadiativeTransferPrepare(LevelArray, level, MetaData, AllStars, 
			     dtLevelAbove);
    RadiativeTransferCallFLD(LevelArray, level, MetaData, AllStars, 
			     ImplicitSolver);

    /* Solve the radiative transfer */
	
    GridTime = Grids[0]->GridData->ReturnTime() + dtThisLevel[level];
    EvolvePhotons(MetaData, LevelArray, AllStars, GridTime, level);
 
#endif /* TRANSFER */

    /* trying to clear Emissivity here after FLD uses it, doesn't work */
 
    CreateFluxes(Grids,SubgridFluxesEstimate,NumberOfGrids,NumberOfSubgrids);

    /* ------------------------------------------------------- */
    /* Prepare the density field (including particle density). */

    When = 0.5;

#ifdef FAST_SIB
     PrepareDensityField(LevelArray, SiblingList, level, MetaData, When);
#else   // !FAST_SIB
     PrepareDensityField(LevelArray, level, MetaData, When);
#endif  // end FAST_SIB
 
 
    /* Prepare normalization for random forcing. Involves top grid only. */
 
    ComputeRandomForcingNormalization(LevelArray, 0, MetaData,
				      &norm, &TopGridTimeStep);

    /* ------------------------------------------------------- */
    /* Evolve all grids by timestep dtThisLevel. */

    for (grid1 = 0; grid1 < NumberOfGrids; grid1++) {
 
      CallProblemSpecificRoutines(MetaData, Grids[grid1], grid1, &norm, 
				  TopGridTimeStep, level, LevelCycleCount);

      /* Gravity: compute acceleration field for grid and particles. */
 
      if (SelfGravity) {
	if (level <= MaximumGravityRefinementLevel) {
 
	  /* Compute the potential. */
 
	  if (level > 0)
	    Grids[grid1]->GridData->SolveForPotential(level);
	  Grids[grid1]->GridData->ComputeAccelerations(level);
	  Grids[grid1]->GridData->CopyPotentialToBaryonField();
	}
	  /* otherwise, interpolate potential from coarser grid, which is
	     now done in PrepareDensity. */
 
      } // end: if (SelfGravity)
 
      /* Gravity: compute field due to preset sources. */
 
      Grids[grid1]->GridData->ComputeAccelerationFieldExternal();
 
      /* Radiation Pressure: add to acceleration field */

#ifdef TRANSFER
      Grids[grid1]->GridData->AddRadiationPressureAcceleration();
#endif /* TRANSFER */

      /* Check for energy conservation. */
/*
      if (ComputePotential)
	if (CheckEnergyConservation(Grids, grid, NumberOfGrids, level,
				    dtThisLevel) == FAIL) {
	  ENZO_FAIL("Error in CheckEnergyConservation.\n");
	}
*/
#ifdef SAB
    } // End of loop over grids
    
    //Ensure the consistency of the AccelerationField
    SetAccelerationBoundary(Grids, NumberOfGrids,SiblingList,level, MetaData,
			    Exterior, LevelArray[level], LevelCycleCount[level]);
    for (grid1 = 0; grid1 < NumberOfGrids; grid1++) {
#endif //SAB.
      /* Copy current fields (with their boundaries) to the old fields
	  in preparation for the new step. */
      Grids[grid1]->GridData->CopyBaryonFieldToOldBaryonField();

      /* Call hydro solver and save fluxes around subgrids. */
      Grids[grid1]->GridData->SolveHydroEquations(LevelCycleCount[level],
	    NumberOfSubgrids[grid1], SubgridFluxesEstimate[grid1], level);
      /* Solve the cooling and species rate equations. */
 
      Grids[grid1]->GridData->MultiSpeciesHandler();

      /* Update particle positions (if present). */
      
      UpdateParticlePositions(Grids[grid1]->GridData);

    /*Trying after solving for radiative transfer */
#ifdef EMISSIVITY
    /*                                                                                                           
        clear the Emissivity of the level below, after the level below                                            
        updated the current level (it's parent) and before the next
        timestep at the current level.                                                                            
    */
      /*    if (StarMakerEmissivityField > 0) {
    LevelHierarchyEntry *Temp;
    Temp = LevelArray[level];
    while (Temp != NULL) {
      Temp->GridData->ClearEmissivity();
      Temp = Temp->NextGridThisLevel;
      }
      }*/
#endif

      /* Include 'star' particle creation and feedback. */

      Grids[grid1]->GridData->ActiveParticleHandler
	(Grids[grid1]->NextGridNextLevel, level ,dtLevelAbove, 
	 NumberOfNewActiveParticles[grid1]);      

      /* Include shock-finding */

      Grids[grid1]->GridData->ShocksHandler();

      /* Compute and apply thermal conduction. */
      if(IsotropicConduction || AnisotropicConduction){
	if(Grids[grid1]->GridData->ConductHeat() == FAIL){
	  ENZO_FAIL("Error in grid->ConductHeat.\n");
	}
      }

      /* Gravity: clean up AccelerationField. */

#ifndef SAB
      if ((level != MaximumGravityRefinementLevel ||
	   MaximumGravityRefinementLevel == MaximumRefinementLevel) &&
	  !PressureFree)
	Grids[grid1]->GridData->DeleteAccelerationField();
#endif //!SAB

      Grids[grid1]->GridData->DeleteParticleAcceleration();
 
      /* Update current problem time of this subgrid. */
 
      Grids[grid1]->GridData->SetTimeNextTimestep();
 
      /* If using comoving co-ordinates, do the expansion terms now. */
 
      if (ComovingCoordinates)
	Grids[grid1]->GridData->ComovingExpansionTerms();
 
    }  // end loop over grids
 
    /* Finalize (accretion, feedback, etc.) star particles */

    ActiveParticleFinalize(Grids, MetaData, NumberOfGrids, LevelArray,
			   level, NumberOfNewActiveParticles);

    /* For each grid: a) interpolate boundaries from the parent grid.
                      b) copy any overlapping zones from siblings. */
 
#ifdef FAST_SIB
    SetBoundaryConditions(Grids, NumberOfGrids, SiblingList,
			  level, MetaData, Exterior, LevelArray[level]);
#else
    SetBoundaryConditions(Grids, NumberOfGrids, level, MetaData,
			  Exterior, LevelArray[level]);
#endif

    /* If cosmology, then compute grav. potential for output if needed. */


    /* For each grid, delete the GravitatingMassFieldParticles. */
 
    for (grid1 = 0; grid1 < NumberOfGrids; grid1++)
      Grids[grid1]->GridData->DeleteGravitatingMassFieldParticles();

    TIMER_STOP(level_name);
    /* ----------------------------------------- */
    /* Evolve the next level down (recursively). */
 
    MetaData->FirstTimestepAfterRestart = FALSE;

    } else { // CheckpointRestart
        // dtThisLevelSoFar set during restart
        // dtThisLevel set during restart
        // Set dtFixed on each grid to dtThisLevel
        for (grid1 = 0; grid1 < NumberOfGrids; grid1++)
          Grids[grid1]->GridData->SetTimeStep(dtThisLevel[level]);
    }

    if (LevelArray[level+1] != NULL) {
      if (EvolveLevel(MetaData, LevelArray, level+1, dtThisLevel[level], Exterior
#ifdef TRANSFER
		      , ImplicitSolver
#endif
		      ) == FAIL) {
	ENZO_VFAIL("Error in EvolveLevel (%"ISYM").\n", level)
      }
    }

#ifdef USE_LCAPERF
    // Update lcaperf "level" attribute

    lcaperf.attribute ("level",&lcaperf_level,LCAPERF_INT);
#endif

    OutputFromEvolveLevel(LevelArray, MetaData, level, Exterior
#ifdef TRANSFER
			  , ImplicitSolver
#endif
			  );
#ifdef USE_PYTHON
    LCAPERF_START("CallPython");
    CallPython(LevelArray, Grids, MetaData, level, 0);
    LCAPERF_STOP("CallPython");
#endif

    /* Update SubcycleNumber and the timestep counter for the
       streaming data if this is the bottom of the hierarchy -- Note
       that this not unique based on which level is the highest, it
       just keeps going */

    if (LevelArray[level+1] == NULL) {
      MetaData->SubcycleNumber++;
      MetaData->MovieTimestepCounter++;
    }

    /* Once MBH particles are inserted throughout the whole grid hierarchy,
       turn off MBH creation (at the bottom of the hierarchy) */

    if (STARMAKE_METHOD(MBH_PARTICLE) && (LevelArray[level+1] == NULL)) { 
      StarParticleCreation -= pow(2, MBH_PARTICLE);  
    }

    /* ------------------------------------------------------- */
    /* For each grid,
     * (a) project the subgrid's solution into this grid (step #18)
     * (b) correct for the difference between this grid's fluxes and the
     *     subgrid's fluxes. (step #19)
     */
 
#ifdef FLUX_FIX
    SUBlingList = new LevelHierarchyEntry*[NumberOfGrids];
#ifdef FAST_SIB
    CreateSUBlingList(MetaData, LevelArray, level, SiblingList,
		      &SUBlingList);
#else
    CreateSUBlingList(MetaData, LevelArray, level, &SUBlingList);
#endif /* FAST_SIB */
#endif /* FLUX_FIX */
    
#ifdef FLUX_FIX
    UpdateFromFinerGrids(level, Grids, NumberOfGrids, NumberOfSubgrids,
			     SubgridFluxesEstimate,SUBlingList,MetaData);
#else
    UpdateFromFinerGrids(level, Grids, NumberOfGrids, NumberOfSubgrids,
			 SubgridFluxesEstimate);
#endif

#ifdef FLUX_FIX
    DeleteSUBlingList( NumberOfGrids, SUBlingList );
#endif

  /* ------------------------------------------------------- */
  /* Add the saved fluxes (in the last subsubgrid entry) to the exterior
     fluxes for this subgrid .
     (Note: this must be done after CorrectForRefinedFluxes). */

    FinalizeFluxes(Grids,SubgridFluxesEstimate,NumberOfGrids,NumberOfSubgrids);

    /* Recompute radiation field, if requested. */
    RadiationFieldUpdate(LevelArray, level, MetaData);
 
//     //dcc cut second potential cut: Duplicate?
 
//     if (SelfGravity && WritePotential) {
//       CopyGravPotential = TRUE;
//       When = 0.0;
 
// #ifdef FAST_SIB
//       PrepareDensityField(LevelArray, SiblingList, level, MetaData, When);
// #else   // !FAST_SIB
//       PrepareDensityField(LevelArray, level, MetaData, When);
// #endif  // end FAST_SIB
 
 
//       for (grid1 = 0; grid1 < NumberOfGrids; grid1++) {
//         if (level <= MaximumGravityRefinementLevel) {
 
//           /* Compute the potential. */
 
//           if (level > 0)
//             Grids[grid1]->GridData->SolveForPotential(level);
//           Grids[grid1]->GridData->CopyPotentialToBaryonField();
//         }
//       } //  end loop over grids
//        CopyGravPotential = FALSE;

//     } // if WritePotential
 
    /* Rebuild the Grids on the next level down.
       Don't bother on the last cycle, as we'll rebuild this grid soon. */

    /* Count up number of grids on this level. */

    int GridMemory, NumberOfCells, CellsTotal, Particles;
    float AxialRatio, GridVolume;
    for (grid1 = 0; grid1 < NumberOfGrids; grid1++) {
      Grids[grid1]->GridData->CollectGridInformation
        (GridMemory, GridVolume, NumberOfCells, AxialRatio, CellsTotal, Particles);
      LevelZoneCycleCount[level] += NumberOfCells;
      TIMER_ADD_CELLS(level, NumberOfCells);
      if (MyProcessorNumber == Grids[grid1]->GridData->ReturnProcessorNumber())
	LevelZoneCycleCountPerProc[level] += NumberOfCells;
    }
    TIMER_SET_NGRIDS(level, NumberOfGrids);

    /* Rebuild the Grids on the next level down.
       Don't bother on the last cycle, as we'll rebuild this grid soon. */
 
    if (dtThisLevelSoFar[level] < dtLevelAbove) {
      RebuildHierarchy(MetaData, LevelArray, level);
    }

    cycle++;
    LevelCycleCount[level]++;
 
  } // end of loop over subcycles
 
  if (debug)
    fprintf(stdout, "EvolveLevel[%"ISYM"]: NumberOfSubCycles = %"ISYM" (%"ISYM" total)\n", level,
           cycle, LevelCycleCount[level]);
 
  /* If possible & desired, report on memory usage. */
 
  ReportMemoryUsage("Memory usage report: Evolve Level");
 
#ifdef USE_LCAPERF
  lcaperf.attribute ("level",0,LCAPERF_NULL);
#endif

  
  /* Clean up. */
 
  delete [] NumberOfSubgrids;
  delete [] NumberOfNewParticles;
  delete [] Grids;
  delete [] SubgridFluxesEstimate;

  dtThisLevel[level] = dtThisLevelSoFar[level] = 0.0;
 
  /* Clean up the sibling list. */


  if ((NumberOfGrids >1) || ( StaticLevelZero == 1 && level != 0 ) || StaticLevelZero == 0 ) {

    for (grid1 = 0; grid1 < NumberOfGrids; grid1++)
      delete [] SiblingList[grid1].GridList;
    delete [] SiblingList;
  }

  return SUCCESS;
 
}