Exemplo n.º 1
0
void pop_heap(size_t n, int *heap) {
  if (n > 1) {
    swap(heap, 0, n - 1);
    heapify(n - 1, heap, 0);
  }
}
Exemplo n.º 2
0
void Swap::optimizeAlg(int nIterations)
{
    swap(nIterations);
}
static int
hash_ipport4_uadt(struct ip_set *set, struct nlattr *tb[],
		  enum ipset_adt adt, u32 *lineno, u32 flags, bool retried)
{
	const struct hash_ipport *h = set->data;
	ipset_adtfn adtfn = set->variant->adt[adt];
	struct hash_ipport4_elem e = { };
	struct ip_set_ext ext = IP_SET_INIT_UEXT(h);
	u32 ip, ip_to, p = 0, port, port_to;
	bool with_ports = false;
	int ret;

	if (unlikely(!tb[IPSET_ATTR_IP] ||
		     !ip_set_attr_netorder(tb, IPSET_ATTR_PORT) ||
		     !ip_set_optattr_netorder(tb, IPSET_ATTR_PORT_TO) ||
		     !ip_set_optattr_netorder(tb, IPSET_ATTR_TIMEOUT) ||
		     !ip_set_optattr_netorder(tb, IPSET_ATTR_PACKETS) ||
		     !ip_set_optattr_netorder(tb, IPSET_ATTR_BYTES)))
		return -IPSET_ERR_PROTOCOL;

	if (tb[IPSET_ATTR_LINENO])
		*lineno = nla_get_u32(tb[IPSET_ATTR_LINENO]);

	ret = ip_set_get_ipaddr4(tb[IPSET_ATTR_IP], &e.ip) ||
	      ip_set_get_extensions(set, tb, &ext);
	if (ret)
		return ret;

	if (tb[IPSET_ATTR_PORT])
		e.port = nla_get_be16(tb[IPSET_ATTR_PORT]);
	else
		return -IPSET_ERR_PROTOCOL;

	if (tb[IPSET_ATTR_PROTO]) {
		e.proto = nla_get_u8(tb[IPSET_ATTR_PROTO]);
		with_ports = ip_set_proto_with_ports(e.proto);

		if (e.proto == 0)
			return -IPSET_ERR_INVALID_PROTO;
	} else
		return -IPSET_ERR_MISSING_PROTO;

	if (!(with_ports || e.proto == IPPROTO_ICMP))
		e.port = 0;

	if (adt == IPSET_TEST ||
	    !(tb[IPSET_ATTR_IP_TO] || tb[IPSET_ATTR_CIDR] ||
	      tb[IPSET_ATTR_PORT_TO])) {
		ret = adtfn(set, &e, &ext, &ext, flags);
		return ip_set_eexist(ret, flags) ? 0 : ret;
	}

	ip_to = ip = ntohl(e.ip);
	if (tb[IPSET_ATTR_IP_TO]) {
		ret = ip_set_get_hostipaddr4(tb[IPSET_ATTR_IP_TO], &ip_to);
		if (ret)
			return ret;
		if (ip > ip_to)
			swap(ip, ip_to);
	} else if (tb[IPSET_ATTR_CIDR]) {
		u8 cidr = nla_get_u8(tb[IPSET_ATTR_CIDR]);

		if (!cidr || cidr > 32)
			return -IPSET_ERR_INVALID_CIDR;
		ip_set_mask_from_to(ip, ip_to, cidr);
	}

	port_to = port = ntohs(e.port);
	if (with_ports && tb[IPSET_ATTR_PORT_TO]) {
		port_to = ip_set_get_h16(tb[IPSET_ATTR_PORT_TO]);
		if (port > port_to)
			swap(port, port_to);
	}

