Exemplo n.º 1
0
/**
 *
 * Execute the best play
 *
 * */
zet Agent::play(board& b,bool player){
	this->playing_color = player;
	if (lapse(get_generator())){
		std::vector<zet> s = enumerate_moves(b,player); 
		int rn_n = std::uniform_int_distribution<int>(0,s.size()-1)(get_generator());
		FILE_LOG(logDEBUG)<<" * lapsing - returning random move" <<std::endl;
		return s[rn_n];
	}
	std::vector<zet> s = solve(b,player); 
	FILE_LOG(logDEBUG)<<"Playing for player "<<((player==BLACK)?"BLACK":"WHITE")<< " there are "<< s.size() <<" moves" << std::endl;
	FILE_LOG(logDEBUG)<<" board is :" <<b<<std::endl;
	if(s.empty()){
		FILE_LOG(logERROR)<<" board with no moves "<<b <<std::endl;
	}
	assert(!s.empty());
	zet r;
	//std::random_shuffle(s.begin(),s.end());
	if (player == BLACK || is_negamax()){
		r=*std::max_element(s.begin(),s.end(),[](const zet& z1, const zet& z2 ){ return z1.val < z2.val;});
	} else{
		r=*std::min_element(s.begin(),s.end(),[](const zet& z1, const zet& z2 ){ return z1.val < z2.val;});
	}
	FILE_LOG(logDEBUG)<<((player==BLACK)?"BLACK":"WHITE")<<" playes move "<<r.zet_id<<" with value:"<<r.val <<std::endl;
	return r;
}
Exemplo n.º 2
0
void CPortmap::freePorts(San2::Utils::CProducerConsumer<std::shared_ptr<San2::Network::CCapsule> > *applicationQueue)
{
    FILE_LOG(logDEBUG4) << "CPortmap::freePorts():: freeing ports \n";
    // thanks to http://stackoverflow.com/questions/4600567/c-deleting-elements-with-iterator

    std::function<bool (std::pair<unsigned short int, San2::Utils::CProducerConsumer<std::shared_ptr<San2::Network::CCapsule> >*>)> shouldDelete = [applicationQueue] (std::pair<unsigned short int, San2::Utils::CProducerConsumer<std::shared_ptr<San2::Network::CCapsule> >*> pair) -> bool
    {
        return pair.second == applicationQueue;
    };

    std::map<unsigned short int, San2::Utils::CProducerConsumer<std::shared_ptr<San2::Network::CCapsule> >*>::iterator itr = mapPorts.begin();
    while (itr != mapPorts.end())
    {
        if (shouldDelete(*itr))
        {
            std::map<unsigned short int, San2::Utils::CProducerConsumer<std::shared_ptr<San2::Network::CCapsule> >*>::iterator toErase = itr;
            ++itr;
            mapPorts.erase(toErase);
            FILE_LOG(logDEBUG4) << "CPortmap::freePorts():: port has been freed OK\n";
        }
        else
        {
            ++itr;
        }
    }
}
Exemplo n.º 3
0
void ColaTopologyAddon::handleResizes(const cola::Resizes& resizeList,
        unsigned n, std::valarray<double>& X, std::valarray<double>& Y, 
        cola::CompoundConstraints& ccs, vpsc::Rectangles& boundingBoxes,
        cola::RootCluster* clusterHierarchy)
{
    FILE_LOG(cola::logDEBUG) << "ColaTopologyAddon::handleResizes()...";
    if(topologyNodes.empty()) {
        COLA_ASSERT(topologyRoutes.empty());
        return;
    }
    // all shapes to be resized are wrapped in a ResizeInfo and
    // placed in a lookup table, resizes, indexed by id
    ResizeMap resizes;
    for(cola::Resizes::const_iterator r=resizeList.begin();r!=resizeList.end();++r) {
        topology::ResizeInfo ri(topologyNodes[r->getID()],r->getTarget());
        resizes.insert(std::make_pair(r->getID(),ri));
    }
    vpsc::Variables xvs, yvs;
    vpsc::Constraints xcs, ycs;
    cola::setupVarsAndConstraints(n, ccs, vpsc::HORIZONTAL, boundingBoxes,
            clusterHierarchy, xvs, xcs, X);
    cola::setupVarsAndConstraints(n, ccs, vpsc::VERTICAL, boundingBoxes,
            clusterHierarchy, yvs, ycs, Y);
    topology::applyResizes(topologyNodes, topologyRoutes, clusterHierarchy,
            resizes, xvs, xcs, yvs, ycs);
    for_each(xvs.begin(), xvs.end(), delete_object());
    for_each(yvs.begin(), yvs.end(), delete_object());
    for_each(xcs.begin(), xcs.end(), delete_object());
    for_each(ycs.begin(), ycs.end(), delete_object());
    FILE_LOG(cola::logDEBUG) << "ColaTopologyAddon::handleResizes()... done.";
}
Exemplo n.º 4
0
bool CommonAPI::InitAS()
{
	engine = asCreateScriptEngine(ANGELSCRIPT_VERSION);
	engine->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL);
	RegisterStdString(engine);

	RegisterAPI();

	CScriptBuilder builder;

	if(builder.StartNewModule(engine, "MyModule") < 0)
		FILE_LOG(logERROR) << "Unrecoverable error while starting a new module.";

	string scriptPath = exePath.substr(0, exePath.find_last_of(".")).append(".tes");

	if(builder.AddSectionFromFile(scriptPath.c_str()) < 0)
		FILE_LOG(logERROR) << "Unable to load script." << scriptPath;
	else
		FILE_LOG(logINFO) << "Script " << scriptPath << " loaded successfully.";

	if(builder.BuildModule() < 0)
		FILE_LOG(logERROR) << "Please correct the errors in the script and try again.";

	
	module = engine->GetModule("MyModule");

	return true;
}
Exemplo n.º 5
0
Measurement::Measurement(Picoscope *p)
{
	FILE_LOG(logDEBUG3) << "Measurement::Measurement (Picoscope=" << p << ")";

	int i;

	picoscope = p;
	trigger = NULL;
	is_triggered = false;
	max_memory_consumption    = 0;
	max_trace_length_to_fetch = 0;
	ntraces = 1;
	max_traces_to_fetch = 1;
	timebase_reported_by_osciloscope = 0.0;
	use_signal_generator = false;
	rate_per_second = 0.0;

	for(i=0; i<GetNumberOfChannels(); i++) {
		// initialize the channels
		FILE_LOG(logDEBUG4) << "Measurement::Measurement - initialize channel nr. " << i;
		channels[i]=new Channel(i, this);
		data[i] = NULL;
		data_allocated[i] = false;
		data_length[i] = 0;
	}
	// only a temporary setting; this needs to be fixed if more than a single channel is enabled
	timebase = 0UL;
}
Exemplo n.º 6
0
FeedbackState::FeedbackState(const string &text): answer("", App::white, 1, TXT_BLEND), suggestion("", App::white, 1, TXT_BLEND){
	name = "Feedback";
	instruction = string("Press Enter to Continue.");
//	this->text = string(text);
	
	FILE_LOG(logDEBUG3) << "FeedbackState cstruct " << text;
	result = App::get()->judge.calcScore(text);
	/*
	screen_text.push_back(Text(text, App::white));
	screen_text.push_back(Text(result.answer, App::white));
	screen_text.push_back(Text(result.suggestion, App::white));
	*/
//	FILE_LOG(logDEBUG3) << "FeedbackState cstruct " << screen_text[1].getText();
	stringstream s;
	s << "Score: " << result.score;
	caption.setText(s.str());
	
	answer.setText(result.answer);
	suggestion.setText(result.suggestion);

	FILE_LOG(logDEBUG3) << "FeedbackState cstruct " << caption.getText();
	App::get()->judge.talk = 600;
	App::get()->judge.head_nod = 700 -2*result.score;
	
}
Exemplo n.º 7
0
// sets the maximum allowed memory consumption
// and the maximum trace length to be read at once
void Measurement::SetMaxMemoryConsumption(unsigned long bytes)
{
	FILE_LOG(logDEBUG3) << "Measurement::SetMaxMemoryConsumption (bytes=" << bytes << ")";

	int enabled_channels = GetNumberOfEnabledChannels();
	FILE_LOG(logDEBUG4) << "Measurement::SetMaxMemoryConsumption - enabled_channels=" << enabled_channels;
	unsigned long single_trace_bytes;

	max_memory_consumption    = bytes;
	if (enabled_channels > 0) {
		max_trace_length_to_fetch = bytes/(sizeof(short)*enabled_channels);
		FILE_LOG(logDEBUG4) << "Measurement::SetMaxMemoryConsumption - max_trace_length_to_fetch=" << max_trace_length_to_fetch;
	} else {
		max_trace_length_to_fetch = bytes/sizeof(short);
		FILE_LOG(logDEBUG4) << "Measurement::SetMaxMemoryConsumption - max_trace_length_to_fetch=" << max_trace_length_to_fetch << " (no enabled channels)";
	}
	if(GetNTraces() > 1) {
		single_trace_bytes = sizeof(short)*enabled_channels*GetLength();
		if(GetNTraces()*single_trace_bytes < max_memory_consumption) {
			max_traces_to_fetch = GetNTraces();
		} else {
			max_traces_to_fetch = (unsigned long)floor(max_memory_consumption/single_trace_bytes);
			FILE_LOG(logDEBUG4) << "Measurement::SetMaxMemoryConsumption - max_traces_to_fetch=" << max_traces_to_fetch << " (above limit for max_memory_consumption=" << max_memory_consumption << ")";
		}
	}
	assert(enabled_channels<=4);
}
Exemplo n.º 8
0
void Store::_initDB()
{
    string connectionString = string(_ndbConnectString) + ":" + to_string(_ndbPort);
    setenv("NDB_CONNECTSTRING", connectionString.c_str(), 1);
    
    ndb_init();

    //_mysql.reset(new MYSQL[_noExecutorThreads], ArrayDeleter<MYSQL>());

    _clusterConnections.reset(new Ndb_cluster_connection[_totalClusterConnections], ArrayDeleter<Ndb_cluster_connection>());

    for (int i = 0; i < _totalClusterConnections; i++)
    {
        if(_clusterConnections.get()[i].connect(12, 5, 1) != 0)
        {
            FILE_LOG(logERROR)<<"Failed to connect to ndb cluster connection no "<<i+1;
            exit(EXIT_FAILURE);
        }
    }
    
   FILE_LOG(logINFO)<<"Initialzing NDB ";
    
//    _initNDB(_ndbDefiners, _noDefinerThread);
    _initNDB(_ndbExecutors, _noExecutorThreads);
    
   FILE_LOG(logINFO)<<"NDB Initialzed";
    
    NDBMessageExecutor::initialize(_mysql.get(), _ndbExecutors.get(), &_tableInfoCache);
//    NDBMessageProcessor::initialize(_ndbDefiners.get(), &_tableInfoCache);

}
Exemplo n.º 9
0
  void MCMCModel::setCriteria(randEngine& eng)
  {
    CriteriaFactory mCFactory;

    for(size_t i = 0; i<nParticles; ++i)
      {
	mCrit.push_back(mCFactory.create(mParameters.crit_name,&mGP[i]));
	mCrit[i].setRandomEngine(eng);

	if (mCrit[i].nParameters() == mParameters.crit_params.size())
	  {
	    mCrit[i].setParameters(mParameters.crit_params);
	  }
	else // If the number of parameters is different, use default.
	  {
	    if (mParameters.crit_params.size() != 0)
	      {
		FILE_LOG(logERROR) << "Expected " << mCrit[i].nParameters() 
				   << " parameters. Got " 
				   << mParameters.crit_params.size() << " instead.";
	      }
	    FILE_LOG(logINFO) << "Using default parameters for criteria.";
	  }
      }
  } // setCriteria
