void FunctorClass::fundapcpp()
{
  double arrl[LIM] = {1, 2, 3, 4, 5, 6};
  double arr2[LIM] = {7, 8, 9, 1, 2, 3};
  std::vector<double> gr8(arrl, arrl + LIM);
  std::vector<double> m8(arr2, arr2 + LIM);
  std::cout.setf(std::ios_base::fixed);
  std::cout.precision(2); // number of numbers after dot
  std::cout << "gr8:\t";
  for_each(gr8.begin(), gr8.end(), show);
  std::cout << std::endl;
  std::cout << "m8: \t";
  for_each(m8.begin (), m8.end(), show);
  std::cout << std::endl;

  std::vector<double> sum(LIM);
  transform(gr8.begin (), gr8.end(), m8.begin(), sum.begin(), std::plus<double> ());
  std::cout << "sum:\t";
  for_each(sum.begin (), sum.end(), show);
  std::cout << std::endl;
  
  std::vector<double> prod(LIM);
  transform(gr8.begin (), gr8.end(), prod.begin(), bind1st(std::multiplies<double> (), 2.5));

  std::cout << "prod:\t";
  for_each(prod.begin (), prod.end(), show);
  std::cout << std::endl;

}
    bool next_permutation(BidiIt first, BidiIt last) {
        // Get a reversed range to simplify reversed traversal.
        const auto rfirst = reverse_iterator<BidiIt>(last);
        const auto rlast = reverse_iterator<BidiIt>(first);

        // Begin from the second last element to the first element.
        auto pivot = next(rfirst);

        // Find `pivot`, which is the first element that is no less than its
        // successor.  `Prev` is used since `pivort` is a `reversed_iterator`.
        while (pivot != rlast && *pivot >= *prev(pivot))
            ++pivot;

        // No such elemenet found, current sequence is already the largest
        // permutation, then rearrange to the first permutation and return false.
        if (pivot == rlast) {
            reverse(rfirst, rlast);
            return false;
        }

        // Scan from right to left, find the first element that is greater than
        // `pivot`.
        auto change = find_if(rfirst, pivot, bind1st(less<int>(), *pivot));

        swap(*change, *pivot);
        reverse(rfirst, pivot);

        return true;
    }
Exemple #3
0
void TestSTL::test_adaptors()
{
	/**
	*  bind1st function template: constructs an unary function object from a binary function object,
	*  by binding the first parameter to a certain value.
	*/

	int array[] = { 1, -99, 2, -100 };
	int arraySize = sizeof(array)/sizeof(array[0]);

	std::vector<int> vec1(array, array + arraySize);
	std::vector<int>::iterator newEnd;
	//Calls std::less(0, element). If less(0,element) returns true => remove that element
	newEnd = std::remove_if(vec1.begin(), vec1.end(), bind1st(std::less<int>(), 0));

	for(std::vector<int>::iterator it = vec1.begin(); it != newEnd; ++it)
	{
		TESTIFY_ASSERT(*it < 0);
	}

	/**
	*  bind2nd function template: constructs an unary function object from a binary function object,
	*  by binding the second parameter to a certain value.
	*/
	std::vector<int> vec2(array, array + arraySize);

	//Calls std::greater(element, 0). If element greater(element, 0) returns true => remove that element
	newEnd = std::remove_if(vec2.begin(), vec2.end(), bind2nd(std::greater<int>(), 0));
	for(std::vector<int>::iterator it = vec2.begin(); it != newEnd; ++it)
	{
		TESTIFY_ASSERT(*it < 0);
	}
}
Exemple #4
0
/*
**	Refresh the map.
*/
void	Gui::dump()
{
  size_t	x = 0;
  size_t	y = 1;
  size_t const	width = m_nibbler.getWidth();
  size_t const	height = m_nibbler.getHeight();
  std::string	map = m_nibbler.getMap();
  std::ostringstream	os;

  os << m_nibbler.getScore();
  if (wmove(m_win, height + 2, width / 2 - os.str().size() / 2) == -1)
    throw (NibError("ncurses_wmove", "fail"));
  if (wrefresh(m_win) == -1)
    throw (NibError("ncurses_wrefresh", "fail"));
  if (waddstr(m_win, os.str().c_str()) == -1)
    throw (NibError("ncurses_waddstr", "fail"));
  if (wrefresh(m_win) == -1)
    throw (NibError("ncurses_wrefresh", "fail"));
  while (x < width * height)
    {
      if (wmove(m_win, y++, 1) == -1)
	throw (NibError("ncurses_wmove", "fail"));
      if (wrefresh(m_win) == -1)
	throw (NibError("ncurses_wrefresh", "fail"));
      std::string line(map.substr(x, width).c_str());
      std::for_each(line.begin(), line.end(), bind1st(std::mem_fun(&Gui::tcPutchar), this));
      x += width;
    }
  if (wrefresh(m_win) == -1)
    throw (NibError("ncurses_wrefresh", "fail"));
}
Exemple #5
0
 string genNext(string s) {
     string ss;
     for (auto i = s.begin(); i != s.end(); i++) {
         auto j = find_if(i, s.end(), bind1st(not_equal_to<char>(), *i));
         ss << distance(i, j) << *i;
         i = j;
     }
 }
