int main()
{
	double x1,y1,x2,y2;
	double tx1,ty1,tx2,ty2;
	double k1,tk2;
	double isK1Exist,isTK2Exist;
	int t;
	double angle;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%lf%lf%lf%lf%lf%lf%lf%lf",
				&x1,&y1,&x2,&y2,&tx1,&ty1,&tx2,&ty2);
		isK1Exist=getK(x1,y1,x2,y2,&k1);
		isTK2Exist=getK(tx1,ty1,tx2,ty2,&tk2);
		if(isK1Exist==1 && isTK2Exist==1)
		{
			angle=getJiaJiao(k1,tk2);
		}
		else if(isK1Exist==1)//直线1斜率存在
		{
			angle=atan(fabs((x2-x1)/(y2-y1)));
		}//若一条直线的斜率不存在,则可看为一条直线与y轴的夹角
		else if(isTK2Exist==1)//直线2斜率存在
		{
			angle=atan(fabs((tx2-tx1)/(ty2-ty1)));
		}
		else angle=0.0;
		angle*=180.0/PI;
		printf("%.1lf\n",angle);
	}
	return 0;
}
Exemplo n.º 2
0
	inline int getK(int ll, int lr, int root, int k)
	{
		if (sum_tree[root] < k) return -1;
		if (ll == lr) return ll;
		int lm = (ll + lr) / 2;
		if (sum_tree[2*root+1] >= k) return getK(ll, lm, 2 * root + 1, k);
		return getK(lm + 1, lr, 2 * root + 2, k-sum_tree[2*root+1]);
	}
    //! main constructor
    Panel(point_type p0, point_type p1, point_type p2) : BC(POTENTIAL) {
      vertices.resize(3);
      vertices[0] = p0;
      vertices[1] = p1;
      vertices[2] = p2;

      // get the center
      center = (p0+p1+p2)/3;

      // area & normal
      point_type L0 = p2-p0;
      point_type L1 = p1-p0;

      point_type c = point_type(L0[1]*L1[2]-L0[2]*L1[1],
                                -(L0[0]*L1[2]-L0[2]*L1[0]),
                                L0[0]*L1[1]-L0[1]*L1[0]);
      Area = 0.5*norm(c);
      normal = c/2/Area;

      // generate the quadrature points
      // assume K = 3 for now
      auto Config = BEMConfig::Instance();
      unsigned k = Config->getK();
      auto& points = Config->GaussPoints();
      quad_points.resize(k);
      // loop over K points performing matvecs
      for (unsigned i=0; i<k; i++) {
        double x = vertices[0][0]*points[i][0]+vertices[1][0]*points[i][1]+vertices[2][0]*points[i][2];
        double y = vertices[0][1]*points[i][0]+vertices[1][1]*points[i][1]+vertices[2][1]*points[i][2];
        double z = vertices[0][2]*points[i][0]+vertices[1][2]*points[i][1]+vertices[2][2]*points[i][2];

        quad_points[i] = point_type(x,y,z);
      }
    }
Exemplo n.º 4
0
void
PFEMElement2DBubble::getF(Vector& f) const
{
    f.resize(6);
    f.Zero();

    // external force
    for(int a=0; a<3; a++) {
        f(2*a) = bx;
        f(2*a+1) = by;
    }
    f *= rho*thickness*J/6.0;

    // velocity
    if(mu > 0) {
        Vector v(6);
        for(int a=0; a<3; a++) {
            const Vector& vel = nodes[2*a]->getTrialVel();
            v(2*a) = vel(0);
            v(2*a+1) = vel(1);
        }
        Matrix k(6,6);
        getK(k);
        f.addMatrixVector(1.0, k, v, -1.0);
    }
}
Exemplo n.º 5
0
	void MCNeuronSim::setupSingleNeuronParms(int grpRowId, int neurId, bool coupledComp){
			for(unsigned int c = 0; c < compCount; c++) // each neuron has compCount compartments
			{
				network->setIzhikevichParameter(excGroup[grpRowId][c], neurId, "C", getCm(neurId, c));
				network->setIzhikevichParameter(excGroup[grpRowId][c], neurId, "k", getK(neurId, c));
				network->setIzhikevichParameter(excGroup[grpRowId][c], neurId, "vr", getVr(neurId));
				network->setIzhikevichParameter(excGroup[grpRowId][c], neurId, "vt", getVt(neurId, c));
				network->setIzhikevichParameter(excGroup[grpRowId][c], neurId, "a", getA(neurId, c));
				network->setIzhikevichParameter(excGroup[grpRowId][c], neurId, "b", getB(neurId, c));
				network->setIzhikevichParameter(excGroup[grpRowId][c], neurId, "vpeak", getVpeak(neurId, c));
				network->setIzhikevichParameter(excGroup[grpRowId][c], neurId, "c", getVmin(neurId, c));
				network->setIzhikevichParameter(excGroup[grpRowId][c], neurId, "d", getD(neurId, c));

				if(coupledComp){
					if(c>0){
						double G = getG(neurId, c); //parameters[neurId][G_idx[c-1]];
						double P = getP(neurId, c);//parameters[neurId][P_idx[c-1]];
						float fwd = G * P;
						float bwd = G * (1-P);
						/*
						 * generally, fwd is carlsim 'down', bwd is carlsim 'up' for the purpose of coupling constant assignment, but,
						 * when there is a dendrite 'below' soma: ****cases 3c2 and 4c2***
						 * up and down are reversed.
						 */
						if(compCount>2 && c==1 && connLayout[c]==connLayout[c+1]){ //meaning 2 dendrites (dend 1 and dend2 ) connecting to the same point
							network->setCouplingConstant(excGroup[grpRowId][connLayout[c]], neurId, "down", bwd);
							network->setCouplingConstant(excGroup[grpRowId][c], neurId, "up", fwd);
						}else{
							network->setCouplingConstant(excGroup[grpRowId][c], neurId, "down", fwd);
							network->setCouplingConstant(excGroup[grpRowId][connLayout[c]], neurId, "up", bwd);
						}
					}
				}
			}
		}
