ViewerGL::Implementation::WipePolygonEnum ViewerGL::Implementation::getWipePolygon(const RectD & texRectClipped, QPolygonF & polygonPoints, bool rightPlane) const { ///Compute a second point on the plane separator line ///we don't really care how far it is from the center point, it just has to be on the line QPointF firstPoint, secondPoint; QPointF center; double angle; { QMutexLocker l(&wipeControlsMutex); center = wipeCenter; angle = wipeAngle; } ///extrapolate the line to the maximum size of the RoD so we're sure the line ///intersection algorithm works double maxSize = std::max(texRectClipped.x2 - texRectClipped.x1, texRectClipped.y2 - texRectClipped.y1) * 10000.; double xmax, ymax; xmax = std::cos(angle + M_PI_2) * maxSize; ymax = std::sin(angle + M_PI_2) * maxSize; firstPoint.setX(center.x() - xmax); firstPoint.setY(center.y() - ymax); secondPoint.setX(center.x() + xmax); secondPoint.setY(center.y() + ymax); QLineF inter(firstPoint, secondPoint); QLineF::IntersectType intersectionTypes[4]; QPointF intersections[4]; QLineF topEdge(texRectClipped.x1, texRectClipped.y2, texRectClipped.x2, texRectClipped.y2); QLineF rightEdge(texRectClipped.x2, texRectClipped.y2, texRectClipped.x2, texRectClipped.y1); QLineF bottomEdge(texRectClipped.x2, texRectClipped.y1, texRectClipped.x1, texRectClipped.y1); QLineF leftEdge(texRectClipped.x1, texRectClipped.y1, texRectClipped.x1, texRectClipped.y2); bool crossingTop = false, crossingRight = false, crossingLeft = false, crossingBtm = false; int validIntersectionsIndex[4]; validIntersectionsIndex[0] = validIntersectionsIndex[1] = -1; int numIntersec = 0; intersectionTypes[0] = inter.intersect(topEdge, &intersections[0]); if (intersectionTypes[0] == QLineF::BoundedIntersection) { validIntersectionsIndex[numIntersec] = 0; crossingTop = true; ++numIntersec; } intersectionTypes[1] = inter.intersect(rightEdge, &intersections[1]); if (intersectionTypes[1] == QLineF::BoundedIntersection) { validIntersectionsIndex[numIntersec] = 1; crossingRight = true; ++numIntersec; } intersectionTypes[2] = inter.intersect(bottomEdge, &intersections[2]); if (intersectionTypes[2] == QLineF::BoundedIntersection) { validIntersectionsIndex[numIntersec] = 2; crossingBtm = true; ++numIntersec; } intersectionTypes[3] = inter.intersect(leftEdge, &intersections[3]); if (intersectionTypes[3] == QLineF::BoundedIntersection) { validIntersectionsIndex[numIntersec] = 3; crossingLeft = true; ++numIntersec; } if ( (numIntersec != 0) && (numIntersec != 2) ) { ///Don't bother drawing the polygon, it is most certainly not visible in this case return ViewerGL::Implementation::eWipePolygonEmpty; } ///determine the orientation of the planes double crossProd = ( secondPoint.x() - center.x() ) * ( texRectClipped.y1 - center.y() ) - ( secondPoint.y() - center.y() ) * ( texRectClipped.x1 - center.x() ); if (numIntersec == 0) { ///the bottom left corner is on the left plane if ( (crossProd > 0) && ( (center.x() >= texRectClipped.x2) || (center.y() >= texRectClipped.y2) ) ) { ///the plane is invisible because the wipe handle is below or on the left of the texRectClipped return rightPlane ? ViewerGL::Implementation::eWipePolygonEmpty : ViewerGL::Implementation::eWipePolygonFull; } ///otherwise we draw the entire texture as usual return rightPlane ? ViewerGL::Implementation::eWipePolygonFull : ViewerGL::Implementation::eWipePolygonEmpty; } else { ///we have 2 intersects assert(validIntersectionsIndex[0] != -1 && validIntersectionsIndex[1] != -1); bool isBottomLeftOnLeftPlane = crossProd > 0; ///there are 6 cases if (crossingBtm && crossingLeft) { if ( (isBottomLeftOnLeftPlane && rightPlane) || (!isBottomLeftOnLeftPlane && !rightPlane) ) { //btm intersect is the first polygonPoints.insert(0, intersections[validIntersectionsIndex[0]]); polygonPoints.insert(1, intersections[validIntersectionsIndex[1]]); polygonPoints.insert( 2, QPointF(texRectClipped.x1, texRectClipped.y2) ); polygonPoints.insert( 3, QPointF(texRectClipped.x2, texRectClipped.y2) ); polygonPoints.insert( 4, QPointF(texRectClipped.x2, texRectClipped.y1) ); polygonPoints.insert(5, intersections[validIntersectionsIndex[0]]); } else { polygonPoints.insert(0, intersections[validIntersectionsIndex[0]]); polygonPoints.insert(1, intersections[validIntersectionsIndex[1]]); polygonPoints.insert( 2, QPointF(texRectClipped.x1, texRectClipped.y1) ); polygonPoints.insert(3, intersections[validIntersectionsIndex[0]]); } } else if (crossingBtm && crossingTop) { if ( (isBottomLeftOnLeftPlane && rightPlane) || (!isBottomLeftOnLeftPlane && !rightPlane) ) { ///btm intersect is the second polygonPoints.insert(0, intersections[validIntersectionsIndex[1]]); polygonPoints.insert(1, intersections[validIntersectionsIndex[0]]); polygonPoints.insert( 2, QPointF(texRectClipped.x2, texRectClipped.y2) ); polygonPoints.insert( 3, QPointF(texRectClipped.x2, texRectClipped.y1) ); polygonPoints.insert(4, intersections[validIntersectionsIndex[1]]); } else { polygonPoints.insert(0, intersections[validIntersectionsIndex[1]]); polygonPoints.insert(1, intersections[validIntersectionsIndex[0]]); polygonPoints.insert( 2, QPointF(texRectClipped.x1, texRectClipped.y2) ); polygonPoints.insert( 3, QPointF(texRectClipped.x1, texRectClipped.y1) ); polygonPoints.insert(4, intersections[validIntersectionsIndex[1]]); } } else if (crossingBtm && crossingRight) { if ( (isBottomLeftOnLeftPlane && rightPlane) || (!isBottomLeftOnLeftPlane && !rightPlane) ) { ///btm intersect is the second polygonPoints.insert(0, intersections[validIntersectionsIndex[1]]); polygonPoints.insert(1, intersections[validIntersectionsIndex[0]]); polygonPoints.insert( 2, QPointF(texRectClipped.x2, texRectClipped.y1) ); polygonPoints.insert(3, intersections[validIntersectionsIndex[1]]); } else { polygonPoints.insert(0, intersections[validIntersectionsIndex[1]]); polygonPoints.insert(1, intersections[validIntersectionsIndex[0]]); polygonPoints.insert( 2, QPointF(texRectClipped.x2, texRectClipped.y2) ); polygonPoints.insert( 3, QPointF(texRectClipped.x1, texRectClipped.y2) ); polygonPoints.insert( 4, QPointF(texRectClipped.x1, texRectClipped.y1) ); polygonPoints.insert(5, intersections[validIntersectionsIndex[1]]); } } else if (crossingLeft && crossingTop) { if ( (isBottomLeftOnLeftPlane && rightPlane) || (!isBottomLeftOnLeftPlane && !rightPlane) ) { ///left intersect is the second polygonPoints.insert(0, intersections[validIntersectionsIndex[1]]); polygonPoints.insert(1, intersections[validIntersectionsIndex[0]]); polygonPoints.insert( 2, QPointF(texRectClipped.x1, texRectClipped.y2) ); polygonPoints.insert(3, intersections[validIntersectionsIndex[1]]); } else { polygonPoints.insert(0, intersections[validIntersectionsIndex[1]]); polygonPoints.insert(1, intersections[validIntersectionsIndex[0]]); polygonPoints.insert( 2, QPointF(texRectClipped.x2, texRectClipped.y2) ); polygonPoints.insert( 3, QPointF(texRectClipped.x2, texRectClipped.y1) ); polygonPoints.insert( 4, QPointF(texRectClipped.x1, texRectClipped.y1) ); polygonPoints.insert(5, intersections[validIntersectionsIndex[1]]); } } else if (crossingLeft && crossingRight) { if ( (isBottomLeftOnLeftPlane && rightPlane) || (!isBottomLeftOnLeftPlane && !rightPlane) ) { ///left intersect is the second polygonPoints.insert(0, intersections[validIntersectionsIndex[1]]); polygonPoints.insert( 1, QPointF(texRectClipped.x1, texRectClipped.y2) ); polygonPoints.insert( 2, QPointF(texRectClipped.x2, texRectClipped.y2) ); polygonPoints.insert(3, intersections[validIntersectionsIndex[0]]); polygonPoints.insert(4, intersections[validIntersectionsIndex[1]]); } else { polygonPoints.insert(0, intersections[validIntersectionsIndex[1]]); polygonPoints.insert(1, intersections[validIntersectionsIndex[0]]); polygonPoints.insert( 2, QPointF(texRectClipped.x2, texRectClipped.y1) ); polygonPoints.insert( 3, QPointF(texRectClipped.x1, texRectClipped.y1) ); polygonPoints.insert(4, intersections[validIntersectionsIndex[1]]); } } else if (crossingTop && crossingRight) { if ( (isBottomLeftOnLeftPlane && rightPlane) || (!isBottomLeftOnLeftPlane && !rightPlane) ) { ///right is second polygonPoints.insert(0, intersections[validIntersectionsIndex[0]]); polygonPoints.insert( 1, QPointF(texRectClipped.x2, texRectClipped.y2) ); polygonPoints.insert(2, intersections[validIntersectionsIndex[1]]); polygonPoints.insert(3, intersections[validIntersectionsIndex[0]]); } else { polygonPoints.insert(0, intersections[validIntersectionsIndex[0]]); polygonPoints.insert(1, intersections[validIntersectionsIndex[1]]); polygonPoints.insert( 2, QPointF(texRectClipped.x2, texRectClipped.y1) ); polygonPoints.insert( 3, QPointF(texRectClipped.x1, texRectClipped.y1) ); polygonPoints.insert( 4, QPointF(texRectClipped.x1, texRectClipped.y2) ); polygonPoints.insert(5, intersections[validIntersectionsIndex[0]]); } } else { assert(false); } } return ViewerGL::Implementation::eWipePolygonPartial; } // getWipePolygon
Matrix<double> gaussseidel(Matrix<double> A, Matrix<double> b, Matrix<double> xold, double tol, int maxiter, char check='n') { //cout << "\ngaussseidel: Input LHS matrix is " << A.rows() << " x " << A.cols() << endl; if(A.rows() != b.rows()) { cout << "! gaussseidel: Invalid dimensions of A and b!\n"; return b; } if(xold.rows() != b.rows()) { cout << "! gaussseidel: Invalid dimensions on xold !\n"; return b; } int N = A.rows(); if(check == 'y') { for(int i = 0; i < A.rows(); i++) { double sum = 0; for(int j = 0; j < A.cols(); j++) { if(i != j) sum += dabs(A(i,j)); } if(dabs(A(i,i)) <= sum) cout << "* gaussseidel: LHS Matrix is NOT strictly diagonally dominant in row " << i << "!!\n"; } } Matrix<double> x(b.rows(),1); Matrix<double> M(N,N,ROWMAJOR); // diagonal matrix M.zeros(); //populate diagonal matrix M for(int i = 0; i < N; i++) M(i,i) = A(i,i); A = A - M; // diagonal entries of A are now zero //invert M for(int i = 0; i < N; i++) M(i,i) = 1.0/M(i,i); //x.zeros(); //cout << "gaussseidel: Initial error = " << (xold-x).dabsmax() << endl; x = xold; int c = 0; double initres; bool first = true; Matrix<double> Axold(N,1); Matrix<double> inter(N,1); Matrix<double> diff(N,1); // diff = x - xold double error = 1.0; do { xold = x; Axold.zeros(); for(int i = 0; i < N; i++) { for(int k = 0; k < i; k++) Axold(i,0) += A(i,k)*x(k,0); for(int k = i; k < N; k++) Axold(i,0) += A(i,k)*xold(k,0); inter(i,0) = b(i,0) - Axold(i,0); x(i,0) = M(i,i) * inter(i,0); } // NOTE: The above results in FORWARD Gauss-Seidel c++; if(c > maxiter) { cout << "gaussseidel: Max iterations exceeded!\n"; break; } for(int i = 0; i < N; i++) diff(i,0) = x(i,0) - xold(i,0); error = dabs(diff(0,0)); for(int i = 1; i < N; i++) if(dabs(diff(i,0)) > error) error = dabs(diff(i,0)); //cout << "gaussseidel: error = " << error << endl; if(first == true) { initres = error; //cout << "gaussseidel: Initial residue = " << initres << endl; first = false; } //if(c%20 == 0) cout << "gaussseidel(): Step " << c << ", Relative error = " << error/initres << endl; } while(error/initres >= tol); //cout << "gaussseidel: No. of iterations = " << c << endl; return x; }
void FEdgeXDetector::ProcessRidgeFace(WXFace *iFace) { // RIDGE LAYER // Compute the RidgeFunction, that is the derivative of the ppal curvature along e1 at each vertex of the face WVertex *v; Vec3r v1v2; real t; vector<WXFaceLayer*> SmoothLayers; WXFaceLayer *faceLayer; Face_Curvature_Info *layer_info; real K1_a(0), K1_b(0); Vec3r Inter_a, Inter_b; // find the ridge layer of the face iFace->retrieveSmoothLayers(Nature::RIDGE, SmoothLayers); if ( SmoothLayers.size()!=1 ) return; faceLayer = SmoothLayers[0]; // retrieve the curvature info of this layer layer_info = (Face_Curvature_Info *)faceLayer->userdata; int numVertices = iFace->numberOfVertices(); for (int i = 0; i < numVertices; i++) { v = iFace->GetVertex(i); // vec_curvature_info[i] contains the curvature info of this vertex Vec3r e2 = layer_info->vec_curvature_info[i]->K2*layer_info->vec_curvature_info[i]->e2; Vec3r e1 = layer_info->vec_curvature_info[i]->K1*layer_info->vec_curvature_info[i]->e1; e2.normalize(); WVertex::face_iterator fit = v->faces_begin(); WVertex::face_iterator fitend = v->faces_end(); for (; fit != fitend; ++fit) { WXFace *wxf = dynamic_cast<WXFace*>(*fit); WOEdge *oppositeEdge; if (!(wxf->getOppositeEdge(v, oppositeEdge))) continue; v1v2 = oppositeEdge->GetbVertex()->GetVertex() - oppositeEdge->GetaVertex()->GetVertex(); GeomUtils::intersection_test res; res = GeomUtils::intersectRayPlane(oppositeEdge->GetaVertex()->GetVertex(), v1v2, e2, -(v->GetVertex()*e2), t, 1.0e-06); if ((res == GeomUtils::DO_INTERSECT) && (t >= 0.0) && (t <= 1.0)) { vector<WXFaceLayer*> second_ridge_layer; wxf->retrieveSmoothLayers(Nature::RIDGE, second_ridge_layer); if (second_ridge_layer.size() != 1) continue; Face_Curvature_Info *second_layer_info = (Face_Curvature_Info*)second_ridge_layer[0]->userdata; unsigned index1 = wxf->GetIndex(oppositeEdge->GetaVertex()); unsigned index2 = wxf->GetIndex(oppositeEdge->GetbVertex()); real K1_1 = second_layer_info->vec_curvature_info[index1]->K1; real K1_2 = second_layer_info->vec_curvature_info[index2]->K1; real K1 = (1.0 - t) * K1_1 + t * K1_2; Vec3r inter((1.0 - t) * oppositeEdge->GetaVertex()->GetVertex() + t * oppositeEdge->GetbVertex()->GetVertex()); Vec3r vtmp(inter - v->GetVertex()); // is it K1_a or K1_b ? if (vtmp * e1 > 0) { K1_b = K1; Inter_b = inter; } else { K1_a = K1; Inter_a = inter; } } } // Once we have K1 along the ppal direction compute the derivative : K1b - K1a put it in DotP //real d = fabs(K1_b) - fabs(K1_a); real d = 0; real threshold = _meanK1 + (_maxK1 - _meanK1) / 7.0; //real threshold = _meanK1; //if ((fabs(K1_b) > threshold) || ((fabs(K1_a) > threshold))) d = (K1_b) - (K1_a) / (Inter_b - Inter_a).norm(); faceLayer->PushDotP(d); //faceLayer->PushDotP(layer_info->vec_curvature_info[i]->K1); } // Make the values relevant by checking whether all principal directions have the "same" direction: Vec3r e0((layer_info->vec_curvature_info[0]->K1 * layer_info->vec_curvature_info[0]->e1)); e0.normalize(); Vec3r e1((layer_info->vec_curvature_info[1]->K1 * layer_info->vec_curvature_info[1]->e1)); e1.normalize(); Vec3r e2((layer_info->vec_curvature_info[2]->K1 * layer_info->vec_curvature_info[2]->e1)); e2.normalize(); if (e0 * e1 < 0) // invert dotP[1] faceLayer->ReplaceDotP(1, -faceLayer->dotP(1)); if (e0 * e2 < 0) // invert dotP[2] faceLayer->ReplaceDotP(2, -faceLayer->dotP(2)); #if 0 // remove the weakest values; real minDiff = (_maxK1 - _minK1) / 10.0; real minDiff = _meanK1; if ((faceLayer->dotP(0) < minDiff) && (faceLayer->dotP(1) < minDiff) && (faceLayer->dotP(2) < minDiff)) { faceLayer->ReplaceDotP(0, 0); faceLayer->ReplaceDotP(1, 0); faceLayer->ReplaceDotP(2, 0); } #endif }
void main() { NODE *s1,*s2; int ch; s1=NULL; s2=NULL; while(1) { clrscr(); printf("Enter choice:\n"); printf(" 1.Append element at end\n 2.Concatinate two lists\n"); printf(" 3.Free all nodes in a list\n 4.Reverse a list\n"); printf(" 5.Delete last element\n 6.Delete nth element\n"); printf(" 7.Combine two ordered list into single ordered list\n"); printf(" 8.Find union of two lists\n 9.Find intersection of two lists\n"); printf("10.Insert after nth element\n11.Delete every second element\n"); printf("12.Place elements in order\n13.Return sum of data\n"); printf("14.Return number of elements\n15.Make second copy of list\n"); printf("16.Move node forward to n positions\n17.Exit\n"); scanf("%d",&ch); clrscr(); if(ch>0&&ch<=16) s1=create(s1); disp(s1); switch(ch) { case 1:s1=append(s1);break; case 2:s2=create(s2);disp(s2);s1=concat(s1,s2);break; case 3:s1=fr(s1); printf("List freed\n"); disp(s1); break; case 4:s1=rev(s1);break; case 5:s1=dellast(s1);break; case 6:s1=deln(s1);break; case 7:s2=create(s2);disp(s2);s1=comb(s1,s2);break; case 8:s2=create(s2);disp(s2);s1=uni(s1,s2);break; case 9:s2=create(s2);disp(s2);s1=inter(s1,s2);break; case 10:s1=insertn(s1);break; case 11:s1=del2(s1);break; case 12:s1=sort(s1);break; case 13:printf("Sum of elements=%d",sum(s1));break; case 14:printf("Number of elements=%d",elements(s1));break; case 15: s2=copy(s1); printf("Second list:\n"); disp(s2); break; case 16:s1=forward(s1);break; case 17:exit(0);break; default:printf("Wrong choice.Enter again");break; } if(ch!=3&&ch!=13&&ch!=14&&ch!=15&&ch>0&&ch<=16) { printf("\nResult:"); disp(s1); } s1=fr(s1); s2=fr(s2); getch(); } }
void ProjectionRenderer::draw(void *_device) { qDebug() << "[render/proj] start!"; // preparing data for interpolation const int n = config->getDimSizeX(); const double* data = reinterpret_cast<const double*>(config->getData()); vector<double> data_x, data_y; double max_value = data[0], min_value = data[0]; const double x_scaled = (n - 1) / 100.0 * parameters->x_scale->value(); for(int i = 0; i < n; i++) { double x = i * (parameters->x_scale->value() / 100.0); data_x.push_back(x); data_y.push_back(data[i] * parameters->y_scale->value()); max_value = max(max_value, data[i]); min_value = min(min_value, data[i]); } if(config->getDimSizeX() == 0) { buffer->prepare(); return ; } // interpolation Interpolator inter(data_x, data_y); const int nn = int(x_scaled); int x_scrool_width = static_cast<int>(n * parameters->x_scale->value() / 100.0 + (1.0 - EPS)); qDebug() << "[render/proj] xwidth" << x_scrool_width << "buf->width" << buffer->width(); if(buffer->width() - 50 < x_scrool_width) buffer->setXScroll(divup<int>(x_scrool_width - buffer->width() - 50, XSCROLL_SIZE)); else buffer->setXScroll(GraphicBuffer::SCROLL_DISABLE); int y_scrool_width = static_cast<int>((min_value + max_value) * parameters->y_scale->value() + (1.0 - EPS)); if(buffer->height() - FRAME_SIZE < y_scrool_width || true) buffer->setYScroll(divup<int>(y_scrool_width - buffer->height() - 50, YSCROLL_SIZE)); else buffer->setYScroll(GraphicBuffer::SCROLL_DISABLE); // TODO more nice view buffer->prepare(); QPainter *painter = buffer->getRawPaintDevice(); /* * Draw grid */ const int shift_scrool_x = (parameters->x_scale->value() == parameters->x_scale->maximum() && false ? static_cast<int>(XSCROLL_SIZE * buffer->getXScroll() * 100.0 / parameters->x_scale->value() + .5) // TODO: fix : static_cast<int>(XSCROLL_SIZE * buffer->getXScroll() * 100.0 / parameters->x_scale->value() + .5) ); const int shift_x = FRAME_SIZE - buffer->getXScroll() * 100; const int value_invert = buffer->height() - FRAME_SIZE; QPicture digits_picuture; QPainter digits_painter(&digits_picuture); // y-axis digits_painter.fillRect(0, 0, FRAME_SIZE, buffer->height(), Qt::white); for(int i = 0; i <= buffer->height() / parameters->y_scale->value(); i++) { int x = FRAME_SIZE; int y = value_invert - i * parameters->y_scale->value(); // primary dark grid painter->setPen(QColor(0xAA, 0xAA, 0xAA)); painter->drawLine(x, y, buffer->width(), y); digits_painter.setPen(Qt::black); digits_painter.drawText(x - FRAME_SIZE * 4 / 5, y, toStdString<int>(i).c_str()); // secondary light grid const int cnt = parameters->y_scale->value() / 25; const int secondary_height = parameters->y_scale->value() / cnt; painter->setPen(QColor(0xDD, 0xDD, 0xDD)); digits_painter.setPen(QColor(0x55, 0x55, 0x55)); for(int j = 1; j < cnt; j++) { y -= secondary_height; painter->drawLine(x, y, buffer->width(), y); digits_painter.drawText(x - FRAME_SIZE * 4 / 5, y, toStdString<double>(i + 1.0 / (cnt + 1) * (j)).substr(0, 4).c_str()); } } // x-axis // TODO: draw with step 100 digits_painter.begin(&digits_picuture); digits_painter.fillRect(0, buffer->height(), buffer->width(), value_invert, Qt::white); for(int i = 0; i <= buffer->width() / parameters->x_scale->value(); i++) { int x = FRAME_SIZE + i * parameters->x_scale->value(); int y = value_invert; // primary dark grid painter->setPen(QColor(0xAA, 0xAA, 0xAA)); painter->drawLine(x, y, x, 0); digits_painter.setPen(Qt::black); digits_painter.drawText(x, y + FRAME_SIZE / 2, toStdString<int>(i * 100 + buffer->getXScroll() * XSCROLL_SIZE * 100.0 / parameters->x_scale->value()).c_str()); } // TODO: draw numbers digits_painter.end(); /* * Draw interpolation values */ if(parameters->chk_interpolation->isChecked()) { painter->setPen(QColor(0xCC, 0x00, 0x00)); int last_value = -1; for(int x = 0; x < nn; x++) { int value = int(inter.Eval(x) + .5); value = value_invert - value; if(last_value != -1) painter->drawLine(x - 1 + shift_x, last_value, x + shift_x, value); else painter->drawPoint(x + shift_x, value); last_value = value; } } /* * Draw given value */ if(parameters->chk_segments->isChecked()) { painter->setPen(QColor(0x00, 0xCC, 0x00)); int px = data_x[0]; int py = data_y[0]; for(int ii = 1; ii < n / 10; ii++) { int i = ii * 10; painter->drawLine(px + shift_x, value_invert - py, data_x[i] + shift_x, value_invert - data_y[i]); px = data_x[i]; py = data_y[i]; } } painter->drawPicture(0, 0, digits_picuture); }
// Cette routine est la racine de l'arbre de recherche. Elle doit etre separee // car plusieurs chose ne sont pas utile a la racine. Comme le null move et // le lookup dans la table de transposition. int SearchRacine(int depth, int wtm, int alpha, int beta) { register int Valeur, AlphaInitiale, extension = 0; AlphaInitiale = alpha; // Calculer le temps restant. if ( (iNodes & 0xFF ) == 0xFF ) { if ( TimeCheck() ) { timeabort = true; } // Verifier si il y a quelque chose dans le tampon // d'entree. if ( inter() ) { interrupted = true; } } // Maintenant, evaluer chaque coup. while( NextMoveRacine( cb, wtm ) && !g_bAbort ) { if ( g_bModeAnalyse ) { printf( "stat01: %d %d %d %d %d\n", (TempsCenti()-timestamp), iNodes, iProfondeurIteration, cb.MoveList[1].nbmove - cb.MoveList[1].currmove-1, cb.MoveList[1].nbmove ); } else if ( !xboard ) { printf( "\r [%d] (%2d/%d)", iProfondeurIteration, cb.MoveList[1].currmove+1, cb.MoveList[1].nbmove ); } // On execute le coup. iNodes++; MakeMove(1, cb.MoveList[1].CurrentMove(), wtm); // Mettre le coup dans le chemin actuel. cb.CurrentPath.moves[1] = cb.MoveList[1].moves[cb.MoveList[1].currmove]; // Si le coup met en echec etendre la recherche d'une profondeur // pour qu'il puisse en sortir. if ( Check(!wtm) ) { cb.inCheck[2] = true; extension = 1; cb.RaisonExtension[1] = EXTENSION_ECHEC; } else { extension = 0; cb.inCheck[2] = false; cb.RaisonExtension[1] = PAS_EXTENSION; } // On l'explore. // Si c'est la variation principale, Fenetre normale, sinon, // fenetre est n et n+1. if ( cb.MoveList[1].currmove == 0 ) { Valeur = -ABSearch(depth-1+extension, 2, !wtm, -beta, -alpha, true); } else { Valeur = -ABSearch(depth-1+extension, 2, !wtm, -alpha-1, -alpha, true); if ( Valeur > alpha && Valeur < beta ) { Valeur = -ABSearch(depth-1+extension, 2, !wtm, -beta, -alpha, true); } } // La nouvelle valeur. cb.CurrentPath.moves[1].Score = Valeur; cb.MoveList[1].moves[cb.MoveList[1].currmove].Score = Valeur; // On defait le coup. UnmakeMove(1, cb.MoveList[1].CurrentMove(), wtm); if (interrupted) return Valeur; #ifdef DEBUG Consistence( cb, cb.MoveList[1].CurrentMove() ); #endif // Est-elle meileur que notre valeur actuelle? if ( !timeabort || g_bModeAnalyse ) { if ( Valeur > alpha ) { pv[1][1] = cb.CurrentPath.moves[1]; pv_length[1] = pv_length[2]; memcpy( &pv[1][2], &pv[2][2], sizeof( TMove )*(pv_length[1]-1)); AffichePV(iProfondeurIteration); if ( Valeur >= beta ) { return Valeur; } alpha = Valeur; } else if ( cb.MoveList[1].currmove == 0 ) return alpha; } } // while return alpha; }
ExecStatus ElementUnionConst<SView,RView>::propagate(Space& home, const ModEventDelta&) { Region r(home); bool* stillSelected = r.alloc<bool>(n_iv); bool loopVar; do { loopVar = false; for (int i=n_iv; i--;) stillSelected[i] = false; // Cache the upper bound iterator, as we have to // modify the upper bound while iterating LubRanges<RView> x1ub(x1); Iter::Ranges::Cache x1ubc(r,x1ub); Iter::Ranges::ToValues<Iter::Ranges::Cache> vx1ub(x1ubc); GlbRanges<RView> x1lb(x1); Iter::Ranges::Cache x1lbc(r,x1lb); Iter::Ranges::ToValues<Iter::Ranges::Cache> vx1(x1lbc); // In the first iteration, compute in before[i] the union // of all the upper bounds of the x_i. At the same time, // exclude inconsistent x_i from x1. GLBndSet sofarBefore(home); LUBndSet selectedInter(home, IntSet (Limits::min, Limits::max)); GLBndSet* before = static_cast<GLBndSet*>(r.ralloc(sizeof(GLBndSet)*n_iv)); unsigned int maxCard = 0; unsigned int minCard = Limits::card; while (vx1ub()) { int i = vx1ub.val(); IntSetRanges candCardR(iv[i]); unsigned int candidateCard = Iter::Ranges::size(candCardR); IntSetRanges candlb(iv[i]); LubRanges<SView> x0ub(x0); Iter::Ranges::Diff<IntSetRanges, LubRanges<SView> > diff(candlb, x0ub); bool selectSingleInconsistent = false; if (x1.cardMax() <= 1) { GlbRanges<SView> x0lb(x0); IntSetRanges candub(iv[i]); Iter::Ranges::Diff<GlbRanges<SView>, IntSetRanges > diff2(x0lb, candub); selectSingleInconsistent = diff2() || candidateCard < x0.cardMin(); } // exclude inconsistent x_i // an x_i is inconsistent if // * at most one x_i can be selected and there are // elements in x_0 that can't be in x_i // (selectSingleInconsistent) // * its min cardinality is greater than maxCard of x0 // * inter is not empty (there are elements in x_i // that can't be in x_0) if (selectSingleInconsistent || candidateCard > x0.cardMax() || diff()) { ModEvent me = (x1.exclude(home,i)); loopVar |= me_modified(me); GECODE_ME_CHECK(me); } else { stillSelected[i] = true; // if x_i is consistent, check whether we know // that its index is in x1 if (vx1() && vx1.val()==i) { // x0 >= candidate, candidate <= x0 // GlbRanges<SView> candlb(candidate); IntSetRanges candlb(iv[i]); ModEvent me = x0.includeI(home,candlb); loopVar |= me_modified(me); GECODE_ME_CHECK(me); ++vx1; } new (&before[i]) GLBndSet(home); before[i].update(home,sofarBefore); IntSetRanges cub(iv[i]); sofarBefore.includeI(home,cub); IntSetRanges clb(iv[i]); selectedInter.intersectI(home,clb); maxCard = std::max(maxCard, candidateCard); minCard = std::min(minCard, candidateCard); } ++vx1ub; } if (x1.cardMax()==0) { // Selector is empty, hence the result must be empty { GECODE_ME_CHECK(x0.cardMax(home,0)); } for (int i=n_iv; i--;) if (stillSelected[i]) before[i].dispose(home); selectedInter.dispose(home); sofarBefore.dispose(home); return home.ES_SUBSUMED(*this); } if (x1.cardMin() > 0) { // Selector is not empty, hence the intersection of the // possibly selected lower bounds is contained in x0 BndSetRanges si(selectedInter); ModEvent me = x0.includeI(home, si); loopVar |= me_modified(me); GECODE_ME_CHECK(me); me = x0.cardMin(home, minCard); loopVar |= me_modified(me); GECODE_ME_CHECK(me); } selectedInter.dispose(home); if (x1.cardMax() <= 1) { ModEvent me = x0.cardMax(home, maxCard); loopVar |= me_modified(me); GECODE_ME_CHECK(me); } { // x0 <= sofarBefore BndSetRanges sfB(sofarBefore); ModEvent me = x0.intersectI(home,sfB); loopVar |= me_modified(me); GECODE_ME_CHECK(me); } sofarBefore.dispose(home); GLBndSet sofarAfter(home); // In the second iteration, this time backwards, compute // sofarAfter as the union of all lub(x_j) with j>i for (int i=n_iv; i--;) { if (!stillSelected[i]) continue; BndSetRanges b(before[i]); BndSetRanges s(sofarAfter); GlbRanges<SView> x0lb(x0); Iter::Ranges::Union<BndSetRanges, BndSetRanges> inter(b,s); Iter::Ranges::Diff<GlbRanges<SView>, Iter::Ranges::Union<BndSetRanges,BndSetRanges> > diff(x0lb, inter); if (diff()) { ModEvent me = (x1.include(home,i)); loopVar |= me_modified(me); GECODE_ME_CHECK(me); // candidate != extra IntSetRanges ivi(iv[i]); if (!Iter::Ranges::subset(diff, ivi)) GECODE_ME_CHECK(ME_SET_FAILED); } IntSetRanges iviub(iv[i]); sofarAfter.includeI(home,iviub); before[i].dispose(home); } sofarAfter.dispose(home); } while (loopVar); if (x1.assigned()) { assert(x0.assigned()); return home.ES_SUBSUMED(*this); } return ES_FIX; }
// Algorithme de recherche MinMax avec des coupes Alpha-Beta. int Search(int depth, int ply, int wtm, int alpha, int beta, bool do_null) { register int Valeur, AlphaInitiale, check_ext = 0, extension = 0, MoveCherche, danger = 0; if ( ply >= MAXPLY-1 ) return beta; iNodes++; // Si on n'est pas en mode Analyse, Reste-t-il du temps? if ( interrupted || (timeabort && !g_bModeAnalyse) ) { return beta; } AlphaInitiale = alpha; // Calculer le temps restant. if ( (iNodes & 0xFF ) == 0xFF ) { if ( TimeCheck() ) { timeabort = true; } // Verifier si il y a quelque chose dans le tampon // d'entree. if ( inter() ) { char buf[10]; int c = fgetc(stdin); if (c == 10) { c = fgetc(stdin); ungetc(c, stdin); if (c == '.') { scanf("%s", &buf); printf( "stat01: %d %d %d %d %d\n", (TempsCenti()-timestamp), iNodes, iProfondeurIteration, cb.MoveList[1].nbmove - cb.MoveList[1].currmove-1, cb.MoveList[1].nbmove ); journal.Log("received a dot\n"); } else { interrupted = true; } } else { ungetc(c, stdin); interrupted = true; } } } // Verifier si ce n'est pas une nulle. if (Repetition(wtm)) { //if ( 0 < beta ) { // pv[ply-1][ply-1] = cb.CurrentPath.moves[ply-1]; return 0; // if ( wtm ) { // return DRAWSCORE; // } // else { // return -DRAWSCORE; // } //} } // Regarder dans la table de transposition pour voir si cette position // n'a pas deja ete calculer. #ifdef TRANSPOSITION switch( TableTrans->Lookup( cb, ply, depth, wtm, alpha, beta, danger ) ) { case SCORE_EXACTE: return alpha; case BORNE_SUPERIEUR: return alpha; case BORNE_INFERIEUR: return beta; case EVITER_NULL: do_null = false; } #endif #ifdef NULL_MOVE // En premier, on essai le NULL MOVE. if ( do_null ) { int nbPiece = wtm?cb.TotalMaterielBlanc:cb.TotalMaterielNoir; if ( !cb.inCheck[ply] && nbPiece > 5 && depth > 3 && alpha == beta-1) { int EnPassantB = cb.EnPassantB[ply+1]; int EnPassantN = cb.EnPassantN[ply+1]; cb.EnPassantB[ply+1] = -1; cb.EnPassantN[ply+1] = -1; Valeur = -Search(depth-3, ply+1, !wtm, -beta, -beta+1, false); cb.EnPassantB[ply+1] = EnPassantB; cb.EnPassantN[ply+1] = EnPassantN; if ( Valeur >= beta ) { #ifdef TRANSPOSITION TableTrans->StoreRefutation( cb, ply, depth, wtm, Valeur, alpha, beta, danger ); #endif return Valeur; } if ( Valeur <= -MATE+50 ) danger = 1; } } #endif // Internal Iterative Deepening. /* if ( depth > 2 && ((!(ply&1) && alpha==root_alpha && beta==root_beta) || ((ply&1) && alpha==-root_beta && beta==-root_alpha)) && cb.HashMove[ply].From == 0 && cb.HashMove[ply].To == 0 ) { Valeur = ABSearch( cb, depth-2, ply, wtm, alpha, beta, true ); if ( Valeur <= alpha ) { Valeur = ABSearch( cb, depth-2, ply, wtm, -MATE, beta, true ); } else { if ( Valeur < beta ) { cb.HashMove[ply] = pv[ply-1][ply]; } else cb.HashMove[ply] = cb.CurrentPath.moves[ply]; } }*/ #ifdef TRANSPOSITION Phase[ply] = HASH_MOVE; #else // if ( ((!(ply&1) && alpha==root_alpha && beta==root_beta) || // ( (ply&1) && alpha==-root_beta && beta==-root_alpha)) ) Phase[ply] = PV_MOVE; // else // Phase[ply] = GENERATE_CAPTURE_MOVES; #endif // Maintenant, evaluer chaque coup. MoveCherche = 0; while( Phase[ply] != NO_MORE_MOVES && !interrupted ) { if ( NextMove( cb, ply, wtm ) ) { // Si // On execute le coup. MakeMove(ply, cb.MoveList[ply].CurrentMove(), wtm); // Mettre le coup dans le chemin actuel. cb.CurrentPath.moves[ply] = cb.MoveList[ply].moves[cb.MoveList[ply].currmove]; if (!Check(wtm)) { MoveCherche++; // Si le coup met en echec etendre la recherche d'une profondeur // pour qu'il puisse en sortir. if (Check(!wtm) ) { cb.inCheck[ply+1] = true; extension = 1; cb.RaisonExtension[ply] = EXTENSION_ECHEC; } else { extension = 0; cb.inCheck[ply+1] = false; cb.RaisonExtension[ply] = PAS_EXTENSION; } // Si le coup est une recapture // etendre la recherche d'une profondeur. if ( cb.CurrentPath.moves[ply].Capture && abs(ValeurPiece[cb.CurrentPath.moves[ply-1].Capture] - ValeurPiece[cb.CurrentPath.moves[ply].Capture]) <= 20 && (cb.CurrentPath.moves[ply-1].To == cb.CurrentPath.moves[ply].To) && cb.RaisonExtension[ply-1] != EXTENSION_RECAPTURE) { extension = 1; cb.RaisonExtension[ply] = EXTENSION_RECAPTURE; } // Si on est sur le point de promouvoir un pion, étendre la recherche // pour voir si c'est une menace. if ( extension == 0 && cb.CurrentPath.moves[ply].Piece == 1 && PromoteExtension[ cb.CurrentPath.moves[ply].To ] ) { extension = 1; cb.RaisonExtension[ply] = EXTENSION_PROMOTION; } // Si on pousse un pion passe, pousser la recherche plus // loin pour voir si c'est un danger. if ( cb.CurrentPath.moves[ply].Piece == pion ) if ( wtm ) { if ( cb.CurrentPath.moves[ply].To <= H5 ) if ( cb.PionPasseB[cb.CurrentPath.moves[ply].To&7] ) { extension = 1; cb.RaisonExtension[ply] = EXTENSION_PIONPASSE; } } else { if ( cb.CurrentPath.moves[ply].To >= A4 ) if ( cb.PionPasseN[cb.CurrentPath.moves[ply].To&7] ) { extension = 1; cb.RaisonExtension[ply] = EXTENSION_PIONPASSE; } } // Razoring trick. Idee prise dans Crafty. if ( depth == 2 && !cb.inCheck[ply] && extension == 0 ) { int valeur; if ( wtm ) valeur = Eval(ply, wtm, alpha, beta); else valeur = -Eval(ply, wtm, alpha, beta); if ( valeur+50 < alpha ) extension = -1; } // On l'explore. // Si c'est la variation principale, Fenetre normale, sinon, // fenetre est n et n+1. int inpv = 1; if (ply&1) { if ( alpha != root_alpha || beta != root_beta ) inpv = 0; } else { if ( alpha != -root_beta || beta != -root_alpha ) inpv = 0; } if ( inpv ) { Valeur = -ABSearch(depth-1+extension+danger, ply+1, !wtm, -beta, -alpha, true); } else { Valeur = -ABSearch(depth-1+extension+danger, ply+1, !wtm, -alpha-1, -alpha, true); if ( Valeur > alpha && Valeur < beta ) { pvsresearch++; Valeur = -ABSearch(depth-1+extension+danger, ply+1, !wtm, -beta, -alpha, true); } } } else { Valeur = -INFINI; } cb.MoveList[ply].CurrentMove().Score = Valeur; // On defait le coup. UnmakeMove(ply, cb.MoveList[ply].CurrentMove(), wtm); if (interrupted) return Valeur; #ifdef DEBUG Consistence( cb, cb.MoveList[ply].CurrentMove() ); #endif // Est-il meilleur que notre valeur actuelle? if ( Valeur > alpha ) { if ( Valeur >= beta ) { #ifdef TRANSPOSITION TableTrans->StoreRefutation( cb, ply, depth, wtm, Valeur, alpha, beta, check_ext ); #endif g_iRefutation++; // Verifier si on peu l'utiliser comme killer move. if ( Phase[ply] == NON_CAPTURE_MOVES ) { cb.AddKiller( &cb.CurrentPath.moves[ply-1], ply-1 ); } else { if ( Phase[ply] == KILLER_MOVE_2 ) cb.Killers[ply-1][0].Score++; else if ( Phase[ply] == GENERATE_NON_CAPTURE_MOVES ) cb.Killers[ply-1][1].Score++; } return Valeur; } pv[ply][ply] = cb.CurrentPath.moves[ply]; pv_length[ply] = pv_length[ply+1]; memcpy(&pv[ply][ply+1], &pv[ply+1][ply+1], sizeof(TMove)*(pv_length[ply]-ply)); alpha = Valeur; } } // if } // Verifier si il y a mat ou pat. if ( MoveCherche == 0 ) { if (!Check(wtm)) { pv[ply][ply] = cb.CurrentPath.moves[ply]; return 0; // if ( wtm ) { // return DRAWSCORE; // } // else { // return -DRAWSCORE; // } } else { if ( ply < iMateInPly ) iMateInPly = ply; alpha = -MATE+iMateInPly; } } #ifdef TRANSPOSITION TableTrans->StoreBest( cb, ply, depth, wtm, alpha, AlphaInitiale, danger ); #endif return alpha; }
/* Intersection area */ template<class K> typename K::FT intersection_area_two_slabs(const Rectangle_2<K>& a, const Rectangle_2<K> &b) { typedef typename K::Vector_2 Vector_2; typedef typename K::Line_2 Line_2; typedef typename K::Point_2 Point_2; typedef typename K::FT FT; Origin O; if(a.is_degenerate() || b.is_degenerate()) return 0; std::vector<Vector_2> v; std::vector<Line_2> l; for(unsigned int i=0; i<4; ++i) { v.push_back(b[i]-O); l.push_back(b.line(i)); } const Vector_2& n = a.normal(); FT r = a.ratio(); FT n2 = n.squared_length(); FT rn2 = r*r*n2; Vector_2 vc(a.center()-O); Vector_2 trn(-r*n.y(),r*n.x()); FT ctrn = vc*trn; FT cn = vc*n; Vector_2 ln[] = { n, trn }; FT lc[] = { cn+n2, ctrn+rn2, cn-n2, ctrn-rn2 }; // basically it is the iterative intersection of the convex polygon initialized with b // with the 2 slabs line0/line2 and line1/line3. for(unsigned int i=0; i<2; ++i) { int begin0=-1, end0=-1; int begin1=-1, end1=-1; unsigned int n=v.size(); for(unsigned int j=0; j<n; ++j) { FT dot = ln[i]*v[j]; if( dot>lc[i]) { if(end0==-1 && begin0!=-1) end0=j; if(begin1<=end1) begin1=j; } else { if(begin0<=end0) begin0=j; if(dot<lc[i+2]) { if(end1==-1 && begin1!=-1) end1=j; } else { if(begin1<=end1) begin1=j; } } } if(begin0==-1 || begin1==-1 ) return 0; // outside the slab if(end0 ==-1) { if(begin0!=0) end0=0; else begin0=begin1; } if(end1 ==-1) { if(begin1!=0) end1=0; else { if(end0==-1) continue; // inside the slab begin1=begin0; } } std::vector<Vector_2> w; std::vector<Line_2> m; if(end0!=-1) { // cut outside line(i+1) for(int j=begin1; j!=end0; j=(j+1)%n) { w.push_back(v[j]); m.push_back(l[j]); } Point_2 inter(O); Line_2 li(ln[i].x(),ln[i].y(),-lc[i]); intersection(l[(end0+n-1)%n],li).assign(inter); w.push_back(inter-O); m.push_back(li); m.push_back(l[(begin0+n-1)%n]); intersection(li,m.back()).assign(inter); w.push_back(inter-O); } if(end1!=-1) { // cut outside line(i+3) for(int j=begin0; j!=end1; j=(j+1)%n) { w.push_back(v[j]); m.push_back(l[j]); } Point_2 inter(O); Line_2 li(ln[i].x(),ln[i].y(),-lc[i+2]); intersection(l[(end1+n-1)%n],li).assign(inter); w.push_back(inter-O); m.push_back(li); m.push_back(l[(begin1+n-1)%n]); intersection(li,m.back()).assign(inter); w.push_back(inter-O); } std::swap(v,w); std::swap(l,m); } std::vector<Point_2> p; for(unsigned int i=0; i<v.size(); ++i) { p.push_back(O+v[i]); } FT area; area_2(p.begin(),p.end(),area); return abs(area); }
void spu_interpreter::DEFAULT(SPUThread& CPU, spu_opcode_t op) { SPUInterpreter inter(CPU); (*SPU_instr::rrr_list)(&inter, op.opcode); }
void OSNSPTest::testAVI() { std::cout << "===========================================" <<std::endl; std::cout << " ===== OSNSP tests start ... ===== " <<std::endl; std::cout << "===========================================" <<std::endl; std::cout << "------- implicit Twisting relation -------" <<std::endl; _h = 1e-1; _T = 20.0; double G = 10.0; double beta = .3; _A->zero(); (*_A)(0, 1) = 1.0; _x0->zero(); (*_x0)(0) = 10.0; (*_x0)(1) = 10.0; SP::SimpleMatrix B(new SimpleMatrix(_n, _n, 0)); SP::SimpleMatrix C(new SimpleMatrix(_n, _n)); (*B)(1, 0) = G; (*B)(1, 1) = G*beta; C->eye(); SP::FirstOrderLinearTIR rel(new FirstOrderLinearTIR(C, B)); SP::SimpleMatrix H(new SimpleMatrix(4, 2)); (*H)(0, 0) = 1.0; (*H)(1, 0) = -_h/2.0; (*H)(2, 0) = -1.0; (*H)(3, 0) = _h/2.0; (*H)(1, 1) = 1.0; (*H)(3, 1) = -1.0; SP::SiconosVector K(new SiconosVector(4)); (*K)(0) = -1.0; (*K)(1) = -1.0; (*K)(2) = -1.0; (*K)(3) = -1.0; SP::NonSmoothLaw nslaw(new NormalConeNSL(_n, H, K)); _DS.reset(new FirstOrderLinearTIDS(_x0, _A, _b)); _TD.reset(new TimeDiscretisation(_t0, _h)); _model.reset(new Model(_t0, _T)); SP::Interaction inter(new Interaction(_n, nslaw, rel)); _osi.reset(new EulerMoreauOSI(_theta)); _model->nonSmoothDynamicalSystem()->insertDynamicalSystem(_DS); _model->nonSmoothDynamicalSystem()->setOSI(_DS, _osi); _model->nonSmoothDynamicalSystem()->link(inter, _DS); _sim.reset(new TimeStepping(_TD)); _sim->insertIntegrator(_osi); SP::AVI osnspb(new AVI()); _sim->insertNonSmoothProblem(osnspb); _model->initialize(_sim); SimpleMatrix dataPlot((unsigned)ceil((_T - _t0) / _h) + 10, 5); SiconosVector& xProc = *_DS->x(); SiconosVector& lambda = *inter->lambda(0); unsigned int k = 0; dataPlot(0, 0) = _t0; dataPlot(0, 1) = (*_x0)(0); dataPlot(0, 2) = (*_x0)(1); dataPlot(0, 3) = -1.0; dataPlot(0, 4) = -1.0; while (_sim->hasNextEvent()) { _sim->computeOneStep(); k++; dataPlot(k, 0) = _sim->nextTime(); dataPlot(k, 1) = xProc(0); dataPlot(k, 2) = xProc(1); dataPlot(k, 3) = lambda(0); dataPlot(k, 4) = lambda(1); _sim->nextStep(); } std::cout <<std::endl <<std::endl; dataPlot.resize(k, dataPlot.size(1)); ioMatrix::write("testAVI.dat", "ascii", dataPlot, "noDim"); // Reference Matrix SimpleMatrix dataPlotRef(dataPlot); dataPlotRef.zero(); ioMatrix::read("testAVI.ref", "ascii", dataPlotRef); std::cout << "------- Integration Ok, error = " << (dataPlot - dataPlotRef).normInf() << " -------" <<std::endl; CPPUNIT_ASSERT_EQUAL_MESSAGE("testAVI : ", (dataPlot - dataPlotRef).normInf() < _tol, true); }
int main(void) { char line[MAX_LINE]; entry *entryHead; //head of entry list snapshot *snapHead; //head of snapshot list entryHead = NULL; snapHead = NULL; while (true) { printf("> "); if (fgets(line, MAX_LINE, stdin) == NULL) { printf("\n"); command_bye(entryHead, snapHead); return 0; } //get command from the input line as well as a second parameter if it exists char *ptr = strtok(line, " "); char firstToken[MAX_COMMAND]; //stores a command strcpy(firstToken, ptr); ptr = strtok(NULL, " "); char secondToken[MAX_KEY]; //stores either a key or a second part of the command secondToken[0] = '\0'; //get rid of a new line character if it exists in the last valid token entered char *newLine; if (ptr != NULL) { strcpy(secondToken, ptr); newLine = strchr(secondToken, '\n'); } else { newLine = strchr(firstToken, '\n'); } if (newLine) { *newLine = 0; } //identify the command and call the right function to execute the command entered if (strcasecmp(firstToken, "BYE") == 0) { command_bye(entryHead, snapHead); return 0; } else if (strcasecmp(firstToken, "HELP") == 0) { command_help(); } else if (strcasecmp(firstToken, "LIST") == 0) { if (strcasecmp(secondToken, "ENTRIES") == 0) { list_entries(entryHead); } else if (strcasecmp(secondToken, "KEYS") == 0) { list_keys(entryHead); } else if(strcasecmp(secondToken, "SNAPSHOTS") == 0) { list_snapshots(snapHead); } else { printf("unknown\n"); } } else if (strcasecmp(firstToken, "GET") == 0) { get(secondToken, entryHead); } else if (strcasecmp(firstToken, "DEL") == 0) { entryHead = del(entryHead, secondToken); } else if (strcasecmp(firstToken, "PURGE") == 0) { entryHead = purge(secondToken, entryHead, snapHead); } else if (strcasecmp(firstToken, "SET") == 0) { if (ptr != NULL && secondToken[0] != '\0') { entryHead = set(ptr, secondToken, entryHead); } else { printf("invalid input\n"); } } else if (strcasecmp(firstToken, "PUSH") == 0 || strcasecmp(firstToken, "APPEND") == 0) { push_append(ptr, secondToken, entryHead, firstToken); } else if (strcasecmp(firstToken, "PICK") == 0) { ptr = strtok(NULL, " "); int index = atoi(ptr); pick(index, secondToken, entryHead); } else if (strcasecmp(firstToken, "PLUCK") == 0) { ptr = strtok(NULL, " "); int index = atoi(ptr); pluck(index, secondToken, entryHead); } else if (strcasecmp(firstToken, "POP") == 0) { pluck(1, secondToken, entryHead); } else if (strcasecmp(firstToken, "DROP") == 0) { snapHead = drop(snapHead, atoi(secondToken)); } else if (strcasecmp(firstToken, "ROLLBACK") == 0) { entryHead = checkout(atoi(secondToken), entryHead, snapHead); snapHead = remove_snapshots(atoi(secondToken), snapHead); } else if (strcasecmp(firstToken, "CHECKOUT") == 0) { entryHead = checkout(atoi(secondToken), entryHead, snapHead); } else if (strcasecmp(firstToken, "SNAPSHOT") == 0) { snapHead = take_snapshot(entryHead, snapHead); } else if (strcasecmp(firstToken, "MIN") == 0) { min(secondToken, entryHead); } else if (strcasecmp(firstToken, "MAX") == 0) { max(secondToken, entryHead); } else if (strcasecmp(firstToken, "SUM") == 0) { sum(secondToken, entryHead); } else if (strcasecmp(firstToken, "LEN") == 0) { len(secondToken, entryHead); } else if (strcasecmp(firstToken, "REV") == 0) { reverse(secondToken, entryHead); } else if (strcasecmp(firstToken, "UNIQ") == 0) { unique(secondToken, entryHead); } else if (strcasecmp(firstToken, "SORT") == 0) { sort(secondToken, entryHead); } else if (strcasecmp(firstToken, "DIFF") == 0) { diff(ptr, secondToken, entryHead); } else if (strcasecmp(firstToken, "INTER") == 0) { inter(ptr, secondToken, entryHead); } else if (strcasecmp(firstToken, "UNION") == 0) { union_oper(ptr, secondToken, entryHead); } else { printf("unknown\n"); } printf("\n"); } return 0; }
bool AmiraConverter::ConvertToRAW(const std::string& strSourceFilename, const std::string& strTempDir, bool, uint64_t& iHeaderSkip, unsigned& iComponentSize, uint64_t& iComponentCount, bool& bConvertEndianness, bool& bSigned, bool& bIsFloat, UINT64VECTOR3& vVolumeSize, FLOATVECTOR3& vVolumeAspect, std::string& strTitle, std::string& strIntermediateFile, bool& bDeleteIntermediateFile) { strTitle = "from Amira converter"; std::ifstream amira(strSourceFilename.c_str()); if(!amira) { T_ERROR("Could not open %s!", strSourceFilename.c_str()); return false; } iHeaderSkip = 0; // we'll create a new, raw file. iComponentSize = 64; iComponentCount = 1; bConvertEndianness = false; bSigned = true; bIsFloat = true; vVolumeAspect = FLOATVECTOR3(1.0, 1.0, 1.0); strIntermediateFile = strTempDir + "/" + "am.iv3d.tmp"; bDeleteIntermediateFile = true; std::string junk; std::string version; amira >> junk >> junk >> junk >> version; // "# AmiraMesh ASCII 1.0" MESSAGE("Reading 'AmiraMesh' file, version %s", version.c_str()); // "define Lattice X Y Z" amira >> junk >> junk >> vVolumeSize[0] >> vVolumeSize[1] >> vVolumeSize[2]; assert(vVolumeSize[0] > 0); assert(vVolumeSize[1] > 0); assert(vVolumeSize[2] > 0); MESSAGE("%llu-bit %llux%llux%llu data.", iComponentSize, vVolumeSize[0], vVolumeSize[1], vVolumeSize[2]); // The rest of the header is stuff we don't bother with right now, and then: // // Lattice { float Data } = @1 // // @1 // first-elem 2nd-elem ... // // Presumably they could define multiple "Lattice"s and then use @2, @3, // etc., but I don't have any such example data files, so screw it. // We're just going to read up until that @1. Then we'll read up until the // next @1. At that point we can just copy each elem into an output file. do { amira >> junk; } while(junk != "@1"); // " ... } = @1" do { amira >> junk; } while(junk != "@1"); // "@1\n" std::ofstream inter(strIntermediateFile.c_str(), std::ofstream::out | std::ofstream::out); if(!inter) { T_ERROR("Could not create intermediate file '%s'.", strIntermediateFile.c_str()); bDeleteIntermediateFile = false; return false; } std::copy(std::istream_iterator<double>(amira), std::istream_iterator<double>(), binary_ostream_iterator(inter)); return true; }
Matrix<double> sparseSOR(SpMatrix* A, Matrix<double> b, Matrix<double> xold, double tol, int maxiter, double w=1.25, char check='n') // CAUTION: does not work in parallel due to some reason { cout << "sparseSOR(): Input LHS matrix is " << A->rows() << " x " << A->cols() << endl; if(A->rows() != b.rows()) { cout << "! sparseSOR(): Invalid dimensions of A and b!\n"; return b; } if(xold.rows() != b.rows()) { cout << "! sparseSOR(): Invalid dimensions on xold !\n"; return b; } int N = A->rows(); if(check == 'y') { for(int i = 0; i < A->rows(); i++) { double sum = 0; for(int j = 0; j < A->cols(); j++) { if(i != j) sum += dabs(A->get(i,j)); } if(dabs(A->get(i,i)) <= sum) cout << "* sparseSOR(): LHS Matrix is NOT strictly diagonally dominant in row " << i << "!!\n"; } } Matrix<double> x(b.rows(),1); Matrix<double> M(N,1); // vector of diagonal elements of A M.zeros(); // diagonal matrix M //cout << "sparsegaussseidel(): Getting diagonal of sparse matrix\n"; A->get_diagonal(&M); //invert M for(int i = 0; i < N; i++) M(i) = 1.0/M(i); //x.zeros(); //cout << "gaussseidel: Initial error = " << (xold-x).dabsmax() << endl; x = xold; int c = 0; double initres; bool first = true; Matrix<double> Axold(N,1); Matrix<double> inter(N,1); Matrix<double> diff(N,1); // diff = x - xold double error = 1.0; //cout << "sparsegaussseidel(): Starting iterations\n"; do { xold = x; Axold.zeros(); int i; //#pragma omp parallel for default(none) private(i) shared(A,b,Axold,x,xold,inter,M,N,w) num_threads(nthreads_linalg) for(i = 0; i < N; i++) { //cout << " Calling sparse getelem_multiply_parts\n"; Axold(i) = A->getelem_multiply_parts(i, &x, &xold, i, xold.get(i)); //cout << " Setting inter\n"; inter(i,0) = w*(b(i,0) - Axold(i,0)); x(i,0) = (1-w)*xold(i,0) + M(i) * inter(i,0); } // NOTE: The above results in FORWARD Gauss-Seidel //if(c > maxiter) { cout << "gaussseidel: Max iterations exceeded!\n"; break; } for(int i = 0; i < N; i++) diff(i,0) = x(i,0) - xold(i,0); error = dabs(diff(0,0)); for(int i = 1; i < N; i++) if(dabs(diff(i,0)) > error) error = dabs(diff(i,0)); //cout << "gaussseidel: error = " << error << endl; if(first == true) { initres = error; if(dabs(initres) < tol*tol) { cout << "sparseSOR(): Initial residue = " << initres << endl; break; } first = false; } if(c%10 == 0 || c == 1) cout << "sparseSOR(): Step " << c << ", Relative error = " << error/initres << endl; c++; } while(error/initres >= tol && c <= maxiter); cout << "sparseSOR(): No. of iterations = " << c << ", final error " << error/initres << endl; return x; }
void Viewer::drawConfigurationPath(const rl::plan::VectorList& path) { this->path->enableNotify(false); this->pathCoordinate->point.setNum(0); this->pathIndexedLineSet->coordIndex.setNum(0); rl::math::Vector inter(this->model->getDofPosition()); for (std::size_t l = 0; l < this->model->getOperationalDof(); ++l) { rl::plan::VectorList::const_iterator i = path.begin(); rl::plan::VectorList::const_iterator j = ++path.begin(); if (i != path.end() && j != path.end()) { this->model->setPosition(*i); this->model->updateFrames(); this->pathCoordinate->point.set1Value( this->pathCoordinate->point.getNum(), this->model->forwardPosition(l)(0, 3), this->model->forwardPosition(l)(1, 3), this->model->forwardPosition(l)(2, 3) ); this->pathIndexedLineSet->coordIndex.set1Value( this->pathIndexedLineSet->coordIndex.getNum(), this->pathCoordinate->point.getNum() - 1 ); } for (; i != path.end() && j != path.end(); ++i, ++j) { rl::math::Real steps = std::ceil(this->model->distance(*i, *j) / this->delta); for (std::size_t k = 1; k < steps + 1; ++k) { this->model->interpolate(*i, *j, k / steps, inter); this->model->setPosition(inter); this->model->updateFrames(false); this->pathCoordinate->point.set1Value( this->pathCoordinate->point.getNum(), this->model->forwardPosition(l)(0, 3), this->model->forwardPosition(l)(1, 3), this->model->forwardPosition(l)(2, 3) ); this->pathIndexedLineSet->coordIndex.set1Value( this->pathIndexedLineSet->coordIndex.getNum(), this->pathCoordinate->point.getNum() - 1 ); } } this->pathIndexedLineSet->coordIndex.set1Value( this->pathIndexedLineSet->coordIndex.getNum(), SO_END_FACE_INDEX ); } this->path->enableNotify(true); this->path->touch(); }
void pass1(string in_file) { cout<<"Running pass 1..."<<endl; ifstream in((in_file + ".txt").c_str()); ofstream inter((in_file + ".i").c_str()); char line[100]; char* tokens[6]; int line_no = 1; int locctr = 0, prev_locctr = 0; int no_tokens = 0, sc = 0, temp = 0; string label, operation, operand, comment; string prog_name, loc; try{ while(in && operation!="END") { label.clear(),operation.clear(),operand.clear(),comment.clear(); in.getline(line,100); if(line[0]==';') { comment = line; //Neglect complete comment... } else { no_tokens = extractTokens(line,tokens,'\t'); label.assign(tokens[0]); if(optab.search(label)!=-1) throw 1; operation.assign(tokens[1]); if(no_tokens==3) { if(tokens[2][0]==';') comment.assign(tokens[2]); else operand.assign(tokens[2]); } else if(no_tokens==4) { operand.assign(tokens[2]); comment.assign(tokens[3]); } if(line_no==1) { if(operation=="START") { prog_name = label; if(prog_name.length()>10) throw 8; operation = "START"; if(operand[0]=='x') { stringstream ss(operand.substr(1,operand.length()-1)); ss>>hex>>locctr; } else if(operand[0]=='#') { stringstream ss(operand.substr(1,operand.length()-1)); ss>>dec>>locctr; } start_add = prev_locctr = locctr; } else cout<<"No Prog Name and Start Address specified. Default assumed."<<endl; }
void Viewer::drawSweptVolume(const rl::plan::VectorList& path) { this->sweptGroup->enableNotify(false); this->sweptGroup->removeAllChildren(); rl::math::Real length = 0; rl::plan::VectorList::const_iterator i = path.begin(); rl::plan::VectorList::const_iterator j = ++path.begin(); for (; i != path.end() && j != path.end(); ++i, ++j) { length += this->model->distance(*i, *j); } rl::math::Real delta = length / static_cast<std::size_t>(std::ceil(length / this->deltaSwept)); rl::math::Vector inter(this->model->getDofPosition()); rl::math::Real x0 = 0; rl::math::Real x1 = x0; rl::math::Real x = 0; i = path.begin(); j = ++path.begin(); for (; i != path.end() && j != path.end(); ++i, ++j) { x1 += this->model->distance(*i, *j); for (; x < x1; x += delta) { this->model->interpolate(*i, *j, (x - x0) / (x1 - x0), inter); this->model->setPosition(inter); this->model->updateFrames(); SoVRMLGroup* model = new SoVRMLGroup(); for (std::size_t k = 0; k < this->model->model->getNumBodies(); ++k) { SoVRMLTransform* frame = new SoVRMLTransform(); frame->copyFieldValues(static_cast<rl::sg::so::Body*>(this->model->model->getBody(k))->root); for (std::size_t l = 0; l < this->model->model->getBody(k)->getNumShapes(); ++l) { SoVRMLTransform* transform = new SoVRMLTransform(); transform->copyFieldValues(static_cast<rl::sg::so::Shape*>(this->model->model->getBody(k)->getShape(l))->root); transform->addChild(static_cast<rl::sg::so::Shape*>(this->model->model->getBody(k)->getShape(l))->shape); frame->addChild(transform); } model->addChild(frame); } this->sweptGroup->addChild(model); } x0 = x1; if (j == --path.end()) { this->model->interpolate(*i, *j, 1, inter); this->model->setPosition(inter); this->model->updateFrames(); SoVRMLGroup* model = new SoVRMLGroup(); for (std::size_t k = 0; k < this->model->model->getNumBodies(); ++k) { SoVRMLTransform* frame = new SoVRMLTransform(); frame->copyFieldValues(static_cast<rl::sg::so::Body*>(this->model->model->getBody(k))->root); for (std::size_t l = 0; l < this->model->model->getBody(k)->getNumShapes(); ++l) { SoVRMLTransform* transform = new SoVRMLTransform(); transform->copyFieldValues(static_cast<rl::sg::so::Shape*>(this->model->model->getBody(k)->getShape(l))->root); transform->addChild(static_cast<rl::sg::so::Shape*>(this->model->model->getBody(k)->getShape(l))->shape); frame->addChild(transform); } model->addChild(frame); } this->sweptGroup->addChild(model); } } this->sweptGroup->enableNotify(true); this->sweptGroup->touch(); }
void fluid::enforce_glass( particle* p, double& dt, math::vec& newpos ) { /* if(newpos.x<190) { double passed_time=(p->pos.x-190)/p->v.x; p->v.x*=-wall_damping; //reversing direction newpos.x=190+(dt-passed_time)*p->v.x; } else if(newpos.x>210) { double passed_time=(210-p->pos.x)/p->v.x; p->v.x*=-wall_damping; //reversing direction newpos.x=210-(dt-passed_time)*p->v.x; } */ bool critical_particle=false; if(newpos.x<190.0) critical_particle=true; if(newpos.x>210.0) critical_particle=true; critical_particle=false; if(critical_particle) { logger::log("critical particle %p\n", p); logger::log("pos=%s, v=%s, newpos=%s", STR(p->pos), STR(p->v), STR(newpos)); } //#define DEBUGGING bool r=true; while(dt>0 && r) { math:: line l2=math::line(p->pos, newpos); auto it =min_element(physics::scenery.begin(), physics::scenery.end(), [&] (math::line& a, math::line& b) -> bool { math::vec inter_a(0, 0), inter_b(0, 0); bool r_a=math::intersection(a, l2, inter_a), r_b=math::intersection(b, l2, inter_b); if(!r_a && !r_b) { return (p->pos-inter_a).LengthSq()<(p->pos-inter_b).LengthSq();; } else { if(!r_b) return true; if(!r_a) return false; return (p->pos-inter_a).LengthSq()<(p->pos-inter_b).LengthSq(); } }); math::line l1=*it; math::vec inter(0, 0); r=math::intersection(l1, l2, inter); if(r) { double passed_time=sqrt((p->pos-inter).LengthSq()/p->v.LengthSq()); math::vec oldv=p->v; p->v=p->v.deflect(l1)*wall_damping; dt-=passed_time; math::vec oldpos=p->pos; p->pos=inter; newpos=inter+(p->v)*(dt); if(critical_particle) { logger::log("deflected to pos=%s, v=%s, newpos=%s", STR(p->pos), STR(p->v), STR(newpos)); logger::log("force: %s", STR(mass*(1.0/passed_time)*(p->v-oldv))); } } } p->pos=newpos; if(critical_particle) { if(newpos.x>210.0+1e-3) __debugbreak(); if(newpos.x<190.0-1e-3) __debugbreak(); } }
/** * Interprete Expression */ int inter(nodeType *p) { if (!p) {printf("Compile Error(1010): Unknown Type\n");exit(-1);return 0;} switch(p->type) { case typeCon: return p->con.value; case typeOpr: switch(p->opr.oper) { case UMINUS: return -inter(p->opr.op[0]); case '+': return inter(p->opr.op[0]) + inter(p->opr.op[1]); case '-': return inter(p->opr.op[0]) - inter(p->opr.op[1]); case '*': return inter(p->opr.op[0]) * inter(p->opr.op[1]); case '/': return inter(p->opr.op[0]) / inter(p->opr.op[1]); case '%': return inter(p->opr.op[0]) % inter(p->opr.op[1]); case '<': return inter(p->opr.op[0]) < inter(p->opr.op[1]); case '>': return inter(p->opr.op[0]) > inter(p->opr.op[1]); case GE: return inter(p->opr.op[0]) >= inter(p->opr.op[1]); case LE: return inter(p->opr.op[0]) <= inter(p->opr.op[1]); case NE: return inter(p->opr.op[0]) != inter(p->opr.op[1]); case EQ: return inter(p->opr.op[0]) == inter(p->opr.op[1]); case AND: return inter(p->opr.op[0]) && inter(p->opr.op[1]); case OR: return inter(p->opr.op[0]) || inter(p->opr.op[1]); } } return 0; }
void test_intersect() { DoubleVec dv; IntVec iv; const struct { unsigned int pos; double val; } dTbl[] = { { 5, 3.14 }, { 10, 2 }, { 12, 1.4 }, { 100, 2.3 }, { 1000, 4 }, }; const struct { unsigned int pos; int val; } iTbl[] = { { 2, 4 }, { 5, 2 }, { 100, 4 }, { 101, 3}, { 999, 4 }, { 1000, 1 }, { 2000, 3 }, }; const struct { unsigned int pos; double d; int i; } interTbl[] = { { 5, 3.14, 2 }, { 100, 2.3, 4 }, { 1000, 4, 1 } }; for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(dTbl); i++) { dv.push_back(dTbl[i].pos, dTbl[i].val); } for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(iTbl); i++) { iv.push_back(iTbl[i].pos, iTbl[i].val); } int j = 0; for (typename DoubleVec::const_iterator i = dv.begin(), ie = dv.end(); i != ie; ++i) { CYBOZU_TEST_EQUAL(i->pos(), dTbl[j].pos); CYBOZU_TEST_EQUAL(i->val(), dTbl[j].val); j++; } j = 0; for (typename IntVec::const_iterator i = iv.begin(), ie = iv.end(); i != ie; ++i) { CYBOZU_TEST_EQUAL(i->pos(), iTbl[j].pos); CYBOZU_TEST_EQUAL(i->val(), iTbl[j].val); j++; } int sum = 0; for (typename IntVec::const_iterator i = iv.begin(), ie = iv.end(); i != ie; ++i) { sum += i->val() * i->val(); } CYBOZU_TEST_EQUAL(sum, 71); typedef cybozu::nlp::Intersection<DoubleVec, IntVec> InterSection; InterSection inter(dv, iv); j = 0; for (typename InterSection::const_iterator i = inter.begin(), ie = inter.end(); i != ie; ++i) { CYBOZU_TEST_EQUAL(i->pos(), interTbl[j].pos); CYBOZU_TEST_EQUAL(i->val1(), interTbl[j].d); CYBOZU_TEST_EQUAL(i->val2(), interTbl[j].i); j++; } }
virtual void on_draw() { struct font_type { const agg::int8u* font; const char* name; } fonts[] = { { agg::gse4x6, "gse4x6" }, { agg::gse4x8, "gse4x8" }, { agg::gse5x7, "gse5x7" }, { agg::gse5x9, "gse5x9" }, { agg::gse6x9, "gse6x9" }, { agg::gse6x12, "gse6x12" }, { agg::gse7x11, "gse7x11" }, { agg::gse7x11_bold, "gse7x11_bold" }, { agg::gse7x15, "gse7x15" }, { agg::gse7x15_bold, "gse7x15_bold" }, { agg::gse8x16, "gse8x16" }, { agg::gse8x16_bold, "gse8x16_bold" }, { agg::mcs11_prop, "mcs11_prop" }, { agg::mcs11_prop_condensed, "mcs11_prop_condensed" }, { agg::mcs12_prop, "mcs12_prop" }, { agg::mcs13_prop, "mcs13_prop" }, { agg::mcs5x10_mono, "mcs5x10_mono" }, { agg::mcs5x11_mono, "mcs5x11_mono" }, { agg::mcs6x10_mono, "mcs6x10_mono" }, { agg::mcs6x11_mono, "mcs6x11_mono" }, { agg::mcs7x12_mono_high, "mcs7x12_mono_high" }, { agg::mcs7x12_mono_low, "mcs7x12_mono_low" }, { agg::verdana12, "verdana12" }, { agg::verdana12_bold, "verdana12_bold" }, { agg::verdana13, "verdana13" }, { agg::verdana13_bold, "verdana13_bold" }, { agg::verdana14, "verdana14" }, { agg::verdana14_bold, "verdana14_bold" }, { agg::verdana16, "verdana16" }, { agg::verdana16_bold, "verdana16_bold" }, { agg::verdana17, "verdana17" }, { agg::verdana17_bold, "verdana17_bold" }, { agg::verdana18, "verdana18" }, { agg::verdana18_bold, "verdana18_bold" }, 0, 0 }; glyph_gen glyph(0); pixfmt pixf(rbuf_window()); ren_base rb(pixf); rb.clear(agg::rgba(1,1,1)); agg::renderer_raster_htext_solid<ren_base, glyph_gen> rt(rb, glyph); int i; double y = 5; rt.color(agg::rgba(0,0,0)); for(i = 0; fonts[i].font; i++) { char buf[100]; strcpy(buf, "A quick brown fox jumps over the lazy dog 0123456789: "); strcat(buf, fonts[i].name); // Testing "wide-char" unsigned wbuf[100]; unsigned* wp = wbuf; const char* p = buf; while(*p) *wp++ = *(unsigned char*)p++; *wp++ = 0; glyph.font(fonts[i].font); rt.render_text(5, y, wbuf, !flip_y()); y += glyph.height() + 1; } // Rendering raster text with a custom span generator, gradient typedef agg::span_interpolator_linear<> interpolator_type; typedef agg::span_allocator<agg::rgba8> span_alloc_type; typedef agg::span_gradient<agg::rgba8, interpolator_type, gradient_sine_repeat_adaptor<agg::gradient_circle>, agg::gradient_linear_color<agg::rgba8> > span_gen_type; typedef agg::renderer_scanline_aa<ren_base, span_alloc_type, span_gen_type> ren_type; agg::trans_affine mtx; gradient_sine_repeat_adaptor<agg::gradient_circle> grad_func; grad_func.periods(5); agg::gradient_linear_color<agg::rgba8> color_func; color_func.colors(agg::rgba(1.0,0,0), agg::rgba(0,0.5,0)); interpolator_type inter(mtx); span_alloc_type sa; span_gen_type sg(inter, grad_func, color_func, 0, 150.0); ren_type ren(rb, sa, sg); agg::renderer_raster_htext<ren_type, glyph_gen> rt2(ren, glyph); rt2.render_text(5, 465, (unsigned char*)"RADIAL REPEATING GRADIENT: A quick brown fox jumps over the lazy dog", !flip_y()); }
void ZOHTest::testMatrixIntegration4() { std::cout << "===========================================" <<std::endl; std::cout << " ===== ZOH tests start ... ===== " <<std::endl; std::cout << "===========================================" <<std::endl; std::cout << "------- Integrate Orlov's controller -------" <<std::endl; _h = .001; _A->zero(); (*_A)(0, 1) = 1; _x0->zero(); (*_x0)(0) = 1; (*_x0)(1) = 1; SP::SimpleMatrix B(new SimpleMatrix(_n, _n, 0)); SP::SimpleMatrix C(new SimpleMatrix(_n, _n)); (*B)(1, 0) = 2; (*B)(1, 1) = 1; C->eye(); SP::FirstOrderLinearTIR rel(new FirstOrderLinearTIR(C, B)); SP::SimpleMatrix D(new SimpleMatrix(_n, _n, 0)); rel->setDPtr(D); SP::NonSmoothLaw nslaw(new RelayNSL(_n)); _DS.reset(new FirstOrderLinearDS(_x0, _A, _b)); _TD.reset(new TimeDiscretisation(_t0, _h)); _model.reset(new Model(_t0, _T)); SP::Interaction inter(new Interaction(_n, nslaw, rel)); _ZOH.reset(new ZeroOrderHoldOSI()); _model->nonSmoothDynamicalSystem()->insertDynamicalSystem(_DS); _model->nonSmoothDynamicalSystem()->topology()->setOSI(_DS, _ZOH); _model->nonSmoothDynamicalSystem()->link(inter, _DS); _model->nonSmoothDynamicalSystem()->setControlProperty(inter, true); _sim.reset(new TimeStepping(_TD, 1)); _sim->insertIntegrator(_ZOH); SP::Relay osnspb(new Relay()); _sim->insertNonSmoothProblem(osnspb); _model->setSimulation(_sim); _model->initialize(); SimpleMatrix dataPlot((unsigned)ceil((_T - _t0) / _h) + 10, 7); SiconosVector& xProc = *_DS->x(); SiconosVector& lambda = *inter->lambda(0); SiconosVector sampledControl(_n); unsigned int k = 0; dataPlot(0, 0) = _t0; dataPlot(0, 1) = (*_x0)(0); dataPlot(0, 2) = (*_x0)(1); dataPlot(0, 3) = 0; dataPlot(0, 4) = 0; dataPlot(0, 5) = 0; dataPlot(0, 6) = 0; while (_sim->hasNextEvent()) { _sim->computeOneStep(); prod(*B, lambda, sampledControl, true); k++; dataPlot(k, 0) = _sim->nextTime(); dataPlot(k, 1) = xProc(0); dataPlot(k, 2) = xProc(1); dataPlot(k, 3) = sampledControl(0); dataPlot(k, 4) = sampledControl(1); dataPlot(k, 5) = lambda(0); dataPlot(k, 6) = lambda(1); _sim->nextStep(); } dataPlot.resize(k, 7); dataPlot.display(); std::cout <<std::endl <<std::endl; ioMatrix::write("testMatrixIntegration4.dat", "ascii", dataPlot, "noDim"); // Reference Matrix SimpleMatrix dataPlotRef(dataPlot); dataPlotRef.zero(); ioMatrix::read("testMatrixIntegration4.ref", "ascii", dataPlotRef); std::cout << "------- Integration Ok, error = " << (dataPlot - dataPlotRef).normInf() << " -------" <<std::endl; CPPUNIT_ASSERT_EQUAL_MESSAGE("testMatrixExp4 : ", (dataPlot - dataPlotRef).normInf() < _tol, true); }
int Dense3d_MPI::evaluate(Vec srcDen, Vec trgVal) { //begin // CHECK pA(_srcPos!=NULL && _srcNor!=NULL && _trgPos!=NULL && srcDen!=NULL && trgVal!=NULL); //----------------------------------- int dim = this->dim(); int srcDOF = this->srcDOF(); int trgDOF = this->trgDOF(); /* Get global number of source positions */ PetscInt srcGlbNum = procGlbNum(_srcPos); /* Get local number of target positions */ PetscInt trgLclNum = procLclNum(_trgPos); Vec srcAllPos = _srcAllPos; Vec srcAllNor = _srcAllNor; Vec srcAllDen; /* Create scatter context to scatter source densities to all processors */ { VecScatter ctx; pC( VecScatterCreateToAll(srcDen, &ctx, &srcAllDen) ); pC( VecScatterBegin(ctx, srcDen, srcAllDen, INSERT_VALUES, SCATTER_FORWARD) ); pC( VecScatterEnd(ctx, srcDen, srcAllDen, INSERT_VALUES, SCATTER_FORWARD) ); pC( VecScatterDestroy(ctx) ); } Vec trgLclPos = _trgPos; Vec trgLclVal = trgVal; /* Create matrices for source positions, normals, densities. See common/nummat.hpp for * more information on matrices */ double* srcAllPosArr; pC( VecGetArray(srcAllPos, &srcAllPosArr) ); DblNumMat srcAllPosMat(dim, srcGlbNum, false, srcAllPosArr); double* srcAllNorArr; pC( VecGetArray(srcAllNor, &srcAllNorArr) ); DblNumMat srcAllNorMat(dim, srcGlbNum, false, srcAllNorArr); double* srcAllDenArr; pC( VecGetArray(srcAllDen, &srcAllDenArr) ); DblNumVec srcAllDenVec(srcDOF*srcGlbNum, false, srcAllDenArr); /* Create matrices for target positions and values */ double* trgLclPosArr; pC( VecGetArray(trgLclPos, &trgLclPosArr) ); DblNumMat trgLclPosMat(dim, trgLclNum, false, trgLclPosArr); double* trgLclValArr; pC( VecGetArray(trgLclVal, &trgLclValArr) ); DblNumVec trgLclValVec(trgDOF*trgLclNum, false, trgLclValArr); /* Create an evaluation context and evaluate based on kernel type */ DblNumMat inter(trgDOF, srcGlbNum*srcDOF); /* Do multiplication one line of the matrices at a time */ for(int i=0; i<trgLclNum; i++) { DblNumMat onePosMat(dim, 1, false, trgLclPosMat.clmdata(i)); DblNumVec oneValVec(trgDOF, false, trgLclValVec.data()+trgDOF*i); /* Create kernel multiplier context based on kernel type */ pC( _knl.buildKnlIntCtx(srcAllPosMat, srcAllNorMat, onePosMat, inter) ); /* Computes 1.0*inter*srcAllDenVec + 0.0*oneValVec = oneValVec */ pC( dgemv(1.0, inter, srcAllDenVec, 0.0, oneValVec) ); } pC( VecRestoreArray(srcAllPos, &srcAllPosArr) ); pC( VecRestoreArray(srcAllNor, &srcAllNorArr) ); pC( VecRestoreArray(srcAllDen, &srcAllDenArr) ); pC( VecRestoreArray(trgLclPos, &trgLclPosArr) ); pC( VecRestoreArray(trgLclVal, &trgLclValArr) ); pC( VecDestroy(srcAllDen) ); return(0); }
ExecStatus Match<View>::propagate(Space& home, const ModEventDelta&) { int xs_size = xs.size(); bool loopFlag; do { loopFlag = false; // Order int vars in xs GECODE_ME_CHECK(xs[0].gq(home,x0.lubMin())); for (int i=xs_size-1; i--; ) { GECODE_ME_CHECK_MODIFIED(loopFlag, xs[i+1].gq(home,xs[i].min() + 1)); } GECODE_ME_CHECK_MODIFIED(loopFlag, xs[xs_size-1].lq(home,x0.lubMax())); for (int i=xs_size-2; i--; ) { GECODE_ME_CHECK_MODIFIED(loopFlag, xs[i].lq(home,xs[i+1].max() - 1)); } // if y from xs is assigned, add to glb(x0) for (int i=xs_size; i--; ) { if (xs[i].assigned()) { GECODE_ME_CHECK_MODIFIED(loopFlag, x0.include(home,xs[i].val())); } } // intersect every y in xs with lub(x0) for (int i=xs_size; i--; ) { LubRanges<View> ub(x0); GECODE_ME_CHECK_MODIFIED(loopFlag, xs[i].inter_r(home,ub,false)); } // remove gaps between vars in xs from lub(x0) GECODE_ME_CHECK_MODIFIED(loopFlag, x0.exclude(home,Limits::min,xs[0].min()-1)); GECODE_ME_CHECK_MODIFIED(loopFlag, x0.exclude(home,xs[xs_size-1].max()+1, Limits::max)); for (int i=xs_size-1; i--; ) { int start = xs[i].max() + 1; int end = xs[i+1].min() - 1; if (start<=end) { GECODE_ME_CHECK_MODIFIED(loopFlag, x0.exclude(home,start,end)); } } // try to assign vars in xs from glb(x0) if (x0.glbSize()>0) { LubRanges<View> ub(x0); Iter::Ranges::ToValues<LubRanges<View> > ubv(ub); GlbRanges<View> lb(x0); Iter::Ranges::ToValues<GlbRanges<View> > lbv(lb); int i=0; for (; ubv() && lbv() && ubv.val()==lbv.val(); ++ubv, ++lbv, i++) { GECODE_ME_CHECK_MODIFIED(loopFlag, xs[i].eq(home,lbv.val())); } if (i<xs_size-1 && x0.lubMax()==x0.glbMax()) { LubRanges<View> lbx0(x0); GlbRanges<View> ubx0(x0); Iter::Ranges::Inter<LubRanges<View>,GlbRanges<View> > inter(lbx0, ubx0); int to = x0.glbMax(); int from = to; while (inter()) { from = inter.min(); ++inter; } int i=xs_size-1; for (int j=to; j>=from;j--,i--) { GECODE_ME_CHECK_MODIFIED(loopFlag, xs[i].eq(home,j)); } } } } while (loopFlag); for (int i=xs_size; i--; ) if (!xs[i].assigned()) return ES_FIX; return home.ES_SUBSUMED(*this); }
/** * Returns whether or not the given point p belongs to the face defined * by the vector points. */ static bool onFace(gml::Point3D const & p, std::vector < gml::Point3D > const & points) { std::vector<double> plane; // double dist= 0.0; std::vector <int> samePoints; std::vector < gml::Point3D > allPoints; // Firstly copy of the vector points in the vector // samePoints, if all the points are different for(int i=0; i<(int)points.size(); i++) { for(int j=i+1; j<(int)points.size();j++) { if (isTheSame(points[i], points[j])) { samePoints.push_back(i); } } } // Construction of the vector allPoints, with only the different points bool diff=true; for (int i=0; i<(int)points.size();i++) { int j=0; while (j<(int)samePoints.size() && diff) { if (i==samePoints[j]) { diff = false; } else { j++; } } if (diff) { allPoints.push_back(points[i]); } diff = true; } // 1) Check if the vector allPoints is a really a plan plane = definePlane(allPoints); if( plane.empty() ) { return false; } // 2) Check if the current point is on the plan if( ! onPlane(p, allPoints) ) { return false; } // 3) Check if the point belows to one of edge of the face for (int i=0 ; i<(int)allPoints.size() ; i++) { int next = i+1; if (next == (int)allPoints.size()) { next = 0; } double t; if (isOnEdge(p, allPoints[i], allPoints[next], &t)) { return true; } } // 4) Computation of a line // double diffx = allPoints[0][0] - allPoints[1][0]; // double diffy = allPoints[0][1] - allPoints[1][1]; // double diffz = allPoints[0][2] - allPoints[1][2]; gml::Vector3D diffVector = allPoints[0] - allPoints[1]; gml::Point3D newPoint = p + diffVector; // newPoint[0] = p[0] + diffx; // newPoint[1] = p[1] + diffy; // newPoint[2] = p[2] + diffz; // 5) Check if the line cut or not the plan int nbCut = 0; for (int i=0 ; i<(int)allPoints.size() ; i++) { int next = i+1; if (next == (int)allPoints.size()) { next = 0; } std::vector< gml::Point3D > newPlane; newPlane.push_back(newPoint); newPlane.push_back(allPoints[i]); newPlane.push_back(allPoints[next]); double t1, t2; int valueCut = inter(p, newPlane, &t1, &t2); if (valueCut > 0) { if (isGreaterOrEqual(t1, 0) && isGreaterOrEqual(t2, 0) && isLesserOrEqual(t2, 1)) { nbCut++; } } if (nbCut == 1) { return true; } } return false; } //end of method on face