コード例 #1
0
void affineInterp(const PointSet &src, PointSet &res, const double mat[DIM_MAX][DIM_MAX+1])
{
  int N = src.dim() ;
  res.al(src.size(), src.dim()) ;
  for (unsigned int i=0; i< src.size(); i++) {
    for (int j=0; j< N; j++) {
      res[i][j] = mat[j][N] ;
      for(int jj=0; jj< N; jj++)
	res[i][j] += mat[j][jj] * src[i][jj] ;
    }
  }
}
コード例 #2
0
//make sure everytime the pointSet is cleared at first;
bool MemMapStrategy::Read(PointSet &pointSet)
{
	if(_isFinish)
		return false;

	unsigned int numLeft;
	unsigned int thisTimeToRead;
	if(_numOfPointsToRead>MEM_MAP_THRESHOLD) {
		numLeft = _numOfPointsToRead - MEM_MAP_THRESHOLD;
		thisTimeToRead = MEM_MAP_THRESHOLD;
	} else {
		numLeft = 0;
		thisTimeToRead = _numOfPointsToRead;
	}

	time_t sT, eT;
	sT = clock();
	inputor->_num = thisTimeToRead;
	ReadConcept(*inputor, pointSet, _recordType);
	eT = clock();
	_log << "Read "<< pointSet.size() <<" points, Time : "<<difftime(eT, sT)<<endl;

	_numOfPointsToRead = numLeft;
	if(_numOfPointsToRead<=0) {
		_log << "Finish Read!"<<endl;
		_isFinish = true;
	}

	return true;
}
コード例 #3
0
ファイル: pointset.cpp プロジェクト: andrewazmy/dbicp
double PointSet::get_scaled_dist_with(const PointSet &other,const vector<bool> &mask) const {
    /**
    * Sum of the distances where the value of the mask is true
    */

    double dist=0;
    if (this->size()==other.size() && this->size()==mask.size()) {
        double mean = 0, sigma = 0;
        for (unsigned int i=0;i<this->size();i++) {
            if (mask[i])
                mean += (*this)[i].get_dist_with(other[i]);
        }
        mean = mean/this->size();

        for (unsigned int i=0;i<this->size();i++) {
            if (mask[i])
                dist += (*this)[i].get_dist_with(other[i]);
                sigma += pow((*this)[i].get_dist_with(other[i])-mean,2);
        }

        sigma = sqrt(sigma/this->size());

        if (sigma==0) {
            cout << "FATAL ERROR: division by 0 in PointSet::get_scaled_dist_with" << endl;
            exit(2);
        }
        dist /= sigma;

    }
    else {
        cout << "ERROR in PointSet: point set 1 and 2 and mask must have the same sizes!" <<endl;
        exit(2);
    }
    return dist;
}
コード例 #4
0
bool SimpleReadStrategy::Read(PointSet &pointSet)
{
	if(_isFinish)
		return false;

	time_t sT, eT;

	sT = clock();

	std::ifstream infile(_fileName.c_str());

	if(!infile)
	{
		_log << "Can not open this file in this path"<<endl;
		return false;
	}

	_log<<"Begin to read data."<<endl;

	SimpleInputor inputor(infile);
	inputor.ReadHead();
	ReadConcept(inputor, pointSet, _recordType);
	infile.close();

	//inputor.infile.close();
	_log<<"All "<<pointSet.size()<<" points have been read successfully!"<<endl;

	eT = clock();
	_log << "Read-Time: "<<difftime(eT, sT)<<endl;

	_isFinish = true;
	return true;
}
コード例 #5
0
ファイル: points.hpp プロジェクト: LegendGraphics/regmm
    void savePointSet(const std::string& filename, PointSet& ps)
    {
        std::fstream fout(filename.c_str(), std::ios_base::out);

        for (size_t i = 0; i < ps.size(); ++ i)
        {
            if (Dim == 3)
                fout << ps[i].x() << " " << ps[i].y() << " " << ps[i].z() << "\n";
            else
                fout << ps[i].x() << " " << ps[i].y() << "\n";
        }

        fout.close();
    }
