npdet_fields.cxx 10.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "Math/Vector3D.h"
#include "Math/Vector4D.h"
#include "Math/VectorUtil.h"
#include "TCanvas.h"
#include "TLegend.h"
#include "TMath.h"
#include "TRandom3.h"
#include "TFile.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TH1D.h"
#include "TH2D.h"
#include "TTree.h"
#include "TF1.h"

#include <algorithm>
#include <iterator>
18
19
#include <tuple>
#include <vector>
20

21
#include "DD4hep/DD4hepUnits.h"
22
23
24
25
#include "DD4hep/Detector.h"
#include "DDG4/Geant4Data.h"
#include "DDRec/CellIDPositionConverter.h"
#include "DDRec/Surface.h"
26
#include "DDRec/SurfaceManager.h"
27
28
#include "TApplication.h"
#include "TGraph.h"
29
#include "TMultiGraph.h"
30
31
32
33
34
35
36
37

#include "Math/DisplacementVector3D.h"

#include <iostream>
#include <string>
#include "clipp.h"

using namespace clipp;
38
39
using namespace ROOT::Math;
using namespace dd4hep;
40
41
42
43
44
45

struct settings {
  bool success = false;
  std::string infile = "";
  ROOT::Math::XYZVector  start_position{0.0,0.0,0.0};
  ROOT::Math::XYZVector  direction{0.0,0.0,1.0};
46
  double step_size   = 0.5*cm;
47
48
49
50
  bool   rec    = false; 
  bool   utf16  = false;
  bool   search = false;
  int    search_level = 0;
51
52
  std::vector<std::string> field_comps = {"Bz"};
  std::string format    = "json";
53
  std::vector<std::string> axes;
54
  int    Nsteps = 200;
55
56
57
  double x0 = 0.0;
  double y0 = 0.0;
  double z0 = 0.0;
58
59
60
61
62
  double x1 = 0.0;
  double y1 = 0.0;
  double z1 = 0.0;
  double x2 = 0.0;
  double y2 = 0.0;
63
64
65
66
  double z2 = 1.0;
  bool   by_step_size = false;
  bool   with_end_point = false;
  bool verbose = false;
67
68
69
70
71
72
73
74
};