Exemple #6
0
void Dictionary::insert(std::string &str){
  Word w(str);
  auto it = std::find_if(vec.begin(), vec.end(), bind1st(std::equal_to<Word>(),w));
  if(it != vec.end())
    it->freq++;
  else
    vec.push_back(Word(str));
}
Exemple #7
0
 string getNext(const string &s) {
     stringstream ss;
     for (auto i = s.begin(); i != s.end(); ) {
         auto j = find_if(i, s.end(), bind1st(not_equal_to<char>(), *i));
         ss << distance(i, j) << *i;
         i = j;
     }
     return ss.str();
 }
void Genome::allele(const std::wstring& name,double val)
{
	ALLELE::iterator it=find_if(m_Alleles.begin(),m_Alleles.end(),
								bind1st(pair_equal_to<std::wstring,double>(),name));
	if(it!=m_Alleles.end())
		it->second=val;
	else
		m_Alleles.push_back(std::make_pair<std::wstring,double>(std::wstring(name),double(val)));
}
 string getNext(const string& str) {
     string next_seq = "";
     for(auto i=str.cbegin();i!=str.cend();) {
         auto j = find_if(i,str.cend(),bind1st(not_equal_to<char>(), *i));
         next_seq.append(to_string(distance(i,j)));
         next_seq.push_back(*i);
         i = j;
     }
     return next_seq;
 }
Exemple #10
0
void index_set::collect_variable_set(const std::vector<int>& marked_as_cse) {

	ASSERT(constraint_variable_set.empty());

	marked_cse = Set(marked_as_cse.begin(), marked_as_cse.end());

	look_for_cse_mismatch();

	for_each(constraint_index_sets.begin(), constraint_index_sets.end(), bind1st(mem_fun(&index_set::copy_vars), this));
}
Exemple #11
0
void TestBigFill (const size_t size, const T magic)
{
    vector<T> vbig (size);
    fill (vbig.begin() + 1, vbig.end(), magic);		// offset to test prealignment loop
    typename vector<T>::const_iterator iMismatch;
    iMismatch = find_if (vbig.begin() + 1, vbig.end(), bind1st (not_equal_to<T>(), magic));
    if (iMismatch == vbig.end())
	cout << "works\n";
    else
	cout.format ("does not work: mismatch at %zd, =0x%lX\n", abs_distance (vbig.begin(), iMismatch), (unsigned long)(*iMismatch));
}
Exemple #12
0
void	Ncurses::display(std::list<t_snake> snake, const t_food food)
{
  wclear(_game);
  draw_border();
  for_each(snake.begin(), snake.end(), bind1st(std::mem_fun(&Ncurses::snake_body), this));
  snake_head(snake.begin()->x, snake.begin()->y);
  wattron(_game, COLOR_PAIR(1));
  mvwprintw(_game, food.y + 1, food.x + 1, "@");
  wattroff(_game, COLOR_PAIR(1));
  speedup(snake.begin()->x, snake.begin()->y, food.x, food.y);
  wrefresh(_game);
}
Exemple #13
0
/*public*/
void
MCIndexNoder::computeNodes(SegmentString::NonConstVect* inputSegStrings)
{
	nodedSegStrings = inputSegStrings;
	assert(nodedSegStrings);

	for_each(nodedSegStrings->begin(), nodedSegStrings->end(),
			bind1st(mem_fun(&MCIndexNoder::add), this));

	intersectChains();
//cerr<<"MCIndexNoder: # chain overlaps = "<<nOverlaps<<endl;
}
	const Item* Container::getItem(int itemId) const
	{
		ItemSet::const_iterator it = find_if(mItems.begin(), mItems.end(),
			bind1st(FindItemById(), itemId));
		if (it != mItems.end())
		{
			return (*it);
		}
		else
		{
			Throw(IllegalArgumentException, "Item nicht in Container.");
		}
	}
