forked from root-project/root
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
507 lines (414 loc) · 14.2 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
# -*- coding:utf-8 -*-
#-----------------------------------------------------------------------------
# Author: Danilo Piparo <Danilo.Piparo@cern.ch> CERN
#-----------------------------------------------------------------------------
from __future__ import print_function
import os
import sys
import select
import tempfile
import pty
import itertools
import re
import fnmatch
import time
from hashlib import sha1
from contextlib import contextmanager
from subprocess import check_output
from IPython import get_ipython
from IPython.display import HTML
from IPython.core.extensions import ExtensionManager
import IPython.display
import ROOT
from JupyROOT import handlers
# We want iPython to take over the graphics
ROOT.gROOT.SetBatch()
cppMIME = 'text/x-c++src'
_jsMagicHighlight = """
Jupyter.CodeCell.options_default.highlight_modes['magic_{cppMIME}'] = {{'reg':[/^%%cpp/]}};
console.log("JupyROOT - %%cpp magic configured");
"""
_jsNotDrawableClassesPatterns = ["TGraph[23]D","TH3*","TGraphPolar","TProf*","TEve*","TF[23]","TGeo*","TPolyLine3D", "TH2Poly"]
_jsROOTSourceDir = "https://root.cern.ch/js/notebook/"
_jsCanvasWidth = 800
_jsCanvasHeight = 600
_jsCode = """
<div id="{jsDivId}"
style="width: {jsCanvasWidth}px; height: {jsCanvasHeight}px">
</div>
<script>
requirejs.config({{
paths: {{
'JSRootCore' : '{jsROOTSourceDir}/scripts/JSRootCore',
}}
}});
require(['JSRootCore'],
function(Core) {{
var obj = Core.JSONR_unref({jsonContent});
Core.draw("{jsDivId}", obj, "{jsDrawOptions}");
}}
);
</script>
"""
TBufferJSONErrorMessage="The TBufferJSON class is necessary for JS visualisation to work and cannot be found. Did you enable the http module (-D http=ON for CMake)?"
def TBufferJSONAvailable():
if hasattr(ROOT,"TBufferJSON"):
return True
print(TBufferJSONErrorMessage, file=sys.stderr)
return False
_enableJSVis = False
_enableJSVisDebug = False
def enableJSVis():
if not TBufferJSONAvailable():
return
global _enableJSVis
_enableJSVis = True
def disableJSVis():
global _enableJSVis
_enableJSVis = False
def enableJSVisDebug():
if not TBufferJSONAvailable():
return
global _enableJSVis
global _enableJSVisDebug
_enableJSVis = True
_enableJSVisDebug = True
def disableJSVisDebug():
global _enableJSVis
global _enableJSVisDebug
_enableJSVis = False
_enableJSVisDebug = False
def _getPlatform():
return sys.platform
def _getLibExtension(thePlatform):
'''Return appropriate file extension for a shared library
>>> _getLibExtension('darwin')
'.dylib'
>>> _getLibExtension('win32')
'.dll'
>>> _getLibExtension('OddPlatform')
'.so'
'''
pExtMap = {
'darwin' : '.dylib',
'win32' : '.dll'
}
return pExtMap.get(thePlatform, '.so')
def welcomeMsg():
print("Welcome to JupyROOT %s" %ROOT.gROOT.GetVersion())
@contextmanager
def _setIgnoreLevel(level):
originalLevel = ROOT.gErrorIgnoreLevel
ROOT.gErrorIgnoreLevel = level
yield
ROOT.gErrorIgnoreLevel = originalLevel
def commentRemover( text ):
'''
>>> s="// hello"
>>> commentRemover(s)
''
>>> s="int /** Test **/ main() {return 0;}"
>>> commentRemover(s)
'int main() {return 0;}'
'''
def blotOutNonNewlines( strIn ) : # Return a string containing only the newline chars contained in strIn
return "" + ("\n" * strIn.count('\n'))
def replacer( match ) :
s = match.group(0)
if s.startswith('/'): # Matched string is //...EOL or /*...*/ ==> Blot out all non-newline chars
return blotOutNonNewlines(s)
else: # Matched string is '...' or "..." ==> Keep unchanged
return s
pattern = re.compile(\
r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
re.DOTALL | re.MULTILINE)
return re.sub(pattern, replacer, text)
# Here functions are defined to process C++ code
def processCppCodeImpl(code):
#code = commentRemover(code)
ROOT.gInterpreter.ProcessLine(code)
def processMagicCppCodeImpl(code):
err = ROOT.ProcessLineWrapper(code)
if err == ROOT.TInterpreter.kProcessing:
ROOT.gInterpreter.ProcessLine('.@')
ROOT.gInterpreter.ProcessLine('cerr << "Unbalanced braces. This cell was not processed." << endl;')
def declareCppCodeImpl(code):
#code = commentRemover(code)
ROOT.gInterpreter.Declare(code)
def processCppCode(code):
processCppCodeImpl(code)
def processMagicCppCode(code):
processMagicCppCodeImpl(code)
def declareCppCode(code):
declareCppCodeImpl(code)
def _checkOutput(command,errMsg=None):
out = ""
try:
out = check_output(command.split())
except:
if errMsg:
sys.stderr.write("%s (command was %s)\n" %(errMsg,command))
return out
def _invokeAclicMac(fileName):
'''FIXME!
This function is a workaround. On osx, it is impossible to link against
libzmq.so, among the others. The error is known and is
"ld: can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB)"
We cannot at the moment force Aclic to change the linker command in order
to exclude these libraries, so we launch a second root session to compile
the library, which we then load.
'''
command = 'root -l -q -b -e gSystem->CompileMacro(\"%s\",\"k\")*0'%fileName
out = _checkOutput(command, "Error ivoking ACLiC")
libNameBase = fileName.replace(".C","_C")
ROOT.gSystem.Load(libNameBase)
def _codeToFilename(code):
'''Convert code to a unique file name
>>> _codeToFilename("int f(i){return i*i;}")
'dbf7e731.C'
'''
fileNameBase = sha1(code.encode('utf-8')).hexdigest()[0:8]
return fileNameBase + ".C"
def _dumpToUniqueFile(code):
'''Dump code to file whose name is unique
>>> _codeToFilename("int f(i){return i*i;}")
'dbf7e731.C'
'''
fileName = _codeToFilename(code)
with open (fileName,'w') as ofile:
ofile.write(code)
return fileName
def isPlatformApple():
return _getPlatform() == 'darwin';
def invokeAclic(cell):
fileName = _dumpToUniqueFile(cell)
if isPlatformApple():
_invokeAclicMac(fileName)
else:
processCppCode(".L %s+" %fileName)
transformers = []
class StreamCapture(object):
def __init__(self, ip=get_ipython()):
# For the registration
self.shell = ip
self.ioHandler = handlers.IOHandler()
self.flag = True
self.outString = ""
self.errString = ""
self.asyncCapturer = handlers.Runner(self.syncCapture)
self.isFirstPreExecute = True
self.isFirstPostExecute = True
def syncCapture(self, defout = ''):
self.outString = defout
self.errString = defout
waitTimes = [.01, .01, .02, .04, .06, .08, .1]
lenWaitTimes = 7
iterIndex = 0
while self.flag:
self.ioHandler.Poll()
if not self.flag: return
waitTime = .1 if iterIndex >= lenWaitTimes else waitTimes[iterIndex]
time.sleep(waitTime)
def pre_execute(self):
if self.isFirstPreExecute:
self.isFirstPreExecute = False
return 0
self.flag = True
self.ioHandler.Clear()
self.ioHandler.InitCapture()
self.asyncCapturer.AsyncRun('')
def post_execute(self):
if self.isFirstPostExecute:
self.isFirstPostExecute = False
self.isFirstPreExecute = False
return 0
self.flag = False
self.asyncCapturer.Wait()
self.ioHandler.Poll()
self.ioHandler.EndCapture()
# Print for the notebook
out = self.ioHandler.GetStdout()
err = self.ioHandler.GetStderr()
if not transformers:
sys.stdout.write(out)
sys.stderr.write(err)
else:
for t in transformers:
(out, err, otype) = t(out, err)
if otype == 'html':
IPython.display.display(HTML(out))
IPython.display.display(HTML(err))
return 0
def register(self):
self.shell.events.register('pre_execute', self.pre_execute)
self.shell.events.register('post_execute', self.post_execute)
def GetCanvasDrawers():
lOfC = ROOT.gROOT.GetListOfCanvases()
return [NotebookDrawer(can) for can in lOfC if can.IsDrawn()]
def GetGeometryDrawer():
if not hasattr(ROOT,'gGeoManager'): return
if not ROOT.gGeoManager: return
if not ROOT.gGeoManager.GetUserPaintVolume(): return
vol = ROOT.gGeoManager.GetTopVolume()
if vol:
return NotebookDrawer(vol)
def GetDrawers():
drawers = GetCanvasDrawers()
geometryDrawer = GetGeometryDrawer()
if geometryDrawer: drawers.append(geometryDrawer)
return drawers
def DrawGeometry():
drawer = GetGeometryDrawer()
if drawer:
drawer.Draw()
def DrawCanvases():
drawers = GetCanvasDrawers()
for drawer in drawers:
drawer.Draw()
def NotebookDraw():
DrawGeometry()
DrawCanvases()
class CaptureDrawnPrimitives(object):
'''
Capture the canvas which is drawn to display it.
'''
def __init__(self, ip=get_ipython()):
self.shell = ip
def _post_execute(self):
NotebookDraw()
def register(self):
self.shell.events.register('post_execute', self._post_execute)
class NotebookDrawer(object):
'''
Capture the canvas which is drawn and decide if it should be displayed using
jsROOT.
'''
jsUID = 0
def __init__(self, theObject):
self.drawableObject = theObject
self.isCanvas = self.drawableObject.ClassName() == "TCanvas"
def __del__(self):
if self.isCanvas:
self.drawableObject.ResetDrawn()
else:
ROOT.gGeoManager.SetUserPaintVolume(None)
def _getListOfPrimitivesNamesAndTypes(self):
"""
Get the list of primitives in the pad, recursively descending into
histograms and graphs looking for fitted functions.
"""
primitives = self.drawableObject.GetListOfPrimitives()
primitivesNames = map(lambda p: p.ClassName(), primitives)
return sorted(primitivesNames)
def _getUID(self):
'''
Every DIV containing a JavaScript snippet must be unique in the
notebook. This methods provides a unique identifier.
'''
NotebookDrawer.jsUID += 1
return NotebookDrawer.jsUID
def _canJsDisplay(self):
if not TBufferJSONAvailable():
return False
if not self.isCanvas: return True
# to be optimised
if not _enableJSVis: return False
primitivesTypesNames = self._getListOfPrimitivesNamesAndTypes()
for unsupportedPattern in _jsNotDrawableClassesPatterns:
for primitiveTypeName in primitivesTypesNames:
if fnmatch.fnmatch(primitiveTypeName,unsupportedPattern):
print("The canvas contains an object of a type jsROOT cannot currently handle (%s). Falling back to a static png." %primitiveTypeName, file=sys.stderr)
return False
return True
def _getJsCode(self):
# Workaround to have ConvertToJSON work
json = ROOT.TBufferJSON.ConvertToJSON(self.drawableObject, 3)
# Here we could optimise the string manipulation
divId = 'root_plot_' + str(self._getUID())
height = _jsCanvasHeight
width = _jsCanvasHeight
options = "all"
if self.isCanvas:
height = self.drawableObject.GetWw()
width = self.drawableObject.GetWh()
options = ""
thisJsCode = _jsCode.format(jsCanvasWidth = height,
jsCanvasHeight = width,
jsROOTSourceDir = _jsROOTSourceDir,
jsonContent = json.Data(),
jsDrawOptions = options,
jsDivId = divId)
return thisJsCode
def _getJsDiv(self):
return HTML(self._getJsCode())
def _jsDisplay(self):
IPython.display.display(self._getJsDiv())
return 0
def _getPngImage(self):
ofile = tempfile.NamedTemporaryFile(suffix=".png")
with _setIgnoreLevel(ROOT.kError):
self.drawableObject.SaveAs(ofile.name)
img = IPython.display.Image(filename=ofile.name, format='png', embed=True)
return img
def _pngDisplay(self):
img = self._getPngImage()
IPython.display.display(img)
def _display(self):
if _enableJSVisDebug:
self._pngDisplay()
self._jsDisplay()
else:
if self._canJsDisplay():
self._jsDisplay()
else:
self._pngDisplay()
def GetDrawableObjects(self):
if not self.isCanvas:
return [self._getJsDiv()]
if _enableJSVisDebug:
return [self._getJsDiv(),self._getPngImage()]
if self._canJsDisplay():
return [self._getJsDiv()]
else:
return [self._getPngImage()]
def Draw(self):
self._display()
return 0
def setStyle():
style=ROOT.gStyle
style.SetFuncWidth(2)
captures = []
def loadMagicsAndCapturers():
global captures
extNames = ["JupyROOT.magics." + name for name in ["cppmagic","jsrootmagic"]]
ip = get_ipython()
extMgr = ExtensionManager(ip)
for extName in extNames:
extMgr.load_extension(extName)
captures.append(StreamCapture())
captures.append(CaptureDrawnPrimitives())
for capture in captures: capture.register()
def declareProcessLineWrapper():
ROOT.gInterpreter.Declare("""
TInterpreter::EErrorCode ProcessLineWrapper(const char* line) {
TInterpreter::EErrorCode err;
gInterpreter->ProcessLine(line, &err);
return err;
}
""")
def enhanceROOTModule():
ROOT.enableJSVis = enableJSVis
ROOT.disableJSVis = disableJSVis
ROOT.enableJSVisDebug = enableJSVisDebug
ROOT.disableJSVisDebug = disableJSVisDebug
def enableCppHighlighting():
ipDispJs = IPython.display.display_javascript
# Define highlight mode for %%cpp magic
ipDispJs(_jsMagicHighlight.format(cppMIME = cppMIME), raw=True)
def iPythonize():
setStyle()
loadMagicsAndCapturers()
declareProcessLineWrapper()
enableCppHighlighting()
enhanceROOTModule()
welcomeMsg()