コード例 #1
0
ファイル: render.cpp プロジェクト: Kalamatee/RayStorm
void CRenderOutput::UpdateStatus(float percent, float time)
{
	char szBuf[150];

	refresh++;
	if (refresh % 10 == 0 || percent == 1.0 || percent == 0.0)
	{
		if (percent < .0)
			percent = .0;
		if (percent > 1.0)
			percent = 1.0;

		m_Progress.SetPos(int(percent*100));
		sprintf(szBuf, "%3.0f %%", percent*100);
		SetDlgItemText(ID_PERCENT, szBuf);
	
		if (percent > .0)
		{
			Time(szBuf, "Time elapsed:", time);
			SetDlgItemText(ID_ELAPSED, szBuf);
			Time(szBuf, "Left:", (float)clock_t(time/percent) - time);
			SetDlgItemText(ID_TIMELEFT, szBuf);
			Time(szBuf, "Estimated:", (float)clock_t(time/percent));
			SetDlgItemText(ID_ESTIMAT, szBuf);
		}
	}
}
コード例 #2
0
ファイル: render.cpp プロジェクト: Kalamatee/RayStorm
void CRenderOutput::Time(char *buffer, char *text, float time)
{
	clock_t h, m, s;

	h = clock_t(time/3600);
	m = clock_t(fmod((time/60), 60));
	s = clock_t(fmod(time, 60));
	sprintf(buffer, "%s %02d:%02d:%02d", text, h, m, s);
}
コード例 #3
0
bool time_to_save() {
  static clock_t output_period = CLOCKS_PER_SEC; // start at outputting every second
  // top out at one hour interval
  clock_t max_output_period = clock_t(CLOCKS_PER_SEC)*60*60;
  static clock_t last_save_time = 0;

  static int iterations = 0;
  static int how_often = 1;
  // clock can be expensive under fac, so this is a heuristic to
  // reduce our use of it.
  if (++iterations % how_often == 0) {
    const clock_t time_now = clock();
    if(time_now-last_save_time > output_period){

      if (output_period < max_output_period/2) output_period *= 2;
      else if (output_period < max_output_period)
        output_period = max_output_period;

      how_often = 1+ iterations/3; // our simple heuristic
      last_save_time = time_now;
      iterations = 0;
      // flushing occasionally will be no problem and can be helpful
      // if we forget.
      fflush(stdout);
      return true;
    }
  }
  return false;
}
コード例 #4
0
    uint32 MarkedDelegateQueue::callDelegates()
    {
        clock_t nowTime = clock();
        uint32 num = 0;

        for (DelegateQueue::iterator iter = m_delegates.begin();
            iter != m_delegates.end();
            )
        {
            DelegateQueueItem &item = iter->second;
            if (iter->second.isMarked || nowTime - item.enterTime > clock_t(m_expireMillSeconds))
            {
                if (iter->second.isMarked)
                {
                    iter->second.d();
                    ++num;
                }

                iter = m_delegates.erase(iter);
            }
            else
            {
                break;
            }
        }

        return num;
    }
コード例 #5
0
void sleep(int seconds)
// WINDOWS sleep
{
	clock_t endwait;
	endwait = clock_t(clock() + seconds * CLOCKS_PER_SEC);
	while (clock() < endwait) {}
}
コード例 #6
0
ファイル: Wrkf1.cpp プロジェクト: cran/subselect
bool  Forward_DepthF_Search(vind frwind0,vind fvind,vind lvind,vind nvfrwd)  
{
	vind nv,minnv,maxnv,minnvfrd,maxnvfrd;
	vind t,frwind(frwind0);
	real maxstcrt(NOBND);
	subsetdata* prvdatapt;

	if (lvind-fvind > 10) {
		newtime = clock();
		if (newtime==clock_t(-1))  {
			msg("Eleaps error: time overflow\n");
			return false;
		}
		rtime -= static_cast<double>(newtime-ctime);
		if (rtime < 0.) return false;  // Exit if time limit was exceded
		ctime = newtime; 
	} 

//  Find maximal subset dimensionalities of current tree branches
	
	if ( (maxnvfrd=nvfrwd+lvind-fvind+1) > maxdim) maxnvfrd = maxdim;

//  Start pivoting variables 

	{ for (vind u=fvind;u<=lvind;u++)  {

		t = lvind-u; 

//		Set number of variables in the susbset where the current pivot will be performed
		nv = minnvfrd = nvfrwd+u-fvind+1;

		if (maxnvfrd >= mindim && minnvfrd <= maxdim)  {

//			Make a pivot	
			if (minnvfrd < mindim) pivot(SW,SRC,frwind,t,nv,u,t,mindim,maxnvfrd,false);
			else if (minnvfrd < maxdim) pivot(SW,SRC,frwind,t,nv,u,t,minnvfrd,maxnvfrd,false);
				 else pivot(SW,SRC,frwind,0,nv,u,t,minnvfrd,maxnvfrd,false);
		}
		if (t > 0) {	//	Keep track of source memory for current forward search results
			prvks[t-1] = frwind; 
			frwind = t;	// Update memory index 
		}
	} }

//  Process recursevly the subtrees created by the previous cycle

	{ for (vind i=0;i<lvind-fvind;i++)   {
		minnv = nvfrwd+lvind-fvind-i;
		maxnv = nvfrwd+lvind-fvind;

		if (minnv <= maxdim && maxnv >= mindim) 
	 		if (!Forward_DepthF_Search(prvks[i],lvind-i,lvind,minnv-1)) return false;
	} }

	return true;
}
コード例 #7
0
ファイル: process_clock.hpp プロジェクト: AsgeirSH/Client
    void process_clock::now( process_times & times_, system::error_code & ec ) {

        tms tm;
        clock_t c = ::times( &tm );
        if ( c == clock_t(-1) ) // error
        {
            if (BOOST_CHRONO_IS_THROWS(ec))
            {
                boost::throw_exception(
                        system::system_error( 
                                errno, 
                                BOOST_CHRONO_SYSTEM_CATEGORY, 
                                "chrono::process_clock" ));
            }
            else
            {
                ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY );
                times_.real = times_.system = times_.user = nanoseconds(-1);
            }
        }
        else
        {
            times_.real = microseconds(c);
            times_.system = microseconds(tm.tms_stime + tm.tms_cstime);
            times_.user = microseconds(tm.tms_utime + tm.tms_cutime);
            if ( chrono_detail::tick_factor() != -1 )
            {
                if (!BOOST_CHRONO_IS_THROWS(ec)) 
                {
                  ec.clear();
                }
                times_.real *= chrono_detail::tick_factor();
                times_.user *= chrono_detail::tick_factor();
                times_.system *= chrono_detail::tick_factor();
            }
            else
            {
                if (BOOST_CHRONO_IS_THROWS(ec))
                {
                    boost::throw_exception(
                            system::system_error( 
                                    errno, 
                                    BOOST_CHRONO_SYSTEM_CATEGORY, 
                                    "chrono::process_clock" ));
                }
                else
                {
                    ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY );
                    times_.real = times_.user = times_.system = nanoseconds(-1);
                }
            }
        }

    }
コード例 #8
0
ファイル: process_cpu_clocks.hpp プロジェクト: AVCProject/AVC
process_cpu_clock::time_point process_cpu_clock::now( 
        system::error_code & ec ) 
{
    
    
    tms tm;
    clock_t c = ::times( &tm );
    if ( c == clock_t(-1) ) // error
    {
        if (BOOST_CHRONO_IS_THROWS(ec))
        {
            boost::throw_exception(
                    system::system_error( 
                            errno, 
                            BOOST_CHRONO_SYSTEM_CATEGORY, 
                            "chrono::process_clock" ));
        }
        else
        {
            ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY );
            return time_point();
        }
    }
    else
    {
        if ( chrono_detail::tick_factor() != -1 )
        {
            time_point::rep r(
                    c*chrono_detail::tick_factor(), 
                    (tm.tms_utime + tm.tms_cutime)*chrono_detail::tick_factor(), 
                    (tm.tms_stime + tm.tms_cstime)*chrono_detail::tick_factor());
            return time_point(duration(r));
        }
        else
        {
            if (BOOST_CHRONO_IS_THROWS(ec))
            {
                boost::throw_exception(
                        system::system_error( 
                                errno, 
                                BOOST_CHRONO_SYSTEM_CATEGORY, 
                                "chrono::process_clock" ));
            }
            else
            {
                ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY );
                return time_point();
            }
        }
    }
    
}
コード例 #9
0
void LLWLAnimator::startInterpolation(const LLSD& targetWater)
{
	mInterpBeginWL->setAll(LLWLParamManager::getInstance()->mCurParams.getAll());
	mInterpBeginWater->setAll(LLWaterParamManager::getInstance()->mCurParams.getAll());
	
	mInterpStartTime = clock();
	mInterpEndTime = mInterpStartTime + clock_t(INTERP_TOTAL_SECONDS) * CLOCKS_PER_SEC;

	// Don't set any ending WL -- this is continuously calculated as the animator updates since it's a moving target
	mInterpEndWater->setAll(targetWater);

	mIsInterpolating = true;
}
コード例 #10
0
ファイル: process_cpu_clocks.hpp プロジェクト: AVCProject/AVC
process_real_cpu_clock::time_point process_real_cpu_clock::now(
        system::error_code & ec) 
{
    
    tms tm;
    clock_t c = ::times( &tm );
    if ( c == clock_t(-1) ) // error
    {
        if (BOOST_CHRONO_IS_THROWS(ec))
        {
            boost::throw_exception(
                    system::system_error( 
                            errno, 
                            BOOST_CHRONO_SYSTEM_CATEGORY, 
                            "chrono::process_real_cpu_clock" ));
        }
        else
        {
            ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY );
            return time_point();
        }
    }
    else
    {
        if ( chrono_detail::tick_factor() != -1 )
        {
            if (!BOOST_CHRONO_IS_THROWS(ec)) 
            {
                ec.clear();
            }
            return time_point(
                    microseconds(c)*chrono_detail::tick_factor());
        }
        else
        {
            if (BOOST_CHRONO_IS_THROWS(ec))
            {
                boost::throw_exception(
                        system::system_error( 
                                errno, 
                                BOOST_CHRONO_SYSTEM_CATEGORY, 
                                "chrono::process_real_cpu_clock" ));
            }
            else
            {
                ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY );
                return time_point();
            }
        }
    }
}
コード例 #11
0
ファイル: MeikaiC7-3.c プロジェクト: rz6iox/C-Programming
int main(void){
	int i,j,x,no,stage;
	int dgt[9] = {1,2,3,4,5,6,7,8,9,};
	int a[8];
	double jikan;
	clock_t start,end;

	srand(time(NULL));

	printf("欠けている数字を入力してください。\n");

	start = clock_t();

	for(stage=0 ; stage<MAX_STAGE ; stage++){
		x = rand()%9;

		i=j=0;

		while(i<9){
			if(i != x)
				a[j++] = dgt[i];
			i++
		}

		for(i=0;i<8;i++)
			printf("%d ",a[i]);
		printf(":");

		do{
			scanf("%d",&no);
		}while(no != dgt[x]);

	}

	end = clock();
	jikan = (double)(end - start)/(CLOCK_PER_SEC);

	printf("%.1f秒掛かりました。\n",jikan );

	if(jikan > 25.0)
		printf("鈍すぎます\n");
	else if(jikan > 20.0)
		printf("少し鈍い\n");
	else if(jikan > 17.0)
		printf("まあまあ\n");
	else
		printf("素早い!!\n");

	 return(0);
}
コード例 #12
0
process_cpu_clock::time_point process_cpu_clock::now(
        system::error_code & ec )
{
    tms tm;
    clock_t c = ::times( &tm );
    if ( c == clock_t(-1) ) // error
    {
        if (::boost::chrono::is_throws(ec))
        {
            boost::throw_exception(
                    system::system_error(
                            errno,
                            ::boost::system::system_category(),
                            "chrono::process_clock" ));
        }
        else
        {
            ec.assign( errno, ::boost::system::system_category() );
            return time_point();
        }
    }
    else
    {
        if ( chrono_detail::tick_factor() != -1 )
        {
            time_point::rep r(
                c*chrono_detail::tick_factor(),
                (tm.tms_utime + tm.tms_cutime)*chrono_detail::tick_factor(),
                (tm.tms_stime + tm.tms_cstime)*chrono_detail::tick_factor());
            return time_point(duration(r));
        }
        else
        {
            if (::boost::chrono::is_throws(ec))
            {
                boost::throw_exception(
                        system::system_error(
                                errno,
                                ::boost::system::system_category(),
                                "chrono::process_clock" ));
            }
            else
            {
                ec.assign( errno, ::boost::system::system_category() );
                return time_point();
            }
        }
    }

}
コード例 #13
0
ファイル: llwlanimator.cpp プロジェクト: gabeharms/firestorm
void LLWLAnimator::startInterpolation(const LLSD& targetWater)
{
	mInterpBeginWL->setAll(LLWLParamManager::getInstance()->mCurParams.getAll());
	mInterpBeginWater->setAll(LLWaterParamManager::getInstance()->mCurParams.getAll());
	
	mInterpStartTime = clock();
	// <FS:Ansariel> Custom Windlight interpolate time
	//mInterpEndTime = mInterpStartTime + clock_t(INTERP_TOTAL_SECONDS) * CLOCKS_PER_SEC;
	mInterpEndTime = mInterpStartTime + clock_t((F64)gSavedSettings.getF32("FSWindlightInterpolateTime")) * CLOCKS_PER_SEC;

	// Don't set any ending WL -- this is continuously calculated as the animator updates since it's a moving target
	mInterpEndWater->setAll(targetWater);

	mIsInterpolating = true;
}
コード例 #14
0
ファイル: Wrkf1.cpp プロジェクト: cran/subselect
bool Forward_BreadthF_Search(vind frwind0,vind fvind,vind lvind,vind nvfrwd)
{
	vind nv,t,maxnv;  

	if (lvind-fvind > 10) {
		newtime = clock();
		if (newtime==clock_t(-1))  {
			msg("Eleaps error: time overflow\n");
			return false;
		}
		rtime -= static_cast<double>(newtime-ctime);
		if (rtime < 0.) return false;  // Exit if time limit was exceded
		ctime = newtime; 
	} 

//  Find maximal subset dimensionaly of current tree branch
	
	if ( (maxnv=nvfrwd+lvind-fvind+1) > maxdim) maxnv = maxdim;

//  Get number of variables in the susbset where the current pivot will be performed
	nv = nvfrwd + 1;

	if (maxnv < mindim || nv > maxdim)  return true; 

//  Start pivoting variables

	{ for (vind u=fvind;u<=lvind;u++)  {
		t = lvind-u; 
		if (nv < mindim) pivot(SW,SRC,frwind0,t,nv,u,t,mindim,lvind,false);
		else pivot(SW,SRC,frwind0,t,nv,u,t,nv,lvind,false);
	} }

//  Process recursevly the subtrees created by the previous cycle

	for (vind i=1;i<=lvind-fvind;i++)   if  ( !(SW->subsetat(i).getdata().nopivot()) )  
		if (!Forward_BreadthF_Search(i,lvind-i+1,lvind,nvfrwd+1)) return false;
	return true;
}
コード例 #15
0
ファイル: process_cpu_clocks.hpp プロジェクト: AsherBond/PDAL
 process_system_cpu_clock::time_point process_system_cpu_clock::now(system::error_code & ec)
 {
   tms tm;
   clock_t c = ::times(&tm);
   if (c == clock_t(-1)) // error
   {
     if (BOOST_CHRONO_IS_THROWS(ec))
     {
       pdalboost::throw_exception(system::system_error(errno, BOOST_CHRONO_SYSTEM_CATEGORY, "chrono::process_system_cpu_clock"));
     } else
     {
       ec.assign(errno, BOOST_CHRONO_SYSTEM_CATEGORY);
       return time_point();
     }
   } else
   {
     long factor = chrono_detail::tick_factor();
     if (factor != -1)
     {
       if (!BOOST_CHRONO_IS_THROWS(ec))
       {
         ec.clear();
       }
       return time_point(nanoseconds((tm.tms_stime + tm.tms_cstime) * factor));
     } else
     {
       if (BOOST_CHRONO_IS_THROWS(ec))
       {
         pdalboost::throw_exception(system::system_error(errno, BOOST_CHRONO_SYSTEM_CATEGORY, "chrono::process_system_cpu_clock"));
       } else
       {
         ec.assign(errno, BOOST_CHRONO_SYSTEM_CATEGORY);
         return time_point();
       }
     }
   }
 }
コード例 #16
0
ファイル: ActiveSessions.cpp プロジェクト: 0anion0/IBN
//Terminate
DWORD CActiveSessions::Terminate(DWORD dwTime)
{

	if(_thread <= 0)
		return S_OK;

	SetEvent(_hEventExit);

	DWORD TimeExit = WaitForSingleObject(_hExitTimerEvent, dwTime);

	switch(TimeExit)
	{
	case WAIT_OBJECT_0:
		// Ol OK ...
		break;
	case WAIT_TIMEOUT:
		/// Thread can'not Del ...
		//ASSERT(FALSE);
		break;
	default :
		//ASSERT(FALSE);
		break;
	}
	CloseHandle (reinterpret_cast<HANDLE>(_thread));
	_thread = 0;

	clock_t finish;
	finish = clock() + clock_t(dwTime);

	try
	{
		if(finish > clock())
		{
			/// Закрыть ...
			MYPOSITION pos;
			if(_matrix.GetStartPosition(pos))
			{
				long id;
				TCHAR sid[COFSMatrix::_sidSize];
				CActiveSession* pActiveSession = NULL;
				_matrix.GetNextAssoc(pos, id, sid, COFSMatrix::_sidSize, pActiveSession);
				while(pActiveSession && finish>clock())
				{
					ASSERT(pActiveSession != NULL);
					pActiveSession->CloseSession(); 
					pActiveSession->ReleasePointer();
					_matrix.GetNextAssoc(pos, id, sid, COFSMatrix::_sidSize, pActiveSession);
				}
			}
		}
		//// Подождать когда все закроются ...
		while (finish>clock())
		{
			long id;
			TCHAR sid[COFSMatrix::_sidSize];
			CActiveSession* pActiveSession = NULL;
			MYPOSITION pos;

			while(finish > clock())
			{
				BOOL bExit = TRUE;
				_matrix.GetNextAssoc(pos, id, sid, COFSMatrix::_sidSize, pActiveSession);
				while(pActiveSession && finish > clock())
				{
					if(!pActiveSession->IsClosed()) 
						bExit = FALSE;
					pActiveSession->ReleasePointer();
					_matrix.GetNextAssoc(pos, id, sid, COFSMatrix::_sidSize, pActiveSession);
				}

				if(bExit)
					break;

				Sleep(1);
			}
		}
	}
	catch(...)
	{
		ASSERT(FALSE);
	}

	try
	{
		//// Просто убить ...
		MYPOSITION pos;
		if(_matrix.GetStartPosition(pos))
		{
			long id;
			TCHAR sid[COFSMatrix::_sidSize];
			CActiveSession* pActiveSession = NULL;
			_matrix.GetNextAssoc(pos, id, sid, COFSMatrix::_sidSize, pActiveSession);

			while(pActiveSession)
			{
				ASSERT(pActiveSession != NULL);
				if(!pActiveSession->IsClosed())
					pActiveSession->UpdateConnection(NULL, FALSE);
				pActiveSession->ReleasePointer();
				_matrix.Remove(id);
				_matrix.GetNextAssoc(pos, id, sid, COFSMatrix::_sidSize, pActiveSession);
			}
		}
	}
	catch(...)
	{
		ASSERT(FALSE);
	}

	return (finish>clock())?TRUE:FALSE;
}
コード例 #17
0
int main(int argc, char *argv[]){
  if (argc != 5) {
    printf("usage:  %s packing-fraction uncertainty_goal dr filename\n", argv[0]);
    return 1;
  }
  const char *outfilename = argv[4];
  const double packing_fraction = atof(argv[1]);
  const double mean_density = packing_fraction/(4*M_PI/3*R*R*R);
  const long N = (mean_density*lenx*leny*lenz - 1) + 0.5;
  printf("density %g, packing fraction %g gives N %ld\n", mean_density, packing_fraction, N);
  fflush(stdout);
  const double dr = atof(argv[3]);
  Vector3d *spheres = new Vector3d[N];

  //////////////////////////////////////////////////////////////////////////////////////////
  // We start with randomly-placed spheres, and then gradually wiggle
  // them around until they are all within bounds and are not
  // overlapping.  We do this by creating an "overlap" value which we
  // constrain to never increase.  Note that this may not work at all
  // for high filling fractions, since we could get stuck in a local
  // minimum.
  for(long i=0; i<N; i++) {
    spheres[i]=10*lenx*ran3();
  }
  clock_t start = clock();
  long num_to_time = 100*N;
  long num_timed = 0;
  long i = 0;
  double scale = .005;

  // At this stage, we'll set up our output grid...
  long div = long((lenx/2 - innerRad)/dr);
  if (div < 10) div = 10;
  printf("Using %ld divisions, dx ~ %g\n", div, (lenx/2 - innerRad)/div);

  double *radius = new double[div+1];
  for (long i=0;i<div+1;i++) radius[i] = innerRad + (lenx/2 - innerRad)*double(i)/div;

  const double uncertainty_goal = atof(argv[2]);
  const double minvolume = M_PI*(radius[1]*radius[1]*radius[1] - innerRad*innerRad*innerRad)/2;
  const double num_in_min_volume = minvolume*N/lenx/leny/lenz;
  const long iterations = 2.0/uncertainty_goal/uncertainty_goal/num_in_min_volume;
  printf("running with %ld spheres for %ld iterations.\n", N, iterations);
  fflush(stdout);


  // Let's move each sphere once, so they'll all start within our
  // periodic cell!
  for (i=0;i<N;i++) spheres[i] = move(spheres[i], scale);

  clock_t starting_initial_state = clock();
  printf("Initial countOverLaps is %g\n", countOverLaps(spheres, N, R));
  while (countOverLaps(spheres, N, R)>0){
    for (int movethis=0;movethis < 100*N; movethis++) {
      if (num_timed++ > num_to_time) {
        clock_t now = clock();
        //printf("took %g seconds per initialising iteration\n",
        //       (now - double(start))/CLOCKS_PER_SEC/num_to_time);
        num_timed = 0;
        start = now;
      }
      Vector3d old =spheres[i%N];
      double oldoverlap = countOneOverLap(spheres, N, i%N, R);
      spheres[i%N]=move(spheres[i%N],scale);
      double newoverlap = countOneOverLap(spheres, N, i%N, R);
      if(newoverlap>oldoverlap){
        spheres[i%N]=old;
      }
      i++;
      if (i%(100*N) == 0) {
        if (i>iterations/4) {
          for(long i=0; i<N; i++) {
            printf("%g\t%g\t%g\n", spheres[i][0],spheres[i][1],spheres[i][2]);
          }
          printf("couldn't find good state\n");
          exit(1);
        }
        char *debugname = new char[10000];
        sprintf(debugname, "%s.debug", outfilename);
        FILE *spheredebug = fopen(debugname, "w");
        for(long i=0; i<N; i++) {
          fprintf(spheredebug, "%g\t%g\t%g\n", spheres[i][0],spheres[i][1],spheres[i][2]);
        }
        fclose(spheredebug);
        printf("numOverLaps=%g (debug file: %s)\n",countOverLaps(spheres,N,R), debugname);
        delete[] debugname;
        fflush(stdout);
      }
    }
  }
  assert(countOverLaps(spheres, N, R) == 0);
  {
    clock_t now = clock();
    //printf("took %g seconds per initialising iteration\n",
    //       (now - double(start))/CLOCKS_PER_SEC/num_to_time);
    printf("\nFound initial state in %g days!\n", (now - double(starting_initial_state))/CLOCKS_PER_SEC/60.0/60.0/24.0);
  }

  // Here we use a hokey heuristic to decide on an average move
  // distance, which is proportional to the mean distance between
  // spheres.
  const double mean_spacing = pow(lenx*leny*lenz/N, 1.0/3);
  if (mean_spacing > 2*R) {
    scale = 2*(mean_spacing - 2*R);
  } else {
    scale = 0.1;
  }
  printf("Using scale of %g\n", scale);
  long count = 0;
  long *shells = new long[div];
  for (long l=0; l<div; l++) shells[l] = 0;

  double *density = new double[div];

  /////////////////////////////////////////////////////////////////////////////
  num_to_time = 1000;
  start = clock();
  num_timed = 0;
  double secs_per_iteration = 0;
  long workingmoves=0;

  clock_t output_period = CLOCKS_PER_SEC*60; // start at outputting every minute
  clock_t max_output_period = clock_t(CLOCKS_PER_SEC)*60*30; // top out at half hour interval
  clock_t last_output = clock(); // when we last output data
  for (long j=0; j<iterations; j++){
	  num_timed = num_timed + 1;
    if (num_timed > num_to_time || j == iterations - 1) {
      num_timed = 0;
      ///////////////////////////////////////////start of print.dat
      const clock_t now = clock();
      secs_per_iteration = (now - double(start))/CLOCKS_PER_SEC/num_to_time;
      if (secs_per_iteration*num_to_time < 1) {
        printf("took %g microseconds per iteration\n", 1000000*secs_per_iteration);
        num_to_time *= 2;
      } else {
        // Set the number of iterations to time to a minute, so we
        // won't check *too* many times.
        num_to_time = long(60/secs_per_iteration);
      }
      start = now;
      if (now - last_output > output_period || j == iterations - 1) {
        last_output = now;
        if (output_period < max_output_period/2) {
          output_period *= 2;
        } else if (output_period < max_output_period) {
          output_period = max_output_period;
        }
        {
          double secs_done = double(now)/CLOCKS_PER_SEC;
          long mins_done = secs_done / 60;
          long hours_done = mins_done / 60;
          mins_done = mins_done % 60;
          if (hours_done > 50) {
            printf("Saved data after %ld hours\n", hours_done);
          } else if (mins_done < 1) {
            printf("Saved data after %.1f seconds\n", secs_done);
          } else if (hours_done < 1) {
            printf("Saved data after %ld minutes\n", mins_done);
          } else if (hours_done < 2) {
            printf("Saved data after one hour %ld minutes\n", mins_done);
          } else {
            printf("Saved data after %ld hours, %ld minutes\n", hours_done, mins_done);
          }
          fflush(stdout);
        }
        for(long i=0; i<div; i++){
          const double rmax = radius[i+1];
          const double rmin = radius[i];
          const double num_counted = (j+1)/double(N);
          const double dV = 4/3.*M_PI*(rmax*rmax*rmax - rmin*rmin*rmin);
          density[i]=shells[i]/dV/num_counted*(4*M_PI/3);
        }

        FILE *out = fopen((const char *)outfilename,"w");
        if (out == NULL) {
          printf("Error creating file %s\n", outfilename);
          return 1;
        }
        // We will just extrapolate to the contact point with a linear
        // extrapolation.  We could do better than this, but this
        // should be good enough once we have solid statistics.  And
        // in a pinch we could always delete this first line.
        fprintf(out, "%g\t%g\n", radius[0], 1.5*density[0] - 0.5*density[1]);
        fprintf(out, "%g\t%g\n", 0.5*(radius[0]+radius[1]), density[0]);
        long divtoprint = div;
        divtoprint = div - 1;
        for(long i=1; i<divtoprint; i++){
          fprintf(out, "%g\t%g\n", 0.5*(radius[i]+radius[i+1]), density[i]);
        }
        fflush(stdout);
        fclose(out);
      }
      ///////////////////////////////////////////end of print.dat
    }
	
    // only write out the sphere positions after they've all had a
    // chance to move
    if (workingmoves%N == 0) {
      for (long i=0;i<N;i++) {
        //printf("Sphere at %.1f %.1f %.1f\n", spheres[i][0], spheres[i][1], spheres[i][2]);
        shells[shell(spheres[i], div, radius)]++;
      }
    }
    if(j % (iterations/100)==0 && j != 0){
      double secs_to_go = secs_per_iteration*(iterations - j);
      long mins_to_go = secs_to_go / 60;
      long hours_to_go = mins_to_go / 60;
      mins_to_go = mins_to_go % 60;
      if (hours_to_go > 5) {
        printf("%.0f%% complete... (%ld hours to go)\n",j/(iterations*1.0)*100, hours_to_go);
      } else if (mins_to_go < 1) {
        printf("%.0f%% complete... (%.1f seconds to go)\n",j/(iterations*1.0)*100, secs_to_go);
      } else if (hours_to_go < 1) {
        printf("%.0f%% complete... (%ld minutes to go)\n",j/(iterations*1.0)*100, mins_to_go);
      } else if (hours_to_go < 2) {
        printf("%.0f%% complete... (1 hour, %ld minutes to go)\n",j/(iterations*1.0)*100, mins_to_go);
      } else {
        printf("%.0f%% complete... (%ld hours, %ld minutes to go)\n",j/(iterations*1.0)*100, hours_to_go, mins_to_go);
      }
      char *debugname = new char[10000];
      sprintf(debugname, "%s.debug", outfilename);
      FILE *spheredebug = fopen(debugname, "w");
      for(long i=0; i<N; i++) {
        fprintf(spheredebug, "%g\t%g\t%g\n", spheres[i][0],spheres[i][1],spheres[i][2]);
      }
      fclose(spheredebug);
      delete[] debugname;
      fflush(stdout);
    }
    Vector3d temp = move(spheres[j%N],scale);
    count++;
    if(!overlap(spheres, temp, N, R, j%N)){
      spheres[j%N] = temp;
      workingmoves++;
    }
  }

  //////////////////////////////////////////////////////////////////////////////////////////

  printf("Total number of attempted moves = %ld\n",count);
  printf("Total number of successful moves = %ld\n",workingmoves);
  printf("Acceptance rate = %g\n", workingmoves/double(count));
  fflush(stdout);
  delete[] shells;
  delete[] density;
  delete[] spheres;
}
コード例 #18
0
		return;
	}

	LLEnvManagerNew::getInstance()->onRegionSettingsResponse(unvalidated_content);
}
/*virtual*/ void LLEnvironmentRequestResponder::error(U32 status, const std::string& reason)
{
	LL_INFOS("WindlightCaps") << "Got an error, not using region windlight..." << LL_ENDL;
	LLEnvManagerNew::getInstance()->onRegionSettingsResponse(LLSD());
}

