Пример #1
0
def hardcode_vars():

    ### Setup execution block ###############################################
    # Context setup.
    context = DataContext(name='Data')
    context['a'] = 0.5
    context['b'] = 3.0
    context['c'] = 4.0
    """
    context.defer_events = True
    x = arange(0,10,.01)
    context['a'] = 1.0
    context['b'] = array([1, 2, 3])
    context['c'] = array([4, 5, 6])
    context.defer_events = False
    """
    context.defer_events = False

    code = "from blockcanvas.debug.my_operator import add, mul\n" \
           "from numpy import arange\n" \
           "x = arange(0,10,.1)\n" \
           "c1 = mul(a,a)\n" \
           "x1 = mul(x,x)\n" \
           "t1 = mul(c1,x1)\n" \
           "t2 = mul(b, x)\n" \
           "t3 = add(t1,t2)\n" \
           "y = add(t3,c)\n"

    return code, context
Пример #2
0
    def test_assign_value(self):
        context = DataContext()
        context.on_trait_change(self.event_listener, 'items_modified')
        context['a'] = 'foo'

        self.assertEqual(self.event_count, 1)
        self.assertEqual(self.last_event.added, ['a'])
        self.assertEqual(self.last_event.modified, [])
        self.assertEqual(self.last_event.removed, [])
Пример #3
0
def test_checkpoint():
    d = DataContext()
    d['a'] = object()
    d['b'] = object()
    copy = d.checkpoint()
    assert copy is not d
    assert copy.subcontext is not d.subcontext
    assert set(copy.keys()) == set(d.keys())
    assert copy['a'] is d['a']
    assert copy['b'] is d['b']
Пример #4
0
    def test_defer_add_event(self):
        context = DataContext()
        context.on_trait_change(self.event_listener, 'items_modified')
        context.defer_events = True
        context['a'] = 'foo'
        context.defer_events = False

        self.assertEqual(self.event_count, 1)
        self.assertEqual(self.last_event.added, ['a'])
        self.assertEqual(self.last_event.modified, [])
        self.assertEqual(self.last_event.removed, [])
Пример #5
0
    def test_delete_after_add(self):
        context = DataContext()
        context.on_trait_change(self.event_listener, 'items_modified')
        self.assertEqual(self.event_count, 0)
        context.defer_events = True
        self.assertEqual(self.event_count, 0)
        context['a'] = 'foo'
        self.assertEqual(self.event_count, 0)
        del context['a']
        self.assertEqual(self.event_count, 0)
        context.defer_events = False

        self.assertEqual(self.event_count, 0)
Пример #6
0
def test_persistence():
    """ Can DataContexts round-trip through the persistence mechanism?
    """
    d = DataContext(name='test_context')
    d['a'] = 1
    d['b'] = 2

    f = BytesIO()
    d.save(f)
    f.seek(0, 0)
    d2 = DataContext.load(f)

    assert d.name == d2.name
    assert set(d2.keys()) == set(['a', 'b'])
    assert d2['a'] == d['a']
    assert d2['b'] == d['b']
Пример #7
0
    def test_defer_multiple_events(self):
        context = DataContext()
        context.on_trait_change(self.event_listener, 'items_modified')
        context.defer_events = True
        self.assertEqual(self.event_count, 0)
        context['a'] = 'foo'
        self.assertEqual(self.event_count, 0)
        context['a'] = 'foo2'
        self.assertEqual(self.event_count, 0)
        context['b'] = 'bar'
        self.assertEqual(self.event_count, 0)
        context.defer_events = False

        # the modified will be empty, because it was also added
        self.assertEqual(self.event_count, 1)
        self.assertEqual(set(self.last_event.added), set(['a', 'b']))
        self.assertEqual(self.last_event.modified, [])
        self.assertEqual(self.last_event.removed, [])
Пример #8
0
    def test_block_events(self):
        import numpy
        from codetools.blocks.api import Block

        context = DataContext(name="data")
        context.on_trait_change(self.event_listener, 'items_modified')
        context.defer_events = True
        context['a'] = 4
        context['b'] = numpy.array((1,2,3))
        context.defer_events = False

        self.assertEqual(self.event_count, 1)

        multi_context = MultiContext(context, name="multi")
        multi_context.on_trait_change(self.event_listener, 'items_modified')

        block = Block("c = a * b")
        block.execute(multi_context)

        # we expect one event from data context, one from multi context
        self.assertEqual(self.event_count, 3)
    def get_context(self):
        """ Finalize the context
        """

        self.context = None
        if os.path.splitext(self.filename)[1] == '.pickle':
            self.context = DataContext.load_context_from_file(self.filename)

        elif self.model:
            if isinstance(self.model, FileLogReaderUI):
                reader = self.model.active_reader
                if reader:
                    log_info = reader.read_info(self.filename)
                    self.context = create_geo_context(
                        reader.read_data(self.filename, log_info),
                        log_info.well_name)
            else:
                self.context = self.model.read_data()

        return
