void SAstoroidBelt::proces(uint32_t delta, Processor* processor ){
	for(list<SAstoroidBeltRoid*>::iterator it = _roids.begin(); it != _roids.end(); it++){
		if((*it)->_roid == NULL && (*it)->_counter == 0 ){
			SPos temppos(myrandom(_pos.x-_size,_pos.x+_size),myrandom(_pos.y-_size,_pos.y+_size),0);
			temppos.grid = world->getGrids().begin()->second;
			(*it)->_roid = processor->createAsteroid(temppos, *(*it)->_type, this);
			//world->getGrids()[1]->addAstoroid((*it)->_roid);
		}else if((*it)->_roid == NULL && (*it)->_counter ){
			(*it)->_counter--;
		}
	}
}
Exemple #2
0
int main()

{
    degreedaymethod = 1;
    ratio = startratio;

    /*----------------------------------------------------------------*/
    /*** READ DATA FROM CONTROLING INPUT FILE / INITIALISATION     ****/
    /*----------------------------------------------------------------*/

    input_read();      /*** READ INPUT DATA ***/    
    degreestart();
    startinputdata();  /***OPEN AND READ GRID FILES AND CLIMATE DATA until start***/
    checkgridinputdata_ok(); /*check if grid input data ok*/
    startoutascii();   /***OPEN ASCII-OUTPUT FILES AND WRITE HEADS***/
    startspecificmassbalance(); /*OPEN FILE FOR GLACIER-WIDE SEASONAL MASS BAL, MULTI-YEAR RUNS*/
    startarrayreserve();   /*RESERVE STORAGE FOR GRID-ARRAYS*/
    glacierrowcol();  /*FIND FIRST, LAST ROW AND COLUMN WHICH IS GLACIERIZED IN DTM*/
    readclim();       /*** READ CLIMATE INPUT FIRST ROW = ONE TIME STEP ****/

    if((winterbalyes == 1) || (summerbalyes == 1))
        areaelevationbelts();    /*number of grid cells per elevation band, for bn profiles*/

    if(maxmeltstakes > 0)
        startmeltstakes();    /*OUTPUT OF MELT OF SEVERAL LOCATIONS - COMPARISON WITH STAKES*/

    if(snowfreeyes == 1)    /*OPEN FILE WITH TIME SERIES WITH NUMBER OF SNOWFREE PIXELS PER DAY*/
        opensnowfree();

    if((datesfromfileyes == 1) &&  (winterbalyes == 1) && (summerbalyes == 1))
        readdatesmassbal();      /*READ DATES OF MASS BAL MEASUREMENTS FOR EACH YEAR*/

    if(methodprecipinterpol == 2)    /*read precipitation index map once (constant in time)*/
        readprecipindexmap();        /*in turbul.c under precipitation*/

    if (disyes >= 1)        /*DISCHARGE SIMULATION REQUESTED, 1=discharge data, 2=no data*/
        startdischarg();     /*INITIALIZE DISCHARGE SIMULATION*/

/*printf("==============ddmethod in detim.c = %d ===================\n",ddmethod);*/

    /*=============FOR EVERY TIME STEP ===============================================*/

    do {

        nsteps += 1;         /*number of time steps of period calculated*/

        /******* ADJUST BY USER, HOW OFTEN OUTPUT JD-TIME TO SCREEN *******/
        if((zeit==24) && (jd/daysscreenoutput == floor((int)jd/daysscreenoutput)))
            printf("\n  yr= %4.0f  jd = %4.2f   time =%3.0f  number of time steps=%d",year,jd,zeit,nsteps);


        /******* TEMPERATURE INTERPOLATION ******/
        tempinterpol(); /*** ELEVATION-DEPENDENT AIR TEMP INTERPOLATION ***/

        if(do_out_area == 1)
            areameannull();  /* SPATIAL MEANS OF MODEL OUTPUT SET TO ZERO */

        if(ddmethod > 1) {    /*DIRECT RAD NOT NEEDED FOR SIMPLE DEGREE DAY*/
            if (directfromfile == 0)
                schatten();      /*** CALCULATE SHADE, CORRECTION FACTOR, DIRECT GRIDs ***/
            else
                readdirect();    /* READ DIRECT RADIATION (slope corrected) FROM FILE */
        }

        if(methodinisnow == 1)  /*NEEDED FOR DISCHARGE CALCULATIONS FOR ANY ddmethod*/
            albedoread();   /* OPEN AND READ SPECIFIC ALBEDO FILE IF NEW ONE VALID FOR TIME STEP */
        else
            whichsurface();   /*VALUE FOR ARRAY surface (SNOW,FIRN,ICE,ROCK) ICE/SNOW DDF AND K-VALUES*/

        /*EXTENDED TEMP INDEX METHOD WITH DIRECT RAD AND CLOUD REDUCTION*/
        if(ddmethod == 3)
            ratioglobal();   /*CALC RATIO OF MEASURED GLOBAL RAD AND CALCULATED DIRECT RAD*/

        if(methodprecipinterpol == 3)   /*read precipitation grids from file for each time step*/
            readprecipfromfile();


/*------- FOR EACH GRID POINT - only for drainage basin grid (DEM 2 defines the area to be computed)--*/

        for (i=firstrow; i<=lastrow; i++)           /*for all rows with area to be calculated*/
            for (j=firstcol[i]; j<=lastcol[i]; j++) {  /*for all columns*/

                if (griddgmdrain[i][j] != nodata) { /*only for area to be calculated defined by dgmdrain*/
                    if (griddgmdrain[i][j] != griddgm[i][j]) {
                        printf("\n\n ERROR elevation in DTM is not the same as in drainage grid\n");
                        printf("	 row  %d  col  %d      (function meltmod.c\n\n",i,j);
                        exit(12);
                    }

                    temppos();      /*** copying interpolated temp into positive temp-grid ***/
                    airpress();     /*** CALCULATION AIR PRESSURE AT GRID POINT         ***/
                    vappress();     /*** CALCULATION VAPOUR PRESSURE FROM REL. HUMIDITY ***/

                    /*==================================================================*/

                    switch(ddmethod)
                    {
                    case 1:
                        degreedaymelt();    /*CALCULATING MELT WITH DEGREE DAY*/
                        break;
                    case 2:
                        dd_directmelt();    /*INCLUDING DIRECT RADIATION (J.Glac. 1999)*/
                        break;
                    case 3:
                        dd_directglobal();  /*AS BUT INCLUDING GLOBAL RAD (J.GLAC 1999)*/
                        break;

                    default:
                        printf("\n ERROR: No temperature index method (ddmethod) defined\n");
                        printf("       ddmethod should be 1, 2 or 3 (printed from detim.c)\n");
                        exit(20);
                    }

                    /*==================================================================*/

                    ddfcalculation();    /*CALCULATE CORRESPONDING DEGREE DAY MELT/TEMPOS*/

                    /******* PRECIPITATION *********************/
                    precipinterpol();

                    if(methodinisnow == 2)      /*run with known initial snow cover*/
                        snowcoverdegree();       /*snow precip added to snow cover, to find k-values*/

                    if (griddgmglac[i][j] != nodata)   /*only for glacier, no matter if dgmdrain is larger*/
                            massbalance();    /*compute mass balance in any case, used for areamean output*/

                    /*** SUMMING UP ALL VALUES OVER AREA - for spatial means ***/
                    if(do_out_area == 1)
                        areasum();

                } /*endif*/
            }  /*endfor next grid*/


/***------------------ NEXT GRID CELL--------------------------------------------- ***/

        /*WHOLE GRIDS ARE CALCULATED FOR ONE TIME STEP -
           NOW CACULATE DISCHARGE AND WRITE TO OUTPUTFILE*/

        /********************* DISCHARGE ************************/

        if (disyes >= 1) {   /*DISCHARGE TO BE CALCULATED, measured file available (1) or not (2)*/
            if(onlyglacieryes == 1)  /*drainage basin larger than glacier*/
                rainoutsideglac();       /*rain from outside put onto the glacier, discharg.c*/

            if (disyesopt == 0)       /*simulation run*/
                discharge();    /*for every grid calculated discharge, sum to melt and sum discharge*/

            if (disyesopt == 1)     /*optimization run, disyes set to 1 in input.c*/
                dischargeopt();       /*calculated discharg, with optimal r2-criterium*/
        }
 
        /*** WRITE MODEL RESULTS TO FILE FOR INDIVIDUAL GRIDPOINTS FOR EVERY TIME STEP ***/
        if (outgridnumber > 0)     /*output file requested by user*/
            stationoutput();

        /*** WRITE MASS BALANCE FOR SEVERAL LOCATIONS TO ONE FILE ***/
        if(maxmeltstakes > 0)
            writemeltstakes();

        /*** WRITE GRID FILES ***/
        switch(do_out)   /*** WRITE ENERGY BALANCE GRID-OUTPUT-FILES ***/

        {
        case 0:
            break;
        case 1:     /*OUTPUT EVERY TIME STEP*/
            startwritehour();    /*open output-files for every time step*/
            writegridoutput();
            break;

        case 2:     /*OUTPUT ONLY EVERY DAY*/
            sumday();             /*sum up values for subdiurnal timesteps*/
            if (zeit == 24.0) {   /*last hour of day*/
                startwriteday();   /*open files for daily means*/
                writegridoutput(); /*write grid to output file*/
                meandaynull();     /*after writing initialize to zero*/
            }  /*if*/
            break;

        case 3:     /*OUTPUT ONLY FOR WHOLE PERIOD*/
            sumall();             /*sum up values for subdiurnal timesteps*/
            break;                /*mean for whole period : write at end*/

        case 4:     /*OUTPUT EVERY DAY AND FOR WHOLE PERIOD*/
            sumday();             /*sum up for daily means*/
            sumall();             /*sum up for period means*/
            /*must be done before writing daily means to files, because
              MELT-array will be overwritten by daily mean, discharge must
              also be calculated before*/
            if (zeit == 24) {     /*daily means, write period means at end*/
                startwriteday();   /*open files for daily means*/
                writegridoutput();
                meandaynull();     /*after writing initialize to zero*/
            }  /*if*/
        } /*switch*/


        /*CHECK IF SURFACE CONDITIONS OR SNOW COVER FILES SHOULD BE WRITTEN TO OUTPUT*/
        /*    NO TEMPORAL MEANS POSSIBLE - FOR VALIDATION OF SNOW LINE RETREAT */
        writesnoworsurfaceyes();

        /* WRITE GRID OF SURFACE CONDITIONS - ONLY FOR MIDNIGHT EVERY daysnow-th DAY */
        /*   OR FOR SELECTED DAYS SPECIFIED IN input.dat*/

        if((surfyes >= 1) && (write2fileyes == 1))
            writesurface();      /*open file and write to file*/
        if((snowyes >= 1) && (write2fileyes == 1))
            writesnowcover();      /*open file and write to file*/

        /*  WRITE TO TIME SERIES ASCII FILE EVERY MIDNIGHT HOW MANY PIXELS SNOWFREE*/
        if((snowfreeyes == 1) && (zeit == 24))
            percentsnowfree();

        /* WRITE TIME SERIES OF SPATIAL MEAN MODEL RESULTS TO OUTPUT FOR EVERY TIME STEP*/
        if (do_out_area == 1)
            areameanwrite();

        /*write winter/summer/mass balance grids at end of winter/summer*/
        if((winterbalyes == 1) || (summerbalyes == 1))
            if(zeit == 24)
                writemassbalgrid();    /*balance grids are in arrays WINTERBAL, SUMMERBAL*/

        /********** Glacier geometry changes updated only once a year at end of summer **********************************/
    if((jd == summerjdend) && (retreatyes >= 1) && (zeit == 24) )
	 { if( (datesfromfileyes == 0) || ( (datesfromfileyes == 1) && (year == nextyear))) 
	    { switch(retreatyes)	      
	      { case 1:     /*V-A scaling*/
		      scaling();
		      break;
	        case 2:     /*Huss et al. 2010, NEW Aug 2015*/
		      retreat_Huss();
		      break;
	        case 3:     /*Truessel et al. 2015, JGlac, not implemented yet*/
		      break;
	        default:
		  printf("\n no retreat method defined (retreatyes=%d)\n  (Message send from detim.c\n",retreatyes);
                    exit(20);
	      }  /*end switch*/
	     } /*if*/
	    n_retreatyears += 1;  /*count number of years retreat is computed*/
	 } /*if retreat calculation*/


        /**********/
        /*set snow array to zero at end of melt season for next mass balance year*/
        /*to avoid that snow constantly accumulates in accumulation area and therefore*/
        /*firn is never exposed; done each year at start of winter*/
        if( (methodinisnow == 2) && (snow2zeroeachyearyes == 1) && (jd == (winterjdbeg)) && (zeit == 24) )
            initializeglacier2zero_nodatadouble(nrows, ncols, SNOW);

        readclim();       /*** READ CLIMATE INPUT NEXT TIME STEP ****/

        if(timestep != 24) {  /*subdaily timesteps: midnight row is next julian day not to continue with*/
            if((jd > (jdend+1)) && (year == yearend))
                stoploop = 1;
        } else if((jd == jdend+1) && (year == yearend)) /*otherwise last julian day would not be run*/
            stoploop = 1;

    }  while (stoploop != 1);

    /*====================== NEXT TIME STEP =======================================*/

    /*OUTPUT OF MEAN COMPONENTS OF ENERGY BALANCE FOR WHOLE PERIOD OF CALCULATION*/

    if ((do_out == 3) || (do_out == 4)) {   /*mean of whole period*/
        startwriteall();   /*open files for whole period*/
        writegridoutput();
    }

    /********** WRITE MEAN MASS BALANCE PROFILE TO FILE********************************/
        /* only if glacier area is constant*/
    if(((winterbalyes == 1) || (summerbalyes == 1)) && (retreatyes = 0))
        meanmassbalprofile();     /*mean over all years*/

    /******************************************************************/

    if (disyes == 1) {    /*only if discharge data available*/
        r2calc();
        r2calcln();
        if (disyesopt == 1)   /*optimization run*/
            write2matriz();    /*write r2 matriz to file*/
    }

	writeperformance();   /*write model performance (r2 etc) to text-file, added 10/2013*/
    closeall();     /* CLOSE FILES, SPEICHERFREIGABE */
    writemodelmeaspointbalances();    /*must be after closeall because it opens cummassbal.txt, added 10/2013*/
    fclose(outcontrol);    /*can not be in closeall.c because used in writemodelmeaspointbalances()*/
    outcontrol = NULL;

    printf("\n number of calculated grid cells (DEM2)  = %d\n",ndrain);
	printf(" number of glacier grid cells (DEM3)     =  %d\n",nglac);
	printf("   number of calculated time steps       = %d\n",nsteps);
    printf("   number of timesteps of discharge data = %d\n",nstepsdis);
    if(disyes ==1) {
        printf(" Simulated discharge volume (100 000 m3) = %8.2f\n",volumesim);
        printf(" Measured discharge volume               = %8.2f\n",volumemeas);
    }
    printf(" Mass balance over entire simulation period (m) = %.3f\n",areamassbalcum/100);

    printf("\n output written to   %s\n\n",outpath);
    printf("********* PROGRAM RUN COMPLETED ************\n\n");

    return 0;
}
/*!

*/
void Md_method::run(Program_options & options, ostream & output)
{

  output.precision(10);


  string logfile=options.runid+".log";
  prop.setLog(logfile, log_label);

  int natoms=sys->nIons();

  Array1 < Array1 <int> > atom_move;
  Array1 < Array2 <doublevar> > displace;

  //Even numbered displacements are in + direction, odd are in 
  // - direction

  if(natoms==2) {
    //For a dimer, assume they are oriented in the z 
    //direction and only move in that direction.
    atom_move.Resize(4);
    displace.Resize(4);
    int count=0;
    for(int at=0; at < natoms; at++) {
      for(int s=0; s< 2; s++) {
        atom_move(count).Resize(1);
        displace(count).Resize(1,3);
        atom_move(count)(0)=at;
        displace(count)=0;
          if(s==0) 
            displace(count)(0,2)=0.00025;
          else
            displace(count)(0,2)=-0.00025;
          count++;
      }
    }
    
  }
  else {
    int ndim=0;
    for(int d=0; d< 3; d++) {
      if(restrict_dimension(d) ==0) ndim++;
    }
    atom_move.Resize(2*ndim*natoms);
    displace.Resize(2*ndim*natoms);
    int count=0;
    for(int at=0; at< natoms; at++) {
      for(int d=0; d< 3; d++) {
        if(!restrict_dimension(d) ) {
        for(int s=0; s< 2; s++) {
          atom_move(count).Resize(1);
          displace(count).Resize(1,3);
          atom_move(count)(0)=at;
          displace(count)=0;
          if(s==0) 
            displace(count)(0,d)=0.00025;
          else
            displace(count)(0,d)=-0.00025;
          count++;
        }
      }
      }
    }
  }
  
  prop.setDisplacement(atom_move, displace);
  Properties_final_average curravg;
  
  string vmcout=options.runid+".embed";
  ofstream vmcoutput;
  if(output) 
	vmcoutput.open(vmcout.c_str());

 
  Array3 <doublevar> ionpos(nstep+2, natoms, 3, 0.0);
  Array1 <doublevar> temppos(3);


  for(int s=0; s< 2; s++) {
    for(int at=0; at< natoms; at++) {
      sys->getIonPos(at, temppos);
      for(int d=0; d< 3; d++) {
        ionpos(s,at,d)=temppos(d);
      }
    }
  }

  if(readcheckfile != "") {
    read_check(ionpos);
  }


  for(int s=0; s< 2; s++) {
    Array2 <doublevar> pos(ionpos(s));
    recenter(pos, atomic_weights);
  }

  for(int step=0; step < nstep; step++) {

    int currt=step+1; //current time

    for(int at=0; at< natoms; at++) {
      for(int d=0; d< 3; d++) {
        temppos(d)=ionpos(currt, at, d);
      }
      sys->setIonPos(at, temppos);
    }

    qmc_avg->runWithVariables(prop, sys, wfdata, pseudo, vmcoutput);
    prop.getFinal(curravg);
    
    if(output) 
      output << "*****Step " << step << endl;
    Array2 <doublevar> force(natoms, 3, 0.0);
    Array2 <doublevar> force_err(natoms, 3, 0.0);

    for(int f=0; f< atom_move.GetDim(0); f+=2 ) {
      for(int m=0; m < atom_move(f).GetDim(0); m++) {
        int at=atom_move(f)(m);
        for(int d=0; d< 3; d++) {
          //Take a finite difference between the two forces
          doublevar prop=fabs(displace(f)(m,d)/curravg.aux_size(f));
          doublevar fin_diff=(curravg.aux_diff(f,0)-curravg.aux_diff(f+1,0))
            /(2*curravg.aux_size(f));
          force(at,d)+= -prop*fin_diff;
          
          force_err(at,d)+=prop*(curravg.aux_differr(f,0)
                                 +curravg.aux_differr(f+1,0))
            /(2*curravg.aux_size(f))/(2*curravg.aux_size(f));
        }
      }
    }


   
    for(int at=0; at< natoms; at++) {
      for(int d=0; d< 3; d++) 
        force_err(at,d)=sqrt(force_err(at,d));
    }


    //Make sure that Newton's laws are actually followed for
    //two atoms; we can do this for more, as well.
    if(natoms==2) {
      doublevar average=(force(0,2)-force(1,2))/2.0;
      force(0,2)=average;
      force(1,2)=-average;
    }
    
    //Verlet algorithm..
    for(int at=0; at< natoms; at++) {
      for(int d=0; d< 3; d++) {
        ionpos(currt+1, at, d)=ionpos(currt, at,d)
          +(1-damp)*(ionpos(currt, at, d)-ionpos(currt-1, at,d))
          +tstep*tstep*force(at,d)/atomic_weights(at);
        //cout << "pos " << ionpos(currt, at,d)  
        //     << "  last " <<  ionpos(currt-1, at,d) 
        //     << "  weight " << atomic_weights(at) << endl;
      }
    }

    Array2 <doublevar> currpos(ionpos(currt+1));
    recenter(currpos, atomic_weights);
    
    doublevar kinen=0;
    int field=output.precision() + 15;
    
    for(int at=0; at < natoms; at++) {
      if(output) 

        output << "position" << at << " " 
             << setw(field)  << ionpos(currt+1, at, 0)
             << setw(field) << ionpos(currt+1, at, 1) 
             << setw(field) << ionpos(currt+1, at, 2) << endl;

      Array1 <doublevar> velocity(3);
      for(int d=0; d< 3; d++) {
        velocity(d)=(ionpos(currt+1, at, d)-ionpos(currt-1, at,d))/(2*tstep);
      }
      
      for(int d=0;d < 3; d++) {
        kinen+=.5*atomic_weights(at)*velocity(d)*velocity(d);
      }
      if(output ) {
        output << "velocity" << at << " "
               << setw(field) << velocity(0) 
               << setw(field) << velocity(1) 
               << setw(field) << velocity(2) << endl;
        
        output << "force" << at << "    "
               << setw(field) << force(at,0) 
               << setw(field) << force(at, 1) 
               << setw(field) << force(at,2) << endl;
        output << "force_err" << at 
               << setw(field) << force_err(at, 0)
               << setw(field) << force_err(at, 1)
               << setw(field) << force_err(at, 2) << endl;
      //output << "force" << at << "z  " << force(at,2) << " +/- "
      //      << force_err(at,2) << endl;
      }

    }
    if(output ) { 
    output << "kinetic_energy " << kinen << endl;
    output << "electronic_energy " << curravg.total_energy(0) << " +/- " 
           << sqrt(curravg.total_energyerr(0)) << endl;

    output << "total_energy " << curravg.total_energy(0)+kinen << " +/- "
           << sqrt(curravg.total_energyerr(0)) <<  endl;

    if(writecheckfile != "") 
      if(output) 
         write_check(ionpos, currt+1);
    }

  }
  if(output) 
    vmcoutput.close();


}