	if (retried)
		ip = ntohl(h->next.ip);
	for (; !before(ip_to, ip); ip++) {
		p = retried && ip == ntohl(h->next.ip) ? ntohs(h->next.port)
						       : port;
		for (; p <= port_to; p++) {
			e.ip = htonl(ip);
			e.port = htons(p);
			ret = adtfn(set, &e, &ext, &ext, flags);

			if (ret && !ip_set_eexist(ret, flags))
				return ret;
			else
				ret = 0;
		}
	}
	return ret;
}
Exemplo n.º 4
0
static void solve_l1r_lr(
	const problem *prob_col, double *w, double eps, 
	double Cp, double Cn)
{
	int l = prob_col->l;
	int w_size = prob_col->n;
	int j, s, iter = 0;
	int max_iter = 1000;
	int active_size = w_size;
	int max_num_linesearch = 20;

	double x_min = 0;
	double sigma = 0.01;
	double d, G, H;
	double Gmax_old = INF;
	double Gmax_new;
	double Gmax_init;
	double sum1, appxcond1;
	double sum2, appxcond2;
	double cond;

	int *index = new int[w_size];
	schar *y = new schar[l];
	double *exp_wTx = new double[l];
	double *exp_wTx_new = new double[l];
	double *xj_max = new double[w_size];
	double *C_sum = new double[w_size];
	double *xjneg_sum = new double[w_size];
	double *xjpos_sum = new double[w_size];
	feature_node *x;

	double C[3] = {Cn,0,Cp};

	for(j=0; j<l; j++)
	{
		exp_wTx[j] = 1;
		if(prob_col->y[j] > 0)
			y[j] = 1;
		else
			y[j] = -1;
	}
	for(j=0; j<w_size; j++)
	{
		w[j] = 0;
		index[j] = j;
		xj_max[j] = 0;
		C_sum[j] = 0;
		xjneg_sum[j] = 0;
		xjpos_sum[j] = 0;
		x = prob_col->x[j];
		while(x->index != -1)
		{
			int ind = x->index-1;
			double val = x->value;
			x_min = min(x_min, val);
			xj_max[j] = max(xj_max[j], val);
			C_sum[j] += C[GETI(ind)];
			if(y[ind] == -1)
				xjneg_sum[j] += C[GETI(ind)]*val;
			else
				xjpos_sum[j] += C[GETI(ind)]*val;
			x++;
		}
	}

	while(iter < max_iter)
	{
		Gmax_new = 0;

		for(j=0; j<active_size; j++)
		{
			int i = j+rand()%(active_size-j);
			swap(index[i], index[j]);
		}

		for(s=0; s<active_size; s++)
		{
			j = index[s];
			sum1 = 0;
			sum2 = 0;
			H = 0;

			x = prob_col->x[j];
			while(x->index != -1)
			{
				int ind = x->index-1;
				double exp_wTxind = exp_wTx[ind];
				double tmp1 = x->value/(1+exp_wTxind);
				double tmp2 = C[GETI(ind)]*tmp1;
				double tmp3 = tmp2*exp_wTxind;
				sum2 += tmp2;
				sum1 += tmp3;
				H += tmp1*tmp3;
				x++;
			}

			G = -sum2 + xjneg_sum[j];

			double Gp = G+1;
			double Gn = G-1;
			double violation = 0;
			if(w[j] == 0)
			{
				if(Gp < 0)
					violation = -Gp;
				else if(Gn > 0)
					violation = Gn;
				else if(Gp>Gmax_old/l && Gn<-Gmax_old/l)
				{
					active_size--;
					swap(index[s], index[active_size]);
					s--;
					continue;
				}
			}
			else if(w[j] > 0)
				violation = fabs(Gp);
			else
				violation = fabs(Gn);

			Gmax_new = max(Gmax_new, violation);

			// obtain Newton direction d
			if(Gp <= H*w[j])
				d = -Gp/H;
			else if(Gn >= H*w[j])
				d = -Gn/H;
			else
				d = -w[j];

			if(fabs(d) < 1.0e-12)
				continue;

			d = min(max(d,-10.0),10.0);

			double delta = fabs(w[j]+d)-fabs(w[j]) + G*d;
			int num_linesearch;
			for(num_linesearch=0; num_linesearch < max_num_linesearch; num_linesearch++)
			{
				cond = fabs(w[j]+d)-fabs(w[j]) - sigma*delta;

				if(x_min >= 0)
				{
					double tmp = exp(d*xj_max[j]);
					appxcond1 = log(1+sum1*(tmp-1)/xj_max[j]/C_sum[j])*C_sum[j] + cond - d*xjpos_sum[j];
					appxcond2 = log(1+sum2*(1/tmp-1)/xj_max[j]/C_sum[j])*C_sum[j] + cond + d*xjneg_sum[j];
					if(min(appxcond1,appxcond2) <= 0)
					{
						x = prob_col->x[j];
						while(x->index != -1)
						{
							exp_wTx[x->index-1] *= exp(d*x->value);
							x++;
						}
						break;
					}
				}

				cond += d*xjneg_sum[j];

				int i = 0;
				x = prob_col->x[j];
				while(x->index != -1)
				{
					int ind = x->index-1;
					double exp_dx = exp(d*x->value);
					exp_wTx_new[i] = exp_wTx[ind]*exp_dx;
					cond += C[GETI(ind)]*log((1+exp_wTx_new[i])/(exp_dx+exp_wTx_new[i]));
					x++; i++;
				}

				if(cond <= 0)
				{
					int i = 0;
					x = prob_col->x[j];
					while(x->index != -1)
					{
						int ind = x->index-1;
						exp_wTx[ind] = exp_wTx_new[i];
						x++; i++;
					}
					break;
				}
				else
				{
					d *= 0.5;
					delta *= 0.5;
				}
			}

			w[j] += d;

			// recompute exp_wTx[] if line search takes too many steps
			if(num_linesearch >= max_num_linesearch)
			{
				info("#");
				for(int i=0; i<l; i++)
					exp_wTx[i] = 0;

				for(int i=0; i<w_size; i++)
				{
					if(w[i]==0) continue;
					x = prob_col->x[i];
					while(x->index != -1)
					{
						exp_wTx[x->index-1] += w[i]*x->value;
						x++;
					}
				}

				for(int i=0; i<l; i++)
					exp_wTx[i] = exp(exp_wTx[i]);
			}
		}

		if(iter == 0)
			Gmax_init = Gmax_new;
		iter++;
		if(iter % 10 == 0)
			info(".");

		if(Gmax_new <= eps*Gmax_init)
		{
			if(active_size == w_size)
				break;
			else
			{
				active_size = w_size;
				info("*");
				Gmax_old = INF;
				continue;
			}
		}

		Gmax_old = Gmax_new;
	}

	info("\noptimization finished, #iter = %d\n", iter);
	if(iter >= max_iter)
		info("\nWARNING: reaching max number of iterations\n");

	// calculate objective value
	
	double v = 0;
	int nnz = 0;
	for(j=0; j<w_size; j++)
		if(w[j] != 0)
		{
			v += fabs(w[j]);
			nnz++;
		}
	for(j=0; j<l; j++)
		if(y[j] == 1)
			v += C[GETI(j)]*log(1+1/exp_wTx[j]);
		else
			v += C[GETI(j)]*log(1+exp_wTx[j]);

	info("Objective value = %lf\n", v);
	info("#nonzeros/#features = %d/%d\n", nnz, w_size);

	delete [] index;
	delete [] y;
	delete [] exp_wTx;
	delete [] exp_wTx_new;
	delete [] xj_max;
	delete [] C_sum;
	delete [] xjneg_sum;
	delete [] xjpos_sum;
}
Exemplo n.º 5
0
static void solve_l2r_l1l2_svc(
	const problem *prob, double *w, double eps, 
	double Cp, double Cn, int solver_type)
{
	int l = prob->l;
	int w_size = prob->n;
	int i, s, iter = 0;
	double C, d, G;
	double *QD = new double[l];
	int max_iter = 1000;
	int *index = new int[l];
	double *alpha = new double[l];
	schar *y = new schar[l];
	int active_size = l;

	// PG: projected gradient, for shrinking and stopping
	double PG;
	double PGmax_old = INF;
	double PGmin_old = -INF;
	double PGmax_new, PGmin_new;

	// default solver_type: L2R_L2LOSS_SVC_DUAL
	double diag[3] = {0.5/Cn, 0, 0.5/Cp};
	double upper_bound[3] = {INF, 0, INF};
	if(solver_type == L2R_L1LOSS_SVC_DUAL)
	{
		diag[0] = 0;
		diag[2] = 0;
		upper_bound[0] = Cn;
		upper_bound[2] = Cp;
	}

	for(i=0; i<w_size; i++)
		w[i] = 0;
	for(i=0; i<l; i++)
	{
		alpha[i] = 0;
		if(prob->y[i] > 0)
		{
			y[i] = +1; 
		}
		else
		{
			y[i] = -1;
		}
		QD[i] = diag[GETI(i)];

		feature_node *xi = prob->x[i];
		while (xi->index != -1)
		{
			QD[i] += (xi->value)*(xi->value);
			xi++;
		}
		index[i] = i;
	}

	while (iter < max_iter)
	{
		PGmax_new = -INF;
		PGmin_new = INF;

		for (i=0; i<active_size; i++)
		{
			int j = i+rand()%(active_size-i);
			swap(index[i], index[j]);
		}

		for (s=0; s<active_size; s++)
		{
			i = index[s];
			G = 0;
			schar yi = y[i];

			feature_node *xi = prob->x[i];
			while(xi->index!= -1)
			{
				G += w[xi->index-1]*(xi->value);
				xi++;
			}
			G = G*yi-1;

			C = upper_bound[GETI(i)];
			G += alpha[i]*diag[GETI(i)];

			PG = 0;
			if (alpha[i] == 0)
			{
				if (G > PGmax_old)
				{
					active_size--;
					swap(index[s], index[active_size]);
					s--;
					continue;
				}
				else if (G < 0)
					PG = G;
			}
			else if (alpha[i] == C)
			{
				if (G < PGmin_old)
				{
					active_size--;
					swap(index[s], index[active_size]);
					s--;
					continue;
				}
				else if (G > 0)
					PG = G;
			}
			else
				PG = G;

			PGmax_new = max(PGmax_new, PG);
			PGmin_new = min(PGmin_new, PG);

			if(fabs(PG) > 1.0e-12)
			{
				double alpha_old = alpha[i];
				alpha[i] = min(max(alpha[i] - G/QD[i], 0.0), C);
				d = (alpha[i] - alpha_old)*yi;
				xi = prob->x[i];
				while (xi->index != -1)
				{
					w[xi->index-1] += d*xi->value;
					xi++;
				}
			}
		}

		iter++;
		if(iter % 10 == 0)
			info(".");

		if(PGmax_new - PGmin_new <= eps)
		{
			if(active_size == l)
				break;
			else
			{
				active_size = l;
				info("*");
				PGmax_old = INF;
				PGmin_old = -INF;
				continue;
			}
		}
		PGmax_old = PGmax_new;
		PGmin_old = PGmin_new;
		if (PGmax_old <= 0)
			PGmax_old = INF;
		if (PGmin_old >= 0)
			PGmin_old = -INF;
	}

	info("\noptimization finished, #iter = %d\n",iter);
	if (iter >= max_iter)
		info("\nWARNING: reaching max number of iterations\nUsing -s 2 may be faster (also see FAQ)\n\n");

	// calculate objective value

	double v = 0;
	int nSV = 0;
	for(i=0; i<w_size; i++)
		v += w[i]*w[i];
	for(i=0; i<l; i++)
	{
		v += alpha[i]*(alpha[i]*diag[GETI(i)] - 2);
		if(alpha[i] > 0)
			++nSV;
	}
	info("Objective value = %lf\n",v/2);
	info("nSV = %d\n",nSV);

	delete [] QD;
	delete [] alpha;
	delete [] y;
	delete [] index;
}
Exemplo n.º 6
0
void
ZcrossPath::start_sil(Bface *f )
{

   /*
    *
    *  the face class accessor to vertices, edges, etc 
    *  f->v() , f->e(), etc. all take a point from 1 to 3
    *  this is a huge pain when you are trying to move around
    *  the triangle, so i store my values , - g , ex1, ex2, 
    *  in the 0 to 2 range 
    *
    */



   /* the call to has_sil returns if mesh has been looked at
    * and ALWAYS marks it as such. be careful..
    *
    *  this should really be called sil_marked(); or something
    */
   if (!has_sil(f))
      return; //f has been zx_checked this frame


   double g[3]; //
   int ex1, ex2 , nex1, nex2; //indices of cross edges, in 0-2;
   //ex1  is vertex 1 of edge 1 ( and index to edge )
   //nex1 is vertex 2 of edge 1
   bool bgrad;

   get_g(f, g, ex1, ex2 ); //calculates g values, and where

   Bface *f1;
   Bface *f2;

   Bface *iter_f; //iterator for mesh traversal;
   nex1 = (ex1+1)%3;
   nex2 = (ex2+1)%3;

   // new iterators for mesh traversal
   Bvert * svrt[3];
   double sg[3];

   //never check across a crease boundary ()
   //it's a discontinuity in the isosurface

   f1 = ( f->e(ex1+1)->is_crease()) ? NULL : f->nbr(ex1+1);
   f2 = ( f->e(ex2+1)->is_crease()) ? NULL : f->nbr(ex2+1);


   //case 1 - we search and close the loop
   //case 2 - we do not close loop -> so search backward, fix

   double alph1 = -g[ex1] / (g[nex1] - g[ex1]);
   Wpt pt1 = interp ( f->v(ex1+1)->loc(), f->v(nex1+1)->loc(), alph1);

   double alph2 = -g[ex2] / (g[nex2] - g[ex2]);
   Wpt pt2 = interp ( f->v(ex2+1)->loc(), f->v(nex2+1)->loc(), alph2);


   // gradient test;
   int gmax = ( g[0] > g[1] ) ? 0 : 1;
   gmax = ( g[2] > g[gmax] ) ? 2 : gmax;

   Wvec v_iso = pt1 - pt2;
   Wvec v_max = f->v(gmax+1)->loc() - pt2;
   Wvec v_grad = v_max.orthogonalized(v_iso);
   bgrad = ( ( _eye - pt2 ) * v_grad  > 0 ) ;

   //we always move clockwise
   // more specifically, if gradient is up, we always
   // check in the same direction

   // you only have to check once

   if ( cross( v_grad , f->norm()) * v_iso > 0 ) {
      swap ( pt1, pt2);
      swap ( alph1, alph2);
      swap ( f1, f2);
      swap ( ex1, ex2 );
      swap ( nex1, nex2);
   }

   //if everything switches, so does bgrad!

   //vert is the front ( according to gradient ) vertex on the list
   //we were going to use it for visibility, but at the moment it's
   //useless.

   // store our own barycentric coordinate

   Wvec bc;
   bc[ex2] = 1.0-alph2;
   bc[nex2] = alph2;


   //start search on f1



   int cstart = num(); // index start of this chain (for case 2 );

   iter_f = f;
   add_seg ( f , pt2, f->v(ex2+1), bgrad, f);

   if (f1) {

      svrt  [0]   = f->v(ex2+1) ;     //initialize cache values
      sg    [0]   = g[ex2];        //for sil_search
      svrt  [1]   = f->v(nex2+1);     //skee-daddle
      sg    [1]   = g[nex2];

      //we start at f, having already added the previous point
      while ( iter_f ) {

         iter_f = sil_walk_search(iter_f, svrt, sg);

         if ( iter_f == f ) {  //closed loop

            if ( !( _segs[cstart].p()  == _segs.last().p() ) ) {
               //cerr << "XXX ZcrossPath::start_sil():: points are not equal" << endl;
               //                 Wpt a = _segs[cstart].p();
               //                 Wpt b = _segs.last().p();
               //cerr << "diff:" << (a-b).length() << endl;
               _segs.last().p() = _segs[cstart].p() ;
            }
            _segs.last().setf( NULL );
            _segs.last().set_end(); 
            _segs.last().set_bary(f2);

            return;
         }

      }
   } else {
      add_seg ( NULL , pt1, f->v(ex1+1), bgrad, f);
   }

   //if we are this far, we have a section of
   //silhouette in the forward direction, ( it may only cross one triangle tho )
   //which ran across a discontinuity

   //now check for the stretch in the opposite direction

   int chain2start = num(); // index of start of next chain

   if ( !f2 )
      return; // first face in reverse direction is NULL, we are done.

   //find second chain, which needs to be reversed
   //starts at pt2;


   iter_f  = f2;
   add_seg ( f2 , pt2, f->v(ex2+1), bgrad, f2);

   svrt[0] = f->v(ex2+1) ;     //initialize cached values
   sg[0]  = g[ex2];  //for sil_search
   svrt[1] = f->v(nex2+1);
   sg[1]  = g[nex2];

   while ( iter_f ) {
      iter_f = sil_walk_search ( iter_f, svrt, sg );
   }
   int chain2end = num();
   // second chain is found in wrong order, so we flip it


   // reversal code


   int chain2num = (chain2end - chain2start) -1 ;
   if ( chain2num < 0 )
      return;

   _segs.insert(cstart, chain2num);
   int last_ind = num()-1;

   int j=0;
   for ( ; j < chain2num ; j++ ) {
      _segs[last_ind-j].setf( _segs[last_ind-(j+1)].f() );      //shift the faces over by one
      //AND any per-face values
      _segs[last_ind-j].setg(_segs[last_ind-(j+1)].g());        //grad associates with face
      _segs[last_ind-j].set_bary(_segs[last_ind-j].f());        //recalc barycentric
   }
   for ( j=0; j < chain2num ; j++) {
      _segs[cstart+j] = _segs.pop();
   }

   _segs.pop(); //last point was the duplicate

   return;
}
Exemplo n.º 7
0
config &config::operator=(config &&cfg)
{
	clear();
	swap(cfg);
	return *this;
}
Exemplo n.º 8
0
 inline void SetSectionTimes(TTimes & v)
 {
   swap(m_times, v);
 }
