class PhysicalQuadratureChannel(PhysicalChannel): ''' Something used to implement a standard qubit channel with two analog channels and a microwave gating channel. ''' IChannel = Str() QChannel = Str() #During initilization we may just have a string reference to the channel gateChan = Either(Str, Instance(PhysicalMarkerChannel)) ampFactor = Float(1.0) phaseSkew = Float(0.0) SSBFreq = Float(0.0) correctionT = Property(depends_on=['ampFactor', 'phaseSkew']) @cached_property def _get_correctionT(self): return np.array([[self.ampFactor, self.ampFactor*tan(self.phaseSkew*pi/180)], [0, 1/cos(self.phaseSkew*pi/180)]])
class ProjectFileSelector(HasStrictTraits): path_list = List(Str) selected = Either(Str, List(Str)) view = KromView( Item("path_list", show_label=False, editor=ListStrEditor(title='Project(s) to load', selected="selected", editable=False, multi_select=True)), title="Select the project(s) to load", buttons=OKCancelButtons, width=500 ) def _selected_default(self): return []
class CProfileTableView(ModelView): title = Str data_items = Property(depends_on='model.data_items,sort_column,ascending') adapter = Any column_clicked = Event sort_column = Either(None, Int) ascending = Bool(False) def _column_clicked_changed(self, event): if event is None: self.sort_column = None elif self.sort_column == event.column: self.ascending = not self.ascending else: self.sort_column = event.column self.ascending = False def _adapter_default(self): return CProfileTabularAdapter() @cached_property def _get_data_items(self): items = [TableItem(*args) for args in self.model.data_items] if self.sort_column is None: return items attr = self.adapter.columns[self.sort_column][1] return sorted(items, key=attrgetter(attr), reverse=self.ascending) def default_traits_view(self): return View( UItem( 'data_items', editor=TabularEditor( adapter=self.adapter, column_clicked='column_clicked', ), ), height=800, width=1100, resizable=True, title='CProfile Live', )
class CSVCell(HasTraits): txt = Any fmt = Either(Str, Callable) def render(self): txt = self.txt if txt is None: return '' fmt = self.fmt if fmt is None: fmt = str if isinstance(fmt, str): return fmt.format(txt) else: return fmt(txt)
class BaseItem(HasTraits): value = Any fmt = Either(Str, Callable) fontsize = Int(10) fontname = Str#'Helvetica' italic = False def __init__(self, value=None, *args, **kw): self.value = value super(BaseItem, self).__init__(*args, **kw) def render(self): v = self.value if not isinstance(v, Paragraph): fmt = self.fmt if fmt is None: fmt = u'{}' if isinstance(fmt, (str, six.text_type)): v = fmt.format(v) else: v = fmt(v) v = self._set_font(v, self.fontsize, self.fontname) return v def _set_font(self, v, size, name): if isinstance(v, Paragraph): for frag in v.frags: if (hasattr(frag, 'super') and frag.super) or (hasattr(frag, 'sub') and frag.sub): frag.fontSize = size - 2 else: frag.fontSize = size elif name: v = self._new_paragraph(u'<font size="{}" name="{}">{}</font>'.format(size, name, v)) else: v = self._new_paragraph(u'<font size="{}">{}</font>'.format(size, v)) return v def _new_paragraph(self, t, s='Normal'): style = STYLES[s] p = Paragraph(t, style) return p
class Splitter(LayoutContainer): """ A split area in a Task layout. """ #: The orientation of the splitter. orientation = Enum("horizontal", "vertical") #: The sub-items of the splitter, which are PaneItems, Tabbed layouts, and #: other Splitters. items = List( Either( Instance(PaneItem), Instance(Tabbed), Instance("pyface.tasks.task_layout.Splitter"), ), pretty_skip=True, )
class EventDescription(HasPrivateTraits): #x,y coordinate used to identify map locations on actions 1, 2, 3 #used in SPEC_IVIT, SPEC_FIRAK, SPEC_AMBA, SPEC_BON4, SPEC_BON5 coordinates = Either(None, Tuple) #used to identify placement of lost planet lost_planet_coords = Tuple #used to identify upgrade path in ACT3 upgrade = Enum(None, 'planetary institute', 'research lab', 'action academy', 'knowledge academy') #list of x,y map coordinates used to identify satellites in ACT4 feds_satellites = List(Tuple) #index of tech track to move up ACT5 or SPEC_BESCOD tech_track = Enum(None, 'terraforming', 'navigation', 'AI', 'gaiaforming', 'economy', 'science') #index of power action choice for ACT6 power_action = Instance(Interaction) #the special action chosen for ACT7 special_action = Instance(Interaction) #the bonus tile selected for ACT8 bonus_tile = Instance(BonusTile) #the federation token picked in ACT5 or ACT6:QA2 federation_choice = Instance(FederationTile) #the technology tile picked in ACT3:RL, ACT3:AC, or ACT6:QA1 or ITAR:SPEC tech_tile_choice = Instance(TechTile) #the technology tile to replace with an advanced tech tile pick #in ACT3:RL, ACT3:AC or ACT6:QA1 or ITAR:SPEC tech_replace_choice = Instance(TechTile) #which power tokens to utilize in ACT2, ACT4, SPEC_BON5 which_power_tokens_choice = Dict(Str, Int) bonus_declined = Bool cancel_choice = Bool
class Text3D(ModuleFactory): """ Positions text at a 3D location in the scene. **Function signature**:: text3d(x, y, z, text, ...) x, y, and z are the position of the origin of the text. The text is positioned in 3D, in figure coordinates. """ _target = Instance(modules.Text3D, ()) scale = Either(CFloat(1), CArray(shape=(3, )), help="""The scale of the text, in figure units. Either a float, or 3-tuple of floats.""") orientation = CArray(shape=(3, ), adapts='orientation', desc="""the angles giving the orientation of the text. If the text is oriented to the camera, these angles are referenced to the axis of the camera. If not, these angles are referenced to the z axis.""") orient_to_camera = Bool(True, adapts='orient_to_camera', desc="""if the text is kept oriented to the camera, or is pointing in a specific direction, regardless of the camera position.""") def __init__(self, x, y, z, text, **kwargs): """ Override init as for different positional arguments.""" if not 'scale' in kwargs: kwargs['scale'] = 1 super(Text3D, self).__init__(None, **kwargs) self._target.text = text self._target.position = (x, y, z) def _scale_changed(self): scale = self.scale if isinstance(scale, numbers.Number): scale = scale * np.ones((3, )) self._target.scale = scale
class Interaction(HasPrivateTraits): action_id = Either(Str, None) desc = Property def _get_desc(self): return '' def __eq__(self, other): if not type(self) == type(other): return False return self.action_id == other.action_id def __hash__(self): return hash(self.action_id) def __init__(self, action_id=None, *args, **kwargs): super().__init__(*args, **kwargs)
class ODESolver(HasTraits): ode = Instance(ODE) initial_state = Either(Float, Array) t = Array solution = Property(Array, depends_on='initial_state, t, ode') @cached_property def _get_solution(self): return self.solve() def solve(self): """ Solve the ODE and return the values of the solution vector at specified times t. """ from scipy.integrate import odeint return odeint(self.ode.eval, self.initial_state, self.t)
class TaskWindowLayout(LayoutContainer): """ The layout of a TaskWindow. """ #: The ID of the active task. If unspecified, the first task will be #: active. active_task = Str() #: The tasks contained in the window. If an ID is specified, the task will #: use its default layout. Otherwise, it will use the specified TaskLayout items = List(Either(Str, Instance(TaskLayout)), pretty_skip=True) #: The position of the window. position = Tuple(-1, -1) #: The size of the window. size = Tuple(800, 600) #: Whether or not the application is maximized. size_state = Enum("normal", "maximized") def get_active_task(self): """ Returns the ID of the active task in the layout, or None if there is no active task. """ if self.active_task: return self.active_task elif self.items: first = self.items[0] return first if isinstance(first, str) else first.id return None def get_tasks(self): """ Returns the IDs of the tasks in the layout. """ return [(item if isinstance(item, str) else item.id) for item in self.items] def is_equivalent_to(self, layout): """ Returns whether two layouts are equivalent, i.e. whether they contain the same tasks. """ return isinstance(layout, TaskWindowLayout) and set( self.get_tasks()) == set(layout.get_tasks())
class MemoryModel(BaseModel): data_items = List selected_index = Either(None, Int) selected_item = Property(depends_on='selected_index') def _TRANSFORMS_default(self): return { 'RSS': 1. / (1024**2), 'VMS': 1. / (1024**2), } def _UNITS_default(self): return { 'RSS': 'MB', 'VMS': 'MB', } def _get_selected_item(self): if self.selected_index is not None: values = self.data_items[self.selected_index] return [Details(f, v) for f, v in zip(self.fields, values)] return [] def _add_data_item(self, name, values): exitsing = self.plot_data.get_data(name) if name in self.TRANSFORMS: values = np.array(values) * self.TRANSFORMS[name] if exitsing is None: new = values else: new = np.hstack([exitsing, values]) self.plot_data.set_data(name, new) def add_data(self, records): self.data_items.extend(records) if self.plottable_item_indices is None: self._calculate_plottable_item_indices(records[0]) data = zip(*records) for index in self.plottable_item_indices: self._add_data_item(self.fields[index], data[index]) self._update_index() self._update_value() self.updated = True
class HelpDocPreferencesPage(PreferencesPage): """ Base class for preferences pages for help documents. """ #### 'PreferencesPage' interface ########################################## # The page's category. category = 'Documents' # The page's help identifier (optional). help_id = '' # The page name (this is what is shown in the preferences dialog. name = Str def _name_default(self): return self.label # The path to the preferences node that contains the preferences. preferences_path = Str #### Preferences ########################################################### # The UI label for the help doc, which appears in menus or dialogs. label = Str # The full path to the document on disk. filename = File # The program to use to view the document. 'browser' means the platform # default web browser. viewer = Either('browser', File) traits_view = View( Group( Item('viewer', show_label=True), Label("Viewer can be 'browser' or a path to a program."), show_border=True, ), Item('filename', show_label=True), Label( "Filename can be absolute, or relative to the Python directory."), )
class NormalRateSimulator(RateSimulator): """正态分布收益率模拟器""" RateMean = Float(0.05, visible_to_user=True, label="平均收益率") RateSigma = Float(0.3, visible_to_user=True, label="平均波动率") HistoryRate = Instance(np.ndarray, visible_to_user=True, label="历史收益率") NoP = Range(low=1, high=9999, value=252, visible_to_user=True, label="输出期数") DropIllegal = Bool(True, visible_to_user=True, label="舍弃非法值") NPeriod = Int(10, visible_to_user=True, label="模拟期数") NSample = Int(100, visible_to_user=True, label="模拟样本数") Seed = Either(None, Int(0), visible_to_user=True, label="随机数种子") def simulate(self): if self.HistoryRate is not None: RateMean = np.nanprod(1 + self.HistoryRate)**( self.NoP / self.HistoryRate.shape[0]) - 1 # 收益率的历史均值 RateSigma = np.nanstd(self.HistoryRate, ddof=1) * self.NoP**0.5 # 收益率的历史波动率 else: RateMean = self.RateMean RateSigma = self.RateSigma np.random.seed(self.Seed) Rate = np.random.normal(loc=RateMean, scale=RateSigma, size=(self.NPeriod, self.NSample)) if not self.DropIllegal: return Rate Mask = (Rate <= -1) nIllegal = np.sum(Mask) while nIllegal > 0: self._Logger.debug("There are %d illegal samples, try again!" % (nIllegal, )) Rate[Mask] = np.random.normal(loc=RateMean, scale=RateSigma, size=(nIllegal, )) Mask = (Rate <= 1) nIllegal = np.sum(Mask) np.random.seed(None) return Rate
def CVType(type, **metadata): """ Factory that creates an Either type or ContextValue trait. This also sets up one-way synchronization to the editor if no other synchronization is specified. Parameters ---------- type : trait type The trait type that is expected for constant values. **metadata Additional metadata for the trait. Returns ------- cv_type_trait : trait A trait which can either hold a constant of the specified type or an instance of the ContextValue class. """ metadata.setdefault('sync_value', 'to') return Either(type, InstanceOfContextValue, **metadata)
class TaskWindowLayout(LayoutContainer): """ The layout of a TaskWindow. """ # The ID of the active task. If unspecified, the first task will be active. active_task = Str # The tasks contained in the window. If an ID is specified, the task will # use its default layout. Otherwise, it will use the specified TaskLayout. items = List(Either(Str, TaskLayout), pretty_skip=True) # The position of the window. position = Tuple(-1, -1) # The size of the window. size = Tuple(800, 600) def get_active_task(self): """ Returns the ID of the active task in the layout, or None if there is no active task. """ if self.active_task: return self.active_task elif self.items: first = self.items[0] return first if isinstance(first, basestring) else first.id return None def get_tasks(self): """ Returns the IDs of the tasks in the layout. """ return [(item if isinstance(item, basestring) else item.id) for item in self.items] def is_equivalent_to(self, layout): """ Returns whether two layouts are equivalent, i.e. whether they contain the same tasks. """ return isinstance(layout, TaskWindowLayout) and \ set(self.get_tasks()) == set(layout.get_tasks())
class BaseItem(HasTraits): value = Any fmt = Either(Str, Callable) fontsize = Int(8) fontname = 'Helvetica' italic = False def render(self): v = self.value if not isinstance(v, Paragraph): fmt = self.fmt if fmt is None: fmt = u'{}' if isinstance(fmt, (str, unicode)): v = fmt.format(v) else: v = fmt(v) v = self._set_font(v, self.fontsize, self.fontname) return v def _set_font(self, v, size, name): if isinstance(v, Paragraph): for frag in v.frags: if frag.super or frag.sub: frag.fontSize = size - 2 else: frag.fontSize = size else: v = self._new_paragraph( u'<font size="{}" name="{}">{}</font>'.format(size, name, v)) return v def _new_paragraph(self, t, s='Normal'): style = STYLES[s] p = Paragraph(t, style) return p
class ScalarDisplaySettings(DatasetReferenceOptionsStructure): node_color=Either(Str,None) surf_color=Either(Str,None) node_size=Either(Str,None) circle=Either(Str,None) connmat=Either(Str,None) #scalar_sets=List(Str) scalar_sets=Property(List(Either(Str,None))) def _get_scalar_sets(self): return [None]+self.ds_ref.node_scalars.keys() #def update_scalars(self): # self.scalar_sets=self.ds_ref.node_scalars.keys() def reset_configuration(self): self.node_color=''; self.surf_color=''; self.node_size=''; self.circle=''; self.connmat='';
class ODESolver(HasTraits): ode = Instance(ODE) initial_state = Either(Float, Array) t = Array solution = Property(Array, depends_on='initial_state, t, ode.changed') view = View(Item(name='ode', show_label=False, style='custom'), Item(name='initial_state'), Item(name='solution', style='readonly'), title='ODE Solver') @cached_property def _get_solution(self): return self.solve() def solve(self): """ Solve the ODE and return the values of the solution vector at specified times t. """ from scipy.integrate import odeint return odeint(self.ode.eval, self.initial_state, self.t)
class PaneItem(LayoutItem): """ A pane in a Task layout. """ #: The ID of the item. If the item refers to a TaskPane, this is the ID of #: that TaskPane. id = Either(Str, Int, default="", pretty_skip=True) #: The width of the pane in pixels. If not specified, the pane will be #: sized according to its size hint. width = Int(-1) #: The height of the pane in pixels. If not specified, the pane will be #: sized according to its size hint. height = Int(-1) def __init__(self, id="", **traits): super(PaneItem, self).__init__(**traits) self.id = id def pargs(self): return [self.id]
class Schema(atom): ref000 = Either(Str, Instance(Reference, ())) title = Str description = Str required = List(Str) type000 = Str properties = Instance(Properties, ()) #allOf = ??? #additionalProperties = ??? #maxProperties = Str #minProperties = Str items = Instance(Item, ()) # Further schema documentation discriminator = Str readOnly = Bool xml = Instance(XMLObject, ()) externalDocs = Instance(ExternalDocs, ()) example = Any _name_mappings = {"ref000": "$ref"} _name_mappings.update(Item._name_mappings)
class ActionConditional(AutomatedRunConditional): """ Executes a specified action. The action string is executed as pyscript snippet. actions therefore may be any valid measuremnt pyscript code. for example:: # call a gosub gosub("someGoSub") # open a valve open("V") """ action = Either(Str, Callable) resume = Bool # resume==True the script continues execution else break out of measure_iteration def _from_dict_hook(self, cd): for tag in ('action', 'resume'): if tag in cd: setattr(self, tag, cd[tag]) def perform(self, script): """ perform the specified action. use ``MeasurementPyScript.execute_snippet`` to perform desired action :param script: MeasurementPyScript """ action = self.action if isinstance(action, str): try: script.execute_snippet(action) except BaseException: self.warning('Invalid action: "{}"'.format(action)) elif hasattr(action, '__call__'): action()
class myTabularEditor(TabularEditor): key_pressed = Str rearranged = Str pasted = Str autoscroll = Bool(False) # copy_cache = Str # link_copyable = Bool(True) pastable = Bool(True) paste_function = Str drop_factory = Either(Str, Callable) col_widths = Str drag_external = Bool(False) drag_enabled = Bool(True) bgcolor = Color row_height = Int mime_type = Str('pychron.tabular_item') # scroll_to_row_hint = 'top' def _get_klass(self): return _TabularEditor
class ToolBar(ConstraintsWidget): """ A tool bar can be used to hold and display actions. """ #: ToolBars expand freely in width by default hug_width = 'ignore' #: A read-only cached property which holds the list of toolbar #: children which are actions or widgets. contents = Property( List(Either(Instance(Action), Instance(ConstraintsWidget))), depends_on='children', ) #: Overridden parent class trait abstract_obj = Instance(AbstractTkToolBar) @cached_property def _get_contents(self): """ The property getter for the 'contents' attribute. """ filt = lambda child: isinstance(child, (Action, ConstraintsWidget)) return filter(filt, self.children)
class StreamlineFactory(DataModuleFactory): """Applies the Streamline mayavi module to the given VTK data object.""" _target = Instance(modules.Streamline, ()) linetype = Trait('line', 'ribbon', 'tube', adapts='streamline_type', desc="""the type of line-like object used to display the streamline.""") seedtype = Trait('sphere', {'sphere':0, 'line':1, 'plane':2, 'point':3}, desc="""the widget used as a seed for the streamlines.""") seed_visible = Bool(True, adapts='seed.widget.enabled', desc="Control the visibility of the seed.", ) seed_scale = CFloat(1., desc="Scales the seed around its default center", ) seed_resolution = Either(None, CInt, desc='The resolution of the seed. Determines the number of ' 'seed points') integration_direction = Trait('forward', 'backward', 'both', adapts='stream_tracer.integration_direction', desc="The direction of the integration.", ) def _seedtype_changed(self): # XXX: this also acts for seed_scale and seed_resolution, but no # need to define explicit callbacks, as all the callbacks are # being called anyhow. self._target.seed.widget = widget = \ self._target.seed.widget_list[self.seedtype_] if not self.seed_scale==1.: widget.enabled = True if self.seedtype == 'line': p1 = widget.point1 p2 = widget.point2 center = (p1 + p2)/2. widget.point1 = center + self.seed_scale*(p1 - center) widget.point2 = center + self.seed_scale*(p2 - center) elif self.seedtype == 'plane': p1 = widget.point1 p2 = widget.point2 center = (p1 + p2)/2. o = widget.origin widget.point1 = center + self.seed_scale*(p1 - center) widget.point2 = center + self.seed_scale*(p2 - center) widget.origin = center + self.seed_scale*(o - center) elif self.seedtype == 'sphere': widget.radius *= self.seed_scale # XXX: Very ugly, but this is only way I have found to # propagate changes. self._target.seed.stop() self._target.seed.start() widget.enabled = self.seed_visible if self.seed_resolution is not None: widget.enabled = True if self.seedtype in ('plane', 'line'): widget.resolution = self.seed_resolution elif self.seedtype == 'sphere': widget.phi_resolution = widget.theta_resolution = \ self.seed_resolution # XXX: Very ugly, but this is only way I have found to # propagate changes. self._target.seed.stop() self._target.seed.start() widget.enabled = self.seed_visible
class VectorsFactory(DataModuleFactory): """Applies the Vectors mayavi module to the given data object source (Mayavi source, or VTK dataset). """ _target = Instance(modules.Vectors, ()) scale_factor = CFloat(1., adapts='glyph.glyph.scale_factor', desc="""the scaling applied to the glyphs. The size of the glyph is by default in drawing units.""") scale_mode = Trait('vector', {'none':'data_scaling_off', 'scalar':'scale_by_scalar', 'vector':'scale_by_vector'}, help="""the scaling mode for the glyphs ('vector', 'scalar', or 'none').""") resolution = CInt(8, desc="The resolution of the glyph created. For " "spheres, for instance, this is the number of " "divisions along theta and phi.") mask_points = Either(None, CInt, desc="If supplied, only one out of 'mask_points' " "data point is displayed. This option is useful " "to reduce the number of points displayed " "on large datasets") def _resolution_changed(self): glyph = self._target.glyph.glyph_source.glyph_source if hasattr(glyph, 'theta_resolution'): glyph.theta_resolution = self.resolution if hasattr(glyph, 'phi_resolution'): glyph.phi_resolution = self.resolution if hasattr(glyph, 'resolution'): glyph.resolution = self.resolution if hasattr(glyph, 'shaft_resolution'): glyph.shaft_resolution = self.resolution if hasattr(glyph, 'tip_resolution'): glyph.tip_resolution = self.resolution def _mask_points_changed(self): if self.mask_points is not None: self._target.glyph.mask_input_points = True self._target.glyph.mask_points.on_ratio = self.mask_points def _scale_mode_changed(self): self._target.glyph.scale_mode = self.scale_mode_ mode = Trait('2darrow', glyph_mode_dict, desc="""the mode of the glyphs.""") def _mode_changed(self): v = self._target # Workaround for different version of VTK: if hasattr(v.glyph.glyph_source, 'glyph_source'): g = v.glyph.glyph_source else: g = v.glyph if self.mode == 'point': g.glyph_source = tvtk.PointSource(radius=0, number_of_points=1) else: g.glyph_source = g.glyph_list[self.mode_] if self.mode_ == 0: g.glyph_source.glyph_type = self.mode[2:]
class ModelInfo(HasTraits): """Model-specific level of information about a specific model.""" model_name = Str(desc=dedent(""" The name of the model. (Automatically populated from module name). """)) task_model = Bool(True, desc=dedent(""" If True, model the task using a design file matching the model name. """)) smooth_fwhm = Either( Float(2), None, desc=dedent(""" The size of the Gaussian smoothing kernel for spatial filtering. """), ) surface_smoothing = Bool( True, desc=dedent(""" If True, filter cortical voxels using Gaussian weights computed along the surface mesh. """), ) interpolate_noise = Bool( False, desc=dedent(""" If True, identify locally noisy voxels and replace replace their values using interpolation during spatial filtering. Warning: this option is still being refined. """), ) hpf_cutoff = Either( Float(128), None, usedefault=True, desc=dedent(""" The cutoff value (in seconds) for the temporal high-pass filter. """), ) percent_change = Bool( False, desc=dedent(""" If True, convert data to percent signal change units before model fit. """), ) nuisance_components = Dict(Enum("wm", "csf", "edge", "noise"), Int, usedefault=True, desc=dedent(""" Anatomical sources and number of components per source to include. """)) save_residuals = Bool( False, desc=dedent(""" If True, write out an image with the residual time series in each voxel after model fitting. """), ) hrf_derivative = Bool( True, desc=dedent(""" If True, include the temporal derivative of the HRF model. """), ) # TODO parameter names to filter the design and generate default contrasts? contrasts = List( Tuple(Str, List(Str), List(Float)), desc=dedent(""" Definitions for model parameter contrasts. Each item in the list should be a tuple with the fields: (1) the name of the contrast, (2) the names of the parameters included in the contrast, and (3) the weights to apply to the parameters. """), )
class TableColumn(HasPrivateTraits): """ Represents a column in a table editor. """ # ------------------------------------------------------------------------- # Trait definitions: # ------------------------------------------------------------------------- #: Column label to use for this column: label = Str(UndefinedLabel) #: Type of data contained by the column: # XXX currently no other types supported, but potentially there could be... type = Enum("text", "bool") #: Text color for this column: text_color = Color("black") #: Text font for this column: text_font = Either(None, Font) #: Cell background color for this column: cell_color = Color("white", allow_none=True) #: Cell background color for non-editable columns: read_only_cell_color = Color(0xF4F3EE, allow_none=True) #: Cell graph color: graph_color = Color(0xDDD9CC) #: Horizontal alignment of text in the column: horizontal_alignment = Enum("left", ["left", "center", "right"]) #: Vertical alignment of text in the column: vertical_alignment = Enum("center", ["top", "center", "bottom"]) #: Horizontal cell margin horizontal_margin = Int(4) #: Vertical cell margin vertical_margin = Int(3) #: The image to display in the cell: image = Image #: Renderer used to render the contents of this column: renderer = Any # A toolkit specific renderer #: Is the table column visible (i.e., viewable)? visible = Bool(True) #: Is this column editable? editable = Bool(True) #: Is the column automatically edited/viewed (i.e. should the column editor #: or popup be activated automatically on mouse over)? auto_editable = Bool(False) #: Should a checkbox be displayed instead of True/False? show_checkbox = Bool(True) #: Can external objects be dropped on the column? droppable = Bool(False) #: Context menu to display when this column is right-clicked: menu = Instance(Menu) #: The tooltip to display when the mouse is over the column: tooltip = Str() #: The width of the column (< 0.0: Default, 0.0..1.0: fraction of total table #: width, > 1.0: absolute width in pixels): width = Float(-1.0) #: The width of the column while it is being edited (< 0.0: Default, #: 0.0..1.0: fraction of total table width, > 1.0: absolute width in #: pixels): edit_width = Float(-1.0) #: The height of the column cell's row while it is being edited #: (< 0.0: Default, 0.0..1.0: fraction of total table height, #: > 1.0: absolute height in pixels): edit_height = Float(-1.0) #: The resize mode for this column. This takes precedence over other settings #: (like **width**, above). #: - "interactive": column can be resized by users or programmatically #: - "fixed": users cannot resize the column, but it can be set programmatically #: - "stretch": the column will be resized to fill the available space #: - "resize_to_contents": column will be sized to fit the contents, but then cannot be resized resize_mode = Enum("interactive", "fixed", "stretch", "resize_to_contents") #: The view (if any) to display when clicking a non-editable cell: view = AView #: Optional maximum value a numeric cell value can have: maximum = Float(trait_value=True) # ------------------------------------------------------------------------- #: Returns the actual object being edited: # ------------------------------------------------------------------------- def get_object(self, object): """ Returns the actual object being edited. """ return object def get_label(self): """ Gets the label of the column. """ return self.label def get_width(self): """ Returns the width of the column. """ return self.width def get_edit_width(self, object): """ Returns the edit width of the column. """ return self.edit_width def get_edit_height(self, object): """ Returns the height of the column cell's row while it is being edited. """ return self.edit_height def get_type(self, object): """ Gets the type of data for the column for a specified object. """ return self.type def get_text_color(self, object): """ Returns the text color for the column for a specified object. """ return self.text_color_ def get_text_font(self, object): """ Returns the text font for the column for a specified object. """ return self.text_font def get_cell_color(self, object): """ Returns the cell background color for the column for a specified object. """ if self.is_editable(object): return self.cell_color_ return self.read_only_cell_color_ def get_graph_color(self, object): """ Returns the cell background graph color for the column for a specified object. """ return self.graph_color_ def get_horizontal_alignment(self, object): """ Returns the horizontal alignment for the column for a specified object. """ return self.horizontal_alignment def get_vertical_alignment(self, object): """ Returns the vertical alignment for the column for a specified object. """ return self.vertical_alignment def get_image(self, object): """ Returns the image to display for the column for a specified object. """ return self.image def get_renderer(self, object): """ Returns the renderer for the column of a specified object. """ return self.renderer def is_editable(self, object): """ Returns whether the column is editable for a specified object. """ return self.editable def is_auto_editable(self, object): """ Returns whether the column is automatically edited/viewed for a specified object. """ return self.auto_editable def is_droppable(self, object, value): """ Returns whether a specified value is valid for dropping on the column for a specified object. """ return self.droppable def get_menu(self, object): """ Returns the context menu to display when the user right-clicks on the column for a specified object. """ return self.menu def get_tooltip(self, object): """ Returns the tooltip to display when the user mouses over the column for a specified object. """ return self.tooltip def get_view(self, object): """ Returns the view to display when clicking a non-editable cell. """ return self.view def get_maximum(self, object): """ Returns the maximum value a numeric column can have. """ return self.maximum def on_click(self, object): """ Called when the user clicks on the column. """ pass def on_dclick(self, object): """ Called when the user clicks on the column. """ pass def cmp(self, object1, object2): """ Returns the result of comparing the column of two different objects. This is deprecated. """ return (self.key(object1) > self.key(object2)) - ( self.key(object1) < self.key(object2) ) def __str__(self): """ Returns the string representation of the table column. """ return self.get_label()
class _MarketTable(_TSTable): """markettable""" Cycle = Either(Int(60), Enum("day", "week", "month", "quarter", "halfyear", "year"), arg_type="Integer", label="周期", order=0) CycleUnit = Enum("s", "d", arg_type="SingleOption", label="周期单位", order=1) def __QS_initArgs__(self): super().__QS_initArgs__() self.Cycle = 60 def getDateTime(self, ifactor_name=None, iid=None, start_dt=None, end_dt=None, args={}): if iid is None: iid = "000001.SH" CycleStr = self._genCycleStr(args.get("周期", self.Cycle), args.get("周期单位", self.CycleUnit)) if start_dt is None: start_dt = dt.datetime(1970, 1, 1) if end_dt is None: end_dt = dt.datetime.now() CodeStr = "SetSysParam(pn_cycle()," + CycleStr + ");" CodeStr += "return select " + "['date'] " CodeStr += "from markettable datekey inttodate(" + start_dt.strftime( "%Y%m%d") + ") " CodeStr += "to (inttodate(" + end_dt.strftime( "%Y%m%d") + ")+0.9999) of '{ID}' end;" ErrorCode, Data, Msg = self._FactorDB._TSLPy.RemoteExecute( CodeStr.format(ID="".join(reversed(iid.split(".")))), {}) if ErrorCode != 0: raise __QS_Error__("TinySoft 执行错误: " + Msg.decode("gbk")) DTs = np.array([ dt.datetime(*self._FactorDB._TSLPy.DecodeDateTime(iData[b"date"])) for iData in Data ], dtype="O") return DTs[(DTs >= start_dt) & (DTs <= end_dt)].tolist() def _genCycleStr(self, cycle, cycle_unit): if isinstance(cycle, str): return "cy_" + cycle + "()" elif cycle_unit == "s": return ("cy_trailingseconds(%d)" % cycle) elif cycle_unit == "d": return ("cy_trailingdays(%d)" % cycle) else: raise __QS_Error__("不支持的和周期单位: '%s'!" % (cycle_unit, )) def __QS_genGroupInfo__(self, factors, operation_mode): CycleStrGroup = {} for iFactor in factors: iCycleStr = self._genCycleStr(iFactor.Cycle, iFactor.CycleUnit) if iCycleStr not in CycleStrGroup: CycleStrGroup[iCycleStr] = { "FactorNames": [iFactor.Name], "RawFactorNames": {iFactor._NameInFT}, "StartDT": operation_mode._FactorStartDT[iFactor.Name], "args": iFactor.Args.copy() } else: CycleStrGroup[iCycleStr]["FactorNames"].append(iFactor.Name) CycleStrGroup[iCycleStr]["RawFactorNames"].add( iFactor._NameInFT) CycleStrGroup[iCycleStr]["StartDT"] = min( operation_mode._FactorStartDT[iFactor.Name], CycleStrGroup[iCycleStr]["StartDT"]) EndInd = operation_mode.DTRuler.index(operation_mode.DateTimes[-1]) Groups = [] for iCycleStr in CycleStrGroup: StartInd = operation_mode.DTRuler.index( CycleStrGroup[iCycleStr]["StartDT"]) Groups.append((self, CycleStrGroup[iCycleStr]["FactorNames"], list(CycleStrGroup[iCycleStr]["RawFactorNames"]), operation_mode.DTRuler[StartInd:EndInd + 1], CycleStrGroup[iCycleStr]["args"])) return Groups def __QS_prepareRawData__(self, factor_names, ids, dts, args={}): CycleStr = self._genCycleStr(args.get("周期", self.Cycle), args.get("周期单位", self.CycleUnit)) Fields = self._FactorDB._FactorInfo["DBFieldName"].loc[ self.Name].loc[factor_names].tolist() CodeStr = "SetSysParam(pn_cycle()," + CycleStr + ");" CodeStr += "return select " + "['date'],['" + "'],['".join( Fields) + "'] " CodeStr += "from markettable datekey inttodate(" + dts[0].strftime( "%Y%m%d") + ") " CodeStr += "to (inttodate(" + dts[-1].strftime( "%Y%m%d") + ")+0.9999) of '{ID}' end;" Data = {} for iID in ids: iCodeStr = CodeStr.format(ID="".join(reversed(iID.split(".")))) ErrorCode, iData, Msg = self._FactorDB._TSLPy.RemoteExecute( iCodeStr, {}) if ErrorCode != 0: raise __QS_Error__("TinySoft 执行错误: " + Msg.decode("gbk")) if iData: Data[iID] = pd.DataFrame(iData).set_index([b"date"]) if not Data: return pd.Panel(Data) Data = pd.Panel(Data).swapaxes(0, 2) Data.major_axis = [ dt.datetime(*self._FactorDB._TSLPy.DecodeDateTime(iDT)) for iDT in Data.major_axis ] Data.items = [(iCol.decode("gbk") if isinstance(iCol, bytes) else iCol) for i, iCol in enumerate(Data.items)] Data = Data.loc[Fields] Data.items = factor_names return Data def __QS_calcData__(self, raw_data, factor_names, ids, dts, args={}): if raw_data.shape[2] == 0: return pd.Panel(items=factor_names, major_axis=dts, minor_axis=ids) return raw_data.loc[:, dts, ids] def readDayData(self, factor_names, ids, start_date, end_date, args={}): RawData = self.__QS_prepareRawData__(factor_names, ids, dts=[start_date, end_date], args=args) if RawData.shape[2] == 0: return pd.Panel(items=factor_names, major_axis=[], minor_axis=ids) return RawData.loc[:, :, ids]
finally: self._disable_update = False if trait_change_notify: self.update() return self ###################################################################### # Non-public interface. ###################################################################### def _m_data_changed(self, ds): if not hasattr(ds, 'mlab_source'): ds.add_trait('mlab_source', Instance(MlabSource)) ds.mlab_source = self ArrayOrNone = Either(None, CArray, comparison_mode=NO_COMPARE) ArrayNumberOrNone = Either(None, CArrayOrNumber, comparison_mode=NO_COMPARE) ############################################################################### # `MGlyphSource` class. ############################################################################### class MGlyphSource(MlabSource): """ This class represents a glyph data source for Mlab objects and allows the user to set the x, y, z, scalar/vector attributes. """ # The x, y, z and points of the glyphs. x = ArrayNumberOrNone y = ArrayNumberOrNone