class ProxyText(ProxyShape): #: A reference to the shape declaration. declaration = ForwardTyped(lambda: Text) def set_text(self, text): raise NotImplementedError def set_font(self, font): raise NotImplementedError def set_size(self, size): raise NotImplementedError def set_style(self, style): raise NotImplementedError def set_composite(self, composite): raise NotImplementedError def set_vertical_alignment(self, alignment): raise NotImplementedError def set_horizontal_alignment(self, alignment): raise NotImplementedError
class ProxyShape(ProxyControl): #: A reference to the Shape declaration. declaration = ForwardTyped(lambda: Shape) def set_position(self, position): pass def set_direction(self, direction): pass def set_axis(self, axis): raise NotImplementedError def set_color(self, color): pass def set_transparency(self, alpha): pass def set_texture(self, texture): pass def get_bounding_box(self): raise NotImplementedError
class ProxyDataSet(ProxyToolkitObject): #: A reference to the data set declaration. declaration = ForwardTyped(lambda: DataSet) def set_data(self, data): raise NotImplementedError def update_data(self, change): raise NotImplementedError def set_colors(self, colors): raise NotImplementedError def set_text(self, text): raise NotImplementedError def set_text_color(self, color): raise NotImplementedError def set_icons(self, icons): raise NotImplementedError def set_show_icons(self, show): raise NotImplementedError
class ProxyAbstractButton(ProxyControl): """ The abstract definition of a proxy AbstractButton object. """ #: A reference to the AbstractButton declaration. declaration = ForwardTyped(lambda: AbstractButton) def set_text(self, text): raise NotImplementedError def set_icon(self, icon): raise NotImplementedError def set_icon_size(self, size): raise NotImplementedError def set_group(self, group): raise NotImplementedError def set_checkable(self, checkable): raise NotImplementedError def set_checked(self, checked): raise NotImplementedError
class ProxyMenu(ProxyToolkitObject): """ The abstract definition of a proxy Menu object. """ #: A reference to the Menu declaration. declaration = ForwardTyped(lambda: Menu) def set_title(self, title): raise NotImplementedError def set_enabled(self, enabled): raise NotImplementedError def set_visible(self, visible): raise NotImplementedError def set_context_menu(self, context): raise NotImplementedError def popup(self): raise NotImplementedError def close(self): raise NotImplementedError
class ProxyDialog(ProxyToolkitObject): """ The abstract definition of a proxy dialgo object. """ #: A reference to the Label declaration. declaration = ForwardTyped(lambda: Dialog) def set_title(self, title): raise NotImplementedError def set_cancel_on_back(self, cancels): raise NotImplementedError def set_cancel_on_touch_outside(self, cancels): raise NotImplementedError def set_key_events(self, enabled): raise NotImplementedError def set_show(self, show): raise NotImplementedError def set_style(self, style): raise NotImplementedError
class ProxyField(ProxyControl): """ The abstract definition of a proxy Field object. """ #: A reference to the Field declaration. declaration = ForwardTyped(lambda: Field) def set_text(self, text): raise NotImplementedError def set_mask(self, mask): raise NotImplementedError def set_submit_triggers(self, triggers): raise NotImplementedError def set_sync_time(self, time): raise NotImplementedError def set_placeholder(self, placeholder): raise NotImplementedError def set_echo_mode(self, mode): raise NotImplementedError def set_max_length(self, length): raise NotImplementedError def set_read_only(self, read_only): raise NotImplementedError def set_text_align(self, text_align): raise NotImplementedError def field_text(self): raise NotImplementedError
class ProxyToolkitDialog(ProxyToolkitObject): """ The abstract defintion of a proxy ToolkitDialog object. """ #: A reference to the ToolkitDialog declaration. declaration = ForwardTyped(lambda: ToolkitDialog) def set_title(self, title): raise NotImplementedError def show(self): raise NotImplementedError def open(self): raise NotImplementedError def exec_(self): raise NotImplementedError def accept(self): raise NotImplementedError def reject(self): raise NotImplementedError
class ProxyListView(ProxyViewGroup): """ The abstract definition of a proxy ListView object. """ #: A reference to the widget declaration. declaration = ForwardTyped(lambda: ListView) def set_items(self, items): raise NotImplementedError def set_divider_height(self, height): raise NotImplementedError def set_header_dividers(self, enabled): raise NotImplementedError def set_footer_dividers(self, enabled): raise NotImplementedError def set_items_can_focus(self, enabled): raise NotImplementedError def set_selected(self, index): raise NotImplementedError
class ProxyPicker(ProxyLinearLayout): """ The abstract definition of a proxy Picker object. """ #: A reference to the Label declaration. declaration = ForwardTyped(lambda: Picker) def set_max_value(self, value): raise NotImplementedError def set_min_value(self, value): raise NotImplementedError def set_value(self, value): raise NotImplementedError def set_long_press_update_interval(self, interval): raise NotImplementedError def set_wraps(self, wraps): raise NotImplementedError def set_items(self, items): raise NotImplementedError
class ProxyNotebook(ProxyConstraintsWidget): """ The abstract definition of a proxy Notebook object. """ #: A reference to the Notebook declaration. declaration = ForwardTyped(lambda: Notebook) def set_tab_style(self, style): raise NotImplementedError def set_tab_position(self, position): raise NotImplementedError def set_tabs_closable(self, closable): raise NotImplementedError def set_tabs_movable(self, movable): raise NotImplementedError def set_selected_tab(self, name): raise NotImplementedError def set_size_hint_mode(self, mode): raise NotImplementedError
class ProxyNodeGraphicsScene(ProxyGraphicsScene): """ The abstract definition of a proxy QtWidgets.QGraphicsScene object. """ #: A reference to the OpenGLWidget declaration. declaration = ForwardTyped(lambda: NodeGraphicsScene) def update(self, *args): raise NotImplementedError() def boundingRect(self): raise NotImplementedError() def set_width(self, width): raise NotImplementedError def set_height(self, height): raise NotImplementedError def set_show_background(self, show_background): raise NotImplementedError def set_background_grid_squares(self, background_grid_squares): raise NotImplementedError def set_background_grid_size(self, background_grid_size): raise NotImplementedError def set_background(self, background): raise NotImplementedError def set_color_light(self, color_light): raise NotImplementedError def set_color_dark(self, color_dark): raise NotImplementedError
class ProxyMapPolygon(ProxyToolkitObject): #: A reference to the declaration. declaration = ForwardTyped(lambda: MapPolygon) def set_points(self, points): raise NotImplementedError def update_points(self, change): raise NotImplementedError def set_clickable(self, clickable): raise NotImplementedError def set_holes(self, holes): raise NotImplementedError def set_fill_color(self, color): raise NotImplementedError def set_geodesic(self, geodesic): raise NotImplementedError def set_stroke_color(self, color): raise NotImplementedError def set_stroke_joint_type(self, joint_type): raise NotImplementedError def set_stroke_width(self, width): raise NotImplementedError def set_visible(self, visible): raise NotImplementedError def set_zindex(self, zindex): raise NotImplementedError
class ProxyEdgeItem(ProxyGraphicsItem): """ The abstract definition of a proxy edge-item object. """ #: A reference to the ComboBox declaration. declaration = ForwardTyped(lambda: EdgeItem) def set_name(self, name): raise NotImplementedError def set_edge_type(self, edge_type): raise NotImplementedError def set_line_width(self, line_width): raise NotImplementedError def set_edge_roundness(self, edge_roundness): raise NotImplementedError def set_color_default(self, color_default): raise NotImplementedError def set_color_selected(self, color_selected): raise NotImplementedError
class ProxyTreeViewItem(ProxyAbstractWidgetItem): declaration = ForwardTyped(lambda: TreeViewItem) def refresh_model(self, schange): raise NotImplementedError
class ProxyTreeViewColumn(ProxyAbstractWidgetItemGroup): declaration = ForwardTyped(lambda: TreeViewColumn) def set_column(self, column): raise NotImplementedError
class ProxyTreeView(ProxyAbstractItemView): declaration = ForwardTyped(lambda: TreeView)
class ProxyMainWindow(ProxyWindow): """ The abstract definition of a proxy MainWindow object. """ #: A reference to the MainWindow declaration. declaration = ForwardTyped(lambda: MainWindow)
class ProxyView(ProxyToolkitObject): """ The abstract definition of a proxy relative layout object. """ #: A reference to the Label declaration. declaration = ForwardTyped(lambda: View) def set_clickable(self, clickable): raise NotImplementedError def set_long_clickable(self, clickable): raise NotImplementedError def set_focusable(self, focusable): raise NotImplementedError def set_key_events(self, focusable): raise NotImplementedError def set_animations(self, animations): raise NotImplementedError def set_style(self, style): raise NotImplementedError def set_background_color(self, color): raise NotImplementedError def set_alpha(self, alpha): raise NotImplementedError def set_layout(self, layout): raise NotImplementedError def set_width(self, width): raise NotImplementedError def set_height(self, height): raise NotImplementedError def set_x(self, x): raise NotImplementedError def set_y(self, y): raise NotImplementedError def set_z(self, z): raise NotImplementedError def set_margin(self, margin): raise NotImplementedError def set_padding(self, padding): raise NotImplementedError def set_gravity(self, gravity): raise NotImplementedError def set_min_height(self, min_height): raise NotImplementedError def set_max_height(self, max_height): raise NotImplementedError def set_min_width(self, min_width): raise NotImplementedError def set_max_width(self, max_width): raise NotImplementedError def set_flex_grow(self, flex_grow): raise NotImplementedError def set_flex_basis(self, flex_basis): raise NotImplementedError def set_flex_shrink(self, flex_shrink): raise NotImplementedError def set_align_self(self, align_self): raise NotImplementedError
class BaseEngine(Atom): """Base class for all engines. """ #: Declaration defining this engine. declaration = ForwardTyped(lambda: Engine) #: Current status of the engine. status = Enum('Stopped', 'Waiting', 'Running', 'Pausing', 'Paused', 'Resuming', 'Stopping', 'Shutting down') #: Signal used to pass news about the measurement progress. progress = Signal() def perform(self, exec_infos): """Execute a given task and catch any error. Parameters ---------- exec_infos : ExecutionInfos TaskInfos object describing the work to expected of the engine. Returns ------- exec_infos : ExecutionInfos Input object whose values have been updated. This is simply a convenience. """ raise NotImplementedError() def pause(self): """Ask the engine to pause the execution. This method should not wait for the task to pause to return. When the pause is effective the engine should signal it by updating its status. """ raise NotImplementedError() def resume(self): """Ask the engine to resume the execution. This method should not wait for the measure to resume. When the pause is over the engine should signal it by updating its status. """ raise NotImplementedError() def stop(self, force=False): """Ask the engine to stop the execution. This method should not wait for the execution to stop save if a forced stop was requested. Parameters ---------- force : bool, optional Force the engine to stop the performing the task. This allow the engine to use any means necessary to stop, in this case only should the call to this method block. """ raise NotImplementedError() def shutdown(self, force=False): """Ask the engine to stop completely. After a call to this method the engine may need to re-initialize a number of things before running the next task. This method should not wait for the engine to shutdown save if a forced stop was requested. Parameters ---------- force : bool, optional Force the engine to stop the performing the task. This allow the engine to use any means necessary to stop, in this case only should the call to this method block. """ raise NotImplementedError()
class ProxyView(ProxyWidget): """ The abstract definition of a proxy relative layout object. """ #: A reference to the Label declaration. declaration = ForwardTyped(lambda: View) def set_alpha(self, alpha): raise NotImplementedError def set_clickable(self, clickable): raise NotImplementedError def set_background_color(self, color): raise NotImplementedError def set_layout_width(self, width): raise NotImplementedError def set_layout_height(self, height): raise NotImplementedError def set_layout_direction(self, direction): raise NotImplementedError def set_padding(self, padding): raise NotImplementedError def set_margins(self, margins): raise NotImplementedError def set_alpha(self, alpha): raise NotImplementedError def set_top(self, top): raise NotImplementedError def set_left(self, left): raise NotImplementedError def set_right(self, right): raise NotImplementedError def set_bottom(self, bottom): raise NotImplementedError def set_rotation(self, rotation): raise NotImplementedError def set_rotation_x(self, rotation): raise NotImplementedError def set_rotation_y(self, rotation): raise NotImplementedError def set_scale_x(self, scale): raise NotImplementedError def set_scale_y(self, scale): raise NotImplementedError def set_translation_x(self, translation): raise NotImplementedError def set_translation_y(self, translation): raise NotImplementedError def set_translation_z(self, translation): raise NotImplementedError def set_x(self, x): raise NotImplementedError def set_y(self, y): raise NotImplementedError def set_z(self, z): raise NotImplementedError def set_width(self, width): raise NotImplementedError def set_height(self, height): raise NotImplementedError def set_layout(self, layout): raise NotImplementedError
class ProxyViewSwitcher(ProxyViewAnimator): """ The abstract definition of a proxy ViewSwitcher object. """ #: A reference to the declaration. declaration = ForwardTyped(lambda: ViewSwitcher)
class ProxyRawNode(ProxyTag): #: Reference to the declaration declaration = ForwardTyped(lambda: Raw) def set_source(self, source): raise NotImplementedError
class BaseTask(Atom): """Base class defining common members of all Tasks. This class basically defines the minimal skeleton of a Task in term of members and methods. """ #: Identifier for the build dependency collector dep_type = Constant(DEP_TYPE).tag(pref=True) #: Name of the class, used for persistence. task_id = Unicode().tag(pref=True) #: Name of the task this should be unique in hierarchy. name = Unicode().tag(pref=True) #: Depth of the task in the hierarchy. this should not be manipulated #: directly by user code. depth = Int() #: Reference to the Section in which the task stores its preferences. preferences = Typed(Section) #: Reference to the database used by the task to exchange information. database = Typed(TaskDatabase) #: Entries the task declares in the database and the associated default #: values. This should be copied and re-assign when modified not modfied #: in place. database_entries = Dict(Unicode(), Value()) #: Path of the task in the hierarchy. This refers to the parent task and #: is used when writing in the database. path = Unicode() #: Reference to the root task in the hierarchy. root = ForwardTyped(lambda: RootTask) #: Refrence to the parent task. parent = ForwardTyped(lambda: BaseTask) #: Unbound method called when the task is asked to do its job. This is #: basically the perform method but wrapped with useful stuff such as #: interruption check or parallel, wait features. perform_ = Callable() #: Flag indicating if this task can be stopped. stoppable = Bool(True).tag(pref=True) #: Dictionary indicating whether the task is executed in parallel #: ('activated' key) and which is pool it belongs to ('pool' key). parallel = Dict(Unicode()).tag(pref=True) #: Dictionary indicating whether the task should wait on any pool before #: performing its job. Three valid keys can be used : #: - 'activated' : a bool indicating whether or not to wait. #: - 'wait' : the list should then specify which pool should be waited. #: - 'no_wait' : the list should specify which pool not to wait on. wait = Dict(Unicode()).tag(pref=True) #: Dict of access exception in the database. This should not be manipulated #: by user code. access_exs = Dict().tag(pref=True) def perform(self): """ Main method of the task called when the measurement is performed. """ raise NotImplementedError( fill( cleandoc('''This method should be implemented by subclasses of BaseTask. This method is called when the program requires the task to perform its job.'''))) def check(self, *args, **kwargs): """Check that everything is alright before starting a measurement. By default tries to format all members tagged with 'fmt' and try to eval all members tagged with 'feval'. """ res = True traceback = {} err_path = self.get_error_path() for n, m in tagged_members(self, 'fmt').items(): try: val = self.format_string(getattr(self, n)) if n in self.database_entries: self.write_in_database(n, val) except Exception: if m.metadata['fmt'] != 'Warn': res = False msg = 'Failed to format %s : %s' % (n, format_exc()) traceback[err_path + '-' + n] = msg for n, m in tagged_members(self, 'feval').items(): val = m.metadata['feval'] if not isinstance(val, validators.Feval): res = False msg = 'Feval validator is not a subclass validators.Feval' else: value, f_res, msg = val.check(self, n) res &= f_res if msg: traceback[err_path + '-' + n] = msg elif value is not None and n in self.database_entries: self.write_in_database(n, value) return res, traceback def prepare(self): """Prepare the task to be performed. This method is called once by the root task before starting the execution of its children tasks. By default it simply build the perform\_ method by wrapping perform with the appropriate decorators. This method can be overridden to execute other actions, however keep in my mind that those actions must not depende on the state of the system (no link to database). """ perform_func = self.perform.__func__ parallel = self.parallel if parallel.get('activated') and parallel.get('pool'): perform_func = make_parallel(perform_func, parallel['pool']) wait = self.wait if wait.get('activated'): perform_func = make_wait(perform_func, wait.get('wait'), wait.get('no_wait')) if self.stoppable: perform_func = make_stoppable(perform_func) self.perform_ = MethodType(perform_func, self) def register_preferences(self): """Create the task entries in the preferences object. """ raise NotImplementedError() def update_preferences_from_members(self): """Update the entries in the preference object. """ raise NotImplementedError() @classmethod def build_from_config(cls, config, dependencies): """Create a new instance using the provided infos for initialisation. Parameters ---------- config : dict(str) Dictionary holding the new values to give to the members in string format, or dictionnary like for instance with prefs. dependencies : dict Dictionary holding the necessary classes needed when rebuilding.. """ raise NotImplementedError() def traverse(self, depth=-1): """Yield a task and all of its components. The base implementation simply yields the task itself. Parameters ---------- depth : int How deep should we explore the tree of tasks. When this number reaches zero deeper children should not be explored but simply yielded. """ yield self def register_in_database(self): """ Register the task entries into the database. """ if self.database_entries: for entry in self.database_entries: # Perform a deepcopy of the entry value as I don't want to # alter that default value when dealing with the database later # on (apply for list and dict). value = deepcopy(self.database_entries[entry]) self.write_in_database(entry, value) for access_ex, level in self.access_exs.items(): self._add_access_exception(access_ex, level) def unregister_from_database(self): """ Remove the task entries from the database. """ if self.database_entries: for entry in self.database_entries: self.database.delete_value(self.path, self._task_entry(entry)) for access_ex, level in self.access_exs.items(): self._remove_access_exception(access_ex, level) def add_access_exception(self, entry, level): """Add an access exception for an entry. Parameters ---------- entry : unicode Name of the task database entry for which to add an exception. level : int Number of hierarchical levels to go up when adding the exception. """ self._add_access_exception(entry, level) access_exs = self.access_exs.copy() access_exs[entry] = level self.access_exs = access_exs def modify_access_exception(self, entry, new): """Modify the level of an existing access exception. Parameters ---------- entry : unicode Name of the task database entry for which to modify an exception. new : int New level for the access exception. If this is not strictly positive the access exception is simply removed. """ access_exs = self.access_exs.copy() old = access_exs[entry] if new > 0: access_exs[entry] = new else: del access_exs[entry] full_name = self._task_entry(entry) parent = self while old: parent = parent.parent old -= 1 self.database.remove_access_exception(parent.path, full_name) if new > 0: parent = self while new: parent = parent.parent new -= 1 self.database.add_access_exception(parent.path, self.path, full_name) self.access_exs = access_exs def remove_access_exception(self, entry): """Remove an access exception . Parameters ---------- entry : unicode Name of the task database entry for which to remove an exception. """ access_exs = self.access_exs.copy() level = access_exs.pop(entry) self.access_exs = access_exs self._remove_access_exception(entry, level) def write_in_database(self, name, value): """Write a value to the right database entry. This method build a task specific database entry from the name and the name argument and set the database entry to the specified value. Parameters ---------- name : str Simple name of the entry whose value should be set, ie no task name required. value: Value to give to the entry. """ value_name = self._task_entry(name) return self.database.set_value(self.path, value_name, value) def get_from_database(self, full_name): """Access to a database value using full name. Parameters ---------- full_name : str Full name of the database entry, ie name + '_' + entry, where name is the name of the task that wrote the value in the database. """ return self.database.get_value(self.path, full_name) def remove_from_database(self, full_name): """Delete a database entry using its full name. Parameters ---------- full_name : str Full name of the database entry, ie name + '_' + entry, where name is the name of the task that wrote the value in the database. """ return self.database.delete_value(self.path, full_name) def list_accessible_database_entries(self): """List the database entries accessible from this task. """ return self.database.list_accessible_entries(self.path) def format_string(self, string): """Replace values between {} by their corresponding database value. Parameters ---------- string : str The string to format using the current values of the database. Returns ------- formatted : str Formatted version of the input. """ # If a cache evaluation of the string already exists use it. if string in self._format_cache: preformatted, ids = self._format_cache[string] vals = self.database.get_values_by_index(ids, PREFIX) return preformatted.format(**vals) # Otherwise if we are in running mode build a cache formatting. elif self.database.running: database = self.database aux_strings = string.split('{') if len(aux_strings) > 1: elements = [el for aux in aux_strings for el in aux.split('}')] database_indexes = database.get_entries_indexes( self.path, elements[1::2]) str_to_format = '' length = len(elements) for i in range(0, length, 2): if i + 1 < length: repl = PREFIX + str(database_indexes[elements[i + 1]]) str_to_format += elements[i] + '{' + repl + '}' else: str_to_format += elements[i] indexes = database_indexes.values() self._format_cache[string] = (str_to_format, indexes) vals = self.database.get_values_by_index(indexes, PREFIX) return str_to_format.format(**vals) else: self._format_cache[string] = (string, []) return string # In edition mode simply perfom the formatting as execution time is not # critical. else: database = self.database aux_strings = string.split('{') if len(aux_strings) > 1: elements = [el for aux in aux_strings for el in aux.split('}')] replacement_values = [ database.get_value(self.path, key) for key in elements[1::2] ] str_to_format = '' for key in elements[::2]: str_to_format += key + '{}' str_to_format = str_to_format[:-2] return str_to_format.format(*replacement_values) else: return string def format_and_eval_string(self, string): """ Replace values in {} by their corresponding database value and eval Parameters ---------- string : str The string to eval using the current values of the database. Returns ------- value : object Evaluated version of the input. """ # If a cache evaluation of the string already exists use it. if string in self._eval_cache: preformatted, ids = self._eval_cache[string] vals = self.database.get_values_by_index(ids, PREFIX) return safe_eval(preformatted, vals) # Otherwise if we are in running mode build a cache evaluation. elif self.database.running: database = self.database aux_strings = string.split('{') if len(aux_strings) > 1: elements = [el for aux in aux_strings for el in aux.split('}')] database_indexes = database.get_entries_indexes( self.path, elements[1::2]) str_to_eval = '' length = len(elements) for i in range(0, length, 2): if i + 1 < length: repl = PREFIX + str(database_indexes[elements[i + 1]]) str_to_eval += elements[i] + repl else: str_to_eval += elements[i] indexes = database_indexes.values() self._eval_cache[string] = (str_to_eval, indexes) vals = self.database.get_values_by_index(indexes, PREFIX) return safe_eval(str_to_eval, vals) else: self._eval_cache[string] = (string, []) return safe_eval(string, {}) # In edition mode simply perfom the evaluation as execution time is not # critical and as the database has not been collapsed to an indexed # representation. else: database = self.database aux_strings = string.split('{') if len(aux_strings) > 1: elements = [el for aux in aux_strings for el in aux.split('}')] replacement_token = [ PREFIX + str(i) for i in range(len(elements[1::2])) ] repl = { PREFIX + str(i): database.get_value(self.path, key) for i, key in enumerate(elements[1::2]) } str_to_format = '' for key in elements[::2]: str_to_format += key + '{}' str_to_format = str_to_format[:-2] expr = str_to_format.format(*replacement_token) return safe_eval(expr, repl) else: return safe_eval(string, {}) def get_error_path(self): """Build the path to use when reporting errors during checks. """ return self.path + '/' + self.name # ========================================================================= # --- Private API --------------------------------------------------------- # ========================================================================= #: Dictionary storing infos necessary to perform fast formatting. #: Only used in running mode. _format_cache = Dict() #: Dictionary storing infos necessary to perform fast evaluation. #: Only used in running mode. _eval_cache = Dict() def _default_task_id(self): """Default value for the task_id member. """ pack, _ = self.__module__.split('.', 1) return pack + '.' + type(self).__name__ def _post_setattr_database_entries(self, old, new): """Update the database content each time the database entries change. """ if self.database: new = set(new) old = set(old) if old else set() added = new - old removed = old - new for entry in removed: full_name = self._task_entry(entry) self.remove_from_database(full_name) for entry in added: new_value = deepcopy(self.database_entries[entry]) self.write_in_database(entry, new_value) for r in [r for r in removed if r in self.access_exs]: self.remove_access_exception(r) def _post_setattr_name(self, old, new): """Update the database entries as they use the task name. """ if not old or not self.database: return olds = [old + '_' + e for e in self.database_entries] news = [new + '_' + e for e in self.database_entries] old_access = { old + '_' + k: v for k, v in self.access_exs.items() if old + '_' + k in olds } self.database.rename_values(self.path, olds, news, old_access) def _add_access_exception(self, entry, level): """Add an access exception without modifying the access_exs member. """ parent = self while level: parent = parent.parent level -= 1 self.database.add_access_exception(parent.path, self.path, self._task_entry(entry)) def _remove_access_exception(self, entry, level): """Remove the access without modifying the access_exs member. """ parent = self while level: parent = parent.parent level -= 1 full_name = self._task_entry(entry) self.database.remove_access_exception(parent.path, full_name) def _task_entry(self, entry): """Build the full name of an entry for a task. """ return self.name + '_' + entry
class XYFormat(Atom): rend_list=List(default=[None, None, None]) #First is line, second is scatter #Typed(BaseXYPlot) name=Unicode() xname=Unicode() yname=Unicode() zname=Unicode() colormap=Enum("jet") line_color=Enum(*mycolors) #'blue', 'red', 'green', 'purple', 'black', 'darkgray', 'cyan', 'magenta', 'orange') plot_type=Enum('line', 'scatter', 'line+scatter') line_width=Float(1.0) marker = Enum('square', 'circle', 'triangle', 'inverted_triangle', 'plus', 'cross', 'diamond', 'dot', 'pixel') marker_size = Float(3.0) outline_color=Enum(*mycolors) outline_width=Float(1.0) inside_color=Enum(*mycolors) line_style=Enum('solid', 'dot dash', 'dash', 'dot', 'long dash') render_style=Enum('connectedpoints', 'hold', 'connectedhold') plotter=ForwardTyped(lambda: Plotter) def _default_name(self): return self.yname def set_param(self, param, change, index=-1): if change['type']!='create': # if self.rend_list[index]!=None: setattr(self.rend_list[index], param, change['value']) #print self.rend_list def set_line_param(self, param, change): self.set_param(param, change, index=0) def set_scatter_param(self, param, change): self.set_param(param, change, index=1) def _observe_line_color(self, change): self.set_line_param('color', change) def _observe_marker_size(self, change): self.set_scatter_param('marker_size', change) def _observe_marker(self, change): self.set_scatter_param('marker', change) def _observe_line_width(self, change): self.set_line_param('line_width', change) def _observe_outline_width(self, change): self.set_scatter_param('line_width', change) def _observe_outline_color(self, change): self.set_scatter_param('outline_color', change) def _observe_inside_color(self, change): self.set_scatter_param('color', change) def _observe_line_style(self, change): self.set_line_param('line_style', change) def redraw_plot(self): self.draw_plot(name=self.name, zname=self.zname, xname=self.xname) def draw_img_plot(self, name, zname, xname=None, yname=None): self.plotter.delete_all_plots() self.name=name self.zname=zname #self.plotter.pd.set_data(zname, z) img_plot = self.plotter.plot.img_plot(self.zname, name="img_plot", colormap=self.colormap)[0] # z_shape=shape(self.plotter.pd.get_data(self.zname)) #xdata=img_plot.index.get_data()[0].get_data() #ydata=img_plot.index.get_data()[1].get_data() if xname!=None: xdata=self.plotter.get_data(xname) else: xdata=img_plot.index.get_data()[0].get_data() if yname!=None: ydata=self.plotter.get_data(yname) else: ydata=img_plot.index.get_data()[1].get_data() img_plot.index.set_data(xdata,ydata) img_plot.request_redraw() self.rend_list[2]=img_plot def draw_plot(self, name, zname, zdata=None, xname='', xdata=None): if "img_plot" in self.plotter.plot.plots.keys(): self.plotter.delete_all_plots() if "{0}_line".format(name) in self.plotter.plot.plots.keys(): self.plotter.plot.delplot("{0}_line".format(name)) if "{0}_scatter".format(name) in self.plotter.plot.plots.keys(): self.plotter.plot.delplot("{0}_scatter".format(name)) #if xname==None: # xname="{0}_x0".format(zname) # self.plotter.pd.set_data(xname, arange(len(self.plotter.pd.arrays[zname]))) self.xname=xname self.zname=zname self.name=name if self.plot_type=='line': self.draw_line_plot() elif self.plot_type=='scatter': self.draw_scatter_plot() elif self.plot_type=='line+scatter': self.draw_line_plot() self.draw_scatter_plot() # if data.x_unit: # x_label = "{} [{}]".format(data.x_label, data.x_unit) # else: # x_label = data.x_label # if data.y_unit: # y_label = "{} [{}]".format(data.y_label, data.y_unit) # else: # y_label = data.y_label # plot.x_axis.title = x_label # plot.y_axis.title = y_label # plot.x_axis.tick_label_formatter = lambda x: '%.e'%x # plot.y_axis.tick_label_formatter = lambda x: '%.e'%x def draw_line_plot(self): renderer=self.plotter.plot.plot( self.zname , name="{0}_line".format(self.name), type="line", line_width=self.line_width, color=self.line_color, render_style=self.render_style, value_scale=self.plotter.value_scale, index_scale=self.plotter.index_scale )[0] xdata=self.plotter.get_data(self.xname) if xdata!=None: renderer.index.set_data(xdata) renderer.request_redraw() self.rend_list[0]=renderer def draw_scatter_plot(self): renderer=self.plotter.plot.plot(self.zname, name="{0}_scatter".format(self.name), #self.zname, type="scatter", #self.xyformat.plot_type, line_width=self.line_width, color=self.inside_color, outline_color=self.outline_color, marker = self.marker, marker_size = self.marker_size, value_scale=self.plotter.value_scale, index_scale=self.plotter.index_scale )[0] xdata=self.plotter.get_data(self.xname) if xdata!=None: renderer.index.set_data(xdata) renderer.request_redraw() self.rend_list[1]=renderer
class ProxyStackItem(ProxyWidget): """ The abstract definition of a proxy StackItem object. """ #: A reference to the StackItem declaration. declaration = ForwardTyped(lambda: StackItem)
class DeclarativeNode(CompilerNode): """ A compiler node which represents a declarative declaration. Instances of this class are generated by the compiler and contain the information needed to create an instance of the hierarchy at runtime. """ #: The declarative type object to instantiate. klass = Typed(type) #: The local identifier to associate with the instance. identifier = Str() #: Whether or not the node should store the locals in the map. store_locals = Bool(False) #: Whether or not the instance intercepts the child nodes. child_intercept = Bool(False) #: The expression engine to associate with the instance. engine = Typed(ExpressionEngine) #: The set of scope keys for the closure scopes. This will be None #: if the node does not require any closure scopes. closure_keys = Typed(set) #: The superclass nodes of this node. This will be None if the #: node represents a raw declarative object vs an enamldef. super_node = ForwardTyped(lambda: EnamlDefNode) def __call__(self, parent): """ Instantiate the type hierarchy. This is invoked by a parent compiler node when the declarative hierarchy is being instantiated. Parameters ---------- parent : Declarative or None The parent declarative object for the hierarchy. Returns ------- result : Declarative The declarative instance created by the node. """ klass = self.klass instance = klass.__new__(klass) self.populate(instance) instance.__init__(parent) return instance def populate(self, instance): """ Populate an instance generated for the node. Parameters ---------- instance : Declarative The declarative instance for this node. """ if self.super_node is not None: self.super_node(instance) f_locals = peek_scope() scope_key = self.scope_key if self.identifier: f_locals[self.identifier] = instance if self.store_locals: instance._d_storage[scope_key] = f_locals if self.engine is not None: instance._d_engine = self.engine if self.closure_keys is not None: for key in self.closure_keys: instance._d_storage[key] = fetch_scope(key) if self.child_intercept: children_copy = self.children[:] instance.child_node_intercept(children_copy, scope_key, f_locals) else: for node in self.children: node(instance) def size(self): """ Return the size of the instantiated node. """ return 1 def update_id_nodes(self, mapping): """ Update the id nodes for this node. Parameters ---------- mapping : sortedmap The mapping to fill with the identifier information. """ if self.identifier: mapping[self.identifier] = self super(DeclarativeNode, self).update_id_nodes(mapping) def copy(self): """ Create a copy of this portion of the node hierarchy. Returns ------- result : DeclarativeNode A copy of the node hierarchy from this node down. """ node = super(DeclarativeNode, self).copy() node.klass = self.klass node.identifier = self.identifier node.store_locals = self.store_locals node.child_intercept = self.child_intercept if self.engine is not None: node.engine = self.engine.copy() if self.super_node is not None: node.super_node = self.super_node.copy() if self.closure_keys is not None: node.closure_keys = self.closure_keys.copy() return node
class ProxyTableViewRow(ProxyAbstractWidgetItemGroup): declaration = ForwardTyped(lambda: TableViewRow) def set_row(self, row): raise NotImplementedError
class Plotter(Atom): name=Unicode() title=Unicode("yoyoyoyoyo") xlabel=Unicode() ylabel=Unicode() xyfs=Dict() #pd=Typed(ArrayPlotData, ()) plot= ForwardTyped(lambda: Plot) color_index=Int() clts=Dict() fig=Typed(Figure) axe=Typed(Axes) #clt=Typed(PolyCollection) plottables=Dict() overall_plot_type=Enum("XY", "img", "polygon") value_scale=Enum('linear', 'log') index_scale=Enum('linear', 'log') #def _default_clt(self): # return PolyCollection([((0,0), (0,0))], alpha=0.6, antialiased=True)#, rasterized=False, antialiased=False) def _default_axe(self): axe=self.fig.add_subplot(111) axe.autoscale_view(True) return axe def _default_fig(self): return Figure() def _observe_value_scale(self, change): if self.overall_plot_type=="XY plot": self.plot.value_scale=self.value_scale self.plot.request_redraw() def _observe_index_scale(self, change): if self.overall_plot_type=="XY plot": self.plot.index_scale=self.index_scale self.plot.request_redraw() def _default_plottables(self): return dict(plotted=[None]) def _observe_title(self, change): self.axe.set_title(self.title) #self.plot.request_redraw() def _observe_xlabel(self, change): self.axe.set_xlabel(self.xlabel) #self.plot.x_axis.title=self.xlabel #self.plot.request_redraw() def _observe_ylabel(self, change): self.axe.set_ylabel(self.ylabel) # self.plot.request_redraw() def _default_xyfs(self): xyf=AllXYFormat(plotter=self) return {"All":xyf} def delete_all_plots(self): for key in self.plot.plots.keys(): self.plot.delplot(key) self.color_index=0 def _save(self): global PlotGraphicsContext if PlotGraphicsContext==None: from chaco.plot_graphics_context import PlotGraphicsContext win_size = self.plot.outer_bounds plot_gc = PlotGraphicsContext(win_size)#, dpi=300) plot_gc.render_component(self.plot) plot_gc.save("image_test.png") def set_data(self, zname, zdata, zcolor): if zdata!=None: if self.overall_plot_type=="polygon": if zname not in self.clts: #plottables['plotted']:#self.pd.list_data(): clt=PolyCollection(zdata, alpha=0.5, antialiased=True)#, rasterized=False, antialiased=False) clt.set_color(colorConverter.to_rgba(zcolor)) self.clts[zname]=clt self.axe.add_collection(self.clts[zname], autolim=True) else: self.clts[zname].set_verts(zdata) if self.overall_plot_type=="XY": if zname not in self.clts: clt = LineCollection(zdata)#, offsets=offs) clt.set_color(colors) #print dir(clt) self.clts[zname]=clt self.axe.add_collection(self.clts[zname], autolim=True) self.axe.autoscale_view() else: self.clts[zname].set_segments(zdata) if self.overall_plot_type=="img": if zname not in self.clts: axeimg=self.axe.imshow( Magvec, vmin=amin(Magvec), vmax=0.001, #amax(Magvec), aspect="auto", origin="lower", extent=[amin(yoko),amax(yoko), amin(freq),amax(freq)], #cmap='RdBu' ) self.fig.colorbar(axeimg) def draw(self): if self.fig.canvas!=None: #trans = transforms.Affine2D().scale(self.fig.dpi/72.0) #self.clt.set_transform(trans) # the points to pixels transform #self.clt.set_color(colors) #self.axe.autoscale_view(True) self.fig.canvas.draw() def set_xlim(self, xmin, xmax): self.axe.set_xlim(xmin, xmax) def set_ylim(self, ymin, ymax): self.axe.set_ylim(ymin, ymax) def get_data(self, zname, index=None, axis=0): data=[c.to_polygons() for c in self.clt.get_paths()] if index==None: return data if axis==0: return atleast_2d(data)[index, :] return atleast_2d(data)[:, index] def add_poly_plot_old(self, n, verts, cn="green", polyname=""): nxarray, nyarray = transpose(verts) xname=polyname+"x" + str(n) yname=polyname+"y" + str(n) self.pd.set_data(xname, nxarray, coord='x') #coord='x' is likely redundant or a metadata tag self.pd.set_data(yname, nyarray, coord='y') self.plot.plot((xname, yname), type="polygon", face_color=cn, #colors[nsides], hittest_type="poly")[0] def add_poly_plot(self, n, verts, cn="green", polyname=""): #for n,p in enumerate(self.polylist): log_debug("drawing polygon #: {0}".format(n)) #npoints = p.verts #n_gon(center=p, r=2, nsides=nsides) nxarray, nyarray = transpose(verts) self.pd.set_data("x" + str(n), nxarray) self.pd.set_data("y" + str(n), nyarray) log_debug("data set") self.plot.plot(("x"+str(n), "y"+str(n)), type="polygon", face_color=cn, #colors[nsides], hittest_type="poly" )[0] log_debug("plot occured") def add_img_plot(self, zname, zdata, xname=None, xdata=None, yname=None, ydata=None): self.add_data(zname=zname, zdata=zdata, xname=xname, xdata=xdata, yname=yname, ydata=ydata, overwrite=True, concat=False) print self.pd.get_data(zname) xyf=XYFormat(plotter=self) xyf.draw_img_plot(name='img_plot', zname=zname, xname=xname, yname=yname) self.xyfs.update(**{xyf.name: xyf}) self.overall_plot_type="img plot" def add_line_plot(self, name, zname, zdata, xname='', xdata=None): #self.add_data(zname=zname, zdata=zdata, xname=xname, xdata=xdata, overwrite=True) self.set_data(zname, zdata) self.set_data(xname, xdata) xyf=XYFormat(plotter=self) zdata=self.get_data(zname) #if 1: #zdata.ndim>1: # for i, arr in enumerate(self.splitMultiD(zdata, 0)): # self.add_line_plot(name+str(i), zname+str(i), squeeze(arr), xname, xdata ) #else: #self.set_data(zname, zdata) #if xname!=None and xdata!=None: # self.set_data(xname, xdata, coord='x') xyf.draw_plot(name=name, zname=zname, xname=xname) self.xyfs.update(**{xyf.name: xyf}) self.overall_plot_type="XY plot" # def append_data(self, name, zpoint, xpoint=None): # xyf=self.xyfs[name] # zdata=self.pd.get_data(xyf.zname) # zdata=append(zdata, zpoint) # self.pd.set_data(xyf.zname, zdata) # xdata=self.pd.get_data(xyf.xname) # if xpoint==None: # xpoint=max(xdata)+range(len(zpoint))+1 # xdata=append(xdata, xpoint) # self.pd.set_data(xyf.xname, xdata) # def _default_plot(self): # global Plot, PanTool, ZoomTool, LegendTool # if Plot==None: # from chaco.plot import Plot # if PanTool==None or ZoomTool==None or LegendTool==None: # from chaco.tools.api import PanTool, ZoomTool, LegendTool #, LineInspector # # plot=Plot(self.pd, padding=50, fill_padding=True, # bgcolor="white", use_backbuffer=True, unified_draw=True)#, use_downsampling=True) # plot.tools.append(PanTool(plot, constrain_key="shift")) # plot.overlays.append(ZoomTool(component=plot, tool_mode="box", always_on=False)) # plot.legend.tools.append(LegendTool(plot.legend, drag_button="right")) # return plot def splitMultiD(self, arr, axis=0): if arr.ndim<2: return atleast_2d(arr) else: return split(arr, arr.shape[axis], axis=axis) def gatherMultiD(self, name, arrs, appen=None, concat=True, overwrite=False): if not isinstance(arrs, tuple): arrs=(arrs,) if appen==None: if shape(arrs)==(1,): appen=True else: appen=False orig=self.get_data(name) if orig!=None and not overwrite: arrs=(orig,)+arrs if appen: axis=1 else: axis=0 print arrs[0]==atleast_2d(*arrs) #if ndim(arrs[0])>1: # concat=False if concat: data=concatenate(atleast_2d(*arrs), axis) self.set_data(name, data) def add_data(self, zname, zdata, xname=None, xdata=None, yname=None, ydata=None, appen=None, concat=True, overwrite=False): if xname!=None: self.gatherMultiD(xname, xdata, appen=appen, overwrite=overwrite, concat=concat) if yname!=None: self.gatherMultiD(yname, ydata, appen=appen, overwrite=overwrite, concat=concat) self.gatherMultiD(zname, zdata, appen=appen, overwrite=overwrite, concat=concat) def show(self): with imports(): from e_Plotter import PlotMain app = QtApplication() view = PlotMain(plotr=self) view.show() app.start()
class ProxyTableViewItem(ProxyAbstractWidgetItem): declaration = ForwardTyped(lambda: TableViewItem) def data_changed(self, change): raise NotImplementedError