Exemplo n.º 6
0
/*
 * Class:     uk_ac_manchester_cs_factplusplus_FaCTPlusPlus
 * Method:    realise
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_realise
(JNIEnv * env, jobject obj)
{
    MemoryStatistics MS("Realization");
    TRACE_JNI("realise");
    PROCESS_QUERY ( getK(env,obj)->realiseKB() );
}
Exemplo n.º 7
0
/*
 * Class:     uk_ac_manchester_cs_factplusplus_FaCTPlusPlus
 * Method:    classify
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_classify
(JNIEnv * env, jobject obj)
{
    MemoryStatistics MS("Classification");
    TRACE_JNI("classify");
    PROCESS_QUERY ( getK(env,obj)->classifyKB() );
}
Exemplo n.º 8
0
std::pair<size_t, Double> KMInput::getClosest(size_t i) const {
	size_t const l(label(i));
	std::pair<size_t, Double> min(l, d(i));
	//	for (size_t k(0); k < getK(); ++k) {
	//		if (k != l) {
	//			std::pair<size_t, Double> const d(k, getDistance(i, k));
	//			if (d.second < min.second) {
	//				min = d;
	//			}
	//		}
	//	}

	if (_modifiedLabels.contains(l)) {
		for (size_t k(0); k < getK(); ++k) {
			if (k != l) {
				std::pair<size_t, Double> const d(k, getDistance(i, k));
				if (d.second < min.second) {
					min = d;
				}
			}
		}
	} else {
		for (auto const & k : _modifiedLabels) {
			//	for (size_t k(0); k < getK(); ++k) {
			if (k != l) {
				std::pair<size_t, Double> const d(k, getDistance(i, k));
				if (d.second < min.second) {
					min = d;
				}
			}
		}
	}
	return min;
}
Exemplo n.º 9
0
 int maxPoints(vector<Point>& points) {
     unordered_map<float, int> m;
     
     int size = points.size();
     if (size == 0) return 0;
     
     int res = 0;
     for (int i=0; i<size; i++) {
         m.clear();
         int same = 0;
         int sameY = 0;
         const Point& pointI = points[i];
         for (int j=i+1; j<size; j++) {
             const Point& pointJ = points[j];
             if (pointI.x == pointJ.x) {
                 if (pointI.y == pointJ.y) {
                     same ++;
                 } else {
                     // a special case, equal y, but x is not equal, it can not use getK to compute K
                     sameY ++;
                 }
             } else {
                 m[getK(points[i], points[j])] ++;
             }
         }
         
         res = max(res, max(sameY, maxVal(m)) + same + 1);
     }
     
     return res;
 }
Exemplo n.º 10
0
Arquivo: sumK.cpp Projeto: mma0727/DSA
    void addLast(const std::vector<int>& list) 
    {
        int n = _nums.size();
        int k = getK();

        _nums.insert(_nums.end(), list.begin(), list.end());
        
        if (_nums.size() < k) return;
        
        else if (_nums.size() == k) {
            _sum.insert(std::accumulate(_nums.begin(), _nums.end(), 0));
        }

        else {
            int start = n > k ? n - k + 1 : 0;
            int sum = 0;
            for (int i = start; i < int(_nums.size()); ++i) {
                sum += _nums[i];
                if (i - start + 1 >= k) {
                    _sum.insert(sum);
                    sum -= _nums[i-k+1];
                }
            }
        }
    }
Exemplo n.º 11
0
void KalmanFilter::updateKalman() {
  double** K = getK();

  getP(K);
  getX(K);

  freeMatrix(K,3);
}
Exemplo n.º 12
0
// -----------------------------------------------------------------------
	void BanditLearner::save(ofstream& outputStream, int numTabs)
	{
		BaseLearner::save(outputStream, numTabs);

		outputStream << Serialization::standardTag("reward", getReward(), numTabs) << endl;
		outputStream << Serialization::standardTag("K", getK(), numTabs) << endl;
		outputStream << Serialization::standardTag("arm", getKeyToString(), numTabs) << endl;
	}
Exemplo n.º 13
0
  void print() {
    auto lk =getK();
    Lock l(global::coutLock);
    std::cout << "K in "
	      << std::this_thread::get_id() 
      //	      << " is " << getK() << std::endl;
	      << " is " << lk << std::endl;
  }
Exemplo n.º 14
0
/*
 * Class:     uk_ac_manchester_cs_factplusplus_FaCTPlusPlus
 * Method:    isKBConsistent
 * Signature: ()Z
 */
JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isKBConsistent
(JNIEnv * env, jobject obj)
{
    MemoryStatistics MS("Consistency Checking");
    TRACE_JNI("isKBConsistent");
    bool ret = false;
    PROCESS_QUERY ( ret=getK(env,obj)->isKBConsistent() );
    return ret;
}
Exemplo n.º 15
0
 std::string GammaDeviate::make_repr(bool incl_seed)
 {
     std::ostringstream oss(" ");
     oss << "galsim.GammaDeviate(";
     if (incl_seed) oss << seedstring(split(serialize(), ' ')) << ", ";
     oss << "k="<<getK()<<", ";
     oss << "theta="<<getTheta()<<")";
     return oss.str();
 }
Exemplo n.º 16
0
void Sudoku::solve() {
	std::clog << "Ich weiss nicht, wie man " << getK() << "-Sudokus loest, dieses auch nicht:" << std::endl;
	std::cout << *this << std::endl;

	if(solveBacktracking( 0, 0 )) {
		std::clog << "Aber ich hab's doch geschafft!!1!" << std::endl;
	}
	std::cout << *this << std::endl;
}
Exemplo n.º 17
0
void deadlock() {

  K k(5);

  getK(k,1);

  Thread t1(setK,std::ref(k));
  Thread t2(getK,std::ref(k),5000);
  Thread t3(getK,std::ref(k),5000);

  getK(k,5000);

  t1.join();
  t2.join();
  t3.join();
  
  getK(k,1);

}
Exemplo n.º 18
0
/*
 * Class:     uk_ac_manchester_cs_factplusplus_FaCTPlusPlus
 * Method:    clearSaveLoadContext
 * Signature: (Ljava/lang/String;)Z
 */
JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_clearSaveLoadContext
  (JNIEnv * env, jobject obj, jstring str)
{
	TRACE_JNI("clearSaveLoadContext");
	TRACE_STR(env,str);
	JString* pContext = str ? new JString(env,str) : NULL;
	const char* context = pContext ? (*pContext)() : "";
	bool ret = getK(env,obj)->clearSaveLoadContext(context);
	delete pContext;
	return ret;
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QMainWindow::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: getBitPlane((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 1: getDisplayOption((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 2: getEdgeFilter((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 3: getImpulseNoise((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 4: getKLTQuality((*reinterpret_cast< double(*)>(_a[1]))); break;
        case 5: getKLTMinDist((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 6: getKLTWindowSize((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 7: getKLTNumLevels((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 8: getLogarithmConstant((*reinterpret_cast< double(*)>(_a[1]))); break;
        case 9: getOFAlgorithm((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 10: getPowerLawConstant((*reinterpret_cast< double(*)>(_a[1]))); break;
        case 11: getPowerLawGamma((*reinterpret_cast< double(*)>(_a[1]))); break;
        case 12: getR1((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 13: getK((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 14: getMinSize((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 15: getSharpeningAlgorithm((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 16: getSigma((*reinterpret_cast< double(*)>(_a[1]))); break;
        case 17: getSmoothingFilter((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 18: getSmoothingMask((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 19: exitApplication(); break;
        case 20: openImageDirectory(); break;
        case 21: toggleAddGaussianNoise(); break;
        case 22: toggleAddGammaNoise(); break;
        case 23: toggleAddImpulseNoise(); break;
        case 24: toggleBitPlaneSlicing(); break;
        case 25: toggleContrastStretching(); break;
        case 26: toggleFilter(); break;
        case 27: toggleFitToWindow(); break;
        case 28: toggleHistogramEqualization(); break;
        case 29: toggleLogarithm(); break;
        case 30: toggleNegative(); break;
        case 31: toggleOpticalFlow(); break;
        case 32: togglePowerLaw(); break;
        case 33: toggleSegmentation(); break;
        case 34: toggleSharpeningAlgorithm(); break;
        case 35: toggleSmoothing(); break;
        case 36: toggleSwapRedBlue(); break;
        case 37: updateImageNumber((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 38: timerEvent((*reinterpret_cast< QTimerEvent*(*)>(_a[1]))); break;
        case 39: on_pushButtonTrack_clicked(); break;
        default: ;
        }
        _id -= 40;
    }
    return _id;
}
Exemplo n.º 20
0
int main()
{
	FILE *fp;
	float a1, a2;
	double Aarray[] = { 1,1,-0.1,1 };
	double Harray[] = { 1,1,0,1 };
	Mat *X[100],*Qk,*Rk,*A,*H,*Z,*Pk,*K;
	int iter = 0;
	fopen_s(&fp, "measure.txt", "r");
	Z = mallocMat(2, 1, TYPE_FLOAT);
	X[0] = mallocMat(2, 1, TYPE_FLOAT);
	setVecVal(X[0], 0, 0.1);
	setVecVal(X[0], 1, 0.9);
	A = scanMat(2, 2, TYPE_FLOAT, Aarray);
	H = scanMat(2, 2, TYPE_FLOAT, Harray);
	Qk = identity(2, TYPE_FLOAT);
	Rk = identity(2, TYPE_FLOAT);
	Pk = identity(2, TYPE_FLOAT);
	K = zerosMat(2, 2, TYPE_FLOAT);
	if (!fp)
	{
		return -1;
	}
	while (!feof(fp))
	{
		fscanf_s(fp, "%f %f", &a1, &a2);
		if (iter == 0)
		{
			iter++;
			continue;
		}
		setVecVal(Z, 0, a1);
		setVecVal(Z, 1, a2);
		X[iter] = mallocMat(2, 1, TYPE_FLOAT);
		predictState(A, X[iter - 1], X[iter]);
		predictErrorVariance(A, Pk, Qk, Pk);
		if (iter % 5 == 0)
		{
			getK(Pk, H, Rk, K);
			stateCorrect(X[iter], K, Z, H, X[iter]);
			varianceCorrect(Pk, K, H, Pk);
		}
		iter++;
	}
	
	return 1;

}
Exemplo n.º 21
0
void 
PFEMElement2DBubble::getdK(const Vector& v, Matrix& dk) const
{
    dk.resize(6,6);
    getK(dk);
    dk *= -1.0/J;

    Vector kv = dk*v;

    dk.Zero();
    for(int a=0; a<6; a++) {
        for(int b=0; b<6; b++) {
            dk(a,b) = kv(a)*dJ(b);
        }
    }
}
Exemplo n.º 22
0
std::pair<size_t, Double> KMInput::getBest(size_t i) const {
	size_t const l(label(i));
	std::pair<size_t, Double> min(l, 0);

	if (sizeOfLabel(l) != 1) {
		Double const cst(-getDistance(i) * getCoeff<false>(i, l));
		for (size_t j(0); j < getK(); ++j) {
			if (j != l && feasible(i, j)) {
				Double delta(cst);
				delta += getDistance(i, j) * getCoeff<true>(i, j);
				delta *= obsWeight(i);
				if (delta < min.second) {
					min.first = j;
					min.second = delta;
				}
			}
		}
	}
	return min;
}
Exemplo n.º 23
0
/*
 * Class:     uk_ac_manchester_cs_factplusplus_FaCTPlusPlus
 * Method:    getDataSubType
 * Signature: (Ljava/lang/String;Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;)Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;
 */
JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataSubType
  (JNIEnv * env, jobject obj ATTR_UNUSED, jstring str ATTR_UNUSED, jobject type ATTR_UNUSED)
{
	TRACE_JNI("getDataSubType");
	TRACE_STR(env,str);
//	TJNICache* J = getJ(env,obj);
	JString name(env,str);
	Throw ( env, "FaCT++ Kernel: unsupported operation 'getDataSubType'" );
	jobject ret = (jobject)0;
#if 0
	try
	{
		ret = DataTypeExpression ( env, getK(env,obj)->getDataTypeCenter().
								   getDataType ( name(), getDataExpr(env,type) ) );
	}
	catch (const EFPPCantRegName&)
	{
		Throw ( env, "FaCT++ Kernel: Can not register new data type" );
	}
#endif
	return ret;
}
Exemplo n.º 24
0
int putstring(int code, int *pKwK) {

    Trie t = C_to_T(code); // DIEs if code invalid
    sawT(t);
    int K = getK(code);

    if (pref(code) == EMPTY) {

        putchar(K); 
        return K;
    }
    else {

        int finalK = putstring(pref(code), NULL);
        if (K != STANDBY) 
            putchar(K);

        else   // KwK; will put second K later
            *pKwK = 1; 

        return finalK;
    }
}
Exemplo n.º 25
0
void TextArt::EnvelopeWarp::morph(SkPath& bSkeleton, SkPathMeasure& bMeasure, SkPathCrossing& bCrossing,
								SkPath& tSkeleton, SkPathMeasure& tMeasure, SkPathCrossing& tCrossing,
								SkPath& glypthPath, SkPathMeasure& lineMeasure, SkMatrix& scaleMatrix,
								SkScalar xpos, SkScalar hBOffset, SkScalar hTOffset, SkPath& warpedPath)
{
	SkRect glypthBound;
	glypthBound = glypthPath.getBounds();

	SkScalar k1 = 1.0;

	if (!isSymmetric_)
	{	
		SkScalar hBOffsetTmp = 0.0;
		SkScalar hTOffsetTmp = 0.0;

		if (isTopBased_)
		{
			glypthBound.fTop = 0;
			glypthBound.fBottom = -boundsRect_.height();

			SkMatrix	compositeTMatrix(scaleMatrix);
			compositeTMatrix.postTranslate(xpos + hTOffset, 0);
			compositeTMatrix.postConcat(matrix_);

			if ( getK(glypthBound, bCrossing, tCrossing, tMeasure, compositeTMatrix, k1, hBOffsetTmp, hTOffsetTmp) )
			{
				k1 = 1/k1;

				hBOffset = hBOffsetTmp;
				hTOffset = xpos + hTOffset;
			}
		}
		else
		{
			glypthBound.fTop = -boundsRect_.height();
			glypthBound.fBottom = 0;

			SkMatrix	compositeBMatrix(scaleMatrix);
			compositeBMatrix.postTranslate(xpos + hBOffset, 0);
			compositeBMatrix.postConcat(matrix_);

			if ( getK(glypthBound, bCrossing, tCrossing, bMeasure, compositeBMatrix, k1, hBOffsetTmp, hTOffsetTmp) )
			{
				//use distance to Left on Top Skeleton for positioning Top glypthn
				hTOffset = hTOffsetTmp;
				hBOffset = xpos + hBOffset;
			}
		}
	}
	else
	{
		hBOffset = xpos + hBOffset;
		hTOffset = hBOffset;
	}
				
	SkMatrix	compositeBMatrix(scaleMatrix);
	compositeBMatrix.postTranslate(hBOffset, 0);
	compositeBMatrix.postConcat(matrix_);

	//warp Glypth by bottom line
	k1_ = isTopBased_ ? k1 : SkIntToScalar(1);
	isTop = false;
	SkPath bWarped;
	morphpath(&bWarped, glypthPath, bMeasure, compositeBMatrix);
	bWarped_.addPath(bWarped);

	if (!tSkeleton_.isEmpty())
	{
		SkMatrix	compositeTMatrix(scaleMatrix);
		compositeTMatrix.postTranslate(hTOffset, 0);
		compositeTMatrix.postConcat(matrix_);

		//warp Glypth by top line
		k1_ = !isTopBased_ ? k1 : SkIntToScalar(1);
		isTop = true;
		SkPath tWarped;
		morphpath(&tWarped, glypthPath, tMeasure, compositeTMatrix);
		tWarped_.addPath(tWarped);

		//convert Glypth to Path to allow weighting
		SkPath lineMorphed;
		morphpath(&lineMorphed, glypthPath, lineMeasure, scaleMatrix);

		weight(lineMorphed, tWarped, bWarped, &warpedPath);
	}
	else
		warpedPath.addPath(bWarped_);
}
Exemplo n.º 26
0
void CVRP::init(VRP V) {
	cout.setf(ios::fixed | ios::showpoint);
	cout.precision(2);
	std::cout.imbue(
			std::locale(std::cout.getloc(), new punct_facet<char, ','>));

	bool init1 = false;

	if (init1) {
		setNroCustomers(V.getBusStops().size() + 1);
		Customer depot(V.getCoorSchool().getX(), V.getCoorSchool().getY(),
				V.getCoorSchool().getCapacity());

		std::vector<Stop> a;
		a.insert(a.begin() + 0, V.getCoorSchool());
		std::vector<Stop> b = V.getBusStops();
		//Set AllCustomer but not depot
		std::vector<Customer> allCustNotDepot;
		for (size_t i = 0; i < V.getBusStops().size(); i++) {
			Stop stop = V.getBusStops().at(i);
			Customer customer(stop.getX(), stop.getY(), stop.getCapacity());
			allCustNotDepot.insert(allCustNotDepot.begin() + i, customer);
		}
		setAllCustNoDepot(allCustNotDepot);

		a.insert(a.end(), b.begin(), b.end());
		std::vector<Customer> allCustomers;
		for (size_t i = 0; i < a.size(); i++) {
			Stop stop = a.at(i);
			Customer customer(stop.getX(), stop.getY(), stop.getCapacity());
			allCustomers.insert(allCustomers.begin() + i, customer);
		}

		for (size_t i = 0; i < allCustomers.size(); i++) {
			Customer customer = allCustomers.at(i);
			cout << "(" << customer.getX() << ", " << customer.getY() << ", "
					<< customer.getDemand() << ")" << endl;
		}
		setDepot(depot);
		setAllCustomers(allCustomers);
		setK(V.getK());
		setC(V.getCk());
		setKmin(V.getKmin());
	} else {
		setNroCustomers(V.getBusAssigned().size() + 1);
		Customer depot(V.getCoorSchool().getX(), V.getCoorSchool().getY(),
				V.getCoorSchool().getCapacity());

		std::vector<Stop> a;
		a.insert(a.begin() + 0, V.getCoorSchool());
		std::vector<Stop> b = V.getBusAssigned();

		//Set AllCustomer but not depot
		std::vector<Customer> allCustNotDepot;
		for (size_t i = 0; i < V.getBusAssigned().size(); i++) {
			Stop stop = V.getBusAssigned().at(i);
			Customer customer(stop.getX(), stop.getY(), stop.getCapacity());
			allCustNotDepot.insert(allCustNotDepot.begin() + i, customer);
		}
		setAllCustNoDepot(allCustNotDepot);

		a.insert(a.end(), b.begin(), b.end());
		std::vector<Customer> allCustomers;
		for (size_t i = 0; i < a.size(); i++) {
			Stop stop = a.at(i);
			Customer customer(stop.getX(), stop.getY(), stop.getCapacity());
			allCustomers.insert(allCustomers.begin() + i, customer);
		}
		cout << "List of customers! the first customert is the depot." << endl;
		for (size_t i = 0; i < allCustomers.size(); i++) {
			Customer customer = allCustomers.at(i);
			cout << "(" << customer.getX() << ", " << customer.getY() << ", "
					<< customer.getDemand() << ")" << endl;
		}
		setDepot(depot);
		setAllCustomers(allCustomers);
		setK(V.getK());
		setC(V.getCk());
		setKmin(V.getKmin());
	}
	//Validation of the numbers of enters to the depot
	//Initialization of x
	//Initialization of d

	std::vector<Customer> allCustomers = getAllCustomers();
	int nro_customers = getNroCustomers();
	double** d_cvpr = new double*[nro_customers];
	double** s_cvpr = new double*[nro_customers];
	bool** x_cvpr = new bool*[nro_customers];

	for (int i = 0; i < nro_customers; i++) {
		d_cvpr[i] = new double[nro_customers];
		x_cvpr[i] = new bool[nro_customers];
		s_cvpr[i] = new double[nro_customers];
	}
	cout << "Save the distance in a d array of array" << endl;
	for (int i = 0; i < nro_customers; i++) {
		Customer customer = allCustomers.at(i);
		cout << "(" << customer.getX() << ", " << customer.getY() << ")"
				<< endl;
		for (int j = 0; j < nro_customers; j++) {
			Customer pivot = allCustomers.at(j);
			double distance = getDistanceIJ(customer, pivot);
			d_cvpr[i][j] = distance;
			x_cvpr[i][j] = false;
		}
	}
	cout << "Imprimir distance from i to j:" << endl;
	for (int i = 0; i < nro_customers; i++) {
		for (int j = 0; j < nro_customers; j++) {
			cout << d_cvpr[i][j] << " ";
		}
		cout << "\n";
	}

	cout << "Imprimir x from i to j." << endl;
	for (int i = 0; i < nro_customers; i++) {
		for (int j = 0; j < nro_customers; j++) {
			cout << x_cvpr[i][j] << " ";
		}
		cout << "\n";
	}

	setD(d_cvpr);

	//CREATE CONSTRUCTIVE - Saving Computation
	std::vector<Saving> savingList;
	int count1 = 0;
	int nro_buses = getK();
	std::vector<Customer> allCSaving = getAllCustNoDepot();

	for (int i = 0; i < nro_buses; i++) {
		Customer customer = allCSaving.at(i);
		for (int j = 0; j < nro_buses; j++) {
			if (i != j) {
				Customer pivot = allCSaving.at(j);
				double d1 = d_cvpr[i][0];
				double d2 = d_cvpr[0][j];
				double d3 = d_cvpr[i][j];

				s_cvpr[i][j] = d1 + d2 - d3;
				Saving save(customer, pivot, s_cvpr[i][j]);
				savingList.insert(savingList.begin() + count1, save);
				count1++;
			}
		}
	}

	//Ordering
	Saving temp;
	int flag = 1;
	for (size_t i = 1; i < savingList.size() && flag; i++) {
		flag = 0;
		for (size_t j = 0; j < savingList.size() - 1; j++) {
			if (savingList.at(j + 1).getSavingPeso()
					> savingList.at(j).getSavingPeso()) {
				temp = savingList.at(j);
				savingList.at(j) = savingList.at(j + 1);
				savingList.at(j + 1) = temp;
				flag = 1;
			}
		}
	}
	cout << "Saving List after ordered." << endl;
	int m = 0;
	for (size_t i = 0; i < savingList.size(); i++) {
		Saving save = savingList.at(i);
		Customer c1 = save.getSavingC1();
		Customer c2 = save.getSavingC2();
		double peso = save.getSavingPeso();
		cout << "i = (" << c1.getX() << ", " << c1.getY() << ") j = ("
				<< c2.getX() << ", " << c2.getY() << ") peso = " << peso
				<< endl;
	}
	cout << "Insertion." << endl;
	std::vector<std::vector<Customer> > routes;
	for (int i = 0; i < nro_buses; i++) {
		Customer customer = getAllCustNoDepot().at(i);
		//Create routes
		std::vector<Customer> route;
		route.insert(route.begin() + 0, getDepot());
		route.insert(route.begin() + 1, customer);
		route.insert(route.begin() + 2, getDepot());
		routes.insert(routes.begin() + m, route);
		m++;
		route.clear();

	}

	//Routes
	cout << "Print route for each new route:" << endl;
	for (size_t i = 0; i < routes.size(); i++) {
		std::vector<Customer> customers = routes.at(i);
		map.insert(pair<int, std::vector<Customer> >(i, customers));
		cout << "route #" << i << endl;
		for (size_t j = 0; j < customers.size(); j++) {
			Customer c = customers.at(j);
			cout << "(" << c.getX() << ", " << c.getY() << ") - ";
		}
		cout << "\n";
	}

	//Best feasible merge
	//1.- look for 0, j
	/*
	 * Step 2. Best feasible merge (Parallel version)
	 Starting from the top of the savings list, execute the following:
	 Given a saving sij, determine whether there exist two routes that can
	 feasibility be merged:
	 One starting with (0,j)
	 One ending with (i,0)
	 Combine these two routes by deleting (0,j) and (i,0) and introducing (i,j).
	 *
	 */
	cout << "=========================================================="
			<< endl;
	cout << "Starting saving List process" << endl;
	for (size_t i = 0; i < savingList.size(); i++) {
		bool firstCondition = false;
		unsigned int route_number = 0;
		bool secondCondition = false;
		unsigned int route_number2 = 0;

		Saving saving = savingList.at(i);
		Customer customer1 = saving.getSavingC1();
		Customer customer2 = saving.getSavingC2();
		Customer firstElement;
		Customer secondElement;
		cout << "=======Print route each time new SavingList is used========="
				<< endl;
		cout << "For saving customer1 = (" << customer1.getX() << ", "
				<< customer1.getY() << ")" << endl;
		cout << "For saving customer2 = (" << customer2.getX() << ", "
				<< customer2.getY() << ")" << endl;
		for (size_t i = 0; i < routes.size(); i++) {
			std::vector<Customer> customers = routes.at(i);
			cout << "route #" << i << endl;
			for (size_t j = 0; j < customers.size(); j++) {
				Customer c = customers.at(j);
				cout << "(" << c.getX() << ", " << c.getY() << ") - ";
			}
			cout << "\n";
		}

		//First Condition
		for (size_t j = 0; j < routes.size(); j++) {
			std::vector<Customer> customersRoutes = routes.at(j);

			bool c1IsFound = false;
			bool depotIsFound = false;
			unsigned int pivot = 0;

			for (size_t k = 0; k < customersRoutes.size(); k++) {

				Customer c = customersRoutes.at(k);
				if (compareCustomers(c, customer1)) {
					c1IsFound = true;
					pivot = k;
				}
				if (c1IsFound && (pivot + 1 == k)) {
					if (compareCustomers(getDepot(), c)) {
						depotIsFound = true;
						firstElement = customersRoutes.at(pivot);
						cout << "first Element = (" << firstElement.getX()
								<< ", " << firstElement.getY() << ")" << endl;
						route_number = j;
					}
				}
			}
			if (c1IsFound && depotIsFound) {
				map.insert(
						pair<int, std::vector<Customer> >(route_number,
								routes.at(route_number)));
				firstCondition = true;
			} else {
				cout << "Not" << endl;
			}

		}
		//Second condition
		for (size_t j = 0; j < routes.size(); j++) {
			std::vector<Customer> customersRoutes = routes.at(j);
			bool c2IsFound = false;
			bool depot2IsFound = false;
			unsigned int pivot2 = 0;

			for (size_t k = 0; k < customersRoutes.size(); k++) {
				Customer c = customersRoutes.at(k);

				if (compareCustomers(getDepot(), c)) {
					depot2IsFound = true;
					pivot2 = k;
				}
				if (depot2IsFound && (pivot2 + 1 == k)) {
					if (compareCustomers(c, customer2)) {
						c2IsFound = true;
						secondElement = customersRoutes.at(pivot2 + 1);
						cout << "second Element = (" << secondElement.getX()
								<< ", " << secondElement.getY() << ")" << endl;
						route_number2 = j;
					}
				}
			}

			if (depot2IsFound && c2IsFound) {
				map.insert(
						pair<int, std::vector<Customer> >(route_number2,
								routes.at(route_number2)));
				secondCondition = true;
			} else {
				cout << "Not2" << endl;
			}

		}
		if (firstCondition && secondCondition) {
			if (route_number != route_number2) {
				cout << "route 1 = " << route_number << endl;
				cout << "route 2 = " << route_number2 << endl;
				cout << "first Element = (" << firstElement.getX() << ", "
						<< firstElement.getY() << ")" << endl;
				cout << "second Element = (" << secondElement.getX() << ", "
						<< secondElement.getY() << ")" << endl;
				cout << "soy sensacional" << endl;
				std::vector<Customer> route1 = routes.at(route_number);
				for (size_t r = 0; r < route1.size(); r++) {
					Customer c = route1.at(r);
					cout << "(" << c.getX() << ", " << c.getY() << ") -";
				}
				cout << endl;
				//remote the depot
				for (size_t r = 0; r < route1.size(); r++) {
					Customer customer = route1.at(r);
					if (compareCustomers(customer, getDepot())) {
						route1.erase(route1.begin() + r);
					}
				}
				std::vector<Customer> route2 = routes.at(route_number2);
				for (size_t r = 0; r < route2.size(); r++) {
					Customer c = route2.at(r);
					cout << "(" << c.getX() << ", " << c.getY() << ") -";
				}
				cout << endl;
				for (size_t r = 0; r < route2.size(); r++) {
					Customer customer = route2.at(r);
					if (compareCustomers(customer, getDepot())) {
						route2.erase(route2.begin() + r);
					}
				}
				route1.insert(route1.end(), route2.begin(), route2.end());
				cout << "Nueva ruta generada por las rutas " << route_number
						<< " y " << route_number2 << endl;
				for (size_t l = 0; l < route1.size(); l++) {
					Customer customer = route1.at(l);
					cout << "(" << customer.getX() << ", " << customer.getY()
							<< ") - ";
				}
				routes.erase(routes.begin() + route_number);
				routes.erase(routes.begin() + route_number2 - 1);

				cout << "After remove the routes " << route_number << " and "
						<< route_number2 << endl;
				for (size_t i = 0; i < routes.size(); i++) {
					std::vector<Customer> customers = routes.at(i);
					cout << "route #" << i << endl;
					for (size_t j = 0; j < customers.size(); j++) {
						Customer c = customers.at(j);
						cout << "(" << c.getX() << ", " << c.getY() << ") - ";
					}
					cout << "\n";
				}

				routes.push_back(route1);
				cout << "after add the new  route merged." << endl;
				for (size_t i = 0; i < routes.size(); i++) {
					std::vector<Customer> customers = routes.at(i);
					cout << "route #" << i << endl;
					for (size_t j = 0; j < customers.size(); j++) {
						Customer c = customers.at(j);
						cout << "(" << c.getX() << ", " << c.getY() << ") - ";
					}
					cout << "\n";
				}
				cout << "routes.size() = " << routes.size() << endl;

			}
			cout << "=======end saving element from the list=========" << endl;
		} else {
			//Not to merge
		}
	}

	//Route Extension
	//Routes
	cout << "Print routes after the first merge process:" << endl;
	for (size_t i = 0; i < routes.size(); i++) {
		std::vector<Customer> customers = routes.at(i);
		cout << "route #" << i << endl;
		for (size_t j = 0; j < customers.size(); j++) {
			Customer c = customers.at(j);
			cout << "(" << c.getX() << ", " << c.getY() << ") - ";
		}
		cout << "\n";
	}

}
Exemplo n.º 27
0
ompl::base::PlannerStatus ompl::geometric::LazyLBTRRT::solve(const base::PlannerTerminationCondition &ptc)
{
    checkValidity();
    // update goal and check validity
    base::Goal *goal = pdef_->getGoal().get();
    auto *goal_s = dynamic_cast<base::GoalSampleableRegion *>(goal);

    if (goal == nullptr)
    {
        OMPL_ERROR("%s: Goal undefined", getName().c_str());
        return base::PlannerStatus::INVALID_GOAL;
    }

    while (const base::State *st = pis_.nextStart())
    {
        startMotion_ = createMotion(goal_s, st);
        break;
    }

    if (nn_->size() == 0)
    {
        OMPL_ERROR("%s: There are no valid initial states!", getName().c_str());
        return base::PlannerStatus::INVALID_START;
    }

    if (!sampler_)
        sampler_ = si_->allocStateSampler();

    OMPL_INFORM("%s: Starting planning with %u states already in datastructure", getName().c_str(), nn_->size());

    bool solved = false;

    auto *rmotion = new Motion(si_);
    base::State *xstate = si_->allocState();

    goalMotion_ = createGoalMotion(goal_s);

    CostEstimatorLb costEstimatorLb(goal, idToMotionMap_);
    LPAstarLb_ = new LPAstarLb(startMotion_->id_, goalMotion_->id_, graphLb_, costEstimatorLb);  // rooted at source
    CostEstimatorApx costEstimatorApx(this);
    LPAstarApx_ = new LPAstarApx(goalMotion_->id_, startMotion_->id_, graphApx_, costEstimatorApx);  // rooted at target
    double approxdif = std::numeric_limits<double>::infinity();
    // e+e/d.  K-nearest RRT*
    double k_rrg = boost::math::constants::e<double>() +
                   boost::math::constants::e<double>() / (double)si_->getStateSpace()->getDimension();

    ////////////////////////////////////////////
    // step (1) - RRT
    ////////////////////////////////////////////
    bestCost_ = std::numeric_limits<double>::infinity();
    rrt(ptc, goal_s, xstate, rmotion, approxdif);
    if (!ptc())
    {
        solved = true;

        ////////////////////////////////////////////
        // step (2) - Lazy construction of G_lb
        ////////////////////////////////////////////
        idToMotionMap_.push_back(goalMotion_);
        int k = getK(idToMotionMap_.size(), k_rrg);
        std::vector<Motion *> nnVec;
        nnVec.reserve(k);
        BOOST_FOREACH (Motion *motion, idToMotionMap_)
        {
            nn_->nearestK(motion, k, nnVec);
            BOOST_FOREACH (Motion *neighbor, nnVec)
                if (neighbor->id_ != motion->id_ && !edgeExistsLb(motion, neighbor))
                    addEdgeLb(motion, neighbor, distanceFunction(motion, neighbor));
        }
Exemplo n.º 28
0
 void Well::setRefDepthFromCompletions() const {
     size_t timeStep = m_creationTimeStep;
     while (true) {
         auto completions = getCompletions( timeStep );
         if (completions->size() > 0) {
             auto firstCompletion = completions->get(0);
             double depth = m_grid->getCellDepth( firstCompletion->getI() , firstCompletion->getJ() , firstCompletion->getK());
             m_refDepth.setValue( depth );
             break;
         } else {
             timeStep++;
             if (timeStep >= m_timeMap->size())
                 throw std::invalid_argument("No completions defined for well: " + name() + " can not infer reference depth");
         }
     }
 }
Exemplo n.º 29
0
int main(void)
{
    Key_val *k = NULL;
    Vec *v = NULL;
    char *s;
    char ts[] = "one";
    int i = 0;

    k = keyAdd(k, ts, "1");
    k = keyAdd(k, "two", "2");
    k = keyAdd(k, "three", "3");
    k = keyAdd(k, "four", "4");
    k = keyAdd(k, "five", "5");
    v = vecAdd(v, "ONE", k);
    //This doesn_t have to be last but k
    // must have a value. So it can_t go first.

	// You need to reset k
	k = NULL;
    k = keyAdd(k, "twenty one", "21");
    k = keyAdd(k, "twenty two", "22");
    k = keyAdd(k, "twenty three", "23");
    k = keyAdd(k, "twenty four", "24");
    v = vecAdd(v, "TWO", k);

    prV(v);

    printf("\n\n ................ \n\n");

    //Example returning key_val from the string found in vector v
	printf("Below pr(findK(v,\"ONE\"))\n");
    pr(findK(v, "ONE"));

    printf("Below pr(findK(v,\"TWO\"))\n");
    pr(findK(v, "TWO"));



    printf("\n");
    s = (char *)malloc(sizeof(char) * 80);
    strcpy(s, "twenty two");
    fprintf(stderr, "find(c,%s)=%s\n", s, find(k, s));
    modify(k,s,"New twenty two");

    k = findK(v, "ONE");
    strcpy(s, "one");
    fprintf(stderr, "find(c,%s)=%s\n", s, find(k, s));
    free(s);

    printf("\n\nExample use in a for loop.\n\n");
    for (i = 0; i < pvLength(v); ++i) {
	pr(getK(v, i));
	printf("......\n");

    }

    myfreeV(v);
    //Note myfreeV calls this
	// myfree(k);

    return 0;
}
Exemplo n.º 30
0
void KMcenters::print(			// print centers
    bool fancy) {
    kmPrintPts("Center_Points", ctrs, getK(), fancy);
}