int main() { // 2 1 3 ListNode l1(2), l2(1), l3(3); ListNode l4(4), l5(2), l6(1), l7(6), l8(6), l9(9), l10(10), l11(11), l12(12), l13(6); ListNode n1(0), n2(0), n3(0), n4(1); l1.next = &l2; //l2.next = &l3; l4.next = &l5; l5.next = &l6; l6.next = &l7; l7.next = &l8; l8.next = &l9; l9.next = &l10; l10.next = &l11; l11.next = &l12; l12.next = &l13; print_list(&l1); Solution s; ListNode *result = s.removeNthFromEnd(&l1, 2); print_list(result); return 0; }
JSONNode ModuleManager::convertIrcMessageToJSONString(IrcMessage& message) { JSONNode n(JSON_NODE); n.push_back(JSONNode("ircLine", message.ircLine)); n.push_back(JSONNode("prefix", message.prefix)); n.push_back(JSONNode("hasDetailedPrefix", message.hasDetailedPrefix)); JSONNode n2(JSON_NODE); n2.set_name("msgPrefix"); n2.push_back(JSONNode("nick_or_server", message.msgPrefix.nick_or_server)); n2.push_back(JSONNode("user", message.msgPrefix.user)); n2.push_back(JSONNode("host", message.msgPrefix.host)); n.push_back(n2); n.push_back(JSONNode("command", message.command)); n.push_back(JSONNode("isNumeric", message.isNumeric)); n.push_back(JSONNode("target", message.target)); n.push_back(JSONNode("params", message.params)); return n; }
CStandardGroundFlash::CStandardGroundFlash(const float3& p,float circleAlpha,float flashAlpha,float flashSize,float circleSpeed,float ttl, const float3& col) : CGroundFlash(p), circleAlpha(circleAlpha), flashAlpha(flashAlpha), flashSize(flashSize), circleGrowth(circleSpeed), circleSize(circleSpeed), flashAge(0), ttl((int)ttl), circleAlphaDec(ttl?circleAlpha/ttl:0), flashAgeSpeed(ttl?1.0f/ttl:0) { for (int a=0;a<3;a++) color[a] = (unsigned char)(col[a]*255.0f); float3 fw = camera->forward*-1000.0f; this->pos.y=ground->GetHeight2(p.x,p.z)+1; float3 p1(p.x+flashSize,0,p.z); p1.y=ground->GetApproximateHeight(p1.x,p1.z); p1 += fw; float3 p2(p.x-flashSize,0,p.z); p2.y=ground->GetApproximateHeight(p2.x,p2.z); p2 += fw; float3 p3(p.x,0,p.z+flashSize); p3.y=ground->GetApproximateHeight(p3.x,p3.z); p3 += fw; float3 p4(p.x,0,p.z-flashSize); p4.y=ground->GetApproximateHeight(p4.x,p4.z); p4 += fw; float3 n1((p3-p1).cross(p4-p1)); n1.Normalize(); float3 n2((p4-p2).cross(p3-p2)); n2.Normalize(); float3 normal=n1+n2; normal.Normalize(); side1=normal.cross(float3(1,0,0)); side1.Normalize(); side2=side1.cross(normal); ph->AddGroundFlash(this); }
void NodeImporter::importSubmarineCableEdgesWaypoints() { std::unique_ptr<SubmarineCable> sc(new SubmarineCable(_dbFilename)); while (sc->hasNext()) { SubmarineCableEdge edge = sc->getNext(); if (edge.coord1 == edge.coord2) continue; GeographicNode_Ptr n1(new SeaCableNode(_nodenumber, edge.coord1.first, edge.coord1.second)); ++_nodenumber; // find nearest node GeographicNode_Ptr nearestNode = findNearest(n1); SeaCableLandingPoint* slp = dynamic_cast<SeaCableLandingPoint*>(nearestNode.get()); CityNode* cnp = dynamic_cast<CityNode*>(nearestNode.get()); GeographicNode_Ptr nnP(new GeographicNode(*nearestNode)); double dist = GeometricHelpers::sphericalDist(n1, nnP); if (!((slp || (cnp && cnp->isSeaCableLandingPoint())) && dist < NodeImporter::DIST_TRESHOLD)) addNode(n1); else { auto rtn = _fallbackProjection.insert(std::make_pair(edge.coord1, nearestNode->coord())); assert(rtn.second == false || _fallbackProjection.at(edge.coord1) == nearestNode->coord()); } GeographicNode_Ptr n2(new SeaCableNode(_nodenumber, edge.coord2.first, edge.coord2.second)); ++_nodenumber; // find nearest node nearestNode = findNearest(n2); slp = dynamic_cast<SeaCableLandingPoint*>(nearestNode.get()); cnp = dynamic_cast<CityNode*>(nearestNode.get()); nnP = GeographicNode_Ptr(new GeographicNode(*nearestNode)); dist = GeometricHelpers::sphericalDist(n2, nnP); if (!((slp || (cnp && cnp->isSeaCableLandingPoint())) && dist < NodeImporter::DIST_TRESHOLD)) addNode(n2); else { auto rtn = _fallbackProjection.insert(std::make_pair(edge.coord2, nearestNode->coord())); assert(rtn.second == false || _fallbackProjection.at(edge.coord2) == nearestNode->coord()); } } }
/** * This method is called when subtracting from rhythm value can't be solved in single note. * So given 'long' note is split, then calling method tries to subtract from smaller rhythm. * Because adding new, split note doesn't change measure duration, * this method simplifies process of adding new note to staff and measure. * It ties notes as well. */ void TscoreMeasure::split(TscoreNote* sn) { auto tieCopy = sn->note()->rtm.tie(); // if (!sn->note()->isRest()) // preserveTie(tieCopy, sn); TrhythmList splitList; sn->note()->rtm.split(splitList); sn->note()->rtm.setRhythm(splitList.first()); Tnote n2(*sn->note(), splitList.last()); // TODO: common code like in @p noteChangedSlot() - do method of it auto inserted = m_staff->insertNote(n2, sn->index() + 1, sn->isReadOnly()); fixStemDirection(inserted); m_notes.insert(inserted->index() - firstNoteId(), inserted); connect(inserted, &TscoreNote::noteGoingToChange, this, &TscoreMeasure::noteChangedSlot); inserted->setGroup(sn->group()); m_staff->updateNotesPos(inserted->index()); // ------------ if (!sn->note()->isRest()) restoreTie(tieCopy, sn); }
int main() { srand(time(NULL)); scanf("%d", &n); for(int i=1; i<=n; i++) a[i] = rand(); long long ans6 = ndp(); printf("O(n) DP : %lld\n", ans6); long long ans5 = ngreedy(); printf("O(n) greedy : %lld\n", ans5); long long ans4 = n1(); printf("n : %lld\n", ans4); long long ans3 = nlogn(1, n+1); printf("nlogn : %lld\n", ans3); long long ans2 = n2(); printf("n^2 : %lld\n", ans2); long long ans1 = n3(); printf("n^3 : %lld\n", ans1); assert(ans1 == ans2 && ans2 == ans3 && ans3 == ans4 && ans4 == ans5); system("pause"); return 0; }
bool path_intersects_path(PathIterator& p1, PathIterator& p2) { typedef PathNanRemover<PathIterator> no_nans_t; typedef agg::conv_curve<no_nans_t> curve_t; if (p1.total_vertices() < 2 || p2.total_vertices() < 2) { return false; } no_nans_t n1(p1, true, p1.has_curves()); no_nans_t n2(p2, true, p2.has_curves()); curve_t c1(n1); curve_t c2(n2); double x11, y11, x12, y12; double x21, y21, x22, y22; c1.vertex(&x11, &y11); while (c1.vertex(&x12, &y12) != agg::path_cmd_stop) { c2.rewind(0); c2.vertex(&x21, &y21); while (c2.vertex(&x22, &y22) != agg::path_cmd_stop) { if (segments_intersect(x11, y11, x12, y12, x21, y21, x22, y22)) { return true; } x21 = x22; y21 = y22; } x11 = x12; y11 = y12; } return false; }
void test() { LLVMDependenceGraph d; LLVMDependenceGraph s; int rc; rc = s.ref(); check(rc == 2, "refcount shold be 2, but is %d", rc); rc = s.unref(); check(rc == 1, "refcount shold be 1, but is %d", rc); s.ref(); rc = s.ref(); check(rc == 3, "refcount shold be 3, but is %d", rc); s.unref(); rc = s.unref(); check(rc == 1, "refcount shold be 1, but is %d", rc); // addSubgraph increases refcount LLVMNode n1(nullptr), n2(nullptr); n1.addSubgraph(&s); n2.addSubgraph(&s); // we do not have a getter for refcounts, so just // inc and dec the counter to get the current value s.ref(); rc = s.unref(); check(rc == 3, "refcount shold be 3, but is %d", rc); // set entry blocks, otherwise the constructor will call assert LLVMBBlock *entryBB1 = new LLVMBBlock(&n1); LLVMBBlock *entryBB2 = new LLVMBBlock(&n2); d.setEntryBB(entryBB1); s.setEntryBB(entryBB2); delete entryBB1; delete entryBB2; }
void MyMoneyPriceTest::testRate() { MyMoneyPrice n1(QString("from"), QString("to"), QDate(2005, 9, 23), MyMoneyMoney(1, 3), QString("MySource")); MyMoneyPrice n2(QString("from"), QString("to"), QDate(), MyMoneyMoney(1, 3), QString("MySource")); try { QVERIFY(n1.rate("to") == MyMoneyMoney(1, 3)); QVERIFY(n1.rate("from") == MyMoneyMoney(3, 1)); QVERIFY(n1.rate(QString()) == MyMoneyMoney(1, 3)); QVERIFY(n2.isValid() == false); QVERIFY(n2.rate("to") == MyMoneyMoney::ONE); } catch (const MyMoneyException &) { QFAIL("Unexpected exception"); } try { n1.rate("unknown"); QFAIL("Missing expected exception"); } catch (const MyMoneyException &) { } }
int main() { // 5 // / \ // 4 8 // / \ // 11 4 TreeNode n1(5); TreeNode n2(4); TreeNode n3(8); TreeNode n4(11); TreeNode n5(4); n1.left = &n2; n1.right = &n3; n2.left = &n4; n3.right = &n5; Solution slt; std::cout << slt.hasPathSum(&n1, 20) << std::endl; std::cout << slt.hasPathSum(&n1, 21) << std::endl; }
TEST(search, tfind_tsearch_twalk_tdestroy) { void* root = nullptr; node n1("z"); node n2("a"); node n3("m"); // tfind(3) can't find anything in the empty tree. ASSERT_EQ(nullptr, tfind(&n1, &root, node_cmp)); ASSERT_EQ(nullptr, tfind(&n2, &root, node_cmp)); ASSERT_EQ(nullptr, tfind(&n3, &root, node_cmp)); // tsearch(3) inserts and returns a pointer to a new node. void* i1 = tsearch(&n1, &root, node_cmp); ASSERT_NE(nullptr, i1); // ...which tfind(3) will then return. ASSERT_EQ(i1, tfind(&n1, &root, node_cmp)); ASSERT_EQ(nullptr, tfind(&n2, &root, node_cmp)); ASSERT_EQ(nullptr, tfind(&n3, &root, node_cmp)); // Add the other nodes. ASSERT_NE(nullptr, tsearch(&n2, &root, node_cmp)); ASSERT_NE(nullptr, tsearch(&n3, &root, node_cmp)); // Use twalk(3) to iterate over the nodes. g_nodes.clear(); twalk(root, node_walk); ASSERT_EQ(3U, g_nodes.size()); ASSERT_EQ("a", g_nodes[0]); ASSERT_EQ("m", g_nodes[1]); ASSERT_EQ("z", g_nodes[2]); // tdestroy(3) removes nodes under a node, calling our callback to destroy each one. g_free_calls = 0; tdestroy(root, node_free); ASSERT_EQ(3U, g_free_calls); }
int main() { TreeNode n1(3); TreeNode n2(9); TreeNode n3(20); TreeNode n4(15); TreeNode n5(7); n1.left = &n2; n1.right = &n3; n3.left = &n4; n3.right = &n5; Solution sln; auto a = sln.levelOrder(&n1); for(int i = 0; i < a.size(); i++) { for(int j = 0; j < a[i].size(); j++) { cout << a[i][j] << "\t"; } cout << endl; } return 0; }
void Element::polarDecompositionEigen( const ColumnMajorMatrix & Fhat, ColumnMajorMatrix & Rhat, SymmTensor & strain_increment ) { const int ND = 3; ColumnMajorMatrix eigen_value(ND,1), eigen_vector(ND,ND); ColumnMajorMatrix invUhat(ND,ND), logVhat(ND,ND); ColumnMajorMatrix n1(ND,1), n2(ND,1), n3(ND,1), N1(ND,1), N2(ND,1), N3(ND,1); ColumnMajorMatrix Chat = Fhat.transpose() * Fhat; Chat.eigen(eigen_value,eigen_vector); for(int i = 0; i < ND; i++) { N1(i) = eigen_vector(i,0); N2(i) = eigen_vector(i,1); N3(i) = eigen_vector(i,2); } const Real lamda1 = std::sqrt(eigen_value(0)); const Real lamda2 = std::sqrt(eigen_value(1)); const Real lamda3 = std::sqrt(eigen_value(2)); const Real log1 = std::log(lamda1); const Real log2 = std::log(lamda2); const Real log3 = std::log(lamda3); ColumnMajorMatrix Uhat = N1 * N1.transpose() * lamda1 + N2 * N2.transpose() * lamda2 + N3 * N3.transpose() * lamda3; invertMatrix(Uhat,invUhat); Rhat = Fhat * invUhat; strain_increment = N1 * N1.transpose() * log1 + N2 * N2.transpose() * log2 + N3 * N3.transpose() * log3; }
void CSimpleGroundFlash::Init(const float3& explosionPos, CUnit *owner) { pos += explosionPos; float flashsize = size+sizeGrowth*ttl; float3 fw = camera->forward*-1000.0f; this->pos.y=ground->GetHeight2(pos.x,pos.z)+1; float3 p1(pos.x+flashsize,0,pos.z); p1.y=ground->GetApproximateHeight(p1.x,p1.z); p1 += fw; float3 p2(pos.x-flashsize,0,pos.z); p2.y=ground->GetApproximateHeight(p2.x,p2.z); p2 += fw; float3 p3(pos.x,0,pos.z+flashsize); p3.y=ground->GetApproximateHeight(p3.x,p3.z); p3 += fw; float3 p4(pos.x,0,pos.z-flashsize); p4.y=ground->GetApproximateHeight(p4.x,p4.z); p4 += fw; float3 n1((p3-p1).cross(p4-p1)); n1.Normalize(); float3 n2((p4-p2).cross(p3-p2)); n2.Normalize(); //pos += fw; float3 normal=n1+n2; normal.Normalize(); side1=normal.cross(float3(1,0,0)); side1.Normalize(); side2=side1.cross(normal); ph->AddGroundFlash(this); age=0.0f; agerate = ttl?1/(float)ttl:0; }
const Rational operator +(const Rational& r1, const Rational& r2){ //If the parameters are const, then the get() function must be suffix const BigInt n1(r1.getNumerator()); BigInt n2(r2.getNumerator()); BigInt d1(r1.getDenominator()); BigInt d2(r2.getDenominator()); BigInt gcd(GCD(d1, d2)); gcd.abs(); if(!n1.isNeg() && !n2.isNeg()){ BigInt n(n1 * (d2 / gcd) + n2 * (d1 / gcd)); BigInt d(d1 * d2 / gcd); return Rational(n, d); } else if(n1.isNeg() && n2.isNeg()){ n1 = -n1; d1 = -d1; n2 = -n2; d2 = -d2; BigInt n(n1 * (d2 / gcd) + n2 * (d1 / gcd)); BigInt d(d1 * d2 / gcd); return Rational(n, d); } else if(!n1.isNeg() && n2.isNeg()){ n2 = -n2; d2 = -d2; BigInt n(n1 * (d2 / gcd) + n2 * (d1 / gcd)); BigInt d(d1 * d2 / gcd); return Rational(n, d); } else if(n1.isNeg() && !n2.isNeg()){ n1 = -n1; d1 = -d1; BigInt n(n2 * (d1 / gcd) + n1 * (d2 / gcd)); BigInt d(d1 * d2 / gcd); return Rational(n, d); } }
void Mesh::generate_smooth_normals(map<string, vector<int> > &vertex_map ) { verify_initialized(); vector<float> normals_original = normals; char vertex_key[100]; // Loop over atoms ProgressBar p(num_vertices,"Creating smooth normal vectors"); for(int i=0; i<num_vertices; i++) { p.update(i); CVector v1(vertices[3*i+0], vertices[3*i+1], vertices[3*i+2]); CVector n1(normals_original[3*i+0], normals_original[3*i+1], normals_original[3*i+2]); CVector n1_original(normals_original[3*i+0], normals_original[3*i+1], normals_original[3*i+2]); sprintf(vertex_key, "%.2f%.2f%.2f",vertices[3*i+0], vertices[3*i+1], vertices[3*i+2]); string key = vertex_key; std::map<string, vector<int> >::iterator iterator = vertex_map.find(key); vector<int> &neighbor_triangle_indices = iterator->second; for(int j=0; j<neighbor_triangle_indices.size(); j++) { int neighbor_triangle_index = neighbor_triangle_indices[j]; if(i != neighbor_triangle_index) { CVector v2(vertices[3*neighbor_triangle_index+0], vertices[3*neighbor_triangle_index+1], vertices[3*neighbor_triangle_index+2]); if(v1 == v2) { CVector n2(normals_original[3*neighbor_triangle_index+0], normals_original[3*neighbor_triangle_index+1], normals_original[3*neighbor_triangle_index+2]); if(n1_original.dot(n2) > 0) n1 = n1+n2; // Only add normals pointing in the same direction } } } // end j n1 = n1.normalize(); normals[3*i+0] = n1.x; normals[3*i+1] = n1.y; normals[3*i+2] = n1.z; } normals_original.clear(); }
int main(int argc, const char *argv[]) { typedef std::vector<int> Point; int dimensions = 2; Point p1 = {10, 3}; Point p2 = {3, 8}; Point p3 = {8, 3}; Point p4 = {1, 4}; Point p5 = {5, 1}; Node<Point> n1(p1); Node<Point> n2(p2); Node<Point> n3(p3); Node<Point> n4(p4); Node<Point> n5(p5); Node<Point> nodes[] = {n1, n2, n3, n4, n5}; std::cout << "Source:" << std::endl; for (int i = 0; i < sizeof(nodes) / sizeof(*nodes); ++i) { std::cout << "("; for (int j = 0; j < dimensions; ++j) { std::cout << nodes[i].value[j] << ","; } std::cout << "), "; } std::cout << std::endl; std::cout << "Tree:" << std::endl; KDTree<Point> tree; tree.make_tree(nodes, 5, 2); tree.visualise(); return 0; }
int main(int argc, char** argv) { int npt = 20; // No. points to sample on test printing int k = 10; // order of wavelet double thresh = 1e-12; // truncation threshold printf ("1. Initializing FunctionASTs\n"); FunctionAST f1(k, thresh, test1); FunctionAST f2(k, thresh, test2); FunctionAST f4(k, thresh, sinn); printf ("2. Reconstructing FunctionASTs\n"); f1.reconstruct(0, 0); f2.reconstruct(0, 0); f4.reconstruct(0, 0); printf ("3. Initializing FunctionAST\n"); FunctionAST resultAST(k, thresh, NULL); printf ("4. Creating Nodes\n"); Node n1(&f1, 0, 0, 0, 0, 0, 0); Node n2(&f2, 0, 0, 0, 0, 0, 0); Node n4(&f4, 0, 0, 0, 0, 0, 0); printf ("5. Creating ASTs\n"); printf ("6. Computing Functions\n"); printf ("The Norm of Difference is \n"); }
string multiply(string num1, string num2){ if(!num1.length() || !num2.length()) return ""; if(num1[0]=='0' || num2[0]=='0') return "0"; int len1=num1.length(),len2=num2.length(),len=max(len1,len2)*2; vector<int> res(len+1,0),n1(len1,0),n2(len2,0);//多申请一位就是为了确保最高位进位时可以保存下来 for(int i=len1-1,j=0;i>=0;--i,++j) n1[j]=num1[i]-'0'; for(int i=len2-1,j=0;i>=0;--i,++j) n2[j]=num2[i]-'0'; for(int i=0;i<len1;++i) for(int j=0;j<len2;++j) res[i+j]+=n1[i]*n2[j]; for(int i=0;i<len;++i) if(res[i]>=10){ res[i+1]+=res[i]/10; res[i]%=10; } string ret; int flag=true; for(int i=len;i>=0;--i){ while(!res[i] && flag) --i; flag=false; ret+=res[i]+'0'; } return ret; }
int main(int argc, char *argv[]) { Pooma::initialize(argc, argv); Pooma::Tester tester(argc, argv); Interval<1> n1(1,5); Interval<1> n2(4,8); Interval<1> n3(10,20); Interval<2> a(n1,n2); Interval<3> b(n1,n2,n3); Range<1> r1(1,5); Range<1> r2(4,8,2); Range<1> r3(5,9,2); Range<1> r4(10,20,5); Range<2> ra(r1,r2); Range<2> rb(r1,r3); Range<3> rc(r1,r2,r3); tester.out() << "1: touches(" << a[0] << "," << a[1] << ") ? "; tester.out() << touches(a[0], a[1]) << std::endl; tester.check( touches(a[0], a[1]) ); tester.out() << "0: touches(" << a[0] << "," << b[2] << ") ? "; tester.out() << touches(a[0], b[2]) << std::endl; tester.check( touches(a[0], b[2])==0); tester.out() << "1: touches(" << a[0] << "," << ra[0] << ") ? "; tester.out() << touches(a[0], ra[0]) << std::endl; tester.check(touches(a[0], ra[0])); tester.out() << "1: touches(" << ra[0] << "," << ra[1] << ") ? "; tester.out() << touches(ra[0], ra[1]) << std::endl; tester.check( touches(ra[0], ra[1])); tester.out() << "0: touches(" << r2 << "," << r3 << ") ? "; tester.out() << touches(r2, r3) << std::endl; tester.check( touches(r2, r3)==0); tester.out() << "0: touches(" << ra << "," << rb << ") ? "; tester.out() << touches(ra, rb) << std::endl; tester.check( touches(ra, rb) ==0); tester.out() << "1: touches(" << rc << "," << rc << ") ? "; tester.out() << touches(rc, rc) << std::endl; tester.check( touches(rc, rc) ); tester.out() << "------------------------------------" << std::endl; tester.check(" touches ", true); Interval<1> c1(1,10); Interval<1> c2(3,8); Interval<1> c3(5,15); Interval<2> ca(c1, c1); Interval<2> cb(c1, c2); Range<1> cr1(2,20,2); Range<1> cr2(4,16,4); Range<1> cr3(3,15,2); Range<1> cr4(5,15,5); tester.out() << "1: contains(" << c1 << "," << c2 << ") ? "; tester.out() << contains(c1,c2) << std::endl; tester.check(contains(c1,c2)); tester.out() << "0: contains(" << c2 << "," << c1 << ") ? "; tester.out() << contains(c2,c1) << std::endl; tester.check(contains(c2,c1)==0); tester.out() << "0: contains(" << c1 << "," << c3 << ") ? "; tester.out() << contains(c1,c3) << std::endl; tester.check(contains(c1,c3)==0); tester.out() << "1: contains(" << ca << "," << cb << ") ? "; tester.out() << contains(ca,cb) << std::endl; tester.check(contains(ca,cb)); tester.out() << "0: contains(" << cb << "," << ca << ") ? "; tester.out() << contains(cb,ca) << std::endl; tester.check(contains(cb,ca)==0); tester.out() << "1: contains(" << cr1 << "," << cr2 << ") ? "; tester.out() << contains(cr1,cr2) << std::endl; tester.check( contains(cr1,cr2)); tester.out() << "0: contains(" << cr1 << "," << cr3 << ") ? "; tester.out() << contains(cr1,cr3) << std::endl; tester.check(contains(cr1,cr3)==0); tester.out() << "1: contains(" << c3 << "," << cr4 << ") ? "; tester.out() << contains(c3,cr4) << std::endl; tester.check(contains(c3,cr4)); tester.out() << "0: contains(" << cr4 << "," << c3 << ") ? "; tester.out() << contains(cr4,c3) << std::endl; tester.check(contains(cr4,c3)==0); tester.out() << "------------------------------------" << std::endl; Interval<2> s1, s2; Range<2> sr1, sr2; split(cb, s1, s2); tester.out() << "split(" << cb << ") = " << s1 << " and " << s2 << std::endl; tester.check(s1==Interval<2>(Interval<1>(1,5),Interval<1>(3,5))); tester.check(s2==Interval<2>(Interval<1>(6,10),Interval<1>(6,8))); split(rb, sr1, sr2); tester.out() << "split(" << rb << ") = " << sr1 << " and " << sr2 << std::endl; tester.check(sr1==Range<2>(Range<1>(1,2),Range<1>(5,5,2))); tester.check(sr2==Range<2>(Range<1>(3,5),Range<1>(7,9,2))); tester.out() << "------------------------------------" << std::endl; tester.out() << "intersect(" << cb << "," << ca << ") = "; tester.out() << intersect(cb,ca) << std::endl; tester.check(intersect(cb,ca)==Interval<2>(Interval<1>(1,10), Interval<1>(3,8))); tester.out() << "intersect(" << rb << "," << ra << ") = "; tester.out() << intersect(rb,ra) << std::endl; Range<1> i1(1,16,3); Range<1> i2(17,3,-2); tester.out() << "intersect(" << i1 << "," << i2 << ") = "; tester.out() << intersect(i1,i2) << std::endl; tester.check( intersect(i1,i2) == Range<1>(7,14,6)); tester.out() << "intersect(" << i2 << "," << i1 << ") = "; tester.out() << intersect(i2,i1) << std::endl; tester.check( intersect(i2,i1) == Range<1>(13,7,-6)); tester.out() << "------------------------------------" << std::endl; Interval<1> eq1(1,5); Range<1> eq2 = -2 * eq1 + 3; Range<1> eq3(-8,8,4); Range<1> eq4 = 3 * eq1; Range<1> eq5 = 2 * eq1; Range<1> eq6 = 6 * eq1 + 1; tester.out() << "For " << eq1 << " --> " << eq4 << ", then " << eq3 << " --> "; tester.out() << equivSubset(eq1,eq4,eq3) << std::endl; tester.out() << "For " << eq4 << " --> " << eq6 << ", then " << eq3 << " --> "; tester.out() << equivSubset(eq4,eq6,eq3) << std::endl; tester.out() << "For " << eq1 << " --> " << eq2 << ", then " << eq3 << " --> "; tester.out() << equivSubset(eq1,eq2,eq3) << std::endl; tester.out() << "------------------------------------" << std::endl; NewDomain3<Interval<1>, Interval<1>, int>::SliceType_t ba; // tester.out() << "Created initial slice domain ba = " << ba << std::endl; ba = NewDomain3<Interval<1>, Interval<1>, int>::combineSlice(ba,eq1,eq1,7); tester.out() << "After taking slice, ba = " << ba << std::endl; int retval = tester.results("Domain Calc"); Pooma::finalize(); return retval; }
/** * Runs a debug version of perty for visualizing the results. Not necessary for normal testing. */ void runDebugTest() { shared_ptr<OsmMap> map(new OsmMap()); OGREnvelope env; env.MinX = 0; env.MinY = 0; env.MaxX = 1; env.MaxY = 1; map->setProjection(MapProjector::createAeacProjection(env)); //OsmReader reader; //reader.read("test-files/ToyTestA.osm", map); // force the map bounds. NodePtr n1(new Node(Status::Unknown1, map->createNextNodeId(), 0, 0, 10)); NodePtr n2(new Node(Status::Unknown1, map->createNextNodeId(), 100, 100, 10)); map->addNode(n1); map->addNode(n2); double gridSpacing = 2.5; for (double x = 0.0; x < 200.0; x += gridSpacing / 4) { for (double y = 0.0; y < 100.0; y += gridSpacing / 4) { NodePtr n(new Node(Status::Unknown1, map->createNextNodeId(), x, y, 10)); //n->setTag("note", QString::number(n->getId())); map->addNode(n); } } OsmWriter writer; QDir().mkpath("test-output/perty"); shared_ptr<OsmMap> original(new OsmMap(map)); MapProjector::projectToWgs84(original); writer.write(original, "test-output/perty/Original.osm"); PertyOp uut; uut.setGridSpacing(gridSpacing); uut.setRandomError(0.0, 0.0); uut.setSeed(1); uut.setSystematicError(10.0, 10.0); uut.setCsmParameters(9, 10); //uut.apply(map); // for (int i = 0; i < 100; i++) // { // shared_ptr<OsmMap> tmp(new OsmMap(map)); // uut.permute(tmp); // } //tbs::SampleStats ss(uut._x); //LOG_INFO("sd: " << ss.calculateUnbiasedStandardDeviation()); shared_ptr<OsmMap> debug = uut.generateDebugMap(map); // for (int i = 0; i < 100; i++) // { // shared_ptr<OsmMap> tmp(new OsmMap(map)); // uut.permute(tmp); // } //tbs::SampleStats ss(uut._x); //LOG_INFO("sd: " << ss.calculateUnbiasedStandardDeviation MapProjector::projectToWgs84(debug); writer.write(debug, "test-output/perty/Debug.osm"); MapProjector::projectToWgs84(map); writer.write(map, "test-output/perty/Permuted.osm"); }
// Compute allowable normal ranges based on adjacency. // A normal n is allowable iff: // cross(n, n1) >= 0.0f && cross(n2, n) >= 0.0f // n points from A to B (edge to polygon) void b2EPCollider::ComputeAdjacency() { b2Vec2 v0 = m_edgeA.v0; b2Vec2 v1 = m_edgeA.v1; b2Vec2 v2 = m_edgeA.v2; b2Vec2 v3 = m_edgeA.v3; // Determine allowable the normal regions based on adjacency. // Note: it may be possible that no normal is admissable. b2Vec2 centerB = m_proxyB.centroid; if (m_edgeA.hasVertex0) { b2Vec2 e0 = v1 - v0; b2Vec2 e1 = v2 - v1; b2Vec2 n0(e0.y, -e0.x); b2Vec2 n1(e1.y, -e1.x); n0.Normalize(); n1.Normalize(); bool convex = b2Cross(n0, n1) >= 0.0f; bool front0 = b2Dot(n0, centerB - v0) >= 0.0f; bool front1 = b2Dot(n1, centerB - v1) >= 0.0f; if (convex) { if (front0 || front1) { m_limit11 = n1; m_limit12 = n0; } else { m_limit11 = -n1; m_limit12 = -n0; } } else { if (front0 && front1) { m_limit11 = n0; m_limit12 = n1; } else { m_limit11 = -n0; m_limit12 = -n1; } } } else { m_limit11.SetZero(); m_limit12.SetZero(); } if (m_edgeA.hasVertex3) { b2Vec2 e1 = v2 - v1; b2Vec2 e2 = v3 - v2; b2Vec2 n1(e1.y, -e1.x); b2Vec2 n2(e2.y, -e2.x); n1.Normalize(); n2.Normalize(); bool convex = b2Cross(n1, n2) >= 0.0f; bool front1 = b2Dot(n1, centerB - v1) >= 0.0f; bool front2 = b2Dot(n2, centerB - v2) >= 0.0f; if (convex) { if (front1 || front2) { m_limit21 = n2; m_limit22 = n1; } else { m_limit21 = -n2; m_limit22 = -n1; } } else { if (front1 && front2) { m_limit21 = n1; m_limit22 = n2; } else { m_limit21 = -n1; m_limit22 = -n2; } } } else { m_limit21.SetZero(); m_limit22.SetZero(); } }
void fitGraphs( const ZGConfig& cfg, const std::vector<float> masses, const std::string& width, const std::string& outdir, TFile* outfile, const std::string& name, const std::string& sel ) { std::cout << "+++ STARTING: " << name << std::endl; TString name_tstr(name); std::string plotdir = outdir + "/plots"; system( Form("mkdir -p %s", plotdir.c_str() ) ); TGraphErrors* gr_mean = new TGraphErrors(0); TGraphErrors* gr_sigma = new TGraphErrors(0); TGraphErrors* gr_width = new TGraphErrors(0); TGraphErrors* gr_alpha1 = new TGraphErrors(0); TGraphErrors* gr_n1 = new TGraphErrors(0); TGraphErrors* gr_alpha2 = new TGraphErrors(0); TGraphErrors* gr_n2 = new TGraphErrors(0); gr_mean ->SetName(Form("mean_w%s_%s" , width.c_str(), name.c_str())); gr_sigma ->SetName(Form("sigma_w%s_%s" , width.c_str(), name.c_str())); gr_width ->SetName(Form("width_w%s_%s" , width.c_str(), name.c_str())); gr_alpha1->SetName(Form("alpha1_w%s_%s", width.c_str(), name.c_str())); gr_n1 ->SetName(Form("n1_w%s_%s" , width.c_str(), name.c_str())); gr_alpha2->SetName(Form("alpha2_w%s_%s", width.c_str(), name.c_str())); gr_n2 ->SetName(Form("n2_w%s_%s" , width.c_str(), name.c_str())); TFile* file = TFile::Open( Form("%s/trees.root", cfg.getEventYieldDir().c_str()) ); outfile->cd(); int iPoint = 0; for( unsigned i=0; i<masses.size(); ++i ) { float thisMass = masses[i]; if( thisMass==1250. && name=="mm" && width=="0p014" ) continue; std::cout << "-> Starting mass: " << thisMass << std::endl; std::string signalName; if( thisMass <= 500. ) { signalName = std::string(Form("XZg_Spin0ToZG_ZToLL_W_%s_M_%.0f", width.c_str(), thisMass )); } else { signalName = std::string(Form("GluGluSpin0ToZG_ZToLL_W%s_M%.0f", width.c_str(), thisMass )); } TTree* tree0 = (TTree*)file->Get( signalName.c_str() ); if( tree0 == 0 ) continue; TTree* tree; if( sel=="" ) { tree = tree0; } else { tree = tree0->CopyTree(sel.c_str()); } float maxMassFact = (thisMass>1000. || width=="5p6" ) ? 1.5 : 1.3; RooRealVar x("boss_mass", "boss_mass", thisMass, 0.5*thisMass, maxMassFact*thisMass ); // Crystal-Ball RooRealVar mean( "mean", "mean", thisMass, 0.9*thisMass, 1.1*thisMass ); float sigmaResolution = ( width=="5p6" ) ? 0.03 : 0.015; RooRealVar sigma( "sigma", "sigma", sigmaResolution*thisMass, 0., 0.07*thisMass ); float alpha1_init = (width=="5p6" && thisMass<1000. ) ? 0.8 : 1.2; if( width=="5p6" && thisMass==1500.) alpha1_init=1.4; RooRealVar alpha1( "alpha1", "alpha1", alpha1_init, 0., 2.5 ); RooRealVar n1( "n1", "n1", 3., 0., 5. ); RooRealVar alpha2( "alpha2", "alpha2", 1.2, 0., 2.5 ); RooRealVar n2( "n2", "n2", 3.5, 0., 10. ); RooDoubleCBShape cb( "cb", "cb", x, mean, sigma, alpha1, n1, alpha2, n2 ); RooDataSet* data = new RooDataSet( "data", "data", RooArgSet(x), RooFit::Import(*tree) ); cb.fitTo( *data, RooFit::Strategy(2) ); RooPlot* frame = x.frame(); data->plotOn(frame); cb.plotOn(frame); TCanvas* c1 = new TCanvas("c1", "", 600, 600); c1->cd(); frame->Draw(); c1->SaveAs( Form("%s/fit_%s_m%.0f_w%s.eps", plotdir.c_str(), name.c_str(), thisMass, width.c_str()) ); c1->SaveAs( Form("%s/fit_%s_m%.0f_w%s.pdf", plotdir.c_str(), name.c_str(), thisMass, width.c_str()) ); c1->SetLogy(); c1->SaveAs( Form("%s/fit_%s_m%.0f_w%s_log.eps", plotdir.c_str(), name.c_str(), thisMass, width.c_str()) ); c1->SaveAs( Form("%s/fit_%s_m%.0f_w%s_log.pdf", plotdir.c_str(), name.c_str(), thisMass, width.c_str()) ); delete c1; gr_mean ->SetPoint( iPoint, thisMass, mean.getVal() ); gr_sigma ->SetPoint( iPoint, thisMass, sigma.getVal() ); gr_width ->SetPoint( iPoint, thisMass, sigma.getVal()/mean.getVal() ); gr_alpha1->SetPoint( iPoint, thisMass, alpha1.getVal() ); gr_n1 ->SetPoint( iPoint, thisMass, n1.getVal() ); gr_alpha2->SetPoint( iPoint, thisMass, alpha2.getVal() ); gr_n2 ->SetPoint( iPoint, thisMass, n2.getVal() ); gr_mean ->SetPointError( iPoint, 0., mean.getError() ); gr_sigma ->SetPointError( iPoint, 0., sigma.getError() ); gr_width ->SetPointError( iPoint, 0., sigma.getError()/mean.getVal() ); // random gr_alpha1->SetPointError( iPoint, 0., alpha1.getError() ); gr_n1 ->SetPointError( iPoint, 0., n1.getError() ); gr_alpha2->SetPointError( iPoint, 0., alpha2.getError() ); gr_n2 ->SetPointError( iPoint, 0., n2.getError() ); //gr_width->SetPointError( iPoint, 0., sqrt( sigma.getError()*sigma.getError()/(mean.getVal()*mean.getVal()) + sigma.getVal()*sigma.getVal()*mean.getError()*mean.getError()/(mean.getError()*mean.getError()*mean.getError()*mean.getError()) ) ); iPoint++; delete tree; delete data; } // for i TF1* f1_mean = fitGraph(plotdir, gr_mean , "Gaussian Mean [GeV]"); TF1* f1_sigma = fitGraph(plotdir, gr_sigma , "Gaussian Sigma [GeV]"); TF1* f1_width = fitGraph(plotdir, gr_width , "Gaussian #sigma/#mu"); TF1* f1_alpha1 = fitGraph(plotdir, gr_alpha1, "CB left #alpha"); TF1* f1_n1 = fitGraph(plotdir, gr_n1 , "CB left N"); TF1* f1_alpha2 = fitGraph(plotdir, gr_alpha2, "CB right #alpha"); TF1* f1_n2 = fitGraph(plotdir, gr_n2 , "CB right N"); f1_mean ->Write(); f1_sigma ->Write(); f1_width ->Write(); f1_alpha1->Write(); f1_n1 ->Write(); f1_alpha2->Write(); f1_n2 ->Write(); gr_mean ->Write(); gr_sigma ->Write(); gr_width ->Write(); gr_alpha1->Write(); gr_n1 ->Write(); gr_alpha2->Write(); gr_n2 ->Write(); }
int main () { double pause; //Overloaded Constructors cout<<"Overloaded Constructors:"<<endl; Rational a; cout<<"Default: " << a << endl; Rational b(3); cout<<"b(3): " << b << endl; Rational c(-2,5); cout<<"c(-2,5): " << c << endl; Rational d("1/2"); cout<<"d(\"1/2\"): " << d << endl << endl; //Copy Constructor Rational e(c); cout<<"Copy constructor of object initialized with ints (c(-2,5)): " << e << endl; Rational f(d); cout<<"Copy constructor of object initialized with string (d(\"1/2\")): " << f << endl << endl; //Overloaded Assignment Operators cout<<"Overloaded Assignment Operators"<<endl; Rational g(6,7); Rational j=g; cout<<"Int initialized object to object (g(6/7), j=g): "<<j<<endl; Rational k=3; cout<<"Int initialized object to int (k=3): "<<k<<endl; Rational l="5/6"; g=l; cout<<"Int initialized object to string (l=\"5/6\"): "<<g<< endl; Rational i("4/9"); j=i; cout<<"String initialized object to object (i(\"4/9\"), j=i): "<<j<<endl; i=3; cout<<"String initialized object to int (i=3): "<<i<<endl; i=l; cout<<"String initialized object to string (l=\"5/6\", i=l): "<<i<<endl<<endl; //Overloaded Arithemtic Operators Rational m(4,5); Rational m2("4/5"); Rational n(2,3); Rational n2("2/3"); Rational s(3,8); Rational s2("3/8"); cout<<"Overloaded Arithemtic Operators"<<endl; Rational o=m+n; cout<<"obj(4,5) + obj(2,3): "<<o<<endl; Rational o2=m2+n2; cout<<"obj(\"4/5\") + obj(\"2/3\"): "<<o2<<endl; Rational p=n+3; cout<<"obj(2,3) + int 3: "<<p<<endl; Rational p2=n2+3; cout<<"obj(\"2/3\") + int 3: "<<p2<<endl; Rational r2=s+string("1/2"); cout<<"obj(3,8) + str(\"1/2\"): "<<r2<<endl; Rational r=s2+string("1/2"); cout<<"obj(\"3/8\") + str(\"1/2\"): "<<r<<endl; //+= operator cout<<"+= Operator: "<<endl; m+=n; cout<<"(4,5) += (2,3): "<<m<<endl; m2+=n2; cout<<"(\"4/5\") += (\"2/3\"): "<<m2<<endl; n+=3; cout<<"(2,3) += 3: "<<n<<endl; n2+=3; cout<<"(\"2/3\") += 3: "<<n2<<endl; s+=string("1/2"); cout<<"(3,8) += (\"1/2\"): "<<s<<endl; s2+=string("1/2"); cout<<"(\"3/8\") += (\"1/2\"): "<<s2<<endl; //Relational operators cout<<"Relational Operators: "<<endl; if(m==n) { cout<<"m==n"<<endl; } else { cout<<"m is not equal to n"<<endl; } if(m>n) { cout<<"m is greater than n"<<endl; } else { cout<<"m is not greater than n"<<endl; } cout<<"a: "<<a<<endl; cout<<"b: "<<b<<endl; for(int i=0; i<4; i++) { cout<<"a++: "<<a++<<endl; cout<<"++b: "<<++b<<endl; } //Double conversion function Rational doubl(4,5); double doub=double(doubl); cout<<"double conversion of (4/5): "<<doub<<endl; cin>> pause; }
void runFullCovarianceTest() { shared_ptr<OsmMap> map(new OsmMap()); OGREnvelope env; env.MinX = 0; env.MinY = 0; env.MaxX = 1; env.MaxY = 1; map->setProjection(MapReprojector::createAeacProjection(env)); //OsmReader reader; //reader.read("test-files/ToyTestA.osm", map); // force the map bounds. NodePtr n1(new Node(Status::Unknown1, map->createNextNodeId(), 0, 0, 10)); NodePtr n2(new Node(Status::Unknown1, map->createNextNodeId(), 500, 500, 10)); map->addNode(n1); map->addNode(n2); for (double x = 0.0; x <= 500.0; x += 220) { for (double y = 0.0; y <= 500.0; y += 260) { NodePtr n(new Node(Status::Unknown1, map->createNextNodeId(), x, y, 10)); map->addNode(n); } } PertyOp uut; uut.setSeed(1); uut.setCsmParameters(9, 100); uut.setPermuteAlgorithm(QString::fromStdString(FullCovariance::className())); uut.setNamedOps(QStringList()); uut.apply(map); //// // Handy bit for regenerating the test values, _AFTER_ it has been visually verified. //// QList<long> keys = map->getNodeMap().uniqueKeys(); qSort(keys); // OsmWriter writer; // QDir().mkpath("test-output/perty"); // MapReprojector::reprojectToWgs84(map); // writer.write(map, "test-output/perty/BasicTest.osm"); // QString result = ""; // for (int i = 0; i < keys.size(); i++) // { // const NodePtr& n = map->getNode(keys[i]); // result += QString("n = map->getNode(keys[%1]);\n").arg(i); // result += QString("CPPUNIT_ASSERT_DOUBLES_EQUAL(%1, n->getX(), 1e-3);\n").arg(n->getX()); // result += QString("CPPUNIT_ASSERT_DOUBLES_EQUAL(%1, n->getY(), 1e-3);\n").arg(n->getY()); // } // LOG_INFO(result); NodePtr n; n = map->getNode(keys[0]); CPPUNIT_ASSERT_DOUBLES_EQUAL(442.786, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(280.686, n->getY(), 1e-3); n = map->getNode(keys[1]); CPPUNIT_ASSERT_DOUBLES_EQUAL(427.903, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(30.3295, n->getY(), 1e-3); n = map->getNode(keys[2]); CPPUNIT_ASSERT_DOUBLES_EQUAL(258.949, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(270.03, n->getY(), 1e-3); n = map->getNode(keys[3]); CPPUNIT_ASSERT_DOUBLES_EQUAL(259.729, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(20.6173, n->getY(), 1e-3); n = map->getNode(keys[4]); CPPUNIT_ASSERT_DOUBLES_EQUAL(21.9168, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(283.485, n->getY(), 1e-3); n = map->getNode(keys[5]); CPPUNIT_ASSERT_DOUBLES_EQUAL(-5.71276, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(8.83212, n->getY(), 1e-3); n = map->getNode(keys[6]); CPPUNIT_ASSERT_DOUBLES_EQUAL(499.789, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(486.422, n->getY(), 1e-3); n = map->getNode(keys[7]); CPPUNIT_ASSERT_DOUBLES_EQUAL(-5.71276, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(8.83212, n->getY(), 1e-3); }
void BDT_cuts_norm(){ gROOT->ProcessLine(".L ~/cern/project/lhcbStyle.C"); lhcbStyle(); const std::string filename("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/normalisation_samples/Lb2JpsipK_2011_2012_signal_withbdt.root"); const std::string treename = "withbdt"; const std::string filenameMC("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/normalisation_samples/Lb2JpsipK_MC_2011_2012_norm_withbdt.root"); TFile* file = TFile::Open( filename.c_str() ); if( !file ) std::cout << "file " << filename << " does not exist" << std::endl; TTree* tree = (TTree*)file->Get( treename.c_str() ); if( !tree ) std::cout << "tree " << treename << " does not exist" << std::endl; TFile* fileMC = TFile::Open( filenameMC.c_str() ); if( !fileMC ) std::cout << "file " << filenameMC << " does not exist" << std::endl; TTree* treeMC = (TTree*)fileMC->Get( treename.c_str() ); if( !treeMC ) std::cout << "tree " << treename << " does not exist" << std::endl; // -- signal, mass shape RooRealVar Lambda_b0_DTF_MASS_constr1("Lambda_b0_DTF_MASS_constr1","m(J/#psi pK^{-})", 5550., 5700., "MeV/c^{2}"); RooRealVar Jpsi_M("Jpsi_M","m(#mu#mu)", 3000., 3200., "MeV/c^{2}"); RooRealVar chi_c_M("chi_c_M","m(J/#psi#gamma)", 3400., 3700., "MeV/c^{2}"); RooRealVar mean("mean","mean", 5630., 5610., 5650.); RooRealVar sigma1("sigma1","sigma1", 10., 1., 100.); RooRealVar sigma2("sigma2","sigma2", 30.0, 5.0, 300.0); RooRealVar alpha1("alpha1","alpha1", 1.0, 0.5, 5.0); RooRealVar n1("n1","n1", 1.8, 0.2, 15.0); RooRealVar alpha2("alpha2","alpha2", -0.5, -5.5, 0.0); RooRealVar n2("n2","n2", 0.7, 0.2, 10.0); //RooRealVar bkgcat_chic("bkgcat_chic","bkgcat_chic", 0, 100); RooRealVar bdtg3("bdtg3", "bdtg3", -1.0, 1.0); RooRealVar frac2("frac2","frac2", 0.3, 0., 1.); RooGaussian gauss1("gauss1","gauss1", Lambda_b0_DTF_MASS_constr1, mean, sigma1); RooGaussian gauss2("gauss2","gauss2", Lambda_b0_DTF_MASS_constr1, mean, sigma2); RooCBShape cb1("cb1","cb1", Lambda_b0_DTF_MASS_constr1, mean, sigma1, alpha1, n1); RooCBShape cb2("cb2","cb2", Lambda_b0_DTF_MASS_constr1, mean, sigma2, alpha2, n2); RooAddPdf sig("sig", "sig", RooArgList(cb1, cb2), RooArgList( frac2 )); RooRealVar cbRatio("cbRatio","cb Ratio", 0.8, 0.1, 1.0); RooRealVar sigYield("sigYield","sig Yield", 4e2, 1e0, 1e6); RooRealVar bgYield("bgYield","bg Yield", 1e4, 1e0, 1e6); //put in values from fit_MC here <<--- DON'T FORGET TO CHANGE THESE IF THE FIT CHANGES!!! /* EXT PARAMETER INTERNAL INTERNAL NO. NAME VALUE ERROR STEP SIZE VALUE 1 alpha1 2.18020e+00 2.85078e-02 1.38432e-04 -2.56034e-01 2 alpha2 -2.79102e+00 6.74385e-02 1.51818e-04 -1.49177e-02 3 cbRatio 3.07172e-01 1.49204e-02 1.72642e-04 -5.69984e-01 4 mean 5.61985e+03 9.58397e-03 5.56682e-05 -9.66293e-02 5 n1 1.49358e+00 8.14447e-02 2.09300e-04 -9.70542e-01 6 n2 1.45276e+00 1.09864e-01 2.59028e-04 -8.39538e-01 7 sigma1 8.46303e+00 1.32851e-01 2.86985e-05 -1.01453e+00 8 sigma2 4.93976e+00 3.42842e-02 5.03572e-06 -1.44512e+00 */ alpha1.setVal( 2.18020e+00 ); alpha2.setVal( -2.79102e+00 ); n1.setVal( 1.49358e+00 ); n2.setVal( 1.45276e+00 ); frac2.setVal( 3.07172e-01 ); sigma1.setVal( 8.46303e+00 ); sigma2.setVal( 4.93976e+00 ); alpha1.setConstant( true ); alpha2.setConstant( true ); frac2.setConstant( true ); n1.setConstant( true ); n2.setConstant( true ); sigma1.setConstant( true ); sigma2.setConstant( true ); // -- bg, mass shape RooRealVar a1("a1","a1", -0.1, -0.5, 0.5); RooChebychev comb("comb","comb", Lambda_b0_DTF_MASS_constr1, a1); RooRealVar mean3("mean3","mean3", 5560., 5500., 5600.); RooRealVar sigma3("sigma3","sigma3", 5., 1., 10.); RooRealVar frac3("frac3","frac", 0.2, 0.0, 0.3); RooGaussian gauss3("gauss3","gauss3", Lambda_b0_DTF_MASS_constr1, mean3, sigma3); //RooAddPdf bg("bg","bg", RooArgList(comb), RooArgList(frac3)); // -- add signal & bg RooAddPdf pdf("pdf", "pdf", RooArgList(sig, comb), RooArgList( sigYield, bgYield)); double efficiencies1[40]; double efficiencies1_error[40]; double bdt_cuts[40]; double efficiencies2[40]; double efficiencies2_error[40]; double sideband_bg_val[40]; double MC_pre = treeMC->GetEntries(); double effvals[40]; //loop starting here for(int i=0; i < 40; i=i+1) { double cut_val = -1.0 + i*0.05; //double cut_val = -1.0; // testing bdt_cuts[i] = cut_val; std::stringstream c; c << "bdtg3" << " >= " << cut_val; const std::string cut = c.str(); //std::cout << cut; RooArgSet obs; obs.add(Lambda_b0_DTF_MASS_constr1); //obs.add(chi_c_Mp); //obs.add(mass_pK); obs.add(Jpsi_M); obs.add(chi_c_M); obs.add(bdtg3); RooDataSet ds("ds","ds", obs, RooFit::Import(*tree), RooFit::Cut(cut.c_str())); RooPlot* plot = Lambda_b0_DTF_MASS_constr1.frame(); RooFitResult * result = pdf.fitTo( ds, RooFit::Extended() ); double sig_val = sigYield.getVal(); double bg_val = bgYield.getVal(); double sig_error = sigYield.getError(); double bg_error = bgYield.getError(); double efficiency1 = (sig_val)/(sqrt(sig_val + bg_val)); efficiencies1[i] = efficiency1; double efficiency1_error_sq = (pow(sig_error,2)/(sig_val+bg_val) + (pow(sig_val,2)*(pow(sig_error,2)+pow(bg_error,2))/(4*pow((sig_val+bg_val),3)))); double efficiency1_error = sqrt(efficiency1_error_sq); efficiencies1_error[i] = efficiency1_error; /* double MC_post = treeMC->GetEntries(cut.c_str()); double eff_val = MC_post/MC_pre; //something here to get the sideband background count Lambda_b0_DTF_MASS_constr1.setRange("R", 5650., 5700.); RooFitResult * sideband = bg.fitTo( ds, RooFit::Range("R") ); sideband->Print(); Lambda_b0_DTF_MASS_constr1.setRange("R", 5650., 5700.); RooAbsReal* integral = pdf.createIntegral(Lambda_b0_DTF_MASS_constr1, RooFit::Range("R")); //std::cout << integral->getVal() << std::endl; //std::cout << integral->getError() << std::endl; //Double_t sideband_bg_val = integral->getVal(); //double sideband_bg_error = integral->getError(); std::stringstream r; r << "bdtg3" << " >= " << cut_val << " && Lambda_b0_DTF_MASS_constr1 >= 5650 && Lambda_b0_DTF_MASS_constr1 <= 5700"; const std::string cut2 = r.str(); double integ = tree->GetEntries(cut2.c_str()); //double integ = integral->getVal(); double efficiency2 = eff_val/(5./2. + sqrt(integ)); efficiencies2[i] = efficiency2; effvals[i]=eff_val; std::cout << "\n" << integ << std::endl; std::cout << "\n" << eff_val << std::endl; std::cout << "\n" << efficiency2 << std::endl; */ //double efficiency2_error = efficiency2*sqrt(pow(eff_error/eff_val,2)+(1/(4*sideband_bg_val))*pow(sideband_bg_error/(5/2+sideband_bg_val),2)); //std::cout << "\n\n" << "BDT cut value = " << cut_val << "\n" ; //std::cout << "S = " << sig_val << " +/- " << sig_error << "\n" ; //std::cout << "B = " << bg_val << " +/- " << bg_error << "\n" ; //std::cout << "S/sqrt(S+B) = " << efficiency << " +/- " << efficiency_error << "\n\n" ; //ds.plotOn( plot ); //pdf.plotOn( plot ); //RooPlot* plotPullMass = mass.frame(); //plotPullMass->addPlotable( plot->pullHist() ); //plotPullMass->SetMinimum(); //plotPullMass->SetMaximum(); //std::cout << cut_val; } TCanvas *c1 = new TCanvas(); //double zeros[20]; //for (i=0, i<20, i++) zeros[i]=0.0; TGraphErrors* graph = new TGraphErrors(40, bdt_cuts, efficiencies1, 0, efficiencies1_error); graph->SetTitle("S/sqrt(S+B) vs BDTG3 cut"); //graph->SetMarkerColor(4); //graph->SetMarkerStyle(20); //graph->SetMarkerSize(1.0); graph->GetXaxis()->SetTitle("BDTG3 cut (>)"); graph->GetXaxis()->SetRangeUser(-1.0,1.0); graph->GetYaxis()->SetTitle("S/sqrt(S+B)"); //graph->Fit("pol5"); graph->Draw("AP"); c1->SaveAs("~/cern/plots/bdt_cuts_norm/Lb2JpsipK_2011_2012_BDTG3_cuts_S_sqrtS+B.pdf"); //return c1; //std::cout << efficiencies1_error[5] << std::endl; //gStyle->SetOptFit(1011); /*TCanvas *c2 = new TCanvas(); TGraph* graph2 = new TGraph(40, bdt_cuts, efficiencies2); graph2->SetTitle("eff/[5/2+sqrt(B)] vs BDTG3 cut"); graph2->SetMarkerColor(4); graph2->SetMarkerStyle(20); graph2->SetMarkerSize(1.0); graph2->GetXaxis()->SetTitle("BDTG3 cut (>)"); graph2->GetXaxis()->SetRangeUser(-1.0,1.0); graph2->GetYaxis()->SetTitle("eff/[5/2+sqrt(B)]"); //graph2->Fit("pol7"); graph2->Draw("AP"); c2->SaveAs("~/cern/plots/bdt_cuts_norm/Lb2JpsipK_2011_2012_BDTG3_cuts_Punzi.png"); //return c2; */ /* TCanvas* c = new TCanvas(); TPad* pad1 = new TPad("pad1","pad1", 0, 0.3, 1, 1.0); pad1->SetBottomMargin(0.1); pad1->SetTopMargin(0.1); pad1->Draw(); c->cd(); TPad* pad2 = new TPad("pad2","pad2", 0, 0, 1, 0.3); pad2->SetBottomMargin(0.1); pad2->SetTopMargin(0.0); pad2->Draw(); //pdf.plotOn( plot, RooFit::Components( DfbPdf ), RooFit::LineColor( kRed ), RooFit::LineStyle(kDashed) ); //pdf.plotOn( plot, RooFit::Components( promptPdf ), RooFit::LineColor( kBlue ), RooFit::LineStyle(kDotted) ); //pdf.plotOn( plot, RooFit::Components( bgPdf ), RooFit::LineColor( kOrange ), RooFit::LineStyle(kDashDotted) ); pad1->cd(); plot->Draw(); pad2->cd(); plotPullMass->Draw("AP"); c->SaveAs(out_file_mass); RooStats::SPlot* sData = new RooStats::SPlot("sData","An SPlot", ds, &pdf, RooArgList(sigYield, bgYield) ); RooDataSet * dataw_z = new RooDataSet(ds.GetName(),ds.GetTitle(),&ds,*(ds.get()),0,"sigYield_sw") ; */ /* TCanvas* d = new TCanvas(); RooPlot* w_mass_chicp = mass_chicp.frame(); dataw_z->plotOn(w_mass_chicp, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ; w_mass_chicp->Draw(); d->SaveAs("m_chicp_sweighted.png"); TCanvas* e = new TCanvas(); RooPlot* w_mass_pK = mass_pK.frame(); dataw_z->plotOn(w_mass_pK, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ; w_mass_pK->Draw(); e->SaveAs("m_pK_sweighted.png"); */ /* TCanvas* f = new TCanvas(); RooPlot* w_mass_Jpsi = mass_Jpsi.frame(); dataw_z->plotOn(w_mass_Jpsi, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ; w_mass_Jpsi->Draw(); f->SaveAs("m_Jpsi_sweighted.png"); TCanvas* g = new TCanvas(); RooPlot* w_mass_Chic = mass_Chic.frame(); dataw_z->plotOn(w_mass_Chic, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ; w_mass_Chic->Draw(); g->SaveAs("m_Chic_sweighted.png"); */ }
DEF_TEST(PDFPrimitives, reporter) { SkAutoTUnref<SkPDFInt> int42(new SkPDFInt(42)); SimpleCheckObjectOutput(reporter, int42.get(), "42"); SkAutoTUnref<SkPDFScalar> realHalf(new SkPDFScalar(SK_ScalarHalf)); SimpleCheckObjectOutput(reporter, realHalf.get(), "0.5"); SkAutoTUnref<SkPDFScalar> bigScalar(new SkPDFScalar(110999.75f)); #if !defined(SK_ALLOW_LARGE_PDF_SCALARS) SimpleCheckObjectOutput(reporter, bigScalar.get(), "111000"); #else SimpleCheckObjectOutput(reporter, bigScalar.get(), "110999.75"); SkAutoTUnref<SkPDFScalar> biggerScalar(new SkPDFScalar(50000000.1)); SimpleCheckObjectOutput(reporter, biggerScalar.get(), "50000000"); SkAutoTUnref<SkPDFScalar> smallestScalar(new SkPDFScalar(1.0/65536)); SimpleCheckObjectOutput(reporter, smallestScalar.get(), "0.00001526"); #endif SkAutoTUnref<SkPDFString> stringSimple( new SkPDFString("test ) string ( foo")); SimpleCheckObjectOutput(reporter, stringSimple.get(), "(test \\) string \\( foo)"); SkAutoTUnref<SkPDFString> stringComplex( new SkPDFString("\ttest ) string ( foo")); SimpleCheckObjectOutput(reporter, stringComplex.get(), "<0974657374202920737472696E67202820666F6F>"); SkAutoTUnref<SkPDFName> name(new SkPDFName("Test name\twith#tab")); const char expectedResult[] = "/Test#20name#09with#23tab"; CheckObjectOutput(reporter, name.get(), expectedResult, strlen(expectedResult), false, false); SkAutoTUnref<SkPDFName> escapedName(new SkPDFName("A#/%()<>[]{}B")); const char escapedNameExpected[] = "/A#23#2F#25#28#29#3C#3E#5B#5D#7B#7DB"; CheckObjectOutput(reporter, escapedName.get(), escapedNameExpected, strlen(escapedNameExpected), false, false); // Test that we correctly handle characters with the high-bit set. const unsigned char highBitCString[] = {0xDE, 0xAD, 'b', 'e', 0xEF, 0}; SkAutoTUnref<SkPDFName> highBitName( new SkPDFName((const char*)highBitCString)); const char highBitExpectedResult[] = "/#DE#ADbe#EF"; CheckObjectOutput(reporter, highBitName.get(), highBitExpectedResult, strlen(highBitExpectedResult), false, false); SkAutoTUnref<SkPDFArray> array(new SkPDFArray); SimpleCheckObjectOutput(reporter, array.get(), "[]"); array->append(int42.get()); SimpleCheckObjectOutput(reporter, array.get(), "[42]"); array->append(realHalf.get()); SimpleCheckObjectOutput(reporter, array.get(), "[42 0.5]"); SkAutoTUnref<SkPDFInt> int0(new SkPDFInt(0)); array->append(int0.get()); SimpleCheckObjectOutput(reporter, array.get(), "[42 0.5 0]"); SkAutoTUnref<SkPDFInt> int1(new SkPDFInt(1)); array->setAt(0, int1.get()); SimpleCheckObjectOutput(reporter, array.get(), "[1 0.5 0]"); SkAutoTUnref<SkPDFDict> dict(new SkPDFDict); SimpleCheckObjectOutput(reporter, dict.get(), "<<>>"); SkAutoTUnref<SkPDFName> n1(new SkPDFName("n1")); dict->insert(n1.get(), int42.get()); SimpleCheckObjectOutput(reporter, dict.get(), "<</n1 42\n>>"); SkAutoTUnref<SkPDFName> n2(new SkPDFName("n2")); SkAutoTUnref<SkPDFName> n3(new SkPDFName("n3")); dict->insert(n2.get(), realHalf.get()); dict->insert(n3.get(), array.get()); SimpleCheckObjectOutput(reporter, dict.get(), "<</n1 42\n/n2 0.5\n/n3 [1 0.5 0]\n>>"); TestPDFStream(reporter); TestCatalog(reporter); TestObjectRef(reporter); TestSubstitute(reporter); test_issue1083(); TestImages(reporter); }
PView *GMSH_CVTRemeshPlugin::execute(PView *v) { //TODO normalization GModel* m = GModel::current() ; std::vector<double> vertices ; std::vector<unsigned int> faces ; unsigned int offset = 0 ; for(GModel::fiter it = m->firstFace(); it != m->lastFace(); ++it) { (*it)->buildSTLTriangulation() ; for(unsigned int i = 0; i < (*it)->stl_vertices.size(); ++i) { GPoint p = (*it)->point((*it)->stl_vertices[i]) ; vertices.push_back(p.x()) ; vertices.push_back(p.y()) ; vertices.push_back(p.z()) ; } for(unsigned int i = 0; i < (*it)->stl_triangles.size(); ++i) { faces.push_back((*it)->stl_triangles[i]+offset) ; } offset += (*it)->stl_vertices.size() ; } Revoropt::MeshBuilder<3> mesh ; mesh.swap_vertices(vertices) ; mesh.swap_faces(faces) ; double mesh_center[3] ; double mesh_scale ; Revoropt::normalize_mesh(&mesh, mesh_center, &mesh_scale) ; double nradius = (double)CVTRemeshOptions_Number[5].def ; //normals std::vector<double> normals(3*mesh.vertices_size()) ; Revoropt::full_robust_vertex_normals(&mesh,nradius,normals.data()) ; //lifted vertices std::vector<double> lifted_vertices(6*mesh.vertices_size(), 0) ; for(unsigned int vertex = 0; vertex < mesh.vertices_size(); ++vertex) { std::copy( mesh.vertex(vertex), mesh.vertex(vertex)+3, lifted_vertices.data()+6*vertex ) ; std::copy( normals.data()+3*vertex, normals.data()+3*vertex+3, lifted_vertices.data()+6*vertex+3 ) ; } //setup lifted mesh Revoropt::ROMeshWrapper<3,6> lifted_mesh( lifted_vertices.data(), lifted_vertices.size()/6, &mesh ) ; //triangle weight factor double twfactor = (double)CVTRemeshOptions_Number[3].def ; //face ratios std::vector<double> triangle_weights(lifted_mesh.faces_size()) ; if(twfactor > 0) { for(unsigned int f = 0; f < lifted_mesh.faces_size(); ++f) { //vertices of the initial triangle const unsigned int* fverts = mesh.face(f) ; //positions const double* x[3] ; for(int i=0; i<3; ++i) { x[i] = lifted_mesh.vertex(fverts[i]) ; } //ratio double ratio = 1 ; //vectors typedef Eigen::Matrix<double,3,1> Vector3 ; Eigen::Map<const Vector3> v0(x[0]) ; Eigen::Map<const Vector3> v1(x[1]) ; Eigen::Map<const Vector3> v2(x[2]) ; //triangle frame Vector3 U = (v1-v0) ; const double U_len = U.norm() ; if(U_len > 0) { U /= U_len ; Vector3 H = (v2-v0) ; H = H - H.dot(U)*U ; const double H_len = H.norm() ; if(H_len > 0) { //we know that the triangle is not flat H /= H_len ; //gradient of the barycentric weights in the triangle Eigen::Matrix<double,3,2> bar_grads ; bar_grads(2,0) = 0 ; bar_grads(2,1) = 1/H_len ; //gradient norms of every normal component for(int i = 0; i < 2; ++i) { //reference frame for the vertex Eigen::Map<const Vector3> vi0(x[(i+1)%3]) ; Eigen::Map<const Vector3> vi1(x[(i+2)%3]) ; Eigen::Map<const Vector3> vi2(x[ i ]) ; Vector3 Ui = (vi1-vi0) ; Ui /= Ui.norm() ; Vector3 Hi = (vi2-vi0) ; Hi = Hi - Hi.dot(Ui)*Ui ; const double Hi_invlen = 1/Hi.norm() ; Hi *= Hi_invlen ; bar_grads(i,0) = Hi.dot(U)*Hi_invlen ; bar_grads(i,1) = Hi.dot(H)*Hi_invlen ; } //gradient of each component of the normal Eigen::Map<const Vector3> n0(x[0]+3) ; Eigen::Map<const Vector3> n1(x[1]+3) ; Eigen::Map<const Vector3> n2(x[2]+3) ; Eigen::Matrix<double,3,2> n_grads = Eigen::Matrix<double,3,2>::Zero() ; n_grads = n0*bar_grads.row(0) ; n_grads += n1*bar_grads.row(1) ; n_grads += n2*bar_grads.row(2) ; //maximal gradient norm double g_max = n_grads.row(0).dot(n_grads.row(0)) ; double g_other = n_grads.row(1).dot(n_grads.row(1)) ; g_max = g_max > g_other ? g_max : g_other ; g_other = n_grads.row(2).dot(n_grads.row(2)) ; g_max = g_max > g_other ? g_max : g_other ; if(g_max == g_max) { //prevent nan ratio += g_max ; } } } triangle_weights[f] = pow(ratio,twfactor) ; } } //normal factor double nfactor = (double)CVTRemeshOptions_Number[2].def ; ; //weight the normal component by the provided factor for(unsigned int i = 0; i<lifted_mesh.vertices_size(); ++i) { double* v = lifted_vertices.data() + 6*i ; v[3]*= nfactor ; v[4]*= nfactor ; v[5]*= nfactor ; } //number of sites unsigned int nsites = (unsigned int)CVTRemeshOptions_Number[0].def ; //lifted sites std::vector<double> lifted_sites(6*nsites) ; if(twfactor > 0) { Revoropt::generate_random_sites< Revoropt::ROMesh<3,6> >( &lifted_mesh, nsites, lifted_sites.data(), triangle_weights.data() ) ; } else { Revoropt::generate_random_sites< Revoropt::ROMesh<3,6> >( &lifted_mesh, nsites, lifted_sites.data() ) ; } //setup the cvt minimizer Revoropt::CVT::DirectMinimizer< Revoropt::ROMesh<3,6> > cvt ; cvt.set_sites(lifted_sites.data(), nsites) ; cvt.set_mesh(&lifted_mesh) ; if(twfactor > 0) { cvt.set_triangle_weights(triangle_weights.data()) ; } //setup the callback SolverCallback callback ; //number of iterations unsigned int niter = (unsigned int)CVTRemeshOptions_Number[1].def ; ; unsigned int aniso_niter = std::min<unsigned int>(10,niter) ; //solver status int status = 0 ; //isotropic iterations if(niter > 10) { aniso_niter = std::max(aniso_niter,niter*10/100) ; cvt.set_anisotropy(1) ; status = cvt.minimize<Revoropt::Solver::AlgLBFGS>(niter-aniso_niter, &callback) ; } //anisotropic iterations if(niter > 0) { //tangent space anisotropy double tanisotropy = (double)CVTRemeshOptions_Number[4].def ; ; //anisotropic iterations cvt.set_anisotropy(tanisotropy) ; status = cvt.minimize<Revoropt::Solver::AlgLBFGS>(aniso_niter, &callback) ; } //rdt std::vector<unsigned int> rdt_triangles ; Revoropt::RDTBuilder< Revoropt::ROMesh<3,6> > build_rdt(rdt_triangles) ; Revoropt::RVD< Revoropt::ROMesh<3,6> > rvd ; rvd.set_sites(lifted_sites.data(), nsites) ; rvd.set_mesh(&lifted_mesh) ; rvd.compute(build_rdt) ; GFace* res_face = new discreteFace(m, m->getMaxElementaryNumber(2)+1) ; m->add(res_face) ; //scale back and transfer to gmsh std::vector<MVertex*> m_verts(nsites) ; for(unsigned int i = 0; i < nsites; ++i) { m_verts[i] = new MVertex( lifted_sites[6*i ]*mesh_scale + mesh_center[0], lifted_sites[6*i+1]*mesh_scale + mesh_center[1], lifted_sites[6*i+2]*mesh_scale + mesh_center[2] ) ; res_face->addMeshVertex(m_verts[i]) ; } for(unsigned int i = 0; i < rdt_triangles.size()/3; ++i) { res_face->addTriangle( new MTriangle( m_verts[rdt_triangles[3*i ]], m_verts[rdt_triangles[3*i+1]], m_verts[rdt_triangles[3*i+2]] ) ) ; } res_face->setAllElementsVisible(true) ; return v ; }
void runDirectSequentialSimulationTest() { shared_ptr<OsmMap> map(new OsmMap()); OGREnvelope env; env.MinX = 0; env.MinY = 0; env.MaxX = 1; env.MaxY = 1; map->setProjection(MapProjector::createAeacProjection(env)); //OsmReader reader; //reader.read("test-files/ToyTestA.osm", map); // force the map bounds. NodePtr n1(new Node(Status::Unknown1, map->createNextNodeId(), 0, 0, 10)); NodePtr n2(new Node(Status::Unknown1, map->createNextNodeId(), 500, 500, 10)); map->addNode(n1); map->addNode(n2); for (double x = 0.0; x <= 500.0; x += 220) { for (double y = 0.0; y <= 500.0; y += 260) { NodePtr n(new Node(Status::Unknown1, map->createNextNodeId(), x, y, 10)); map->addNode(n); } } PertyOp uut; uut.setSeed(1); uut.setPermuteAlgorithm(QString::fromStdString(DirectSequentialSimulation::className())); uut.setCsmParameters(9, 100); uut.setNamedOps(QStringList()); uut.apply(map); //// // Handy bit for regenerating the test values, _AFTER_ it has been visually verified. //// QSet<long> nids; NodeMap::const_iterator it = map->getNodeMap().begin(); while (it != map->getNodeMap().end()) { nids.insert(it->first); it++; } QList<long> keys = QList<long>::fromSet(nids); qSort(keys); // OsmWriter writer; // QDir().mkpath("test-output/perty"); // MapProjector::reprojectToWgs84(map); // writer.write(map, "test-output/perty/BasicTest.osm"); // QString result = ""; // for (int i = 0; i < keys.size(); i++) // { // const NodePtr& n = map->getNode(keys[i]); // result += QString("n = map->getNode(keys[%1]);\n").arg(i); // result += QString("CPPUNIT_ASSERT_DOUBLES_EQUAL(%1, n->getX(), 1e-3);\n").arg(n->getX()); // result += QString("CPPUNIT_ASSERT_DOUBLES_EQUAL(%1, n->getY(), 1e-3);\n").arg(n->getY()); // } // LOG_INFO(result); NodePtr n; n = map->getNode(keys[0]); CPPUNIT_ASSERT_DOUBLES_EQUAL(418.5, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(210.61, n->getY(), 1e-3); n = map->getNode(keys[1]); CPPUNIT_ASSERT_DOUBLES_EQUAL(417.754, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(-5.31176, n->getY(), 1e-3); n = map->getNode(keys[2]); CPPUNIT_ASSERT_DOUBLES_EQUAL(203.892, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(179.617, n->getY(), 1e-3); n = map->getNode(keys[3]); CPPUNIT_ASSERT_DOUBLES_EQUAL(168.138, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(-28.9846, n->getY(), 1e-3); n = map->getNode(keys[4]); CPPUNIT_ASSERT_DOUBLES_EQUAL(-12.5047, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(257.038, n->getY(), 1e-3); n = map->getNode(keys[5]); CPPUNIT_ASSERT_DOUBLES_EQUAL(-14.5567, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(-4.34252, n->getY(), 1e-3); n = map->getNode(keys[6]); CPPUNIT_ASSERT_DOUBLES_EQUAL(534.813, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(475.291, n->getY(), 1e-3); n = map->getNode(keys[7]); CPPUNIT_ASSERT_DOUBLES_EQUAL(-14.5567, n->getX(), 1e-3); CPPUNIT_ASSERT_DOUBLES_EQUAL(-4.34252, n->getY(), 1e-3); }
void fitSingleMass( const std::string& basedir, float mass, const std::string& width, TGraphErrors* gr_mean, TGraphErrors* gr_sigma, TGraphErrors* gr_width, TGraphErrors* gr_alpha1, TGraphErrors* gr_n1, TGraphErrors* gr_alpha2, TGraphErrors* gr_n2 ) { std::string outdir = "genSignalShapes"; system( Form("mkdir -p %s", outdir.c_str()) ); std::string dataset( Form( "GluGluSpin0ToZGamma_ZToLL_W_%s_M_%.0f_TuneCUEP8M1_13TeV_pythia8", width.c_str(), mass ) ); std::cout << "-> Starting: " << dataset << std::endl; system( Form("ls %s/%s/crab_%s/*/0000/genAna_1.root >> toBeAdded.txt", basedir.c_str(), dataset.c_str(), dataset.c_str() ) ); TChain* tree = new TChain("mt2"); ifstream ifs("toBeAdded.txt"); while( ifs.good() ) { std::string fileName; ifs >> fileName; TString fileName_tstr(fileName); if( !fileName_tstr.Contains("pnfs") ) continue; tree->Add(Form("$DCAP/%s/mt2", fileName.c_str()) ); } system( "rm toBeAdded.txt" ); if( tree->GetEntries()==0 ) return; int ngenPart; tree->SetBranchAddress( "ngenPart", &ngenPart ); float genPart_pt[100]; tree->SetBranchAddress( "genPart_pt", genPart_pt ); float genPart_eta[100]; tree->SetBranchAddress( "genPart_eta", genPart_eta ); float genPart_phi[100]; tree->SetBranchAddress( "genPart_phi", genPart_phi ); float genPart_mass[100]; tree->SetBranchAddress( "genPart_mass", genPart_mass ); int genPart_pdgId[100]; tree->SetBranchAddress( "genPart_pdgId", genPart_pdgId ); int genPart_motherId[100]; tree->SetBranchAddress( "genPart_motherId", genPart_motherId ); int genPart_status[100]; tree->SetBranchAddress( "genPart_status", genPart_status ); RooRealVar* x = new RooRealVar("boss_mass", "boss_mass", mass, 0.5*mass, 1.5*mass ); RooDataSet* data = new RooDataSet( "data", "data", RooArgSet(*x) ); int nentries = tree->GetEntries(); for( int iEntry = 0; iEntry<nentries; ++iEntry ) { if( iEntry % 25000 == 0 ) std::cout << " Entry: " << iEntry << " / " << nentries << std::endl; tree->GetEntry(iEntry); TLorentzVector leptPlus; TLorentzVector leptMinus; TLorentzVector photon; bool foundLeptPlus = false; bool foundLeptMinus = false; bool foundPhoton = false; bool tauEvent = false; for( int iPart=0; iPart<ngenPart; ++iPart ) { if( genPart_status[iPart]!=1 ) continue; if( abs(genPart_pdgId[iPart])==15 ) { tauEvent = true; break; } if( (genPart_pdgId[iPart]==+11 || genPart_pdgId[iPart]==+13) && genPart_motherId[iPart]==23 ) { leptMinus.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] ); foundLeptMinus = true; } if( (genPart_pdgId[iPart]==-11 || genPart_pdgId[iPart]==-13) && genPart_motherId[iPart]==23 ) { leptPlus.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] ); foundLeptPlus = true; } if( genPart_pdgId[iPart]==22 && genPart_motherId[iPart]==25 ) { photon.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] ); foundPhoton = true; } } // for genparts if( tauEvent ) continue; if( !foundLeptPlus || !foundLeptMinus || !foundPhoton ) continue; if( photon.Pt() < 40. ) continue; float ptMax = TMath::Max( leptPlus.Pt(), leptMinus.Pt() ); float ptMin = TMath::Min( leptPlus.Pt(), leptMinus.Pt() ); if( ptMax<25. ) continue; if( ptMin<20. ) continue; if( fabs( photon.Eta() ) > 2.5 ) continue; if( fabs( photon.Eta())>1.44 && fabs( photon.Eta())<1.57 ) continue; if( fabs( leptPlus.Eta() ) > 2.4 ) continue; if( fabs( leptMinus.Eta() ) > 2.4 ) continue; if( photon.DeltaR( leptPlus ) < 0.4 ) continue; if( photon.DeltaR( leptMinus ) < 0.4 ) continue; TLorentzVector zBoson = leptPlus + leptMinus; if( zBoson.M() < 50. ) continue; TLorentzVector boss = zBoson + photon; if( boss.M() < 200. ) continue; if( photon.Pt()/boss.M()< 40./150. ) continue; x->setVal(boss.M()); data->add(RooArgSet(*x)); } //RooRealVar* bw_mean = new RooRealVar( "bw_mean", "Breit-Wigner Mean" , mass, 0.2*mass, 1.8*mass ); //RooRealVar* bw_gamma = new RooRealVar( "bw_gamma", "Breit-Wigner Width", 0.01*mass, 0., 0.3*mass ); //RooBreitWigner* model = new RooBreitWigner( "bw", "Breit-Wigner", *x, *bw_mean, *bw_gamma); // Crystal-Ball RooRealVar mean( "mean", "mean", mass, 0.9*mass, 1.1*mass ); RooRealVar sigma( "sigma", "sigma", 0.015*mass, 0., 0.07*mass ); RooRealVar alpha1( "alpha1", "alpha1", 1.2, 0., 2.5 ); RooRealVar n1( "n1", "n1", 3., 0., 5. ); RooRealVar alpha2( "alpha2", "alpha2", 1.2, 0., 2.5 ); RooRealVar n2( "n2", "n2", 3., 0., 10. ); RooDoubleCBShape* model = new RooDoubleCBShape( "cb", "cb", *x, mean, sigma, alpha1, n1, alpha2, n2 ); model->fitTo( *data ); int npoints = gr_mean->GetN(); gr_mean ->SetPoint( npoints, mass, mean.getVal() ); gr_sigma ->SetPoint( npoints, mass, sigma.getVal() ); gr_width ->SetPoint( npoints, mass, sigma.getVal()/mean.getVal() ); gr_alpha1->SetPoint( npoints, mass, alpha1.getVal() ); gr_alpha2->SetPoint( npoints, mass, alpha2.getVal() ); gr_n1 ->SetPoint( npoints, mass, n1.getVal() ); gr_n2 ->SetPoint( npoints, mass, n2.getVal() ); gr_mean ->SetPointError( npoints, 0., mean.getError() ); gr_sigma ->SetPointError( npoints, 0., sigma.getError() ); gr_width ->SetPointError( npoints, 0., sigma.getError()/mean.getVal() ); gr_alpha1->SetPointError( npoints, 0., alpha1.getError() ); gr_alpha2->SetPointError( npoints, 0., alpha2.getError() ); gr_n1 ->SetPointError( npoints, 0., n1.getError() ); gr_n2 ->SetPointError( npoints, 0., n2.getError() ); //gr_mean ->SetPoint ( npoints, mass, bw_mean->getVal() ); //gr_gamma->SetPoint ( npoints, mass, bw_gamma->getVal() ); //gr_width->SetPoint ( npoints, mass, bw_gamma->getVal()/bw_mean->getVal() ); //gr_mean ->SetPointError( npoints, 0., bw_mean->getError() ); //gr_gamma->SetPointError( npoints, 0., bw_gamma->getError()/bw_mean->getVal() ); //gr_width->SetPointError( npoints, 0., bw_gamma->getError()/bw_mean->getVal() ); RooPlot* plot = x->frame(); data->plotOn(plot); model->plotOn(plot); TCanvas* c1 = new TCanvas( "c1", "", 600, 600 ); c1->cd(); plot->Draw(); c1->SaveAs( Form("%s/fit_m%.0f_%s.eps", outdir.c_str(), mass, width.c_str()) ); c1->SaveAs( Form("%s/fit_m%.0f_%s.pdf", outdir.c_str(), mass, width.c_str()) ); c1->SetLogy(); c1->SaveAs( Form("%s/fit_m%.0f_%s_log.eps", outdir.c_str(), mass, width.c_str()) ); c1->SaveAs( Form("%s/fit_m%.0f_%s_log.pdf", outdir.c_str(), mass, width.c_str()) ); //delete bw_mean; //delete bw_gamma; delete c1; delete data; delete model; delete plot; delete x; }