Exemple #15
0
void index_set::copy_vars(const Set* indices) {

	vector<int> tmp;

	// copy_if variable -> copy_if_not not variable

	remove_copy_if(indices->begin(), indices->end(), inserter(tmp, tmp.begin()),
			bind1st(mem_fun(&index_set::not_variable), this));

	ASSERT(!tmp.empty());

	constraint_variable_set.push_back(tmp);
}
Exemple #16
0
/*public*/
std::auto_ptr< std::vector<geom::Coordinate> >
OffsetPointGenerator::getPoints()
{
	assert (offsetPts.get() == NULL);
	offsetPts.reset(new vector<Coordinate>());

	vector<const LineString*> lines;
	geos::geom::util::LinearComponentExtracter::getLines(g, lines);
	for_each(lines.begin(), lines.end(),
		bind1st(mem_fun(&OffsetPointGenerator::extractPoints), this));

	return offsetPts;
}
 Item* Container::removeItem(int itemId)
 {
     Item* rval = 0;
     ItemSet::iterator it = find_if(mItems.begin(), mItems.end(),
         bind1st(FindItemById(), itemId));
     if (it != mItems.end())
     {
         rval = *it;
         mItems.erase(it);
     }
     else
     {
         Throw(IllegalArgumentException, "Item nicht in Container.");
     }
     return rval;
 }
 void nextPermutation(vector<int> &num) {
     vector<int>::reverse_iterator rlast = num.rend();
     vector<int>::reverse_iterator rit = num.rbegin();
     while(rit!=rlast){
         if(*rit > *(++rit))
             break;
     }
     if(rit == rlast){
         reverse(num.begin(), num.end());
         return;
     }
     vector<int>::reverse_iterator change = find_if(num.rbegin(), rit, bind1st(less<int>(), *rit));
     swap(*rit, *change);
     reverse(num.rbegin(), rit);
     return;
 }
Exemple #19
0
//vcDists: sorted pair<id, dist>. 
void CRegionalMetaModel::SubdividTrainingData( dist_pair_vector& vcDists, vector< vector<int> >& vcIdSet, int min_pts )
{
	//step 1. find the media's id.
	REAL rMaxDist = vcDists[ vcDists.size()-1 ].second;
	REAL rMinDist = vcDists[ 0 ].second;

	dist_pair_vector::iterator pos = find_if( vcDists.begin(), vcDists.end(), bind1st(op_dist_less(), make_pair(0, (rMaxDist+rMinDist)/2.0)) );
	if( pos>vcDists.end()-min_pts ){
		pos = max( vcDists.begin(), vcDists.end()-min_pts );
	}
	if( vcDists.end() - pos > min_pts ) pos = vcDists.end() - min_pts;

	//check how many points can be sampled.
	int nFirstHalfPts = pos - vcDists.begin();
	int nSecndHalfPts = vcDists.size() - nFirstHalfPts;
	if( 2*nSecndHalfPts > vcDists.size() || nFirstHalfPts<min_pts){
		//there are not enough points to support the next subdivition, stop it.
		vector<int> vcIds;
		vcIds.resize( vcDists.size() );
		for( int i=0; i<vcDists.size(); i++ )vcIds[i] = vcDists[i].first;
		vcIdSet.push_back( vcIds );
	}else{
		//save the first half dist pairs
		//will sample from the first half ids.
		dist_pair_vector vcTmpDists( vcDists.begin(), pos );

		//sample from the first half
		vector<int> vcIds = SampleIds( vcTmpDists, nSecndHalfPts );

		//then sample all the points in the second half
		vcIds.reserve( vcIds.size()+nSecndHalfPts );
		for( int i=0; i<nSecndHalfPts; i++ )vcIds.push_back( (*pos++).first );

		//put it into the vcIdSet and do the next subdivition
		vcIdSet.push_back( vcIds );

		//need a subdivition.
		SubdividTrainingData( vcTmpDists, vcIdSet, min_pts );
	}
}
Exemple #20
0
 bool next_permutation(t first, t last) {
     if (first == last) return false;
     
     auto rFirst = reverse_iterator<t>(last);
     auto rLast = reverse_iterator<t>(first);
     
     auto pivot = next(rFirst);
     
     while (pivot != rLast && *pivot > *(pivot - 1))
         pivot++;
     
     if (pivot == rLast) {
         reverse(first, last);
         return false;
     }
     
     auto change = find_if(rFirst, pivot, bind1st(less<int>(), *pivot));
     
     swap(*change, *pivot);
     reverse(rFirst, pivot);
     
     return true;
 }
