Empty Histogram: Values Possibly Not Recognized? - c++

I had a question on how to fix an empty histogram. I am creating a vector called "mass" that I want to plot its histogram (as can be seen in the code) from the variables in my Branches Muon_PT, Muon_Eta, Muon_Phi, and mass. However, I get an empty histogram. I am suspecting that it is not reading the branch variables. I suspect this because when I write something like:
auto idx_cmb = Combinations(Muon_PT, 2);
I get the error that:
Warning in <TROOT::Append>: Replacing existing TH1: mass (Potential memory leak).
terminate called after throwing an instance of 'std::runtime_error'
what(): Cannot make unique combinations of size 2 from vector of size 0.
Although when I plot the histogram in the ROOT terminal I am able to get a histogram. It is just when I write it in its own script I am not able to call the branches.
Below is my code:
#include "Math/Vector4Dfwd.h"
#include "ROOT/RDF/RInterface.hxx"
#include "ROOT/RDataFrame.hxx"
#include "ROOT/RVec.hxx"
#include "TCanvas.h"
#include "TH1D.h"
#include "TLatex.h"
#include "TLegend.h"
#include "TStyle.h"
#include <string>
#include <vector>
using namespace ROOT::VecOps;
const auto z_mass = 91.2;
void selectMuon() {
ROOT::EnableImplicitMT();
ROOT::RDataFrame df("Delphes;4", "tag_1_delphes_events.root");
TH1F *histDiMuonMass = new TH1F(
"mass", "M_{inv}(Z[3]Z[5]); M_inv (GeV/c^2); Events", 50, 0.0, 1500);
RVec<float> Muon_PT;
RVec<float> Muon_Eta;
RVec<float> Muon_Phi;
RVec<int> Muon_Charge;
// auto idx_cmb = Combinations(Muon_PT, 2);
for (size_t i = 0; i < Muon_Charge.size(); i++) {
if (Muon_Charge[1] != Muon_Charge[2]) {
ROOT::Math::PtEtaPhiMVector m1((Muon_PT)[1], (Muon_Eta)[1], (Muon_Phi)[1],
0.1);
ROOT::Math::PtEtaPhiMVector m2((Muon_PT)[2], (Muon_Eta)[2], (Muon_Phi)[2],
0.1);
auto mass = (m1 + m2).M();
histDiMuonMass->Fill(mass);
auto df_mass = df.Define("Dimuon_mass", InvariantMass<float>,
{"Muon_PT", "Muon_Eta", "Muon_Phi", "m"});
// Make histogram of dimuon mass spectrum
auto h = df_mass.Histo1D({"Dimuon_mass", "Dimuon_mass", 30000, 0.25, 300},
"Dimuon_mass");
}
} // end of event for loop
histDiMuonMass->Draw();
}
Why isn't accessing the Branch Variables Muon_PT, etc. How can I fix this?

Related

Subtensor of a Tensorflow tensor (C++)

