9 from hashlib
import sha1
10 from contextlib
import contextmanager
11 from subprocess
import check_output
12 from IPython
import get_ipython
13 from IPython.display
import HTML
14 from IPython.core.extensions
import ExtensionManager
15 import IPython.display
25 cppMIME =
'text/x-c++src' 26 ipyMIME =
'text/x-ipython' 28 _jsDefaultHighlight =
""" 29 // Set default mode for code cells 30 IPython.CodeCell.options_default.cm_config.mode = '{mimeType}'; 31 // Set CodeMirror's current mode 32 var cells = IPython.notebook.get_cells(); 33 cells[cells.length-1].code_mirror.setOption('mode', '{mimeType}'); 34 // Set current mode for newly created cell 35 cells[cells.length-1].cm_config.mode = '{mimeType}'; 38 _jsMagicHighlight =
"IPython.CodeCell.config_defaults.highlight_modes['magic_{cppMIME}'] = {{'reg':[/^%%cpp/]}};" 41 _jsNotDrawableClassesPatterns = [
"TGraph[23]D",
"TH3*",
"TGraphPolar",
"TProf*",
"TEve*",
"TF[23]",
"TGeo*",
"TPolyLine3D"]
44 _jsROOTSourceDir =
"https://root.cern.ch/js/dev/" 50 style="width: {jsCanvasWidth}px; height: {jsCanvasHeight}px"> 57 'JSRootCore' : '{jsROOTSourceDir}/scripts/JSRootCore', 58 'JSRootPainter' : '{jsROOTSourceDir}/scripts/JSRootPainter', 62 require(['JSRootCore', 'JSRootPainter'], 63 function(Core, Painter) {{ 64 var obj = Core.parse('{jsonContent}'); 65 Painter.draw("{jsDivId}", obj, "{jsDrawOptions}"); 72 _enableJSVisDebug =
False 83 global _enableJSVisDebug
85 _enableJSVisDebug =
True 89 global _enableJSVisDebug
91 _enableJSVisDebug =
False 97 '''Return appropriate file extension for a shared library 98 >>> _getLibExtension('darwin') 100 >>> _getLibExtension('win32') 102 >>> _getLibExtension('OddPlatform') 109 return pExtMap.get(thePlatform,
'.so')
112 print "Welcome to ROOTaaS %s" %ROOT.gROOT.GetVersion()
116 originalLevel = ROOT.gErrorIgnoreLevel
117 ROOT.gErrorIgnoreLevel = level
119 ROOT.gErrorIgnoreLevel = originalLevel
124 >>> commentRemover(s) 126 >>> s="int /** Test **/ main() {return 0;}" 127 >>> commentRemover(s) 128 'int main() {return 0;}' 130 def blotOutNonNewlines( strIn ) :
131 return "" + (
"\n" * strIn.count(
'\n'))
133 def replacer( match ) :
135 if s.startswith(
'/'):
136 return blotOutNonNewlines(s)
140 pattern = re.compile(\
141 r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
142 re.DOTALL | re.MULTILINE)
144 return re.sub(pattern, replacer, text)
150 ROOT.gInterpreter.ProcessLine(code)
154 ROOT.gInterpreter.Declare(code)
165 out = check_output(command.split())
168 sys.stderr.write(
"%s (command was %s)\n" %(errMsg,command))
173 This function is a workaround. On osx, it is impossible to link against 174 libzmq.so, among the others. The error is known and is 175 "ld: can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)" 176 We cannot at the moment force Aclic to change the linker command in order 177 to exclude these libraries, so we launch a second root session to compile 178 the library, which we then load. 180 command =
'root -l -q -b -e gSystem->CompileMacro(\"%s\",\"k\")*0'%fileName
182 libNameBase = fileName.replace(
".C",
"_C")
183 ROOT.gSystem.Load(libNameBase)
186 '''Convert code to a unique file name 188 >>> _codeToFilename("int f(i){return i*i;}") 191 fileNameBase = sha1(code).hexdigest()[0:8]
192 return fileNameBase +
".C" 195 '''Dump code to file whose name is unique 197 >>> _codeToFilename("int f(i){return i*i;}") 201 with open (fileName,
'w')
as ofile:
214 nbStreamsPyStreamsMap={sys.stderr:sys.__stderr__,sys.stdout:sys.__stdout__}
223 flushFunctionName=
'_ROOTaaS_Flush' 224 if (
not hasattr(ROOT,flushFunctionName)):
226 self.
flush = getattr(ROOT,flushFunctionName)
229 r, _, _ = select.select([self.pipe_out], [], [], 0)
236 out += os.read(self.pipe_out, 8192)
247 Capture the canvas which is drawn to display it. 256 for can
in ROOT.gROOT.GetListOfCanvases():
272 Change the mode of the notebook to CPP. It is preferred to use cell magic, 273 but this option is handy to set up servers and for debugging purposes. 276 cpptransformer.load_ipython_extension(ip)
278 IPython.display.display_javascript(_jsDefaultHighlight.format(mimeType = cppMIME), raw=
True)
279 print "Notebook is in Cpp mode" 283 Capture the canvas which is drawn and decide if it should be displayed using 293 Get the list of primitives in the pad, recursively descending into 294 histograms and graphs looking for fitted functions. 296 primitives = self.
thePad.GetListOfPrimitives()
297 primitivesNames = map(
lambda p: p.ClassName(), primitives)
302 return sorted(primitivesNames)
306 Every DIV containing a JavaScript snippet must be unique in the 307 notebook. This methods provides a unique identifier. 309 CanvasDrawer.jsUID += 1
310 return CanvasDrawer.jsUID
314 if not _enableJSVis:
return False 316 for unsupportedPattern
in _jsNotDrawableClassesPatterns:
317 for primitiveTypeName
in primitivesTypesNames:
318 if fnmatch.fnmatch(primitiveTypeName,unsupportedPattern):
319 print >> sys.stderr,
"The canvas contains an object of a type jsROOT cannot currently handle (%s). Falling back to a static png." %primitiveTypeName
325 pad = ROOT.gROOT.GetListOfCanvases().FindObject(ROOT.gPad.GetName())
326 json = ROOT.TBufferJSON.ConvertToJSON(pad, 3)
330 divId =
'root_plot_' + str(self.
_getUID())
331 thisJsCode = _jsCode.format(jsCanvasWidth = _jsCanvasWidth,
332 jsCanvasHeight = _jsCanvasHeight,
333 jsROOTSourceDir = _jsROOTSourceDir,
334 jsonContent=json.Data(),
339 IPython.display.display(HTML(thisJsCode))
343 ofile = tempfile.NamedTemporaryFile(suffix=
".png")
345 self.
thePad.SaveAs(ofile.name)
346 img = IPython.display.Image(filename=ofile.name, format=
'png', embed=
True)
347 IPython.display.display(img)
351 if _enableJSVisDebug:
367 Invoke the draw function and intercept the graphics 375 style.SetFuncWidth(3)
376 style.SetHistLineWidth(3)
377 style.SetMarkerStyle(8)
378 style.SetMarkerSize(.5)
379 style.SetMarkerColor(ROOT.kBlue)
383 extNames = [
"ROOTaaS.iPyROOT." + name
for name
in [
"cppmagic"]]
385 extMgr = ExtensionManager(ip)
386 for extName
in extNames:
387 extMgr.load_extension(extName)
388 cppcompleter.load_ipython_extension(ip)
390 for capture
in captures: capture.register()
394 ROOT.enableJSVis = enableJSVis
395 ROOT.disableJSVis = disableJSVis
396 ROOT.enableJSVisDebug = enableJSVisDebug
397 ROOT.disableJSVisDebug = disableJSVisDebug
398 ROOT.TCanvas.DrawCpp = ROOT.TCanvas.Draw
399 ROOT.TCanvas.Draw = _PyDraw
402 ipDispJs = IPython.display.display_javascript
404 ipDispJs(
"require(['codemirror/mode/clike/clike'], function(Clike) { console.log('ROOTaaS - C++ CodeMirror module loaded'); });", raw=
True)
406 ipDispJs(_jsMagicHighlight.format(cppMIME = cppMIME), raw=
True)
def _getLibExtension(thePlatform)
double write(int n, const std::string &file_name, const std::string &vector_type, int compress=0)
writing
def __init__(self, thePad)
def declareCppCodeImpl(code)
def loadExtensionsAndCapturers()
def __init__(self, ip=get_ipython())
def _getListOfPrimitivesNamesAndTypes(self)
def _dumpToUniqueFile(code)
def _invokeAclicMac(fileName)
def processCppCodeImpl(code)
def enableCppHighlighting()
def _setIgnoreLevel(level)
def _codeToFilename(code)
def _checkOutput(command, errMsg=None)
def __init__(self, stream, ip=get_ipython())