settings cmdline_settings(int argc, char* argv[]) {
  settings s;

  auto helpMode = "help mode:" % (
    command("help")
    );
75
76
77
78

  auto drawMode =
      "draw mode:" %
      (command("draw"), // values("component").set(s.field_comps),
79
       option("--Nsteps") & number("Nsteps", s.step_size) % "number of steps to evaluate",
80
       option("--step") & number("step", s.step_size) % "step size",
81
82
83
84
85
       option("--start") & (number("x", s.x0).if_missing([] { std::cout << "x missing!\n"; }),
                            number("y", s.y0).if_missing([] { std::cout << "y missing!\n"; }),
                            number("z", s.z0).if_missing([] { std::cout << "z missing!\n"; })),
       (option("--end").set(s.with_end_point, true) & (number("x1", s.x1).if_missing([] { std::cout << "x1 missing!\n"; }),
                           number("y1", s.y1).if_missing([] { std::cout << "y1 missing!\n"; }),
86
87
                           number("z1", s.z1).if_missing([] { std::cout << "z1 missing!\n"; }))) |
       (option("--direction") &
88
89
            (number("x2", s.x2).if_missing([] { std::cout << "x2 missing!\n"; }),
             number("y2", s.y2).if_missing([] { std::cout << "y2 missing!\n"; }),
90
             number("z2", s.z2).if_missing([] { std::cout << "z2 missing!\n"; })))
91
       // required("--vs","--Vs")    & values("axes",s.axes ), % "axes"
92
93
94
95
96
97
98
99
       //option("-l", "--level") & integers("level", s.search_level) % "search level"
       );

  auto printMode = "integral mode (not implemented):" % (
    command("integrate") 
    //option("--all")         % "copy all"
    //option("--replace")     % "replace existing files",
    //option("-f", "--force") % "don't ask for confirmation"
100
101
102
    );

  auto firstOpt = "user interface options:" % (
103
104
    //joinable(
    option("-v", "--verbose").set(s.verbose)     % "show detailed output",
105
    option("-h", "--help")      % "show help"
106
107
    //option("-i", "--interactive") % "use interactive mode (not implemented)"
     // )
108
    );
109
110
111
112
  auto lastOpt = value("file", s.infile).if_missing([] {
    std::cout << "You need to provide an input xml filename as the last argument!\n";
  }) % "compact description should probly have a \"fields\" sect4ion with more than one magnetic "
       "field defined.";
113
114
115

  auto cli = (
    firstOpt,
116
    drawMode,// (| printMode | command("list")),
117
118
119
120
121
122
    lastOpt
    );
  //auto cli = (
  //  command("help")
  //  command("search")
  //  );
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

  auto result = parse(argc, argv, cli);
  // parse debugging:
  auto doc_label = [](const parameter& p) {
    if (!p.flags().empty())
      return p.flags().front();
    if (!p.label().empty())
      return p.label();
    return doc_string{"<?>"};
  };

  std::cout << "args -> parameter mapping:\n";
  for (const auto& m : result) {
    std::cout << "#" << m.index() << " " << m.arg() << " -> ";
    auto p = m.param();
    if (p) {
      std::cout << doc_label(*p) << " \t";
      if (m.repeat() > 0) {
        std::cout << (m.bad_repeat() ? "[bad repeat " : "[repeat ") << m.repeat() << "]";
      }
      if (m.blocked())
        std::cout << " [blocked]";
      if (m.conflict())
        std::cout << " [conflict]";
      std::cout << '\n';
    } else {
      std::cout << " [unmapped]\n";
    }
  }
  std::cout << "missing parameters:\n";
  for (const auto& m : result.missing()) {
    auto p = m.param();
    if (p) {
      std::cout << doc_label(*p) << " \t";
      std::cout << " [missing after " << m.after_index() << "]\n";
    }
  }
  std::cout << bool(result) << "\n";

  if(!result) {
163
    s.success = false;
164
165
    std::cout << make_man_page(cli, argv[0])
    .prepend_section("DESCRIPTION", " Tool for quickly looking at magnetic fields.")
166
    .append_section("EXAMPLES","    npdet_fields draw --start 0 0 0 detector.xml\n");
167
168
169
    return s;
  }

170
  s.start_position.SetXYZ(s.x0*cm,s.y0*cm,s.z0*cm);
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
  if(s.with_end_point){
    s.direction = ROOT::Math::XYZVector(s.x1 * cm, s.y1 * cm, s.z1 * cm) - s.start_position;
    s.step_size = s.direction.R()/s.Nsteps;
    s.direction = s.direction.Unit();
  } else {
    s.direction.SetXYZ(s.x2 * cm, s.y2 * cm, s.z2 * cm);
    //s.step_size = s.direction.R()/s.Nsteps;
    s.direction = s.direction.Unit();
  }
  s.success   = true;

  std::cout << "start [cm] : " << s.start_position/cm <<"\n";
  std::cout << "dir   [cm] : " << s.direction/cm <<"\n";
  std::cout << "step  [cm] : " << s.step_size/cm <<"\n";
  std::cout << "nstep      : " << s.Nsteps <<"\n";

187
188
  return s;
}
189
//______________________________________________________________________________
190

191
192
193
194
195
196
TGraph* build_1D_field_graph(dd4hep::Detector& detector, const settings& s,
                             std::function<double(ROOT::Math::XYZVector)> B_comp);

/** Cell size example.
 *
 */
197
198
void mag_field(dd4hep::Detector& detector)
{
199
200
  double x_min   = -100.0;
  double x_max   = 100.0;
Wouter Deconinck's avatar
Wouter Deconinck committed
201
202
203
204
205
206
  int    nx_bins = 200;
  double dx      = (x_max - x_min) / nx_bins;
  //double y_min   = -100.0;
  //double y_max   = 100.0;
  //int    ny_bins = 200;
  //double dy      = (y_max - y_min) / ny_bins;
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
  double z_min   = -100.0;
  double z_max   = 100.0;
  int    nz_bins = 200;
  double dz      = (z_max - z_min) / nz_bins;

  double y0 = 20.0 * cm;

  TH2F* hBx = new TH2F("hBx","; z [cm]; x [cm]; B_{x} [T]",nz_bins,z_min,z_max,nx_bins,x_min,x_max);
  TH2F* hBz = new TH2F("hBz","; z [cm]; x [cm]; B_{z} [T]",nz_bins,z_min,z_max,nx_bins,x_min,x_max);
  TH2F* hBr = new TH2F("hBr","; z [cm]; x [cm]; B_{r} [T]",nz_bins,z_min,z_max,nx_bins,x_min,x_max);
  TH2F* hBphi = new TH2F("hBphi","; z [cm]; x [cm]; B_{#phi} [T]",nz_bins,z_min,z_max,nx_bins,x_min,x_max);


  for(int ix = 0; ix< nx_bins; ix++) {
    for(int iz = 0; iz< nz_bins; iz++) {

      double x = (x_min + ix*dx)*cm;
      double z = (z_min + iz*dz)*cm;

      XYZVector pos{ x, y0, z };
      XYZVector field = detector.field().magneticField(pos);

      hBz->Fill(z,x,   field.z()/tesla);
      hBx->Fill(z,x,   field.x()/tesla);
      hBr->Fill(z,x,   field.rho()/tesla);
      hBphi->Fill(z,x, field.phi()/tesla);
    }

  }

  auto c = new TCanvas();
  c->Divide(2,2);

  c->cd(1);
  hBz->Draw("colz");

  c->cd(2);
  hBx->Draw("colz");

  c->cd(3);
  hBr->Draw("colz");

  c->cd(4);
  hBphi->Draw("colz");
}
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272