Exemple #21
0
	void sortColors(int A[],int n)
	{
		partition(partition(A,A+n,bind1st(equal_to<int>(),0)),A+n,
			bind1st(equal_to<int>(),1));
	}
 void sortColors(vector<int>& nums) {
     partition(partition(nums.begin(), nums.end(), bind1st(equal_to<int>(), 0)),
              nums.end(), bind1st(equal_to<int>(), 1));
 }
Exemple #23
0
void NNFitnessFcn(int nVars, int nPopSize, double* pPop, double* pScore)
{
	Matrix pop(nPopSize, nVars, pPop);
	pop = !pop;
	Matrix score(nPopSize, 1);
	Matrix chrom, ch_sc, diff;
	Matrix mean = pop.vMean();
	bool bBad;
	//bounds penalty coefs
	Matrix bpc = pnna->ga_.opt_.initRange.GetRows(1) - pnna->ga_.opt_.initRange.GetRows(0);
	bpc *= 0.1;
	transform(bpc.begin(), bpc.end(), bpc.begin(), bind1st(divides<double>(), 1));
	//calc scores
	for(ulong i=0; i<score.size(); ++i) {
		chrom = pop.GetColumns(i);
		bBad = false;
		//score[i] = 0;
		/*
		for(ulong j=0; j<chrom.size(); ++j) {
			if(chrom[j] < pnna->_ga.opt_.initRange(0, j) || chrom[j] > pnna->_ga.opt_.initRange(1, j)) {
				score[i] = 1;
				bBad = true;
				break;
			}
		}
		*/
		if(pnna->opt_.normInp)
			chrom /= pnna->state_.max_ch_r;
		if(pnna->opt_.usePCA)
			chrom <<= pnna->netPCA_->Sim(chrom - pnna->state_.inpMean);

		if(pnna->opt_.netType == matrix_nn)
			ch_sc = pnna->net_.Sim(chrom);
		else
			ch_sc = pnn->sim(chrom);

		//if(bBad || pnna->opt_.pred_ratio <= 0) continue;
		if(pnna->opt_.pred_ratio > 0 && ch_sc[0] < pnna->state_.n_cur_min)
			ch_sc[0] += pow((pnna->state_.n_cur_min - ch_sc[0])/pnna->state_.pred_r, 4);

		score[i] = ch_sc[0];

		//check bounds
		if(1 == 1) {
			chrom <<= !chrom;
			diff <<= chrom - pnna->ga_.opt_.initRange.GetRows(0);
			replace_if(diff.begin(), diff.end(), bind2nd(greater<double>(), 0), 0);
			//multiply by penalty coefs
			diff *= bpc;
			score[i] += abs(score[i])*diff.Mul(diff).Sum();
			//score[i] -= abs(score[i])*diff.Sum();

			diff <<= pnna->ga_.opt_.initRange.GetRows(1) - chrom;
			replace_if(diff.begin(), diff.end(), bind2nd(greater<double>(), 0), 0);
			//multiply by penalty coefs
			diff *= bpc;
			score[i] += abs(score[i])*diff.Mul(diff).Sum();
			//score[i] -= abs(score[i])*diff.Sum();
		}
	}
	//score = pnna->GetRealData(score);
	memcpy(pScore, score.GetBuffer(), score.raw_size());
}
   // Assign to a function object.
   function<void(int)> f1 = bind1st(mem_fun(&square::square_value), &s);
   call<int> c1(f1);

   // Alternatively, use the auto keyword to have the compiler deduce the type.
   auto f2 = bind1st(mem_fun(&square::square_value), &s);
   call<int> c2(f2);