Exemplo n.º 10
0
void Consensus::initialize(const vector<Point2f> & points_normalized)
{
    FILE_LOG(logDEBUG) << "Consensus::initialize() call";

    //Copy normalized points
    this->points_normalized = points_normalized;

    size_t num_points = points_normalized.size();

    //Create matrices of pairwise distances/angles
    distances_pairwise = Mat(num_points, num_points, CV_32FC1);
    angles_pairwise = Mat(num_points, num_points, CV_32FC1);

    for (size_t i = 0; i < num_points; i++)
    {
        for (size_t j = 0; j < num_points; j++)
        {
            Point2f v = points_normalized[i] - points_normalized[j];

            float distance = norm(v);
            float angle = atan2(v.y,v.x);

            distances_pairwise.at<float>(i,j) = distance;
            angles_pairwise.at<float>(i,j) = angle;
        }

    }

    FILE_LOG(logDEBUG) << "Consensus::initialize() return";
}
Exemplo n.º 11
0
int main(int argc, char* argv[])
{
  try
    {
      // levels: logERROR, logWARNING, logINFO, logDEBUG, 
      // logDEBUG1, logDEBUG2, logDEBUG3, logDEBUG4
      
      //
      // Set a reporting level
      //
      FILELog::ReportingLevel() = FILELog::FromString("DEBUG4");

      //
      // Set an output file
      //
      FILE* pFile = fopen("application.log", "a");
      Output2FILE::Stream() = pFile;

      const int count = 3;
      FILE_LOG(logDEBUG) << "A loop with " << count << " iterations";
      for (int i = 0; i != count; ++i)
        {
	  FILE_LOG(logDEBUG1) << "the counter i = " << i;
        }
      return 0;
    }
  catch(const std::exception& e)
    {
      FILE_LOG(logERROR) << e.what();
    }
  return -1;
}
Exemplo n.º 12
0
int bayes_optimization_disc(int nDim, eval_func f, void* f_data,
			    double *valid_x, size_t n_points,
			    double *x, double *minf, bopt_params parameters)
{
  vectord result(nDim);
  vectord input(nDim);
  vecOfvec xSet;

  for(size_t i = 0; i<n_points;++i)
    {
      for(int j = 0; j<nDim; ++j)
	{
	 input(j) = valid_x[i*nDim+j]; 
	}
      xSet.push_back(input);
    }

  if(parameters.n_init_samples > n_points)
    {
      parameters.n_init_samples = n_points;
      parameters.n_iterations = 0;
    }

  try
    {
      CDiscreteModel optimizer(xSet,parameters);
      
      optimizer.set_eval_funct(f);
      optimizer.save_other_data(f_data);
      optimizer.optimize(result);

      std::copy(result.begin(), result.end(), x);

      *minf = optimizer.getValueAtMinimum();
    }
  catch (std::bad_alloc& e)
    {
      FILE_LOG(logERROR) << e.what(); 
      return  BAYESOPT_OUT_OF_MEMORY; 
    }
  catch (std::invalid_argument& e)
    { 
      FILE_LOG(logERROR) << e.what(); 
      return BAYESOPT_INVALID_ARGS; 
    }
  catch (std::runtime_error& e)
    { 
      FILE_LOG(logERROR) << e.what(); 
      return BAYESOPT_RUNTIME_ERROR;
    }
  catch (...)
    { 
      FILE_LOG(logERROR) << "Unknown error";
      return BAYESOPT_FAILURE; 
    }

  return 0; /* everything ok*/
}
Exemplo n.º 13
0
	// TODO: socket closing in open() and receive(), add cleanup() and destructor again
	TcpErrorCode CTcpClient::open()
	{
		if (m_sock != SNET_BADSOCKET) SNET_SOCKCLOSE(m_sock);
		m_sock = SNET_BADSOCKET;
		struct addrinfo hints, *servinfo, *p;
		int ret;

		memset(&hints, 0, sizeof hints);
		hints.ai_family = AF_INET; // force IPv4
		hints.ai_socktype = SOCK_STREAM;

		if ((ret = getaddrinfo(m_ip.c_str(), m_port.c_str(), &hints, &servinfo)) != 0) 
		{
            #ifdef LINUX
			    FILE_LOG(logDEBUG3) << "CTcpClient::open():getaddrinfo: " << gai_strerror(ret);
            #endif

            #ifdef WINDOWS
                FILE_LOG(logDEBUG3) << "CTcpClient::open():getaddrinfo: WSAGetLastError() " <<  WSAGetLastError();
            #endif

			return TcpErrorCode::FAILURE;
		}

		// loop through all the results and connect to the first we can
		for(p = servinfo; p != NULL; p = p->ai_next) 
		{
			if ((m_sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) 
			{
				FILE_LOG(logDEBUG3) << "CTcpClient::open():socket()" << strerror(errno);
				continue;
			}

			if (connect(m_sock, p->ai_addr, p->ai_addrlen) == -1) 
			{
				san_cleanup_socket(&m_sock);
				// perror("client: connect");
				continue;
			}

			break;
		}

		if (p == NULL) 
		{
			// FILE_LOG(logDEBUG3) << "CTcpClient::open(): failed to connect";
			san_cleanup_socket(&m_sock);
			return TcpErrorCode::FAILURE;
		}

		// inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
		// printf("client: connecting to %s\n", s);

		freeaddrinfo(servinfo); // all done with this structure

		//close(m_sock);
		return TcpErrorCode::SUCCESS;
	}
	void CLIENT::netHandler::connect(char *remoteIPAddress, unsigned short serverPort) {
		FILE_LOG(logINFO) << "Connecting to " << remoteIPAddress << ":" << serverPort;
		bool tryingToConnect;
		tryingToConnect = peer->Connect(remoteIPAddress, serverPort, 0, 0, 0) == RakNet::CONNECTION_ATTEMPT_STARTED;
		if (tryingToConnect == false)
		{
			FILE_LOG(logINFO) << "Client wont start connecting?";
		}
	}
Exemplo n.º 15
0
void Measurement::AllocateMemoryRapidBlock(unsigned long bytes)
{
	FILE_LOG(logDEBUG3) << "Measurement::AllocateMemoryRapidBlock (bytes=" << bytes << ")";

	int i;
	unsigned long maxtraces, maxlen, memlen;

	SetMaxMemoryConsumption(bytes);
	maxtraces = GetMaxTracesToFetch();
	// TODO: one should not multiply with GetNumberOfEnabledChannels() !!!
	maxlen    = maxtraces*GetLength();
	memlen    = maxlen*sizeof(short)*GetNumberOfEnabledChannels();

	std::cerr << "Allocating memory of length ";
	if(memlen<1e3) {
		std::cerr << memlen;
	} else if(memlen<5e5) {
		std::cerr << memlen*1e-3f << "k";
	} else if(memlen<5e8) {
		std::cerr << memlen*1e-6f << "M";
	} else {
		std::cerr << memlen*1e-9f << "G";
	}
	std::cerr << " ... ";

	try {
		for(i=0; i<GetNumberOfChannels(); i++) {
			if(GetChannel(i)->IsEnabled()) {
				if(data_allocated[i]) {
					if(data_length[i] == maxlen) {
						// no need to do anything; data is already allocated and of the proper size
						// however it is still weird to call this function
						std::cerr << "Warning: Memory for channel " << (char)('A'+i) << " has already been allocated.\n";
					} else {
						std::cerr << "Warning: Memory for channel " << (char)('A'+i) << " has already been allocated; changing size.\n";
						delete [] data[i];
						// std::cerr << "allocate channel " << i << " with size" << maxlen << "\n";
						data[i] = new short[maxlen];
						data_allocated[i] = true;
						data_length[i] = maxlen;
					}
				} else {
					std::cerr << "(allocate channel " << (char)(i+'A') << " with size " << maxlen << ")\n";
					data[i] = new short[maxlen];
					data_allocated[i] = true;
					data_length[i] = maxlen;
				}
			}
		}
		FILE_LOG(logDEBUG4) << "!!!!!!!!!Measurement::AllocateMemoryBlock - maxlen=" << maxlen;
		std::cerr << "OK\n";
	} catch(...) {
		std::cerr << "Unable to allocate memory in Measurement::AllocateMemoryBlock, tried to allocate " << bytes << "bytes." << std::endl;
		throw;
	}
}
Exemplo n.º 16
0
bool CPortmap::registerPort(unsigned short int port, San2::Utils::CProducerConsumer<std::shared_ptr<San2::Network::CCapsule> >* applicationQueue)
{
    FILE_LOG(logDEBUG4) << "CPortmap::registerPort():: attempting to register port " << port << "\n";
    std::pair<std::map<unsigned short int, San2::Utils::CProducerConsumer<std::shared_ptr<San2::Network::CCapsule> >* >::iterator, bool> pair = mapPorts.insert(std::pair<unsigned short int, San2::Utils::CProducerConsumer<std::shared_ptr<San2::Network::CCapsule> >*>(port, applicationQueue));

    if (pair.second) FILE_LOG(logDEBUG4) << "CPortmap::registerPort():: port REG OK \n";
    else FILE_LOG(logDEBUG4) << "CPortmap::registerPort():: port REG FAILED \n";

    return pair.second;
}
Exemplo n.º 17
0
Agent* Agent_builder::create_instance(std::string type){

	FILE_LOG(logDEBUG) << " Creating instance of agent from type "<<type<<std::endl;
	if (agent_constructors.find(type)==agent_constructors.end()){
		FILE_LOG(logERROR)<< " Cannot create agent of type ["<<type<<"]"<< std::endl;
		exit(-1);
	}
	Agent *a=agent_constructors[type]();
	return a;
}
Exemplo n.º 18
0
//TODO: Check for estimate_scale, estimate_rotation
void Consensus::estimateScaleRotation(const vector<Point2f> & points, const vector<int> & classes,
        float & scale, float & rotation)
{
    FILE_LOG(logDEBUG) << "Consensus::estimateScaleRotation() call";

    //Compute pairwise changes in scale/rotation
    vector<float> changes_scale;
    if (estimate_scale) changes_scale.reserve(points.size()*points.size());
    vector<float> changes_angles;
    if (estimate_rotation) changes_angles.reserve(points.size()*points.size());

    for (size_t i = 0; i < points.size(); i++)
    {
        for (size_t j = 0; j < points.size(); j++)
        {
            if (classes[i] != classes[j])
            {
                Point2f v = points[i] - points[j];

                if (estimate_scale)
                {
                    float distance = norm(v);
                    float distance_original = distances_pairwise.at<float>(classes[i],classes[j]);
                    float change_scale = distance / distance_original;
                    changes_scale.push_back(change_scale);
                }

                if (estimate_rotation)
                {
                    float angle = atan2(v.y,v.x);
                    float angle_original = angles_pairwise.at<float>(classes[i],classes[j]);
                    float change_angle = angle - angle_original;

                    //Fix long way angles
                    if (fabs(change_angle) > M_PI) {
                        change_angle = sgn(change_angle) * 2 * M_PI + change_angle;
                    }

                    changes_angles.push_back(change_angle);
                }
            }

        }

    }

    //Do not use changes_scale, changes_angle after this point as their order is changed by median()
    if (changes_scale.size() < 2) scale = 1;
    else scale = median(changes_scale);

    if (changes_angles.size() < 2) rotation = 0;
    else rotation = median(changes_angles);

    FILE_LOG(logDEBUG) << "Consensus::estimateScaleRotation() return";
}
Exemplo n.º 19
0
Agent* Agent_builder::build(Agent_params p){
	FILE_LOG(logDEBUG) << " Agent_builder::build "<<std::endl;
	Agent* agent= create_instance(p.implementation);
	assert(agent);
	FILE_LOG(logDEBUG) << " Instance created "<<std::endl;
	agent->set_properties(p.m_properties);
	agent->set_agent_file(p.agent_file);
	FILE_LOG(logDEBUG) << " Agent init "<<std::endl;
	agent->init();
	return agent;
}
Exemplo n.º 20
0
/***
 * Look for the values of ?? and fills it with the relevant data
 * Suggestion: ?<index>{lower,upper}
 * */
inline void concrete(Agent_params& ap,double* paramptr){
	FILE_LOG(logDEBUG) << "starting concrete " << std::endl;
	for (properties::iterator i = ap.m_properties.begin(); i != ap.m_properties.end(); ++i) {
		if(is_concrete_param(i->second)){
			FILE_LOG(logDEBUG) << "need to concrete: ["<<i->first << "] with value:" << i->second<< std::endl; 
			ap.m_properties[i->first]=assigned_val(i->second,paramptr);
			FILE_LOG(logDEBUG) << " concrete-assgined ("<< ap.m_properties[i->first]<<")"<< std::endl;
	       	}

	}
}
Exemplo n.º 21
0
FkInt32S FkSilhDetector_PaintedFlies::segmentFrame(const IplImage *thisFrame) // I want to keep it void
{
    FILE_LOG(logDEBUG1)<< "\nbegin of FkSilhDetector_PaintedFlies::segmentFrame";

    if(m_isInited!=1)
    {
        FILE_LOG(logDEBUG1)<< "\nsilhDetector is not init";
        return(FK_ERR_SILH_DETECT_IS_NOT_INIT);
    }
    CvPoint pt1, pt2; //this is for ROI, TODO: get this exposed 
    pt1 = cvPoint(1,1);
    pt2 = cvPoint(thisFrame->width, thisFrame->height); //setting ROI the whole image

    cvZero(m_rawChangeMask);

    int i, j, minX,maxX,minY,maxY;
    minX = FK_MIN(pt1.x, pt2.x);
    maxX = FK_MAX(pt1.x, pt2.x);
    minY = FK_MIN(pt1.y, pt2.y);
    maxY = FK_MAX(pt1.y, pt2.y);

#if __USE_OPENMP_FOR_SEGMENTATION
#pragma omp parallel shared(i,j,maxX,maxY,minX,minY)//, thisFrame, m_bgModel, m_threshold, m_rawChangeMask)
    {
#pragma omp for schedule(dynamic)
#endif
    for(i= minY+1; i<maxY-1; ++i) //just look for silhouettes in ROI
    {
        for(j=minX+1; j<maxX-1; ++j)
        {
            
            if( pixelDistance( &UPIXEL(thisFrame, i, j, 0), &UPIXEL(m_bgModel, i, j, 0), 3 ) > -m_threshold )
            {
                //for(int k = 0; k < m_bgModel->nChannels; ++k)
                //{
                //    //if (parentCamView->frameNum % 1000 == 0)
                //    //    UPIXEL(m_bgModel, i, j, k) = (unsigned char) (alpha * UPIXEL(thisFrame, i, j, k) + (1-alpha) * UPIXEL(m_bgModel, i, j, k));
                //}
            }
            else
            {
                PIXEL(m_rawChangeMask,i, j, 0) |= 0xFF;
            }
        }
    }

#if __USE_OPENMP_FOR_SEGMENTATION
    }
#endif


    FILE_LOG(logDEBUG1)<< "\nEnd of FkSilhDetector_PaintedFlies::segmentFrame";
    return (FK_OK);
}
Exemplo n.º 22
0
  void checkNLOPTerror(nlopt_result errortype)
  {
    switch(errortype)
      {
      case -1: FILE_LOG(logERROR) << "NLOPT: General failure"; break;
      case -2: FILE_LOG(logERROR) << "NLOPT: Invalid arguments. Check bounds."; break;
      case -3: FILE_LOG(logERROR) << "NLOPT: Out of memory"; break;
      case -4: FILE_LOG(logERROR) << "NLOPT Warning: Potential roundoff error. " 
				  << "In general, this can be ignored."; break;
      case -5: FILE_LOG(logERROR) << "NLOPT: Force stop."; break;
      default: ;
      }
  }
Exemplo n.º 23
0
  void MCMCModel::updateHyperParameters()
  {
    // We take the initial point as the last particle from previous update.
    size_t last = mGP.size()-1;
    vectord lastTheta = mGP[last].getHyperParameters();

    FILE_LOG(logDEBUG) << "Initial kernel parameters: " << lastTheta;
    kSampler->run(lastTheta);
    for(size_t i = 0; i<nParticles; ++i)
      {
	mGP[i].setHyperParameters(kSampler->getParticle(i));
      }
    FILE_LOG(logDEBUG) << "Final kernel parameters: " << lastTheta;	
  };
Exemplo n.º 24
0
  void DiscreteModel::plotStepData(size_t iteration, const vectord& xNext,
				   double yNext)
  {
    if(mParameters.verbose_level >0)
      { 
	FILE_LOG(logINFO) << "Iteration: " << iteration+1 << " of " 
			  << mParameters.n_iterations << " | Total samples: " 
			  << iteration+1+mParameters.n_init_samples ;
	FILE_LOG(logINFO) << "Trying point at: " << xNext ;
	FILE_LOG(logINFO) << "Current outcome: " << yNext ;
	FILE_LOG(logINFO) << "Best found at: " << getPointAtMinimum() ; 
	FILE_LOG(logINFO) << "Best outcome: " <<  getValueAtMinimum() ;    
      }
  }
Exemplo n.º 25
0
void Store::_executorWorkerThreadFunc(unsigned short threadNo)
{
    try
    {
        initMySQL(&_mysql.get()[threadNo], threadNo);
        
        zmq::socket_t taskReceiverSocket(*_serverTransport->getContext(), ZMQ_PULL);
        taskReceiverSocket.bind(TransportUtils::getSinkName(_EXECUTOR_SINK_NAME, threadNo).c_str());
        
        zmq::socket_t taskSenderSocket(*_serverTransport->getContext(), ZMQ_PUSH);
        taskSenderSocket.connect(TransportUtils::getSinkName(ServerTransport::SERVER_SINK_NAME, threadNo%_noDefinerThread).c_str());

        const int TASK_RECEIVER_SOCKET_INDEX = 0;
        const int TOTAL_POLL_ITEMS = 1;
        const int POLL_WAIT_MS = _storePollWait;
        
        FILE_LOG(logINFO)<<"Initialized executor worker # "<<threadNo;

        addExecutorInitializationCount();
        
        zmq::pollitem_t items[] = {
            {taskReceiverSocket, 0, ZMQ_POLLIN, 0},
        };
        
        while(true)
        {
            if(_stopFlag)
                break;
            
//            zmq::poll(items, TOTAL_POLL_ITEMS, POLL_WAIT_MS);
            
            std::this_thread::sleep_for(chrono::milliseconds(10));
            
//            if (items[TASK_RECEIVER_SOCKET_INDEX].revents & ZMQ_POLLIN)
            {
                auto messages = TransportUtils::receiveQueuedMessages(taskReceiverSocket, _MAX_TRANSACTIONS);
                if(messages.size() > 0)
                {
//                FILE_LOG(logINFO)<<"Received: ";
                    _executeMessages(messages, taskSenderSocket, threadNo);
                }
            }
        }
    }
    catch(exception& ex)
    {
        FILE_LOG(logERROR)<<"EXCEPTION IN EXECUTOR WORKER # "<<threadNo<<": "<<ex.what();
    }
}
Exemplo n.º 26
0
/**************************************************************************************************
 *  Procedure                                                                                     *
 *                                                                                                *
 *  Description: operator()                                                                       *
 *  Class      : UnscentedExpectedImprovement                                                     *
 **************************************************************************************************/
double UnscentedExpectedImprovement::operator() (const vectord& x)
{
    double               e_uei = 0.0;
    double               d_uei = 0.0;
    std::vector<double > ei_i;
    std::vector<vectord> xx;
                         xx.push_back(x);

    // Calculate query_i
    for (size_t column = 0; column < _px.size2(); ++column)
    {
        xx.push_back(x - boost::numeric::ublas::column(_px, column));
        xx.push_back(x + boost::numeric::ublas::column(_px, column));
    }

    // Calculate EI_i and E[UEI]
    for (size_t idx = 0; idx < xx.size(); ++idx)
    {
        // Calculate ei_i according to underlying _criteria
        ei_i.push_back( (*_criteria)(xx[idx]) );

        FILE_LOG(logDEBUG) << "cUEI Query " << idx << " = " << xx[idx];

        // e_uei = sum_{i=0}^{2_dim+1} (ei_i * w_i)
        if (idx == 0) e_uei += ei_i[idx] * ( _scale / (_dim + _scale) );
        else          e_uei += ei_i[idx] * (  0.5   / (_dim + _scale) );
    }

    // Normalize e_uei
    e_uei /= xx.size();

    // Calculate V[UEI]
    for (size_t idx = 0; idx < xx.size(); idx += 1)
    {
        // d_uei = sum_{i=0}^{2_dim+1} ( (ei_i-e_uei)^2 * w_i)
        if (idx == 0) d_uei += ( ei_i[idx] - e_uei ) * ( ei_i[idx] - e_uei ) * ( _scale / (_dim + _scale) );
        else          d_uei += ( ei_i[idx] - e_uei ) * ( ei_i[idx] - e_uei ) * (  0.5   / (_dim + _scale) );
    }

    // Normalize d_uei
    d_uei  = std::sqrt(d_uei / xx.size());

    FILE_LOG(logDEBUG) << "e_uei = " << e_uei;
    FILE_LOG(logDEBUG) << "d_uei = " << d_uei;

    // Return criteria
    return ( ((1 -_alpha) * e_uei) - (_alpha * d_uei) );
}
Exemplo n.º 27
0
U2VertexShader::U2VertexShader(const U2DynString& szShadername)
	:U2Shader(szShadername)	
{	
	U2GpuProgram* pProgramItr = U2GpuProgram::GetHead();
	bool bFound = false;

	while(pProgramItr)
	{
		if(pProgramItr->GetName() == szShadername)
		{
			m_spProgram = pProgramItr;
			bFound = true;
			break;
		}
		
		pProgramItr = pProgramItr->GetNext();
	}

	if(!m_spProgram)
	{
		m_spProgram =U2VertexProgram::Load(szShadername);		
	}

	if(m_spProgram)
	{
		FILE_LOG(logDEBUG) << _T("Vertex Shader ") << szShadername.Str() << _T(" loaded");
		OnLoadProgram();
	}
}
Exemplo n.º 28
0
inline bool Store::shouldIgnoreRequest()
{
    time_t currentTime = time(0);
    
    resetTransactionMonitorCounterIfRequired(currentTime);
    
    double percentFailed = 0;
    int recentTransactionsCount = NDBMessageProcessor::_noRecentTransactions;
    if(recentTransactionsCount > 0)
        percentFailed = NDBMessageProcessor::_noRecentFailedTransactions/recentTransactionsCount;
    
    if(percentFailed > 0)
    {
        int randVal = rand()%100;
        
        //ignore request, TODO: user should get a reponse that it's a temp error and should try again.
        if(randVal < (int)percentFailed)
        {
            FILE_LOG(logINFO)<<"Ignoring request because of failing transactions";
            return true;
        }
    }

    return false;
}
Exemplo n.º 29
0
  void KernelModel::setKernel (const vectord &thetav, 
			      const vectord &stheta,
			      std::string k_name, 
			      size_t dim)
  {
    KernelFactory mKFactory;

    mKernel.reset(mKFactory.create(k_name, dim));

    if ((thetav.size() == 1) && (stheta.size() == 1) && (mKernel->nHyperParameters() != 1))
      {
	// We assume isotropic prior, so we replicate the vectors for all dimensions
	size_t n = mKernel->nHyperParameters();

	FILE_LOG(logINFO) << "Expected " << n << " hyperparameters."
			  << " Replicating parameters and prior.";

	vectord newthetav = svectord(n,thetav(0));
	vectord newstheta = svectord(n,stheta(0));

	setKernelPrior(newthetav,newstheta);
	mKernel->setHyperParameters(newthetav);
      }
    else
      {
	setKernelPrior(thetav,stheta);
	mKernel->setHyperParameters(thetav);
      }
  }
Exemplo n.º 30
0
double TriConstraint::slack(const double ux, const double vx, const double wx) const {
    const double lhs = wx;
    const double rhs = ux+p*(vx-ux)+g;
    FILE_LOG(logDEBUG1)<<"  TriConstraint::slack("<<ux<<","<<vx<<","<<wx<<"):leftOf="<<leftOf<<",lhs="<<lhs<<",rhs="<<rhs;
    return leftOf ? rhs - lhs
                  : lhs - rhs;
}