-
Notifications
You must be signed in to change notification settings - Fork 122
/
MantidFramework.py
2030 lines (1745 loc) · 73.5 KB
/
MantidFramework.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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Access the Mantid Framework.
"""
import os
import platform
import sys
import types
import copy
import inspect
import opcode
import __builtin__
import __main__
try:
import mantidplot
import PyQt4.QtCore as qtcore
HAVE_GUI = True
except:
HAVE_GUI = False # Assume no gui
try:
import numpy
HAVE_NUMPY = True
except ImportError:
HAVE_NUMPY = False
# A list of filenames to suppress warnings about API removal
SUPPRESS_API_WARN = set()
###############################################################################
# Define the api version
###############################################################################
def apiVersion():
"""Indicates that this is version 1
of the API
"""
return 1
# Check whether MANTIDPATH is defined. If so, append it to the PYTHONPATH.
if os.getenv("MANTIDPATH") is not None:
sys.path.append(os.getenv("MANTIDPATH"))
else:
framework_file = os.path.abspath(__file__)
os.environ["MANTIDPATH"]=os.path.split(framework_file)[0] # use the directory
# --- Import the Mantid API ---
if os.name == 'nt':
from MantidPythonAPI import *
from MantidPythonAPI import _binary_op, _equals_op
else:
# The libMantidPythonAPI module is essentially statically linked
# to boost python. However, we need to ensure the Mantid libraries
# are loaded with the the RTLD_GLOBAL flag so that the singleton
# symbols are shared across the boundaries.
#
# We also need to coexist with the new-style interface meaning that
# the boost python registry must be kept private in each api
# so that multiple converters are not defined. This means that
# we cannot just pass the RTLD_GLOBAL flag here as this will
# cause the registry to be shared with the new api if it is
# loaded on top of this one. The only solution is to cherry
# pick the modules that are loaded with the RTLD symbol.
#
# Another nice issue is that the dl module is broken on 64-bit
# systems for Python 2.4 and ctypes doesn't exist there yet!
# All in all this meant a small custom module calling dlopen
# ourselves was the easiest way
import libdlopen
dlloader = libdlopen.loadlibrary
import subprocess
_bin = os.path.abspath(os.path.dirname(__file__))
pythonlib = os.path.join(_bin,'libMantidPythonAPI.so')
if not os.path.exists(pythonlib):
_bin = os.environ['MANTIDPATH']
pythonlib = os.path.join(_bin,'libMantidPythonAPI.so')
if not os.path.exists(pythonlib):
raise RuntimeError('Unable to find libMantidPythonAPI, cannot continue')
def get_libpath(mainlib, dependency):
if platform.system() == 'Linux':
cmd = 'ldd %s | grep %s' % (mainlib, dependency)
subp = subprocess.Popen(cmd,stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,shell=True)
out = subp.communicate()[0]
# ldd produces a string that always has 4 columns. The full path
# is in the 3rd column
libpath = out.split()[2]
else:
libpath = os.path.join(_bin, dependency + '.dylib')
return libpath
library_var = "LD_LIBRARY_PATH"
if platform.system() == 'Darwin':
library_var = 'DY' + library_var
ldpath = os.environ.get(library_var, "")
ldpath += ":" + _bin
os.environ[library_var] = ldpath
if platform.system() == 'Linux':
# stdc++ has to be loaded first or exceptions don't get translated
# properly across bounadries
# NeXus has to be loaded as well as there seems to be an issue with
# the thread-local storage not being initialized properly unles
# it is loaded before other libraries.
dlloader(get_libpath(pythonlib, 'stdc++'))
dlloader(get_libpath(pythonlib, 'libNeXus.so'))
dlloader(get_libpath(pythonlib, 'libMantidKernel'))
dlloader(get_libpath(pythonlib, 'libMantidGeometry'))
dlloader(get_libpath(pythonlib, 'libMantidAPI'))
oldflags = sys.getdlopenflags()
if platform.system() == "Darwin":
try:
import dl
RTLD_LOCAL = dl.RTLD_LOCAL
RTLD_NOW = dl.RTLD_NOW
except ImportError:
RTLD_LOCAL = 0x4
RTLD_NOW = 0x2
sys.setdlopenflags(RTLD_LOCAL|RTLD_NOW)
from libMantidPythonAPI import *
from libMantidPythonAPI import _binary_op, _equals_op
sys.setdlopenflags(oldflags)
# --- End of library load ---
#-------------------------------------------------------------------------------
def _makeString(value):
"""Make a string out of a value such that the Mantid properties can understand it
"""
if HAVE_NUMPY and isinstance(value, numpy.ndarray):
value = list(value) # Temp until more complete solution available (#2340)
if isinstance(value, list) or isinstance(value, cpp_list_dbl) \
or isinstance(value, cpp_list_int) or isinstance(value, cpp_list_long):
return str(value).lstrip('[').rstrip(']')
elif isinstance(value, tuple):
return str(value).lstrip('(').rstrip(')')
elif isinstance(value, bool):
if value:
return '1'
else:
return '0'
else:
return str(value)
#-------------------------------------------------------------------------------
def _decompile(code_object):
"""
Taken from
http://thermalnoise.wordpress.com/2007/12/30/exploring-python-bytecode/
Extracts dissasembly information from the byte code and stores it in
a list for further use.
Call signature(s):
instructions=decompile(f.f_code)
Required arguments:
========= =====================================================================
code_object A bytecode object extracted with inspect.currentframe()
or any other mechanism that returns byte code.
Optional keyword arguments: NONE
Outputs:
========= =====================================================================
instructions a list of offsets, op_codes, names, arguments, argument_type,
argument_value which can be deconstructed to find out various things
about a function call.
Example:
# Two frames back so that we get the callers' caller
f = inspect.currentframe().f_back.f_back
i = f.f_lasti # index of the last attempted instruction in byte code
ins = decompile(f.f_code)
"""
code = code_object.co_code
variables = code_object.co_cellvars + code_object.co_freevars
instructions = []
n = len(code)
i = 0
e = 0
while i < n:
i_offset = i
i_opcode = ord(code[i])
i = i + 1
if i_opcode >= opcode.HAVE_ARGUMENT:
i_argument = ord(code[i]) + (ord(code[i+1]) << (4*2)) + e
i = i + 2
if i_opcode == opcode.EXTENDED_ARG:
e = iarg << 16
else:
e = 0
if i_opcode in opcode.hasconst:
i_arg_value = repr(code_object.co_consts[i_argument])
i_arg_type = 'CONSTANT'
elif i_opcode in opcode.hasname:
i_arg_value = code_object.co_names[i_argument]
i_arg_type = 'GLOBAL VARIABLE'
elif i_opcode in opcode.hasjrel:
i_arg_value = repr(i + i_argument)
i_arg_type = 'RELATIVE JUMP'
elif i_opcode in opcode.haslocal:
i_arg_value = code_object.co_varnames[i_argument]
i_arg_type = 'LOCAL VARIABLE'
elif i_opcode in opcode.hascompare:
i_arg_value = opcode.cmp_op[i_argument]
i_arg_type = 'COMPARE OPERATOR'
elif i_opcode in opcode.hasfree:
i_arg_value = variables[i_argument]
i_arg_type = 'FREE VARIABLE'
else:
i_arg_value = i_argument
i_arg_type = 'OTHER'
else:
i_argument = None
i_arg_value = None
i_arg_type = None
instructions.append( (i_offset, i_opcode, opcode.opname[i_opcode], i_argument, i_arg_type, i_arg_value) )
return instructions
#-------------------------------------------------------------------------------
# A must list all of the operators that behave like a function calls in byte-code
# This is for the lhs functionality
__operator_names=set(['CALL_FUNCTION','UNARY_POSITIVE','UNARY_NEGATIVE','UNARY_NOT',
'UNARY_CONVERT','UNARY_INVERT','GET_ITER', 'BINARY_POWER',
'BINARY_MULTIPLY','BINARY_DIVIDE', 'BINARY_FLOOR_DIVIDE',
'BINARY_TRUE_DIVIDE', 'BINARY_MODULO','BINARY_ADD','BINARY_SUBTRACT',
'BINARY_SUBSCR','BINARY_LSHIFT','BINARY_RSHIFT','BINARY_AND',
'BINARY_XOR','BINARY_OR', 'INPLACE_POWER', 'INPLACE_MULTIPLY',
'INPLACE_DIVIDE', 'INPLACE_TRUE_DIVIDE','INPLACE_FLOOR_DIVIDE',
'INPLACE_MODULO', 'INPLACE_ADD', 'INPLACE_SUBTRACT',
'INPLACE_LSHIFT','INPLACE_RSHIFT','INPLACE_AND', 'INPLACE_XOR',
'INPLACE_OR',
'COMPARE_OP'])
#-------------------------------------------------------------------------------
def lhs_info(output_type='both'):
"""Returns the number of arguments on the left of assignment along
with the names of the variables.
Acknowledgements:
Thanks to Tim Charlton and Jon Taylor of the ISIS facility for
figuring this out.
Call signature(s)::
Required arguments: NONE
Optional keyword arguments Meaning:
=========================== ==========
output_type A string enumerating the type of output, one of
output_type = 'nreturns' : The number of return values
expected from the call
output_type = 'names' : Just return a list of
variable names
output_type = 'both' : A tuple containing both of
the above
Outputs:
=========
Depends on the value of the argument. See above.
"""
# Two frames back so that we get the callers' caller, i.e. this should only
# be called from within a function
try:
frame = inspect.currentframe().f_back.f_back
except AttributeError:
raise RuntimeError("lhs_info cannot be used on the command line, only within a function")
# Process the frame noting the advice here:
# http://docs.python.org/library/inspect.html#the-interpreter-stack
try:
ret_vals = _process_frame(frame)
finally:
del frame
if output_type == 'nreturns':
ret_vals = ret_vals[0]
elif output_type == 'names':
ret_vals = ret_vals[1]
else:
pass
return ret_vals
#-------------------------------------------------------------------------------
def _process_frame(frame):
"""Returns the number of arguments on the left of assignment along
with the names of the variables for the given frame.
Call signature(s)::
Required arguments:
=========================== ==========
frame The code frame to analyse
Outputs:
=========
Returns the a tuple with the number of arguments and their names
"""
# Index of the last attempted instruction in byte code
last_i = frame.f_lasti
ins_stack = _decompile(frame.f_code)
call_function_locs = {}
start_index = 0
start_offset = 0
for index, instruction in enumerate(ins_stack):
(offset, op, name, argument, argtype, argvalue) = instruction
if name in __operator_names:
call_function_locs[start_offset] = (start_index, index)
start_index = index
start_offset = offset
(offset, op, name, argument, argtype, argvalue) = ins_stack[-1]
# Append the index of the last entry to form the last boundary
call_function_locs[start_offset] = (start_index, len(ins_stack)-1)
# In our case last_i should always be the offset of a call_function_locs instruction.
# We use this to bracket the bit which we are interested in
output_var_names = []
max_returns = []
last_func_offset = call_function_locs[last_i][0]
(offset, op, name, argument, argtype, argvalue) = ins_stack[last_func_offset + 1]
if name == 'POP_TOP': # no return values
pass
if name == 'STORE_FAST' or name == 'STORE_NAME': # one return value
output_var_names.append(argvalue)
if name == 'UNPACK_SEQUENCE': # Many Return Values, One equal sign
for index in range(argvalue):
(offset_, op_, name_, argument_, argtype_, argvalue_) = ins_stack[last_func_offset + 2 +index]
output_var_names.append(argvalue_)
max_returns = len(output_var_names)
if name == 'DUP_TOP': # Many Return Values, Many equal signs
# The output here should be a multi-dim list which mimics the variable unpacking sequence.
# For instance a,b=c,d=f() => [ ['a','b'] , ['c','d'] ]
# a,b=c=d=f() => [ ['a','b'] , 'c','d' ] So on and so forth.
# put this in a loop and stack the results in an array.
count = 0
max_returns = 0 # Must count the max_returns ourselves in this case
while count < len(ins_stack[call_function_locs[i][0]:call_function_locs[i][1]]):
(offset_, op_, name_, argument_, argtype_, argvalue_) = ins[call_function_locs[i][0]+count]
if name_ == 'UNPACK_SEQUENCE': # Many Return Values, One equal sign
hold = []
if argvalue_ > max_returns:
max_returns = argvalue_
for index in range(argvalue_):
(_offset_, _op_, _name_, _argument_, _argtype_, _argvalue_) = ins[call_function_locs[i][0] + count+1+index]
hold.append(_argvalue_)
count = count + argvalue_
output_var_names.append(hold)
# Need to now skip the entries we just appended with the for loop.
if name_ == 'STORE_FAST' or name_ == 'STORE_NAME': # One Return Value
if 1 > max_returns:
max_returns = 1
output_var_names.append(argvalue_)
count = count + 1
return (max_returns,output_var_names)
#-------------------------------------------------------------------------------
def in_callstack(fn_name, frame):
"""Check whether the call stack from the given frame contains the given
function name.
@param fn_name :: The function name to search for
@param frame :: Start the search at this frame
@returns True if the function name exists in the stack, false otherwise
"""
if frame.f_code.co_name == fn_name:
return True
while True:
if frame.f_back:
if frame.f_back.f_code.co_name == fn_name:
return True
frame = frame.f_back
else:
break
if frame.f_code.co_name == fn_name:
return True
else:
return False
#-------------------------------------------------------------------------------
def find_parent_python_algorithm(frame):
""" By inspecting the call stack looking for PyExec(), find the
parent PythonAlgorithm that is calling the current method.
Returns
-------
The 'self' python algorithm object that is running PyExec().
or, None if not found.
"""
# We are looking for this method name, signifying PythonAlgorithm
fn_name = "PyExec"
# Return the 'self' object of a given frame
def get_self(frame):
return frame.f_locals['self']
# Look recursively for the PyExec method in the stack
if frame.f_code.co_name == fn_name:
return get_self(frame)
while True:
if frame.f_back:
if frame.f_back.f_code.co_name == fn_name:
return get_self(frame.f_back)
frame = frame.f_back
else:
break
if frame.f_code.co_name == fn_name:
return get_self(frame)
else:
return None
#-------------------------------------------------------------------------------
def mtdGlobalHelp():
# first part is algorithm name, second is version
orig_algs = mtd._getRegisteredAlgorithms(include_hidden=False)
# do the final formatting
algs = []
for alg in orig_algs:
(name, version) = alg
version = ["v%d" % it for it in version]
version = " ".join(version)
if version == "v1":
algs.append(name)
else:
algs.append("%s %s" % (name, version))
algs.sort()
# print out the global help information
print "The algorithms available are:\n"
for alg in algs:
print " %s" % alg
print "For help with a specific command type: help('cmd')"
if HAVE_GUI:
print "Note: Each command also has a counterpart with the word 'Dialog' appended ",
print "to it, which when run will bring up a property input dialog for that algorithm."
# Commit on behalf of Pete Peterson:
def mantidHelp(cmd = None):
if cmd == None or cmd == '':
mtdGlobalHelp()
return
help(cmd)
## This function should generically go away, but for now...
#def mantidHelp(cmd = None):
# if cmd == None or cmd == '':
# mtdGlobalHelp()
# return
# try:
# cmd = cmd.func_name
# except AttributeError:
# pass
# try:
# # Try exact case first as it will be quicker
# exec('help(%s)' % cmd)
# return
# except NameError:
# alg_name = mtd.isAlgorithmName(cmd)
# if alg_name == '':
# print 'mtdHelp(): "%s" not found in help list' % cmd
# else:
# exec('help(%s)' % alg_name)
# Some case variations on the mantidHelp function
mantidhelp = mantidHelp
mantidHelp = mantidHelp
MantidHelp = mantidHelp
mtdhelp = mantidHelp
mtdHelp = mantidHelp
Mtdhelp = mantidHelp
MtdHelp = mantidHelp
#-------------------------------------------------------------------------------
class ProxyObject(object):
"""Base class for all objects acting as proxys
"""
def __init__(self, toproxy):
self.__obj = toproxy
def __getattr__(self, attr):
"""
Reroute a method call to the the stored object
"""
return getattr(self._getHeldObject(), attr)
def __str__(self):
"""
Return a string representation of the proxied object
"""
return str(self._getHeldObject())
def __repr__(self):
"""
Return a string representation of the proxied object
"""
return `self._getHeldObject()`
def _getHeldObject(self):
"""
Returns a reference to the held object
"""
return self.__obj
def _kill_object(self):
"""
Release the stored instance
"""
self.__obj = None
def _swap(self, obj):
"""
Swap an object so that the proxy now refers to this object
"""
self.__obj = obj
# Prefix for temporary objects within workspace binary operations
_binary_op_prefix = '__binary_tmp'
# A list of temporary workspaces created by algebraic operations
_binary_op_tmps = []
class WorkspaceProxy(ProxyObject):
"""
A proxy object that stores a workspace instance. When the workspace is deleted
from the ADS in Mantid, the object reference held here is set to 'None'
"""
def __init__(self, obj, factory):
"""
Create a proxy for the given object
"""
super(WorkspaceProxy, self).__init__(obj)
self.__factory = factory
def __iter__(self):
"""
Pass on to iterator if this is a table
"""
if hasattr(self._getHeldObject(), '__iter__'):
return self._getHeldObject().__iter__()
else:
raise AttributeError('Object does not support iteration')
def __getitem__(self, index):
"""
If we are a group then return a member, else return self
"""
if self.isGroup():
return self.__factory.create(self._getHeldObject().getNames()[index])
else:
raise AttributeError('Index invalid, object is not a group.')
def __do_operation(self, op, rhs, inplace, reverse, lhs_vars):
"""
Perform the given binary operation
lhs_vars is expected to be a tuple containing the number of lhs variables and
their names as the first and second element respectively
"""
global _binary_op_tmps
if lhs_vars[0] > 0:
# Assume the first and clear the tempoaries as this
# must be the final assignment
if inplace:
output_name = self.getName()
else:
output_name = lhs_vars[1][0]
clear_tmps = True
else:
# Give it a temporary name and keep track of it
clear_tmps = False
output_name = _binary_op_prefix + str(len(_binary_op_tmps))
_binary_op_tmps.append(output_name)
# Do the operation
if isinstance(rhs, WorkspaceProxy):
rhs = rhs._getHeldObject()
resultws = _binary_op(self._getHeldObject(),rhs, op, output_name, inplace, reverse)
if clear_tmps:
for name in _binary_op_tmps:
if mtd.workspaceExists(name) and output_name != name:
mtd.deleteWorkspace(name)
_binary_op_tmps = []
if inplace:
return self
else:
return self.__factory.create(resultws)
def __add__(self, rhs):
"""
Sum the proxied objects and return a new proxy managing that object
"""
# Figure out the name of the output. Only the final function call that is
# before the assignment will have the name of the variable
lhs = lhs_info()
return self.__do_operation('Plus', rhs,inplace=False, reverse=False,
lhs_vars=lhs)
def __radd__(self, rhs):
"""
Sum the proxied objects and return a new proxy managing that object
"""
lhs = lhs_info()
return self.__do_operation('Plus', rhs,inplace=False, reverse=True,
lhs_vars=lhs)
def __iadd__(self, rhs):
"""
In-place sum the proxied objects and return a new proxy managing that object
"""
lhs = lhs_info()
return self.__do_operation('Plus', rhs,inplace=True, reverse=False,
lhs_vars=lhs)
def __sub__(self, rhs):
"""
Subtract the proxied objects and return a new proxy managing that object
"""
lhs = lhs_info()
return self.__do_operation('Minus', rhs,inplace=False, reverse=False,
lhs_vars=lhs)
def __rsub__(self, rhs):
"""
Handle a (double - workspace)
"""
lhs = lhs_info()
return self.__do_operation('Minus', rhs,inplace=False, reverse=True,
lhs_vars=lhs)
def __isub__(self, rhs):
"""
In-place subtract the proxied objects and return a new proxy managing that object
"""
lhs = lhs_info()
return self.__do_operation('Minus', rhs,inplace=True, reverse=False,
lhs_vars=lhs)
def __mul__(self, rhs):
"""
Multiply the proxied objects and return a new proxy managing that object
"""
lhs = lhs_info()
return self.__do_operation('Multiply', rhs,inplace=False, reverse=False,
lhs_vars=lhs)
def __rmul__(self, rhs):
"""
Multiply the proxied objects and return a new proxy managing that object
"""
lhs = lhs_info()
return self.__do_operation('Multiply', rhs,inplace=False, reverse=True,
lhs_vars=lhs)
def __imul__(self, rhs):
"""
In-place multiply the proxied objects and return a new proxy managing that object
"""
lhs = lhs_info()
return self.__do_operation('Multiply', rhs,inplace=True, reverse=False,
lhs_vars=lhs)
def __div__(self, rhs):
"""
Divide the proxied objects and return a new proxy managing that object
"""
lhs = lhs_info()
return self.__do_operation('Divide', rhs,inplace=False, reverse=False,
lhs_vars=lhs)
def __rdiv__(self, rhs):
"""
Handle a double/workspace
"""
lhs = lhs_info()
return self.__do_operation('Divide', rhs,inplace=False, reverse=True,
lhs_vars=lhs)
def __idiv__(self, rhs):
"""
In-place divide the proxied objects and return a new proxy managing that object
"""
lhs = lhs_info()
return self.__do_operation('Divide', rhs,inplace=True, reverse=False,
lhs_vars=lhs)
def __lt__(self, rhs):
"""
Do the (self < rhs) comparison and return a new proxy managing that object
"""
lhs = lhs_info()
return self.__do_operation('LessThan', rhs, inplace=False, reverse=False,
lhs_vars=lhs)
def __gt__(self, rhs):
"""
Do the (self > rhs) comparison and return a new proxy managing that object
"""
lhs = lhs_info()
return self.__do_operation('GreaterThan', rhs, inplace=False, reverse=False,
lhs_vars=lhs)
def __or__(self, rhs):
"""
Do the (self || rhs) comparison and return a new proxy managing that object
"""
lhs = lhs_info()
return self.__do_operation('Or', rhs, inplace=False, reverse=False,
lhs_vars=lhs)
def __and__(self, rhs):
"""
Do the (self && rhs) comparison and return a new proxy managing that object
"""
lhs = lhs_info()
return self.__do_operation('And', rhs, inplace=False, reverse=False,
lhs_vars=lhs)
def __xor__(self, rhs):
"""
Do the (self ^ rhs) comparison and return a new proxy managing that object
"""
lhs = lhs_info()
return self.__do_operation('Xor', rhs, inplace=False, reverse=False,
lhs_vars=lhs)
def __pow__(self, y):
""" Raise a workspace to a power. Equivalent of x**y.
Args:
x :: workspace or other type.
y :: exponent
"""
lhs = lhs_info()
return self.__do_unary_operation("PowerMD", lhs, Exponent=y)
def __do_unary_operation(self, op, lhs_vars, **kwargs):
"""
Perform the unary operation
Args:
op :: name of the algorithm to run
lhs_vars :: is expected to be a tuple containing the number of lhs variables and
their names as the first and second element respectively
kwargs :: additional properties to give to algorithm
"""
global _binary_op_tmps
if lhs_vars[0] > 0:
# Assume the first and clear the tempoaries as this
# must be the final assignment
output_name = lhs_vars[1][0]
clear_tmps = True
else:
# Give it a temporary name and keep track of it
clear_tmps = False
output_name = _binary_op_prefix + str(len(_binary_op_tmps))
_binary_op_tmps.append(output_name)
# Do the operation
alg = mtd.createAlgorithm(op)
alg.setPropertyValue("InputWorkspace", self.getName())
alg.setPropertyValue("OutputWorkspace", output_name)
for (key,value) in kwargs.items():
alg.setPropertyValue(key,str(value))
alg.execute()
resultws = alg.workspace()
if clear_tmps:
for name in _binary_op_tmps:
if mtd.workspaceExists(name) and output_name != name:
mtd.deleteWorkspace(name)
_binary_op_tmps = []
return resultws
def __invert__(self):
"""
Return the inversion (NOT operator) on self
"""
lhs = lhs_info()
return self.__do_unary_operation('NotMD', lhs_vars=lhs)
def equals(self, rhs, tol):
"""
Checks whether the given workspace matches this one within the allowed
tolerance.
rhs - The workspace to compare with
tol - A tolerance value, e.g. 1e-08
Returns True if the workspaces contain the same data, false otherwise
"""
return _equals_op(self._getHeldObject(), rhs._getHeldObject(), tol)
def isGroup(self):
"""
Is the data object a WorkspaceGroup or not
"""
if isinstance(self._getHeldObject(), WorkspaceGroup):
return True
else:
return False
def getRun(self):
"""
Return an object describing properties of the run
"""
return RunProxy(self._getHeldObject().getRun())
#-------------------------------------------------------------------------------
class RunProxy(ProxyObject):
"""Holds information regarding the run as a list of properties.
It defines a dictionary interface for the run properties.
"""
def __init__(self, runobj):
"""
Constructor
"""
super(RunProxy, self).__init__(runobj)
self.__properties = {}
props = runobj.getProperties()
for prop in props:
self.__properties[prop.name] = prop
def keys(self):
"""
Return a list of property names
"""
return self.__properties.keys()
def __contains__(self, key):
"""
Does the run contain a given property?
Returns true if it does, false otherwise
"""
return key in self.__properties
def __getitem__(self, key):
"""
Returns the value of the item with the given key.
If the key is not contained within the property list
then a KeyValueError is raised
"""
return self.__properties[key]
def get(self, key, default=None):
"""
Returns the value of the item with the given key or default if
the key does not exist
"""
if key in self.__properties:
return self[key]
else:
return default
def __setitem__(self, key, value, overwrite=False):
"""
Sets the value of the item with the given key. This has limited
support for types.
"""
print "__setitem__(%s, %s, %s, %s)" % (self, key, value, overwrite)
value_type = type(value)
runobj = self._getHeldObject()
if value_type == type(1.):
runobj.addProperty_dbl(key, value, overwrite)
elif value_type == type(1):
runobj.addProperty_int(key, value, overwrite)
elif value_type == type(""):
runobj.addProperty_str(key, value, overwrite)
else:
raise TypeError("Not working for %s" % str(type(value)))
prop = self._getHeldObject().getProperty(key)
self.__properties[key] = prop
#-------------------------------------------------------------------------------
class WorkspaceProxyFactory(object):
def __init__(self, garbage_collector, framework):
self.__gc = garbage_collector
self.__framework = framework
def create(self, obj):
wksp = obj
if isinstance(obj, str):
wksp = self.__framework._retrieveWorkspace(obj)
if wksp == None:
return None
proxy = WorkspaceProxy(wksp, self)
self.__gc.register(wksp.getName(), proxy)
return proxy
#-------------------------------------------------------------------------------
class WorkspaceGarbageCollector(object):
"""
A register of workspaces that have been retrieved from Mantid
"""
def __init__(self):
self._refs = {}
def register(self, name, proxy):
"""
Register a name and reference to the store
"""
self._refs[name] = proxy
def replace(self, name, wksp):
"""
Replace an object reference within a proxy
"""
try:
self._refs[name]._swap(wksp)
except Exception:
pass
def kill_object(self, name):
"""
Signal the proxy to nullify its stored reference
"""
try:
self._refs[name]._kill_object()
# Remove the key as we don't want to keep the reference around
del self._refs[name]
except Exception:
pass
def kill_all(self):
"""
Kill all references to data objects
"""
# Note here that a simple clear won't do as it won't set the object reference to None
for w in self._refs:
self._refs[w]._kill_object()
self._refs.clear()
#---------------------------------------------------------------------------------------
class IAlgorithmProxy(ProxyObject):
"""
A proxy object for IAlgorithm returns
"""
def __init__(self, ialg, framework):
super(IAlgorithmProxy, self).__init__(ialg)
self.__framework = framework
self.__havelist = False
self.__wkspnames = []
self.__propertynames = {} # the names of properties and their directions
# 0 - input
# 1 - output
for prop in ialg.getProperties():
self.__propertynames[prop.name] = prop.direction
self.__propertyOrder = None
def workspace(self):
return self._retrieveWorkspaceByIndex(0)
def keys(self):
return self.__propertynames.keys()
def __contains__(self, key):
if key in self.__propertynames.keys():
return True
# TODO should there be more checks?
return False
def __getitem__(self, key):
if key in self.__propertynames.keys():
# get the value of the properties
value = self._getHeldObject().getPropertyValue(key)
# convert to a workspace if appropriate
self._createWorkspaceList()
if value in self.__wkspnames:
return self.__framework[value]
else: