コード例 #1
0
TEST( Vector, DataRoutineView )
{
    std::vector<int> arr( 100, 99 );

    bolt::amp::device_vector< int, concurrency::array_view > av( arr );

    av[50] = 0;
    av.data( );

    EXPECT_EQ( arr[50], av[50] );
}
コード例 #2
0
ファイル: test.cpp プロジェクト: jstepien/abandon-all-reason
 really_equal() {
   std::cerr
     << str<a>().s
     << " is not equal to "
     << str<b>().s
     << "\n  because "
     << av()
     << " != "
     << bv()
     << "\n";
   fail();
 }
コード例 #3
0
ファイル: main.cpp プロジェクト: CCJY/coliru
int main() {
  std::vector<B> bv{B(1), B(2), B(3), B(4), B(5)};
  std::vector<A> av(bv.size());
  std::vector<B> bbv(bv.size());
  std::copy(bv.begin(), bv.end(), av.begin());
  for(auto i : av) std::cout << i << " ";
  std::cout << std::endl;
  std::copy(av.begin(), av.end(), bbv.begin());
  for(auto i : bbv) std::cout << i << " ";
  std::cout << std::endl;  
  return 0;
}
コード例 #4
0
ファイル: static_library2.cpp プロジェクト: jvesely/hcc
int main() {

  hc::array_view<int,1> av(64);
  for (int i = 0;i < 64; i++)
    av[i] = i;

  int s = sum(av);

 // printf("sum: %d\n",s);

  return !(s==2016);
}
コード例 #5
0
ファイル: SkGlyphCache.cpp プロジェクト: YangchenVR/skia
/*  This guy calls the visitor from within the mutext lock, so the visitor
    cannot:
    - take too much time
    - try to acquire the mutext again
    - call a fontscaler (which might call into the cache)
*/
SkGlyphCache* SkGlyphCache::VisitCache(SkTypeface* typeface,
                              const SkDescriptor* desc,
                              bool (*proc)(const SkGlyphCache*, void*),
                              void* context) {
    if (!typeface) {
        typeface = SkTypeface::GetDefaultTypeface();
    }
    SkASSERT(desc);

    SkGlyphCache_Globals& globals = get_globals();
    SkGlyphCache*         cache;

    {
        Exclusive ac(globals.fLock);

        globals.validate();

        for (cache = globals.internalGetHead(); cache != nullptr; cache = cache->fNext) {
            if (cache->fDesc->equals(*desc)) {
                globals.internalDetachCache(cache);
                if (!proc(cache, context)) {
                    globals.internalAttachCacheToHead(cache);
                    cache = nullptr;
                }
                return cache;
            }
        }
    }

    // Check if we can create a scaler-context before creating the glyphcache.
    // If not, we may have exhausted OS/font resources, so try purging the
    // cache once and try again.
    {
        // pass true the first time, to notice if the scalercontext failed,
        // so we can try the purge.
        SkScalerContext* ctx = typeface->createScalerContext(desc, true);
        if (!ctx) {
            get_globals().purgeAll();
            ctx = typeface->createScalerContext(desc, false);
            SkASSERT(ctx);
        }
        cache = new SkGlyphCache(typeface, desc, ctx);
    }

    AutoValidate av(cache);

    if (!proc(cache, context)) {   // need to reattach
        globals.attachCacheToHead(cache);
        cache = nullptr;
    }
    return cache;
}
コード例 #6
0
void MazeController::ligacoes(int value, Maze** maze)
{
	std::list<Liga> p;
	for (int i = 0; i < value; i++)
	{
		for (int j = 0; j < value; j++)
		{
			if (i == 5 && j == 5)

			if (maze[i][j].north == 0){ Liga l; l.aX = j; l.aY = i; l.bX = j; l.bY = i - 1;  p.push_back(l); }
			if (maze[i][j].south == 0){ Liga l; l.aX = j; l.aY = i; l.bX = j; l.bY = i + 1;  p.push_back(l); }
			if (maze[i][j].east == 0) { Liga l; l.aX = j; l.aY = i; l.bX = j + 1; l.bY = i;  p.push_back(l); }
			if (maze[i][j].west == 0) { Liga l; l.aX = j; l.aY = i; l.bX = j - 1; l.bY = i;  p.push_back(l); }

		}
	}


	ofstream myfile;
	myfile.open("example.txt");
	int i = 0;
	while (!p.empty())
	{
		PlTermv av(1);
		string arg1 = "(";
		string arg2 = "(";
		Liga x = p.front();
		arg1 += convertInt(x.aX) + ",";
		arg1 += convertInt(x.aY) + ")";
		arg2 += convertInt(x.bX) + ",";
		arg2 += convertInt(x.bY) + ")";
		p.pop_front();
		string ligacao = "liga(" + arg1 + "," + arg2 + ")";

		av[0] = PlCompound(ligacao.c_str());
		PlQuery query("asserta", av);

		if (query.next_solution()) myfile << ligacao << "." << endl;
		i++;

		PlTermv parm(2);
		parm[0] = PlCompound(arg1.c_str());
		PlQuery query2("liga", parm);
		while (query2.next_solution()){
			cout << arg1 << " ---> ";
			printf(parm[1]);
			cout << " " << endl;
		}

	}
	myfile.close();
}
コード例 #7
0
void SkGradientBitmapCache::add(const void* buffer, size_t len, const SkBitmap& bm) {
    AutoValidate av(this);

    if (fEntryCount == fMaxEntries) {
        SkASSERT(fTail);
        delete this->release(fTail);
        fEntryCount -= 1;
    }

    Entry* entry = new Entry(buffer, len, bm);
    this->attachToHead(entry);
    fEntryCount += 1;
}
コード例 #8
0
ファイル: p24.c プロジェクト: edpack1980/uml-auto-assessment
int main( int argc, char *argv[]){
  int x[4], i;
  i = 0;
  FILE *fin;
  fin = fopen ("testdata24", "r");
  while( i < 4 ){ 
    fscanf(fin, "%d", &x[i]);
      i++;
      }
  printf("%f\n", av(x));
  fclose(fin);
  return 0;
}
コード例 #9
0
inline bool
checkFieldPosition(const Field<Geometry, T, Engine> &f,
		   const FieldOffsetList<Dim> &fol,
		   const Loc<Dim> &loc,
		   const T sumAnswer, const T avAnswer,
		   const T minAnswer, const T maxAnswer,
		   const double tolerance)
{
  return 
    std::abs(sum(f, fol, loc) - sumAnswer) < tolerance &&
    std::abs(av(f, fol, loc) - avAnswer) < tolerance &&
    std::abs(min(f, fol, loc) - minAnswer) < tolerance &&
    std::abs(max(f, fol, loc) - maxAnswer) < tolerance;
}
コード例 #10
0
  void callAsConstructor(const Function *fn, Value *result, const internal::JSArguments &argv)
    {
    const v8::Arguments &args = JSArgumentsInternal::val(&argv);

    const int argc = args.Length();
    std::vector< v8::Handle<v8::Value> > av(static_cast<size_t>(argc),v8::Undefined());

    for( int i = 0; i < argc; ++i )
      {
      av[i] = args[i];
      }

    const FunctionInternal* func = FunctionInternal::val(fn);
    *result = fromHandle(func->_object->NewInstance(argc, &av[0]));
    }
コード例 #11
0
ファイル: GrResourceCache2.cpp プロジェクト: OS-Corp/skia
void GrResourceCache2::releaseAll() {
    AutoValidate av(this);

    SkASSERT(!fPurging);
    while (GrGpuResource* head = fResources.head()) {
        SkASSERT(!head->wasDestroyed());
        head->cacheAccess().release();
        // release should have already removed this from the list.
        SkASSERT(head != fResources.head());
    }
    SkASSERT(!fScratchMap.count());
    SkASSERT(!fCount);
    SkASSERT(!fBytes);
    SkASSERT(!fBudgetedCount);
    SkASSERT(!fBudgetedBytes);
}
コード例 #12
0
bool SkGradientBitmapCache::find(const void* buffer, size_t size, SkBitmap* bm) const {
    AutoValidate av(this);

    Entry* entry = fHead;
    while (entry) {
        if (entry->equals(buffer, size)) {
            if (bm) {
                *bm = entry->fBitmap;
            }
            // move to the head of our list, so we purge it last
            this->release(entry);
            this->attachToHead(entry);
            return true;
        }
        entry = entry->fNext;
    }
    return false;
}
コード例 #13
0
ファイル: 1.c プロジェクト: qhauict13/hustCbasic
void medias(int *arr,int len){
  double ava,dis,dism;
  int i;
  ava = av(arr,len);
  
  dis = 0;
  dism = fabs(ava - arr[0]);

  for (i = 1; i < len ; i++) {
    dis = fabs(ava - arr[i]);
    if( dis < dism )  dism = dis;
  }
  printf("\n");
  for ( i = 0 ; i < len ; i++) {
    if(dism ==  fabs(ava - arr[i])) printf("%d\t",arr[i]);
  }
  printf("\n");
}
コード例 #14
0
  void
  Connection::write(Message& message)
  {
    ACE_Time_Value av(ACE_OS::gettimeofday() + ACE_Time_Value(1));

    if (writeMutex.acquire(av) == -1)
      throw Miro::CException(errno, "Error writing can device.");

    // Roland: Is this sleep necessary for Sparrow2003 can ???

    ACE_Time_Value time = ACE_OS::gettimeofday();
    ACE_Time_Value delta = time - lastWrite;
    if (delta < canTimeOut) {
      // is this sleep necessary ???
      // well, yes

      ACE_OS::sleep(canTimeOut - delta); // this is at least 10usec thanks to linux
      time = ACE_OS::gettimeofday();
    }

    // will definitely choke if base is off
    int rc;
    if (parameters_.module == "pcan") {
       pcanmsg * msgp;
       message.canMessage((int **) &msgp);
       msgp->msg.msgtype = MSGTYPE_EXTENDED;
       for(int i = 0; i < msgp->msg.len; i++)
          std::cout << msgp->msg.data[i];
       rc = ioctl(ioBuffer.get_handle(), PCAN_WRITE_MSG, msgp);
    }
    else {
       canmsg * msg;
       message.canMessage((int **) &msg);
       rc = ioBuffer.send_n(msg, sizeof(canmsg));
    }

    lastWrite = time;

    writeMutex.release();
    if (rc == -1)
      throw Miro::CException(errno, "Error writing can device.");
  }