Exemple #25
0
/**
* Example using STL adaptors
*/
void STLMoblet::STL_adaptors()
{
	LOG("\n");
	LOG("========================= STL adaptors ==========================================================================");

	LOG("/**");
	LOG("* Function object adaptors are used to create a function object from another function object."				);
	LOG("* The created function object, is not the same as the original functor, but is adapted to a certain need."	);
	LOG("* For example if we have a function object like std::less, and we want to compare all the elements"		);
	LOG("* in a range against 10, then be can use an STL adaptor (bind2nd), that bounds the second argument"		);
	LOG("* of std::less to 10. Then we can use std::less with algorithms like remove_copy_if,"						);
	LOG("* that need a unary predicate."																			);
	LOG("*"																											);
	LOG("* STL provides two functor adaptors: bind1st and bind2nd."													);
	LOG("*"																											);
	LOG("* 	bind1st: constructs an unary function object from a binary function object, by binding"					);
	LOG("* 	the first argument to a fixed value."																	);
	LOG("*"																											);
	LOG("* 	bind1st template function is defined like this:"														);
	LOG("*"																											);
	LOG("*   binder1st<SomeFunctor> bind1st (const SomeFunctor& fun, const T& fixedValue"							);
	LOG("*	{"																										);
	LOG("*		return binder1st<SomeFunctor>(fun, x);"																);
	LOG("*	}"																										);
	LOG("*"																											);
	LOG("*	bind1st returns an binder1st object, which is actually a functor that forwards the function calls"		);
	LOG("*	to the \"fun\" argument it takes as a parameter, when constructed:"										);
	LOG("*"																											);
	LOG("*	template <class Functor> class binder1st {"																);
	LOG("*"																											);
	LOG("*		binder1st(const Functor &fun, Functor::first_argument_type &fixed)"									);
	LOG("*		{"																									);
	LOG("*			mFun = fun;"																					);
	LOG("*			mFixedValue = fixed;"																			);
	LOG("*		}"																									);
	LOG("*"																											);
	LOG("*		Functor::result_type operator()(Functor::second_argument_type &someValue){"							);
	LOG("*			return mFun(mFixedValue, someValue);"															);
	LOG("*		}"																									);
	LOG("*	};"																										);
	LOG("*"																											);
	LOG("*	bind2nd is implemented in a similar way, but instead of binding the first argument,"					);
	LOG("*	bind2nd it will bind the second one to a fixed value."													);
	LOG("*"																											);
	LOG("*	bind1st and bind2nd function templates are defined in the <functional> header."							);
	LOG("*/");
	LOG("\n");

	LOG("				Example using adaptors 							  ");


	LOG("\n																				   ");
	LOG("/**"																				);
	LOG("*  bind1st function template: constructs an unary function object from a"			);
	LOG("*  binary function object, by binding the first parameter to a certain value."		);
	LOG("\n    */"																			);

	log_to_console("\n     Example using std::bind1st:\n");

	int array[] = { 1, -99, 2, -100 };
	int arraySize = sizeof(array)/sizeof(array[0]);

	std::vector<int> vec1(array, array + arraySize);
	log_to_console(vec1, "vec1 contains: ");

	LOG("\n"																		);
	LOG("/**std::remove_if calls std::less(0, element). If less(0,element) returns"	);
	LOG("*  true => removes that element."											);
	LOG("*  less(0,element) is equivalent to 0<element."							);
	LOG("*/"																		);
	LOG("\n"																		);

	TRACE(std::vector<int>::iterator newEnd = std::remove_if(vec1.begin(),
			vec1.end(), bind1st(std::less<int>(), 1)));

	log_to_console("vec1 after calling std::remove_if(vec1.begin(), vec1.end(), "
			"bind1st(std::less<int>(), 0)): ");
	for(std::vector<int>::iterator it = vec1.begin(); it != newEnd; ++it)
	{
		log_to_console(*it);
	}


	LOG("\n"															      	  );
	LOG("/**"																  	  );
	LOG("*  bind2nd function template: constructs an unary function object from a");
	LOG("*  binary function object, by binding the second parameter to a certain" );
	LOG("*  value."															 	  );
	LOG("*/"																	  );

	log_to_console("\n     Example using std::bind2nd:\n");

	std::vector<int> vec2(array, array + arraySize);
	log_to_console(vec2, "vec2 contains: ");

	LOG("\n"																	  );
	LOG("/**  std::remove_if calls std::greater(element, 0)."					  );
	LOG("*  If std::greater(element, 0) returns true => removes that element."	  );
	LOG("*  std::greater(element, 0) is equivalent to element > 0"				  );
	LOG("*/"																	  );
	LOG("\n");

	TRACE(newEnd = std::remove_if(vec2.begin(), vec2.end(),
			bind2nd(std::greater<int>(), 0)));

	log_to_console("vec2 after calling: std::remove_if(vec2.begin(), vec2.end(), "
			"bind2nd(std::greater<int>(), 0));");

	for(std::vector<int>::iterator it = vec2.begin(); it != newEnd; ++it)
	{
		log_to_console(*it);
	}
	LOG("\n");
}
Exemple #26
0
  void OutputCSTBonds(ostream &ofs, OBMol &mol, string prefix)
  {
    string bond_type;

    /* ---- Write povray-description of all bonds---- */
    for(unsigned int i = 0; i < mol.NumBonds(); ++i)
      {

        double x1,y1,z1,x2,y2,z2; /* Start and stop coordinates of a bond       */
        double dist;              /* Distance between (x1|y1|z1) and (x2|y2|z2) */
        double phi,theta;         /* Angles between (x1|y1|z1) and (x2|y2|z2)   */
        double dy;                /* Distance between (x1|0|z1) and (x2|0|z2)   */

        /* ---- Get a pointer to ith atom ---- */
        OBBond *bond = mol.GetBond(i);

        /* ---- Assign start of bond i ---- */
        x1 = (bond -> GetBeginAtom()) -> GetX();
        y1 = (bond -> GetBeginAtom()) -> GetY();
        z1 = (bond -> GetBeginAtom()) -> GetZ();

        /* ---- Assign end of bond i ---- */
        x2 = (bond -> GetEndAtom()) -> GetX();
        y2 = (bond -> GetEndAtom()) -> GetY();
        z2 = (bond -> GetEndAtom()) -> GetZ();

        /* ---- Calculate length of bond and (x1|0|z1) - (x2|0|z2) ---- */
        dist = sqrt(SQUARE(x2-x1) + SQUARE(y2-y1) + SQUARE(z2-z1));
        dy = sqrt(SQUARE(x2-x1) + SQUARE(z2-z1));

        /* ---- Calculate Phi and Theta ---- */
        phi = (double) 0.0;
        theta = (double) 0.0;
        if (fabs(dist) >= EPSILON)
          phi = acos((y2-y1)/dist);
        if (fabs(dy) >= EPSILON)
          theta = acos((x2-x1)/dy);

        /* ---- Begin of description of bond i (for a capped sticks model) ---- */
        ofs << "#declare " << prefix << "_bond" << i << " = object {" << endl;
        ofs << "\t  union {" << endl;

        /* ---- Begin of Start-Half of Bond (i) ---- */
        ofs << "\t   object {" << endl << "\t    bond_" << bond -> GetBondOrder()  << "\n";

        /* ---- Add a pigment - statement for start-atom of bond ---- */
        bond_type = bond->GetBeginAtom() -> GetType();
        bond_type.erase(remove_if(bond_type.begin(), bond_type.end(), bind1st(equal_to<char>(), '.')), bond_type.end());
        ofs << "\t    pigment{color Color_"
            << bond_type
            << "}" << endl;

        /* ---- Scale bond if needed ---- */
        if (fabs((double) 2.0 * dist) >= EPSILON)
          {

            /* ---- Print povray scale-statement (x-Axis) ---- */
            ofs << "\t    scale <" << (double) 0.5 * dist << ",1.0000,1.0000>" << endl;

          }

        /* ---- Rotate (Phi) bond if needed ---- */
        if (fabs(RAD2DEG(-phi) + (double) 90.0) >= EPSILON)
          {

            /* ---- Rotate along z-axis ---- */
            ofs << "\t    rotate <0.0000,0.0000,"
                << RAD2DEG(-phi) + (double) 90.0
                << ">" << endl;

          }

        /* ---- Check angle between (x1|0|z1) and (x2|0|z2) ---- */
        if (theta >= EPSILON)
          {

            /* ---- Check direction ---- */
            if ((z2 - z1) >= (double) 0.0)
              {

                /* ---- Rotate along y-Axis (negative) ---- */
                ofs << "\t    rotate <0.0000,"
                    << RAD2DEG((double) -1.0 *theta) << ",0.0000>"
                    << endl;

              }
            else
              {

                /* ---- Rotate along y-Axis (positive) ---- */
                ofs << "\t    rotate <0.0000," << RAD2DEG(theta) << ",0.0000>" << endl;

              }

          }

        /* ---- Translate bond to start ---- */

        ofs << "\t    translate " << prefix << "_pos_" << bond -> GetBeginAtomIdx() << endl;

        /* ---- End of description of Start-Bond ---- */
        ofs << "\t   }" << endl;

        /* ---- Begin of End-Half of Bond i ---- */
        ofs << "\t   object {" << endl << "\t    bond_" << bond -> GetBondOrder() << endl;

        /* ---- Add a pigment - statement for end-atom of bond i ---- */
        bond_type = bond->GetEndAtom() -> GetType();
        bond_type.erase(remove_if(bond_type.begin(), bond_type.end(), bind1st(equal_to<char>(), '.')), bond_type.end());

        ofs << "\t    pigment{color Color_"
            << bond_type
            << "}" << endl;

        /* ---- Scale bond if needed ---- */
        if (fabs((double) 2.0 * dist) >= EPSILON)
          {

            /* ---- Print povray scale-statement (x-Axis) ---- */
            ofs << "\t    scale <" << (double) 0.5 * dist << ",1.0000,1.0000>" << endl;

          }

        /* ---- Rotate (Phi) bond if needed ---- */
        if (fabs(RAD2DEG(-phi) + (double) 270.0) >= EPSILON)
          {

            /* ---- Rotate along z-axis (oposite to start half) ---- */
            ofs << "\t    rotate <0.0000,0.0000,"
                << (RAD2DEG(-phi) + (double) 90.0) + (double) 180.0
                << ">" << endl;

          }

        /* ---- Check angle between (x1|0|z1) and (x2|0|z2) ---- */
        if (fabs(theta) >= EPSILON)
          {

            /* ---- Check direction ---- */
            if ((z2 - z1) >= (double) 0.0)
              {

                /* ---- Rotate along y-Axis (negative) (oposite orientation) ---- */
                ofs << "\t    rotate <0.0000,"
                    << RAD2DEG((double) -1.0 * theta)
                    << ",0.0000>"
                    << endl;

              }
            else
              {

                /* ---- Rotate along y-Axis (positive) (oposite orientation) ---- */
                ofs << "\t    rotate <0.0000," << RAD2DEG(theta) << ",0.0000>" << endl;

              }

          }

        /* ---- Translate bond to end ---- */
        ofs << "\t    translate " << prefix << "_pos_" << bond -> GetEndAtomIdx() << endl;

        /* ---- End of description of End-Bond ---- */
        ofs << "\t   }" << endl;

        /* ---- End of description of bond i ---- */
        ofs << "\t  }" << endl << "\t }" << endl << endl;

      }

  }