コード例 #6
0
ファイル: Computations.cpp プロジェクト: JanKolomaznik/MedV4D
void
computeCovarianceMatrixFromPointSet( const PointSet &aPoints, Vector3f &aCenter, Eigen::Matrix3f &aCovarianceMatrix )
{
	float scale = 1.0f/aPoints.size();
	aCenter = scale * std::accumulate( aPoints.begin(), aPoints.end(), Vector3f() );

/*	//compute variances
	Vector3f variances;
	for ( size_t k = 0; k < aPoints.size(); ++k ) {
		variances += VectorCoordinateProduct( aPoints[k]-aCenter, aPoints[k]-aCenter );
	}
	variances *= scale;*/

	for ( size_t i = 0; i < 3; ++i ) {
		for ( size_t j = 0; j < 3; ++j ) {
			float covariance = 0.0f;
			for ( size_t k = 0; k < aPoints.size(); ++k ) {
				covariance += (aPoints[k][i]-aCenter[i]) * (aPoints[k][j]-aCenter[j]);
			}
			aCovarianceMatrix(i,j) = scale * covariance;
		}
	}
}
コード例 #7
0
ファイル: pointset.cpp プロジェクト: andrewazmy/dbicp
double PointSet::get_dist_with(const PointSet &other) const {
    /**
    * Simple sum of the distances
    */
    double dist=0;
    if (this->size()==other.size()) {
        for (unsigned int i=0;i<this->size();i++)
            dist += (*this)[i].get_dist_with(other[i]);
    }
    else {
        cout << "ERROR in PointSet: point sets must have the same sizes!" <<endl;
        exit(2);
    }
    return dist;
}
コード例 #8
0
ファイル: pointset.cpp プロジェクト: andrewazmy/dbicp
double PointSet::get_dist_with(const PointSet &other,const vector<bool> &mask) const {
    /**
    * Sum of the distances where the value of the mask is true
    */
    double dist=0;
    if (this->size()==other.size() && this->size()==mask.size()) {
        for (unsigned int i=0;i<this->size();i++) {
            if (mask[i])
                dist += (*this)[i].get_dist_with(other[i]);
        }
    }
    else {
        cout << "ERROR in PointSet: point set 1 and 2 and mask must have the same sizes!" <<endl;
        exit(2);
    }
    return dist;
}
コード例 #9
0
// Create a randomly generated point
// scatter time execution
void testScalability(unsigned numpts)
{
    using namespace boost;
    using namespace std;

    typedef adjacency_matrix<undirectedS, no_property,
        property <edge_weight_t, double,
        property<edge_index_t, int> > > Graph;
    typedef graph_traits<Graph>::vertex_descriptor Vertex;
    typedef property_map<Graph, edge_weight_t>::type WeightMap;
    typedef set<simple_point<double>, cmpPnt<double> > PointSet;
    typedef vector< Vertex > Container;

    boost::mt19937 rng(time(0));
    uniform_real<> range(0.01, (numpts * 2));
    variate_generator<boost::mt19937&, uniform_real<> >
        pnt_gen(rng, range);

    PointSet points;
    simple_point<double> pnt;

    while (points.size() < numpts)
    {
        pnt.x = pnt_gen();
        pnt.y = pnt_gen();
        points.insert(pnt);
    }

    Graph g(numpts);
    WeightMap weight_map(get(edge_weight, g));
    vector<simple_point<double> > point_vec(points.begin(), points.end());

    connectAllEuclidean(g, point_vec, weight_map, get(vertex_index, g), numpts);

    Container c;
    timer t;
    double len = 0.0;

    // Run the TSP approx, creating the visitor on the fly.
    metric_tsp_approx(g, make_tsp_tour_len_visitor(g, back_inserter(c), len, weight_map));

    cout << "Number of points: " << num_vertices(g) << endl;
    cout << "Number of edges: " << num_edges(g) << endl;
    cout << "Length of tour: " << len << endl;
    cout << "Elapsed: " << t.elapsed() << endl;
}
コード例 #10
0
ファイル: statistics.cpp プロジェクト: joeedh/psa
static void Distances(const PointSet &points, int npoints,
                      float *mindist, float *avgmindist)
{
    *mindist = FLT_MAX;
    *avgmindist = 0;
    for (int i = 0; i < npoints; ++i) {
        float localmd = FLT_MAX;
        for (int j = 0; j < npoints; ++j) {
            if (i == j) continue;
            float dist = points[i].SquaredDistUnitTorus(points[j]);
            localmd = std::min(dist, localmd);
        }
        *mindist = std::min(localmd, *mindist);
        *avgmindist += sqrtf(localmd);
    }
    *mindist = sqrtf(*mindist);
    *avgmindist /= points.size();
}
コード例 #11
0
ファイル: native.cpp プロジェクト: ericyao2013/ARdroneUAV
void saveKeypoints(Image<unsigned char>& imageToSave)
{
	for(int i=0; i<corners.size(); i++)
	{
		TooN::Vector<2> undistorted_coords = drone_camera_model.linearproject(corners[i].cam_coords);
		if(imageToSave.in_image(ImageRef((int) undistorted_coords[0], (int) undistorted_coords[1])))
			drawBox(imageToSave.data(), undistorted_coords[0], undistorted_coords[1], 6);
	}

	printf("saving keypoints\n");
	
	FILE *file_fd;
	file_fd = fopen("keypoints12.yuv", "wb");
	const void *p;
	p = (const void*) imageToSave.data();
	fwrite(p, WIDTH*HEIGHT, 1, file_fd);
	fclose(file_fd);
}
コード例 #12
0
/*
  void SoftmaxPolicyPlayout::initProbabilities(const Go::Board *init_board) {
    //memset(m_probTableBlack, 0, sizeof(double)*MAX_BOARD_SIZE);
    //memset(m_probTableWhite, 0, sizeof(double)*MAX_BOARD_SIZE);

    //SparseVector extractedFeatures;
    Color turns[] = {BLACK, WHITE};
    double *tables[2] = {m_probTableBlack, m_probTableWhite};
    SparseVector *featureTables[2] = {m_featureTableBlack, m_featureTableWhite};

    for (int i=0; i<2 && tables[i] != NULL; i++) {
      Color myTurn = turns[i];

      initProbabilities(init_board, myTurn, tables[i], featureTables[i]);
    }
  }
*/
  void SoftmaxPolicyPlayout::initProbabilities(const Go::Board *init_board, Color myTurn, double *table, SparseVector *featureTable) {
    Color enemyTurn = Board::flipColor(myTurn);
    PointSet &updatedMoves = myTurn == BLACK ? m_toResetStaticFeaturesMovesBlack : m_toResetStaticFeaturesMovesWhite;
    updatedMoves.clear();

    for (int y=0; y<init_board->getSize(); y++) {
      for (int x=0; x<init_board->getSize(); x++) {
        featureTable[init_board->xyToPoint(x,y)].clear();
      }
    }

    PointSet legalMovesSet;

    // update pattern features
    for (int y=0; y<init_board->getSize(); y++) {
      for (int x=0; x<init_board->getSize(); x++) {
        Point p = init_board->xyToPoint(x,y);
        if (init_board->isColor(p, FREE) &&
            (init_board->getNeighborEmptyCount(p)>=1 || init_board->checkLegalHand(p, myTurn, enemyTurn) == Board::PUT_LEGAL)) {
          m_featureExtractor.updatePatternFeature(featureTable[p], init_board, p, myTurn);
          legalMovesSet.insert(p,p);
        } else {
          // prob is 0
          //featureTable[p].clear();
          if (init_board->isColor(p, FREE)) {
            m_featureExtractor.updatePatternFeature(featureTable[p], init_board, p, myTurn);
          }
          table[p] = 0;
        }
      }
    }

    // update static features
    m_featureExtractor.updateStaticFeaturesForAllMovesWithoutClearOldFeatures(init_board, myTurn, legalMovesSet, featureTable, updatedMoves);
    
    for (size_t i=0; i<legalMovesSet.size(); i++) {
      //table[legalMovesSet[i]] = m_expFeatureWeights.multiplyAll(featureTable[legalMovesSet[i]]);
      table[legalMovesSet[i]] = fmath::expd(m_featureWeights.dot(featureTable[legalMovesSet[i]]));
      //table[legalMovesSet[i]] = exp(m_featureWeights.dot(featureTable[legalMovesSet[i]]));
    }

  }