Пример #10
0
def main():

    # Search boxes for finding functions to place on module.
    function_search = HandledFunctionSearch()

    ### Setup execution block ###############################################
    # Context setup.
    context = DataContext(name='Data')
    context['a'] = 1.0
    context.defer_events = False

    ### Setup the main application object ###################################
    # Reload from a file
    # Note: test case for block persistence, set the file_path to '' if
    # persistence need not be tested
    file_path = ''

    if not os.path.isfile(file_path):
        code = "from numpy import arange\n" \
               "b=3\n" \
               "c=4\n" \
               "x = arange(0,10,.1)\n" \
               "y = a*x**2 + b*x + c\n"

        bu = BlockUnit(code=code,
                      data_context=context)
    else:
        bu = BlockUnit(data_context=context)
        bu.load_block_from_file(file_path)

    def loop_interactor(interactor):
        import time
        import numpy
        time.sleep(1)

        for i in range(1,100):
            interactor.interactor_shadow.input_a = numpy.sin(i/10)
            time.sleep(0.1)

        print "done"
        import sys
        sys.exit(0)


    from blockcanvas.interactor.configurable_interactor import ConfigurableInteractor
    from blockcanvas.interactor.shadow_interactor import ShadowInteractor
    from blockcanvas.interactor.interactor_config import PlotConfig, InteractorConfig, VariableConfig
    from blockcanvas.plot.configurable_context_plot import ConfigurableContextPlot
    from blockcanvas.block_display.block_unit_variables import \
            BlockUnitVariableList
    from threading import Thread

    vars = BlockUnitVariableList(block = bu.codeblock.block,
                                 context = bu._exec_context)
    config = InteractorConfig(vars = vars.variables,
                              var_configs=[VariableConfig(name='a', type="Shadow")],
                              plot_configs=[PlotConfig(x='x', y='y')])
    interactor = ConfigurableInteractor(context = bu._exec_context,
                                        block = bu.codeblock.block,
                                        interactor_config = config)

#    Thread(target=loop_interactor, args=(interactor,)).start()
    interactor.edit_traits(kind='livemodal')
Пример #11
0
    def load_project_from_file(self, file_path):
        """ Load a project from .prj files.

            Parameters:
            -----------
            file_path: Str
                Complete file-path where the project is saved.

        """

        logger.debug('BlockUnit: Loading project from %s' %file_path)

        del self.block_unit
        self.block_unit = BlockUnit()

        if not os.path.exists(file_path):
            msg = 'BlockUnit: Loading of project at ' + \
                    file_path + ' failed: Path does not exist.'
            logger.error(msg)
            return

        self.project_file_path = file_path

        # Read the .prj file and retrieve information about where the script
        # and context are separately saved.
        file_object = open(file_path, 'rb')
        lines = file_object.readlines()
        lines_split = [line.split('=') for line in lines]
        lines_dict = {}
        for line in lines_split:
            key = line[0].strip().lower()
            if key != '':
                lines_dict[key] = line[1].strip()
        file_object.close()

        # Read the code and build the block
        s_path = 'script_path'
        if lines_dict.has_key(s_path) and os.path.exists(lines_dict[s_path]):
            self.load_block_from_file(lines_dict[s_path])
        else:
            msg = 'BlockUnit: Loading of script for project at ' + \
                    file_path + ' failed.'
            logger.error(msg)

        # Read the context file
        context, c_path = None, 'context_path'
        if lines_dict.has_key(c_path) and os.path.exists(lines_dict[c_path]):
            context = DataContext.load_context_from_file(lines_dict[c_path])

        # Read the layout file
        l_path = 'layout_path'
        if lines_dict.has_key(l_path) and os.path.exists(lines_dict[l_path]):
            self.block_unit.codeblock_ui.block_controller.layout_engine.load_layout(lines_dict[l_path])

        # Assign the context if any
        if context is not None:
            self.block_unit.data_context = context
        else:
            msg = 'BlockUnit: Loading of context for project at ' + \
                    file_path + ' failed.'
            logger.error(msg)

        # Interactor range files
        for key in INTERACTOR_LIST:
            if lines_dict.has_key(key):
                self.interactor_range_files[key] = lines_dict[key]

        # Loading saved contexts
        self.exec_context.saved_contexts = {}
        saved_context_keys = [key for key in lines_dict.keys() if
                              key.startswith(saved_context_prefix) ]
        if len(saved_context_keys):
            for key in saved_context_keys:
                final_key = key.replace(saved_context_prefix,'')
                self.exec_context.saved_contexts[final_key] = lines_dict[key]

        return