Exemple #27
0
const char* _Delimiter::_M_scan_for_delim(const char* __first, const char* __last) const
{
    return find_if(__first, __last, bind1st(mem_fun(&_Delimiter::_M_is_delim), this));
}
Exemple #28
0
HMMNetwork* HMM::makeHMMNetwork(const Vector<WordIndex>& es,
                                const Vector<WordIndex>&fs,
                                bool doInit) const {
  unsigned int i,j;
  unsigned int l = es.size() - 1;
  unsigned int m = fs.size() - 1;
  unsigned int I=2*l,J=m;
  int IJ=I*J;
  bool DependencyOfJ=(CompareAlDeps&(16|8))||(g_prediction_in_alignments==2);
  bool DependencyOfPrevAJ=(CompareAlDeps&(2|4))||(g_prediction_in_alignments==0);
  HMMNetwork *net = new HMMNetwork(I,J);
  fill(net->alphainit.begin(),net->alphainit.end(),0.0);
  fill(net->betainit.begin(),net->betainit.end(),0.0);
  for (j=1;j<=m;j++)
  {
    for (i=1;i<=l;i++)
      net->n(i-1,j-1)=tTable.getProb(es[i], fs[j]);
    double emptyContribution=0;
    emptyContribution=tTable.getProb(es[0],fs[j]);
    for (i=1;i<=l;i++)
      net->n(i+l-1,j-1)=emptyContribution;
    net->finalMultiply*=max(normalize_if_possible_with_increment(&net->n(0,j-1),&net->n(0,j-1)+IJ,J),double(1e-12));
  }
  if (DependencyOfJ)
    net->e.resize(m-1);
  else
    net->e.resize(J>1);
  for (j=0;j<net->e.size();j++)
  {
    int frenchClass=fwordclasses.getClass(fs[1+min(int(m)-1,int(j)+1)]);
    net->e[j].resize(I,I,0);
    for (unsigned int i1=0;i1<I;++i1) {
      Array<double> al(l);
      CLASSIFY2(i1,i1real);
      for (unsigned int i2=0;i2<l;i2++)
        al[i2]=probs.getAlProb(i1real,i2,l,m,ewordclasses.getClass(es[1+i1real]),frenchClass
                               ,j+1);
      normalize_if_possible(conv<double>(al.begin()),conv<double>(al.end()));
      if (SmoothHMM&2)
        smooth_standard(conv<double>(al.begin()),conv<double>(al.end()),HMMAlignmentModelSmoothFactor);
      for (unsigned int i2=0;i2<I;i2++) {
        CLASSIFY(i2,empty_i2,i2real);
        net->e[j](i1,i2)      = al[i2real];

        if (empty_i2)
          if (i1real!=i2real)
          {
            net->e[j](i1,i2)=0;
          }
          else
          {
            net->e[j](i1,i2)=doInit?al[0]:(probs.getProbabilityForEmpty()); // make first HMM iteration like IBM-1
          }
      }
      normalize_if_possible(&net->e[j](i1,0),&net->e[j](i1,0)+I);
    }
  }
  if (doInit)
  {
    for (unsigned int i=0;i<I;++i)
    {
      net->alphainit[i]=net->betainit[i]=(i<I/2)?1:(2.0/I);
      net->betainit[i]=1.0;
    }
  }
  else
  {
    if (DependencyOfPrevAJ==0)
    {
      for (i=0;i<I;i++)
      {
        CLASSIFY2(i,ireal);
        net->alphainit[i]=probs.getAlProb(-1,ireal,l,m,0,fwordclasses.getClass(fs[1+0]),0);
      }
    }
    else
    {
      if (g_uniform_entry_exit&2)probs.getBetaInit(I,net->betainit);
      if (g_uniform_entry_exit&1)probs.getAlphaInit(I,net->alphainit);
    }
  }
  MASSERT( net->alphainit.size()==I);MASSERT( net->betainit.size()==I);
  normalize_if_possible(conv<double>(net->alphainit.begin()),conv<double>(net->alphainit.end()));
  normalize_if_possible(conv<double>(net->betainit.begin()),conv<double>(net->betainit.end()));
  transform(net->betainit.begin(),net->betainit.end(),net->betainit.begin(),bind1st(multiplies<double>(),2*l));
  return net;
}
	void print_()
	{
		int a[10]={0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; //arguments for print(int a)
		std::vector<int> v(a, a+10);
		std::for_each(v.begin(), v.end(), bind1st(std::mem_fun(&myClass::printInt), this));
	}
/*public*/
void
MCIndexSnapRounder::computeVertexSnaps(SegmentString::NonConstVect& edges)
{
	for_each(edges.begin(), edges.end(), bind1st(mem_fun(&MCIndexSnapRounder::computeEdgeVertexSnaps), this));
}