Exemplo n.º 9
0
void sort( double * a, double * b, double * c ){
    if (*a < *b) swap(a, b);
    if (*b < *c) swap(b, c);
    if (*a < *b) swap(a, b);
    printf("%f, %f, %f\n", *a, *b, *c);
}
Exemplo n.º 10
0
Wvec
sym_mat_eigenvalues(const WMat3& A)
{
   // Algorithm from "Eigenvalues of a symmetric 3x3 matrix"
   //   by Oliver K. Smith
   //   http://portal.acm.org/citation.cfm?doid=355578.366316

   if (!A.is_symmetric()) {
      cerr << "sym_mat_eigenvalues: error: matrix is not symmetric:"
           << endl
           << A
           << endl;
      return Wvec();
   }

   // m is 1/3 of the trace of A
   double m = A.trace()/3;

   cerr << "m: " << m
        << endl;

   // B = (A - Im)
   WMat3 B = A - WMat3()*m;

   cerr << "B: "
        << endl
        << B
        << endl;

   // q is 1/2 the determinant of B
   double q = B.det()/2;

   cerr << "q: " << q
        << endl;

   // p is 1/6 the sum of squares of B
   double p = (B[0].length_sqrd() +
               B[1].length_sqrd() +
               B[2].length_sqrd())/6;

   cerr << "p: " << p
        << endl;

   double theta = atan(sqrt(fabs(pow(p,3) - sqr(q)))/q)/3;

   cerr << "theta: " << theta
        << endl;

   // compute eigenvalues:
   Wvec l; 
   l[0] = m + 2*sqrt(p)*cos(theta);
   l[1] = m - sqrt(p)*(cos(theta) + sqrt(3)*sin(theta));
   l[2] = m - sqrt(p)*(cos(theta) - sqrt(3)*sin(theta));

   // they should all be positive
   assert(l[0] > -epsAbsMath() &&
          l[1] > -epsAbsMath() &&
          l[2] > -epsAbsMath());
   l[0] = max(l[0],0.0);
   l[1] = max(l[1],0.0);
   l[2] = max(l[2],0.0);

   // set near-zero values to zero:
   if (isZero(l[0])) l[0] = 0;
   if (isZero(l[1])) l[1] = 0;
   if (isZero(l[2])) l[2] = 0;

   // re-order so l[0] >= l[1] >= l[2]:
   if (l[0]<l[1]) swap(l[0],l[1]);
   if (l[0]<l[2]) swap(l[0],l[2]);
   if (l[1]<l[2]) swap(l[1],l[2]);

   // set near-equal values equal:
   if (isEqual(l[0],l[1])) l[1] = l[0];
   if (isEqual(l[1],l[2])) l[2] = l[1];
   
   cerr << "eigenvalues: "
        << l[0] << ", " << l[1] << ", " << l[2]
        << endl;

   return l;
}
Exemplo n.º 11
0
 inline void SetTurnInstructions(TTurns & v)
 {
   swap(m_turns, v);
 }
