Пример #1
0
bool mitk::PointSetDataInteractor::MoveSet(StateMachineAction*, InteractionEvent* interactionEvent)
{
  InteractionPositionEvent* positionEvent = dynamic_cast<InteractionPositionEvent*>(interactionEvent);
  if (positionEvent != NULL)
  {
    int timeStep = positionEvent->GetSender()->GetTimeStep();
    // Vector that represents movement relative to last position
    Point3D movementVector;
    movementVector[0] = positionEvent->GetPositionInWorld()[0] - m_PointSet->GetPoint(m_SelectedPointIndex, timeStep)[0];
    movementVector[1] = positionEvent->GetPositionInWorld()[1] - m_PointSet->GetPoint(m_SelectedPointIndex, timeStep)[1];
    movementVector[2] = positionEvent->GetPositionInWorld()[2] - m_PointSet->GetPoint(m_SelectedPointIndex, timeStep)[2];

    PointSet* points = dynamic_cast<PointSet*>(GetDataNode()->GetData());
    PointSet::PointsContainer* pointsContainer = points->GetPointSet(timeStep)->GetPoints();

    // Iterate over point set and update each point
    Point3D newPoint;
    for (PointSet::PointsIterator it = pointsContainer->Begin(); it != pointsContainer->End(); it++)
    {
      newPoint[0] = m_PointSet->GetPoint(it->Index(), timeStep)[0] + movementVector[0];
      newPoint[1] = m_PointSet->GetPoint(it->Index(), timeStep)[1] + movementVector[1];
      newPoint[2] = m_PointSet->GetPoint(it->Index(), timeStep)[2] + movementVector[2];
      m_PointSet->SetPoint(it->Index(), newPoint, timeStep);
    }

    GetDataNode()->SetData(m_PointSet);
    GetDataNode()->Modified();
    mitk::RenderingManager::GetInstance()->RequestUpdateAll();
    return true;
  }
  else
  {
    return false;
  }
}
bool RangeProfilePlotManager::mouseMoveEvent(PlotView* pView, QMouseEvent* pEvent)
{
   bool rval = false;
   if (!mMouseStart.isNull())
   {
      double dataX, startY, curY;
      pView->translateScreenToData(0.0, mMouseStart.y(), dataX, startY);
      pView->translateScreenToData(0.0, pEvent->y(), dataX, curY);
      double shift = curY - startY;

      std::list<PlotObject*> selected;
      pView->getSelectedObjects(selected, true);
      for (std::list<PlotObject*>::iterator obj = selected.begin(); obj != selected.end(); ++obj)
      {
         PointSet* pSet = dynamic_cast<PointSet*>(*obj);
         if (pSet != NULL)
         {
            rval = true;
            std::vector<Point*> points = pSet->getPoints();
            for (std::vector<Point*>::iterator point = points.begin(); point != points.end(); ++point)
            {
               LocationType loc = (*point)->getLocation();
               loc.mY -= shift;
               (*point)->setLocation(loc);
            }
         }
      }
      mMouseStart = pEvent->pos();
      pView->refresh();
   }
   return rval;
}
Пример #3
0
int mitk::PointSetDataInteractor::GetPointIndexByPosition(Point3D position, unsigned int time, float accuracy)
{
  // iterate over point set and check if it contains a point close enough to the pointer to be selected
  PointSet* points = dynamic_cast<PointSet*>(GetDataNode()->GetData());
  int index = -1;
  if (points == NULL)
  {
    return index;
  }


  if (points->GetPointSet(time) == nullptr)
    return -1;

  PointSet::PointsContainer* pointsContainer = points->GetPointSet(time)->GetPoints();

  float minDistance = m_SelectionAccuracy;
  if (accuracy != -1 )
    minDistance = accuracy;


  for (PointSet::PointsIterator it = pointsContainer->Begin(); it != pointsContainer->End(); it++)
  {
    float distance = sqrt(position.SquaredEuclideanDistanceTo(points->GetPoint(it->Index(), time)));
    if (distance < minDistance) // if several points fall within the margin, choose the one with minimal distance to position
    {
      index = it->Index();
    }
  }
  return index;
}
Пример #4
0
void PointSets::serializeRead(QDataStream &s, Q3Canvas* canvas)
{
  axesPointSet.serializeRead(s, canvas);
  axesPointSet.attachPointsToPointSet();
  scalePointSet.serializeRead(s, canvas);
  scalePointSet.attachPointsToPointSet();

  int i;
  int count;
  s >> (Q_INT32 &) count;
  for (i = 0; i < count; i++)
  {
    PointSet pointSet;
    pointSet.serializeRead(s, canvas);
    curveList.append(pointSet);
    curveList.last().attachPointsToPointSet();
  }
  s >> (Q_INT32 &) count;
  for (i = 0; i < count; i++)
  {
    PointSet pointSet;
    pointSet.serializeRead(s, canvas);
    measureList.append(pointSet);
    measureList.last().attachPointsToPointSet();
  }
}
Пример #5
0
int PointSets::pointCountMeasure(QString name)
{
  PointSet* pointSet = findMeasure(name);
  if (pointSet == 0)
    return 0;
  else
    return pointSet->pointCount();
}
Пример #6
0
SceneObjectPtr 
PointSet::copy(DeepCopier& copier) const 
{
  PointSet * ptr = new PointSet(*this);
  copier.copy_attribute(ptr->getPointList());
  copier.copy_attribute(ptr->getColorList());
  return SceneObjectPtr(ptr);
}
Пример #7
0
void PointSets::addCurve(QString name)
{
  PointSet pointSet;

  pointSet.setStyle(DefaultSettings::instance().getCurveStyle(curveList.count()));
  pointSet.setName(name);

  curveList.append(pointSet);
}
Пример #8
0
void PointSets::addMeasure(QString name)
{
  PointSet pointSet;

  pointSet.setStyle(DefaultSettings::instance().getMeasureStyle(measureList.count()));
  pointSet.setName(name);

  measureList.append(pointSet);
}
Пример #9
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] ;
    }
  }
}
Пример #10
0
void BaseMesh::WeldVertices(float Epsilon, Vector<UINT> &OldToNewMapping)
{
    PointSet MyPoints;
    MyPoints.LoadFromMesh(*this);
    KDTree3 &Tree = MyPoints.KDTree();
    
    UINT VC = VertexCount(), IC = IndexCount();
    MeshVertex *V = Vertices();
    DWORD *I = Indices();

    OldToNewMapping.ReSize(VC);
    OldToNewMapping.Clear(VC);
    Vector<UINT> NNResult;
    //MeshVertex *VStorage = new MeshVertex[VC];
    
    for(UINT VertexIndex = 0; VertexIndex < VC; VertexIndex++)
    {
        Vec3f Pos = V[VertexIndex].Pos;
        Tree.WithinDistance(Pos, Epsilon, NNResult);
        bool MatchFound = false;
        //VStorage[VertexIndex] = V[VertexIndex];
        for(UINT ResultIndex = 0; ResultIndex < NNResult.Length() && !MatchFound; ResultIndex++)
        {
            UINT CurIndex = NNResult[ResultIndex];
            if(OldToNewMapping[CurIndex] != VC)
            {
                MatchFound = true;
                OldToNewMapping[VertexIndex] = CurIndex;
            }
        }
        if(!MatchFound)
        {
            OldToNewMapping[VertexIndex] = VertexIndex;
        }
    }

    //DWORD *IStorage = new DWORD[IC];
    for(UINT IndexIndex = 0; IndexIndex < IC; IndexIndex++)
    {
        I[IndexIndex] = OldToNewMapping[UINT(I[IndexIndex])];
    }

    //Allocate(
    //delete[] VStorage;
    
    Vector<UINT> SecondMapping, SplitToUnsplit = OldToNewMapping;
    CleanVerticesAndTriangles(SecondMapping);
    for(UINT VertexIndex = 0; VertexIndex < VC; VertexIndex++)
    {
        OldToNewMapping[VertexIndex] = SecondMapping[SplitToUnsplit[VertexIndex]];
    }
}
Пример #11
0
void GjkContactSolver::penetration(const PointSet & A, const PointSet & B, ClosestTestContext * result)
{
	resetSimplex(result->W);
	const Vector3F r = result->rayDirection;
	const Vector3F startP = Vector3F::Zero - result->rayDirection * 99.f;
	Vector3F hitP = startP;
	// from origin to startP
	Vector3F v = hitP;
	Vector3F w, p, pa, pb, localA, localB;
	float lamda = 0.f;
	float vdotw, vdotr;

	int k = 0;
	for(; k < 39; k++) {
		vdotr = v.dot(r);
	
		// SA-B(v)
		pa = A.supportPoint(v, result->transformA, localA, result->margin);
		pb = B.supportPoint(v.reversed(), result->transformB, localB, result->margin);
		p = pa - pb;// + v.normal() * MARGIN_DISTANCE;
		w = hitP - p;
		vdotw = v.dot(w); 
		
		if(vdotw > 0.f) {
			if(vdotr >= 0.f)
				break;
			lamda -= vdotw / vdotr;
			hitP = startP + r * lamda;
		}
				
		addToSimplex(result->W, p, localB);
	
		result->hasResult = 0;
		result->distance = 1e9;
		result->referencePoint = hitP;
	
		closestOnSimplex(result);
	
		v = hitP - result->closestPoint;
		
		interpolatePointB(result);
	
		if(v.length2() < TINY_VALUE) break;
		
		result->separateAxis = v;
	
		smallestSimplex(result);
	}
	
	result->distance = hitP.length();
	result->separateAxis.normalize();
}
Пример #12
0
bool LabelPosition::pruneCallback( LabelPosition *lp, void *ctx )
{
    PointSet *feat = (( PruneCtx* ) ctx )->obstacle;

    if (( feat == lp->feature ) || ( feat->getHoleOf() && feat->getHoleOf() != lp->feature ) )
    {
        return true;
    }

    CostCalculator::addObstacleCostPenalty( lp, feat );

    return true;
}
Пример #13
0
void
KML_Model::parseCoords( xml_node<>* node, KMLContext& cx )
{
    PointSet* point = new PointSet();

    xml_node<>* location = node->first_node("location", 0, false);
    if (location)
    {
        double latitude  = as<double>(getValue(location, "latitude"), 0.0);
        double longitude = as<double>(getValue(location, "longitude"), 0.0);
        double altitude  = as<double>(getValue(location, "altitude"), 0.0);
        point->push_back( osg::Vec3d(longitude, latitude, altitude));
    }    
    _geom = point;
}
Пример #14
0
void
KML_Model::parseCoords( const Config& conf, KMLContext& cx )
{
    PointSet* point = new PointSet();

    Config location = conf.child("location");
    if (!location.empty())
    {
        double latitude  = location.value("latitude",  0.0);
        double longitude = location.value("longitude", 0.0);
        double altitude  = location.value("altitude", 0.0); 
        point->push_back( osg::Vec3d(longitude, latitude, altitude));
    }    
    _geom = point;
}
Пример #15
0
void* native_thread_main(void* data)
{
	CVD::Image<unsigned char> frame_grey = CVD::Image<unsigned char>(CVD::ImageRef(WIDTH, HEIGHT));
	pose received_location;
	
	received_location.x = 0.0;
	received_location.y = 0.0;
	received_location.z = 0.0;
	received_location.yaw = 0.0;
	
	start_time = util_timestamp();
	while(true)
	{
		//double t1 = util_timestamp();
		get_frame_grey(frame_grey.data());

		corners.build_from_image(frame_grey, drone_xy_lookup, true);//use_rhips

		client_socket.sendto(corners, server_addr, server_addr_len);
		//fprintf(log_file2,"%f,%d\n", (util_timestamp()-t1), corners.size());
		
		pthread_yield();

		if(client_socket.recvfrom(command, server_addr, server_addr_len))
		{
			received_location.x = command.packet.transform[0];
			received_location.y = command.packet.transform[1];
			received_location.z = command.packet.transform[2];
			received_location.yaw = command.packet.transform[4];
			
			if(filter_pose(&received_location))
			{
				pthread_mutex_lock(&the_mutex);
				
				last_good_location.x = received_location.x;
				last_good_location.y = received_location.y;
				last_good_location.z = received_location.z;
				last_good_location.yaw = received_location.yaw;		
				
				time_last_good = util_timestamp();
				
				pthread_mutex_unlock(&the_mutex);
				
				fprintf(log_file,"%f,%f,%f,%f,%f\n"
					,time_last_good   	// timestamp in sec  
					,received_location.x   	// x loction            
					,received_location.y  	// y location    
					,received_location.z		// Z location
					,received_location.yaw);
			}
		}

		frames_processed++;
		//printf("found %d corners\n", corners.size());
		//printf("estimated pose (x,y,z,yaw): %f, %f, %f, %f\n", received_location.x, received_location.y, received_location.z, received_location.yaw);   
		
		while(!video_frame_ready())
			usleep(50);
	}
}
Пример #16
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;
}
Пример #17
0
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;
}
Пример #18
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;
}
/*
 * Check whether the DataNode contains a pointset, if not create one and add it.
 */
void mitk::SinglePointDataInteractor::DataNodeChanged()
{
  if (GetDataNode() != nullptr)
  {
    PointSet *points = dynamic_cast<PointSet *>(GetDataNode()->GetData());
    if (points == NULL)
    {
      m_PointSet = PointSet::New();
      GetDataNode()->SetData(m_PointSet);
    }
    else
    {
      points->Clear();
      m_PointSet = points;
    }
  }
}
Пример #20
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;
}
	inline void frommxArray(const mxArray *ParamArray) {
		/*
		 * This function expects the ParamArray to be a MATLAB structure with 
		 * at-least the following fields
		 * 
		 *   a - single - scalar
		 *   b - single - scalar
		 *   c - single - scalar
		 *   d - single - scalar
		 *   
		 *   GridXSpec - single - vector of length 3
		 *   GridYSpec - single - vector of length 3
		 *   
		 *   GridXSpec = [GridXBegin, GridXStep, GridXEnd]
		 *   GridYSpec = [GridYBegin, GridYStep, GridYEnd]
		 *
		 *   onemsbyTstep - uint32_t - scalar
		 *
		 *   InitialPointSet - should be a valid 'PointVector' struct representing
		 *                     the region of points from which to search ahead.
		 */
		getInputfromStruct<float>(ParamArray, "a", this->a, getInputOps(2, "is_required", "required_size", 1));
		getInputfromStruct<float>(ParamArray, "b", this->b, getInputOps(2, "is_required", "required_size", 1));
		getInputfromStruct<float>(ParamArray, "c", this->c, getInputOps(2, "is_required", "required_size", 1));
		getInputfromStruct<float>(ParamArray, "d", this->d, getInputOps(2, "is_required", "required_size", 1));

		uint32_t onemsbyTstep;
		getInputfromStruct<uint32_t>(ParamArray, "onemsbyTstep", onemsbyTstep, getInputOps(2, "is_required", "required_size", 1));

		MexVector<float> GridXSpec;
		MexVector<float> GridYSpec;

		getInputfromStruct<float>(ParamArray, "GridXSpec", GridXSpec, getInputOps(2, "is_required", "required_size", 3));
		getInputfromStruct<float>(ParamArray, "GridYSpec", GridYSpec, getInputOps(2, "is_required", "required_size", 3));

		float eps = 1E-10; // epsilon used for floating point comparisons
		uint32_t XGridMax, YGridMax;
		XGridMax = uint32_t((GridXSpec[2] - GridXSpec[0])/GridXSpec[1] + 2*eps) + 1;// largest n such that (n-1)*GridXSpec[1] + GridXSpec[0] <= GridXSpec[2]
		YGridMax = uint32_t((GridYSpec[2] - GridYSpec[0])/GridYSpec[1] + 2*eps) + 1;// largest n such that (n-1)*GridYSpec[1] + GridYSpec[0] <= GridYSpec[2]

		this->PrivateTransform.scaleX = GridXSpec[1];
		this->PrivateTransform.scaleY = GridYSpec[1];
		this->PrivateTransform.shiftX = GridXSpec[0];
		this->PrivateTransform.shiftY = GridYSpec[0];

		this->XRange = {0, XGridMax};
		this->YRange = {0, YGridMax};

		this->timeStep = 1.0f / onemsbyTstep;

		// Calculate the Grid Y Coordinate for 30.0V
		auto GridY30V = this->Transform.toGridCoords(SinglePoint(0, 30.0f)).y;
		GridY30V = (GridY30V >= YGridMax)? YGridMax : GridY30V;
		for(uint32_t i=0; i < XGridMax; ++i) {
			Point gridPoint(i, uint32_t(GridY30V+0.5f));
			PrivateInitialPointSet.insert(gridPoint);
		}
	}
Пример #22
0
void initnative() 
{
	corners.erase();

	the_corners.set_max_size(16);
	the_corner_scores.set_max_size(16);
	the_max_corners.set_max_size(16);
	the_max_corner_descriptors.set_max_size(16);
	
	drone_xy_lookup = Image<TooN::Vector<2, float> >(ImageRef(WIDTH, HEIGHT));

	std::ifstream is;
	is.open("dronecamparameters.txt");
	drone_camera_model.load(is);
	is.close();
	
	//TooN::Vector<6> cam_params = drone_camera_model.get_parameters();
	//printf("cam params: %f %f %f %f %f %f\n", cam_params[0], cam_params[1], cam_params[2], cam_params[3], cam_params[4], cam_params[5]);
	generate_xy_lookup(drone_camera_model, drone_xy_lookup);

	client_socket.create(serverip, serverport);
	
	log_file = fopen("udp_logX.csv", "wb");
	if(log_file==NULL)
	{
		printf("File 2 open failed\n");
	}
	fprintf(log_file,"Time,X (m),Y (m),Z (m),Yaw (rad)\n");
	
	/*log_file2 = fopen("udp_log2.csv", "wb");
	if(log_file2==NULL)
	{
		printf("File 3 open failed\n");
	}
	fprintf(log_file2,"Time,Corners\n");*/
	
	//init front camera
	while(video_init((char*) "/dev/video1", WIDTH, HEIGHT, 30))
	{
		printf("Camera initialisation failed. Retry in 2 seconds...\n");
		sleep(2);
	}
	printf("video_init completed\n");
	
	sleep(2);
	
	int rc = pthread_create(&native_thread, NULL, native_thread_main, NULL);
	if (rc)
		printf("ctl_Init: Return code from pthread_create(native_thread) is %d\n", rc);
	
	last_good_location.x = 0.0;	
	last_good_location.y = 0.0;
	last_good_location.z = 0.0;
	last_good_location.yaw = 0.0;
	
	printf("native_init completed\n");
}
void RangeProfilePlotManager::signatureRenamed(Subject& subject, const std::string& signal, const boost::any& value)
{
   std::string newName = boost::any_cast<std::string>(value);
   DataDescriptor& desc = dynamic_cast<DataDescriptor&>(subject);
   for (std::map<Signature*, std::string>::iterator sig = mSigPointSets.begin(); sig != mSigPointSets.end(); ++sig)
   {
      if (sig->first->getDataDescriptor() == &desc)
      {
         PointSet* pSet = getPointSet(sig->first);
         if (pSet != NULL)
         {
            pSet->setObjectName(newName);
            mSigPointSets[sig->first] = newName;
            return;
         }
      }
   }
}
Пример #24
0
FilterContext
CentroidFilter::push(FeatureList& features, FilterContext& context )
{
    for( FeatureList::iterator i = features.begin(); i != features.end(); ++i )
    {
        Feature* f = i->get();
        
        Geometry* geom = f->getGeometry();
        if ( !geom )
            continue;

        PointSet* newGeom = new PointSet();
        newGeom->push_back( geom->getBounds().center() );

        f->setGeometry( newGeom );
    }

    return context;
}
Пример #25
0
void PointSets::setName(QString oldName, QString newName)
{
  ASSERT_ENGAUGE(oldName != AxesPointSetName);
  ASSERT_ENGAUGE(oldName != ScalePointSetName);

  PointSet* pointSet = findCurve(oldName);
  if (pointSet)
  {
    pointSet->setName(newName);
    return;
  }

  pointSet = findMeasure(oldName);
  if (pointSet)
  {
    pointSet->setName(newName);
    return;
  }
}
/*
  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]]));
    }

  }
Пример #27
0
PointSet *PointSet::get(DOMNode *node) {
	
	unsigned int i; 				// variable to counter
	DOMNamedNodeMap *attributes;	// variable to hold the node attributes
	
	PointSet *pointSet;
	
	attributes = node->getAttributes();
	for (i = 0; i < attributes->getLength(); i++) {
		if (!strcmp(XMLString::transcode(attributes->item(i)->getNodeName()) , "USE")) {
			return((PointSet *)getLink(XMLString::transcode(attributes->item(i)->getNodeValue())));
		} 
	}
	
	pointSet = new PointSet();
	pointSet->read(node);
		
	return pointSet;
	
}
Пример #28
0
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;
	}
}
Пример #29
0
void ReadConcept(Inputor& in, PointSet &pointSet, 
								 unsigned int recordType)
{
	string str;
	pointSet.reserve(in._num);
	double x,y,z;
	double I;
	double r,g,b;

	PointRec::Reset_I();
	do
	{
		switch(recordType){
	case XYZ:
		in.getLine(str, '\n');
		sscanf(str.c_str(), "%lf %lf %lf", &x, &y, &z);
		pointSet.push_back(PointRec(x,y,z));
		break;
	case XYZI:
		in.getLine(str, '\n');
		sscanf(str.c_str(), "%lf %lf %lf %lf", &x, &y, &z, &I);
		pointSet.push_back(PointRec(x,y,z,I));
		PointRec::Update_I(I);
		break;
	case XYZRGB:
		in.getLine(str, '\n');
		sscanf(str.c_str(), "%lf %lf %lf %lf %lf %lf", &x, &y, &z, &r, &g, &b);
		pointSet.push_back(PointRec(x,y,z,-1, r, g, b));
		break;
	case XYZIRGB:
		in.getLine(str, '\n');
		sscanf(str.c_str(), "%lf %lf %lf %lf %lf %lf %lf", &x, &y, &z, &I, &r, &g, &b);
		pointSet.push_back(PointRec(x,y,z, I, r, g, b));
		PointRec::Update_I(I);
		break;
		}
		in.frame();
	}while(!in.isEnd());
}
Пример #30
0
    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();
    }