def setUp(self): unittest.TestCase.setUp(self) self.globals = {} self.locals = MultiContext(self.globals) self.interpreter = GlobalAndLocalInterpreter(locals=self.locals, globals=self.globals) # Name of local variable name to use in expressions self.input_name = 'vp' # Value to use in expressions. self.local_input = 1 self.global_input = 1
def setUp(self): code = "from blockcanvas.debug.my_operator import add\n"\ "c = add(a,b)" self.block = Block(code) # Context setup self.context = MultiContext(DataContext(name='Data'), {}) self.context['a'] = 1 self.context['b'] = 2
def test_use_as_context(self): # Can we use the context as the namespace of a python calculation? from codetools.contexts.api import DataContext, MultiContext with tables.open_file('test.h5') as table: hdf_context = Hdf5Context(file_object=table, path=['root', 'root.group1', 'root.group2']) results = DataContext() context = MultiContext(results, hdf_context) exec_('array2_plus_one = [a2 + 1 for a2 in array2]', {}, context) assert_equal(context['array2_plus_one'], [2, 3, 4, 5])
def setUp(self): code = "from blockcanvas.debug.my_operator import add, mul\n" \ "c = add(a,b)\n" \ "d = mul(c, 2)\n" \ "e = mul(c, 3)\n" \ "f = add(d,e)" self.block = Block(code) # Context setup. self.context = MultiContext(DataContext(name='Data'), {}) self.context['a'] = 1 self.context['b'] = 2
def _update_exec_context(self): mc = MultiContext( # Put the function filter in front so we don't dirty up the data # context with function objects. FunctionFilterContext(name='functions'), self._local_context, name='multi', ) if self._shared_context is not None: mc.subcontexts.append(self._shared_context) self.context = ExecutingContext( executable=self.exec_model, subcontext=mc, name='exec', )
def setUp(self): code = "from blockcanvas.debug.my_operator import add,mul\n"\ "c = add(a, b)\n" \ "d = mul(c, 2)\n" \ "e = mul(c, 3)\n" \ "f = add(d, e)\n" \ "g = add(f, 3)\n" \ "h = mul(g, f)\n" \ "i = mul(g,h)" self.block = Block(code) # Context setup. self.context = MultiContext(DataContext(name='Data'), {}) self.context['a'] = 1.0 self.context['b'] = 2 self.block.execute(self.context) # ConfigurableInteractor setup i_config = InteractorConfig(var_configs=[ VariableConfig(name='a', type='Shadow'), VariableConfig(name='b', type='Parametric'), VariableConfig(name='c', type='Shadow'), VariableConfig(name='d', type='Parametric'), VariableConfig(name='e', type='Stochastic: Constant'), VariableConfig(name='f', type='Stochastic: Gaussian'), VariableConfig(name='g', type='Stochastic: Triangular'), VariableConfig(name='h', type='Stochastic: Uniform'), ]) self.interactor = ConfigurableInteractor(interactor_config=i_config, block=self.block, context=self.context) # Temp dir self.temp_dir = tempfile.gettempdir()
class GlobalAndLocalInterpreterTestCase(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self.globals = {} self.locals = MultiContext(self.globals) self.interpreter = GlobalAndLocalInterpreter(locals=self.locals, globals=self.globals) # Name of local variable name to use in expressions self.input_name = 'vp' # Value to use in expressions. self.local_input = 1 self.global_input = 1 def tearDown(self): unittest.TestCase.tearDown(self) def test_default_construction(self): """ Can we create a default interpreter? """ interpreter = GlobalAndLocalInterpreter() def test_set_item_local(self): """ Can we set a value to the local dictionary? """ # vp=1 expr = "%s=%s" % (self.input_name, self.local_input) self.interpreter.push(expr) self.assertEqual(self.locals[self.input_name], self.local_input) def test_del_item_local(self): """ Can we we delete an item from locals? """ # vp=1 expr = "%s=%s" % (self.input_name, self.local_input) self.interpreter.push(expr) # del vp expr = "del %s" % self.input_name self.interpreter.push(expr) self.assertFalse(self.locals.has_key(self.input_name)) def test_del_item_global_with_global_statement(self): """ Can we delete a global variable if declared global? """ self.globals[self.input_name] = self.global_input # assert(vp==1) expr = "assert(%s==%s)" % (self.input_name, self.global_input) self.interpreter.push(expr) # global vpl; del vp; expr = "global %s; del %s" % (self.input_name, self.input_name) self.interpreter.push(expr) self.assertFalse(self.globals.has_key(self.input_name)) def test_del_item_global(self): """ Can we delete a global variable even if it isn't declared global? """ self.globals[self.input_name] = self.global_input self.assertTrue(self.globals.has_key(self.input_name)) # assert(vp==1) expr = "assert(%s==%s)" % (self.input_name, self.global_input) self.interpreter.push(expr) # del vp; expr = "del %s" % self.input_name self.interpreter.push(expr) self.assertFalse(self.locals.has_key(self.input_name)) self.assertFalse(self.globals.has_key(self.input_name)) def test_wildcard_style_imports(self): """ Can we use 'from xyz import \*'? """ self.interpreter.push("from sys import *") self.assertTrue(self.globals.has_key('exc_info')) def test_list_comprehension(self): """ Can we run a list comprehension in the interpreter? """ self.interpreter.push("val = [x for x in [1,2,3]]")
# from scimath.units.length import meter code = "from blockcanvas.debug.my_operator import add, mul\n" \ "c = add(a,b)\n" \ "d = mul(c, 2)\n" \ "e = mul(c, 3)\n" \ "f = add(d,e)" block = Block(code) # context = ParametricContext(GeoContext(), {}) # context['a'] = UnitArray((1,2,3), units=meter) # context['b'] = UnitArray((2,3,4), units=meter) # # interactor = ParametricInteractor(context=context, block = block) # interactor.configure_traits() # Context setup. context = MultiContext(DataContext(name='Data'), {}) context['a'] = 1 context['b'] = 2 interactor = ParametricInteractor(context=context, block=block) interactor.configure_traits() for shadow in context.shadows: block.execute(shadow) print shadow['f'], 'Check with:', 5 * (shadow['a'] + shadow['b']) ### EOF ------------------------------------------------------------------------
class Application(HasTraits): """ The Application object that ties together an execution model, the canvas, the function search window, and the shell. """ ###################################################################### # Application Traits ###################################################################### # The currently loaded, active project project = Instance(Project) # The view model for the current project's context. context_viewer = Instance(ContextVariableList) # The Function Search # fixme: This should probably not live here. function_search = Instance(FunctionSearch, args=()) # The Function Library # fixme: This should probably not live here. function_library = Instance(FunctionLibrary, args=()) # The data directory. data_directory = Str() # The directory for other files. file_directory = Str() # Window for displaying HTML help for functions. # FIXME: It would be better to re-factor this into an active_help_item # trait with an HTML Editor. html_window = Instance(HtmlInfoUI, args=()) # Status bar text status = Str # Exectue automatically whenever the nodes, bindings, etc. are changed auto_execute = Bool(False) ###################################################################### # object interface ###################################################################### def __init__(self, code=None, data_context=None, *args, **kwargs): super(Application, self).__init__(*args, **kwargs) # Set the global app object in the scripting module. scripting.app = self self.project = Project() if data_context is None: data_context = DataContext(name='data') self.project.add_context(data_context) if code is not None: exp = Experiment(code=code, shared_context=data_context) else: exp = Experiment(shared_context=data_context) self.project.active_experiment = exp self.context_viewer = ContextVariableList(context=exp.context) # XXX: the @on_trait_change decorator is not working for this! self.on_trait_change(self._context_items_modified, 'project:active_experiment.context:items_modified') ###################################################################### # HasTraits interface ###################################################################### def trait_view(self, name=None, view_elements=None): if name is None or name=='full': return View( VGroup( HSplit( VSplit( Item('function_search', editor = InstanceEditor(view=function_search_view), label = 'Search', id = 'search', style = 'custom', dock = 'horizontal', show_label = False, ), Item('html_window', style='custom', show_label=False, springy= True, resizable=True, ), id='search_help_view' ), VSplit( Item( 'object.project.active_experiment.canvas', label = 'Canvas', id = 'canvas', # FIXME: need a new way to control the canvas # not using BlockEditor editor = BlockEditor(), dock = 'horizontal', show_label = False ), Item( 'object.project.active_experiment.exec_model.code', label = 'Code', id = 'code', editor = CodeEditor(dim_lines = 'dim_lines', dim_color = 'dim_color', squiggle_lines = 'squiggle_lines'), dock = 'horizontal', show_label = False ), ), Item( 'context_viewer', label = 'Context', id = 'context_table', editor = InstanceEditor(), style = 'custom', dock = 'horizontal', show_label = False, ), id='panel_split', ), Item( 'status', style = 'readonly', show_label = False, resizable = False ), ), title = 'Block Canvas', menubar = BlockApplicationMenuBar, width = 1024, height = 768, id = 'blockcanvas.app.application', resizable = True, handler = BlockApplicationViewHandler(model=self), key_bindings = KeyBindings( KeyBinding(binding1='F5', method_name='_on_execute'), ), ) elif name == 'simple': return View( HSplit( VSplit( Item('function_search', editor = InstanceEditor(view=function_search_view), label = 'Search', id = 'search', style = 'custom', dock = 'horizontal', show_label = False), Item('html_window', style='custom', show_label=False, springy= True, resizable=True), id='search_help_view' ), Item( 'object.project.active_experiment.canvas', label = 'Canvas', id = 'canvas', # FIXME: need a new way to control the canvas # not using BlockEditor editor = BlockEditor(), dock = 'horizontal', show_label = False), id='panel_split'), title = 'Block Canvas - Simple View', menubar = BlockApplicationMenuBar, width = 800, height = 600, id = 'blockcanvas.app.application.simple', resizable = True, handler = BlockApplicationViewHandler(model=self), key_bindings = KeyBindings( KeyBinding(binding1='F5', method_name='_on_execute'), ) ) ###################################################################### # Application interface ###################################################################### def reset(self): """ Reset the Application to its initial state. Clean all old attributes and instanciate new ones. """ for context in self.project.contexts: self.project.remove_context(context) data_context = DataContext(name='data') self.project.add_context(data_context) exp = Experiment(shared_context=data_context) self.project.active_experiment = exp self.context_viewer = ContextVariableList(context=exp.context) ### load/save python scripts ######################################### def load_code_from_file(self, filename): experiment = Experiment() experiment.load_code_from_file(filename) self.project.experiments.append(experiment) self.project.active_experiment = experiment self.update_functions_UI(self.project.active_experiment.exec_model.statements) self.update_functions_context(self.project.active_experiment, self.project.active_experiment.exec_model.statements) def save_code_to_file(self, filename=""): self.project.active_experiment.save_script(filename) def run_custom_ui(self, filename, live=True): """ Load a module to visually interact with the context. Parameters ---------- filename : str The filename of the module with the view. It should expose a function called "viewable(context)" which takes an ExecutingContext and returns a HasTraits instance which can be edited with .edit_traits(). live : bool, optional If True, then the interaction happens directly with the context itself. If False, a "copy-on-write" shadow context is put in front of the context. """ globals = {} try: execfile(filename, globals) except Exception, e: msg = ("Cannot execute the file %s\n%s: %s" % (filename, e.__class__.__name__, e)) dlg = MessageDialog(message=msg, severity='error') dlg.open() return if 'viewable' not in globals: msg = ("Cannot find the 'viewable' function in the module %s" % filename) dlg = MessageDialog(message=msg, severity='error') dlg.open() return viewable = globals['viewable'] if live: context = self.project.active_experiment.context else: # Create a copy-on-write context. exp_context = self.project.active_experiment.context context = ExecutingContext(executable=exp_context.executable, subcontext=MultiContext({}, exp_context.subcontext)) # XXX: put this in a view model with a button to shove the data back # into the main context. tui = viewable(context) tui.edit_traits(kind='live')
def context_factory(self): """ Return the type of context we are testing. """ return MultiContext(GeoContext(), {})