Shapes* Shapes::clone() { Shapes *newShapes = new Shapes(); newShapes->setMarkers(markers); newShapes->setHierarchy(hierarchy); newShapes->setContours(contours); return newShapes; }
int main() { Shapes shapes; shapes.push_back(std::make_shared<Rectangle>(1,2)); shapes.push_back(std::make_shared<Rectangle>(3,4)); shapes.push_back(std::make_shared<Square>(2)); shapes.push_back(std::make_shared<Square>(3)); GeometricCalculator geometricCalculator(shapes); std::cout<<"summed area is equal: " << geometricCalculator.calculateSumArea() << std::endl; }
int main(void) { char* g_image_filename="images/lena.jpg"; Mat src = imread( g_image_filename, 1 ); if (src.empty()) { std::cout << "!!! Failed imread()\n ./colors <image filename>" << std::endl; return -1; } DrawWindow WIPC = DrawWindow(src.cols,src.rows,"IPC countours"); // w,h Shapes SIPC; ImageParserContours IPC; if (1) { IPC.setMinContourLength(5); IPC.setCannyThreshold(50); IPC.parseImage(src); IPC.useRandomColors(1); //IPC.draw(); // IPC.defineShapes(&SIPC); //IPC.printImageData(1); WIPC.clearWindow(230,230,230); // default background is white SIPC.drawAll(&WIPC); WIPC.show(); } DrawWindow WIPK = DrawWindow(src.cols,src.rows,"IPK pixel regions"); // w,h Shapes SIPK; ImageParserKmeans IPK; if (1) { IPK.setMinPixelsInRegion(5); IPK.parseImage(src); IPK.useRandomColors(1); IPK.draw(); IPK.defineShapes(&SIPK); // IPC.printImageData(1); WIPK.clearWindow(230,230,230); // default background is white SIPK.drawAll(&WIPK); WIPK.show(); } while (1) { int k = waitKey(33); if (k==27) { // Esc key to stop return(0); } } return 0; }
//---------------------------------------------------------------------------- init // OpenGL initialization void init() { calcUVN(VPN, VUP); program = InitShader( "/home/GONZAGA/rdraper/Desktop/Ada/Lrdraperjhaddock2FinalProj/vshader53.glsl", "//home/GONZAGA/rdraper/Desktop/Ada/Lrdraperjhaddock2FinalProj/fshader53.glsl" ); // gouraud shading glUseProgram( program ); // Uniform variables: color and viewing parameters model_color = glGetUniformLocation( program, "model_color" ); model_view = glGetUniformLocation( program, "model_view" ); projection = glGetUniformLocation( program, "projection" ); lightSetUp(); myBasketball.createVAO(program); shapes.createVAO(program); land.createVAO(program); glUniform4fv( model_color, 1,vec4(1,1,1,1) ); // set color to white initially glLineWidth(1); glEnable( GL_DEPTH_TEST ); glClearColor( 0.5, 0.5, 0.5, 1.0 ); printControls(); cout << "Shooter Pause: On -- press middle mouse button to toggle off" << endl; }
int main() { /* Square squ1; Triangle tri1; Shapes* ptr1 = &squ1; Shapes* ptr2 = &tri1; ptr1->set_values(2, 4); ptr2->set_values(5, 10); */ // Because of polymorphism every derived class can be made by pointers Shapes* rect = new Square(5, 4); Shapes* tria = new Triangle(5, 4); rect->printarea(); tria->printarea(); delete rect; delete tria; return 0; }
BodyCreator::Shapes BodyCreator::m_ProcessConvex(const Shape& points) { assert(points.size() > b2_maxPolygonVertices); Shapes output; const sf::Uint16 maxVerts = b2_maxPolygonVertices - 2u; const sf::Uint16 shapeCount = static_cast<sf::Uint16>(std::floor(points.size() / maxVerts)); const sf::Uint16 s = points.size(); for (auto i = 0u; i <= shapeCount; i++) { Shape shape; sf::Uint16 total = 0u; for (auto j = 0u; j < maxVerts; j++) { sf::Uint16 index = i * maxVerts + j; if (i) index--; if (index < s) shape.push_back(points[index]); else break; } output.push_back(shape); } //join ends Shape& shape = output[output.size() - 2]; output.back().push_back(output.front().front()); output.back().push_back(shape.back()); return output; }
int main(int argc, char **argv) { int diff, old_score, new_score; struct timeval start; gettimeofday(&start,NULL); Shapes s; s.readFile(argc, argv); s.buildConflictArray(); Graphs g; g.buildConflictGraph(s.getShapes()); s.findBoundingBox(); Windows w; w.createWindow(); w.countArea(s.getShapes(), g.getGraphs()); g.countTotalColorDiff(); Calculate c; //c.printResult(s.getShapes(), g.getGraphs(), w.getWindows(), argc, argv); //printf("real score : %.2f\n\n\n", c.real_score(w.getWindows())); //std::vector<Graph> &gg = g.getGraphs(); //c.changeGraphColor(w.getWindows(), g.getGraphs()[0]); //c.changeGraphColor(w.getWindows(), g.getGraphs()[0]); //c.changeGraphColor(w.getWindows(), g.getGraphs()[2]); c.initial_total_color_diff(&g, g.getGraphs(), w.getWindows()); //c.printResult(s.getShapes(), g.getGraphs(), w.getWindows(), argc, argv); //printf("real score : %.2f\n\n\n", c.real_score(w.getWindows())); for (int group_id = 0; group_id < c.group_size; group_id++) { c.iterative_sol(g.getGraphs(), w.getWindows(), group_id); } //printf("real score : %.2f\n\n\n", c.real_score(w.getWindows())); c.simulatedAnnealing(g.getGraphs(), w.getWindows(), start, argv[1]); for (int group_id = 0; group_id < c.group_size; group_id++) { c.iterative_sol(g.getGraphs(), w.getWindows(), group_id); } c.printResult(s.getShapes(), g.getGraphs(), w.getWindows(), argc, argv); printf("real score : %.2f\n\n\n", c.real_score(w.getWindows())); return 0; }
void Scene::AddTexturedObject(const std::string fname, Material* material, Shapes &objects, const std::string textName, const Point &ofs) const { size_t index = Shape::GetUniqueID(); // —читывание меша из файла L3DS *l3ds = new L3DS(fname.c_str()); if(!l3ds || !l3ds->GetMeshCount()) throw Error("Error in loading extern files"); for(int i = 0; i<l3ds->GetMeshCount(); i++) { LMesh *mesh = l3ds->GetMesh(i); Texture *texture = new Texture(textName.c_str()); for(int j = 0; j<mesh->GetTriangleCount(); j++) { LTriangle tr = mesh->GetTriangle(j); Point a(mesh->GetVertex(tr.a).x, mesh->GetVertex(tr.a).y, mesh->GetVertex(tr.a).z); Point b(mesh->GetVertex(tr.b).x, mesh->GetVertex(tr.b).y, mesh->GetVertex(tr.b).z); Point c(mesh->GetVertex(tr.c).x, mesh->GetVertex(tr.c).y, mesh->GetVertex(tr.c).z); TextureCoords tA(mesh->GetUV(tr.a).u, mesh->GetUV(tr.a).v); TextureCoords tB(mesh->GetUV(tr.b).u, mesh->GetUV(tr.b).v); TextureCoords tC(mesh->GetUV(tr.c).u, mesh->GetUV(tr.c).v); tA.InvertU(); tB.InvertU(); tC.InvertU(); tA*=8; tB*=8; tC*=8; if (Triangle::IsValidTrangle(a,b,c)) objects.push_back(new Triangle(a-ofs, b-ofs, c-ofs, material, index, texture, tA, tB, tC)); } } }
void Scene::AddObject(const std::string& fname,Material* material, Shapes &objects, const Point &ofs) const { size_t index = Shape::GetUniqueID(); // —читывание меша из файла L3DS *l3ds = new L3DS(fname.c_str()); if(!l3ds || !l3ds->GetMeshCount()) throw Error("Error in loading extern files"); for(int i = 0; i<l3ds->GetMeshCount(); i++) { LMesh *mesh = l3ds->GetMesh(i); for(int j = 0; j<mesh->GetTriangleCount(); j++) { LTriangle tr = mesh->GetTriangle(j); Point a(mesh->GetVertex(tr.a).x, mesh->GetVertex(tr.a).y, mesh->GetVertex(tr.a).z); Point b(mesh->GetVertex(tr.b).x, mesh->GetVertex(tr.b).y, mesh->GetVertex(tr.b).z); Point c(mesh->GetVertex(tr.c).x, mesh->GetVertex(tr.c).y, mesh->GetVertex(tr.c).z); if (Triangle::IsValidTrangle(a,b,c)) objects.push_back(new Triangle(a-ofs, b-ofs, c-ofs, material, index)); } } }
bool DetectPolygons::processFrameContainer(BaseFrameContainer *frm, BaseFrameSource *frameSource) { Shapes* shapes = frm->getShapes(); std::vector<Point> approxCurve; unsigned int size = 0; ///for each contour, analyze if it is a paralelepiped likely to be the marker for (unsigned int i=0;i<shapes->getContours().size();i++) { unsigned int contourSize = shapes->getContours()[i].size(); //check it is a possible element by first checking is has enough points if (contourSize>(unsigned int)(frm->getFrame()->getMat().cols /15)) { //approximate to a polygon - 1. limit slozitosti (pocet bodu krat cislo vs konstanta), 2. uzavreny double complexity = double(contourSize)*complexityKoef; complexity = complexity > maxComplexity ? maxComplexity : (complexity < minComplexity ? minComplexity : complexity); cv::approxPolyDP( cv::Mat (shapes->getContours()[i]),approxCurve , complexity , onlyClosed); size = approxCurve.size(); unsigned int one, two; if (approxCurve.size() >= 3) { // remove inline points for (unsigned int i = 0; i < size; i++) { one = (i + 1)%size; two = (i + 2)%size; // rozdil smernic double x1 = approxCurve[i].x, y1 = approxCurve[i].y, x2 = approxCurve[one].x, y2 = approxCurve[one].y, x3 = approxCurve[two].x, y3 = approxCurve[two].y; float k = std::abs(((y2-y1)/(x2-x1)) - ((y3-y1)/(x3-x1))); float d1 = std::sqrt((float) (approxCurve[i].x-approxCurve[one].x)*(approxCurve[i].x-approxCurve[one].x) + (approxCurve[i].y-approxCurve[one].y)*(approxCurve[i].y-approxCurve[one].y)); float d2 = std::sqrt((float) (approxCurve[i].x-approxCurve[two].x)*(approxCurve[i].x-approxCurve[two].x) + (approxCurve[i].y-approxCurve[two].y)*(approxCurve[i].y-approxCurve[two].y)); // if angle is too small or points are too close if (k < 0.2 || d1 < 0.04*d2) { approxCurve.erase(approxCurve.begin()+one); size--; } } } if (size >= minimalPolygonLines && size <= maximalPolygonLines) { //and is convex if (!onlyConvex || cv::isContourConvex(Mat (approxCurve))) { float minDist=1e10; if (minDistance > 0) { for (int i=0;i<size;i++) { float d= std::sqrt((float) (approxCurve[i].x-approxCurve[(i+1)%size].x)*(approxCurve[i].x-approxCurve[(i+1)%size].x) + (approxCurve[i].y-approxCurve[(i+1)%size].y)*(approxCurve[i].y-approxCurve[(i+1)%size].y)); if (d<minDist) minDist=d; } } if (minDist>=minDistance) { shapes->getMarkers().push_back(Marker()); for (unsigned int i=0;i<size;i++) { shapes->getMarkers().back().push_back( Point2f(approxCurve[i].x,approxCurve[i].y)); } } } } } } /// remove these elements whise corners are too close to each other //first detect candidates size = shapes->getMarkers().size(); if (minimalPolygonLines==4 && maximalPolygonLines == 4) { for (unsigned int i=0;i<shapes->getMarkers().size();i++) { //trace a line between the first and second point. //if the thrid point is at the right side, then the points are anti-clockwise double dx1 = shapes->getMarkers()[i][1].x - shapes->getMarkers()[i][0].x; double dy1 = shapes->getMarkers()[i][1].y - shapes->getMarkers()[i][0].y; double dx2 = shapes->getMarkers()[i][2].x - shapes->getMarkers()[i][0].x; double dy2 = shapes->getMarkers()[i][2].y - shapes->getMarkers()[i][0].y; double o = (dx1*dy2)-(dy1*dx2); if (o < 0.0) //if the third point is in the left side, then sort in anti-clockwise order { swap(shapes->getMarkers()[i][1],shapes->getMarkers()[i][3]); } } } vector<pair<int,int> > TooNearCandidates; for (unsigned int i=0;i < size;i++) { // cout<<"Marker i="<<i<<MarkerCanditates[i]<<endl; //calculate the average distance of each corner to the nearest corner of the other marker candidate for (unsigned int j=i+1;j<size;j++) { unsigned int vertexCount = shapes->getMarkers()[i].size(); if (vertexCount == shapes->getMarkers()[j].size()) { float dist=0; for (unsigned int c=0;c<vertexCount;c++) dist+= std::sqrt( (shapes->getMarkers()[i][c].x-shapes->getMarkers()[j][c].x)*(shapes->getMarkers()[i][c].x-shapes->getMarkers()[j][c].x)+(shapes->getMarkers()[i][c].y-shapes->getMarkers()[j][c].y)*(shapes->getMarkers()[i][c].y-shapes->getMarkers()[j][c].y)); dist/=vertexCount; //if distance is too small if (dist< 14) { TooNearCandidates.push_back(pair<int,int>(i,j)); } } } } //mark for removal the element of the pair with smaller perimeter vector<bool> toRemove (shapes->getMarkers().size(),false); for (unsigned int i=0;i<TooNearCandidates.size();i++) { if ( perimeter(shapes->getMarkers()[TooNearCandidates[i].first ])>perimeter(shapes->getMarkers()[ TooNearCandidates[i].second] )) toRemove[TooNearCandidates[i].second]=true; else toRemove[TooNearCandidates[i].first]=true; } //remove the invalid ones removeElements(shapes->getMarkers(),toRemove); return true; }
BodyCreator::Shapes BodyCreator::m_ProcessConcave(const Shape& points) { ShapeQueue q; q.push(points); Shapes output; while (!q.empty()) { const auto& shape = q.front(); sf::Uint16 s = shape.size(); bool convex = true; for (auto i = 0u; i < s; i++) { sf::Uint16 i1 = i; sf::Uint16 i2 = (i < s - 1u) ? i + 1u : i + 1u - s; sf::Uint16 i3 = (i < s - 2u) ? i + 2u : i + 2u - s; sf::Vector2f p1 = shape[i1]; sf::Vector2f p2 = shape[i2]; sf::Vector2f p3 = shape[i3]; float direction = m_GetWinding(p1, p2, p3); if (direction < 0.f) { convex = false; float minLen = FLT_MAX; sf::Int16 j1 = 0; sf::Int16 j2 = 0; sf::Vector2f v1; sf::Vector2f v2; sf::Int16 h = 0; sf::Int16 k = 0; sf::Vector2f hitPoint; for (auto j = 0u; j < s; j++) { if (j != i1 && j != i2) { j1 = j; j2 = (j < s - 1u) ? j + 1u : 0; v1 = shape[j1]; v2 = shape[j2]; sf::Vector2f hp = m_HitPoint(p1, p2, v1, v2); bool b1 = m_OnSeg(p2, p1, hp); bool b2 = m_OnSeg(hp, v1, v2); if (b1 && b2) { sf::Vector2f dist = p2 - hp; float t = Helpers::Vectors::dot(dist, dist); //aka length squared if (t < minLen) { h = j1; k = j2; hitPoint = hp; minLen = t; } } } } assert(minLen != FLT_MAX); Shape shape1; Shape shape2; j1 = h; j2 = k; v1 = shape[j1]; v2 = shape[j2]; if (!m_PointsMatch(hitPoint, v2)) shape1.push_back(hitPoint); if (!m_PointsMatch(hitPoint, v1)) shape2.push_back(hitPoint); h = -1; k = i1; while (true) { if (k != j2) { shape1.push_back(shape[k]); } else { assert(h >= 0 && h < s); if (!m_OnSeg(v2, shape[h], p1)) { shape1.push_back(shape[k]); } break; } h = k; if ((k - 1) < 0) { k = s - 1; } else { k--; } } std::reverse(shape1.begin(), shape1.end()); h = -1; k = i2; while (true) { if (k != j1) { shape2.push_back(shape[k]); } else { assert(h >= 0 && h < s); if ((k == j1) && !m_OnSeg(v1, shape[h], p2)) { shape2.push_back(shape[k]); } break; } h = k; if (k + 1 > s - 1) { k = 0; } else { k++; } } q.push(shape1); q.push(shape2); q.pop(); break; } } if (convex) { output.push_back(q.front()); q.pop(); } } return output; }
LRESULT CALLBACK EXPORT AWClientWndProc ( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { LRESULT lRet; BOOL fHandled; Window* pWnd = (Window*)GetWindowLong(hwnd, I_GWL_WINDOW); Shapes* pShapes = (Shapes*)GetWindowLong(hwnd, I_GWL_SHAPES); switch (uMsg) { case WM_CREATE: pWnd = (Window*)(((CREATESTRUCT*)lParam)->lpCreateParams); pShapes = (pWnd->GetLayout())->Shapes(); SetWindowLong(hwnd, I_GWL_WINDOW, (long)pWnd); SetWindowLong(hwnd, I_GWL_SHAPES, (long)pShapes); fHandled = TRUE; lRet = 0L; break; // the following messages are processed by the Shapes class case WM_MOUSEMOVE: pShapes->MouseMove(pWnd, hwnd, (int)wParam, (short)LOWORD(lParam), (short)HIWORD(lParam)); fHandled = TRUE; lRet = 0L; break; case WM_LBUTTONDOWN: pShapes->MouseLButtonDown(pWnd, hwnd, (int)wParam, (short)LOWORD(lParam), (short)HIWORD(lParam)); fHandled = TRUE; lRet = 0L; break; case WM_LBUTTONDBLCLK: pShapes->MouseLButtonDblClk(pWnd, hwnd, (int)wParam, (short)LOWORD(lParam), (short)HIWORD(lParam)); fHandled = TRUE; lRet = 0L; break; case WM_LBUTTONUP: pShapes->MouseLButtonUp(pWnd, hwnd, (int)wParam, (short)LOWORD(lParam), (short)HIWORD(lParam)); fHandled = TRUE; lRet = 0L; break; case WM_RBUTTONDOWN: pShapes->MouseRButtonDown(pWnd, hwnd, (int)wParam, (short)LOWORD(lParam), (short)HIWORD(lParam)); fHandled = TRUE; lRet = 0L; break; case WM_KEYDOWN: pShapes->KeyDown(pWnd, hwnd, (int)wParam, lParam); fHandled = TRUE; lRet = 0L; break; case WM_KEYUP: pShapes->KeyUp(pWnd, hwnd, (int)wParam, lParam); fHandled = TRUE; lRet = 0L; break; // the following messages are handled by the Window class case WM_ERASEBKGND: pWnd->EraseBackground((HDC)wParam); fHandled = TRUE; lRet = 0L; break; case WM_PAINT: (pWnd->Items())->Paint(); fHandled = TRUE; lRet = 0L; break; case WM_HSCROLL: HANDLE_WM_HSCROLL(hwnd, wParam, lParam, (pWnd->Items())->HScroll); fHandled = TRUE; lRet = 0L; break; case WM_VSCROLL: HANDLE_WM_VSCROLL(hwnd, wParam, lParam, (pWnd->Items())->VScroll); fHandled = TRUE; lRet = 0L; break; case WM_DELETEITEM: case WM_COMPAREITEM: case WM_MEASUREITEM: case WM_DRAWITEM: #if defined(__FLAT__) case WM_CTLCOLORBTN: case WM_CTLCOLORDLG: case WM_CTLCOLOREDIT: case WM_CTLCOLORLISTBOX: case WM_CTLCOLORSCROLLBAR: case WM_CTLCOLORSTATIC: #else case WM_CTLCOLOR: #endif lRet = (pWnd->Items())->ParentNotified(hwnd, uMsg, wParam, lParam); fHandled = TRUE; break; default: fHandled = FALSE; break; } return fHandled ? lRet : DefWindowProc(hwnd, uMsg, wParam, lParam); }
int main(int argc, char* argv[]){ // declarations Fitter fitter; map<string, Dataset> datasets; vector<Event> eventvec_datamc; vector<Event> eventvec_train; vector<Event> eventvec_test; map< string, map<string, TH1D*> > hists_all_; map< string, map<string, TH1D*> > hists_train_; map< string, map<string, TH1D*> > hists_test_; // output fit results int run_number=-1; int fitstatus=-1; double mt=0, mt_err=0; double kmbl=0, kmbl_err=0; double k220=0, k220_err=0; double mcmass=0; double fitchi2=0; double tsig_mbl_chi2 [8] = {0}; double tbkg_mbl_chi2 [8] = {0}; TTree *tree = new TTree("FitResults", "FitResults"); tree->Branch("runNumber", &run_number); tree->Branch("fitStatus", &fitstatus); tree->Branch("mt", &mt); tree->Branch("mt_err", &mt_err); tree->Branch("kmbl", &kmbl); tree->Branch("kbml_err", &kmbl_err); tree->Branch("k220", &k220); tree->Branch("k220_err", &k220_err); tree->Branch("mcmass", &mcmass); tree->Branch("fitchi2", &fitchi2); tree->Branch("tsig_mbl_chi2", tsig_mbl_chi2, "tsig_mbl_chi2[8]/D"); tree->Branch("tbkg_mbl_chi2", tbkg_mbl_chi2, "tbkg_mbl_chi2[8]/D"); // option flags int c; int do_fit = 0; int do_diagnostics = 0; int use_data = 0; float masspnt = 0; int do_bootstrap = 0; int do_templates = 0; int do_learnparams = 0; int do_mbl = 0; int do_mt2 = 0; double fracevts = -1; struct option longopts[] = { { "run_number", required_argument, 0, 'n' }, { "fit", no_argument, &do_fit, 'f' }, { "diagnostics", no_argument, &do_diagnostics, 'd' }, { "templates", no_argument, &do_templates, 'e' }, { "learnparams", no_argument, &do_learnparams, 'x' }, { "data", no_argument, &use_data, 'a' }, { "profile", no_argument, 0, 'p' }, { "masspnt", required_argument, 0, 'm' }, { "bootstrap", no_argument, &do_bootstrap, 'o' }, { "fracevts", required_argument, 0, 'c' }, // If the lmbl flag is not entered, lengthscale_mbl has default value -1. // This instructs the code to not use mbl in the fit. // The same goes for each other kinematic variable. { "mbl", no_argument, &do_mbl, 'b' }, { "mt2", no_argument, &do_mt2, 't' }, { "help", no_argument, NULL, 'h' }, { 0, 0, 0, 0 } }; while( (c = getopt_long(argc, argv, "fdexahponbtm:c:", longopts, NULL)) != -1 ) { switch(c) { case 'n' : run_number = atoi(optarg); break; case 'f' : do_fit = 1; break; case 'd' : do_diagnostics = 1; break; case 'e' : do_templates = 1; break; case 'x' : do_learnparams = 1; break; case 'a' : use_data = 1; break; case 'm' : masspnt = atof(optarg); break; case 'p' : fitter.compute_profile = true; break; case 'o' : do_bootstrap = 1; break; case 'c' : fracevts = atof(optarg); break; case 'b' : do_mbl = true; break; case 't' : do_mt2 = true; break; case 'h' : print_usage(); return -1; break; case 0: /* getopt_long() set a variable, just keep going */ break; case ':': /* missing option argument */ fprintf(stderr, "%s: option `-%c' requires an argument\n", argv[0], optopt); return -1; case '?': default: /* invalid option */ fprintf(stderr, "%s: option `-%c' is invalid: ignored\n", argv[0], optopt); print_usage(); return -1; } } fitter.dists["mbl"].activate = do_mbl; fitter.dists["mt2_220_nomatchmbl"].activate = do_mt2; // Check that at least one kinematic variable's lengthscale has been entered. // Any additional distributions need to be added here if (!(fitter.dists["mbl"].activate) and !(fitter.dists["mt2_220_nomatchmbl"].activate) and do_fit == 1){ std::cout << "At least one variable needed to do fit. Input at least one lengthscale." << std::endl; print_usage(); return -1; } fitter.LoadDatasets( datasets ); // for event counting map<string, int> datacount; // random number seed for bootstrapping (turns on when nonzero) int randseed = 0; if( do_bootstrap ) randseed = run_number+1+10E6; cout << "\nLoading datasets" << endl; for(map<string, Dataset>::iterator it = datasets.begin(); it != datasets.end(); it++){ string name = it->first; Dataset *dat = &(it->second); datacount[name] = 0; TFile file( (dat->path+dat->file).c_str() ); TTree *trees = (TTree*)file.Get("RealData"); cout << setiosflags(ios::left); cout << "... " << setw(25) << name << ": " << trees->GetEntries() << " events" << endl; if( do_diagnostics or use_data ){ fitter.ReadNtuple( dat->path+dat->file, name, dat->mc_xsec/dat->mc_nevts, "RealData", eventvec_datamc, 0, 0, -1 ); } // events for training and testing if( name.compare("data") != 0 ){ if( use_data ){ // train on full mc set fitter.ReadNtuple( dat->path+dat->file, name, dat->mc_xsec/dat->mc_nevts, "RealData", eventvec_train, 0, randseed, -1 ); }else{ fitter.ReadNtuple( dat->path+dat->file, name, dat->mc_xsec/dat->mc_nevts, "RealData", eventvec_train, 1, randseed, -1 ); fitter.ReadNtuple( dat->path+dat->file, name, dat->mc_xsec/dat->mc_nevts, "RealData", eventvec_test, 2, randseed, fracevts ); } } } // data/mc plots, kinematic distributions fitter.GetVariables( eventvec_datamc ); fitter.GetVariables( eventvec_train ); fitter.GetVariables( eventvec_test ); fitter.DeclareHists( hists_train_, "train" ); fitter.FillHists( hists_train_, eventvec_train ); fitter.DeclareHists( hists_test_, "test" ); fitter.FillHists( hists_test_, eventvec_test ); if( do_diagnostics ){ fitter.DeclareHists( hists_all_, "all" ); fitter.FillHists( hists_all_, eventvec_datamc ); fitter.PrintHists( hists_all_ ); } if( do_fit ){ vector<Event> eventvec_fit; vector<Event> eventvec_fit_bkgcontrol; map< string, map<string, TH1D*> > hists_fit_; map< string, map<string, TH1D*> > hists_fit_bkgcontrol_; if( use_data ){ // added 220 distribution to the data fit too, but haven't tested it // // turn this feature off for now -- will need to clean up later. // /* cout << "REMINDER: EVENT WEIGHTS IN MC" << endl; for(vector<Event>::iterator ev = eventvec_datamc.begin(); ev < eventvec_datamc.end();ev++){ if( ev->type.find("data") != string::npos ){ if( ev->type.find("bkgcontrol") == string::npos ){ eventvec_fit.push_back(*ev); }else{ eventvec_fit_bkgcontrol.push_back(*ev); } } } // flag events to be fitted for( vector<Event>::iterator ev = eventvec_fit.begin(); ev < eventvec_fit.end(); ev++){ ev->fit_event = true; for(map<string, int>::iterator it = datacount.begin(); it != datacount.end(); it++){ if( ev->process.compare(it->first) == 0 ) datacount[it->first]+=1; } } for( vector<Event>::iterator ev = eventvec_fit_bkgcontrol.begin(); ev < eventvec_fit_bkgcontrol.end(); ev++){ ev->fit_event = true; for(map<string, int>::iterator it = datacount.begin(); it != datacount.end(); it++){ if( ev->process.compare(it->first) == 0 ) datacount[it->first]+=1; } } cout << "Fit event count: " << endl; cout << setiosflags(ios::left); for(map<string, int>::iterator it = datacount.begin(); it != datacount.end(); it++){ cout << "... " << setw(25) << it->first << ": " << it->second << " events" << endl; } fitter.DeclareHists( hists_fit_, "fit" ); fitter.FillHists( hists_fit_, eventvec_fit, true ); fitter.DeclareHists( hists_fit_bkgcontrol_, "fit_bkgcontrol" ); fitter.FillHists( hists_fit_bkgcontrol_, eventvec_fit_bkgcontrol, true ); double wgt=0; for(vector<Event>::iterator ev = eventvec_fit.begin(); ev < eventvec_fit.end(); ev++){ wgt += ev->weight; } cout << "wgt = " << wgt << endl; // do GP training cout << "Training GP." << endl; // GP training for mbl if ( lengthscale_mbl != -1){ Shapes * fptr = new Shapes( "mbl", fitter.gplength_mbl, fitter.gplength_mt_mbl, fitter.lbnd, fitter.rbnd ); fptr->TrainGP( hists_train_ ); fitter.aGPsig.ResizeTo( fptr->aGPsig.GetNoElements() ); fitter.aGPsig = fptr->aGPsig; fitter.aGPbkg.ResizeTo( fptr->aGPbkg.GetNoElements() ); fitter.aGPbkg = fptr->aGPbkg; } // GP training for 220 if ( lengthscale_220 != -1){ Shapes * fptr220 = new Shapes( "mt2_220_nomatchmbl", fitter.gplength_220, fitter.gplength_mt_220, fitter.lbnd, fitter.rbnd ); fptr220->TrainGP( hists_train_ ); fitter.aGPsig220.ResizeTo( fptr220->aGPsig.GetNoElements() ); fitter.aGPsig220 = fptr220->aGPsig; fitter.aGPbkg220.ResizeTo( fptr220->aGPbkg.GetNoElements() ); fitter.aGPbkg220 = fptr220->aGPbkg; } // events for fitting, hists for training fitter.RunMinimizer( eventvec_fit ); fitter.PlotResults( hists_fit_ ); // plot fitted events // fill results tree mcmass = 0; fitstatus = fitter.gMinuit->Status(); const double *par = fitter.gMinuit->X(); const double *par_err = fitter.gMinuit->Errors(); mt = par[0]; kmbl = par[1]; k220 = par[2]; mt_err = par_err[0]; kmbl_err = par_err[1]; k220_err = par_err[2]; fitchi2 = fitter.fitchi2; gplength_mbl = lengthscale_mbl; gplength_220 = lengthscale_220; gplength_mt_mbl = lengthscale_mt_mbl; gplength_mt_220 = lengthscale_mt_220; // TODO //tree->Fill(); eventvec_fit.clear(); eventvec_fit_bkgcontrol.clear(); fitter.DeleteHists( hists_fit_ ); fitter.DeleteHists( hists_fit_bkgcontrol_ ); */ }else{ // loop over mc masses double masspnts [] = {161.5,163.5,166.5,169.5,172.5,175.5,178.5,181.5}; for(int i=0; i < 8; i++){ double mass = masspnts[i]; // masspoint from command line if( masspnt != 0 ){ bool check = false; for(int j=0; j < 8; j++){ if( masspnts[j] == masspnt ) check = true; } if(check){ mass = masspnt; i = 7; }else{ cout << "masspoint " << masspnt << " not found!" << endl; return -1; } } cout << "############# Fitting Masspoint " << mass << " ###############" << endl; stringstream dstr; dstr << floor(mass); string dname = "ttbar"+dstr.str(); // load events to be fitted for(vector<Event>::iterator ev = eventvec_test.begin(); ev < eventvec_test.end(); ev++){ if( ev->type.find(dname) != string::npos or ev->type.find("other") != string::npos ){ if( ev->type.find("bkgcontrol") == string::npos ){ eventvec_fit.push_back(*ev); }else{ eventvec_fit_bkgcontrol.push_back(*ev); } } } fitter.ReweightMC( eventvec_fit, dname ); // flag events to be fitted for( vector<Event>::iterator ev = eventvec_fit.begin(); ev < eventvec_fit.end(); ev++){ ev->fit_event = true; for(map<string, int>::iterator it = datacount.begin(); it != datacount.end(); it++){ if( ev->process.compare(it->first) == 0 ) datacount[it->first]+=1; } } for( vector<Event>::iterator ev = eventvec_fit_bkgcontrol.begin(); ev < eventvec_fit_bkgcontrol.end(); ev++){ ev->fit_event = true; for(map<string, int>::iterator it = datacount.begin(); it != datacount.end(); it++){ if( ev->process.compare(it->first) == 0 ) datacount[it->first]+=1; } } cout << "Fit event count: " << endl; cout << setiosflags(ios::left); for(map<string, int>::iterator it = datacount.begin(); it != datacount.end(); it++){ cout << "... " << setw(25) << it->first << ": " << it->second << " events" << endl; } fitter.DeclareHists( hists_fit_, "fit" ); fitter.FillHists( hists_fit_, eventvec_fit, true ); fitter.DeclareHists( hists_fit_bkgcontrol_, "fit_bkgcontrol" ); fitter.FillHists( hists_fit_bkgcontrol_, eventvec_fit_bkgcontrol, true ); // do GP training for( map<string, Distribution>::iterator it = fitter.dists.begin(); it != fitter.dists.end(); it++ ){ string name = it->first; Distribution *dist = &(it->second); double m2llsig, m2llbkg; if( dist->activate ){ Shapes * fptr = new Shapes( name, dist->glx, dist->glmt, dist->gnorm1, dist->gnorm2 ); fptr->TrainGP( hists_train_, m2llsig, m2llbkg ); dist->aGPsig.ResizeTo( fptr->aGPsig.GetNoElements() ); dist->aGPsig = fptr->aGPsig; dist->aGPbkg.ResizeTo( fptr->aGPbkg.GetNoElements() ); dist->aGPbkg = fptr->aGPbkg; delete fptr; } } typedef map<string, TH1D*> tmap; typedef map<string, tmap> hmap; for( hmap::iterator h = hists_train_.begin(); h != hists_train_.end(); h++){ for( tmap::iterator t = h->second.begin(); t != h->second.end(); t++){ for(int n=1; n < t->second->GetNbinsX(); n++){ if( t->second->GetBinContent(n) == 0 ) t->second->SetBinError(n, 1.0/35000); } } } // events for fitting, hists for training fitter.RunMinimizer( eventvec_fit ); fitter.PlotResults( hists_fit_ ); // plot fitted events cout << "Fit Chi2 = " << fitter.fitchi2 << endl; // fill results tree // any additional variables need to be added here mcmass = mass; fitstatus = fitter.gMinuit->Status(); const double *par = fitter.gMinuit->X(); const double *par_err = fitter.gMinuit->Errors(); mt = par[0]; kmbl = par[1]; mt_err = par_err[0]; kmbl_err = par_err[1]; k220 = par[2]; k220_err = par_err[2]; fitchi2 = fitter.fitchi2; tree->Fill(); eventvec_fit.clear(); eventvec_fit_bkgcontrol.clear(); fitter.DeleteHists( hists_fit_ ); fitter.DeleteHists( hists_fit_bkgcontrol_ ); } } } if( do_templates ){ // do GP training for( map<string, Distribution>::iterator it = fitter.dists.begin(); it != fitter.dists.end(); it++ ){ string name = it->first; Distribution *dist = &(it->second); double m2llsig, m2llbkg; if( dist->activate ){ Shapes * fptr = new Shapes( name, dist->glx, dist->glmt, dist->gnorm1, dist->gnorm2 ); fptr->TrainGP( hists_train_, m2llsig, m2llbkg ); dist->aGPsig.ResizeTo( fptr->aGPsig.GetNoElements() ); dist->aGPsig = fptr->aGPsig; dist->aGPbkg.ResizeTo( fptr->aGPbkg.GetNoElements() ); dist->aGPbkg = fptr->aGPbkg; dist->Ainv_sig.ResizeTo( fptr->aGPsig.GetNoElements(), fptr->aGPsig.GetNoElements() ); dist->Ainv_sig = fptr->Ainv_sig; dist->Ainv_bkg.ResizeTo( fptr->aGPbkg.GetNoElements(), fptr->aGPbkg.GetNoElements() ); dist->Ainv_bkg = fptr->Ainv_bkg; delete fptr; } } fitter.PlotTemplates( hists_train_ ); for(int j=0; j < 8; j++){ tsig_mbl_chi2[j] = fitter.tsig_mbl_chi2[j]; tbkg_mbl_chi2[j] = fitter.tbkg_mbl_chi2[j]; } } if( do_learnparams ){ string name = "mbl"; Distribution *dist = &(fitter.dists[name]); Shapes * fptr = new Shapes( name, dist->glx, dist->glmt, dist->gnorm1, dist->gnorm2 ); fptr->LearnGPparams( hists_train_ ); delete fptr; } if( do_fit or do_templates ){ tree->Fill(); } // // write fit results // if( do_fit or do_templates ){ // set up output file path std::string pathstr; char* path = std::getenv("WORKING_DIR"); if (path==NULL) { pathstr = "./results"; }else { pathstr = path; } TFile *file = new TFile((pathstr+"/fitresults.root").c_str(), "RECREATE"); file->cd(); tree->Write(); file->Write(); file->Close(); } return 0; }
Vector RayCast(Ray r, int Depth) { Vector result = Vector(); Shapes o = Shapes(); int ShapeNum = 0; bool Intersect = false; //Find nearest intersection between r and objects float Dist = -1.0f; for (int i = 0; i < ShapeList.size(); i++) { // Find Closest intersecting shape // - Find t for each shape // - if t > 0 for that shape find dst // - Smallest Dst is the object ShapeList[i].setT(-1.0f); auto t = ShapeList[i].Intersect(r); if (t > 0.0f) { ShapeList[i].setT(t); Intersect = true; Shapes Place = ShapeList[i]; if (Dist < 0.0f) { Dist = ShapeList[i].getT(); } if (ShapeList[i].getT() <= Dist) { o = ShapeList[i]; ShapeNum = i; Dist = o.getT(); } } } if (!Intersect) { return result; } Vector p = r.Source + (r.Direction * o.getT()); Vector n = o.Normal(p); Vector v = ViewCamera.Position() - p; LightConstants MaterialP = o.getLightConstants(); if (o.Has_Texture()) { Vector Material = o.getMaterialColour(p); MaterialP.Diffuse = Material; } result = aLight.CalculateLightModel(p, n, v, MaterialP, ShapeList, ShapeNum); if (Depth == 0) { return result; } LightConstants P = o.getLightConstants(); Vector ZERO = Vector(0.0f, 0.0f, 0.0f); if ((P.Reflective.x != ZERO.x) || (P.Reflective.y != ZERO.y) || (P.Reflective.z != ZERO.z)) { // Reflection Vector = u - 2(u . n)n float temp = 2.0f * DotProduct(r.Direction.Normalize(), n.Normalize()); Vector R = r.Direction.Normalize() - (n.Normalize() * temp); Vector ReflectColour = RayCast(Ray(p, R.Normalize()), Depth - 1); result = result + Vector(P.Reflective.x * ReflectColour.x, P.Reflective.y * ReflectColour.y, P.Reflective.z * ReflectColour.z); } if ((P.Transmission.x != ZERO.x) || (P.Transmission.y != ZERO.y) || (P.Transmission.z != ZERO.z)) { Vector u = r.Direction; u = u.Normalize() * -1.0f; Vector t = aLight.CalcTransmissionDirection((u), n.Normalize(), 1.5f); if ((t.x != ZERO.x) && (t.y != ZERO.y) && (t.z != ZERO.z)) { Vector T = RayCast(Ray(p, t), Depth - 1); result = result + Vector(P.Transmission.x * T.x, P.Transmission.y * T.y, P.Transmission.z * T.z); } } //if ! Transparent return result; }
int main() { cout << "RayTracer starting...\n"; bitmap image1; image1.create(256, 256); cout << "Image Created...\n"; // Camera is a ray as well, Source would be the position that the camera exists and // Direction would be where it is looking. Vector CameraCenter = Vector(0.0f, 0.0f, 0.0f); ViewCamera = Camera(CameraCenter, Vector(0.0f, 0.0f, 1.0f), Vector(0.0f, 1.0f, 0.0f), image1.getwidth(), image1.getheight()); ViewCamera.CalculatePlaneNormals(); Shapes a = Shapes(); LightConstants Material = LightConstants(Vector(0.0f, 0.9f, 0.0f), Vector(0.1f, 0.1f, 0.1f), Vector(0.1f, 0.1f, 0.1f), Vector(), Vector(), Vector(), 8.0f); a.setPlane(Vector(0.0f, 1.0f, 0.0f, 1.0f), Material); ShapeList.push_back(a); Material = LightConstants(Vector(1.0f, 0.0f, 0.0f), Vector(0.1f, 0.1f, 0.1f), Vector(0.0f, 0.0f, 0.0f), Vector(), Vector(), Vector(), 8.0f); a.setPlane(Vector(0.0f, -1.0f, 0.0f, 1.0f), Material); ShapeList.push_back(a); Material = LightConstants(Vector(0.9f, 0.9f, 0.0f), Vector(0.1f, 0.1f, 0.1f), Vector(0.0f, 0.0f, 0.0f), Vector(), Vector(), Vector(), 8.0f); a.setPlane(Vector(1.0f, 0.0f, 0.0f, 1.0f), Material); ShapeList.push_back(a); Material = LightConstants(Vector(0.9f, 0.9f, 0.9f), Vector(0.1f, 0.1f, 0.1f), Vector(0.0f, 0.0f, 0.0f), Vector(), Vector(), Vector(), 8.0f); a.setPlane(Vector(-1.0f, 0.0f, 0.0f, 1.0f), Material); ShapeList.push_back(a); Shapes b = Shapes(); Material = LightConstants(Vector(0.0f, 0.0f, 0.7f), Vector(0.3f, 0.3f, 0.3f), Vector(), Vector(), Vector(0.1f, 0.1f, 0.1f), Vector(), 4.0f); b.setSphere(0.5f, Material, false); b.Translatef(Vector(0.0f, 1.0f, 0.0f)); ShapeList.push_back(b); Material = LightConstants(Vector(0.7f, 0.0f, 0.0f), Vector(0.3f, 0.3f, 0.3f), Vector(), Vector(), Vector(0.5f, 0.5f, 0.5f), Vector(), 16.0f); b.setSphere(0.5f, Material, false); b.Translatef(Vector(-1.0f, 0.0f, 0.0f)); ShapeList.push_back(b); Material = LightConstants(Vector(0.1f, 0.1f, 0.1f), Vector(0.9f, 0.9f, 0.9f), Vector(), Vector(), Vector(0.5f, 0.5f, 0.5f), Vector(), 16.0f); b.setSphere(0.5f, Material, false); b.Translatef(Vector(1.0f, 0.0f, 0.0f)); ShapeList.push_back(b); Material = LightConstants(Vector(0.0f, 0.7f, 0.0f), Vector(0.3f, 0.3f, 0.3f), Vector(), Vector(), Vector(0.5f, 0.5f, 0.5f), Vector(), 16.0f); b.setSphere(0.5f, Material, false); b.Translatef(Vector(0.0f, -1.0f, 0.0f)); ShapeList.push_back(b); Material = LightConstants(Vector(0.5f, 0.5f, 0.5f), Vector(0.5f, 0.5f, 0.5f), Vector(), Vector(), Vector(), Vector(0.9f, 0.9f, 0.9f), 16.0f); b.setTriangle(Vector(0.5f, 0.0f, 0.0f), Vector(0.0f, 0.5f, 0.0f), Vector(-0.5f, 0.0f, 0.0f), Material); b.Translatef(Vector(0.0f, 0.0f, -0.5f)); //b.Rotatef(3.0f, Vector(0.0f, 1.0f, 0.0f)); ShapeList.push_back(b); LightConstants LightValue = LightConstants(Vector(0.7f, 0.7f, 0.7f), Vector(0.3f, 0.3f, 0.3f), Vector(1.0f, 1.0f, 1.0f)); aLight = Light(Ray(Vector(0.5f, 0.5f, -1.0f), Vector(0.0f, 0.0f, 0.0f)), LightValue); LightValue = LightConstants(Vector(0.7f, 0.7f, 0.7f), Vector(0.3f, 0.3f, 0.3f), Vector(0.5f, 0.5f, 0.5f)); aLight.addLight(Ray(Vector(-0.5f, 0.5f, -1.0f), Vector(0.0f, 0.0f, 0.0f)), LightValue); cout << "Casting Rays...\n"; BYTE Red, Green, Blue; for (int i = 1; i < image1.getwidth(); i++) { cout << i; float w = image1.getwidth(); float t = i / w; Vector Left = Parametric(ViewCamera.P3(), ViewCamera.P0(), t); Vector Right = Parametric(ViewCamera.P2(), ViewCamera.P1(), t); for (int j = 1; j < image1.getheight(); j++) { float h = image1.getheight(); t = j / h; Vector RayDir = Parametric(Left, Right, t); Matrix4Operations Translate; Matrix4Operations TranslateC; Translate.SetTranslate(RayDir); RayDir = Translate.Translate(Vector(0.0f, 0.0f, -3.0f)); Vector C = ViewCamera.Position(); TranslateC.SetTranslate(C); C = TranslateC.Translate(Vector(0.0f, 0.0f, -3.0f)); RayDir = C - RayDir; Ray casted = Ray(C, RayDir.Normalize()); Vector Colour = RayCast(casted, 5); Red = Limit255(Colour.x * 255); Green = Limit255(Colour.y * 255); Blue = Limit255(Colour.z * 255); image1.setcolor(255 - i, 255 - j, Red, Green, Blue); } } cout << "Saving Image...\n"; image1.save("image1.bmp"); //system("PAUSE"); return 0; }