コード例 #15
0
void UpdateCDBCTPConfig(const char *CTPcfg, const char* cdbUri, const char* cfgFile){
  // Produces a trigger configuration starting from a 'cfg' file in the
  // GRP/CTP folder (CTPcfg argument). Stores the configuration in the specified CDB.
  // The third argument allows to specify the config file against which
  // the trigger confiuration is checked.

  IlcCDBManager* cdb = IlcCDBManager::Instance();
  // we set the default storage to the repository because some dets require
  // already at the time of geometry creation to find calibration objects in the cdb
  if(!cdb->IsDefaultStorageSet()) cdb->SetDefaultStorage("local://$ILC_ROOT/OCDB");
  IlcCDBStorage* storage = cdb->GetStorage(cdbUri);
  cdb->SetRun(0);
  IlcCDBId id("GRP/CTP/Config",0,IlcCDBRunRange::Infinity());
  IlcCDBMetaData *md= new IlcCDBMetaData();

  // Get root and IlcRoot versions
  const char* rootv = gROOT->GetVersion();
  gROOT->ProcessLine(".L $ILC_ROOT/macros/GetARversion.C");
  TString av(GetARversion());

  md->SetIlcRootVersion(av.Data());
  md->SetComment(Form("Default CTP configuration for p-p mode produced with root version %s and IlcRoot version %s",rootv,av.Data()));
  
  // construct the CTP configuration starting from GRP/CTP/<CTPcfg>.cfg file
  IlcTriggerConfiguration *trconfig = IlcTriggerConfiguration::LoadConfiguration(CTPcfg);
  if (!trconfig) {
    Printf("Invalid cfg file! Exiting...");
    return;
  }
  if (!trconfig->CheckConfiguration(cfgFile)) {
    Printf("CTP configuration is incompatible with the specified Config.C and IlcRoot version! Exiting...");
    return;
  }
  
  Printf("Storing in CDB geometry produced with root version %s and IlcRoot version %s",rootv,av.Data());
  storage->Put(trconfig,id,md);
  // This is to allow macros lauched after this one in the same session to find the
  // newly produced geometry.
  storage->QueryCDB(cdb->GetRun());

}
コード例 #16
0
ファイル: api_algebraic.cpp プロジェクト: CHolmes3/z3
 Z3_ast Z3_API Z3_algebraic_power(Z3_context c, Z3_ast a, unsigned k) {
     Z3_TRY;
     LOG_Z3_algebraic_power(c, a, k);
     RESET_ERROR_CODE();
     CHECK_IS_ALGEBRAIC_X(a, 0);
     algebraic_numbers::manager & _am = am(c);
     scoped_anum _r(_am);
     if (is_rational(c, a)) {
         scoped_anum av(_am);                                     
         _am.set(av, get_rational(c, a).to_mpq());   
         _am.power(av, k, _r);
     }
     else {
         algebraic_numbers::anum const & av = get_irrational(c, a);
         _am.power(av, k, _r);
     }
     expr * r = au(c).mk_numeral(_r, false);
     mk_c(c)->save_ast_trail(r);
     RETURN_Z3(of_ast(r));
     Z3_CATCH_RETURN(0);
 }