I have a tensorflow::Tensor batch in C++ with shape [2, 720, 1280, 3] (#images x height x width x #channels).
I want to get another tensor with only the first image, thus I would have a tensor of shape [1, 720, 1280, 3]. In order words, I want:
tensorflow::Tensor first = batch[0]
What's the most efficient way to achieve it?
I know how to do this in python, but the C++ api and documentation are not as good as python's.
After spending some time trying to implement through copy, I realised that this operation is supported in the API as Slice:
tensorflow::Tensor first = batch.Slice(0, 1);
Note that, as documented, the returned tensor shares the internal buffer with the sliced one, and the alignment of both tensors may be different, if that is relevant to you.
EDIT:
Since I had already done it, here is my attempt at reproducing the same functionality, copy-based. I think it should work (it is pretty similar to what I use in other context).
#include <cstdlib>
#include <cassert>
#include <tensorflow/core/framework/tensor.h>
#include <tensorflow/core/framework/tensor_shape.h>
tensorflow::Tensor get_element(const tensorflow::Tensor data, unsigned int index, bool keepDim)
{
using namespace std;
using namespace tensorflow;
typedef typename tensorflow::DataTypeToEnum<T> DataType;
auto dtype = DataType::v();
assert(dtype == data.dtype());
auto dtype = data.dtype();
auto dataShape = data.shape();
TensorShape elementShape;
if (keepDim)
{
elementShape.addDim(1);
}
for (int iDim = 1; iDim < dataShape.dims(); iDim++) {
elementShape.AddDim(dataShape.dim_size(iDim));
}
Tensor element(dtype, elementShape);
auto elementBytes = elementShape.num_elements() * DataTypeSize(dtype);
memcpy(element.flat<void>().data(),
batch.flat<void>().data() + elementBytes * index,
elementBytes);
return element;
}
int main()
{
Tensor batch = ...;
Tensor first = get_element(batch, 0);
return 0;
}
The code can also be changed if you just want to extract the data to, for example, a vector or something else.
This works fine
#include "tensorflow/core/framework/tensor_slice.h"
Tensor t2 = t1.Slice(0,1);

Trying to make a live data grapher with CImg library (C++)

I'm new to CImg. Not sure if there's already a live data plotter in the library but I thought I'd go ahead and make one myself. If what I'm looking for already exists in the library please point me to the function. otherwise, here is my super inefficient code that I'm hoping you can help me with~
#include <iostream>
#include "CImg.h"
#include <ctime>
#include <cmath>
using namespace cimg_library;
int main()
{
CImg<unsigned char> plot(400, 320, 1, 3, 0);
CImgDisplay graph(plot, "f(x)");
clock();
const unsigned char red[] = {255, 0, 0};
float* G = new float[plot.width()]; //define an array holding the values that are to be displayed on the graph
while (1){
G[0] = ((plot.height()/4) * sin(clock() / 1000.0)) + plot.height()/2; // new f(t) value
for (int i = 1; i <= plot.width() - 1; i++){
G[plot.width() - i] = G[plot.width() - i - 1]; //basically shift all the array values to current address+1
plot.draw_point(plot.width() - 3*i, G[i-1], red, 1).display(graph);
}
plot.fill(0);
}
return 0;
}
problems
the grapher traverses right to left soo slowly.. and I'm not sure how to make a smooth curve hence I went with points.. how do you make a smooth curve?
There is already something for you in the library, method CImg<T>::draw_graph(), as (brielfy) explained here :
http://cimg.eu/reference/structcimg__library_1_1CImg.html#a2e629aadedc4518001f00333f25bfec8
There are few examples provided with the library that use this method, see files examples/tutorial.cpp and examples/plotter1d.cpp.

boost::geometry Most efficient way of measuring max/min distance of a point to a polygon ring

I have been using boost::geometry library in a program, mostly for handling polygon objects.
I am now trying to optimize my code to scale better with larger polygons. One my functions checks for a given polygon and a given point (usually inside the polygon) the minimum and maximum distance between the point and polygon outer ring.
I do it by looping on the polygon edges:
polygon pol;
point myPoint;
double min = 9999999, max = 0;
for(auto it1 = boost::begin(bg::exterior_ring(pol)); it1 != boost::end(bg::exterior_ring(pol)); ++it1){
double distance = bg::distance(*it1, myPoint);
if(max < distance)
max = distance;
if(min > distance)
min = distance;
}
I am hoping that there are algorithms faster than this one, linear in the polygon number of edges. Is there such a thing already inside the boost::geometry library?
I'd suggest you can use the builtin strategies for finding the minimum distance between the polygon and the point:
Live On Coliru
#include <boost/geometry.hpp>
#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/io/io.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/algorithms/distance.hpp>
namespace bg = boost::geometry;
using point = bg::model::d2::point_xy<double>;
using polygon = bg::model::polygon<point>;
int main() {
polygon pol;
boost::geometry::read_wkt(
"POLYGON((2 1.3,2.4 1.7,2.8 1.8,3.4 1.2,3.7 1.6,3.4 2,4.1 3,5.3 2.6,5.4 1.2,4.9 0.8,2.9 0.7,2 1.3)"
"(4.0 2.0, 4.2 1.4, 4.8 1.9, 4.4 2.2, 4.0 2.0))", pol);
point myPoint(7, 7);
double min = 9999999, max = 0;
std::cout << "Minimal distance: " << bg::distance(pol, myPoint);
}
Prints
Minimal distance: 4.71699
Further hints:
You should consider ranking the distances first using comparable_distance. As you can see the sample there suggests looping over all the sampled distances... so I don't think the library has a better offering at this time.
More sophisticated algorithms are planned, of which a number may be related to this problem:
http://boost-geometry.203548.n3.nabble.com/distance-between-geometries-td4025549.html
mailing list thread http://lists.boost.org/geometry/2013/08/2446.php
another here http://lists.boost.org/geometry/2013/09/2494.php
Note also that Boost Geometry Index has a related predicate comparable_distance_far but it's not exposed as of yet.
Summary
You can improve at least a bit by using comparable_distance here for now.
Features have been planned and it looks like there is a good chance that requesting them on the mailing list/Boost Trac will help getting them there.
For best performances you should use an RTree with boost::geometry::index. Creating the RTree has a cost, but then computing the ditance of a point to any of the (multi)polygon ring will be much faster. Example code:
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/index/rtree.hpp>
#include <iostream>
#include <vector>
int main()
{
namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;
typedef bg::model::point<double, 2, bg::cs::cartesian> point;
typedef bg::model::polygon<point> polygon;
point p{ 0, 0 };
// create some polygon and fill it with data
polygon poly;
double a = 0;
double as = bg::math::two_pi<double>() / 100;
for (int i = 0; i < 100; ++i, a += as)
{
double c = cos(a);
double s = sin(a);
poly.outer().push_back(point{10 * c, 10 * s});
poly.inners().resize(1);
poly.inners()[0].push_back(point{5 * c, 5 * s});
}
// make sure it is valid
bg::correct(poly);
// create rtree containing objects of type bg::model::pointing_segment
typedef bg::segment_iterator<polygon const> segment_iterator;
typedef std::iterator_traits<segment_iterator>::value_type segment_type;
bgi::rtree<segment_type, bgi::rstar<4> > rtree(bg::segments_begin(poly),
bg::segments_end(poly));
// get 1 nearest segment
std::vector<segment_type> result;
rtree.query(bgi::nearest(p, 1), std::back_inserter(result));
BOOST_ASSERT(!result.empty());
std::cout << bg::wkt(result[0]) << ", " << bg::distance(p, result[0]) << std::endl;
return 0;
}

How do I change this variable into an array c++

I am writing code in c++ for a game in which a bucket controlled by the user collects raindrops with the same radius. I want to use an array to make each of the 16 raindrops a different size(radius). I have no clue how to change the variable into an array.
I am given a variable:
int radius = randomBetween( MARGIN / 4, MARGIN / 2 );
Here is an example that uses actual C++.
#include <algorithm>
#include <functional>
#include <random>
#include <vector>
std::mt19937 prng(seed);
std::uniform_int_distribution<> dist(MARGIN / 4, MARGIN / 2);
std::vector<int> radii(16);
std::generate(radii.begin(), radii.end(), std::bind(dist, std::ref(prng)));
You're probably going to want to use floats, but basically if I understand you correctly...
int size_in_elements = 16;
float *a= new float[size_in_elements];
float maxvalue = 100.0f; // this will be the maximum value to assign to each element
for(int i = 0; i < size_in_elements; i++)
{
a[i] = fmodf((float)rand(), maxvalue);
}
delete[] a; // Don't forget the brackets here... delete[] is used for deleting arrays.
Hope I helped some

CGAL Precondition_exception with Polygon intersection and inexact constructions kernel

I'm using CGAL and got into some weird bug, which I can't reproduce in a small test program. Here is the test code that works as given, but when I have the exact same code in my larger program (a ROS node) it spits an error:
#include <vector>
#include <boost/shared_ptr.hpp>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polygon_with_holes_2.h>
#include <CGAL/Boolean_set_operations_2.h>
#include "print.h"
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef Kernel::FT Ft;
typedef Kernel::Point_2 Point;
typedef Kernel::Segment_2 Segment;
typedef Kernel::Direction_2 Direction;
typedef Kernel::Line_2 Line;
typedef Kernel::Vector_2 Vector;
typedef CGAL::Polygon_2<Kernel> Polygon;
typedef CGAL::Polygon_with_holes_2<Kernel> PolygonWithHoles;
main() {
Polygon poly;
float scale = 4.0/100;
float max_y = 500*scale;
poly.push_back(Point(76*scale, max_y-496*scale));
poly.push_back(Point(660*scale, max_y-496*scale));
poly.push_back(Point(660*scale, max_y-48*scale));
poly.push_back(Point(71*scale, max_y-54*scale));
// Holes must be clock wise!!
Polygon holes[10];
holes[0].push_back(Point(131*scale, max_y-86*scale));
holes[0].push_back(Point(179*scale, max_y-85*scale));
holes[0].push_back(Point(180*scale, max_y-238*scale));
holes[0].push_back(Point(133*scale, max_y-239*scale));
holes[1].push_back(Point(237*scale, max_y-84*scale));
holes[1].push_back(Point(286*scale, max_y-84*scale));
holes[1].push_back(Point(288*scale, max_y-237*scale));
holes[1].push_back(Point(240*scale, max_y-238*scale));
// Why does this hole make intersection() error?
holes[2].push_back(Point(345*scale, max_y-84*scale));
holes[2].push_back(Point(393*scale, max_y-83*scale));
holes[2].push_back(Point(396*scale, max_y-236*scale));
holes[2].push_back(Point(348*scale, max_y-236*scale));
PolygonWithHoles polyHoles(poly);
polyHoles.outer_boundary() = poly;
for (int i=0; i<3; ++i)
polyHoles.add_hole(holes[i]);
std::cout << "\nPolygon:" << std::endl;
print_polygon_with_holes(polyHoles);
Polygon selection;
float minx = -5.7669;
float miny = -2.13124;
float maxx = 0.396996;
float maxy = 4.88933;
selection.push_back(Point(minx, miny));
selection.push_back(Point(maxx, miny));
selection.push_back(Point(maxx, maxy));
selection.push_back(Point(minx, maxy));
std::cout << "\nSelection:" << std::endl;
print_polygon(selection);
std::vector<PolygonWithHoles> result;
CGAL::intersection(polyHoles, selection, std::back_inserter(result));
std::cout << "Intersection:" << std::endl;
if (!result.empty())
print_polygon_with_holes(result.front());
}
The error:
terminate called after throwing an instance of 'CGAL::Precondition_exception'
what(): CGAL ERROR: precondition violation!
Expr: comp_f(object, parentP->object) != SMALLER
File: /usr/include/CGAL/Multiset.h
Line: 2128
I found 2 ways to fix this:
Shift one point a little bit: replace 83 with 84.
Use Exact_predicates_exact_constructions_kernel
My question is: what could cause the problem to exist only in the larger program?
I'd like to keep using the unexact_constructions, I don't see why I'd have to use the exact_constructions in this case (points aren't close to each other or anything), but since I don't know what the intersection() algorithm does I might be wrong about that.
The intersect function constructs new points - new points of intersections. If you are not using exact constructions, then these new points are not promised to be correct. If you then use these inexact points for further computations you'll run into problems. Unless you have significant constraints on the running time, I believe you're better of with exact constructions.
Example: Consider the unit circle x^2+y^2=1 and the line y=x and let p be a constructed point of intersection. Then circle.has_on_boundary (p) will return TRUE only if you use the exact constructions.