/****
 * LLEnvironmentApply
 ****/

clock_t LLEnvironmentApply::UPDATE_WAIT_SECONDS = clock_t(3.f);
clock_t LLEnvironmentApply::sLastUpdate = clock_t(0.f);

// static
bool LLEnvironmentApply::initiateRequest(const LLSD& content)
{
	clock_t current = clock();

	// Make sure we don't update too frequently.
	if (current < sLastUpdate + (UPDATE_WAIT_SECONDS * CLOCKS_PER_SEC))
	{
		LLSD args(LLSD::emptyMap());
		args["WAIT"] = (F64)UPDATE_WAIT_SECONDS;
		LLNotifications::instance().add("EnvUpdateRate", args);
		return false;
	}
コード例 #19
0
ファイル: Wrkf1.cpp プロジェクト: cran/subselect
bool Rev_Leaps_Search(vind frwind0,vind bckind0,vind fvind,vind lvind,vind nvfrwd,vind nvbckwrd)
{
	vind prvbckind,bckind(bckind0);  
	vind nv,t,minnv,maxnv,minnvfrd,minnvbkrd,maxnvfrd,maxnvbkrd;  
	real maxstcrt(NOBND);
	const real*	icrtcmpll; 	
// pointer to list with individual criterion components for sums of quadratic form
// criteria with as many parcels as variables in each subset
	subsetdata* prvdatapt;

	if (lvind-fvind > 10) {
		newtime = clock();
		if (newtime==clock_t(-1))  {
			msg("Eleaps error: time overflow\n");
			return false;
		}
		rtime -= static_cast<double>(newtime-ctime);
		if (rtime < 0.) return false;  // Exit if time limit was exceded
		ctime = newtime; 
	} 

//  Find minimal subset dimensionalities of current tree branches
	
	if ( (minnvbkrd=nvbckwrd-frwind0) < mindim) minnvbkrd = mindim;
	minnvfrd = nvfrwd+1;

//  Start pivoting variables

	{ for (vind u=fvind;u<lvind;u++)  {

		t = lvind-u-1; 

//		Get number of variables in the susbset where the current forward pivot will be performed
		nv = nvfrwd + 1;
		if ( (maxnvfrd=nvfrwd+frwind0+fvind-i) > maxdim) maxnvfrd = maxdim;
		if (maxnvfrd >= mindim && minnvfrd <= maxdim)

//			Make a forward pivot 				
			if (minnvfrd < mindim) pivot(SW,SRC,frwind0,t,nv,u,t,mindim,lvind,false);
			else if (minnvfrd < maxdim) pivot(SW,SRC,frwind0,t,nv,u,t,minnvfrd,lvind,false);
				 else pivot(SW,SRC,frwind0,0,nv,u,t,minnvfrd,lvind,false);

//		Get number of variables in the susbset where the current backward pivot will be performed
		nv = maxnvbkrd = nvbckwrd-1+fvind-u;
		if (maxnvbkrd >= mindim && minnvbkrd <= maxdim) {

//			Make a backward pivot 				
			if (maxnvbkrd > maxdim) pivot(IW,INV,bckind,t,nv,u,t,minnvbkrd,maxdim,false);
			else if (maxnvbkrd > mindim) pivot(IW,INV,bckind,t,nv,u,t,minnvbkrd,maxnvbkrd,false);
				 else pivot(IW,INV,bckind,0,nv,u,t,minnvbkrd,maxnvbkrd,false);
		}

		if (t > 0) {	//	Keep track of source memory for current backward search results
				prvks[t-1] = bckind; 
				bckind = t;	// Update memory index for forward search
		}
	} }

//  Process recursevly the subtrees created by the previous cycle

	{ for (vind i=1;i<lvind-fvind;i++)   {
		minnv = nvfrwd+2;
		maxnv = nvfrwd+i+1;
		if (minnv <= maxdim && maxnv >= mindim) {
			if (minnv < mindim) minnv = mindim;
			if (maxnv > maxdim) maxnv = maxdim;
			if (minnv > maxnv) minnv = maxnv;
			prvdatapt = &IW->subsetat((prvbckind=prvks[i-1])+1).getdata();
			if  ( !prvdatapt->nopivot() ) {
				maxstcrt = prvdatapt->criterion();	// Get criterion for maximal subset in the next subtree
				icrtcmpll = prvdatapt->getsqfparcels();
				if (!leap(pcrttp,maxstcrt,icrtcmpll,minnv,maxnv) ) // test if maxstcrt is better than current bounds
					if (!Rev_Leaps_Search(i,prvks[i-1],lvind-i,lvind,nvfrwd+1,nvbckwrd-frwind0+i+1)) return false;
			}
		}
	} }

	return true;
}
コード例 #20
0
void Wait(float seconds)
{
	clock_t endWait;
	endWait = clock_t(clock () + seconds * CLOCKS_PER_SEC);
	while (clock() < endWait) {}
}
コード例 #21
0
ファイル: stop_watch.hpp プロジェクト: dmarce1/FVFMM
	stop_watch() {
		t = clock_t(0);
		on = false;
	}
コード例 #22
0
int main(int argc, const char *argv[]) {
  took("Starting program");
  // ----------------------------------------------------------------------------
  // Define "Constants" -- set from arguments then unchanged
  // ----------------------------------------------------------------------------

  // NOTE: debug can slow things down VERY much
  int debug = false;
  int test_weights = false;
  int print_weights = false;

  int no_weights = false;
  double fix_kT = 0;
  int flat_histogram = false;
  int gaussian_fit = false;
  int walker_weights = false;
  int wang_landau = false;

  double wl_factor = 0.125;
  double wl_fmod = 2;
  double wl_threshold = 0.1;
  double wl_cutoff = 1e-6;

  sw_simulation sw;

  sw.len[0] = sw.len[1] = sw.len[2] = 1;

  sw.walls = 0;
  int wall_dim = 1;
  unsigned long int seed = 0;

  char *dir = new char[1024];
  sprintf(dir, "papers/square-well-liquid/data");
  char *filename = new char[1024];
  sprintf(filename, "default_filename");
  sw.N = 1000;
  long iterations = 2500000;
  long initialization_iterations = 500000;
  double acceptance_goal = .4;
  double R = 1;
  double well_width = 1.3;
  double ff = 0.3;
  double neighbor_scale = 2;
  sw.dr = 0.1;
  double de_density = 0.1;
  double de_g = 0.05;
  double max_rdf_radius = 10;
  int totime = 0;
  // scale is not a quite "constant" -- it is adjusted during the initialization
  //  so that we have a reasonable acceptance rate
  double translation_scale = 0.05;

  poptContext optCon;
  // ----------------------------------------------------------------------------
  // Set values from parameters
  // ----------------------------------------------------------------------------
  poptOption optionsTable[] = {
    {"N", '\0', POPT_ARG_INT, &sw.N, 0, "Number of balls to simulate", "INT"},
    {"ww", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT, &well_width, 0,
     "Ratio of square well width to ball diameter", "DOUBLE"},
    {"ff", '\0', POPT_ARG_DOUBLE, &ff, 0, "Filling fraction. If specified, the "
     "cell dimensions are adjusted accordingly without changing the shape of "
     "the cell"},
    {"walls", '\0', POPT_ARG_INT | POPT_ARGFLAG_SHOW_DEFAULT, &sw.walls, 0,
     "Number of walled dimensions (dimension order: x,y,z)", "INT"},
    {"initialize", '\0', POPT_ARG_LONG | POPT_ARGFLAG_SHOW_DEFAULT,
     &initialization_iterations, 0,
     "Number of iterations to run for initialization", "INT"},
    {"iterations", '\0', POPT_ARG_LONG | POPT_ARGFLAG_SHOW_DEFAULT, &iterations,
     0, "Number of iterations to run for", "INT"},
    {"de_g", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT, &de_g, 0,
     "Resolution of distribution functions", "DOUBLE"},
    {"dr", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT, &sw.dr, 0,
     "Differential radius change used in pressure calculation", "DOUBLE"},
    {"de_density", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT,
     &de_density, 0, "Resolution of density file", "DOUBLE"},
    {"max_rdf_radius", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT,
     &max_rdf_radius, 0, "Set maximum radius for RDF data collection", "DOUBLE"},
    {"lenx", '\0', POPT_ARG_DOUBLE, &sw.len[x], 0,
     "Relative cell size in x dimension", "DOUBLE"},
    {"leny", '\0', POPT_ARG_DOUBLE, &sw.len[y], 0,
     "Relative cell size in y dimension", "DOUBLE"},
    {"lenz", '\0', POPT_ARG_DOUBLE, &sw.len[z], 0,
     "Relative cell size in z dimension", "DOUBLE"},
    {"filename", '\0', POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &filename, 0,
     "Base of output file names", "STRING"},
    {"dir", '\0', POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &dir, 0,
     "Save directory", "dir"},
    {"neighbor_scale", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT,
     &neighbor_scale, 0, "Ratio of neighbor sphere radius to interaction scale "
     "times ball radius. Drastically reduces collision detections","DOUBLE"},
    {"translation_scale", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT,
     &translation_scale, 0, "Standard deviation for translations of balls, "
     "relative to ball radius", "DOUBLE"},
    {"seed", '\0', POPT_ARG_INT | POPT_ARGFLAG_SHOW_DEFAULT, &seed, 0,
     "Seed for the random number generator", "INT"},
    {"acceptance_goal", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT,
     &acceptance_goal, 0, "Goal to set the acceptance rate", "DOUBLE"},
    {"nw", '\0', POPT_ARG_NONE, &no_weights, 0, "Don't use weighing method "
     "to get better statistics on low entropy states", "BOOLEAN"},
    {"kT", '\0', POPT_ARG_DOUBLE, &fix_kT, 0, "Use a fixed temperature of kT"
     " rather than adjusted weights", "DOUBLE"},
    {"flat", '\0', POPT_ARG_NONE, &flat_histogram, 0,
     "Use a flat histogram method", "BOOLEAN"},
    {"gaussian", '\0', POPT_ARG_NONE, &gaussian_fit, 0,
     "Use gaussian weights for flat histogram", "BOOLEAN"},
    {"walkers", '\0', POPT_ARG_NONE, &walker_weights, 0,
     "Use a walker optimization weight histogram method", "BOOLEAN"},
    {"wang_landau", '\0', POPT_ARG_NONE, &wang_landau, 0,
     "Use Wang-Landau histogram method", "BOOLEAN"},
    {"wl_factor", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT, &wl_factor,
     0, "Initial value of Wang-Landau factor", "DOUBLE"},
    {"wl_fmod", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT, &wl_fmod, 0,
     "Wang-Landau factor modifiction parameter", "DOUBLE"},
    {"wl_threshold", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT,
     &wl_threshold, 0, "Threhold for normalized standard deviation in "
     "energy histogram at which to adjust Wang-Landau factor", "DOUBLE"},
    {"wl_cutoff", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT,
     &wl_cutoff, 0, "Cutoff for Wang-Landau factor", "DOUBLE"},
    {"time", '\0', POPT_ARG_INT, &totime, 0,
     "Timing of display information (seconds)", "INT"},
    {"R", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT,
     &R, 0, "Ball radius (for testing purposes; should always be 1)", "DOUBLE"},
    {"test_weights", '\0', POPT_ARG_NONE, &test_weights, 0,
     "Periodically print weight histogram during initialization", "BOOLEAN"},
    {"debug", '\0', POPT_ARG_NONE, &debug, 0, "Debug mode", "BOOLEAN"},
    POPT_AUTOHELP
    POPT_TABLEEND
  };
  optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
  poptSetOtherOptionHelp(optCon, "[OPTION...]\nNumber of balls and filling "
                         "fraction or cell dimensions are required arguments.");

  int c = 0;
  // go through arguments, set them based on optionsTable
  while((c = poptGetNextOpt(optCon)) >= 0);
  if (c < -1) {
    fprintf(stderr, "\n%s: %s\n", poptBadOption(optCon, 0), poptStrerror(c));
    return 1;
  }
  poptFreeContext(optCon);

  // ----------------------------------------------------------------------------
  // Verify we have reasonable arguments and set secondary parameters
  // ----------------------------------------------------------------------------

  // check that only one method is used
  if(bool(no_weights) + bool(flat_histogram) + bool(gaussian_fit)
     + bool(wang_landau) + bool(walker_weights) + (fix_kT != 0) != 1){
    printf("Exactly one histigram method must be selected!");
    return 254;
  }

  if(sw.walls >= 2){
    printf("Code cannot currently handle walls in more than one dimension.\n");
    return 254;
  }
  if(sw.walls > 3){
    printf("You cannot have walls in more than three dimensions.\n");
    return 254;
  }
  if(well_width < 1){
    printf("Interaction scale should be greater than (or equal to) 1.\n");
    return 254;
  }

  // Adjust cell dimensions for desired filling fraction
  const double fac = R*pow(4.0/3.0*M_PI*sw.N/(ff*sw.len[x]*sw.len[y]*sw.len[z]), 1.0/3.0);
  for(int i = 0; i < 3; i++) sw.len[i] *= fac;
  printf("\nSetting cell dimensions to (%g, %g, %g).\n",
         sw.len[x], sw.len[y], sw.len[z]);
  if (sw.N <= 0 || initialization_iterations < 0 || iterations < 0 || R <= 0 ||
      neighbor_scale <= 0 || sw.dr <= 0 || translation_scale < 0 ||
      sw.len[x] < 0 || sw.len[y] < 0 || sw.len[z] < 0) {
    fprintf(stderr, "\nAll parameters must be positive.\n");
    return 1;
  }
  sw.dr *= R;

  const double eta = (double)sw.N*4.0/3.0*M_PI*R*R*R/(sw.len[x]*sw.len[y]*sw.len[z]);
  if (eta > 1) {
    fprintf(stderr, "\nYou're trying to cram too many balls into the cell. "
            "They will never fit. Filling fraction: %g\n", eta);
    return 7;
  }

  // If a filename was not selected, make a default
  if (strcmp(filename, "default_filename") == 0) {
    char *name_suffix = new char[10];
    char *wall_tag = new char[10];
    if(sw.walls == 0) sprintf(wall_tag,"periodic");
    else if(sw.walls == 1) sprintf(wall_tag,"wall");
    else if(sw.walls == 2) sprintf(wall_tag,"tube");
    else if(sw.walls == 3) sprintf(wall_tag,"box");
    if (fix_kT) {
      sprintf(name_suffix, "-kT%g", fix_kT);
    } else if (no_weights) {
      sprintf(name_suffix, "-nw");
    } else if (flat_histogram) {
      sprintf(name_suffix, "-flat");
    } else if (gaussian_fit) {
      sprintf(name_suffix, "-gaussian");
    } else if (wang_landau) {
      sprintf(name_suffix, "-wang_landau");
    } else if (walker_weights) {
      sprintf(name_suffix, "-walkers");
    } else {
      name_suffix[0] = 0; // set name_suffix to the empty string
    }
    sprintf(filename, "%s-ww%04.2f-ff%04.2f-N%i%s",
            wall_tag, well_width, eta, sw.N, name_suffix);
    printf("\nUsing default file name: ");
    delete[] name_suffix;
    delete[] wall_tag;
  }
  else
    printf("\nUsing given file name: ");
  printf("%s\n",filename);

  printf("------------------------------------------------------------------\n");
  printf("Running %s with parameters:\n", argv[0]);
  for(int i = 1; i < argc; i++) {
    if(argv[i][0] == '-') printf("\n");
    printf("%s ", argv[i]);
  }
  printf("\n");
  if (totime > 0) printf("Timing information will be displayed.\n");
  if (debug) printf("DEBUG MODE IS ENABLED!\n");
  else printf("Debug mode disabled\n");
  printf("------------------------------------------------------------------\n\n");

  // ----------------------------------------------------------------------------
  // Define sw_simulation variables
  // ----------------------------------------------------------------------------

  sw.iteration = 0; // start at zeroeth iteration
  sw.state_of_max_interactions = 0;
  sw.state_of_max_entropy = 0;

  // translation distance should scale with ball radius
  sw.translation_distance = translation_scale*R;

  // neighbor radius should scale with radius and interaction scale
  sw.neighbor_R = neighbor_scale*R*well_width;

  // Find the upper limit to the maximum number of neighbors a ball could have
  sw.max_neighbors = max_balls_within(2+neighbor_scale*well_width);

  // Energy histogram
  sw.interaction_distance = 2*R*well_width;
  sw.energy_levels = sw.N/2*max_balls_within(sw.interaction_distance);
  sw.energy_histogram = new long[sw.energy_levels]();

  // Walkers
  sw.current_walker_plus = false;
  sw.walker_plus_threshold = 0;
  sw.walker_minus_threshold = 0;
  sw.walkers_plus = new long[sw.energy_levels]();
  sw.walkers_total = new long[sw.energy_levels]();

  // Energy weights, state density
  int weight_updates = 0;
  sw.ln_energy_weights = new double[sw.energy_levels]();

  // Radial distribution function (RDF) histogram
  long *g_energy_histogram = new long[sw.energy_levels]();
  const int g_bins = round(min(min(min(sw.len[y],sw.len[z]),sw.len[x]),max_rdf_radius)
                           / de_g / 2);
  long **g_histogram = new long*[sw.energy_levels];
  for(int i = 0; i < sw.energy_levels; i++)
    g_histogram[i] = new long[g_bins]();

  // Density histogram
  const int density_bins = round(sw.len[wall_dim]/de_density);
  const double bin_volume = sw.len[x]*sw.len[y]*sw.len[z]/sw.len[wall_dim]*de_density;
  long **density_histogram = new long*[sw.energy_levels];
  for(int i = 0; i < sw.energy_levels; i++)
    density_histogram[i] = new long[density_bins]();

  printf("memory use estimate = %.2g G\n\n",
         8*double((6 + g_bins + density_bins)*sw.energy_levels)/1024/1024/1024);

  sw.balls = new ball[sw.N];

  if(totime < 0) totime = 10*sw.N;

  // a guess for the number of iterations to run for initializing the histogram
  int first_weight_update = sw.energy_levels;

  // Initialize the random number generator with our seed
  random::seed(seed);

  // ----------------------------------------------------------------------------
  // Set up the initial grid of balls
  // ----------------------------------------------------------------------------

  for(int i = 0; i < sw.N; i++) // initialize ball radii
    sw.balls[i].R = R;

  // Balls will be initially placed on a face centered cubic (fcc) grid
  // Note that the unit cells need not be actually "cubic", but the fcc grid will
  //   be stretched to cell dimensions
  const int spots_per_cell = 4; // spots in each fcc periodic unit cell
  const int cells_floor = ceil(sw.N/spots_per_cell); // minimum number of cells
  int cells[3]; // array to contain number of cells in x, y, and z dimensions
  for(int i = 0; i < 3; i++){
    cells[i] = ceil(pow(cells_floor*sw.len[i]*sw.len[i]
                        /(sw.len[(i+1)%3]*sw.len[(i+2)%3]),1.0/3.0));
  }

  // It is usefull to know our cell dimensions
  double cell_width[3];
  for(int i = 0; i < 3; i++) cell_width[i] = sw.len[i]/cells[i];

  // Increase number of cells until all balls can be accomodated
  int total_spots = spots_per_cell*cells[x]*cells[y]*cells[z];
  int i = 0;
  while(total_spots < sw.N) {
    if(cell_width[i%3] <= cell_width[(i+1)%3] &&
       cell_width[(i+1)%3] <= cell_width[(i+2)%3]) {
      cells[i%3] += 1;
      cell_width[i%3] = sw.len[i%3]/cells[i%3];
      total_spots += spots_per_cell*cells[(i+1)%3]*cells[(i+2)%3];
    }
    i++;
  }

  // Define ball positions relative to cell position
  vector3d* offset = new vector3d[4]();
  offset[x] = vector3d(0,cell_width[y],cell_width[z])/2;
  offset[y] = vector3d(cell_width[x],0,cell_width[z])/2;
  offset[z] = vector3d(cell_width[x],cell_width[y],0)/2;

  // Reserve some spots at random to be vacant
  bool *spot_reserved = new bool[total_spots]();
  int p; // Index of reserved spot
  for(int i = 0; i < total_spots-sw.N; i++) {
    p = floor(random::ran()*total_spots); // Pick a random spot index
    if(spot_reserved[p] == false) // If it's not already reserved, reserve it
      spot_reserved[p] = true;
    else // Otherwise redo this index (look for a new spot)
      i--;
  }

  // Place all balls in remaining spots
  int b = 0;
  vector3d cell_pos;
  for(int i = 0; i < cells[x]; i++) {
    for(int j = 0; j < cells[y]; j++) {
      for(int k = 0; k < cells[z]; k++) {
        for(int l = 0; l < 4; l++) {
          if(!spot_reserved[i*(4*cells[z]*cells[y])+j*(4*cells[z])+k*4+l]) {
            sw.balls[b].pos = vector3d(i*cell_width[x],j*cell_width[y],
                                    k*cell_width[z]) + offset[l];
            b++;
          }
        }
      }
    }
  }
  delete[] offset;
  delete[] spot_reserved;
  took("Placement");

  // ----------------------------------------------------------------------------
  // Print info about the initial configuration for troubleshooting
  // ----------------------------------------------------------------------------

  {
    int most_neighbors =
      initialize_neighbor_tables(sw.balls, sw.N, sw.neighbor_R + 2*sw.dr, sw.max_neighbors, sw.len,
                                 sw.walls);
    if (most_neighbors < 0) {
      fprintf(stderr, "The guess of %i max neighbors was too low. Exiting.\n",
              sw.max_neighbors);
      return 1;
    }
    printf("Neighbor tables initialized.\n");
    printf("The most neighbors is %i, whereas the max allowed is %i.\n",
           most_neighbors, sw.max_neighbors);
  }

  // ----------------------------------------------------------------------------
  // Make sure initial placement is valid
  // ----------------------------------------------------------------------------

  bool error = false, error_cell = false;
  for(int i = 0; i < sw.N; i++) {
    if (!in_cell(sw.balls[i], sw.len, sw.walls, sw.dr)) {
      error_cell = true;
      error = true;
    }
    for(int j = 0; j < i; j++) {
      if (overlap(sw.balls[i], sw.balls[j], sw.len, sw.walls)) {
        error = true;
        break;
      }
    }
    if (error) break;
  }
  if (error){
    print_bad(sw.balls, sw.N, sw.len, sw.walls);
    printf("Error in initial placement: ");
    if(error_cell) printf("balls placed outside of cell.\n");
    else printf("balls are overlapping.\n");
    return 253;
  }

  fflush(stdout);

  // ----------------------------------------------------------------------------
  // Initialization of cell
  // ----------------------------------------------------------------------------

  double avg_neighbors = 0;
  sw.interactions =
    count_all_interactions(sw.balls, sw.N, sw.interaction_distance, sw.len, sw.walls);

  // First, let us figure out what the max entropy point is.
  sw.initialize_max_entropy_and_translation_distance();

  if (gaussian_fit) {
    sw.initialize_gaussian(10);
  } else if (flat_histogram) {
    {
      sw.initialize_gaussian(log(1e40));
      const int state_of_max_entropy = sw.state_of_max_entropy;
      sw.initialize_max_entropy_and_translation_distance();
      sw.state_of_max_entropy = state_of_max_entropy;
    }
    const double scale = log(10);
    double width;
    double range;
    do {
      width = sw.initialize_gaussian(scale);
      range = sw.state_of_max_interactions - sw.state_of_max_entropy;
      // Now shift to the max entropy state...
      const int state_of_max_entropy = sw.state_of_max_entropy;
      sw.initialize_max_entropy_and_translation_distance();
      sw.state_of_max_entropy = state_of_max_entropy;
      printf("***\n");
      printf("*** Gaussian has width %.1f compared to range %.0f (ratio %.2f)\n",
             width, range, width/range);
      printf("***\n");
    } while (width < 0.25*range);
  } else if (fix_kT) {
    sw.initialize_canonical(fix_kT);
  } else if (wang_landau) {
    sw.initialize_wang_landau(wl_factor, wl_threshold, wl_cutoff);
  } else {
    for(long iteration = 1;
        iteration <= initialization_iterations + first_weight_update; iteration++) {
      // ---------------------------------------------------------------
      // Move each ball once
      // ---------------------------------------------------------------
      for(int i = 0; i < sw.N; i++) {
        move_one_ball(i, sw.balls, sw.N, sw.len, sw.walls, sw.neighbor_R, sw.translation_distance,
                      sw.interaction_distance, sw.max_neighbors, sw.dr, &sw.moves,
                      sw.interactions, sw.ln_energy_weights);
        sw.interactions += sw.moves.new_count - sw.moves.old_count;
        sw.energy_histogram[sw.interactions]++;
        
        if(walker_weights){
          sw.walkers_total[sw.interactions]++;
          if(sw.interactions >= sw.walker_minus_threshold)
            sw.current_walker_plus = false;
          else if(sw.interactions <= sw.walker_plus_threshold)
            sw.current_walker_plus = true;
          if(sw.current_walker_plus)
            sw.walkers_plus[sw.interactions]++;
        }
      }
      assert(sw.interactions ==
             count_all_interactions(sw.balls, sw.N, sw.interaction_distance, sw.len, sw.walls));
      
      // ---------------------------------------------------------------
      // Update weights
      // ---------------------------------------------------------------
      if(!(no_weights || gaussian_fit)){
        if(iteration == first_weight_update){
          flat_hist(sw.energy_histogram, sw.ln_energy_weights, sw.energy_levels);
          weight_updates++;
        } else if((flat_histogram || walker_weights)
                  && (iteration > first_weight_update)
                  && ((iteration-first_weight_update)
                      % int(first_weight_update*uipow(2,weight_updates)) == 0)){
          printf("Weight update: %d.\n", int(uipow(2,weight_updates)));
          if (flat_histogram)
            flat_hist(sw.energy_histogram, sw.ln_energy_weights, sw.energy_levels);
          else if(walker_weights){
            walker_hist(sw.energy_histogram, sw.ln_energy_weights, sw.energy_levels,
                        sw.walkers_plus, sw.walkers_total, &sw.moves);
          }
          weight_updates++;
          if(test_weights) print_weights = true;
        }
        // for testing purposes; prints energy histogram and weight array
        if(print_weights){
          char *headerinfo = new char[4096];
          sprintf(headerinfo,
                  "# cell dimensions: (%5.2f, %5.2f, %5.2f), walls: %i,"
                  " de_density: %g, de_g: %g\n# seed: %li, N: %i, R: %f,"
                  " well_width: %g, translation_distance: %g\n"
                  "# initialization_iterations: %li, neighbor_scale: %g, dr: %g,"
                  " energy_levels: %i\n",
                  sw.len[0], sw.len[1], sw.len[2], sw.walls, de_density, de_g, seed, sw.N, R,
                  well_width, sw.translation_distance, initialization_iterations,
                  neighbor_scale, sw.dr, sw.energy_levels);
          
          char *countinfo = new char[4096];
          sprintf(countinfo,
                  "# iteration: %li, working moves: %li, total moves: %li, "
                  "acceptance rate: %g\n",
                  iteration, sw.moves.working, sw.moves.total,
                  double(sw.moves.working)/sw.moves.total);
          
          const char *testdir = "test";
          
          char *w_fname = new char[1024];
          char *e_fname = new char[1024];
          mkdir(dir, 0777); // create save directory
          sprintf(w_fname, "%s/%s", dir, testdir);
          mkdir(w_fname, 0777); // create test directory
          sprintf(w_fname, "%s/%s/%s-w%02i.dat",
                  dir, testdir, filename, weight_updates);
          sprintf(e_fname, "%s/%s/%s-E%02i.dat",
                  dir, testdir, filename, weight_updates);
          
          FILE *w_out = fopen(w_fname, "w");
          if (!w_out) {
            fprintf(stderr, "Unable to create %s!\n", w_fname);
            exit(1);
          }
          fprintf(w_out, "%s", headerinfo);
          fprintf(w_out, "%s", countinfo);
          fprintf(w_out, "\n# interactions   value\n");
          for(int i = 0; i < sw.energy_levels; i++)
            fprintf(w_out, "%i  %f\n", i, sw.ln_energy_weights[i]);
          fclose(w_out);
          
          FILE *e_out = fopen((const char *)e_fname, "w");
          fprintf(e_out, "%s", headerinfo);
          fprintf(e_out, "%s", countinfo);
          fprintf(e_out, "\n# interactions   counts\n");
          for(int i = 0; i < sw.energy_levels; i++)
            fprintf(e_out, "%i  %ld\n",i,sw.energy_histogram[i]);
          fclose(e_out);
          
          delete[] headerinfo;
          delete[] countinfo;
          delete[] w_fname;
          delete[] e_fname;
          
          print_weights = false;
        }
      }
      // ---------------------------------------------------------------
      // Print out timing information if desired
      // ---------------------------------------------------------------
      if (totime > 0 && iteration % totime == 0) {
        char *iter = new char[1024];
        sprintf(iter, "%i iterations", totime);
        took(iter);
        delete[] iter;
        printf("Iteration %li, acceptance rate of %g, translation_distance: %g.\n",
               iteration, (double)sw.moves.working/sw.moves.total,
               sw.translation_distance);
        printf("We've had %g updates per kilomove and %g informs per kilomoves, "
               "for %g informs per update.\n",
               1000.0*sw.moves.updates/sw.moves.total,
               1000.0*sw.moves.informs/sw.moves.total,
               (double)sw.moves.informs/sw.moves.updates);
        const long checks_without_tables = sw.moves.total*sw.N;
        int total_neighbors = 0;
        int most_neighbors = 0;
        for(int i = 0; i < sw.N; i++) {
          total_neighbors += sw.balls[i].num_neighbors;
          most_neighbors = max(sw.balls[i].num_neighbors, most_neighbors);
        }
        avg_neighbors = double(total_neighbors)/sw.N;
        const long checks_with_tables = sw.moves.total*avg_neighbors
          + sw.N*sw.moves.updates;
        printf("We've done about %.3g%% of the distance calculations we would "
               "have done without tables.\n",
               100.0*checks_with_tables/checks_without_tables);
        printf("The max number of neighbors is %i, whereas the most we have is "
               "%i.\n", sw.max_neighbors, most_neighbors);
        printf("Neighbor scale is %g and avg. number of neighbors is %g.\n\n",
               neighbor_scale, avg_neighbors);
        fflush(stdout);
      }
    }
  }

  {
    // Now let's iterate to the point where we are at maximum
    // probability before we do teh real simulation.
    const double st = sw.state_of_max_entropy;
    sw.initialize_max_entropy_and_translation_distance();
    sw.state_of_max_entropy = st;
  }
  took("Initialization");

  // ----------------------------------------------------------------------------
  // Generate info to put in save files
  // ----------------------------------------------------------------------------

  mkdir(dir, 0777); // create save directory

  char *headerinfo = new char[4096];
  sprintf(headerinfo,
          "# cell dimensions: (%5.2f, %5.2f, %5.2f), walls: %i,"
          " de_density: %g, de_g: %g\n# seed: %li, N: %i, R: %f,"
          " well_width: %g, translation_distance: %g\n"
          "# initialization_iterations: %li, neighbor_scale: %g, dr: %g,"
          " energy_levels: %i\n",
          sw.len[0], sw.len[1], sw.len[2], sw.walls, de_density, de_g, seed, sw.N, R,
          well_width, sw.translation_distance, initialization_iterations,
          neighbor_scale, sw.dr, sw.energy_levels);

  char *e_fname = new char[1024];
  sprintf(e_fname, "%s/%s-E.dat", dir, filename);

  char *w_fname = new char[1024];
  sprintf(w_fname, "%s/%s-lnw.dat", dir, filename);

  char *density_fname = new char[1024];
  sprintf(density_fname, "%s/%s-density-%i.dat", dir, filename, sw.N);

  char *g_fname = new char[1024];
  sprintf(g_fname, "%s/%s-g.dat", dir, filename);

  // ----------------------------------------------------------------------------
  // MAIN PROGRAM LOOP
  // ----------------------------------------------------------------------------

  clock_t output_period = CLOCKS_PER_SEC; // start at outputting every minute
  // top out at one hour interval
  clock_t max_output_period = clock_t(CLOCKS_PER_SEC)*60*30;
  clock_t last_output = clock(); // when we last output data

  sw.moves.total = 0;
  sw.moves.working = 0;

  // Reset energy histogram
  for(int i = 0; i < sw.energy_levels; i++)
    sw.energy_histogram[i] = 0;

  for(long iteration = 1; iteration <= iterations; iteration++) {
    // ---------------------------------------------------------------
    // Move each ball once, add to energy histogram
    // ---------------------------------------------------------------
    for(int i = 0; i < sw.N; i++) {
      move_one_ball(i, sw.balls, sw.N, sw.len, sw.walls, sw.neighbor_R, sw.translation_distance,
                    sw.interaction_distance, sw.max_neighbors, sw.dr, &sw.moves,
                    sw.interactions, sw.ln_energy_weights);
      sw.interactions += sw.moves.new_count - sw.moves.old_count;
      sw.energy_histogram[sw.interactions]++;
    }
    assert(sw.interactions ==
           count_all_interactions(sw.balls, sw.N, sw.interaction_distance, sw.len, sw.walls));
    // ---------------------------------------------------------------
    // Add data to density and RDF histograms
    // ---------------------------------------------------------------
    // Density histogram
    if(sw.walls){
      for(int i = 0; i < sw.N; i++){
        density_histogram[sw.interactions]
          [int(floor(sw.balls[i].pos[wall_dim]/de_density))] ++;
      }
    }

    // RDF
    if(!sw.walls){
      g_energy_histogram[sw.interactions]++;
      for(int i = 0; i < sw.N; i++){
        for(int j = 0; j < sw.N; j++){
          if(i != j){
            const vector3d r = periodic_diff(sw.balls[i].pos, sw.balls[j].pos, sw.len,
                                             sw.walls);
            const int r_i = floor(r.norm()/de_g);
            if(r_i < g_bins) g_histogram[sw.interactions][r_i]++;
          }
        }
      }
    }
    // ---------------------------------------------------------------
    // Save to file
    // ---------------------------------------------------------------
    const clock_t now = clock();
    if ((now - last_output > output_period) || iteration == iterations) {
      last_output = now;
      assert(last_output);
      if (output_period < max_output_period/2) output_period *= 2;
      else if (output_period < max_output_period)
        output_period = max_output_period;
      const double secs_done = double(now)/CLOCKS_PER_SEC;
      const int seconds = int(secs_done) % 60;
      const int minutes = int(secs_done / 60) % 60;
      const int hours = int(secs_done / 3600) % 24;
      const int days = int(secs_done / 86400);
      printf("Saving data after %i days, %02i:%02i:%02i, %li iterations "
             "complete.\n", days, hours, minutes, seconds, iteration);
      fflush(stdout);

      char *countinfo = new char[4096];
      sprintf(countinfo,
              "# iteration: %li, working moves: %li, total moves: %li, "
              "acceptance rate: %g\n",
              iteration, sw.moves.working, sw.moves.total,
              double(sw.moves.working)/sw.moves.total);

      // Save energy histogram
      FILE *e_out = fopen((const char *)e_fname, "w");
      fprintf(e_out, "%s", headerinfo);
      fprintf(e_out, "%s", countinfo);
      fprintf(e_out, "\n# interactions   counts\n");
      for(int i = 0; i < sw.energy_levels; i++)
        if(sw.energy_histogram[i] != 0)
          fprintf(e_out, "%i  %ld\n",i,sw.energy_histogram[i]);
      fclose(e_out);

      // Save weights histogram
      FILE *w_out = fopen((const char *)w_fname, "w");
      fprintf(w_out, "%s", headerinfo);
      fprintf(w_out, "%s", countinfo);
      fprintf(w_out, "\n# interactions   ln(weight)\n");
      for(int i = 0; i < sw.energy_levels; i++)
        if(sw.energy_histogram[i] != 0){
          fprintf(w_out, "%i  %g\n",i,sw.ln_energy_weights[i]);
        }
      fclose(w_out);

      // Save RDF
      if(!sw.walls){
        FILE *g_out = fopen((const char *)g_fname, "w");
        fprintf(g_out, "%s", headerinfo);
        fprintf(g_out, "%s", countinfo);
        fprintf(g_out, "\n# data table containing values of g");
        fprintf(g_out, "\n# first column reserved for specifying energy level");
        fprintf(g_out, "\n# column number rn (starting from the second column, "
                "counting from zero) corresponds to radius r given by "
                "r = (rn + 0.5) * de_g");
        const double density = sw.N/sw.len[x]/sw.len[y]/sw.len[z];
        const double total_vol = sw.len[x]*sw.len[y]*sw.len[z];
        for(int i = 0; i < sw.energy_levels; i++){
          if(g_histogram[i][g_bins-1] > 0){ // if we have RDF data at this energy
            fprintf(g_out, "\n%i",i);
            for(int r_i = 0; r_i < g_bins; r_i++) {
              const double probability = (double)g_histogram[i][r_i]
                / g_energy_histogram[i];
              const double r = (r_i + 0.5) * de_g;
              const double shell_vol =
                4.0/3.0*M_PI*(uipow(r+de_g/2, 3) - uipow(r-de_g/2, 3));
              const double n2 = probability/total_vol/shell_vol;
              const double g = n2/sqr(density);
              fprintf(g_out, " %8.5f", g);
            }
          }
        }
        fclose(g_out);
      }

      // Saving density data
      if(sw.walls){
        FILE *densityout = fopen((const char *)density_fname, "w");
        fprintf(densityout, "%s", headerinfo);
        fprintf(densityout, "%s", countinfo);
        fprintf(densityout, "\n# data table containing densities in slabs "
                "(bins) of thickness de_density away from a wall");
        fprintf(densityout, "\n# row number corresponds to energy level");
        fprintf(densityout, "\n# column number dn (counting from zero) "
                "corresponds to distance d from wall given by "
                "d = (dn + 0.5) * de_density");
        for(int i = 0; i < sw.energy_levels; i++){
          fprintf(densityout, "\n");
          for(int r_i = 0; r_i < density_bins; r_i++) {
            const double bin_density =
              (double)density_histogram[i][r_i]
              *sw.N/sw.energy_histogram[i]/bin_volume;
            fprintf(densityout, "%8.5f ", bin_density);
          }
        }
        fclose(densityout);
      }

      delete[] countinfo;
    }
  }
  // ----------------------------------------------------------------------------
  // END OF MAIN PROGRAM LOOP
  // ----------------------------------------------------------------------------

  delete[] sw.balls;
  delete[] sw.ln_energy_weights;
  delete[] sw.energy_histogram;
  delete[] g_histogram;
  delete[] density_histogram;

  delete[] headerinfo;
  return 0;
}