Exemplo n.º 12
0
/*
Cette méthode tri le vecteur en fonction du type du tri (par Titre ou Auteur).
Une fois le vecteur trié, on efface la BDD et on recopie chaque élément du vecteur dans le fichier.
Pour le tri, on utilise un tri à bulle.
*/
void Bibliotheque::tri(string pTri)
{
	bool tab_en_ordre = false;
	bool deja_tri = true; 
	//Ce booléen va permettre de savoir si le vecteur est déjà trié, évitant de perdre du temps à le parcourir

	//On vérifie que le choix du tri est valide
    if(pTri == "titre")
    {
		unsigned int taille = this->_bibli.size();

		while(!tab_en_ordre)
		{
		    tab_en_ordre = true;

		    for(unsigned int i=0 ; i < taille-1 ; i++)
		    {
		        if(this->_bibli[i]->getTitre() > this->_bibli[i+1]->getTitre())
		        {
		        	//On compare les titres, et on les échanges si besoin
		            swap(this->_bibli[i], this->_bibli[i+1]);
		            tab_en_ordre = false;
		            deja_tri = false;
		        }
		    }
		    taille--;
		}
	} //Si le Tri est en fonction de l'auteur
	else if (pTri == "auteur")
	{
		unsigned int taille = _bibli.size();

		while(!tab_en_ordre)
		{
		    tab_en_ordre = true;

		    for(unsigned int i=0 ; i < taille-1 ; i++)
		    {
		        if(this->_bibli[i]->getAuteur() > this->_bibli[i+1]->getAuteur())
		        {
		        	//On compare les auteurs, et on les échanges si besoin
		            swap(this->_bibli[i], this->_bibli[i+1]);
		            tab_en_ordre = false;
		            deja_tri = false;
		        }
		    }
		    taille--;
		}
	}
	else cout << "Votre choix de tri n'est pas valide, merci de choisir soit 'auteur' ou 'titre'. " << endl;

	//On affiche si la Bibliothèque à été trié ou non
	if (deja_tri == false)
		cout << "Votre Bibliotheque a ete triee." << endl;
	else
        cout << "Votre Bibliotheque est deja triee" << endl;
	
	
	//On ouvre le fichier et on efface son contenu
	ofstream fichier("Bibli.txt", ios::out | ios::trunc);
   	if(fichier)  // si l'ouverture a réussi
   	{     
   	fichier.close();  // on referme le fichier
    }
    else
     cerr << "Erreur à l'ouverture !" << endl;
	
	//On recopie chaque élément du vecteur dans la BDD
	for (unsigned int u(0); u < this->_bibli.size(); u++)
	{
       this->_bibli[u]->ajout();
	}
}
Exemplo n.º 13
0
void execute(struct ed_s *ed)
{
	double a, b, ib;
	unsigned k, iter, neighb;
	index_type i;
	state_type s, s1;
	MPI_Request req_send, req_recv;
	MPI_Request req_send2, req_recv2;
	MPI_Status stat;
	
	b = 0.0;
	for (i = 0; i < ed->nlstates; ++i)
		b += ed->v1[i] * ed->v1[i];
		
	for (iter = 0; iter < ed->max_iter; ++iter) {
		/* calculate beta */
		MPI_Barrier(MPI_COMM_WORLD);
		MPI_Allreduce(&b, &ed->beta[iter], 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
		ed->beta[iter] = sqrt(fabs(ed->beta[iter]));

		/* normalize v1 */
		ib = 1.0 / ed->beta[iter];
		for (i = 0; i < ed->nlstates; ++i)
			ed->v1[i] *= ib;

		/* send and receive data in advance */
		MPI_Isend(ed->v1, ed->nlstates, MPI_DOUBLE, ed->to_nbs[0], ed->nm - 1, MPI_COMM_WORLD, &req_send);
		MPI_Irecv(ed->vv1, ed->nlstates, MPI_DOUBLE, ed->from_nbs[0], ed->nm - 1, MPI_COMM_WORLD, &req_recv);

		/* matrix vector multiplication */
		/* v2 = A * v1, the same core */
		for (i = 0; i < ed->nlstates; ++i) {
			s = loc_index2state(i, ed->nm, ed->rank);

			/* diagonal part */
			ed->v2[i] = diag(s, ed->n, ed->j) * ed->v1[i];

			/* offdiagonal part */
			for (k = 0; k < ed->nm; ++k) {
				s1 = flip_state(s, k);
				ed->v2[i] += ed->gamma * ed->v1[state2loc_index(s1, ed->nlstates)];
			}
		}

		/* matrix vector multiplication */
		/* v2 = A * v1, offdiagonal part, other cores */
		a = 0.0;
		for (k = ed->nm; k < ed->n; ++k) {
			if (k < ed->n - 1) {
				/* send and receive data in advance */
				neighb = k - ed->nm + 1;
				MPI_Isend(ed->v1, ed->nlstates, MPI_DOUBLE, ed->to_nbs[neighb], k, MPI_COMM_WORLD, &req_send2);
				MPI_Irecv(ed->vv2, ed->nlstates, MPI_DOUBLE, ed->from_nbs[neighb], k, MPI_COMM_WORLD, &req_recv2);
			}

			/* wait until data arrives */
			MPI_Wait(&req_recv, &stat);

			for (i = 0; i < ed->nlstates; ++i) {
				ed->v2[i] += ed->gamma * ed->vv1[i];

				if (k == ed->n - 1)
					a += ed->v1[i] * ed->v2[i];
			}

			req_recv = req_recv2;
			swap(&ed->vv1, &ed->vv2);
		}

		/* calculate alpha */
		MPI_Barrier(MPI_COMM_WORLD);
		MPI_Allreduce(&a, &ed->alpha[iter], 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);

		/* v2 = v2 - v0 * beta1 - v1 * alpha1 */
		b = 0.0;
		for (i = 0; i < ed->nlstates; ++i) {
			ed->v2[i] -= ed->v0[i] * ed->beta[iter] + ed->v1[i] * ed->alpha[iter];
			b += ed->v2[i] * ed->v2[i];
		}

		/* "shift" vectors */
		swap(&ed->v0, &ed->v1); swap(&ed->v1, &ed->v2);

                if (ed->rank == MASTER_CORE && iter > 0) {
                        calc_eigenvalues(ed, iter);
                        printf("%5i %20.12g\n", iter, ed->evals[0]);
                }
	}
}
Exemplo n.º 14
0
	HTTPHeader & HTTPHeader::operator=(HTTPHeader hdr)
	{
		swap(hdr);
		return *this;
	}
Exemplo n.º 15
0
/**
 * drm_primary_helper_update() - Helper for primary plane update
 * @plane: plane object to update
 * @crtc: owning CRTC of owning plane
 * @fb: framebuffer to flip onto plane
 * @crtc_x: x offset of primary plane on crtc
 * @crtc_y: y offset of primary plane on crtc
 * @crtc_w: width of primary plane rectangle on crtc
 * @crtc_h: height of primary plane rectangle on crtc
 * @src_x: x offset of @fb for panning
 * @src_y: y offset of @fb for panning
 * @src_w: width of source rectangle in @fb
 * @src_h: height of source rectangle in @fb
 *
 * Provides a default plane update handler for primary planes.  This is handler
 * is called in response to a userspace SetPlane operation on the plane with a
 * non-NULL framebuffer.  We call the driver's modeset handler to update the
 * framebuffer.
 *
 * SetPlane() on a primary plane of a disabled CRTC is not supported, and will
 * return an error.
 *
 * Note that we make some assumptions about hardware limitations that may not be
 * true for all hardware --
 *   1) Primary plane cannot be repositioned.
 *   2) Primary plane cannot be scaled.
 *   3) Primary plane must cover the entire CRTC.
 *   4) Subpixel positioning is not supported.
 * Drivers for hardware that don't have these restrictions can provide their
 * own implementation rather than using this helper.
 *
 * RETURNS:
 * Zero on success, error code on failure
 */
int drm_primary_helper_update(struct drm_plane *plane, struct drm_crtc *crtc,
			      struct drm_framebuffer *fb,
			      int crtc_x, int crtc_y,
			      unsigned int crtc_w, unsigned int crtc_h,
			      uint32_t src_x, uint32_t src_y,
			      uint32_t src_w, uint32_t src_h)
{
	struct drm_mode_set set = {
		.crtc = crtc,
		.fb = fb,
		.mode = &crtc->mode,
		.x = src_x >> 16,
		.y = src_y >> 16,
	};
	struct drm_rect src = {
		.x1 = src_x,
		.y1 = src_y,
		.x2 = src_x + src_w,
		.y2 = src_y + src_h,
	};
	struct drm_rect dest = {
		.x1 = crtc_x,
		.y1 = crtc_y,
		.x2 = crtc_x + crtc_w,
		.y2 = crtc_y + crtc_h,
	};
	const struct drm_rect clip = {
		.x2 = crtc->mode.hdisplay,
		.y2 = crtc->mode.vdisplay,
	};
	struct drm_connector **connector_list;
	int num_connectors, ret;
	bool visible;

	ret = drm_plane_helper_check_update(plane, crtc, fb,
					    &src, &dest, &clip,
					    DRM_PLANE_HELPER_NO_SCALING,
					    DRM_PLANE_HELPER_NO_SCALING,
					    false, false, &visible);
	if (ret)
		return ret;

	if (!visible)
		/*
		 * Primary plane isn't visible.  Note that unless a driver
		 * provides their own disable function, this will just
		 * wind up returning -EINVAL to userspace.
		 */
		return plane->funcs->disable_plane(plane);

	/* Find current connectors for CRTC */
	num_connectors = get_connectors_for_crtc(crtc, NULL, 0);
	BUG_ON(num_connectors == 0);
	connector_list = kzalloc(num_connectors * sizeof(*connector_list),
				 GFP_KERNEL);
	if (!connector_list)
		return -ENOMEM;
	get_connectors_for_crtc(crtc, connector_list, num_connectors);

	set.connectors = connector_list;
	set.num_connectors = num_connectors;

	/*
	 * We call set_config() directly here rather than using
	 * drm_mode_set_config_internal.  We're reprogramming the same
	 * connectors that were already in use, so we shouldn't need the extra
	 * cross-CRTC fb refcounting to accomodate stealing connectors.
	 * drm_mode_setplane() already handles the basic refcounting for the
	 * framebuffers involved in this operation.
	 */
	ret = crtc->funcs->set_config(&set);

	kfree(connector_list);
	return ret;
}
EXPORT_SYMBOL(drm_primary_helper_update);

/**
 * drm_primary_helper_disable() - Helper for primary plane disable
 * @plane: plane to disable
 *
 * Provides a default plane disable handler for primary planes.  This is handler
 * is called in response to a userspace SetPlane operation on the plane with a
 * NULL framebuffer parameter.  It unconditionally fails the disable call with
 * -EINVAL the only way to disable the primary plane without driver support is
 * to disable the entier CRTC. Which does not match the plane ->disable hook.
 *
 * Note that some hardware may be able to disable the primary plane without
 * disabling the whole CRTC.  Drivers for such hardware should provide their
 * own disable handler that disables just the primary plane (and they'll likely
 * need to provide their own update handler as well to properly re-enable a
 * disabled primary plane).
 *
 * RETURNS:
 * Unconditionally returns -EINVAL.
 */
int drm_primary_helper_disable(struct drm_plane *plane)
{
	return -EINVAL;
}
EXPORT_SYMBOL(drm_primary_helper_disable);

/**
 * drm_primary_helper_destroy() - Helper for primary plane destruction
 * @plane: plane to destroy
 *
 * Provides a default plane destroy handler for primary planes.  This handler
 * is called during CRTC destruction.  We disable the primary plane, remove
 * it from the DRM plane list, and deallocate the plane structure.
 */
void drm_primary_helper_destroy(struct drm_plane *plane)
{
	drm_plane_cleanup(plane);
	kfree(plane);
}
EXPORT_SYMBOL(drm_primary_helper_destroy);

const struct drm_plane_funcs drm_primary_helper_funcs = {
	.update_plane = drm_primary_helper_update,
	.disable_plane = drm_primary_helper_disable,
	.destroy = drm_primary_helper_destroy,
};
EXPORT_SYMBOL(drm_primary_helper_funcs);

static struct drm_plane *create_primary_plane(struct drm_device *dev)
{
	struct drm_plane *primary;
	int ret;

	primary = kzalloc(sizeof(*primary), GFP_KERNEL);
	if (primary == NULL) {
		DRM_DEBUG_KMS("Failed to allocate primary plane\n");
		return NULL;
	}

	/*
	 * Remove the format_default field from drm_plane when dropping
	 * this helper.
	 */
	primary->format_default = true;

	/* possible_crtc's will be filled in later by crtc_init */
	ret = drm_universal_plane_init(dev, primary, 0,
				       &drm_primary_helper_funcs,
				       safe_modeset_formats,
				       ARRAY_SIZE(safe_modeset_formats),
				       DRM_PLANE_TYPE_PRIMARY, NULL);
	if (ret) {
		kfree(primary);
		primary = NULL;
	}

	return primary;
}

/**
 * drm_crtc_init - Legacy CRTC initialization function
 * @dev: DRM device
 * @crtc: CRTC object to init
 * @funcs: callbacks for the new CRTC
 *
 * Initialize a CRTC object with a default helper-provided primary plane and no
 * cursor plane.
 *
 * Returns:
 * Zero on success, error code on failure.
 */
int drm_crtc_init(struct drm_device *dev, struct drm_crtc *crtc,
		  const struct drm_crtc_funcs *funcs)
{
	struct drm_plane *primary;

	primary = create_primary_plane(dev);
	return drm_crtc_init_with_planes(dev, crtc, primary, NULL, funcs,
					 NULL);
}
EXPORT_SYMBOL(drm_crtc_init);

int drm_plane_helper_commit(struct drm_plane *plane,
			    struct drm_plane_state *plane_state,
			    struct drm_framebuffer *old_fb)
{
	const struct drm_plane_helper_funcs *plane_funcs;
	struct drm_crtc *crtc[2];
	const struct drm_crtc_helper_funcs *crtc_funcs[2];
	int i, ret = 0;

	plane_funcs = plane->helper_private;

	/* Since this is a transitional helper we can't assume that plane->state
	 * is always valid. Hence we need to use plane->crtc instead of
	 * plane->state->crtc as the old crtc. */
	crtc[0] = plane->crtc;
	crtc[1] = crtc[0] != plane_state->crtc ? plane_state->crtc : NULL;

	for (i = 0; i < 2; i++)
		crtc_funcs[i] = crtc[i] ? crtc[i]->helper_private : NULL;

	if (plane_funcs->atomic_check) {
		ret = plane_funcs->atomic_check(plane, plane_state);
		if (ret)
			goto out;
	}

	if (plane_funcs->prepare_fb && plane_state->fb &&
	    plane_state->fb != old_fb) {
		ret = plane_funcs->prepare_fb(plane,
					      plane_state);
		if (ret)
			goto out;
	}

	/* Point of no return, commit sw state. */
	swap(plane->state, plane_state);

	for (i = 0; i < 2; i++) {
		if (crtc_funcs[i] && crtc_funcs[i]->atomic_begin)
			crtc_funcs[i]->atomic_begin(crtc[i], crtc[i]->state);
	}

	/*
	 * Drivers may optionally implement the ->atomic_disable callback, so
	 * special-case that here.
	 */
	if (drm_atomic_plane_disabling(plane, plane_state) &&
	    plane_funcs->atomic_disable)
		plane_funcs->atomic_disable(plane, plane_state);
	else
		plane_funcs->atomic_update(plane, plane_state);

	for (i = 0; i < 2; i++) {
		if (crtc_funcs[i] && crtc_funcs[i]->atomic_flush)
			crtc_funcs[i]->atomic_flush(crtc[i], crtc[i]->state);
	}

	/*
	 * If we only moved the plane and didn't change fb's, there's no need to
	 * wait for vblank.
	 */
	if (plane->state->fb == old_fb)
		goto out;

	for (i = 0; i < 2; i++) {
		if (!crtc[i])
			continue;

		if (crtc[i]->cursor == plane)
			continue;

		/* There's no other way to figure out whether the crtc is running. */
		ret = drm_crtc_vblank_get(crtc[i]);
		if (ret == 0) {
			drm_crtc_wait_one_vblank(crtc[i]);
			drm_crtc_vblank_put(crtc[i]);
		}

		ret = 0;
	}

	if (plane_funcs->cleanup_fb)
		plane_funcs->cleanup_fb(plane, plane_state);
out:
	if (plane_state) {
		if (plane->funcs->atomic_destroy_state)
			plane->funcs->atomic_destroy_state(plane, plane_state);
		else
			drm_atomic_helper_plane_destroy_state(plane, plane_state);
	}

	return ret;
}

/**
 * drm_plane_helper_update() - Transitional helper for plane update
 * @plane: plane object to update
 * @crtc: owning CRTC of owning plane
 * @fb: framebuffer to flip onto plane
 * @crtc_x: x offset of primary plane on crtc
 * @crtc_y: y offset of primary plane on crtc
 * @crtc_w: width of primary plane rectangle on crtc
 * @crtc_h: height of primary plane rectangle on crtc
 * @src_x: x offset of @fb for panning
 * @src_y: y offset of @fb for panning
 * @src_w: width of source rectangle in @fb
 * @src_h: height of source rectangle in @fb
 *
 * Provides a default plane update handler using the atomic plane update
 * functions. It is fully left to the driver to check plane constraints and
 * handle corner-cases like a fully occluded or otherwise invisible plane.
 *
 * This is useful for piecewise transitioning of a driver to the atomic helpers.
 *
 * RETURNS:
 * Zero on success, error code on failure
 */
int drm_plane_helper_update(struct drm_plane *plane, struct drm_crtc *crtc,
			    struct drm_framebuffer *fb,
			    int crtc_x, int crtc_y,
			    unsigned int crtc_w, unsigned int crtc_h,
			    uint32_t src_x, uint32_t src_y,
			    uint32_t src_w, uint32_t src_h)
{
	struct drm_plane_state *plane_state;

	if (plane->funcs->atomic_duplicate_state)
		plane_state = plane->funcs->atomic_duplicate_state(plane);
	else {
		if (!plane->state)
			drm_atomic_helper_plane_reset(plane);

		plane_state = drm_atomic_helper_plane_duplicate_state(plane);
	}
	if (!plane_state)
		return -ENOMEM;
	plane_state->plane = plane;

	plane_state->crtc = crtc;
	drm_atomic_set_fb_for_plane(plane_state, fb);
	plane_state->crtc_x = crtc_x;
	plane_state->crtc_y = crtc_y;
	plane_state->crtc_h = crtc_h;
	plane_state->crtc_w = crtc_w;
	plane_state->src_x = src_x;
	plane_state->src_y = src_y;
	plane_state->src_h = src_h;
	plane_state->src_w = src_w;

	return drm_plane_helper_commit(plane, plane_state, plane->fb);
}
EXPORT_SYMBOL(drm_plane_helper_update);

/**
 * drm_plane_helper_disable() - Transitional helper for plane disable
 * @plane: plane to disable
 *
 * Provides a default plane disable handler using the atomic plane update
 * functions. It is fully left to the driver to check plane constraints and
 * handle corner-cases like a fully occluded or otherwise invisible plane.
 *
 * This is useful for piecewise transitioning of a driver to the atomic helpers.
 *
 * RETURNS:
 * Zero on success, error code on failure
 */
int drm_plane_helper_disable(struct drm_plane *plane)
{
	struct drm_plane_state *plane_state;

	/* crtc helpers love to call disable functions for already disabled hw
	 * functions. So cope with that. */
	if (!plane->crtc)
		return 0;

	if (plane->funcs->atomic_duplicate_state)
		plane_state = plane->funcs->atomic_duplicate_state(plane);
	else {
		if (!plane->state)
			drm_atomic_helper_plane_reset(plane);

		plane_state = drm_atomic_helper_plane_duplicate_state(plane);
	}
	if (!plane_state)
		return -ENOMEM;
	plane_state->plane = plane;

	plane_state->crtc = NULL;
	drm_atomic_set_fb_for_plane(plane_state, NULL);

	return drm_plane_helper_commit(plane, plane_state, plane->fb);
}
EXPORT_SYMBOL(drm_plane_helper_disable);
Exemplo n.º 16
0
 es_buffer& operator=(es_buffer const& other)
 {
   es_buffer tmp(other);
   swap(tmp);
   return *this;
 }
Exemplo n.º 17
0
int main()
{
  //Change this type definition to double if your gpu supports that
  typedef float       ScalarType;

  // Choose the Phi (WORKS)
  viennacl::ocl::set_context_device_type(0, viennacl::ocl::accelerator_tag());

  /////////////////////////////////////////////////
  ///////////// Scalar operations /////////////////
  /////////////////////////////////////////////////

  //
  // Define a few CPU scalars:
  //
  ScalarType s1 = static_cast<ScalarType>(3.1415926);
  ScalarType s2 = static_cast<ScalarType>(2.71763);
  ScalarType s3 = static_cast<ScalarType>(42.0);

  //
  // ViennaCL scalars are defined in the same way:
  //
  viennacl::scalar<ScalarType> vcl_s1;
  viennacl::scalar<ScalarType> vcl_s2 = static_cast<ScalarType>(1.0);
  viennacl::scalar<ScalarType> vcl_s3 = static_cast<ScalarType>(1.0);

  //
  // CPU scalars can be transparently assigned to GPU scalars and vice versa:
  //
  vcl_s1 = s1;
  s2 = vcl_s2;
  vcl_s3 = s3;

  //
  // Operations between GPU scalars work just as for CPU scalars:
  // (Note that such single compute kernels on the GPU are considerably slower than on the CPU)
  //

  s1 += s2;
  vcl_s1 += vcl_s2;

  s1 *= s2;
  vcl_s1 *= vcl_s2;

  s1 -= s2;
  vcl_s1 -= vcl_s2;

  s1 /= s2;
  vcl_s1 /= vcl_s2;

  s1 = s2 + s3;
  vcl_s1 = vcl_s2 + vcl_s3;

  s1 = s2 + s3 * s2 - s3 / s1;
  vcl_s1 = vcl_s2 + vcl_s3 * vcl_s2 - vcl_s3 / vcl_s1;


  //
  // Operations can also be mixed:
  //

  vcl_s1 = s1 * vcl_s2 + s3 - vcl_s3;


  //
  // Output stream is overloaded as well:
  //

  std::cout << "CPU scalar s2: " << s2 << std::endl;
  std::cout << "GPU scalar vcl_s2: " << vcl_s2 << std::endl;

  std::vector< viennacl::ocl::device > devices = viennacl::ocl::platform().devices();

  for (int i = 0; i < devices.size(); i++) {
      std::cout << devices[i].info() << "\n";
  }

  std::cout << "SELECTED DEVICE: \n";
  std::cout << viennacl::ocl::current_context().current_device().info() << "\n";

  /////////////////////////////////////////////////
  ///////////// Vector operations /////////////////
  /////////////////////////////////////////////////

  //
  // Define a few vectors (from STL and plain C) and viennacl::vectors
  //
  std::vector<ScalarType>      std_vec1(10);
  std::vector<ScalarType>      std_vec2(10);
  ScalarType                   plain_vec3[10];  //plain C array

  viennacl::vector<ScalarType> vcl_vec1(10);
  viennacl::vector<ScalarType> vcl_vec2(10);
  viennacl::vector<ScalarType> vcl_vec3(10);

  //
  // Let us fill the CPU vectors with random values:
  // (random<> is a helper function from Random.hpp)
  //

  for (unsigned int i = 0; i < 10; ++i)
  {
    std_vec1[i] = random<ScalarType>();
    vcl_vec2(i) = random<ScalarType>();  //also works for GPU vectors, but is MUCH slower (approx. factor 10.000) than the CPU analogue
    plain_vec3[i] = random<ScalarType>();
  }

  //
  // Copy the CPU vectors to the GPU vectors and vice versa
  //
  copy(std_vec1.begin(), std_vec1.end(), vcl_vec1.begin()); //either the STL way
  copy(vcl_vec2.begin(), vcl_vec2.end(), std_vec2.begin()); //either the STL way
  copy(vcl_vec2, std_vec2);                                 //using the short hand notation for objects that provide .begin() and .end() members
  copy(vcl_vec2.begin(), vcl_vec2.end(), plain_vec3);       //copy to plain C vector

  //
  // Compute the inner product of two GPU vectors and write the result to either CPU or GPU
  //

  vcl_s1 = viennacl::linalg::inner_prod(vcl_vec1, vcl_vec2);
  s1 = viennacl::linalg::inner_prod(vcl_vec1, vcl_vec2);

  //
  // Compute norms:
  //

  s1 = viennacl::linalg::norm_1(vcl_vec1);
  vcl_s2 = viennacl::linalg::norm_2(vcl_vec2);
  s3 = viennacl::linalg::norm_inf(vcl_vec3);

  //
  // Plane rotation of two vectors:
  //

  viennacl::linalg::plane_rotation(vcl_vec1, vcl_vec2, 1.1f, 2.3f);

  //
  // Use viennacl::vector via the overloaded operators just as you would write it on paper:
  //

  //simple expression:
  vcl_vec1 = vcl_s1 * vcl_vec2 / vcl_s3;

  //more complicated expression:
  vcl_vec1 = vcl_vec2 / vcl_s1 + vcl_s2 * (vcl_vec1 - vcl_s2 * vcl_vec2);

  //
  // Swap the content of two vectors without a temporary vector:
  //

  swap(vcl_vec1, vcl_vec2);


  //
  //  That's it. Move on to the second tutorial, where dense matrices are explained.
  //
  std::cout << "!!!! TUTORIAL 1 COMPLETED SUCCESSFULLY !!!!" << std::endl;

  exit(EXIT_SUCCESS);
  return 0;
}
Exemplo n.º 18
0
int main()
{
    int type;
    int v = 0;          /* to record variable a-z for = op */
    double op2;
    char s[MAXOP];

    while ((type = getop(s)) != EOF)
    {
        switch (type)
        {
        case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
        case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
        case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
        case 'v': case 'w': case 'x': case 'y': case 'z': case '$':
            /*
             * note: When a variable is reset using the = operator this could
             *       lead to an unused value on the stack.  This is why the
             *       stack is cleared when a newline is encountered.
             */
            if (isvar(type))
            {
                push(getvar(type));
            }
            else if (type == '$')
            {
                printf("error: no previously printed value\n");
            }
            v = type;            /* record for = op below */
            break;
        case '=':
            if (v)
            {
                setvar(v, pop());
                v = 0;
            }
            else
            {
                printf("error: no previous variable specified\n");
            }
            break;
        case 'S':
            push(sin(pop()));
            break;
        case 'C':
            push(cos(pop()));
            break;
        case 'T':
            push(tan(pop()));
            break;
        case 'X':
            push(exp(pop()));
            break;
        case 'L':
            push(log10(pop()));
            break;
        case 'E':
            push(exp(pop()));
            break;
        case 'R':
            push(sqrt(pop()));
            break;
        case 'P':
            op2 = pop();
            push(pow(pop(), op2));
            break;
        case '!':
            clear();
            break;
        case '@':
            swap();
            break;
        case '#':
            duplicate();
            break;
        case '&':
            printf("\t%.8g\n", setvar('$', top()));
            break;
        case NUMBER:
            push(atof(s));
            break;
        case '+':
            push(pop() + pop());
            break;
        case '*':
            push(pop() * pop());
            break;
        case '-':
            op2 = pop();
            push(pop() - op2);
            break;
        case '/':
            op2 = pop();
            if (op2 != 0.0)
                push(pop() / op2);
            else
                printf("error: zero divisor for operator '/'\n");
            break;
        case '%':
            op2 = pop();
            if (op2 != 0.0)
            {
                /* In C the modulus operator only works on short,
                 * integer, long, ... but not when the operands
                 * are float or double.  Thus we have to emulate a
                 * modulus operation for operands of type double.
                 *
                 * note: <math.h> has the function fmod() for this
                 *
                 */
                double d = pop();
                if (d < op2)
                    push(d);
                else if (d == op2)
                    push(0.0);
                else
                {
                    while ((d -= op2) > op2)
                        ;
                    if (d == op2)
                        push(0.0);
                    else
                        push(d);
                }
            }
            else
                printf("error: zero divisor for operator '%%'\n");
            break;
        /* case '|':                            /\* test command for ungets() *\/ */
        /*     ungets(" 23 4 + "); */
        /*     break; */
        case '\n':
            printf("\t%.8g\n", setvar('$', pop()));
            clear();                                    /* clear the stack */
            break;
        default:
            printf("error: unknown command %s\n", s);
            break;
        }
    }
    return 0;
}
Exemplo n.º 19
0
int partition(int *a, int lo, int hi)
  //@ requires a[lo..hi + 1] |-> ?vs &*& lo <= hi;
  /*@
  ensures
      a[lo..result] |-> ?vslow &*&
      a[result] |-> ?vpivot &*&
      a[result + 1..hi + 1] |-> ?vshigh &*&
      forall(vslow, (ge)(vpivot)) == true &*&
      forall(vshigh, (le)(vpivot)) == true &*&
      (mplus)((count_eq)(vslow), (count_eq)(cons(vpivot, vshigh))) == (count_eq)(vs);
  @*/
{
  //@ ints_split(a + lo, hi - lo);
  int pivot = *(a+hi);
  //@ assert a[lo..hi] |-> ?vstodo0 &*& a[hi..hi + 1] |-> cons(_, ?vsrest);
  //@ switch (vsrest) { case nil: case cons(h, t): }
  int i = lo - 1;
  int j;
  //@ count_eq_append(vstodo0, {pivot});
  //@ assert vs == append(vstodo0, {pivot});
  for (j = lo; j < hi; j++)
    /*@
    invariant
      a[lo..i + 1] |-> ?vslow &*&
      a[i + 1..j] |-> ?vshigh &*&
      a[j..hi] |-> ?vstodo &*&
      forall(vslow, (ge)(pivot)) == true &*&
      forall(vshigh, (le)(pivot)) == true &*&
      (mplus)((count_eq)(vstodo), (mplus)((count_eq)(vslow), (count_eq)(cons(pivot, vshigh)))) == (count_eq)(vs);
    @*/
  {
    
    int aj = *(a + j);
    if (aj < pivot) {
      i++;
      if (i < j) {
        swap(a, i, j);
        //@ int ai = a[j];
        //@ close ints(a + i, 1, {aj});
        //@ ints_join(a + lo);
        //@ close ints(a + j, 1, {ai});
        //@ ints_join(a + i + 1);
        //@ forall_append(vslow, {aj}, (ge)(pivot));
        //@ forall_append(tail(vshigh), {ai}, (le)(pivot));
        /*@
        if ((mplus)((count_eq)(tail(vstodo)), (mplus)((count_eq)(append(vslow, {aj})), (count_eq)(cons(pivot, append(tail(vshigh), {ai}))))) !=
            (mplus)((count_eq)(vstodo), (mplus)((count_eq)(vslow), (count_eq)(cons(pivot, vshigh))))) {
            int x = fixpoint_neq_elim((mplus)((count_eq)(tail(vstodo)), (mplus)((count_eq)(append(vslow, {aj})), (count_eq)(cons(pivot, append(tail(vshigh), {ai}))))),
                                    (mplus)((count_eq)(vstodo), (mplus)((count_eq)(vslow), (count_eq)(cons(pivot, vshigh)))));
            count_append(vslow, {aj}, (eq)(x));
            count_append(tail(vshigh), {ai}, (eq)(x));
            assert false;
        }
        @*/
      } else {
        //@ assert i == j;
        //@ open ints(a + i, 0, _);
        //@ close ints(a + i, 1, _);
        //@ ints_join(a + lo);
        //@ forall_append(vslow, {aj}, (ge)(pivot));
        /*@
        if ((mplus)((count_eq)(tail(vstodo)), (mplus)((count_eq)(append(vslow, {aj})), (count_eq)({pivot}))) !=
            (mplus)((count_eq)(vstodo), (mplus)((count_eq)(vslow), (count_eq)(cons(pivot, vshigh))))) {
            int x = fixpoint_neq_elim((mplus)((count_eq)(tail(vstodo)), (mplus)((count_eq)(append(vslow, {aj})), (count_eq)({pivot}))),
                                    (mplus)((count_eq)(vstodo), (mplus)((count_eq)(vslow), (count_eq)(cons(pivot, vshigh)))));
            count_append(vslow, {aj}, (eq)(x));
            assert false;
        }
        @*/
      }
    } else {
      //@ close ints(a + j, 1, {aj});
      //@ ints_join(a + i + 1);
      //@ forall_append(vshigh, {aj}, (le)(pivot));
      /*@
      if ((mplus)((count_eq)(tail(vstodo)), (mplus)((count_eq)(vslow), (count_eq)(cons(pivot, append(vshigh, {aj}))))) !=
          (mplus)((count_eq)(vstodo), (mplus)((count_eq)(vslow), (count_eq)(cons(pivot, vshigh))))) {
          int x = fixpoint_neq_elim((mplus)((count_eq)(tail(vstodo)), (mplus)((count_eq)(vslow), (count_eq)(cons(pivot, append(vshigh, {aj}))))),
                                  (mplus)((count_eq)(vstodo), (mplus)((count_eq)(vslow), (count_eq)(cons(pivot, vshigh)))));
          count_append(vshigh, {aj}, (eq)(x));
          assert false;
      }
      @*/
    }
  }
  //@ assert j == hi;
  //@ open ints(a + hi, 0, _);
  i++;
  //@ assert a[lo..i] |-> ?vslow &*& a[i..hi] |-> ?vshigh;
  if (i < hi) {
    swap(a, i, hi);
    //@ int ai = a[hi];
    //@ close ints(a + hi, 1, {ai});
    //@ ints_join(a + i + 1);
    //@ forall_append(tail(vshigh), {ai}, (le)(pivot));
      /*@
      if ((mplus)((count_eq)(vslow), (count_eq)(cons(pivot, append(tail(vshigh), {ai})))) !=
          (mplus)((count_eq)(nil), (mplus)((count_eq)(vslow), (count_eq)(cons(pivot, vshigh))))) {
          int x = fixpoint_neq_elim((mplus)((count_eq)(vslow), (count_eq)(cons(pivot, append(tail(vshigh), {ai})))),
                                  (mplus)((count_eq)(nil), (mplus)((count_eq)(vslow), (count_eq)(cons(pivot, vshigh)))));
          count_append(tail(vshigh), {ai}, (eq)(x));
          assert false;
      }
      @*/
  } else {
      //@ assert i == hi;
      //@ open ints(a + hi, 0, _);
  }
  return i;
}
Exemplo n.º 20
0
int PixelBone_Matrix::getOffset(int16_t x, int16_t y) {

  if ((x < 0) || (y < 0) || (x >= _width) || (y >= _height))
    return -1;

  int16_t t;
  switch (rotation) {
  case 1:
    t = x;
    x = WIDTH - 1 - y;
    y = t;
    break;
  case 2:
    x = WIDTH - 1 - x;
    y = HEIGHT - 1 - y;
    break;
  case 3:
    t = x;
    x = y;
    y = HEIGHT - 1 - t;
    break;
  }

  int tileOffset = 0, pixelOffset;

  if (remapFn) { // Custom X/Y remapping function
    pixelOffset = (*remapFn)(x, y);
  } else { // Standard single matrix or tiled matrices

    uint8_t corner = type & MATRIX_CORNER;
    uint16_t minor, major, majorScale;

    if (tilesX) { // Tiled display, multiple matrices
      uint16_t tile;

      minor = x / matrixWidth;           // Tile # X/Y; presume row major to
      major = y / matrixHeight,          // start (will swap later if needed)
          x = x - (minor * matrixWidth); // Pixel X/Y within tile
      y = y - (major * matrixHeight);    // (-* is less math than modulo)

      // Determine corner of entry, flip axes if needed
      if (type & TILE_RIGHT)
        minor = tilesX - 1 - minor;
      if (type & TILE_BOTTOM)
        major = tilesY - 1 - major;

      // Determine actual major axis of tiling
      if ((type & TILE_AXIS) == TILE_ROWS) {
        majorScale = tilesX;
      } else {
        swap(major, minor);
        majorScale = tilesY;
      }

      // Determine tile number
      if ((type & TILE_SEQUENCE) == TILE_PROGRESSIVE) {
        // All tiles in same order
        tile = major * majorScale + minor;
      } else {
        // Zigzag; alternate rows change direction.  On these rows,
        // this also flips the starting corner of the matrix for the
        // pixel math later.
        if (major & 1) {
          corner ^= MATRIX_CORNER;
          tile = (major + 1) * majorScale - 1 - minor;
        } else {
          tile = major * majorScale + minor;
        }
      }

      // Index of first pixel in tile
      tileOffset = tile * matrixWidth * matrixHeight;

    } // else no tiling (handle as single tile)

    // Find pixel number within tile
    minor = x; // Presume row major to start (will swap later if needed)
    major = y;

    // Determine corner of entry, flip axes if needed
    if (corner & MATRIX_RIGHT)
      minor = matrixWidth - 1 - minor;
    if (corner & MATRIX_BOTTOM)
      major = matrixHeight - 1 - major;

    // Determine actual major axis of matrix
    if ((type & MATRIX_AXIS) == MATRIX_ROWS) {
      majorScale = matrixWidth;
    } else {
      swap(major, minor);
      majorScale = matrixHeight;
    }

    // Determine pixel number within tile/matrix
    if ((type & MATRIX_SEQUENCE) == MATRIX_PROGRESSIVE) {
      // All lines in same order
      pixelOffset = major * majorScale + minor;
    } else {
      // Zigzag; alternate rows change direction.
      if (major & 1)
        pixelOffset = (major + 1) * majorScale - 1 - minor;
      else
        pixelOffset = major * majorScale + minor;
    }
  }
  int offset = (tileOffset + pixelOffset);
  return offset;
}
Exemplo n.º 21
0
static void solve_l1r_l2_svc(
	problem *prob_col, double *w, double eps, 
	double Cp, double Cn)
{
	int l = prob_col->l;
	int w_size = prob_col->n;
	int j, s, iter = 0;
	int max_iter = 1000;
	int active_size = w_size;
	int max_num_linesearch = 20;

	double sigma = 0.01;
	double d, G_loss, G, H;
	double Gmax_old = INF;
	double Gmax_new;
	double Gmax_init;
	double d_old, d_diff;
	double loss_old, loss_new;
	double appxcond, cond;

	int *index = new int[w_size];
	schar *y = new schar[l];
	double *b = new double[l]; // b = 1-ywTx
	double *xj_sq = new double[w_size];
	feature_node *x;

	double C[3] = {Cn,0,Cp};

	for(j=0; j<l; j++)
	{
		b[j] = 1;
		if(prob_col->y[j] > 0)
			y[j] = 1;
		else
			y[j] = -1;
	}
	for(j=0; j<w_size; j++)
	{
		w[j] = 0;
		index[j] = j;
		xj_sq[j] = 0;
		x = prob_col->x[j];
		while(x->index != -1)
		{
			int ind = x->index-1;
			double val = x->value;
			x->value *= y[ind]; // x->value stores yi*xij
			xj_sq[j] += C[GETI(ind)]*val*val;
			x++;
		}
	}

	while(iter < max_iter)
	{
		Gmax_new  = 0;

		for(j=0; j<active_size; j++)
		{
			int i = j+rand()%(active_size-j);
			swap(index[i], index[j]);
		}

		for(s=0; s<active_size; s++)
		{
			j = index[s];
			G_loss = 0;
			H = 0;

			x = prob_col->x[j];
			while(x->index != -1)
			{
				int ind = x->index-1;
				if(b[ind] > 0)
				{
					double val = x->value;
					double tmp = C[GETI(ind)]*val;
					G_loss -= tmp*b[ind];
					H += tmp*val;
				}
				x++;
			}
			G_loss *= 2;

			G = G_loss;
			H *= 2;
			H = max(H, 1e-12);

			double Gp = G+1;
			double Gn = G-1;
			double violation = 0;
			if(w[j] == 0)
			{
				if(Gp < 0)
					violation = -Gp;
				else if(Gn > 0)
					violation = Gn;
				else if(Gp>Gmax_old/l && Gn<-Gmax_old/l)
				{
					active_size--;
					swap(index[s], index[active_size]);
					s--;
					continue;
				}
			}
			else if(w[j] > 0)
				violation = fabs(Gp);
			else
				violation = fabs(Gn);

			Gmax_new = max(Gmax_new, violation);

			// obtain Newton direction d
			if(Gp <= H*w[j])
				d = -Gp/H;
			else if(Gn >= H*w[j])
				d = -Gn/H;
			else
				d = -w[j];

			if(fabs(d) < 1.0e-12)
				continue;

			double delta = fabs(w[j]+d)-fabs(w[j]) + G*d;
			d_old = 0;
			int num_linesearch;
			for(num_linesearch=0; num_linesearch < max_num_linesearch; num_linesearch++)
			{
				d_diff = d_old - d;
				cond = fabs(w[j]+d)-fabs(w[j]) - sigma*delta;

				appxcond = xj_sq[j]*d*d + G_loss*d + cond;
				if(appxcond <= 0)
				{
					x = prob_col->x[j];
					while(x->index != -1)
					{
						b[x->index-1] += d_diff*x->value;
						x++;
					}
					break;
				}

				if(num_linesearch == 0)
				{
					loss_old = 0;
					loss_new = 0;
					x = prob_col->x[j];
					while(x->index != -1)
					{
						int ind = x->index-1;
						if(b[ind] > 0)
							loss_old += C[GETI(ind)]*b[ind]*b[ind];
						double b_new = b[ind] + d_diff*x->value;
						b[ind] = b_new;
						if(b_new > 0)
							loss_new += C[GETI(ind)]*b_new*b_new;
						x++;
					}
				}
				else
				{
					loss_new = 0;
					x = prob_col->x[j];
					while(x->index != -1)
					{
						int ind = x->index-1;
						double b_new = b[ind] + d_diff*x->value;
						b[ind] = b_new;
						if(b_new > 0)
							loss_new += C[GETI(ind)]*b_new*b_new;
						x++;
					}
				}

				cond = cond + loss_new - loss_old;
				if(cond <= 0)
					break;
				else
				{
					d_old = d;
					d *= 0.5;
					delta *= 0.5;
				}
			}

			w[j] += d;

			// recompute b[] if line search takes too many steps
			if(num_linesearch >= max_num_linesearch)
			{
				info("#");
				for(int i=0; i<l; i++)
					b[i] = 1;

				for(int i=0; i<w_size; i++)
				{
					if(w[i]==0) continue;
					x = prob_col->x[i];
					while(x->index != -1)
					{
						b[x->index-1] -= w[i]*x->value;
						x++;
					}
				}
			}
		}

		if(iter == 0)
			Gmax_init = Gmax_new;
		iter++;
		if(iter % 10 == 0)
			info(".");

		if(Gmax_new <= eps*Gmax_init)
		{
			if(active_size == w_size)
				break;
			else
			{
				active_size = w_size;
				info("*");
				Gmax_old = INF;
				continue;
			}
		}

		Gmax_old = Gmax_new;
	}

	info("\noptimization finished, #iter = %d\n", iter);
	if(iter >= max_iter)
		info("\nWARNING: reaching max number of iterations\n");

	// calculate objective value

	double v = 0;
	int nnz = 0;
	for(j=0; j<w_size; j++)
	{
		x = prob_col->x[j];
		while(x->index != -1)
		{
			x->value *= prob_col->y[x->index-1]; // restore x->value
			x++;
		}
		if(w[j] != 0)
		{
			v += fabs(w[j]);
			nnz++;
		}
	}
	for(j=0; j<l; j++)
		if(b[j] > 0)
			v += C[GETI(j)]*b[j]*b[j];

	info("Objective value = %lf\n", v);
	info("#nonzeros/#features = %d/%d\n", nnz, w_size);

	delete [] index;
	delete [] y;
	delete [] b;
	delete [] xj_sq;
}
Exemplo n.º 22
0
void IString::operator=(IString& newStr){
	swap(newStr.str, str);
}
Exemplo n.º 23
0
void Solver_MCSVM_CS::Solve(double *w)
{
	int i, m, s;
	int iter = 0;
	double *alpha =  new double[l*nr_class];
	double *alpha_new = new double[nr_class];
	int *index = new int[l];
	double *QD = new double[l];
	int *d_ind = new int[nr_class];
	double *d_val = new double[nr_class];
	int *alpha_index = new int[nr_class*l];
	int *y_index = new int[l];
	int active_size = l;
	int *active_size_i = new int[l];
	double eps_shrink = max(10.0*eps, 1.0); // stopping tolerance for shrinking
	bool start_from_all = true;
	// initial
	for(i=0;i<l*nr_class;i++)
		alpha[i] = 0;
	for(i=0;i<w_size*nr_class;i++)
		w[i] = 0; 
	for(i=0;i<l;i++)
	{
		for(m=0;m<nr_class;m++)
			alpha_index[i*nr_class+m] = m;
		feature_node *xi = prob->x[i];
		QD[i] = 0;
		while(xi->index != -1)
		{
			QD[i] += (xi->value)*(xi->value);
			xi++;
		}
		active_size_i[i] = nr_class;
		y_index[i] = prob->y[i];
		index[i] = i;
	}

	while(iter < max_iter) 
	{
		double stopping = -INF;
		for(i=0;i<active_size;i++)
		{
			int j = i+rand()%(active_size-i);
			swap(index[i], index[j]);
		}
		for(s=0;s<active_size;s++)
		{
			i = index[s];
			double Ai = QD[i];
			double *alpha_i = &alpha[i*nr_class];
			int *alpha_index_i = &alpha_index[i*nr_class];

			if(Ai > 0)
			{
				for(m=0;m<active_size_i[i];m++)
					G[m] = 1;
				if(y_index[i] < active_size_i[i])
					G[y_index[i]] = 0;

				feature_node *xi = prob->x[i];
				while(xi->index!= -1)
				{
					double *w_i = &w[(xi->index-1)*nr_class];
					for(m=0;m<active_size_i[i];m++)
						G[m] += w_i[alpha_index_i[m]]*(xi->value);
					xi++;
				}

				double minG = INF;
				double maxG = -INF;
				for(m=0;m<active_size_i[i];m++)
				{
					if(alpha_i[alpha_index_i[m]] < 0 && G[m] < minG)
						minG = G[m];
					if(G[m] > maxG)
						maxG = G[m];
				}
				if(y_index[i] < active_size_i[i])
					if(alpha_i[prob->y[i]] < C[GETI(i)] && G[y_index[i]] < minG)
						minG = G[y_index[i]];

				for(m=0;m<active_size_i[i];m++)
				{
					if(be_shrunk(i, m, y_index[i], alpha_i[alpha_index_i[m]], minG))
					{
						active_size_i[i]--;
						while(active_size_i[i]>m)
						{
							if(!be_shrunk(i, active_size_i[i], y_index[i], 
											alpha_i[alpha_index_i[active_size_i[i]]], minG))
							{
								swap(alpha_index_i[m], alpha_index_i[active_size_i[i]]);
								swap(G[m], G[active_size_i[i]]);
								if(y_index[i] == active_size_i[i])
									y_index[i] = m;
								else if(y_index[i] == m) 
									y_index[i] = active_size_i[i];
								break;
							}
							active_size_i[i]--;
						}
					}
				}

				if(active_size_i[i] <= 1)
				{
					active_size--;
					swap(index[s], index[active_size]);
					s--;	
					continue;
				}

				if(maxG-minG <= 1e-12)
					continue;
				else
					stopping = max(maxG - minG, stopping);

				for(m=0;m<active_size_i[i];m++)
					B[m] = G[m] - Ai*alpha_i[alpha_index_i[m]] ;

				solve_sub_problem(Ai, y_index[i], C[GETI(i)], active_size_i[i], alpha_new);
				int nz_d = 0;
				for(m=0;m<active_size_i[i];m++)
				{
					double d = alpha_new[m] - alpha_i[alpha_index_i[m]];
					alpha_i[alpha_index_i[m]] = alpha_new[m];
					if(fabs(d) >= 1e-12)
					{
						d_ind[nz_d] = alpha_index_i[m];
						d_val[nz_d] = d;
						nz_d++;
					}
				}

				xi = prob->x[i];
				while(xi->index != -1)
				{
					double *w_i = &w[(xi->index-1)*nr_class];
					for(m=0;m<nz_d;m++)
						w_i[d_ind[m]] += d_val[m]*xi->value;
					xi++;
				}
			}
		}

		iter++;
		if(iter % 10 == 0)
		{
			info(".");
		}

		if(stopping < eps_shrink)
		{
			if(stopping < eps && start_from_all == true)
				break;
			else
			{
				active_size = l;
				for(i=0;i<l;i++)
					active_size_i[i] = nr_class;
				info("*");
				eps_shrink = max(eps_shrink/2, eps);
				start_from_all = true;
			}
		}
		else
			start_from_all = false;
	}

	info("\noptimization finished, #iter = %d\n",iter);
	if (iter >= max_iter)
		info("\nWARNING: reaching max number of iterations\n");

	// calculate objective value
	double v = 0;
	int nSV = 0;
	for(i=0;i<w_size*nr_class;i++)
		v += w[i]*w[i];
	v = 0.5*v;
	for(i=0;i<l*nr_class;i++)
	{
		v += alpha[i];
		if(fabs(alpha[i]) > 0)
			nSV++;
	}
	for(i=0;i<l;i++)
		v -= alpha[i*nr_class+prob->y[i]];
	info("Objective value = %lf\n",v);
	info("nSV = %d\n",nSV);

	delete [] alpha;
	delete [] alpha_new;
	delete [] index;
	delete [] QD;
	delete [] d_ind;
	delete [] d_val;
	delete [] alpha_index;
	delete [] y_index;
	delete [] active_size_i;
}
Exemplo n.º 24
0
void IString::reverse(char* str){
	int len = strlen(str);
	for(int i = 0; i < len / 2; i++)
		swap(str[i], str[len-1-i]);
}
Exemplo n.º 25
0
void solve_l2r_lr_dual(const problem *prob, double *w, double eps, double Cp, double Cn)
{
	int l = prob->l;
	int w_size = prob->n;
	int i, s, iter = 0;
	double *xTx = new double[l];
	int max_iter = 1000;
	int *index = new int[l];		
	double *alpha = new double[2*l]; // store alpha and C - alpha
	schar *y = new schar[l];	
	int max_inner_iter = 100; // for inner Newton
	double innereps = 1e-2; 
	double innereps_min = min(1e-8, eps);
	double upper_bound[3] = {Cn, 0, Cp};

	for(i=0; i<w_size; i++)
		w[i] = 0;
	for(i=0; i<l; i++)
	{
		if(prob->y[i] > 0)
		{
			y[i] = +1; 
		}
		else
		{
			y[i] = -1;
		}
		alpha[2*i] = min(0.001*upper_bound[GETI(i)], 1e-8);
		alpha[2*i+1] = upper_bound[GETI(i)] - alpha[2*i];

		xTx[i] = 0;
		feature_node *xi = prob->x[i];
		while (xi->index != -1)
		{
			xTx[i] += (xi->value)*(xi->value);
			w[xi->index-1] += y[i]*alpha[2*i]*xi->value;
			xi++;
		}
		index[i] = i;
	}

	while (iter < max_iter)
	{
		for (i=0; i<l; i++)
		{
			int j = i+rand()%(l-i);
			swap(index[i], index[j]);
		}
		int newton_iter = 0;
		double Gmax = 0;
		for (s=0; s<l; s++)
		{
			i = index[s];
			schar yi = y[i];
			double C = upper_bound[GETI(i)];
			double ywTx = 0, xisq = xTx[i];
			feature_node *xi = prob->x[i];
			while (xi->index != -1)
			{
				ywTx += w[xi->index-1]*xi->value;
				xi++;
			}
			ywTx *= y[i];
			double a = xisq, b = ywTx;

			// Decide to minimize g_1(z) or g_2(z)
			int ind1 = 2*i, ind2 = 2*i+1, sign = 1;
			if(0.5*a*(alpha[ind2]-alpha[ind1])+b < 0) 
			{
				ind1 = 2*i+1;
				ind2 = 2*i;
				sign = -1;
			}

			//  g_t(z) = z*log(z) + (C-z)*log(C-z) + 0.5a(z-alpha_old)^2 + sign*b(z-alpha_old)
			double alpha_old = alpha[ind1];
			double z = alpha_old;
			if(C - z < 0.5 * C) 
				z = 0.1*z;
			double gp = a*(z-alpha_old)+sign*b+log(z/(C-z));
			Gmax = max(Gmax, fabs(gp));

			// Newton method on the sub-problem
			const double eta = 0.1; // xi in the paper
			int inner_iter = 0;
			while (inner_iter <= max_inner_iter) 
			{
				if(fabs(gp) < innereps)
					break;
				double gpp = a + C/(C-z)/z;
				double tmpz = z - gp/gpp;
				if(tmpz <= 0) 
					z *= eta;
				else // tmpz in (0, C)
					z = tmpz;
				gp = a*(z-alpha_old)+sign*b+log(z/(C-z));
				newton_iter++;
				inner_iter++;
			}

			if(inner_iter > 0) // update w
			{
				alpha[ind1] = z;
				alpha[ind2] = C-z;
				xi = prob->x[i];
				while (xi->index != -1)
				{
					w[xi->index-1] += sign*(z-alpha_old)*yi*xi->value;
					xi++;
				}  
			}
		}

		iter++;
		if(iter % 10 == 0)
			info(".");

		if(Gmax < eps) 
			break;

		if(newton_iter < l/10) 
			innereps = max(innereps_min, 0.1*innereps);

	}

	info("\noptimization finished, #iter = %d\n",iter);
	if (iter >= max_iter)
		info("\nWARNING: reaching max number of iterations\nUsing -s 0 may be faster (also see FAQ)\n\n");

	// calculate objective value
	
	double v = 0;
	for(i=0; i<w_size; i++)
		v += w[i] * w[i];
	v *= 0.5;
	for(i=0; i<l; i++)
		v += alpha[2*i] * log(alpha[2*i]) + alpha[2*i+1] * log(alpha[2*i+1]) 
			- upper_bound[GETI(i)] * log(upper_bound[GETI(i)]);
	info("Objective value = %lf\n", v);

	delete [] xTx;
	delete [] alpha;
	delete [] y;
	delete [] index;
}
Exemplo n.º 26
0
void IString::reverse(char* str, int start, int end){
	int len = end - start + 1;
	for(int i = 0; i < len / 2; i++)
		swap(str[start + i], str[end-i]);
}
Exemplo n.º 27
0
 void Swap(vector_base& that) 
 {
     swap(start_, that.start_);
     swap(finish_, that.finish_);
     swap(end_of_storage_, that.end_of_storage_);
 }
Exemplo n.º 28
0
unit_map &unit_map::operator=(const unit_map &that)
{
	unit_map temp(that);
	swap(temp);
	return *this;
}
static int
hash_ipport6_uadt(struct ip_set *set, struct nlattr *tb[],
		  enum ipset_adt adt, u32 *lineno, u32 flags, bool retried)
{
	const struct hash_ipport *h = set->data;
	ipset_adtfn adtfn = set->variant->adt[adt];
	struct hash_ipport6_elem e = { };
	struct ip_set_ext ext = IP_SET_INIT_UEXT(h);
	u32 port, port_to;
	bool with_ports = false;
	int ret;

	if (unlikely(!tb[IPSET_ATTR_IP] ||
		     !ip_set_attr_netorder(tb, IPSET_ATTR_PORT) ||
		     !ip_set_optattr_netorder(tb, IPSET_ATTR_PORT_TO) ||
		     !ip_set_optattr_netorder(tb, IPSET_ATTR_TIMEOUT) ||
		     !ip_set_optattr_netorder(tb, IPSET_ATTR_PACKETS) ||
		     !ip_set_optattr_netorder(tb, IPSET_ATTR_BYTES) ||
		     tb[IPSET_ATTR_IP_TO] ||
		     tb[IPSET_ATTR_CIDR]))
		return -IPSET_ERR_PROTOCOL;

	if (tb[IPSET_ATTR_LINENO])
		*lineno = nla_get_u32(tb[IPSET_ATTR_LINENO]);

	ret = ip_set_get_ipaddr6(tb[IPSET_ATTR_IP], &e.ip) ||
	      ip_set_get_extensions(set, tb, &ext);
	if (ret)
		return ret;

	if (tb[IPSET_ATTR_PORT])
		e.port = nla_get_be16(tb[IPSET_ATTR_PORT]);
	else
		return -IPSET_ERR_PROTOCOL;

	if (tb[IPSET_ATTR_PROTO]) {
		e.proto = nla_get_u8(tb[IPSET_ATTR_PROTO]);
		with_ports = ip_set_proto_with_ports(e.proto);

		if (e.proto == 0)
			return -IPSET_ERR_INVALID_PROTO;
	} else
		return -IPSET_ERR_MISSING_PROTO;

	if (!(with_ports || e.proto == IPPROTO_ICMPV6))
		e.port = 0;

	if (adt == IPSET_TEST || !with_ports || !tb[IPSET_ATTR_PORT_TO]) {
		ret = adtfn(set, &e, &ext, &ext, flags);
		return ip_set_eexist(ret, flags) ? 0 : ret;
	}

	port = ntohs(e.port);
	port_to = ip_set_get_h16(tb[IPSET_ATTR_PORT_TO]);
	if (port > port_to)
		swap(port, port_to);

	if (retried)
		port = ntohs(h->next.port);
	for (; port <= port_to; port++) {
		e.port = htons(port);
		ret = adtfn(set, &e, &ext, &ext, flags);

		if (ret && !ip_set_eexist(ret, flags))
			return ret;
		else
			ret = 0;
	}
	return ret;
}
Exemplo n.º 30
0
void aranjare(float a[], int n) {
	int l = 0, i;
	for (i = 0; i < n; ++i)
		if (a[i] < 0)
			swap(&a[l++], &a[i]);
}