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