Point_3 calculateMove(const Vertex_handle &vertex,
		const Vector_3 &tangient)
{
	DEBUG_START;
	Plane_3 plane = dual(vertex->point());
	Vector_3 u(plane.a(), plane.b(), plane.c());
	if (plane.d() > 0.)
		u = -u;
	double value = tangient * u;
	Plane_3 planeNew(u.x(), u.y(), u.z(), -value);
	Point_3 point = dual(planeNew);
	DEBUG_END;
	return point;
}
Exemple #2
0
//-----------------------------------------------------------------------------
void MGL_EXPORT mgl_datac_set_ri(HADT d, HCDT re, HCDT im)
{
	long nx=d->GetNx(),ny=d->GetNy(),nz=d->GetNz();
	d->Create(nx,ny,nz);
#pragma omp parallel for
	for(long i=0;i<nx*ny*nz;i++)	d->a[i] = dual(re->vthr(i),im->vthr(i));
}
void SlidingTileEnvironment::unrank(uint64_t hashVal, SlidingTileState& s, std::vector<int> pattern)
{
	// int numEntriesLeft = 16 - pattern.size() + 1;
	std::vector<int> dual(pattern.size());
	for (int x = 0; x < pattern.size(); x++)
	{
		auto t = (factorial(15 - x) / factorial(16 - pattern.size()));
		dual[x] = hashVal / t;
		hashVal %= t;
		// hashVal /= numEntriesLeft;
	}
	for (int x = pattern.size() - 1; x >= 0; x--)
	{
		for (int y = x - 1; y >= 0; y--)
		{
			if (dual[y] <= dual[x])
			{
				dual[x]++;
			}
		}
	}

	for (auto &i : s.board)
		i = -1;
	for (int x = 0; x < pattern.size(); x++)
	{ 
		s.board[dual[x]] = pattern[x];
		// if (dual[x] != -1)
		if (pattern[x] == 0) {
			s.x = dual[x] % 4;
			s.y = dual[x] / 4;
		}
	}
}
uint64_t SlidingTileEnvironment::hash(SlidingTileState &a)
{
	std::vector<int> pattern{ 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
	uint64_t hashval = 0;
	// int size = 0;
	int numEntriesLeft = 16;
	std::vector<int> dual(pattern.size());
	for (int x = 0; x < 16; x++)
	{
		for (int y = 0; y < pattern.size(); y++)
		{
			if (a.board[x] == pattern[y])
			{
				dual[a.board[x]] = x;
				break;
			}
		}
	}

	for (int x = 0; x < pattern.size(); x++)
	{
		hashval += dual[x] * factorial(numEntriesLeft - 1) / factorial(16 - pattern.size());
		for (unsigned y = x; y < pattern.size(); y++)
		{
			if (dual[y] > dual[x])
				dual[y]--;
		}
		numEntriesLeft--;
	}
	return hashval;
}
Exemple #5
0
//-----------------------------------------------------------------------------
dual mgl_str2dual(const char *s)
{
	setlocale(LC_NUMERIC, "C");
	double re=0,im=0;	size_t ll=strlen(s);
	while(s[ll]<=' ')	ll--;
	if(*s=='(')		sscanf(s,"(%lg,%lg)",&re,&im);
	else if(*s=='i')	{	re=0;	im=atof(s+1);	}
	else if(*s=='[')	sscanf(s,"[%lg,%lg]",&re,&im);
	else if(*s=='{')	sscanf(s,"{%lg,%lg}",&re,&im);
	else if(s[ll]=='i')
	{
		double a,b;
		int s1=sscanf(s,"%lg+%lgi",&re,&im);
		int s2=sscanf(s,"%lg-%lgi",&a,&b);
		if(s1<2)
		{
		if(s2==2)	{	re=a;	im=-b;	}
		else	{	im=atof(s);	re=0;	}
		}
	}
	else
	{
		double a,b;
		int s1=sscanf(s,"%lg+i%lg",&re,&im);
		int s2=sscanf(s,"%lg-i%lg",&a,&b);
		if(s1<2)
		{
		if(s2==2)	{	re=a;	im=-b;	}
		else	{	re=atof(s);	im=0;	}
		}
	}
	setlocale(LC_NUMERIC, "");
	return dual(re,im);
}
static VectorXd runL2Estimation(SupportFunctionEstimationDataPtr SFEData)
{
	DEBUG_START;
	auto data = SFEData->supportData();
	auto planes = data->supportPlanes();
	auto directions = data->supportDirections<Vector_3>();
	auto values = data->supportValues();

	std::vector<DualPolyhedron_3::PointIndexed_3> points;
	for (unsigned i = 0; i < planes.size(); ++i)
		points.push_back(std::make_pair(dual(planes[i]), i));

	DualPolyhedron_3 dualP(directions, values, planes, points.begin(),
			points.end());
	dualP.initialize();
	double startingFunctional = dualP.calculateFunctional();
	std::cout << "Starting value of functional: " << startingFunctional
		<< std::endl;
	std::cout << "And square root of it: " << sqrt(startingFunctional)
		<< std::endl;

	dualP.makeConsistent();
	auto solution = calculateSolution(data, values);
	DEBUG_END;
	return solution;
}
	void EmbedderOptimalFlexDraw::optimizeOverEmbeddings(
		StaticPlanarSPQRTree &T,
		node parent,
		node mu,
		int bends,
		NodeArray<int> cost[],
		NodeArray<long long> embedding[])
	{
		cost[bends][mu] = numeric_limits<int>::max();
		long long embeddingsCount = T.numberOfNodeEmbeddings(mu);
		for (long long currentEmbedding = 0; currentEmbedding < embeddingsCount; ++currentEmbedding) {

			T.embed(mu, currentEmbedding);

			Skeleton &skeleton = T.skeleton(mu);
			Graph skeletonGraph = skeleton.getGraph();
			ConstCombinatorialEmbedding skeletonEmbedding(skeletonGraph);
			NodeArray<node> vertexNode(skeletonGraph);
			EdgeArray<node> edgeNode(skeletonGraph);
			FaceArray<node> faceNode(skeletonEmbedding);

			Graph N;
			EdgeArray<int> upper(N);
			EdgeArray<int> perUnitCost(N);
			NodeArray<int> supply(N);

			createNetwork(
				parent,
				mu,
				bends,
				cost,
				embedding,
				skeleton,
				edgeNode,
				N,
				upper,
				perUnitCost,
				supply);

			EdgeArray<int> lower(N, 0);
			EdgeArray<int> flow(N);
			NodeArray<int> dual(N);

			m_minCostFlowComputer.get().call(N, lower, upper, perUnitCost, supply, flow, dual);

			int currentCost = 0;
			for (edge e = N.firstEdge(); e != nullptr; e = e->succ())
				currentCost += perUnitCost[e] * flow[e];

			for (adjEntry adj = mu->firstAdj(); adj != nullptr; adj = adj->succ())
				currentCost += cost[0][adj->twinNode()];

			if (currentCost < cost[bends][mu]) {
				cost[bends][mu] = currentCost;
				embedding[bends][mu] = currentEmbedding;
			}
		}
	}
Exemple #8
0
    dualquat<value_t> fakelog () const {

        assert(isunit());
        
        const auto& lower = real().log();
        const auto& upper = dual()*real().C();

        return dualquat<value_t>(lower, upper);
    }
Exemple #9
0
    // TODO: expand this
    dualquat<value_t> operator*(const dualquat<value_t>& other) const {

        const auto& a = real();
        const auto& A = dual();
        const auto& b = other.real();
        const auto& B = other.dual();

        return dualquat<value_t>(a*b, (a*B)+(A*b));
    }
Exemple #10
0
//-----------------------------------------------------------------------------
MGL_NO_EXPORT void *mgl_cmodify(void *par)
{
	mglThreadC *t=(mglThreadC *)par;
	const mglFormulaC *f = (const mglFormulaC *)(t->v);
	long nx=t->p[0],ny=t->p[1],nz=t->p[2];
	dual *b=t->a;
	mreal dx,dy,dz;
	const dual *v=t->b, *w=t->c;
	dx=nx>1?1/(nx-1.):0;	dy=ny>1?1/(ny-1.):0;	dz=nz>1?1/(nz-1.):0;
#if !MGL_HAVE_PTHREAD
#pragma omp parallel for
#endif
	for(long i0=t->id;i0<t->n;i0+=mglNumThr)
	{
		register long i=i0%nx, j=((i0/nx)%ny), k=i0/(nx*ny);
		b[i0] = f->Calc(i*dx, j*dy, k*dz, b[i0], v?v[i0]:dual(0,0), w?w[i0]:dual(0,0));
	}
	return 0;
}
Exemple #11
0
	std::vector<vsr::cga2D::Vec> Intersect(const LineSegment &segment1, const LineSegment &segment2) {
		auto L1 = ToLine(segment1);
		auto L2 = ToLine(segment2);
		// Intersection as a flat point (Flp)
		auto intersection = (L1.dual() ^ L2.dual()).dual();
		
		// Check if the only intersection is the point at infinity
		if(std::abs(intersection[2]) <= 1e-6) {
			return std::vector<vsr::cga2D::Vec>{};
		}
		
		// Check if the intersection point is withint the line segments
		auto pt = vsr::cga2D::Vec(intersection[0], intersection[1]) / intersection[2];
		auto within1 = LineSegmentContainsPoint(segment1, pt);
		auto within2 = LineSegmentContainsPoint(segment2, pt);
		if(!within1 || !within2) {
			return std::vector<vsr::cga2D::Vec>{};
		}
		return std::vector<vsr::cga2D::Vec>{pt};
	}
Exemple #12
0
TEST(SolverContextTest, feature_in_multilabel_out) {
  typedef float Data;
  typedef double Result;

  sdca::size_type n = 50, m = 3, d = 5, pow_from = 0, pow_to = 1;
  std::vector<Data> features;
  std::vector<sdca::size_type> labels;
  std::vector<sdca::size_type> offsets;
  std::vector<Data> primal(d * m);
  std::vector<Data> dual(m * n);
  primal[2] = 1;
  dual[3] = 2;

  std::mt19937 gen(1);
  test_populate_real(n * d, pow_from, pow_to, 1.0f, gen, features);
  test_populate_int<sdca::size_type>(n, 1, m, gen, labels);
  offsets.resize(n + 1);
  std::iota(offsets.begin(), offsets.end(), 0);

  auto ctx = sdca::make_context(
    sdca::make_input_feature(d, n, &features[0]),
    sdca::make_output_multilabel(labels.begin(), labels.end(),
                                 offsets.begin(), offsets.end()),
    sdca::make_objective_l2_multilabel_hinge<Data>(),
    &dual[0], &primal[0]);

  EXPECT_EQ(d, ctx.train.num_dimensions());
  EXPECT_EQ(n, ctx.train.num_examples());
  EXPECT_EQ(m, ctx.train.num_classes());
  EXPECT_EQ(n, ctx.train.out.labels.size());
  EXPECT_EQ(n + 1, ctx.train.out.offsets.size());
  EXPECT_EQ(primal[2], ctx.primal_variables[2]);
  EXPECT_EQ(dual[3], ctx.dual_variables[3]);
  EXPECT_FALSE(ctx.is_dual());

  sdca::size_type n_tst = n - 5;
  labels.resize(n_tst);
  offsets.resize(n_tst + 1);
  ctx.add_test(sdca::make_input_feature(d, n_tst, &features[0]),
               sdca::make_output_multilabel(labels.begin(), labels.end(),
                                            offsets.begin(), offsets.end()));

  EXPECT_EQ(static_cast<std::size_t>(1), ctx.test.size());
  EXPECT_EQ(d, ctx.test[0].num_dimensions());
  EXPECT_EQ(n_tst, ctx.test[0].num_examples());
  EXPECT_EQ(m, ctx.test[0].num_classes());
  EXPECT_EQ(n_tst, ctx.test[0].out.labels.size());
  EXPECT_EQ(n_tst + 1, ctx.test[0].out.offsets.size());

  typedef decltype(ctx)::data_type data_type;
  typedef decltype(ctx)::result_type result_type;
  EXPECT_TRUE((std::is_same<Data, data_type>::value));
  EXPECT_TRUE((std::is_same<Result, result_type>::value));
}
Exemple #13
0
//-----------------------------------------------------------------------------
void MGL_EXPORT mgl_datac_set_ap(HADT d, HCDT a, HCDT p)
{
	long nx=d->GetNx(),ny=d->GetNy(),nz=d->GetNz();
	d->Create(nx,ny,nz);
#pragma omp parallel for
	for(long i=0;i<nx*ny*nz;i++)
	{
		register mreal aa=a->vthr(i), pp=p->vthr(i);
		d->a[i] = dual(aa*cos(pp), aa*sin(pp));
	}
}
Exemple #14
0
//-----------------------------------------------------------------------------
// evaluate formula for 'x'='r', 'y'='n'='v', 't'='z', 'u'='a' variables
dual mglFormulaC::Calc(dual x,dual y,dual t,dual u) const
{
	Error=0;
	dual a1[MGL_VS];	memset(a1,0,MGL_VS*sizeof(dual));
	a1['a'-'a'] = a1['u'-'a'] = u;
	a1['x'-'a'] = a1['r'-'a'] = x;
	a1['y'-'a'] = a1['n'-'a'] = a1['v'-'a'] = y;
	a1['z'-'a'] = a1['t'-'a'] = t;
	a1['i'-'a'] = dual(0,1);
	dual b = CalcIn(a1);
	return mgl_isfin(b) ? b : NAN;
}
Exemple #15
0
double EvtDecayPlaneNormalAngle(const EvtVector4R& p,const EvtVector4R& q,
                          const EvtVector4R& d1,const EvtVector4R& d2){

  EvtVector4C lc=dual(EvtGenFunctions::directProd(d1,d2)).cont2(q);

  EvtVector4R l(real(lc.get(0)),real(lc.get(1)),
		real(lc.get(2)),real(lc.get(3)));

  double pq=p*q;

  return q.mass()*(p*l)/sqrt(-(pq*pq-p.mass2()*q.mass2())*l.mass2());


}
Exemple #16
0
TEST(SolverContextTest, kernel_in_multilabel_out) {
  typedef double Data;
  typedef double Result;

  sdca::size_type n = 50, m = 3, pow_from = 0, pow_to = 1;
  std::vector<Data> kernel;
  std::vector<sdca::size_type> labels;
  std::vector<sdca::size_type> offsets;
  std::vector<Data> dual(m * n);
  dual[3] = 2;

  std::mt19937 gen(1);
  test_populate_real(n * n, pow_from, pow_to, 1.0, gen, kernel);
  test_populate_int<sdca::size_type>(n, 1, m, gen, labels);
  offsets.resize(n + 1);
  std::iota(offsets.begin(), offsets.end(), 0);

  auto ctx = sdca::make_context(
    sdca::make_input_kernel(n, &kernel[0]),
    sdca::make_output_multilabel(labels.begin(), labels.end(),
                                 offsets.begin(), offsets.end()),
    sdca::make_objective_l2_multilabel_hinge_smooth<Data>(),
    &dual[0]);

  EXPECT_EQ(n, ctx.train.num_examples());
  EXPECT_EQ(m, ctx.train.num_classes());
  EXPECT_EQ(n, ctx.train.out.labels.size());
  EXPECT_EQ(n + 1, ctx.train.out.offsets.size());
  EXPECT_EQ(dual[3], ctx.dual_variables[3]);
  EXPECT_TRUE(ctx.is_dual());

  sdca::size_type n_tst = n - 5;
  labels.resize(n_tst);
  offsets.resize(n_tst + 1);
  ctx.add_test(sdca::make_input_kernel(n, n_tst, &kernel[0]),
               sdca::make_output_multilabel(labels.begin(), labels.end(),
                                            offsets.begin(), offsets.end()));

  EXPECT_EQ(n_tst, ctx.test[0].num_examples());
  EXPECT_EQ(m, ctx.test[0].num_classes());
  EXPECT_EQ(n_tst, ctx.test[0].out.labels.size());
  EXPECT_EQ(n_tst + 1, ctx.test[0].out.offsets.size());

  typedef decltype(ctx)::data_type data_type;
  typedef decltype(ctx)::result_type result_type;
  EXPECT_TRUE((std::is_same<Data, data_type>::value));
  EXPECT_TRUE((std::is_same<Result, result_type>::value));
}
Exemple #17
0
int main()
{
   em::mv<7>::type Ie = {1.0};
   em::mv<1,2,4>::type a = {1.0,2.0,3.0};

   std::cout << "a: " << a << ", *a: " << dual(a) << ", **a: " << dual(dual(a)) << std::endl;
   
   std::cout << "a*~I: " << a*(~Ie) << ", a*~I*I: " << a*(~Ie)*Ie << std::endl;
   std::cout << "a*~I: " << a*(~Ie) << ", a*~I*~I: " << a*(~Ie)*(~Ie) << std::endl;

   static const sa::mv<1>::type e1={1.0};
   static const sa::mv<2>::type e2={1.0};
   static const sa::mv<4>::type e3={1.0};
   static const sa::mv<0x40>::type e0={1.0};

   std::cout << "dual(e1*e2): " << dual(e1*e2) << std::endl;
   std::cout << "dual(e3*e0): " << dual(e3*e0) << std::endl;
   std::cout << "*(*(e1*e2) ^ *(e3*e0)): " << dual(dual(e1*e2) ^ dual(e3*e0)) << std::endl;
}
Exemple #18
0
//-----------------------------------------------------------------------------
void mglFromStr(HADT d,char *buf,long NX,long NY,long NZ)	// TODO: add multithreading read
{
	if(NX<1 || NY <1 || NZ<1)	return;
	mgl_datac_create(d, NX,NY,NZ);
	long nb = strlen(buf);
	register long i=0, j=0;
	setlocale(LC_NUMERIC, "C");
	while(j<nb)
	{
		while(buf[j]<=' ' && j<nb)	j++;
		while(buf[j]=='#')		// skip comment
		{
			if(i>0 || buf[j+1]!='#')	// this is columns id
				while(!isn(buf[j]) && j<nb)	j++;
			else
			{
				while(!isn(buf[j]) && j<nb)
				{
					if(buf[j]>='a' && buf[j]<='z')
						d->id.push_back(buf[j]);
					j++;
				}
			}
			while(buf[j]<=' ' && j<nb)	j++;
		}
		char *s=buf+j;
		while(buf[j]>=' ' && buf[j]!=';' && j<nb)	j++;
		buf[j]=0;
		double re=0,im=0;	size_t ll=strlen(s);
		if(*s=='(')		sscanf(s,"(%lg,%lg)",&re,&im);
		else if(*s=='[')	sscanf(s,"[%lg,%lg]",&re,&im);
		else if(*s=='{')	sscanf(s,"{%lg,%lg}",&re,&im);
		else if(s[ll]=='i')	{	s[ll] = 0;	sscanf(s,"%lg+%lg)",&re,&im);	}
		else		sscanf(s,"%lg+i%lg",&re,&im);
		d->a[i] = dual(re,im);
		i++;	if(i>=NX*NY*NZ)	break;
	}
	setlocale(LC_NUMERIC, "");
}
Exemple #19
0
/**
merging a prismatic (oox) and cylindrical (oof) constraint may result in:
<ul>
<li> fixed : all other cases
</ul>
An outer product of the orientation will be zero when they are parallel.
When they define a fixed joint, the locating point is on the
axis of the prismatic joint.
*/
Joint meld_oox_oof(const Joint& slider, const Joint& axis, const bool flip = false) {
	//log4cpp::CategoryStream& log = slider.log_cf.infoStream();
	//log << (flip ? "meld_oof_oox" : "meld_oox_oof");

	// 
	isis_LOG(lg, isis_FILE, isis_INFO) << (flip ? "meld_oof_oox" : "meld_oox_oof");

	e3ga::vector u = e3ga::unit(slider.orientation);
	e3ga::vector v = e3ga::unit(axis.orientation);

	e3ga::bivector uv = u ^ v;
	if (e3ga::zero(uv, DEFAULT_TOLERANCE)) {
		return slider;
	}
	e3ga::vector  w = dual(uv);

	e3ga::bivector vw = v ^ w;
	e3ga::bivector wu = w ^ u;

	double uvw = norm(u ^ v ^ w);

	e3ga::vector  p = axis.location;
	e3ga::vector  q = slider.location; 
	e3ga::vector  r = q;

	double pvw = norm(p ^ v ^ w);
	double quw = norm(q ^ u ^ w);
	double ruv = norm(r ^ u ^ v);

	e3ga::vector location = 
		(pvw / uvw)*u + (quw / uvw) * v + (ruv / uvw) * w;

	Joint result(FIXED, 
		location, slider.orientation, slider.rotation,
		slider, axis);
	return result;
}
/*
  Synopsis: like the previous one, but for the _dual_ real forms.
*/
Interface::Interface(const ComplexReductiveGroup& G,
		     const lietype::Layout& lo, tags::DualTag)
: d_in(G.numDualRealForms())
, d_out(G.numDualRealForms())
, d_name(G.numDualRealForms())
{
  const size_t ndrf = G.numDualRealForms();
  const RootSystem& drs = G.dualRootSystem();
  const Fiber& dfundf = G.dualFundamental();
  const lietype::Layout dlo = dual(lo);

  std::vector<RealFormData> rf_data; rf_data.reserve(ndrf);

  for (RealFormNbr drf = 0; drf<ndrf; ++drf)
  {
    RootNbrSet so = cartanclass::toMostSplit(dfundf,drf,drs);
    Grading gr = cartanclass::specialGrading(dfundf,drf,drs);
    rf_data.push_back(RealFormData(drf,gr,so));
  }

  std::sort(rf_data.begin(),rf_data.end());

  for (size_t i=0; i<ndrf; ++i)
  {
    d_in[i] = rf_data[i].realForm();
    d_out[d_in[i]] = i;
  }

  // write names
  std::ostringstream os;
  for (size_t i=0; i<ndrf; ++i)
  {
    os.str("");
    printType(os,rf_data[i].grading(),dlo);
    d_name[i] = os.str();
  }
}
static unsigned getNearestOuterItemID(const Cell_handle &cell,
		const std::vector<SupportItem> &items,
		const Vertex_handle &infinity)
{
	DEBUG_START;
	Plane_3 plane = getOppositeFacetPlane(cell, infinity);
	Point_3 point = dual(plane);
	cell->info().point = point;
	
	double distanceMin = MINIMIZATION_STARTING_VALUE;
	unsigned iNearest = 0;
	const auto &associations = cell->info().associations;
	unsigned numUnresolved = 0;
	for (unsigned iPlane : associations)
	{
		SupportItem item = items[iPlane];
		Vector_3 u = item.direction;
		double value = item.value;
		double distance = value - u * (point - CGAL::Origin());
		if (!item.resolved)
		{
			ASSERT(distance > 0. && "Incorrect resolved flag");
			if (distance < distanceMin)
			{
				iNearest = iPlane;
				distanceMin = distance;
			}
			++numUnresolved;
		}
	}
	if (numUnresolved > 0)
		ASSERT(distanceMin < MINIMIZATION_STARTING_VALUE
				&& "Failed to find");
	cell->info().distance = distanceMin;
	DEBUG_END;
	return iNearest;
}
Exemple #22
0
void OptimalRanking::doCall(
	const Graph& G,
	NodeArray<int> &rank,
	EdgeArray<bool> &reversed,
	const EdgeArray<int> &length,
	const EdgeArray<int> &costOrig)
{
	MinCostFlowReinelt<int> mcf;

	// construct min-cost flow problem
	GraphCopy GC;
	GC.createEmpty(G);

	// compute connected component of G
	NodeArray<int> component(G);
	int numCC = connectedComponents(G,component);

	// intialize the array of lists of nodes contained in a CC
	Array<List<node> > nodesInCC(numCC);

	for(node v : G.nodes)
		nodesInCC[component[v]].pushBack(v);

	EdgeArray<edge> auxCopy(G);
	rank.init(G);

	for(int i = 0; i < numCC; ++i)
	{
		GC.initByNodes(nodesInCC[i], auxCopy);
		makeLoopFree(GC);

		for(edge e : GC.edges)
			if(reversed[GC.original(e)])
				GC.reverseEdge(e);

		// special cases:
		if(GC.numberOfNodes() == 1) {
			rank[GC.original(GC.firstNode())] = 0;
			continue;
		} else if(GC.numberOfEdges() == 1) {
			edge e = GC.original(GC.firstEdge());
			rank[e->source()] = 0;
			rank[e->target()] = length[e];
			continue;
		}

		EdgeArray<int> lowerBound(GC,0);
		EdgeArray<int> upperBound(GC,mcf.infinity());
		EdgeArray<int> cost(GC);
		NodeArray<int> supply(GC);

		for(edge e : GC.edges)
			cost[e] = -length[GC.original(e)];

		for(node v : GC.nodes) {
			int s = 0;
			edge e;
			forall_adj_edges(e,v) {
				if(v == e->source())
					s += costOrig[GC.original(e)];
				else
					s -= costOrig[GC.original(e)];
			}
			supply[v] = s;
		}

		OGDF_ASSERT(isAcyclic(GC) == true);

		// find min-cost flow
		EdgeArray<int> flow(GC);
		NodeArray<int> dual(GC);
#ifdef OGDF_DEBUG
		bool feasible =
#endif
			mcf.call(GC, lowerBound, upperBound, cost, supply, flow, dual);
		OGDF_ASSERT(feasible);

		for(node v : GC.nodes)
			rank[GC.original(v)] = dual[v];
	}
}
Exemple #23
0
//-----------------------------------------------------------------------------
// Formula constructor (automatically parse and "compile" formula)
mglFormulaC::mglFormulaC(const char *string)
{
	Error=0;
	Left=Right=0;
	Res=0; Kod=0;
	if(!string)	{	Kod = EQ_NUM;	Res = 0;	return;	}
	char *str = new char[strlen(string)+1];
	strcpy(str,string);
	long n,len;
	mgl_strtrim(str);
	mgl_strlwr(str);
	len=strlen(str);
	if(str[0]==0) {	delete []str;	return;	}
	if(str[0]=='(' && mglCheck(&(str[1]),len-2))	// remove braces
	{
		memmove(str,str+1,len);
		len-=2;	str[len]=0;
	}
	len=strlen(str);
	n=mglFindInText(str,"<>=");				// low priority -- conditions
	if(n>=0)
	{
		if(str[n]=='<') Kod=EQ_LT;
		else if(str[n]=='>') Kod=EQ_GT;
		else Kod=EQ_EQ;
		str[n]=0;
		Left=new mglFormulaC(str);
		Right=new mglFormulaC(str+n+1);
		delete []str;	return;
	}
	n=mglFindInText(str,"+-");				// normal priority -- additions
	if(n>=0 && (n<2 || str[n-1]!='e' || (str[n-2]!='.' && !isdigit(str[n-2]))))
	{
		if(str[n]=='+') Kod=EQ_ADD; else Kod=EQ_SUB;
		str[n]=0;
		Left=new mglFormulaC(str);
		Right=new mglFormulaC(str+n+1);
		delete []str;	return;
	}
	n=mglFindInText(str,"*/");				// high priority -- multiplications
	if(n>=0)
	{
		if(str[n]=='*') Kod=EQ_MUL; else Kod=EQ_DIV;
		str[n]=0;
		Left=new mglFormulaC(str);
		Right=new mglFormulaC(str+n+1);
		delete []str;	return;
	}
	n=mglFindInText(str,"^");				// highest priority -- power
	if(n>=0)
	{
		Kod=EQ_IPOW;		str[n]=0;
		Left=new mglFormulaC(str);
		Right=new mglFormulaC(str+n+1);
		delete []str;	return;
	}

	for(n=0;n<len;n++)	if(str[n]=='(')	break;
	if(n>=len)								// this is number or variable
	{
		Kod = EQ_NUM;
//		Left = Right = 0;
		if(str[1]==0 && str[0]>='a' && str[0]<='z')	// available variables
		{	Kod=EQ_A;	Res = str[0]-'a';	}
		else if(!strcmp(str,"rnd"))	Kod=EQ_RND;
		else if(!strcmp(str,"pi"))	Res=M_PI;
		else if(!strcmp(str,"inf"))	Res=INFINITY;
		else if(str[0]=='i')	Res = dual(0,atof(str+1));
		else	Res = (str[len-1]=='i') ? dual(0,atof(str)) : atof(str);
	}
	else
	{
		char name[128];
		mgl_strncpy(name,str,128);	name[127]=name[n]=0;
		memmove(str,str+n+1,len-n);
		len=strlen(str);		str[--len]=0;
		if(!strcmp(name,"sin")) Kod=EQ_SIN;
		else if(!strcmp(name,"cos")) Kod=EQ_COS;
		else if(!strcmp(name,"tg")) Kod=EQ_TAN;
		else if(!strcmp(name,"tan")) Kod=EQ_TAN;
		else if(!strcmp(name,"asin")) Kod=EQ_ASIN;
		else if(!strcmp(name,"acos")) Kod=EQ_ACOS;
		else if(!strcmp(name,"atan")) Kod=EQ_ATAN;
		else if(!strcmp(name,"sinh")) Kod=EQ_SINH;
		else if(!strcmp(name,"cosh")) Kod=EQ_COSH;
		else if(!strcmp(name,"tanh")) Kod=EQ_TANH;
		else if(!strcmp(name,"sh")) Kod=EQ_SINH;
		else if(!strcmp(name,"ch")) Kod=EQ_COSH;
		else if(!strcmp(name,"th")) Kod=EQ_TANH;
		else if(!strcmp(name,"sqrt")) Kod=EQ_SQRT;
		else if(!strcmp(name,"log")) Kod=EQ_LOG;
		else if(!strcmp(name,"pow")) Kod=EQ_POW;
		else if(!strcmp(name,"exp")) Kod=EQ_EXP;
		else if(!strcmp(name,"lg")) Kod=EQ_LG;
		else if(!strcmp(name,"ln")) Kod=EQ_LN;
		else if(!strcmp(name,"abs")) Kod=EQ_ABS;
		else if(!strcmp(name,"arg")) Kod=EQ_ARG;
		else if(!strcmp(name,"conj")) Kod=EQ_CONJ;
		else if(!strcmp(name,"real")) Kod=EQ_REAL;
		else if(!strcmp(name,"imag")) Kod=EQ_IMAG;
		else if(!strcmp(name,"norm")) Kod=EQ_NORM;
		else if(!strcmp(name,"cmplx")) Kod=EQ_CMPLX;
		else if(!strcmp(name,"hypot")) Kod=EQ_HYPOT;
		else {	delete []str;	return;	}	// unknown function
		n=mglFindInText(str,",");
		if(n>=0)
		{
			str[n]=0;
			Left=new mglFormulaC(str);
			Right=new mglFormulaC(str+n+1);
		}
		else
			Left=new mglFormulaC(str);
	}
	delete []str;
}
Exemple #24
0
	void work()
	{
		read();
		dual();
		scan();
	}
Exemple #25
0
/**
Convert a joint marker into a c3ga plane.
*/
c3ga::plane c3gaPlane( const Joint joint ) {
	c3ga::normalizedPoint locate_pnt = c3ga_point( joint.location );
	c3ga::normalizedPoint orient_vec = c3ga_point( joint.orientation );
	return c3ga::plane
		(locate_pnt ^ dual(orient_vec), 0);
}
Exemple #26
0
//######################################################################
/// this is the Volume Algorithm
int
VOL_problem::solve(VOL_user_hooks& hooks, const bool use_preset_dual) 
{

   if (initialize(use_preset_dual) < 0) // initialize several parameters
      return -1;

   double best_ub = parm.ubinit;      // upper bound
   int retval = 0; 

   VOL_dvector rc(psize); // reduced costs

   VOL_dual dual(dsize); // dual vector
   dual.u = dsol;

   VOL_primal primal(psize, dsize);  // primal vector

   retval = hooks.compute_rc(dual.u, rc); // compute reduced costs
   if (retval < 0)  return -1;
   // solve relaxed problem
   retval = hooks.solve_subproblem(dual.u, rc, dual.lcost,
				   primal.x, primal.v, primal.value);
   if (retval < 0)  return -1;
   // set target for the lagrangian value
   double target = readjust_target(-COIN_DBL_MAX/2, dual.lcost);
   // find primal violation 
   primal.find_max_viol(dual_lb, dual_ub); // this may be left out for speed

   VOL_primal pstar(primal); // set pstar=primal
   pstar.find_max_viol(dual_lb, dual_ub); // set violation of pstar
   
   dual.compute_xrc(pstar.x, primal.x, rc); // compute xrc

   //
   VOL_dual dstar(dual); // dstar is the best dual solution so far
   VOL_dual dlast(dual); // set dlast=dual

   iter_ = 0;
   if (parm.printflag)
     print_info(iter_, primal, pstar, dual);

   VOL_swing swing;
   VOL_alpha_factor alpha_factor;

   double * lcost_sequence = new double[parm.ascent_check_invl];

   const int ascent_first_check = VolMax(parm.ascent_first_check,
					 parm.ascent_check_invl);

   for (iter_ = 1; iter_ <= parm.maxsgriters; ++iter_) {  // main iteration
      dlast = dual;
      // take a dual step
      dual.step(target, lambda_, dual_lb, dual_ub, pstar.v);
      // compute reduced costs
      retval = hooks.compute_rc(dual.u, rc);
      if (retval < 0)  break;
      // solve relaxed problem
      retval = hooks.solve_subproblem(dual.u, rc, dual.lcost,
				      primal.x, primal.v, primal.value);
      if (retval < 0)  break;
      // set the violation of primal
      primal.find_max_viol(dual_lb, dual_ub); // this may be left out for speed
      dual.compute_xrc(pstar.x, primal.x, rc); // compute xrc

      if (dual.lcost > dstar.lcost) { 
	dstar = dual; // update dstar
      }
      // check if target should be updated
      target = readjust_target(target, dstar.lcost);
      // compute inner product between the new subgradient and the
      // last direction. This to decide among green, yellow, red
      const double ascent = dual.ascent(primal.v, dlast.u);
      // green, yellow, red
      swing.cond(dlast, dual.lcost, ascent, iter_);
      // change lambda if needed
      lambda_ *= swing.lfactor(parm, lambda_, iter_);

      if (iter_ % parm.alphaint == 0) { // change alpha if needed
	 const double fact = alpha_factor.factor(parm, dstar.lcost, alpha_);
	 if (fact != 1.0 && (parm.printflag & 2)) {
 	    printf(" ------------decreasing alpha to %f\n", alpha_*fact);
	 }
	 alpha_ *= fact;
      }
      // convex combination with new primal vector
      pstar.cc(power_heur(primal, pstar, dual), primal);
      pstar.find_max_viol(dual_lb, dual_ub); // find maximum violation of pstar

      if (swing.rd)
	dual = dstar; // if there is no improvement reset dual=dstar

      if ((iter_ % parm.printinvl == 0) && parm.printflag) { // printing iteration information
	 print_info(iter_, primal, pstar, dual);
	 swing.print();
      }

      if (iter_ % parm.heurinvl == 0) { // run primal heuristic
	 double ub = COIN_DBL_MAX;
	 retval = hooks.heuristics(*this, pstar.x, ub);
	 if (retval < 0)  break;
	 if (ub < best_ub)
	    best_ub = ub;
      }
      // save dual solution every 500 iterations
      if (iter_ % 500 == 0 && parm.temp_dualfile != 0) {
	 FILE* outfile = fopen(parm.temp_dualfile, "w");
	 const VOL_dvector& u = dstar.u;
	 const int m = u.size();
	 for (int i = 0; i < m; ++i) {
	    fprintf(outfile, "%i %f\n", i+1, u[i]);
	 }
	 fclose(outfile);
      }

      // test terminating criteria
      const bool primal_feas = 
	(pstar.viol < parm.primal_abs_precision);
      //const double gap = VolAbs(pstar.value - dstar.lcost); 
      const double gap = pstar.value - dstar.lcost;
      const bool small_gap = VolAbs(dstar.lcost) < 0.0001 ?
	(gap < parm.gap_abs_precision) :
	( (gap < parm.gap_abs_precision) || 
	  (gap/VolAbs(dstar.lcost) < parm.gap_rel_precision) );
      
      // test optimality
      if (primal_feas && small_gap){
	if (parm.printflag) printf(" small lp gap \n");
	break;
      }

      // test proving integer optimality
      if (best_ub - dstar.lcost < parm.granularity){
	if (parm.printflag) printf(" small ip gap \n");
	break;
      }

      // test for non-improvement
      const int k = iter_ % parm.ascent_check_invl;
      if (iter_ > ascent_first_check) {
	 if (dstar.lcost - lcost_sequence[k] <
	     VolAbs(lcost_sequence[k]) * parm.minimum_rel_ascent){
	   if (parm.printflag) printf(" small improvement \n");
	   break;
	 }
      }
      lcost_sequence[k] = dstar.lcost;
   }
   delete[] lcost_sequence;

   if (parm.printflag)
     print_info(iter_, primal, pstar, dual);
   // set solution to return
   value = dstar.lcost;
   psol = pstar.x;
   dsol = dstar.u;
   viol = pstar.v;

   return retval;
}
	void EmbedderOptimalFlexDraw::call(Graph &G, adjEntry &adjExternal)
	{
		StaticPlanarSPQRTree T(G);

		NodeArray<int> cost[4];
		NodeArray<long long> embedding[4];
		for (int bends = 0; bends < 4; ++bends) {
			cost[bends].init(T.tree());
			embedding[bends].init(T.tree());
		}

		int minCost = numeric_limits<int>::max();
		node minCostRoot;
		long long minCostEmbedding;

		for (node root = T.tree().firstNode(); root != nullptr; root = root->succ()) {

			T.rootTreeAt(root);

			for (adjEntry adj = root->firstAdj(); adj != nullptr; adj = adj->succ())
				computePrincipalSplitComponentCost(T, cost, embedding, root, adj->twinNode());

			optimizeOverEmbeddings(T, nullptr, root, 0, cost, embedding);

			if (cost[0][root] < minCost) {
				minCost = cost[0][root];
				minCostEmbedding = embedding[0][root];
				minCostRoot = root;
			}

		}

		T.rootTreeAt(minCostRoot);
		T.embed(minCostRoot, minCostEmbedding);

		for (adjEntry adj = minCostRoot->firstAdj(); adj != nullptr; adj = adj->succ())
			computePrincipalSplitComponentCost(T, cost, embedding, minCostRoot, adj->twinNode());

		Skeleton &skeleton = T.skeleton(minCostRoot);
		Graph skeletonGraph = skeleton.getGraph();
		ConstCombinatorialEmbedding skeletonEmbedding(skeletonGraph);
		EdgeArray<node> edgeNode(skeletonGraph);

		Graph N;
		EdgeArray<int> upper(N);
		EdgeArray<int> perUnitCost(N);
		NodeArray<int> supply(N);

		createNetwork(
			nullptr,
			minCostRoot,
			0,
			cost,
			embedding,
			skeleton,
			edgeNode,
			N,
			upper,
			perUnitCost,
			supply);

		EdgeArray<int> lower(N, 0);
		EdgeArray<int> flow(N);
		NodeArray<int> dual(N);

		m_minCostFlowComputer.get().call(N, lower, upper, perUnitCost, supply, flow, dual);

		for (node mu = T.tree().firstNode(); mu != nullptr; mu = mu->succ()) {

			if (mu == minCostRoot)
				continue;

			int bends = 0;
			for (adjEntry adj = edgeNode[T.skeleton(mu).referenceEdge()]->firstAdj(); adj != nullptr; adj = adj->succ())
				bends += abs(flow[adj->theEdge()]);

			T.embed(mu, embedding[bends][mu]);
		}

		T.embed(G);
		ConstCombinatorialEmbedding graphEmbedding(G);
		adjExternal = graphEmbedding.externalFace()->firstAdj();
	}
Exemple #28
0
 // JOIN operation; higher in lattice.  Done by finding the dual of the
 // meet of the dual of the 2 inputs.
 const Type *join( const Type *t ) const {
   return dual()->meet(t->dual())->dual(); }
void EvtKstarnunu::decay(EvtParticle *p){
  
  static EvtId NUE=EvtPDL::getId("nu_e");
  static EvtId NUM=EvtPDL::getId("nu_mu");
  static EvtId NUT=EvtPDL::getId("nu_tau");
  static EvtId NUEB=EvtPDL::getId("anti-nu_e");
  static EvtId NUMB=EvtPDL::getId("anti-nu_mu");
  static EvtId NUTB=EvtPDL::getId("anti-nu_tau");

  p->initializePhaseSpace(getNDaug(),getDaugs());
  
  double m_b = p->mass();

  EvtParticle *meson, *neutrino1, *neutrino2;
  meson = p->getDaug(0);
  neutrino1 = p->getDaug(1);
  neutrino2 = p->getDaug(2);
  EvtVector4R momnu1 = neutrino1->getP4();
  EvtVector4R momnu2 = neutrino2->getP4();
  EvtVector4R momkstar = meson->getP4();
  
  double v0_0, a1_0, a2_0;
  double m2v0, a1_b, a2_b;
  v0_0 = 0.47;
  a1_0 = 0.37;
  a2_0 = 0.40;
  m2v0 = 5.*5.;
  a1_b = -0.023;
  a2_b = 0.034;

  EvtVector4R q = momnu1+momnu2;
  double q2 = q.mass2();   

  double v0, a1, a2;
  v0 = v0_0/(1-q2/m2v0);
  a1 = a1_0*(1+a1_b*q2);
  a2 = a2_0*(1+a2_b*q2);

  EvtVector4R p4b; p4b.set(m_b,0.,0.,0.);  // Do calcs in mother rest frame
  
  double m_k = meson->mass();

  EvtTensor4C tds=(-2*v0/(m_b+m_k))*dual(EvtGenFunctions::directProd(p4b,momkstar))
    - EvtComplex(0.0,1.0)*
    ( (m_b+m_k)*a1*EvtTensor4C::g()
      - (a2/(m_b+m_k))*EvtGenFunctions::directProd(p4b-momkstar,p4b+momkstar)); 
  
  EvtVector4C l;

  if (getDaug(1)==NUE||getDaug(1)==NUM||getDaug(1)==NUT) {
        l=EvtLeptonVACurrent(neutrino1->spParentNeutrino(),
			     neutrino2->spParentNeutrino());
  }
  if (getDaug(1)==NUEB||getDaug(1)==NUMB||getDaug(1)==NUTB) {
        l=EvtLeptonVACurrent(neutrino2->spParentNeutrino(),
			     neutrino1->spParentNeutrino());
  }

  EvtVector4C et0,et1,et2; 
  et0 = tds.cont1( meson->epsParent(0).conj() );
  et1 = tds.cont1( meson->epsParent(1).conj() );
  et2 = tds.cont1( meson->epsParent(2).conj() );

  vertex(0,l*et0);
  vertex(1,l*et1);
  vertex(2,l*et2);

  return;
}
Exemple #30
0
//======================================================
void EvtBcVNpi::decay( EvtParticle *root_particle ) {
   ++nCall;
//     cout<<"BcVNpi::decay()"<<endl;
    root_particle->initializePhaseSpace(getNDaug(),getDaugs());

    EvtVector4R
	    p4b(root_particle->mass(), 0., 0., 0.),                  // Bc momentum
	    p4meson=root_particle->getDaug(0)->getP4(),     		   // J/psi momenta
	    Q=p4b-p4meson;
    double Q2=Q.mass2();


// check pi-mesons and calculate hadronic current
    EvtVector4C hardCur;
//     bool foundHadCurr=false;
    if( getNDaug() == 2) {
      hardCur = wcurr->WCurrent( root_particle->getDaug(1)->getP4() );
//       foundHadCurr=true;
    }
    else if( getNDaug() == 3) {
      hardCur = wcurr->WCurrent( root_particle->getDaug(1)->getP4() , 
				 root_particle->getDaug(2)->getP4() 
			       );
//       foundHadCurr=true;   
    }
    else if( getNDaug() == 4) {
      hardCur = wcurr->WCurrent( root_particle->getDaug(1)->getP4() , 
				 root_particle->getDaug(2)->getP4(), 
				 root_particle->getDaug(3)->getP4() 
			       );
//       foundHadCurr=true;         
    }
    else if( getNDaug() == 6) // Bc -> psi pi+ pi+ pi- pi- pi+ from [Kuhn, Was, hep-ph/0602162
    {

		hardCur = wcurr->WCurrent(root_particle->getDaug(1)->getP4(),
					  root_particle->getDaug(2)->getP4(),
					  root_particle->getDaug(3)->getP4(),
					  root_particle->getDaug(4)->getP4(),
					  root_particle->getDaug(5)->getP4()
				 );
// 		foundHadCurr=true;
    }	
    else {
	    report(Severity::Error,"EvtGen") << "Have not yet implemented this final state in BCNPI model" << endl;
	    report(Severity::Error,"EvtGen") << "Ndaug="<<getNDaug() << endl;
	    int id;
	    for ( id=0; id<(getNDaug()-1); id++ ) 
	    report(Severity::Error,"EvtGen") << "Daug " << id << " "<<EvtPDL::name(getDaug(id)).c_str() << endl;
	    ::abort();
    };  

// calculate Bc -> V W form-factors
	double a1f, a2f, vf, a0f;
	double m_meson = root_particle->getDaug(0)->mass();
	double m_b = root_particle->mass();
	ffmodel->getvectorff(root_particle->getId(),
				root_particle->getDaug(0)->getId(),
				Q2,
				m_meson,
				&a1f, 
				&a2f, 
				&vf, 
				&a0f);
	double a3f = ((m_b+m_meson)/(2.0*m_meson))*a1f -
	      ((m_b-m_meson)/(2.0*m_meson))*a2f;

// calculate Bc -> V W current
	EvtTensor4C H;
	H = a1f*(m_b+m_meson)*EvtTensor4C::g();
	H.addDirProd((-a2f/(m_b+m_meson))*p4b,p4b+p4meson);
	H+=EvtComplex(0.0,vf/(m_b+m_meson))*dual(EvtGenFunctions::directProd(p4meson+p4b,p4b-p4meson));
	H.addDirProd((a0f-a3f)*2.0*(m_meson/Q2)*p4b,p4b-p4meson);
	EvtVector4C  Heps=H.cont2(hardCur);
	
	for(int i=0; i<4; i++) {
		EvtVector4C  eps=root_particle->getDaug(0)->epsParent(i).conj(); // psi-meson polarization vector
		EvtComplex amp=eps*Heps;
		vertex(i,amp);
	};

}