コード例 #17
0
ファイル: main.cpp プロジェクト: luqui/soylent
void step()
{
    find_crossings();

    step_field();
    step_bullets();
    step_dude();

    for (int i = 0; i < 1; i++) {
        int xidx = rand() % FWIDTH;
        int yidx = rand() % FHEIGHT;
        FIELD[xidx][yidx].value += 16;
    }

    int mousex, mousey;
    Uint8 buts = SDL_GetMouseState(&mousex, &mousey);

    // firing
    if (buts & SDL_BUTTON(1)) {
        Viewport pix = INIT.pixel_view();
        Viewport screen(vec2((SCRRIGHT + SCRLEFT)/2, (SCRTOP + SCRBOTTOM)/2),
                        vec2(SCRRIGHT - SCRLEFT,     SCRTOP - SCRBOTTOM));
        vec2 pos = coord_convert(pix, screen, vec2(mousex, mousey));
        vec2 av(DUDE.xpos, DUDE.ypos);

        int xtidx = int((pos.x - SCRLEFT) / XSTEP);
        int ytidx = int((pos.x - SCRBOTTOM) / YSTEP);

        vec2 dir = ~(pos - av);

        Bullet b;
        b.pos = av + dir;
        b.vel = BULLET_MOTION * dir;
        b.color = CONTOUR[CONTOUR_FIRE] - 1;
        b.target = FIELD[xtidx][ytidx].value;
        b.life = 80;
        BULLETS.push_back(b);
    }
}
コード例 #18
0
QuatT CombineHVComponents3D(const QuatT& cmpH, const QuatT& cmpV)
{
	ANIMCHAR_PROFILE_DETAILED;

	//return CombineHVComponents2D(cmpH, cmpV);

	CRY_ASSERT(cmpH.IsValid());
	CRY_ASSERT(cmpV.IsValid());

	QuatT cmb;
	cmb.t.x = cmpH.t.x;
	cmb.t.y = cmpH.t.y;
	cmb.t.z = cmpV.t.z;

	// TODO: This should be optimized!
	Ang3 ah(cmpH.q);
	Ang3 av(cmpV.q);
	Ang3 a(av.x, av.y, ah.z);
	cmb.q.SetRotationXYZ(a);

	CRY_ASSERT(cmb.IsValid());

	return cmb;
}
コード例 #19
0
ファイル: MulVsDiv.cpp プロジェクト: vilorez/VKDiplom-master
void MulVsDiv::DependendDynamicArrayLoop()
{
	const int length = 256;
	const int loops = 1e6;
	std::cout << "Dependend Dynamic loop:\n---" << std::endl;
	std::vector<double> av(length), bv(length);
	double *a = &av.front(), *b = &bv.front();
	
	std::vector<long> add_times;
	std::vector<long> mul_times;
	std::vector<long> div_times;
	add_times.reserve(loops);
	mul_times.reserve(loops);
	div_times.reserve(loops);
	unsigned long long ignoreit[]{0,0,0};
	
	for (size_t i = 0; i < length; i++)
	{
		av[i] = 8 * (static_cast<double>(rand()) / (RAND_MAX)) + 1;
		//bv[i] = DBL_MIN;
	}

	//Division
	for (size_t i = 0; i < loops; i++)
	{
		auto start = clock();
		for (size_t j = 0; j < length-1; j++)
		{
			b[j] = a[j + 1] / a[j];
		}
		auto finish = clock();
		div_times.push_back(finish-start);
		ignoreit[0] += std::accumulate(bv.begin(), bv.end(), 0);
	}
	auto div_time = std::accumulate(div_times.begin(), div_times.end(), 0)
		/ loops;
	std::cout << "Division:\t\t" << div_time << std::endl;
	//Multiplication
	for (size_t i = 0; i < loops; i++)
	{
		auto start = clock();
		for (size_t j = 0; j < length - 1; j++)
		{
			b[j] = a[j + 1] * a[j];
		}
		auto finish = clock();
		mul_times.push_back(finish - start);
		ignoreit[1] += std::accumulate(bv.begin(),bv.end(), 0);
	}
	auto mul_time = std::accumulate(mul_times.begin(), mul_times.end(), 0)
		/ loops;
	std::cout << "Multiplication:\t\t" << mul_time << std::endl;
	//Addition
	for (size_t i = 0; i < loops; i++)
	{
		auto start = clock();
		for (size_t j = 0; j < length - 1; j++)
		{
			b[j] = a[j + 1] + a[j];
		}
		auto finish = clock();
		add_times.push_back(finish - start);
		ignoreit[2] += std::accumulate(bv.begin(), bv.end(), 0);
	}
	auto add_time = std::accumulate(add_times.begin(), add_times.end(), 0)
		/ loops;
	std::cout << "Addition:\t\t" << add_time << std::endl;

	std::cout << "Addition faster than multiplication:\t" << static_cast<double>(mul_time) / static_cast<double>(add_time) << std::endl;
	std::cout << "Multiplication faster than division:\t" << static_cast<double>(div_time) / static_cast<double>(mul_time) << std::endl;
	std::cout << "Just ignore it: " << ignoreit[0]<< ignoreit[1]<< ignoreit[2] << std::endl << std::endl;
}
コード例 #20
0
ファイル: MulVsDiv.cpp プロジェクト: vilorez/VKDiplom-master
void MulVsDiv::DynamicArrayLoopVectorized()
{
	const int length = 256;
	const int loops = 1e6;
	std::cout << "Vectorized dynamic array loop:\n---" << std::endl;
	std::vector<double> av(length), bv(length), cv(length);
	double *a = &av.front(), *b = &bv.front(), *c = &bv.front();
	auto ignoreit = 0.0;

	ResetArrays(length, a, b, ignoreit);

	int l = 0;
	auto start = clock();
add:
	for (int i = 0; i < length; i++)
	{
		c[i] = a[i] + b[i];
	}
	// MSVC doesn't vectorize nested loops (message 1300 - too little computation to vectorize) in function 'DynamicArrayLoop'.
	// However if nested loop is replaced with this nasty workaround SIMD vectorization will happen.
	// Same condition apply for mul/div/rcp loops
	while (l < loops)
	{
		++l;
		goto add;
	}
	auto add_time = clock() - start;
	std::cout << "Addition: " << add_time << std::endl;

	ResetArrays(length, a, b, ignoreit);
	ignoreit /= c[(rand() % (int)(length))];
	l = 0;
	start = clock();
mul:
	for (int i = 0; i < length; ++i)
	{
		c[i] = a[i] * b[i];
	}
	while (l < loops)
	{
		++l;
		goto mul;
	}
	auto mul_time = clock() - start;
	std::cout << "Multiplication: " << mul_time << std::endl;

	ResetArrays(length, a, b, ignoreit);
	ignoreit /= c[(rand() % (int)(length))];
	l = 0;
	start = clock();
div:
	for (int i = 0; i < length; ++i)
	{
		c[i] = a[i] / b[i];
	}
	while (l < loops)
	{
		++l;
		goto div;
	}
	auto div_time = clock() - start;
	ignoreit /= c[(rand() % (int)(length))];
	ignoreit += a[(rand() % (int)(length))] + b[(rand() % (int)(length))];
	std::cout << "Division: " << div_time << std::endl;

	std::cout << "Addition faster than multiplication: " << static_cast<double>(mul_time) / static_cast<double>(add_time) << std::endl;
	std::cout << "Multiplication faster than division: " << static_cast<double>(div_time) / static_cast<double>(mul_time) << std::endl;
	std::cout << "Just ignore it: " << ignoreit << std::endl << std::endl;
}
コード例 #21
0
ファイル: MulVsDiv.cpp プロジェクト: vilorez/VKDiplom-master
void MulVsDiv::CsabaDynamicArrayLoop()
{
	const int length = 256;//1024 *1024* 8;
	const int loops = 1e6;//1e3 / 2;
	std::cout << "Csaba loop:\n---" << std::endl;
	std::vector<double> av(length), bv(length);
	double *a = &av.front(), *b = &bv.front();
	auto ignoreit = 0.0;

	ResetArrays(length, a, b, ignoreit);
	auto idx1 = (rand() % static_cast<int>(length)), idx2 = (rand() % static_cast<int>(length-1));
	auto start = clock();
	for (size_t l = 0; l < loops; l++)
	{
		// MSVC cannot vectorize this loop (message 1300).
		// However, if this loop will not be nested in, autovectorization will happen.
		// Same condition apply for mul/div/rcp loops

		// ICL does not have this issue, but to provide both vectorized and nonvectorized comparison 
		// i specifically disabled vectorization in this method
#pragma novector
#pragma loop( no_vector )
		for (int i = 1; i < length-1; ++i)
		{
			a[i] = b[idx1] + b[idx2];
		}
	}
	auto add_time = clock() - start;
	std::cout << "Addition: " << add_time << std::endl;

	ignoreit += a[(rand() % static_cast<int>(length))] + b[(rand() % static_cast<int>(length))];

	idx1 = (rand() % static_cast<int>(length)), idx2 = (rand() % static_cast<int>(length));

	start = clock();
	for (size_t l = 0; l < loops; l++)
	{
#pragma novector
#pragma loop( no_vector )
		for (int i = 0; i < length-1; ++i)
		{
			a[i] =b[idx1] * b[idx2];
		}
	}
	auto mul_time = clock() - start;
	std::cout << "Multiplication: " << mul_time << std::endl;

	ignoreit += a[(rand() % static_cast<int>(length))] + b[(rand() % static_cast<int>(length))];
	idx1 = (rand() % static_cast<int>(length)), idx2 = (rand() % static_cast<int>(length));
	start = clock();
	for (size_t l = 0; l < loops; l++)
	{
#pragma novector
#pragma loop( no_vector )
		for (int i = 0; i < length; ++i)
		{
			a[i] = b[idx1] / b[idx2];
		}
	}
	auto div_time = clock() - start;
	ignoreit += a[(rand() % static_cast<int>(length))] + b[(rand() % static_cast<int>(length))];
	std::cout << "Division: " << div_time << std::endl;
	std::cout << "Addition faster than multiplication: " << static_cast<double>(mul_time) / static_cast<double>(add_time) << std::endl;
	std::cout << "Multiplication faster than division: " << static_cast<double>(div_time) / static_cast<double>(mul_time) << std::endl;
	std::cout << "Just ignore it: " << ignoreit << std::endl << std::endl;
}
コード例 #22
0
//this is a feature of webcore but we need it here in case we need to shutdown during a download
void DownloadUpdateTask::downloadUpdate()
{
#ifdef DEBUG
	return;
#endif

	uint32 appver = m_uiAppVer;
	uint32 appbuild = m_uiAppBuild;


	HttpHandle wc(PRIMUPDATE);
	getWebCore()->setWCCookies(wc);
	
	wc->addPostText("appid", appver);
	wc->postWeb();


	if (wc->getDataSize() == 0)
		throw gcException(ERR_INVALIDDATA);


	XML::gcXMLDocument doc(const_cast<char*>(wc->getData()), wc->getDataSize());
	doc.ProcessStatus("appupdate");

	auto mNode = doc.GetRoot("appupdate").FirstChildElement("mcf");

	if (!mNode.IsValid())
		throw gcException(ERR_BADXML);

	uint32 version = 0;
	uint32 build = 0;
	
	mNode.GetAtt("appid", version);
	mNode.GetAtt("build", build);

	if (version == 0 || build == 0)
		throw gcException(ERR_BADXML);

	//check to see if its newer than last
	if (appbuild != 0 && build <= appbuild && appver == version)
		return;

	gcString url = mNode.GetChild("url");

	if (url.size() == 0)
		throw gcException(ERR_BADXML);

#ifdef WIN32
	const char *comAppPath = getUserCore()->getAppDataPath();
	m_szPath = gcString("{0}{1}{2}", comAppPath, DIRS_STR, UPDATEFILE);
#else
	m_szPath = gcString("{0}", UPDATEFILE);
#endif

	m_hMcfHandle->setFile(m_szPath.c_str());
	m_hMcfHandle->setWorkerCount(1);
	
	try
	{
		m_hMcfHandle->dlHeaderFromHttp(url.c_str());

#ifdef WIN32
		const char* dir = ".\\";
#else
		const char* dir = "./";
#endif

		//Dont use courgette for non admins for now
		bool useCourgette = false;

#ifdef WIN32
		if (getUserCore()->isAdmin())
			useCourgette = true;
#endif

		bool res = m_hMcfHandle->verifyInstall(dir, true, useCourgette);

		m_hMcfHandle->getProgEvent() += delegate(this, &DownloadUpdateTask::onDownloadProgress);

		UserCore::Misc::update_s info;
		info.build = build;

		if (!res)
		{
			Msg(gcString("Downloading " PRODUCT_NAME " update: Ver {0} build {1}\n", appver, build));
			info.alert = true;

			onDownloadStartEvent(info);

			if (useCourgette)
				m_hMcfHandle->dlFilesFromHttp(url.c_str(), dir);
			else
				m_hMcfHandle->dlFilesFromHttp(url.c_str());

			if (!isStopped())
				onDownloadCompleteEvent(info);
		}
		else
		{
			//sometimes this gets called after shutdown and causes major problems
			if (!getUserCore() || !getUserCore()->getServiceMain())
				return;

			gcString av("{0}", appver);
			gcString ab("{0}", build);
			info.alert = false;

			try
			{
				getUserCore()->getServiceMain()->updateRegKey(APPID, av.c_str());
				getUserCore()->getServiceMain()->updateRegKey(APPBUILD, ab.c_str());
			}
			catch (gcException &e)
			{
				Warning(gcString("Failed to update reg key: {0}\n", e));
			}

			onDownloadCompleteEvent(info);
		}
	}
	catch (gcException &e)
	{
		Warning(gcString("Download update failed: {0}\n", e));
	}
}
コード例 #23
0
ファイル: group_values.cpp プロジェクト: vadz/lmi.new
census_run_result run_census_in_parallel::operator()
    (fs::path           const& file
    ,mcenum_emission    const  emission
    ,std::vector<Input> const& cells
    ,Ledger                  & composite
    )
{
    Timer timer;
    census_run_result result;
    boost::shared_ptr<progress_meter> meter
        (create_progress_meter
            (cells.size()
            ,"Initializing all cells"
            ,progress_meter_mode(emission)
            )
        );

    ledger_emitter emitter(file, emission);

    std::vector<Input>::const_iterator ip;
    std::vector<boost::shared_ptr<AccountValue> > cell_values;
    std::vector<boost::shared_ptr<AccountValue> >::iterator i;
    std::vector<mcenum_run_basis> const& RunBases = composite.GetRunBases();

    int j = 0;
    int const first_cell_inforce_year  = value_cast<int>((*cells.begin())["InforceYear"].str());
    int const first_cell_inforce_month = value_cast<int>((*cells.begin())["InforceMonth"].str());
    cell_values.reserve(cells.size());
    for(ip = cells.begin(); ip != cells.end(); ++ip, ++j)
        {
        // This condition need be written only once, here, because
        // subsequently 'cell_values' (which reflects the condition)
        // is iterated across instead of 'cells'.
        if(!cell_should_be_ignored(cells[j]))
            {
            { // Begin fenv_guard scope.
            fenv_guard fg;
            boost::shared_ptr<AccountValue> av(new AccountValue(*ip));
            std::string const name(cells[j]["InsuredName"].str());
            av->SetDebugFilename
                (serial_file_path(file, name, j, "hastur").string()
                );

            cell_values.push_back(av);

            if(contains(av->yare_input_.Comments, "idiosyncrasyZ"))
                {
                av->Debugging = true;
                av->DebugPrintInit();
                }

            if
                (   first_cell_inforce_year  != av->yare_input_.InforceYear
                ||  first_cell_inforce_month != av->yare_input_.InforceMonth
                )
                {
                fatal_error()
                    << "Running census by month untested for inforce"
                    << " with inforce duration varying across cells."
                    << LMI_FLUSH
                    ;
                }

            if(mce_solve_none != av->yare_input_.SolveType)
                {
                fatal_error()
                    << "Running census by month: solves not permitted."
                    << LMI_FLUSH
                    ;
                }
            } // End fenv_guard scope.
            }

        if(!meter->reflect_progress())
            {
            result.completed_normally_ = false;
            goto done;
            }
        } // End for.
    meter->culminate();
    if(cell_values.empty())
        {
        // Make sure it's safe to dereference cell_values[0] later.
        fatal_error()
            << "No cell with any lives was included in the composite."
            << LMI_FLUSH
            ;
        }

    for
        (std::vector<mcenum_run_basis>::const_iterator run_basis = RunBases.begin()
        ;run_basis != RunBases.end()
        ;++run_basis
        )
        {
        // It seems somewhat anomalous to create and update a GUI
        // progress meter inside this critical calculation section,
        // because it is not entirely inconceivable that doing so
        // might affect the floating-point control word. However,
        // rogue msw dlls that improperly alter the control word
        // seem to do so when they are initially loaded, and any
        // such dll would already have been loaded to support the
        // progress meter used earlier in this function.
        { // Begin fenv_guard scope.
        fenv_guard fg;
        mcenum_gen_basis expense_and_general_account_basis;
        mcenum_sep_basis separate_account_basis;
        set_cloven_bases_from_run_basis
            (*run_basis
            ,expense_and_general_account_basis
            ,separate_account_basis
            );

        // Calculate duration when the youngest life matures.
        int MaxYr = 0;
        for(i = cell_values.begin(); i != cell_values.end(); ++i)
            {
            (*i)->InitializeLife(*run_basis);
            MaxYr = std::max(MaxYr, (*i)->GetLength());
            }

        meter = create_progress_meter
            (MaxYr - first_cell_inforce_year
            ,mc_str(*run_basis)
            ,progress_meter_mode(emission)
            );

        // Variables to support tiering and experience rating.

        double const case_ibnr_months =
            cell_values[0]->ibnr_as_months_of_mortality_charges()
            ;
        double const case_experience_rating_amortization_years =
            cell_values[0]->experience_rating_amortization_years()
            ;

        double case_accum_net_mortchgs = 0.0;
        double case_accum_net_claims   = 0.0;
        double case_k_factor = cell_values[0]->yare_input_.ExperienceRatingInitialKFactor;

        // Experience rating as implemented here uses either a special
        // scalar input rate, or the separate-account rate. Those
        // rates as entered might vary across cells, but there must be
        // only one rate: therefore, use the first cell's rate, and
        // extend its last element if it doesn't have enough values.

        std::vector<double> experience_reserve_rate;
        std::copy
            (cell_values[0]->yare_input_.SeparateAccountRate.begin()
            ,cell_values[0]->yare_input_.SeparateAccountRate.end()
            ,std::back_inserter(experience_reserve_rate)
            );
        experience_reserve_rate.resize(MaxYr, experience_reserve_rate.back());
        if(cell_values[0]->yare_input_.OverrideExperienceReserveRate)
            {
            experience_reserve_rate.assign
                (experience_reserve_rate.size()
                ,cell_values[0]->yare_input_.ExperienceReserveRate
                );
            }

        for(int year = first_cell_inforce_year; year < MaxYr; ++year)
            {
            double experience_reserve_annual_u =
                    1.0
                +   experience_reserve_rate[year]
                ;

            for(i = cell_values.begin(); i != cell_values.end(); ++i)
                {
                // A cell must be initialized at the beginning of any
                // partial inforce year in which it's illustrated.
                if((*i)->PrecedesInforceDuration(year, 11))
                    {
                    continue;
                    }
                (*i)->Year = year;
                (*i)->CoordinateCounters();
                (*i)->InitializeYear();
                }

            // Process one month at a time for all cells.
            int const inforce_month =
                first_cell_inforce_year == year
                    ? first_cell_inforce_month
                    : 0
                    ;
            for(int month = inforce_month; month < 12; ++month)
                {
                double assets = 0.0;

                // Get total case assets prior to interest crediting because
                // those assets may determine the M&E charge.

                // Process transactions through monthly deduction.
                for(i = cell_values.begin(); i != cell_values.end(); ++i)
                    {
                    if((*i)->PrecedesInforceDuration(year, month))
                        {
                        continue;
                        }
                    (*i)->Month = month;
                    (*i)->CoordinateCounters();
                    (*i)->IncrementBOM(year, month, case_k_factor);
                    assets += (*i)->GetSepAcctAssetsInforce();
                    }

                // Process transactions from int credit through end of month.
                for(i = cell_values.begin(); i != cell_values.end(); ++i)
                    {
                    if((*i)->PrecedesInforceDuration(year, month))
                        {
                        continue;
                        }
                    (*i)->IncrementEOM(year, month, assets, (*i)->CumPmts);
                    }
                }

            // Perform end of year calculations.

            // Project claims using the partial-mortality rate:
            // it's curtate, so the whole year's claims occur at
            // the end of the last month and no interest
            // adjustment is required.
            //
            // An off-anniversary inforce case generates a full
            // year's claims, which is consistent with curtate
            // mortality.

            double eoy_inforce_lives      = 0.0;
            double years_net_claims       = 0.0;
            double years_net_mortchgs     = 0.0;
            double projected_net_mortchgs = 0.0;
            for(i = cell_values.begin(); i != cell_values.end(); ++i)
                {
                if((*i)->PrecedesInforceDuration(year, 11))
                    {
                    continue;
                    }
                (*i)->SetClaims();
                (*i)->SetProjectedCoiCharge();
                eoy_inforce_lives      += (*i)->InforceLivesEoy();
                (*i)->IncrementEOY(year);
                years_net_claims       += (*i)->GetCurtateNetClaimsInforce();
                years_net_mortchgs     += (*i)->GetCurtateNetCoiChargeInforce();
                projected_net_mortchgs += (*i)->GetProjectedCoiChargeInforce();
                }

            // Calculate next year's k factor. Do this only for
            // current-expense bases, not as a speed optimization,
            // but rather because experience rating on other bases
            // is undefined.

            case_accum_net_claims   *= experience_reserve_annual_u;
            case_accum_net_claims   += years_net_claims;

            case_accum_net_mortchgs *= experience_reserve_annual_u;
            case_accum_net_mortchgs += years_net_mortchgs;

            // Presumably an admin system would maintain a scalar
            // reserve instead of tracking claims and mortality
            // charges separately, and accumulate it at interest more
            // frequently than once a year.
            //
            // Therefore, add inforce reserve here, to avoid crediting
            // a year's interest to it. Because only a scalar reserve
            // is captured, it must all be added to one side of the
            // reserve equation: the distinction between claims and
            // mortality charges is lost, but their difference is
            // preserved, so the resulting reserve is correct.
            //
            // The inforce reserve would reflect net claims already
            // paid as well as mortality charges already deducted for
            // any partial year. Therefore, although inforce YTD COI
            // charge is captured separately for adjusting IBNR, it
            // would be incorrect to add it here.

            if(first_cell_inforce_year == year)
                {
                case_accum_net_mortchgs += cell_values[0]->yare_input_.InforceNetExperienceReserve;
                }

            // Apportion experience-rating reserve uniformly across
            // inforce lives. Previously, it had been apportioned by
            // projected mortality charges; that proved unworkable
            // when a cell lapsed, matured, or failed to have a
            // nonzero NAAR due to a corridor factor of unity. To
            // guard against such problems, the apportioned reserve
            // is summed across cells and asserted materially to
            // equal the original total reserve.

            if
                (   cell_values[0]->yare_input_.UseExperienceRating
                &&  mce_gen_curr == expense_and_general_account_basis
                &&  0.0 != eoy_inforce_lives
                )
                {
                if(first_cell_inforce_year == year)
                    {
                    years_net_mortchgs += cell_values[0]->yare_input_.InforceYtdNetCoiCharge;
                    }
                double case_ibnr =
                        years_net_mortchgs
                    *   case_ibnr_months
                    /   12.0
                    ;
                double case_net_mortality_reserve =
                        case_accum_net_mortchgs
                    -   case_accum_net_claims
                    -   case_ibnr
                    ;

                // Current net mortality charge can actually be zero,
                // e.g., when the corridor factor is unity.
                double denominator =
                        case_experience_rating_amortization_years
                    *   projected_net_mortchgs
                    ;
                if(0.0 == denominator)
                    {
                    case_k_factor = 1.0;
                    }
                else
                    {
                    case_k_factor = std::max
                        (0.0
                        ,1.0 - case_net_mortality_reserve / denominator
                        );
                    }

                double case_net_mortality_reserve_checksum = 0.0;
                for(i = cell_values.begin(); i != cell_values.end(); ++i)
                    {
                    if((*i)->PrecedesInforceDuration(year, 11))
                        {
                        continue;
                        }
                    case_net_mortality_reserve_checksum +=
                        (*i)->ApportionNetMortalityReserve
                            (   case_net_mortality_reserve
                            /   eoy_inforce_lives
                            );
                    }
                if
                    (!materially_equal
                        (case_net_mortality_reserve
                        ,case_net_mortality_reserve_checksum
                        )
                    )
                    {
                    fatal_error()
                        << "\nExperience-rating reserve discrepancy in year "
                        << year
                        << ": "
                        << case_net_mortality_reserve
                        << " != "
                        << case_net_mortality_reserve_checksum
                        << LMI_FLUSH
                        ;
                    }
                }

            if(!meter->reflect_progress())
                {
                result.completed_normally_ = false;
                goto done;
                }
            } // End for year.
        meter->culminate();

        for(i = cell_values.begin(); i != cell_values.end(); ++i)
            {
            (*i)->FinalizeLife(*run_basis);
            }

        } // End fenv_guard scope.
        } // End for.

    meter = create_progress_meter
        (cell_values.size()
        ,"Finalizing all cells"
        ,progress_meter_mode(emission)
        );
    for(i = cell_values.begin(); i != cell_values.end(); ++i)
        {
        fenv_guard fg;
        (*i)->FinalizeLifeAllBases();
        composite.PlusEq(*(*i)->ledger_from_av());
        if(!meter->reflect_progress())
            {
            result.completed_normally_ = false;
            goto done;
            }
        }
    meter->culminate();

    result.seconds_for_output_ += emitter.initiate();

    meter = create_progress_meter
        (cell_values.size()
        ,"Writing output for all cells"
        ,progress_meter_mode(emission)
        );
    for(j = 0, i = cell_values.begin(); i != cell_values.end(); ++i, ++j)
        {
        std::string const name(cells[j]["InsuredName"].str());
        result.seconds_for_output_ += emitter.emit_cell
            (serial_file_path(file, name, j, "hastur")
            ,*(*i)->ledger_from_av()
            );
        meter->dawdle(intermission_between_printouts(emission));
        if(!meter->reflect_progress())
            {
            result.completed_normally_ = false;
            goto done;
            }
        }
    meter->culminate();

    result.seconds_for_output_ += emitter.emit_cell
        (serial_file_path(file, "composite", -1, "hastur")
        ,composite
        );
    result.seconds_for_output_ += emitter.finish();

  done:
    double total_seconds = timer.stop().elapsed_seconds();
    status() << Timer::elapsed_msec_str(total_seconds) << std::flush;
    result.seconds_for_calculations_ = total_seconds - result.seconds_for_output_;
    return result;
}
コード例 #24
0
ファイル: persistor_blog.cpp プロジェクト: corentin38/pmb
basics::Persistable_blog basics::Persistor_blog::read_blog(bfs::path content_storage_file)
{
    // Parsing content from file
    rapidxml::xml_document<> content;
    rapidxml::file<> content_file(content_storage_file.string().c_str());

    // Retreiving root node
    content.parse<0>(content_file.data());
    rapidxml::xml_node<> *blog_root = content.first_node("blog");

    // Retreiving config
    rapidxml::xml_node<> *conf = blog_root->first_node("config");
    basics::Configuration_blog config(nv(conf, "meta-desc"),
                                      nv(conf, "meta-author"),
                                      nv(conf, "meta-title"),
                                      nv(conf, "meta-conf-bootstrap"),
                                      nv(conf, "meta-conf-css"),
                                      nvs(conf, "nav-items"),
                                      nv(conf, "home-link"),
                                      nv(conf, "title"),
                                      nv(conf, "subtitle"),
                                      nv(conf, "about"),
                                      av(conf, "about", "line"),
                                      nvs(conf, "links"),
                                      av(conf, "links", "line"),
                                      nv(conf, "philosophy"),
                                      nv(conf, "backtotop"),
                                      std::stoi(nv(conf, "post-per-page")));


    // Iterating over "post" nodes
    rapidxml::xml_node<> *post_node = blog_root->first_node("posts");
    std::vector<basics::Post> posts;
    rapidxml::xml_node<> *post;
    for (post = post_node->first_node("post"); post; post = post->next_sibling("post")) {
        // Attributes
        std::string timestamp_str = post->first_attribute("date")->value();
        std::string author = post->first_attribute("author")->value();

        // title child node
        rapidxml::xml_node<> *title_node = post->first_node("title");
        std::string title = title_node->value();

        // mylife child node
        rapidxml::xml_node<> *life_node = post->first_node("mylife");
        std::string life = basics::unescape_string(life_node->value());

        // Reading editions
        rapidxml::xml_node<> *eds = post->first_node("editions");
        std::vector<std::string> editions;
        rapidxml::xml_node<> *ed;
        for (ed = eds->first_node("edition"); ed; ed = ed->next_sibling("edition")) {
            std::string edition = ed->value();
            editions.push_back(edition);
        }

        // Creating a new Post object from all infos
        basics::Post another_post(title, author, life, timestamp_str);
        another_post.set_editions(editions);

        posts.push_back(another_post);
    }

    basics::Persistable_blog blog_ptr(posts, config);
    return blog_ptr;
}
コード例 #25
0
ファイル: lambda-template4.C プロジェクト: 0day-ci/gcc
int main()
{
  function linear1 = []{};
  function av(animate(linear1));
  av();
}
コード例 #26
0
ファイル: Mesh.cpp プロジェクト: ElliotWood/max_nif_plugin
NiTriBasedGeomRef Exporter::makeMesh(NiNodeRef &parent, Mtl *mtl, FaceGroup &grp, bool exportStrips)
{
	NiTriBasedGeomRef shape;
	NiTriBasedGeomDataRef data;

   //if (Exporter::mFixNormals) {
   //   FixNormals(grp.faces, grp.verts, grp.vnorms);
   //}

	if (exportStrips) {
      shape = new NiTriStrips();
      data = new NiTriStripsData(grp.faces, !mUseAlternateStripper);
	} else {
      shape = new NiTriShape();
      data = new NiTriShapeData(grp.faces);
	}

   if ( IsFallout3() || IsSkyrim() )
      shape->SetFlags( 14 );

   data->SetVertices(grp.verts);
   data->SetNormals(grp.vnorms);
   data->SetVertexIndices(grp.vidx);
   data->SetUVSetMap(grp.uvMapping);

   int nUVs = grp.uvs.size();
   if ( IsFallout3() || IsSkyrim() )
      nUVs = min(1, nUVs);
   data->SetUVSetCount(nUVs);
   for (int i =0;i<nUVs; ++i) {
	   data->SetUVSet(i, grp.uvs[i]);
   }

   //if (IsSkyrim() && grp.vcolors.size() == 0)
   //   grp.vcolors.resize(grp.verts.size(), Color4(1.0f,1.0f,1.0f,1.0f));

	if (mVertexColors && grp.vcolors.size() > 0)
	{
		bool allWhite = true;
		Color4 white(1.0f, 1.0f, 1.0f, 1.0f);
		for (int i=0,n=grp.vcolors.size();i<n; ++i) {
			if (white != grp.vcolors[i]) {
				allWhite = false; 
				break;
			}
		}
		if (!allWhite)
			data->SetVertexColors(grp.vcolors);
	}

	data->SetConsistencyFlags(CT_STATIC);
	shape->SetData(data);

   if (Exporter::mTangentAndBinormalExtraData && (Exporter::mNifVersionInt > VER_4_2_2_0))
   {
      // enable traditional tangents and binormals for non-oblivion meshes
      if ( !IsOblivion() && (Exporter::mNifVersionInt >= VER_10_0_1_0) )
         data->SetTspaceFlag( 0x01 );
	   shape->UpdateTangentSpace(Exporter::mTangentAndBinormalMethod);
   }

	parent->AddChild(DynamicCast<NiAVObject>(shape));

   NiAVObjectRef av(DynamicCast<NiAVObject>(shape));
   makeMaterial(av, mtl);
   shape->SetActiveMaterial(0);

	return shape;
}
コード例 #27
0
ファイル: test4.cpp プロジェクト: UncleHandsome/hcc
int main()
{
    std::array_view<int, 2> v;
    std::array_view<int, 3> av(v);
}
コード例 #28
0
Bool_t MakeCosmicTriggersEntry(const char *fileName, const char* cdbUri)
{
  const char* macroname = "MakeCosmicTriggersEntry.C";

  if (gSystem->AccessPathName(fileName)) {
    Error(macroname,Form("file (%s) not found", fileName));
    return kFALSE;
  }

  ifstream *file = new ifstream(fileName);
  if (!*file) {
    Error(macroname,Form("Error opening file (%s) !",fileName));
    file->close();
    delete file;
    return kFALSE;
  }

  THashTable *table = new THashTable();
  table->SetName("List of defined cosmic triggers");

  TString strLine;
  while (strLine.ReadLine(*file)) {

    if (strLine.BeginsWith("#")) continue;

    strLine.ReplaceAll(" ","");
    strLine.ReplaceAll("\t","");
    if (strLine.IsNull()) continue;

    TObjString *obj = new TObjString(strLine.Data());
    table->Add(obj);
  }

  file->close();
  delete file;


  // create OCDB storage
  TString Storage(cdbUri);
  if(!Storage.BeginsWith("local://") && !Storage.BeginsWith("alien://")) {
    Error(macroname,"STORAGE variable set to %s is not valid. Exiting\n",Storage.Data());
    return kFALSE;
  }
  AliCDBManager* cdb = AliCDBManager::Instance();
  AliCDBStorage* storage = cdb->GetStorage(Storage.Data());
  if(!storage){
    Error(macroname,"Unable to open storage %s\n",Storage.Data());
    return kFALSE;
  }

  AliCDBMetaData* md = new AliCDBMetaData();
  md->SetResponsible("Federico Antinori");
  md->SetComment("List of the defined cosmic triggers. It is used in order to steer the reconstruction, namely in the selection of the proper event specie. It is maintained and updated by the trigger coordinator.");
  // Get root and AliRoot versions and set them in the metadata
  const char* rootv = gROOT->GetVersion();
  TString av(ALIROOT_VERSION);
  TString revnum(ALIROOT_REVISION);
  av+=" - revision: ";
  av+=revnum;
  md->SetAliRootVersion(av.Data());

  AliCDBId id("GRP/Calib/CosmicTriggers",0,AliCDBRunRange::Infinity());
  Info(macroname,"Saving the list of defined cosmic triggers in the OCDB storage \"%s\"",Storage.Data());
  storage->Put(table,id,md);

  table->Delete();
  delete table;

  return kTRUE;
}
コード例 #29
0
int main(int argc, char **argv) {
  parse_cmd(argc, argv);

  cudaSetDevice(device);

  ffloat T = host_omega>0?(2*PI/host_omega):0; // period of external a/c emf
  if( display == 9 ) {
    t_max = t_start + 101*T;
    init_strobe_array();
  } else {
    t_max = t_start + T;
  }
  if( quiet == 0 ) { printf("# t_max = %0.20f kernel=%d\n", t_max, BLTZM_KERNEL); }

  // we will allocate enough memory to accommodate range
  // from -PhiY_max_range to PhiY_max_range, but will use only
  // part of it from PhiYmin to PhiYmax
  ffloat PhiY_max_range = fabs(PhiYmin);
  if( PhiY_max_range < fabs(PhiYmax) ) {
    PhiY_max_range = fabs(PhiYmax);
  }

  //host_dPhi = PhiY_max_range/host_M;
  host_dPhi = (PhiYmax-PhiYmin)/host_M;

  NSIZE = host_N+1;
  //MSIZE = 2*host_M+3;
  MSIZE = host_M+3;
  PADDED_MSIZE = (MSIZE*sizeof(ffloat))%128==0?MSIZE:((((MSIZE*sizeof(ffloat))/128)*128+128)/sizeof(ffloat));
  printf("PADDED MEMORY FROM %d ELEMENTS PER ROW TO %d\n", MSIZE, (int)PADDED_MSIZE);

  MP1 = host_M+1; // 

  SIZE_2D = NSIZE*PADDED_MSIZE;
  const int SIZE_2Df = SIZE_2D*sizeof(ffloat);

  host_TMSIZE=host_M+1;

  host_nu = 1+host_dt/2;
  host_nu2 = host_nu * host_nu;
  host_nu_tilde = 1-host_dt/2;
  host_bdt = host_B*host_dt/(4*host_dPhi);

  load_data();

  // create a0 and populate it with f0
  ffloat *host_a0; host_a0 = (ffloat *)calloc(SIZE_2D, sizeof(ffloat));
  for( int n=0; n<host_N+1; n++ ) {
    ffloat a = gsl_sf_bessel_In(n, host_mu)*(n==0?0.5:1)/(PI*gsl_sf_bessel_In(0, host_mu))*sqrt(host_mu/(2*PI*host_alpha));
    for( int m = 0; m < host_M+3; m++ ) {
      nm(host_a0, n, m) = a*expl(-host_mu*pow(phi_y(m),2)/2);
    }
  }

  // create device_a0 and transfer data from host_a0 to device_a0
  ffloat *a0;
  HANDLE_ERROR(cudaMalloc((void **)&a0, SIZE_2Df));
  HANDLE_ERROR(cudaMemcpy(a0, host_a0, SIZE_2Df, cudaMemcpyHostToDevice));

  // create a and b 2D vectors, four of each. one for current,
  // another for next pointer on main and shifted grids
  ffloat *host_a = (ffloat *)calloc(SIZE_2D, sizeof(ffloat));
  ffloat *host_b = (ffloat *)calloc(SIZE_2D, sizeof(ffloat));

  ffloat *a[4];
  ffloat *b[4];
  for( int i = 0; i < 4; i++ ) {
    HANDLE_ERROR(cudaMalloc((void **)&a[i], SIZE_2Df));
    HANDLE_ERROR(cudaMalloc((void **)&b[i], SIZE_2Df));

    // zero vector b[i]
    HANDLE_ERROR(cudaMemset((void *)a[i], 0, SIZE_2Df));
    HANDLE_ERROR(cudaMemset((void *)b[i], 0, SIZE_2Df));
  }

  int current = 0; int next = 1;
  int current_hs = 2; int next_hs = 3; // 'hs' - half step

  // init vectors a[0] and a[2]
  HANDLE_ERROR(cudaMemcpy(a[current], host_a0, SIZE_2Df,
                          cudaMemcpyHostToDevice));

  int blocks = (host_M+3)/TH_PER_BLOCK;

  // tiptow to the first half step
  ffloat *host_a_hs = (ffloat *)calloc(SIZE_2D, sizeof(ffloat));
  ffloat *host_b_hs = (ffloat *)calloc(SIZE_2D, sizeof(ffloat));
  ffloat cos_omega_t = 1; // cos(host_omega*t); for t = 0
  ffloat cos_omega_t_plus_dt = cos(host_omega*(host_dt));
  step_on_grid(blocks, a0, a[current], b[current], a[current_hs], b[current_hs],
               a[current], b[current], 0, 0,
               cos_omega_t, cos_omega_t_plus_dt);
  /*
  // temporary solution // FIX ME!!!
  memcpy(host_a_hs, host_a, SIZE_2D*sizeof(ffloat));
  HANDLE_ERROR(cudaMemcpy(a[current_hs], host_a_hs,
                          SIZE_2Df, cudaMemcpyHostToDevice));
  HANDLE_ERROR(cudaMemcpy(b[current_hs], host_b_hs,
                          SIZE_2Df, cudaMemcpyHostToDevice));
  */

  // used for file names when generated data for making animation
  char *file_name_buf = (char *)calloc(128, sizeof(char));

  char buf[16384]; // output buffer for writing frame data when display==77

  int step = 0;
  ffloat frame_time = 0; int frame_number = 1;

  ffloat *host_av_data; host_av_data = (ffloat *)calloc(5, sizeof(ffloat));
  ffloat *av_data;
  HANDLE_ERROR(cudaMalloc((void **)&av_data, 6*sizeof(ffloat)));
  HANDLE_ERROR(cudaMemset((void *)av_data, 0, 6*sizeof(ffloat)));

  float t_hs = 0;

  ffloat t0 = 0;
  ffloat t = t0;
  ffloat timeout = -999;

  ffloat last_tT_reminder = 0;

  for(;;) {
    //read_from
    int ccc = 0;
    for( t = t0; t < t_max; t += host_dt ) {
      /// XXX
      //ccc++;
      //if( ccc == 51 ) { break; }

      t_hs = t + host_dt/2;
      cos_omega_t = cos(host_omega*t);
      cos_omega_t_plus_dt = cos(host_omega*(t+host_dt));
      step_on_grid(blocks, a0, a[current], b[current], a[next], b[next], a[current_hs],
                   b[current_hs], t, t_hs,
                   cos_omega_t, cos_omega_t_plus_dt);

      cudaThreadSynchronize();

      cos_omega_t = cos(host_omega*t_hs);
      cos_omega_t_plus_dt = cos(host_omega*(t_hs+host_dt));
      step_on_half_grid(blocks, a0, a[current], b[current], a[next], b[next], a[current_hs],
                        b[current_hs], a[next_hs], b[next_hs], t, t_hs,
                        cos_omega_t, cos_omega_t_plus_dt);

      /*
      if( t >= 0 ) { 
	HANDLE_ERROR(cudaMemcpy(host_a, a[current], SIZE_2Df, cudaMemcpyDeviceToHost));
	HANDLE_ERROR(cudaMemcpy(host_b, b[current], SIZE_2Df, cudaMemcpyDeviceToHost));
          sprintf(file_name_buf, "strobe.data");
          FILE *frame_file_stream = fopen(file_name_buf, "w");
          setvbuf(frame_file_stream, buf, _IOFBF, sizeof(buf));
          printf("\nWriting strobe %s\n", file_name_buf);
          print_2d_strobe(frame_file_stream, MSIZE, host_a0, host_a, host_b, host_alpha, t);
          fclose(frame_file_stream);
          frame_time = 0;

	break; } /// XXX REMOVE ME
      */

      if( host_E_omega > 0 && display == 77 && frame_time >= 0.01) {
        // we need to perform averaging of v_dr, m_x and A
        av(blocks, a[next], b[next], av_data, t);
        HANDLE_ERROR(cudaMemcpy(host_a, a[current], SIZE_2Df, cudaMemcpyDeviceToHost));
        HANDLE_ERROR(cudaMemcpy(host_b, b[current], SIZE_2Df, cudaMemcpyDeviceToHost));
        HANDLE_ERROR(cudaMemcpy(host_av_data, av_data, 6*sizeof(ffloat), cudaMemcpyDeviceToHost));
        ffloat norm = eval_norm(host_a, host_alpha, MSIZE);
        print_time_evolution_of_parameters(out, norm, host_a, host_b, MSIZE,
                                           host_mu, host_alpha, host_E_dc, host_E_omega, host_omega,
                                           host_av_data, t);
        frame_time = 0;
      }

      if( host_E_omega > 0 && display != 7 && display != 77 && display != 8 && t >= t_start ) {
        // we need to perform averaging of v_dr, m_x and A
        av(blocks, a[next], b[next], av_data, t);
      }

      if( current    == 0 ) {    current = 1;    next = 0; } else { current = 0; next = 1; }
      if( current_hs == 2 ) { current_hs = 3; next_hs = 2; } else { current_hs = 2; next_hs = 3; }

      //if( display == 9 && t >= t_start ) {
      //  ffloat tT = t/T;
      //  printf("t=%0.12f %0.12f %0.12f\n", t, , T);
      //}

      if( display == 9 && t >= t_start ) { // XXX PUT ME BACK
        ffloat tT = t/T;
        ffloat tT_reminder = tT-((int)tT);
        if( tT_reminder < last_tT_reminder ) { 
          HANDLE_ERROR(cudaMemcpy(host_a, a[current], SIZE_2Df, cudaMemcpyDeviceToHost));
          HANDLE_ERROR(cudaMemcpy(host_b, b[current], SIZE_2Df, cudaMemcpyDeviceToHost));
          sprintf(file_name_buf, "strobe%08d.data", frame_number++);
          FILE *frame_file_stream = fopen(file_name_buf, "w");
          setvbuf(frame_file_stream, buf, _IOFBF, sizeof(buf));
          printf("\nWriting strobe %s\n", file_name_buf);
          print_2d_strobe(frame_file_stream, MSIZE, host_a0, host_a, host_b, host_alpha, t);
          fclose(frame_file_stream);
          frame_time = 0;
	}
        last_tT_reminder = tT_reminder;
      }

      if( display == 7 && frame_time >= 0.01 && t > frame_start ) { // we are making movie
        HANDLE_ERROR(cudaMemcpy(host_a, a[current], SIZE_2Df, cudaMemcpyDeviceToHost));
        HANDLE_ERROR(cudaMemcpy(host_b, b[current], SIZE_2Df, cudaMemcpyDeviceToHost));
        sprintf(file_name_buf, "frame%08d.data", frame_number++);
        FILE *frame_file_stream = fopen(file_name_buf, "w");
        setvbuf(frame_file_stream, buf, _IOFBF, sizeof(buf));
        printf("\nWriting frame %s\n", file_name_buf);
        print_2d_data(frame_file_stream, MSIZE, host_a0, host_a, host_b, host_alpha, t);
        fclose(frame_file_stream);
        frame_time=0;
      }

      if( out != stdout && display != 7 ) {
        step++;
        if( step == 300 ) {
          printf("\rt=%0.9f %0.2f%%", t, t/t_max*100);
          fflush(stdout);
          step = 0;
        }
      }
      frame_time += host_dt;

      if( display == 9 && t <= t_start && frame_time >= T ) {
        frame_time == 0;
      }
    }

    HANDLE_ERROR(cudaMemcpy(host_a, a[current], SIZE_2Df, cudaMemcpyDeviceToHost));
    HANDLE_ERROR(cudaMemcpy(host_b, b[current], SIZE_2Df, cudaMemcpyDeviceToHost));
    HANDLE_ERROR(cudaMemcpy(host_av_data, av_data, 6*sizeof(ffloat), cudaMemcpyDeviceToHost));

    ffloat norm = 0;
    ffloat dphi_over_2 = host_dPhi/2.0;
    for( int m = 1; m < host_M+1; m++ ) {
      norm += (nm(host_a,0,m)+nm(host_a,0,m))*dphi_over_2;
    }
    norm *= 2*PI*sqrt(host_alpha);

    if( display == 3 ) {
      for( ffloat phi_x = -PI; phi_x < PI; phi_x += 0.01 ) {
        for( int m = 1; m < host_M; m++ ) {
          ffloat value = 0;
          ffloat value0 = 0;
          for( int n = 0; n < host_N+1; n++ ) {
            value  += nm(host_a,n,m)*cos(n*phi_x) + nm(host_b,n,m)*sin(n*phi_x);
            value0 += nm(host_a0,n,m)*cos(n*phi_x);
          }
          fprintf(out, "%0.5f %0.5f %0.20f %0.20f\n", phi_x, phi_y(m), value<0?0:value, value0<0?0:value0);
        }
      }
      fprintf(out, "# norm=%0.20f\n", norm);
      printf("# norm=%0.20f\n", norm);
      //if( out != stdout ) { fclose(out); }
      cuda_clean_up();
      return EXIT_SUCCESS;
    }

    if( display == 8 ) {
      // single shot image
      HANDLE_ERROR(cudaMemcpy(host_a, a[current], SIZE_2Df, cudaMemcpyDeviceToHost));
      HANDLE_ERROR(cudaMemcpy(host_b, b[current], SIZE_2Df, cudaMemcpyDeviceToHost));
      sprintf(file_name_buf, "frame.data");
      FILE *frame_file_stream = fopen(file_name_buf, "w");
      setvbuf(frame_file_stream, buf, _IOFBF, sizeof(buf));
      printf("\nWriting frame %s\n", file_name_buf);
      print_2d_data(frame_file_stream, MSIZE, host_a0, host_a, host_b, host_alpha, t);
      fclose(frame_file_stream);
      frame_time=0;
      return EXIT_SUCCESS;
    }

    if( display == 4 ) {
      if( quiet == 0 ) { printf("\n# norm=%0.20f\n", norm); }
      ffloat v_dr_inst = 0 ;
      ffloat v_y_inst = 0;
      ffloat m_over_m_x_inst = 0;
      for( int m = 1; m < host_M; m++ ) {
        v_dr_inst += nm(host_b,1,m)*host_dPhi;
        v_y_inst  += nm(host_a,0,m)*phi_y(m)*host_dPhi;
        m_over_m_x_inst += nm(host_a,1,m)*host_dPhi;
      }

      ffloat v_dr_multiplier = 2*gsl_sf_bessel_I0(host_mu)*PI*sqrt(host_alpha)/gsl_sf_bessel_In(1, host_mu);
      ffloat v_y_multiplier  = 4*PI*gsl_sf_bessel_I0(host_mu)/gsl_sf_bessel_In(1, host_mu);
      ffloat m_over_multiplier = PI*host_alpha*sqrt(host_alpha);
      v_dr_inst       *= v_dr_multiplier;
      v_y_inst        *= v_y_multiplier;
      m_over_m_x_inst *= m_over_multiplier;

      host_av_data[1] *= v_dr_multiplier;
      host_av_data[2] *= v_y_multiplier;
      host_av_data[3] *= m_over_multiplier;
      host_av_data[4] *= v_dr_multiplier;
      host_av_data[4] /= T;
      host_av_data[5] *= v_dr_multiplier;
      host_av_data[5] /= T;

      fprintf(out, "# display=%d E_dc=%0.20f E_omega=%0.20f omega=%0.20f mu=%0.20f alpha=%0.20f n-harmonics=%d PhiYmin=%0.20f PhiYmax=%0.20f B=%0.20f t-max=%0.20f dt=%0.20f g-grid=%d\n",
                      display,   host_E_dc,  host_E_omega,  host_omega,  host_mu,  host_alpha,  host_N,        PhiYmin,       PhiYmax,       host_B,  t_start,     host_dt,  host_M);
      fprintf(out, "#E_{dc}                \\tilde{E}_{\\omega}     \\tilde{\\omega}         mu                     v_{dr}/v_{p}         A(\\omega)              NORM     v_{y}/v_{p}    m/m_{x,k}   <v_{dr}/v_{p}>   <v_{y}/v_{p}>    <m/m_{x,k}>    Asin\n");
      fprintf(out, "%0.20f %0.20f %0.20f %0.20f %0.20f %0.20f %0.20f %0.20f %0.20f %0.20f %0.20f %0.20f %0.20f\n",
              host_E_dc, host_E_omega, host_omega, host_mu, v_dr_inst, host_av_data[4], norm, v_y_inst,
              m_over_m_x_inst, host_av_data[1], host_av_data[2], host_av_data[3], host_av_data[5]);
    }

    if( read_from == NULL ) { break; }

    // scan for new parameters
    timeout = scan_for_new_parameters();
    if( timeout < -900 ) { break; } // user entered 'exit'
    t_start = t + timeout;
    t_max = t_start + T;
    t0 = t + host_dt;
    T=host_omega>0?(2*PI/host_omega):0;
    load_data(); // re-load data
    HANDLE_ERROR(cudaMemset((void *)av_data, 0, 6*sizeof(ffloat))); // clear averaging data
    if( quiet == 0 ) { printf("# t_max = %0.20f\n", t_max); }
  } // for(;;)

  if( out != NULL && out != stdout ) {
    fclose(out);
  }
  cuda_clean_up();
  return EXIT_SUCCESS;
} // end of main(...)
コード例 #30
0
ファイル: average_main.cpp プロジェクト: dtegunov/tom
/****************************************************************************//**
 *
 *
 *******************************************************************************/
