ROOT  6.06/09
Reference Guide
TRInterface.h
Go to the documentation of this file.
1 // @(#)root/r:$Id$
2 // Author: Omar Zapata 29/05/2013
3 
4 
5 /*************************************************************************
6  * Copyright (C) 2013-2014, Omar Andres Zapata Mesa *
7  * All rights reserved. *
8  * *
9  * For the licensing terms see $ROOTSYS/LICENSE. *
10  * For the list of contributors see $ROOTSYS/README/CREDITS. *
11  *************************************************************************/
12 #ifndef ROOT_R_TRInterface
13 #define ROOT_R_TRInterface
14 
15 #ifndef ROOT_R_TRObject
16 #include<TRObject.h>
17 #endif
18 
19 #ifndef ROOT_R_TRDataFrame
20 #include<TRDataFrame.h>
21 #endif
22 
23 #ifndef ROOT_R_TFunctionExport
24 #include<TRFunctionExport.h>
25 #endif
26 
27 #ifndef ROOT_R_TFunctionImport
28 #include<TRFunctionImport.h>
29 #endif
30 
31 #ifndef ROOT_TThread
32 #include<TThread.h>
33 #endif
34 
35 /**
36  @namespace ROOT::R
37  namespace associated R package for ROOT.
38  @defgroup R R Interface for Statistical Computing
39  */
40 namespace ROOT {
41  namespace R {
42  /**
43  \class TRInterface
44  ROOT R was implemented using the
45  <A HREF="http://www.r-project.org/">R Project</A> library and the modules
46  <A HREF="http://cran.r-project.org/web/packages/Rcpp/index.html">Rcpp</A> and
47  <A HREF="http://cran.r-project.org/web/packages/RInside/index.html">RInside</A>
48  <h2>Users Guide </h2>
49  <a href="http://oproject.org/tiki-index.php?page=ROOT+R+Users+Guide"> http://oproject.org/tiki-index.php?page=ROOT+R+Users+Guide</a><br>
50  <a href="https://root.cern.ch/drupal/content/how-use-r-root-root-r-interface"> https://root.cern.ch/drupal/content/how-use-r-root-root-r-interface</a>
51 
52  \ingroup R
53  */
54 
55 
56  /**
57  <center><h2>TRInterface class</h2></center>
58 
59  </p>
60  The TRInterface class lets you procces R code from ROOT.<br>
61  You can call R libraries and their functions, plot results in R or ROOT,<br>
62  and use the power of ROOT and R at the same time.<br>
63  It also lets you pass scalars, vectors and matrices from ROOT to R<br>
64  and from R to ROOT using TRObject; but you can to use overloaded opetarors [],<< and >> <br>
65  to work with ROOTR like work with streams of data.<br>
66 
67  TRInterface class can not be instantiated directly, but you can create objects using the static methods
68  TRInterface& Instance() and TRInterface* InstancePtr() to create your own objects.<br>
69  <br>
70  </p>
71  Show an example below:
72  Create an exponential fit, the idea is to create a set of numbers x,y with noise from ROOT,
73  pass them to R and fit the data to \f$ x^3 \f$, get the fitted coefficient(power) and plot the data,
74  the known function and the fitted function.
75  \code{.cpp}
76 
77  TCanvas *c1 = new TCanvas("c1","Curve Fit",700,500);
78  c1->SetGrid();
79 
80  // draw a frame for multiples graphs
81  TMultiGraph *mg = new TMultiGraph();
82 
83  // create the first graph (points with gaussian noise)
84  const Int_t n = 24;
85  Double_t x[n] ;
86  Double_t y[n] ;
87  //Generate points along a X^3 with noise
88  TRandom rg;
89  rg.SetSeed(520);
90  for (Int_t i = 0; i < n; i++) {
91  x[i] = rg.Uniform(0, 1);
92  y[i] = TMath::Power(x[i], 3) + rg.Gaus() * 0.06;
93  }
94 
95  TGraph *gr1 = new TGraph(n,x,y);
96  gr1->SetMarkerColor(kBlue);
97  gr1->SetMarkerStyle(8);
98  gr1->SetMarkerSize(1);
99  mg->Add(gr1);
100 
101  // create second graph
102  TF1 *f_known=new TF1("f_known","pow(x,3)",0,1);
103  TGraph *gr2 = new TGraph(f_known);
104  gr2->SetMarkerColor(kRed);
105  gr2->SetMarkerStyle(8);
106  gr2->SetMarkerSize(1);
107  mg->Add(gr2);
108 
109  //passing x and y values to R for fitting
110  ROOT::R::TRInterface &r=ROOT::R::TRInterface::Instance();
111  r["x"]<<TVectorD(n, x);
112  r["y"]<<TVectorD(n, y);
113  //creating a R data frame
114  r<<"ds<-data.frame(x=x,y=y)";
115  //fitting x and y to X^power using Nonlinear Least Squares
116  r<<"m <- nls(y ~ I(x^power),data = ds, start = list(power = 1),trace = T)";
117  //getting the fitted value (power)
118  Double_t power;
119  r["summary(m)$coefficients[1]"]>>power;
120 
121  TF1 *f_fitted=new TF1("f_fitted","pow(x,[0])",0,1);
122  f_fitted->SetParameter(0,power);
123  //plotting the fitted function
124  TGraph *gr3 = new TGraph(f_fitted);
125  gr3->SetMarkerColor(kGreen);
126  gr3->SetMarkerStyle(8);
127  gr3->SetMarkerSize(1);
128 
129  mg->Add(gr3);
130  mg->Draw("ap");
131 
132  //displaying basic results
133  TPaveText *pt = new TPaveText(0.1,0.6,0.5,0.9,"brNDC");
134  pt->SetFillColor(18);
135  pt->SetTextAlign(12);
136  pt->AddText("Fitting x^power ");
137  pt->AddText(" \"Blue\" Points with gaussian noise to be fitted");
138  pt->AddText(" \"Red\" Known function x^3");
139  TString fmsg;
140  fmsg.Form(" \"Green\" Fitted function with power=%.4lf",power);
141  pt->AddText(fmsg);
142  pt->Draw();
143  c1->Update();
144  \endcode
145  @ingroup R
146  */
147  class TRInterface: public TObject {
148  protected:
149  RInside *fR;
151  public:
152  //Proxy class to use operators for assignation Ex: r["name"]=object
153  class Binding {
154  public:
157  {
158  fInterface = obj.fInterface;
159  fName = obj.fName;
160  return *this;
161  }
162  template <class T> Binding &operator=(const T &data)
163  {
164  fInterface->Assign<T>(data, fName);
165  return *this;
166  }
168  {
169  //The method assign is not a template for a function
170  fInterface->Assign(fun, fName);
171  return *this;
172  }
173 
175  {
176  //The method assign is not a template for a function
177  fInterface->Assign(fun, fName);
178  return *this;
179  }
180 
182  {
183  fInterface->Assign(df, fName);
184  return *this;
185  }
186 
188  {
189  fInterface->Assign(df, fName);
190  return *this;
191  }
192 
193  template <class T> Binding &operator >>(T &var)
194  {
195  var = fInterface->Eval(fName).As<T>();
196  return *this;
197  }
198 
199  template <class T> Binding &operator <<(T var)
200  {
201  fInterface->Assign<T>(var, fName);
202  return *this;
203  }
204 #include<TRInterface_Binding.h>
205  template <class T> operator T()
206  {
207  return fInterface->Eval(fName);
208  }
209 
210  private:
213  };
214  private:
215  /**
216  The command line arguments are by deafult argc=0 and argv=NULL,
217  The verbose mode is by default disabled but you can enable it to show procedures information in stdout/stderr \note some time can produce so much noise in the output
218  \param argc default 0
219  \param args default null
220  \param loadRcpp default true
221  \param verbose default false
222  \param interactive default true
223  */
224  TRInterface(const int argc = 0, const char *argv[] = NULL, const bool loadRcpp = true, const bool verbose = false, const bool interactive = true);
225  public:
226  ~TRInterface();
227 
228  /**
229  Method to set verbose mode, that produce extra output
230  \note some time can produce so much noise in the output
231  \param status boolean to enable of disable
232  */
233  void SetVerbose(Bool_t status);
234  /**
235  Method to eval R code and you get the result in a reference to TRObject
236  \param code R code
237  \param ands reference to TRObject
238  \return an true or false if the execution was sucessful or not.
239  */
240  Int_t Eval(const TString &code, TRObject &ans); // parse line, returns in ans; error code rc
241  /**
242  Method to eval R code
243  \param code R code
244  */
245  void Execute(const TString &code);
246 
247  /**
248  Method to eval R code and you get the result in a TRObject
249  \param code R code
250  \return a TRObject with result
251  */
252  TRObject Eval(const TString &code);
253 
254 
255  /**
256  Template method to assign C++ variables into R enviroment
257  \param var any R wrappable datatype
258  \param name name of the variable in R's enviroment
259  */
260  template<typename T >void Assign(const T &var, const TString &name)
261  {
262  // This method lets you pass variables from ROOT to R.
263  // The template T should be a supported ROOT datatype and
264  // the TString's name is the name of the variable in the R enviroment.
265  fR->assign<T>(var, name.Data());
266  }
267  /**
268  Method to assign TRFunctionExport in R's enviroment
269  \param fun TRFunctionExport
270  \param name name of the variable in R's enviroment
271  */
272  void Assign(const TRFunctionExport &fun, const TString &name);
273  /**
274  Method to assign TRDataFrame in R's enviroment
275  \param df TRDataFrame
276  \param name name of the variable in R's enviroment
277  */
278  void Assign(const TRDataFrame &df, const TString &name);
279 
280  /**
281  Method to get a R prompt to work interactively with tab completation support
282  */
283  void Interactive();
284 
285  /**
286  Init event loop in a thread to support actions in windows from R graphics system
287  */
288  void ProcessEventsLoop();
289 
290  /**
291  Method to verify if a package is installed
292  \param pkg R's pkg name
293  \return true or false if the package is installed or not
294  */
296  /**
297  Method to load an R's package
298  \param pkg R's pkg name
299  \return true or false if the package was loaded or not
300  */
301  Bool_t Require(TString pkg);
302  /**
303  Method to install an R's package
304  \param pkg R's pkg name
305  \param repos url for R's package repository
306  \return true or false if the package was installed or not
307  */
308  Bool_t Install(TString pkg, TString repos = "http://cran.r-project.org");
309  Binding operator[](const TString &name);
310 
311  /**
312  static method to get an TRInterface instance reference
313  \return TRInterface instance reference
314  */
315  static TRInterface &Instance();
316  /**
317  static method to get an TRInterface instance pointer
318  \return TRInterface instance pointer
319  */
320  static TRInterface *InstancePtr();
321 
323  };
324  }
325 }
326 
328 {
329  r.Execute(code);
330  return r;
331 }
332 
333 #endif
XYZVector ans(TestRotation const &t, XYZVector const &v_in)
void Execute(const TString &code)
Method to eval R code.
Definition: TRInterface.cxx:77
Bool_t IsInstalled(TString pkg)
Method to verify if a package is installed.
Namespace for new ROOT classes and functions.
Definition: ROOT.py:1
static TRInterface * InstancePtr()
static method to get an TRInterface instance pointer
double T(double x)
Definition: ChebyshevPol.h:34
Basic string class.
Definition: TString.h:137
int Int_t
Definition: RtypesCore.h:41
TAlienJobStatus * status
Definition: TAlienJob.cxx:51
bool Bool_t
Definition: RtypesCore.h:59
TRInterface(const int argc=0, const char *argv[]=NULL, const bool loadRcpp=true, const bool verbose=false, const bool interactive=true)
The command line arguments are by deafult argc=0 and argv=NULL, The verbose mode is by default disabl...
Definition: TRInterface.cxx:25
void Binding()
Definition: Binding.C:21
const char * Data() const
Definition: TString.h:349
#define ClassDef(name, id)
Definition: Rtypes.h:254
void Assign(const T &var, const TString &name)
Template method to assign C++ variables into R enviroment.
Definition: TRInterface.h:260
Binding & operator<<(const TRFunctionExport &fun)
Definition: TRInterface.h:174
Bool_t Install(TString pkg, TString repos="http://cran.r-project.org")
Method to install an R's package.
Binding & operator>>(T &var)
Definition: TRInterface.h:193
Bool_t Require(TString pkg)
Method to load an R's package.
This is a class to get ROOT's objects from R's objects
Definition: TRObject.h:73
ROOT::R::TRInterface & r
Definition: Object.C:4
bool verbose
void ProcessEventsLoop()
Init event loop in a thread to support actions in windows from R graphics system. ...
Binding & operator=(const Binding &obj)
Definition: TRInterface.h:156
void Interactive()
Method to get a R prompt to work interactively with tab completation support.
void SetVerbose(Bool_t status)
Method to set verbose mode, that produce extra output.
static TRInterface & Instance()
static method to get an TRInterface instance reference
Binding operator[](const TString &name)
#define name(a, b)
Definition: linkTestLib0.cpp:5
Mother of all ROOT objects.
Definition: TObject.h:58
Binding(TRInterface *rnt, TString name)
Definition: TRInterface.h:155
Binding & operator<<(const TRDataFrame &df)
Definition: TRInterface.h:187
#define NULL
Definition: Rtypes.h:82
ROOT::R::TRInterface & operator<<(ROOT::R::TRInterface &r, TString code)
Definition: TRInterface.h:327
TObject * obj
Int_t Eval(const TString &code, TRObject &ans)
Method to eval R code and you get the result in a reference to TRObject.
Definition: TRInterface.cxx:58
Binding & operator=(const TRFunctionExport &fun)
Definition: TRInterface.h:167
This is a class to pass functions from ROOT to R
TRandom3 R
a TMatrixD.
Definition: testIO.cxx:28
Binding & operator=(const TRDataFrame &df)
Definition: TRInterface.h:181
This is a class to create DataFrames from ROOT to R
Definition: TRDataFrame.h:183
Binding & operator=(const T &data)
Definition: TRInterface.h:162