コード例 #13
0
ファイル: gradient-descent.hpp プロジェクト: dcoeurjo/stk
void GradientDescent<DIM, POS, VAL>::optimize(PointSet<DIM, POS, VAL>& _pts)
{
	PointSet<DIM, POS, POS> data = _pts;
	
	int iSz = _pts.size();
	
	for(int d=0; d<DIM; d++)
	{
		Vector<DIM, POS> shift;
		shift[d] += m_shift;
			
		for(int i=0; i<iSz; i++)
		{
			data.push_back(Point<DIM, POS, POS>(_pts[i].pos() + shift, 0));
		}
	}
	
	evalFunction(data);

	m_max = 0.0;
	m_mean = 0.0;
	if(iSz != 0)
	{
		for(int i=0; i<iSz; i++)
		{
			Vector<DIM, POS> motion;
			
			for(int d=0; d<DIM; d++)
			{
				POS p = (data[i].val() - data[i+iSz*(d+1)].val()) / m_shift;
				_pts[i].pos()[d] -= p;
				motion[d] = p;
			}
			
			POS norm = motion.norm();
			m_mean += norm;
			if(m_max < norm) m_max = norm;
		}
		m_mean /= iSz;
	}
}
コード例 #14
0
bool UnknownNumStrategy::Read(PointSet& pointSet)
{
	if(_isFinish)
		return false;

	unsigned int numLeft;
	unsigned int thisTimeToRead = MEM_MAP_THRESHOLD;

	time_t sT, eT;
	sT = clock();
	inputor->_num = thisTimeToRead;
	ReadConcept(*inputor, pointSet, _recordType);
	eT = clock();
	_log << "Read "<< pointSet.size() <<" points, Time : "<<difftime(eT, sT)<<endl;

	if(inputor->reachFileEnd()) {
		_log << "Finish Read!"<<endl;
		_isFinish = true;
	}

	return true;
}
コード例 #15
0
ファイル: Computations.cpp プロジェクト: JanKolomaznik/MedV4D
void
getHeadMeasurementData( const PointSet &aPoints, HeadMeasurementData &aHeadMeasurementData )
{
	ASSERT( aPoints.size() >= 3 );

	Vector3f center;
	Eigen::Matrix3f covarianceMatrix;

	computeCovarianceMatrixFromPointSet( aPoints, center, covarianceMatrix );

	typedef Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> Solver;
	Solver eigensolver(covarianceMatrix);

	Solver::RealVectorType eigenVals = eigensolver.eigenvalues();
	Eigen::Matrix3f eigenVectors = eigensolver.eigenvectors();
	D_PRINT( "Eigen values :\n" << eigenVals );
	D_PRINT( "Eigen vectors :\n" << eigenVectors );


	Vector3f v1( eigenVectors(0,2), eigenVectors(1,2), eigenVectors(2,2) );
	Vector3f v2( eigenVectors(0,1), eigenVectors(1,1), eigenVectors(2,1) );
	
/*	Vector3f v1 = mHumeralHeadPoints[0] - center;
	Vector3f v2 = mHumeralHeadPoints[1] - center;
	VectorNormalization( v1 );
	VectorNormalization( v2 );*/
	Vector3f normal = VectorProduct( v1, v2 );
	VectorNormalization( normal );
	/*v2 = VectorProduct( v1, normal );
	VectorNormalization( v2 );*/

	aHeadMeasurementData.point = center;
	aHeadMeasurementData.normal = normal;
	aHeadMeasurementData.vDirection = v1;
	aHeadMeasurementData.wDirection = v2;
	aHeadMeasurementData.available = true;
}
コード例 #16
0
void evalAgreemenRate(vector<Board_Move_Dataset *> dataset, unsigned int randomSeed, vector<int> &correctCount, vector<int> &positionCount) {
  // init seed of random
  srand(randomSeed);

  correctCount.clear();
  positionCount.clear();

  SparseVector featureTable[MAX_BOARD_SIZE];
  SparseVector passFeature;

  int corrects = 0, positions = 0;

  vector<shared_ptr<FeatureWeights> >::iterator it, end = featureWeights.end();
  for (it = featureWeights.begin(); it!=end; it++) {
    shared_ptr<FeatureWeights> weights = *it;

    corrects = positions = 0;

    for (size_t i=0; i<dataset.size(); i++) {      

      Board_Move_Dataset &set = *dataset[i];
      set.seekToBegin();

      if (set.empty()) continue;

      Board_Move_Data init_data(set.get());

      //std::shared_ptr<AI::PlayerBase> players[2] = {
      //  AI::Parameters::getInstanceOfColor(BLACK).createPlayerAccordingToKind(init_data.state.get(), 1),
      //  AI::Parameters::getInstanceOfColor(WHITE).createPlayerAccordingToKind(init_data.state.get(), 1)
      //};

      do {
        Board_Move_Data data(set.get());

        Color turn = data.turn;

        // extract features
        PointSet possibleMoves;
        featureExtractor.extractFromStateForAllMoves(data.state.get(), turn, featureTable, passFeature, possibleMoves);
        double maxValue = -99999999999;
        Point maxMove = POINT_NULL;
        for (size_t i=0; i<possibleMoves.size(); i++) {
          Point p = possibleMoves[i];
          SparseVector &vec = featureTable[p];
          double sum = weights->dot(vec);
          if (sum > maxValue) {
            maxValue = sum;
            maxMove = p;
          }
        }
        double sum = weights->dot(passFeature);
        if (sum > maxValue) {
          maxValue = sum;
          maxMove = PASS;
        }

        //Point selected = players[turn == BLACK ? 0 : 1]->selectBestMove(turn);
        //data.state->printToErr();

        if (maxMove == data.move) {
          corrects++;
          //cerr << "correct " << endl;
        }
        positions++;

      } while (set.next());
      cerr << "end dataset " << i << endl;
    };

    correctCount.push_back(corrects);
    positionCount.push_back(positions);
  }
}
コード例 #17
0
ファイル: Computations.cpp プロジェクト: JanKolomaznik/MedV4D
void
getProximalShaftMeasurementData( const PointSet &aPoints, ProximalShaftMeasurementData &aProximalShaftMeasurementData )
{
	Vector3f center;
	Vector3f v1;
	Eigen::Matrix3f covarianceMatrix;


	Vector3f minimum = aPoints[0];
	Vector3f maximum = aPoints[0];
	for ( size_t i = 1; i < aPoints.size(); ++i ) {
		minimum = M4D::minVect< float, 3 >( static_cast< const Vector3f &>( minimum ), static_cast< const Vector3f &>( aPoints[i] ) );
		maximum = M4D::maxVect< float, 3 >( static_cast< const Vector3f &>( maximum ), static_cast< const Vector3f &>( aPoints[i] ) );
		/*D_PRINT( "point : " << aPoints[i] );
		D_PRINT( "min : " << minimum );
		D_PRINT( "max : " << maximum << "\n" );*/
	}

	if ( !aProximalShaftMeasurementData.available ) {
		computeCovarianceMatrixFromPointSet( aPoints, center, covarianceMatrix );
		typedef Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> Solver;
		Solver eigensolver(covarianceMatrix);

		Solver::RealVectorType eigenVals = eigensolver.eigenvalues();
		Eigen::Matrix3f eigenVectors = eigensolver.eigenvectors();
		D_PRINT( "Eigen values :\n" << eigenVals );
		D_PRINT( "Eigen vectors :\n" << eigenVectors );

		v1 = Vector3f( eigenVectors(0,2), eigenVectors(1,2), eigenVectors(2,2) );

	} else {
		center = aProximalShaftMeasurementData.centerPoint;
		v1 = aProximalShaftMeasurementData.direction;
	}
	//********************************************************************
	float d = 0.15f;
	float d2 = 5.0f;
	NumericOptimizer< float, 6, CylinderMaximumFillFtor > optimizer;
	Vector< float, 6 > result = optimizer.optimize( 
		Vector< float, 6 >( center[0]-d2, center[1]-d2, center[2], v1[0]-d, v1[1]-d, v1[2]-d ), 
		Vector< float, 6 >( center[0]+d2, center[1]+d2, center[2], v1[0]+d, v1[1]+d, v1[2]+d ), 
		Vector< float, 6 >( center[0], center[1], center[2], v1[0], v1[1], v1[2] ), 
		CylinderMaximumFillFtor( aPoints )
		);

	center = result.GetSubVector< 0, 3 >();
	v1 = result.GetSubVector< 3, 6 >();
	LOG( "Result : " << result );
	LOG( "center : " << center );
	LOG( "v1 : " << v1 );

	VectorNormalization( v1 );

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


	Vector3f intersection1;
	Vector3f intersection2;
	M4D::lineAABBIntersections( minimum, maximum, 
			center, v1,
			intersection1, intersection2
			);
	
	v1 = intersection2 - intersection1;
	VectorNormalization( v1 );


	/*D_PRINT( "minT = " << minT );
	D_PRINT( "maxT = " << maxT );
	D_PRINT( "diffT = " << diffT );*/
	float minDistance = M4D::PointLineDistance( static_cast< Vector3f >( aPoints[0] ), center, v1 );
	for ( size_t i = 1; i < aPoints.size(); ++i ) {
		float tmp = M4D::PointLineDistance( static_cast< Vector3f >( aPoints[i] ), center, v1 );
		minDistance = M4D::min( minDistance, tmp );
	}

	float height = VectorSize( intersection2 - intersection1 );

	aProximalShaftMeasurementData.point = intersection1 - v1 * (0.1f * height);//center + minT * v1;
	aProximalShaftMeasurementData.bboxP1 = intersection1;
	aProximalShaftMeasurementData.bboxP2 = intersection2;


	aProximalShaftMeasurementData.centerPoint = center;
	aProximalShaftMeasurementData.direction = v1;
	aProximalShaftMeasurementData.height = height * 1.2;
	aProximalShaftMeasurementData.radius = minDistance;
	aProximalShaftMeasurementData.available = true;
	aProximalShaftMeasurementData.minimum = minimum;
	aProximalShaftMeasurementData.maximum = maximum;
}
コード例 #18
0
ファイル: RWMain.C プロジェクト: suhanree/OpinionNetwork
int main(int argc, char **argv) {

	using namespace std;

	
	// Command line input test.
	if (argc!=2) {
		cerr << " Usage: RWSim <input filename>\n";
		exit(1);
	};
	// Input filename in a string.
	string infile(argv[1]);

	//===============================================================
	//=================(Input Parameters)============================
	AgentID nagents;
	long xsize;
	long ysize;
	long geometry=1;
	string in_excluded_file;
	PointSet excluded;
	double ag_threshold;
	double op_threshold=0.5;
	short opinion_topology=2;
	short op_init_method=1;
	double gullibility;
	double standard_dev=0.1;
	long int_range=0;
	int neighbor_type_sg=0;
	long agent_max_speed=1;
	int neighbor_type_movement=1;
	long update_method=1;
	long total_time;

	unsigned long rseed1=1;
	unsigned long rseed2=1;
	long max_rn=1000;
	int convergence_method=1;
	long convergence_check_period=10;
	long convergence_out_period=10;

	bool if_snapshot_out=false;
	string out_snapshot_file;
	long out_snapshot_interval=1;

	bool if_ag_snapshot_out=false;
	string out_ag_snapshot_file;
	int out_ag_snapshot_method=0;
	long out_ag_snapshot_interval=1;

	bool if_sg_snapshot_out=false;
	string out_sg_snapshot_file;
	int out_sg_snapshot_method=0;
	long out_sg_snapshot_interval=1;

	bool if_agent_out=false;
	AgentID agent_id;
	string out_agent_file;
	long out_agent_interval=1;

	bool if_summary_out=false;
	string out_summary_file;

	bool if_network_stat_out=false;
	long out_network_stat_time=-1;
	bool if_components_out=false;
	string out_components_file;

	bool if_agraph_in=false;
	string in_agraph_file;
	short in_agraph_file_format=1;
	short in_agraph_method=0;
	long num_edges;
	double wiring_prob;

	bool if_agents_in=false;
	string in_agents_file;

	//===============================================================
	//==============(Reading Input Parameters)=======================
	cout << "1, Reading the input parameters..." << endl;
	InputParam in1(infile);
	in1.read();
	// in1.print_key_val();
	if (!in1.get("nagents",nagents,cerr)) {
		cerr << "# No parameter given: nagents \n";
		cerr << endl;
		exit(1);
	};
	if (!in1.get("xsize",xsize,cerr)) {
		cerr << "# No parameter given: xsize \n";
		exit(1);
	};
	if (!in1.get("ysize",ysize,cerr)) {
		cerr << "# No parameter given: ysize \n";
		exit(1);
	};
	if (!in1.get("geometry",geometry,cerr)) {
		cerr << "# No parameter given: geometry.";
		cerr << " Default value 1 (regular) will be used.\n";
	};
	if (geometry==2 && \
		!in1.get("in_excluded_file",in_excluded_file,cerr)) {
		cerr << "# No parameter given: in_excluded_file \n";
		exit(1);
	};
	if (!in1.get("gullibility",gullibility,cerr)) {
		cerr << "# No parameter given: gullibility \n";
		exit(1);
	};
	if (gullibility<-epsilon && !in1.get("standard_dev",standard_dev,cerr)) {
		cerr << "# No parameter given: standard_dev \n";
		exit(1);
	};
	if (!in1.get("ag_threshold",ag_threshold,cerr)) {
		ag_threshold=1.0/nagents;
		cerr << "# No parameter given: ag_threshold";
		cerr << ". Default value, 1/nagents=" << ag_threshold;
		cerr << ",  will be used.\n";
	};
	if (!in1.get("op_threshold",op_threshold,cerr)) {
		cerr << "# No parameter given: op_threshold";
		cerr << ". Default value, 0.5" << op_threshold;
		cerr << ",  will be used.\n";
	};
	//if (!in1.get("sg_effect",sg_effect,cerr)) {
	//	cerr << "# No parameter given: sg_effect";
	//	cerr << ". Default value, false, will be used.\n";
	//};
	if (!in1.get("opinion_topology",opinion_topology,cerr)) {
		cerr << "# No parameter given: opinion_topology";
		cerr << ". Default value 2 (circular) will be used.\n";
	};
	if (!in1.get("op_init_method",op_init_method,cerr)) {
		cerr << "# No parameter given: op_init_method";
		cerr << ". Default value 1 (random) will be used.\n";
	};
	if (!in1.get("neighbor_type_sg",neighbor_type_sg,cerr)) {
		cerr << "# No parameter given: neighbor_type_sg";
		cerr << ". Default value 0 (no SG effect) will be used.\n";
	};
	if (!in1.get("int_range",int_range,cerr)) {
		cerr << "# No parameter given: int_range";
		cerr << ". Default value 0 will be used.\n";
	};
	if (!in1.get("agent_max_speed",agent_max_speed,cerr)) {
		cerr << "# No parameter given: agent_max_speed";
		cerr << ". Default value 1 will be used.\n";
	};
	if (!in1.get("neighbor_type_movement",neighbor_type_movement,cerr)) {
		cerr << "# No parameter given: neighbor_type_movement";
		cerr << ". Default value 1 (von Neumann+center) will be used.\n";
	};
	if (!in1.get("update_method",update_method,cerr)) {
		cerr << "# No parameter given: update_method";
		cerr << ". Default value 2 (new) will be used.\n";
	};
	if (!in1.get("total_time",total_time,cerr)) {
		cerr << "# No parameter given: total_time \n";
		exit(1);
	};
	double drseed1, drseed2, dmax=2147483647;
	if (!in1.get("rseed1",drseed1,cerr)) {
		cerr << "# No parameter given: rseed1";
		cerr << ". Default value, " << rseed1 << ", will be used.\n";
	}
	else {
		if (drseed1 < 0) drseed1=-drseed1;
		rseed1=(unsigned long) (drseed1-dmax*((unsigned long) (drseed1/dmax))+0.5);
	};
	if (!in1.get("rseed2",drseed2,cerr)) {
		cerr << "# No parameter given: rseed2";
		cerr << ". Default value, " << rseed2 << ", will be used.\n";
	}
	else {
		if (drseed2 < 0) drseed2=-drseed2;
		rseed2=(unsigned long) (drseed2-dmax*((unsigned long) (drseed2/dmax))+0.5);
	};
	if (!in1.get("max_rn",max_rn,cerr)) {
		cerr << "# No parameter given: max_rn";
		cerr << ". Default value, " << max_rn << ", will be used.\n";
	};
	if (!in1.get("convergence_method",convergence_method,cerr)) {
		cerr << "# No parameter given: convergence_method";
		cerr << ". Default value, 1, will be used.\n";
	};
	if (convergence_method && !in1.get("convergence_check_period",convergence_check_period,cerr)) {
		convergence_check_period=xsize*ysize;
		cerr << "# No parameter given: convergence_check_period.\n";
		cerr << "  Default value, xsize*ysize=" << convergence_check_period;
		cerr << ", will be used.\n";
	};
	if (convergence_method>3 && !in1.get("convergence_out_period",convergence_out_period,cerr)) {
		convergence_out_period=convergence_check_period;
		cerr << "# No parameter given: convergence_out_period.\n";
		cerr << "  Default value, convergence_out_period, " << convergence_check_period;
		cerr << ", will be used.\n";
	};
	if (!in1.get("if_snapshot_out",if_snapshot_out,cerr)) {
		cerr << "# No parameter given: if_snapshot_out";
		cerr << ". Default value, false, will be used.\n";
	};
	if (if_snapshot_out && \
		!in1.get("out_snapshot_file",out_snapshot_file,cerr)) {
		cerr << "# No parameter given: out_snapshot_file \n";
		exit(1);
	};
	if (if_snapshot_out && !in1.get("out_snapshot_interval", \
		out_snapshot_interval,cerr)) {
		cerr << "# No parameter given: out_snapshot_interval";
		cerr << ". Default value 1 will be used.\n";
	};
	if (!in1.get("if_ag_snapshot_out",if_ag_snapshot_out,cerr)) {
		cerr << "# No parameter given: if_ag_snapshot_out";
		cerr << ". Default value, false, will be used.\n";
	};
	if (if_ag_snapshot_out && !in1.get("out_ag_snapshot_file",\
		out_ag_snapshot_file,cerr)) {
		cerr << "# No parameter given: out_ag_snapshot_file \n";
		exit(1);
	};
	if (if_ag_snapshot_out && !in1.get("out_ag_snapshot_method",\
		out_ag_snapshot_method,cerr)) {
		cerr << "# No parameter given: out_ag_snapshot_method";
		cerr << ". Default value 0 will be used.\n";
	};
	if (if_ag_snapshot_out && !in1.get("out_ag_snapshot_interval",\
		out_ag_snapshot_interval,cerr)) {
		cerr << "# No parameter given: out_ag_snapshot_interval";
		cerr << ". Default value 1 will be used.\n";
	};
	if (!in1.get("if_sg_snapshot_out",if_sg_snapshot_out,cerr)) {
		cerr << "# No parameter given: if_sg_snapshot_out";
		cerr << ". Default value, false, will be used.\n";
	};
	if (if_sg_snapshot_out && !in1.get("out_sg_snapshot_file",\
		out_sg_snapshot_file,cerr)) {
		cerr << "# No parameter given: out_sg_snapshot_file \n";
		exit(1);
	};
	if (if_sg_snapshot_out && !in1.get("out_sg_snapshot_method",\
		out_sg_snapshot_method,cerr)) {
		cerr << "# No parameter given: out_sg_snapshot_method";
		cerr << ". Default value 0 will be used.\n";
	};
	if (if_sg_snapshot_out && !in1.get("out_sg_snapshot_interval",\
		out_sg_snapshot_interval,cerr)) {
		cerr << "# No parameter given: out_sg_snapshot_interval";
		cerr << ". Default value 1 will be used.\n";
	};
	if (!in1.get("if_agent_out",if_agent_out,cerr)) {
		cerr << "# No parameter given: if_agent_out";
		cerr << ". Default value, false, will be used.\n";
	};
	if (if_agent_out && !in1.get("agent_id",agent_id,cerr)) {
		cerr << "# No parameter given: agent_id \n";
		exit(1);
	};
	if (if_agent_out && !in1.get("out_agent_file",out_agent_file,cerr)) {
		cerr << "# No parameter given: out_agent_file \n";
		exit(1);
	};
	if (if_agent_out && !in1.get("out_agent_interval",\
		out_agent_interval,cerr)) {
		cerr << "# No parameter given: out_agent_interval";
		cerr << ". Default value 1 will be used.\n";
	};
	if (!in1.get("if_summary_out",if_summary_out,cerr)) {
		cerr << "# No parameter given: if_summary_out";
		cerr << ". Default value, false, will be used.\n";
	};
	if (if_summary_out && !in1.get("out_summary_file",\
		out_summary_file,cerr)) {
		cerr << "# No parameter given: out_summary_file \n";
		exit(1);
	};
	if (if_summary_out && !in1.get("if_network_stat_out",if_network_stat_out,cerr)) {
		cerr << "# No parameter given: if_network_stat_out";
		cerr << ". Default value, false, will be used.\n";
	};
	if (if_summary_out && if_network_stat_out && !in1.get("out_network_stat_time",\
		out_network_stat_time,cerr)) {
		cerr << "# No parameter given: out_network_stat_time";
		cerr << ". Default value, -1, will be used.\n";
	};
	if (if_summary_out && if_network_stat_out && !in1.get("if_components_out",if_components_out,cerr)) {
		cerr << "# No parameter given: if_components_out";
		cerr << ". Default value, false, will be used.\n";
	};
	if (if_summary_out && if_network_stat_out && if_components_out && !in1.get("out_components_file",\
		out_components_file,cerr)) {
		cerr << "# No parameter given: out_components_file \n";
		exit(1);
	};
	if (!in1.get("if_agraph_in",if_agraph_in,cerr)) {
		if_agraph_in=false;
		cerr << "# No parameter given: in_agraph_in.";
		cerr << "  Default value, false, will be used.\n";
	};
	if (if_agraph_in) {
		if (in1.get("in_agraph_file",in_agraph_file,cerr)) {
			if (!Util::if_file(in_agraph_file)) {
				cerr << "# File, " << in_agraph_file << ", doesn't exist.";
				cerr << "  AG will be created randomly.\n";
				if_agraph_in=false;
			};
		}
		else {
			cerr << "# No parameter given: in_agraph_file.";
			cerr << "  AG will be created randomly.\n";
			if_agraph_in=false;
		};
	};
	if (if_agraph_in && !in1.get("in_agraph_file_format",in_agraph_file_format,cerr)) {
		cerr << "# No parameter given: in_agraph_file_format.";
		cerr << "  Default value, 1, will be used.\n";
	};
	if (!if_agraph_in && !in1.get("num_edges",num_edges,cerr)) {
		cerr << "# No parameter given: num_edges \n";
		exit(1);
	};
	if (!in1.get("wiring_prob",wiring_prob,cerr) && ((!if_agraph_in && num_edges<0) || update_method>=3)) {
		cerr << "# No parameter given: wiring_prob \n";
		exit(1);
	};
	if (!if_agraph_in && !in1.get("in_agraph_method",in_agraph_method,cerr)) {
		cerr << "# No parameter given: in_agraph_method \n";
		exit(1);
	};
	if (!in1.get("if_agents_in",if_agents_in,cerr)) {
		if_agents_in=false;
		cerr << "# No parameter given: in_agents_in.";
		cerr << "  Default value, false, will be used.\n";
	};
	if (if_agents_in) {
		if (in1.get("in_agents_file",in_agents_file,cerr)) {
			if (!Util::if_file(in_agents_file)) {
				cerr << "# File, " << in_agents_file << ", doesn't exist.";
				cerr << "  Agents will be created randomly.\n";
				if_agents_in=false;
			};
		}
		else {
			cerr << "# No parameter given: in_agents_file.";
			cerr << "  Agents will be created randomly.\n";
			if_agents_in=false;
		};
	};
	
	// close the input parameter file.
	in1.close();

	// Checking values of basic input parameters
	Util::error_check(nagents,xsize,ysize,gullibility,standard_dev,\
		ag_threshold, op_threshold,opinion_topology,op_init_method,neighbor_type_sg,agent_max_speed,\
		(!if_agraph_in && num_edges<0 ? wiring_prob : 0.5),total_time,\
		(if_agraph_in ? 0 : num_edges),rseed1,rseed2,max_rn);

	cout << "\tNumber of agents: " << nagents << endl;

	// Assigning the size of the grid.
	if (geometry==0) { // special case of 1d ring.
		xsize=nagents;
		ysize=1;
		gullibility=1;
		neighbor_type_sg=1;
		agent_max_speed=0;
		neighbor_type_movement=1;
		cout << "\tSpecial case of 1D ring with no agent movement." << endl;
	};
	Point::set_size(xsize,ysize); 
	cout << "\tGrid size: " << Point::get_xsize() << " and " << Point::get_ysize() << endl;
	if (geometry==2) {
		std::ifstream ifile;
		ifile.open(in_excluded_file.c_str(),ios::in);
		if (!ifile) {
			cerr << "# Error: Input file, " << in_excluded_file;
			cerr << ", doesn't exist.\n";
			exit(1);
		};
		long x, y;
		while (ifile >> x >> y && x>=0 && x<xsize && y>=0 && y<ysize) excluded.insert(Point(x,y));
		ifile.close();
		cout << "\t(Total of " << excluded.size() << " points will be excluded.)" << endl;
	};
コード例 #19
0
ファイル: AddScan.cpp プロジェクト: elliotwoods/ofxRulr
					//----------
					vector<AddScan::DataPoint> AddScan::getFitPoints() const {
						Utils::ScopedProcess scopedProcess("Get fit points");

						this->throwIfMissingAConnection<Scan::Graycode>();
						auto graycodeNode = this->getInput<Scan::Graycode>();

						graycodeNode->throwIfMissingAConnection<Item::Camera>();
						auto cameraNode = graycodeNode->getInput<Item::Camera>();

						this->throwIfMissingAConnection<Item::Projector>();
						auto projectorNode = this->getInput<Item::Projector>();

						auto cameraView = cameraNode->getViewInWorldSpace();
						auto projectorView = projectorNode->getViewInWorldSpace();

						auto & scanDataSet = graycodeNode->getDataSet();
						if (!scanDataSet.getHasData()) {
							throw(ofxRulr::Exception("Scan has no data"));
						}

						//start with set of data
						typedef map<uint32_t, ofxGraycode::DataSet::const_iterator> PointSet;
						PointSet activeCameraPixels;
						{
							Utils::ScopedProcess scopedProcessActivePixels("Get all active pixels", false);
							for (ofxGraycode::DataSet::const_iterator pixelIt = scanDataSet.begin(); pixelIt != scanDataSet.end(); pixelIt.operator++()) {
								auto & pixel = pixelIt.operator->();
								if (pixel.active) {
									activeCameraPixels[pixel.camera] = pixelIt;
								}
							}
						}


						//split the data into a 4x4 grid (quad tree approach would be nicer if we have more time)
						//and separate into bins of distance (higher is best)
						const uint32_t GRID_RES = 4;

						//array (per grid square) of map<distance, vector<points>> 
						map<uint8_t, vector<ofxGraycode::DataSet::const_iterator>> pixelsByDistancePerGridSquare[GRID_RES * GRID_RES];

						{
							Utils::ScopedProcess scopedProcessActivePixels("Split scan points into grid and distance bins", false);
							uint32_t gridCellWidth = cameraNode->getWidth() / GRID_RES;
							uint32_t gridCellHeight = cameraNode->getHeight() / GRID_RES;

							for (auto & point : activeCameraPixels) {
								auto & pixel = point.second.operator->();
								auto cameraXY = pixel.getCameraXY();

								int gridIndex = ((uint32_t)cameraXY.x / gridCellWidth) + ((uint32_t)cameraXY.y / gridCellHeight) * GRID_RES;
								pixelsByDistancePerGridSquare[gridIndex][pixel.distance].push_back(point.second);
							}
						}

						
						vector<AddScan::DataPoint> dataPoints;
						size_t targetSize = (float)activeCameraPixels.size() * this->parameters.includeForFitRatio;

						//accumulate fit points and remove as we go along
						{
							Utils::ScopedProcess scopedProcessAccumulatePoints("Split scan points into grid and distance bins", false);
							size_t gridSquare = 0;
							while (dataPoints.size() < targetSize) {
								auto & pointsForThisSquare = pixelsByDistancePerGridSquare[gridSquare];

								//if no bins available, continue to next square
								//remove best bin if empty
								//if no bins available, continue to next square
								//find best point
								//remove it from bin

								{
									if (pointsForThisSquare.empty()) {
										goto continueToNextSquare;
									}
									auto bestPointsIt = pointsForThisSquare.rbegin();
									while (bestPointsIt->second.empty()) {
										pointsForThisSquare.erase(bestPointsIt->first);
										if (pointsForThisSquare.empty()) {
											goto continueToNextSquare;
										}
										bestPointsIt = pointsForThisSquare.rbegin();
									}
									auto point = bestPointsIt->second.back().operator->();
									DataPoint dataPoint{
										cameraView.pixelToCoordinate(point.getCameraXY()),
										projectorView.pixelToCoordinate(point.getProjectorXY()),
										point.median
									};
									dataPoints.push_back(dataPoint);

									bestPointsIt->second.pop_back();
								}
							continueToNextSquare:
								gridSquare++;
								gridSquare %= (GRID_RES * GRID_RES);
							}
						}
						
						scopedProcess.end();

						return dataPoints;
					}