int main(int argc, char *argv[]) {

    typedef double TFLOAT;

    if (argc<5 || argc>8) {
        std::cerr << "Usage: " << (argc?argv[0]:"average") << " CONFIG_FILE FTEMPLATES FPARTICLES [LOGFILE] [DO_FSC] [WEDGE_THRESHOLD]"               "\n"
                     "compiled at " __DATE__ " " __TIME__ " from " __FILE__                                                         "\n"
                     "  CONFIG_FILE     : filename of the parallel correlation program."                                                 "\n"
                     "  FTEMPLATES      : filename of the textfile with the names of the templates."                                     "\n"
                     "  FPARTICLES      : filename of the textfile with the names of the particles."                                     "\n"
                     "  ANGLES          : filename of the textfile with the angles."                                                     "\n"
                     "  LOGFILE         : optional parameter for the log file. '-' for STDOUT."                                          "\n"
                     "  DO_FSC          : optional parameter to decide whether to compute the FSC (yes or no)."                          "\n"
                     "  WEDGE_THRESHOLD : Voxels of the averaged wedge are set to zero if they are SMALLER then WEDGE_THRESHOLD% of the number of particles (default 0 == no cutoff)."  << std::endl;
        return -1;
    }

    double use_threshold = 0.005;
    if (argc >= 8) {
        try {
            use_threshold = boost::lexical_cast<double>(argv[7]);
        } catch (boost::bad_lexical_cast &) {
            throw std::invalid_argument("The WEDGE_THRESHOLD must be a floating point number.");
        }
        if (use_threshold > 1 && use_threshold <= 100) {
            use_threshold = use_threshold/100.;
        }
        if (use_threshold > 1 || use_threshold <= 0) {
            throw std::invalid_argument("WEDGE_THRESHOLD must be either a prozentual value ]1, 100] or relative between ]0.0, 1.0].");
        }
    }

    bool do_fourier_shell = true;
    if (argc >= 7) {
        std::string p(argv[6]);
        std::transform(p.begin(), p.end(), p.begin(), &toupper);
        if (p=="YES" || p=="1" || p=="FSC" || p=="TRUE") {
            do_fourier_shell = true;
        } else if (p=="NO" || p=="0" || p=="FALSE") {
            do_fourier_shell = false;
        } else {
            std::cerr << "Argument 6 (do_fsc) must be either \"yes\" or \"no\"." << std::endl;
            return -2;
        }
    }


    std::size_t itemplate, iparticle, ntemplates, nparticles, i;

    std::vector<std::string> ftemplates, fparticles;
    std::vector<boost::shared_ptr<tom::Volume<double> > > angles;
    std::vector<helper::triple<double, double, double> > anglesv;
    std::vector<boost::shared_ptr<tom::WedgeDescriptor<TFLOAT> > > wedge_templates, wedge_particles;
    std::vector<tom::cc_peak<TFLOAT> > peak_list;
    tom::corr::ConfigDataServer c;
    std::string outputdir;

    std::stringstream clog;
    std::auto_ptr<std::ofstream> f;
    std::auto_ptr<helper::ostream_swapper> stream_swapper;
    clog.precision(20);
    clog << "# start " << (argc>0?argv[0]:"average") << " at " << helper::now2str() << " (compiled at " __DATE__ " " __TIME__ ")." << std::endl;

    // Parse the input files.
    clog << "# parse configuration (" << argv[1] << ")" << std::endl;
    c.read_from_conf(argv[1]);
    clog << "# parse filelist for templates (" << argv[2] << ")" << std::endl;
    tom::corr::parse_filelist(argv[2], ftemplates, wedge_templates, 1);
    ntemplates = ftemplates.size();
    clog << "#   " << ntemplates << " templates read.\n"
            "# parse filelist for particles (" << argv[3] << ")" << std::endl;
    tom::corr::parse_filelist(argv[3], fparticles, wedge_particles, 1);
    nparticles = fparticles.size();
    clog << "#   " << nparticles << " particles read.\n"
            "# parse the list of angles (" << argv[4] << ")" << std::endl;
    tom::corr::parse_angleslist(argv[4], ntemplates, nparticles, angles);
    clog << "# parse peak list (" << c.peakfilename << ")" << std::endl;
    tom::corr::parse_peaklist(c.peakfilename, peak_list, anglesv, ntemplates, nparticles);

    clog << "#\n# use a threshold for the wedge of " << use_threshold << "\n# (values in the summed wedge are set to zero if they are smaller then the relative threshold compared to the number of particles).\n" << std::endl;

    tom::avg::filename_generator f_gen(c.outputdir);


    // open the logfile.
    {
        std::ostream *use_log = &std::clog;

        std::string logfilename(argc>=6 ? argv[5] : "-");
        if (logfilename != "-") {
            f.reset(new std::ofstream(logfilename.c_str(), std::ios::out | std::ios::trunc));
            if (!f->good()) {
                f.reset(NULL);
                clog << "# ERROR: could not open log-file \"" << logfilename << "\" for writing. Use CERR instead." << std::endl;
            } else {
                use_log = f.get();
            }
        }
        *use_log << clog.rdbuf() << std::flush;
        clog.clear();
        stream_swapper.reset(new helper::ostream_swapper(clog, *use_log));
    }



    // Find out, which particles average to which template.
    std::vector<std::vector<std::size_t> > use_particles(ntemplates), use_particles1(ntemplates), use_particles2(ntemplates), use_particles3(ntemplates);
    for (iparticle=0; iparticle<nparticles; iparticle++) {
        std::size_t max_index = ntemplates;
        double max_ccvalue = - std::numeric_limits<double>::infinity();
        for (itemplate=0; itemplate<ntemplates; itemplate++) {
            i = itemplate * nparticles + iparticle;

            if (angles[i].get()) {
                assert(angles[i]->getSizeX()==3 && angles[i]->getSizeZ()==1);

                if (peak_list[i].angle_idx < 0) {
                    clog << "# WARNING: no peak found for template #" << itemplate << ", particle #" << iparticle << "." << std::endl;
                    continue;
                } else {
                    if (static_cast<std::size_t>(peak_list[i].angle_idx) >= angles[i]->getSizeY()) {
                        clog << "# WARNING: peak-index for template #" << itemplate << ", particle #" << iparticle << " is larger then the entire angle-list (" << peak_list[i].angle_idx << " vs. " << angles[i]->getSizeY() << "). Using peak from file." << std::endl;
                    } else {
                        boost::tuples::tuple<double &, double &, double &> a = boost::tuples::tie(angles[i]->get(0, peak_list[i].angle_idx, 0), angles[i]->get(0, peak_list[i].angle_idx, 0), angles[i]->get(0, peak_list[i].angle_idx, 0));
                        if (fabs(a.get<0>()-anglesv[i].x)>1e-7 || fabs(a.get<0>()-anglesv[i].x)>1e-7 || fabs(a.get<0>()-anglesv[i].x)>1e-7) {
                            clog << "# WARNING: peak-index for template #" << itemplate << ", particle #" << iparticle << " differs from angles list and peakfile: (" << a.get<0>() << " vs. " << anglesv[i].x << "; " << a.get<0>() << " vs. " << anglesv[i].x << "; " << a.get<0>() << " vs. " << anglesv[i].x << "). Take from peak-file." << std::endl;
                        }
                    }
                }
            } else {
                if (peak_list[i].angle_idx >= 0) {
                    clog << "# WARNING: peak-index for template #" << itemplate << ", particle #" << iparticle << " given, but the angles list is empty. Using peak from file." << std::endl;
                } else {
                    // everything is fine.
                    continue;
                }
            }
            const double shiftx = - peak_list[i].x;
            const double shifty = - peak_list[i].y;
            const double shiftz = - peak_list[i].z;
            if (fabs(shiftx) > c.volsize/2 || fabs(shifty) > c.volsize/2 || fabs(shiftz) > c.volsize/2) {
                clog << "# WARNING: the shift of template #" << itemplate << ", particle #" << iparticle << " is too large for the volume of size " << c.volsize << " (" << shiftx << "," << shifty << "," << shiftz << ")." << std::endl;
                continue;
            }

            if (max_index==ntemplates || max_ccvalue<peak_list[i].val) {
                max_ccvalue = peak_list[i].val;
                max_index = itemplate;
            }
        }
        if (max_index != ntemplates) {
            use_particles[max_index].push_back(iparticle);
        }
    }

    // Split the list of particles in two sets for the FSC.
    if (do_fourier_shell) {
        for (itemplate=0; itemplate<ntemplates; itemplate++) {
            std::size_t size = use_particles[itemplate].size();
            if (size >= 2) {
                const std::vector<std::size_t> &v_ = use_particles [itemplate];
                std::vector<std::size_t> &v1 = use_particles1[itemplate];
                std::vector<std::size_t> &v2 = use_particles2[itemplate];
                std::vector<std::size_t> &v3 = use_particles3[itemplate];
                v1.resize(0);
                v2.resize(0);
                v3.resize(0);
                if (size%2) {
                    size--;
                    v3.push_back(v_[size]);
                }
                v1.reserve(size/2);
                v2.reserve(size/2);
                for (iparticle=0; iparticle<size; iparticle+=2) { v1.push_back(v_[iparticle]); }
                for (iparticle=1; iparticle<size; iparticle+=2) { v2.push_back(v_[iparticle]); }
            }
        }
    } else {
        clog << "# don't compute the Fourier Shell Correlation." << std::endl;
    }


    // Init the spheremask
    std::auto_ptr<const tom::Volume<TFLOAT> > mask_sphere;
    if (c.sphere_mask_inner_radius>0 || c.sphere_mask_sigma>0) {
        tom::Volume<TFLOAT> *p;
        mask_sphere.reset(p = new tom::Volume<TFLOAT>(c.volsize, c.volsize, c.volsize, NULL,NULL));
        tom::init_spheremask(*p, c.sphere_mask_inner_radius, c.sphere_mask_sigma, c.sphere_mask_cutoff_radius);
    }



    tom::Volume<TFLOAT> avg(c.volsize, c.volsize, c.volsize, tom::fftw::fftw_malloc<TFLOAT>(), tom::fftw::fftw_free<TFLOAT>());
    tom::Volume<TFLOAT> avgwedge(c.volsize, c.volsize, c.volsize, NULL,NULL);
    tom::Volume<TFLOAT> avgwedge_half(avgwedge, NULL, c.volsize, c.volsize, c.volsize/2+1, avgwedge.getStrideX(), avgwedge.getStrideY(), avgwedge.getStrideZ());
    tom::Volume<TFLOAT> avgwedge_sqrtn(c.volsize, c.volsize, c.volsize, NULL,NULL);
    tom::Volume<TFLOAT> avgwedge_sqrtn_half(avgwedge_sqrtn, NULL, c.volsize, c.volsize, c.volsize/2+1, avgwedge.getStrideX(), avgwedge.getStrideY(), avgwedge.getStrideZ());
    tom::Volume<TFLOAT> avg2(c.volsize, c.volsize, c.volsize, NULL,NULL);
    tom::Volume<TFLOAT> avgwedge2(c.volsize, c.volsize, c.volsize, NULL,NULL);
    tom::Volume<TFLOAT> avgwedge2_half(avgwedge2, NULL, c.volsize, c.volsize, c.volsize/2+1, avgwedge2.getStrideX(), avgwedge2.getStrideY(), avgwedge2.getStrideZ());
    tom::Volume<std::complex<TFLOAT> > avg_ft(c.volsize, c.volsize, c.volsize/2+1, tom::fftw::fftw_malloc<TFLOAT>(), tom::fftw::fftw_free<TFLOAT>());
    tom::Volume<std::complex<TFLOAT> > avg_ft2(c.volsize, c.volsize, c.volsize/2+1, tom::fftw::fftw_malloc<TFLOAT>(), tom::fftw::fftw_free<TFLOAT>());

    tom::fftw::Plan<TFLOAT> plan_fwd(avg2, avg_ft, c.fftw_flag | FFTW_DESTROY_INPUT);
    tom::fftw::Plan<TFLOAT> plan_bwd(avg_ft, avg2, c.fftw_flag | FFTW_DESTROY_INPUT);

    std::auto_ptr<tom::Volume<TFLOAT> > vtemplate;
    tom::Volume<std::complex<TFLOAT> > vtemplate_ft(c.volsize, c.volsize, c.volsize/2+1, tom::fftw::fftw_malloc<TFLOAT>(), tom::fftw::fftw_free<TFLOAT>());
    tom::fftw::Plan<TFLOAT> plan_vtemplate(avg, vtemplate_ft, c.fftw_flag | FFTW_DESTROY_INPUT);


    // Volumes for the fourier shell correlation.
    std::auto_ptr<tom::Volume<TFLOAT> > FSC_v, FSC_w2;
    std::auto_ptr<tom::Volume<std::complex<TFLOAT> > > FSC_f1, FSC_f2, FSC_f1_half, FSC_f2_half;
    std::auto_ptr<tom::fftw::Plan<TFLOAT> > FSC_plan1, FSC_plan2;
    if (do_fourier_shell) {
        FSC_v.reset(        new tom::Volume<TFLOAT>(c.volsize, c.volsize, c.volsize, tom::fftw::fftw_malloc<TFLOAT>(), tom::fftw::fftw_free<TFLOAT>()));
        FSC_f1.reset(       new tom::Volume<std::complex<TFLOAT> >(c.volsize, c.volsize, c.volsize, tom::fftw::fftw_malloc<TFLOAT>(), tom::fftw::fftw_free<TFLOAT>()));
        FSC_f2.reset(       new tom::Volume<std::complex<TFLOAT> >(c.volsize, c.volsize, c.volsize, tom::fftw::fftw_malloc<TFLOAT>(), tom::fftw::fftw_free<TFLOAT>()));
        FSC_f1_half.reset(  new tom::Volume<std::complex<TFLOAT> >(*FSC_f1, NULL, c.volsize, c.volsize, c.volsize/2+1, FSC_f1->getStrideX(), FSC_f1->getStrideY(), FSC_f1->getStrideZ()));
        FSC_f2_half.reset(  new tom::Volume<std::complex<TFLOAT> >(*FSC_f2, NULL, c.volsize, c.volsize, c.volsize/2+1, FSC_f2->getStrideX(), FSC_f2->getStrideY(), FSC_f2->getStrideZ()));
        FSC_plan1.reset(    new tom::fftw::Plan<TFLOAT>(*FSC_v, *FSC_f1_half, c.fftw_flag | FFTW_DESTROY_INPUT));
        FSC_plan2.reset(    new tom::fftw::Plan<TFLOAT>(*FSC_v, *FSC_f2_half, c.fftw_flag | FFTW_DESTROY_INPUT));
        FSC_w2.reset(       new tom::Volume<TFLOAT>(c.volsize, c.volsize, c.volsize/2+1, tom::fftw::fftw_malloc<TFLOAT>(), tom::fftw::fftw_free<TFLOAT>()));
    }


    double mean, variance;

    std::vector<std::size_t>::const_iterator culvit; // Const Unsigned Long Vector ITerator

    std::vector<tom::avg::st_average_result> av(ntemplates);

    double threshold = 1;

    // Now compute the average, the FSC, the CC and save it to file.
    for (itemplate=0; itemplate<ntemplates; itemplate++) {
        const std::vector<std::size_t> &v_ = use_particles [itemplate];
        const std::vector<std::size_t> &v1 = use_particles1[itemplate];
        const std::vector<std::size_t> &v2 = use_particles2[itemplate];
        const std::vector<std::size_t> &v3 = use_particles3[itemplate];

        threshold = v_.size()*use_threshold; // cut off.

        assert(std::set<std::size_t>(v_.begin(), v_.end()).size() == v_.size() &&
               (!do_fourier_shell || (v_.size()<2 || v_.size()==(v1.size()+v2.size()+v3.size()))));

        if (v_.empty()) {
            continue;
        }

        tom::avg::st_average_result &ar = av[itemplate];
        ar.use_idx = v_;

        // Read the original template from file.
        try {
            tom::Volume<TFLOAT> *p;
            tom::read_from_em(p, ftemplates[itemplate], NULL,NULL,NULL, NULL, NULL,NULL);
            vtemplate.reset(p);
        } catch (std::exception &e) {
            std::stringstream ss;
            ss << "# The template #" << itemplate << " (" << ftemplates[itemplate] << ") does not exist.";
            if (c.force_files_exist) {
                clog << ss.str() << " ABORT";
                throw;
            }
            clog << ss << " SKIP CC correlation.";
            vtemplate.reset(NULL);
        }
        if (vtemplate.get()) {
            // normalise it and compute its fourier transformation.
            vtemplate->stat(mean, variance, false);
            vtemplate->shift_scale<TFLOAT>(-mean, 1./sqrt(variance));
            avg.setValues(*vtemplate);
            plan_vtemplate.execute(avg, vtemplate_ft);
        }


        // Average the particles.

        if (!v1.empty() && v1.size()==v2.size()) {
            assert(do_fourier_shell);
            tom::avg::average(c.volsize, fparticles, wedge_particles, v1, itemplate, mask_sphere.get(), peak_list, anglesv, c.force_files_exist, &clog, avg, avgwedge_half);
            tom::avg::average(c.volsize, fparticles, wedge_particles, v2, itemplate, mask_sphere.get(), peak_list, anglesv, c.force_files_exist, &clog, avg2, avgwedge2_half);

            std::vector<double> res;
            std::size_t n_shells = c.volsize/2;

            FSC_w2->setValues(avgwedge_half);
            tom::element_wise_set_below_threshold<TFLOAT>(*FSC_w2, threshold*v1.size()/static_cast<double>(v_.size()), 0);
            tom::avg::apply_avgwedge(avg, *FSC_w2, mask_sphere.get(), c.fftw_flag, *FSC_v);
            //FSC_v->setValues(avg);
            //FSC_v->write_to_em("FSC_v1.em", NULL);
            FSC_plan1->execute(*FSC_v, *FSC_f1_half);

            FSC_w2->setValues(avgwedge2_half);
            tom::element_wise_set_below_threshold<TFLOAT>(*FSC_w2, threshold*v2.size()/static_cast<double>(v_.size()), 0);
            tom::avg::apply_avgwedge(avg2, *FSC_w2, mask_sphere.get(), c.fftw_flag, *FSC_v);
            //FSC_v->setValues(avg2);
            //FSC_v->write_to_em("FSC_v2.em", NULL);
            FSC_plan2->execute(*FSC_v, *FSC_f2_half);

            tom::fourier_shell_correlation(*FSC_f1_half, false, *FSC_f2_half, false, c.volsize, n_shells, res);

            ar.fsc.resize(n_shells);
            for (std::size_t i=0; i<n_shells; i++) {
                ar.fsc[i].first  = res[i+n_shells*1];
                ar.fsc[i].second = res[i+n_shells*7];
            }

            //tom::Volume<double>(&res[0], n_shells, 11, 1, 0,0,0, false, NULL).write_to_em("FSC_cc.em", NULL);

            tom::element_wise_add<TFLOAT, TFLOAT>(avg, avg2);
            tom::element_wise_add<TFLOAT, TFLOAT>(avgwedge_half, avgwedge2_half);
            if (!v3.empty()) {
                // Add the missing partivle to the average.
                tom::avg::average(c.volsize, fparticles, wedge_particles, v3, itemplate, mask_sphere.get(), peak_list, anglesv, c.force_files_exist, &clog, avg2, avgwedge2_half);
                tom::element_wise_add<TFLOAT, TFLOAT>(avg, avg2);
                tom::element_wise_add<TFLOAT, TFLOAT>(avgwedge_half, avgwedge2_half);
            }
        } else {
            tom::avg::average(c.volsize, fparticles, wedge_particles, v_, itemplate, mask_sphere.get(), peak_list, anglesv, c.force_files_exist, &clog, avg, avgwedge_half);
        }

        ////////////////////////////////////////////////////////////////////////
        // Save the average volume (the pure sum): avg_s
        avg.write_to_em(f_gen.get_avg_s(itemplate), NULL);
        tom::hermitian_symmetry_to_full(avgwedge);
        tom::fftshift(avgwedge, avgwedge2, true);
        avgwedge2.write_to_em(f_gen.get_avgwedge_s(itemplate), NULL);
        if (vtemplate.get()) {
            // Compute the correlation with the original template.
            avg.stat(mean, variance, false);
            if (variance) {
                avg2.setValues(avg); // make a copy for normalising.
                avg2.shift_scale<TFLOAT>(-mean, 1./sqrt(variance));
                plan_fwd.execute(avg2, avg_ft);
                tom::element_wise_conj_multiply<std::complex<TFLOAT>, std::complex<TFLOAT> >(avg_ft, vtemplate_ft);
                plan_bwd.execute(avg_ft, avg2);
                ar.ccval_s.reset(new double((avg2.get(0,0,0)/avg2.numel())/avg2.numel()));
            }
        }
        ////////////////////////////////////////////////////////////////////////

        // Set values below threshold in volume to 0
        tom::element_wise_set_below_threshold<TFLOAT>(avgwedge_half, threshold, 0);
        tom::hermitian_symmetry_to_full(avgwedge);

        avg2.setValues(avg);
        plan_fwd.execute(avg2, avg_ft);
        avg_ft2.setValues(avg_ft);

        ////////////////////////////////////////////////////////////////////////
        // Compute the average with frequencies weighted by N
        set_where_binary_mask_not_set<std::complex<TFLOAT>, TFLOAT>(avg_ft, avgwedge_half, 0);
        avg_ft.get(0,0,0) = 0;
        plan_bwd.execute(avg_ft, avg2);
        if (mask_sphere.get()) {
            tom::norm_mask<TFLOAT, TFLOAT, double>(avg2, *mask_sphere, tom::norm::NORM_STDDEV_1, NULL, true);
        } else {
            if ((variance=avg2.variance_mean_free(false))) {
                avg2.shift_scale<TFLOAT>(0, 1./sqrt(variance));
            }
        }
        avg2.write_to_em(f_gen.get_avg_n(itemplate), NULL);
        tom::fftshift(avgwedge, avgwedge2, true);
        avgwedge2.write_to_em(f_gen.get_avgwedge_n(itemplate), NULL);
        if (vtemplate.get()) {
            // Compute the correlation with the original template.
            avg2.stat(mean, variance, false);
            if (variance) {
                avg2.shift_scale<TFLOAT>(-mean, 1./sqrt(variance));
                plan_fwd.execute(avg2, avg_ft);
                tom::element_wise_conj_multiply<std::complex<TFLOAT>, std::complex<TFLOAT> >(avg_ft, vtemplate_ft);
                plan_bwd.execute(avg_ft, avg2);
                ar.ccval_n.reset(new double((avg2.get(0,0,0)/avg2.numel())/avg2.numel()));
            }
        }
        ////////////////////////////////////////////////////////////////////////

        ////////////////////////////////////////////////////////////////////////
        // Compute the average with frequencies weighted by sqrt(N)
        avgwedge_sqrtn_half.setValues(avgwedge_half);
        tom::element_wise_operation(avgwedge_sqrtn_half, &tom::math::sqrt<TFLOAT>);
        avg_ft.setValues(avg_ft2);
        tom::element_wise_div<std::complex<TFLOAT>, TFLOAT>(avg_ft, avgwedge_sqrtn_half, std::complex<TFLOAT>(0,0));
        avg_ft.get(0,0,0) = 0;
        plan_bwd.execute(avg_ft, avg2);
        if (mask_sphere.get()) {
            tom::norm_mask<TFLOAT, TFLOAT, double>(avg2, *mask_sphere, tom::norm::NORM_STDDEV_1, NULL, true);
        } else {
            if ((variance=avg2.variance_mean_free(false))) {
                avg2.shift_scale<TFLOAT>(0, 1./sqrt(variance));
            }
        }
        avg2.write_to_em(f_gen.get_avg_sqrtn(itemplate), NULL);
        tom::hermitian_symmetry_to_full(avgwedge_sqrtn);
        tom::fftshift(avgwedge_sqrtn, avgwedge2, true);
        avgwedge2.write_to_em(f_gen.get_avgwedge_sqrtn(itemplate), NULL);
        if (vtemplate.get()) {
            // Compute the correlation with the original template.
            avg2.stat(mean, variance, false);
            if (variance) {
                avg2.shift_scale<TFLOAT>(-mean, 1./sqrt(variance));
                plan_fwd.execute(avg2, avg_ft);
                tom::element_wise_conj_multiply<std::complex<TFLOAT>, std::complex<TFLOAT> >(avg_ft, vtemplate_ft);
                plan_bwd.execute(avg_ft, avg2);
                ar.ccval_sqrtn.reset(new double((avg2.get(0,0,0)/avg2.numel())/avg2.numel()));
            }
        }
        ////////////////////////////////////////////////////////////////////////

        ////////////////////////////////////////////////////////////////////////
        // Compute the average with frequencies weighted by 1
        avgwedge2_half.setValues(avgwedge_half);
        avg_ft.setValues(avg_ft2);
        tom::element_wise_div<std::complex<TFLOAT>, TFLOAT>(avg_ft, avgwedge2_half, std::complex<TFLOAT>(0,0));
        avg_ft.get(0,0,0) = 0;
        plan_bwd.execute(avg_ft, avg2);
        if (mask_sphere.get()) {
            tom::norm_mask<TFLOAT, TFLOAT, double>(avg2, *mask_sphere, tom::norm::NORM_STDDEV_1, NULL, true);
        } else {
            if ((variance=avg2.variance_mean_free(false))) {
                avg2.shift_scale<TFLOAT>(0, 1./sqrt(variance));
            }
        }
        avg2.write_to_em(f_gen.get_avg_1(itemplate), NULL);
        tom::make_binary(avgwedge2);
        tom::hermitian_symmetry_to_full(avgwedge2);
        tom::fftshift(avgwedge2, avgwedge, true);
        avgwedge.write_to_em(f_gen.get_avgwedge_1(itemplate), NULL);
        if (vtemplate.get()) {
            // Compute the correlation with the original template.
            avg2.stat(mean, variance, false);
            if (variance) {
                avg2.shift_scale<TFLOAT>(-mean, 1./sqrt(variance));
                plan_fwd.execute(avg2, avg_ft);
                tom::element_wise_conj_multiply<std::complex<TFLOAT>, std::complex<TFLOAT> >(avg_ft, vtemplate_ft);
                plan_bwd.execute(avg_ft, avg2);
                ar.ccval_1.reset(new double((avg2.get(0,0,0)/avg2.numel())/avg2.numel()));
            }
        }
        ////////////////////////////////////////////////////////////////////////

    }

    tom::avg::write_average_to_log(clog, ftemplates, fparticles, av, c.outputdir);

    clog << "# finished at " << helper::now2str() << std::endl;

    return 0;
}