int main (int argc, char *argv[]) {

  settings s = cmdline_settings(argc,argv);
  if( !s.success ) {
    return 1;
  }

  // ------------------------
  // TODO: CLI Checks 

  using namespace dd4hep;
  
  // -------------------------
  // Get the DD4hep instance
  // Load the compact XML file
  dd4hep::Detector& detector = dd4hep::Detector::getInstance();
  detector.fromCompact(s.infile);

  int root_argc = 0;
  char *root_argv[1];
273
274
  std::string argv0("npdet_fields");
  strncpy(root_argv[0], argv0.c_str(), argv0.size());
275
276
277
278
279
280

  TApplication theApp("tapp", &root_argc, root_argv);

  TMultiGraph* mg = new TMultiGraph();
  for(const auto& comp : s.field_comps){
    std::cout << comp << "\n";
281

282
    auto gr = build_1D_field_graph(detector, s, [](ROOT::Math::XYZVector B) { return B.z(); });
283
284
285
286
287
288
    gr->SetLineColor(2);
    gr->SetLineWidth(2);
    gr->SetFillColor(0);
    gr->SetTitle("B_{z}");
    mg->Add(gr,"l");

289
290
    gr = build_1D_field_graph(detector, s,
                              [&](ROOT::Math::XYZVector B) { return B.Rho(); });
291
292
293
    gr->SetLineColor(1);
    gr->SetLineWidth(2);
    gr->SetFillColor(0);
294
    gr->SetTitle("B_{#perp}");
295
    mg->Add(gr,"l");
296

297
298
299
    gr = build_1D_field_graph(detector, s, [&](ROOT::Math::XYZVector B) {
      return (B - B.Unit() * (B.Dot(s.direction))).r();
    });
300
301
302
303
    gr->SetLineColor(4);
    gr->SetLineWidth(2);
    gr->SetFillColor(0);
    gr->SetTitle("B_{perp}");
Whitney Armstrong's avatar
Whitney Armstrong committed
304
    //mg->Add(gr,"l");
305

306
307
308
309
310
  }

  auto c = new TCanvas();
  mg->Draw("a");
  //mag_field( detector );
311
312
313
314
315
316
  c->BuildLegend();

  std::cout << "input file : " << s.infile << "\n";
  std::cout << "     start : " << s.start_position << "\n";
  std::cout << " direction : " << s.direction << "\n";
  std::cout << "      step : " << s.step_size << "\n";
317
  std::cout << "\n";
318

319
320
321
322
323
324

  theApp.Run();
  return 0;
} 
//______________________________________________________________________________

325
326
TGraph* build_1D_field_graph(dd4hep::Detector& detector, const settings& s,
                             std::function<double(ROOT::Math::XYZVector)> B_comp) {
327
  
328
  int N_steps = s.Nsteps;
329
330
  std::cout << "Steps : " << N_steps << "\n"; 

331
  auto dir = s.direction.Unit();
332
333

  auto gr = new TGraph();
334
335
  for (int i = 0; i < N_steps; i++) {
    ROOT::Math::XYZVector pos   = s.start_position + double(i) * s.step_size * dir;
336
    ROOT::Math::XYZVector field = detector.field().magneticField(pos);
337
338
339
340
341
342

    if (s.verbose) {
      std::cout << "x  : " << pos / mm << "\n";
      std::cout << "B  : " << field / tesla << "\n";
    }
    gr->SetPoint(i, pos.z(), B_comp(field) / tesla);
343
344
345
346
347
  }

  return gr;
}