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