class MeasurementTabularAdapter(BaseTabularAdapter): columns = [ ('Name', 'name'), ('Value', 'value'), ] name_width = Int(80) value_width = Int(80)
class MeasurementTabularAdapter(BaseTabularAdapter): columns = [('Name', 'name'), ('Value', 'value'), ('Units', 'units')] name_width = Int(120) value_width = Int(250) units_width = Int(40)
class NewModelBDialog(NewModelDialog): """Create a dialog requesting the parameters to create Model B.""" model_name = Str(MODEL_B_NAME) nclasses = Int(5) nannotators = Int(8) # prior strength multiplies the dirichlet parameters alpha prior_strength = Float(1.0) parameters_group = VGroup( Item(name='nclasses', editor=RangeEditor(mode='spinner', low=2, high=1000), label='Number of annotation classes:', width=100), Item(name='nannotators', editor=RangeEditor(mode='spinner', low=2, high=1000), label='Number of annotators:', width=100), Item(name='prior_strength', editor=RangeEditor(mode='slider', low=0.0, low_label='null ', high=3.0, high_label=' high', label_width=50), label='Informativeness of prior:') )
class ComputedValueTabularAdapter(BaseTabularAdapter): columns = [('Name', 'name'), ('Value', 'value'), (SIGMA_1, 'error'), ('%', 'percent_error')] name_width = Int(80) value_width = Int(120) units_width = Int(40) error_width = Int(60) error_text = Property percent_error_text = Property value_text = Property def _get_value_text(self): item = self.item if item.display_value: v = item.value n = item.sig_figs return floatfmt(v, n=n, s=n) else: return '' def _get_error_text(self): item = self.item v = item.error n = item.sig_figs return floatfmt(v, n) def _get_percent_error_text(self): e = self.item.error v = self.item.value return format_percent_error(v, e)
class _SamplingParamsDialog(HasTraits): nsamples = Int(200) burn_in_samples = Int(100) thin_samples = Int(1) traits_view = View(VGroup( Item('nsamples', label='Number of samples', editor=RangeEditor(mode='spinner', low=100, high=50000, is_float=False), width=100), Item('burn_in_samples', label='Number of samples in burn-in phase', editor=RangeEditor(mode='spinner', low=1, high=50000, is_float=False), width=100), Item('thin_samples', label='Thinning (keep 1 samples every N)', editor=RangeEditor(mode='spinner', low=1, high=50000, is_float=False), width=100), ), buttons=OKCancelButtons)
class Base(HasTraits): foo = Int(0) foo_notify_count = Int(0) def _foo_changed(self): self.foo_notify_count += 1
class CreateNewAnnotationsDialog(HasTraits): nannotators = Int(8) nitems = Int(100) @staticmethod def create_annotations_dialog(): dialog = CreateNewAnnotationsDialog() dialog_ui = dialog.edit_traits(kind='modal') if dialog_ui.result: # user pressed 'Ok' annotations = np.empty((dialog.nitems, dialog.nannotators), dtype=int) annotations.fill(MISSING_VALUE) return annotations else: return None def traits_view(self): view = View(VGroup( Item('nannotators', editor=RangeEditor(mode='spinner', low=3, high=1000), label='Number of annotators:'), Item('nitems', editor=RangeEditor(mode='spinner', low=2, high=1000000), label='Number of items'), ), buttons=['OK', 'Cancel']) return view
class DateEditor(EditorFactory): """ Editor factory for date/time editors. """ # ------------------------------------------------------------------------- # Trait definitions: # ------------------------------------------------------------------------- # -- ReadonlyEditor traits ------------------------------------------------ #: Message to show when Date is None. message = Str("Undefined") #: The string representation of the date to show. Uses time.strftime #: format. strftime = Str("%B %d %Y (%a)") #: An optional view to display when a read-only text editor is clicked: view = AView # -- CustomEditor traits -------------------------------------------------- #: Should users be able to pick future dates when using the CustomEditor? allow_future = Bool(True) #: How many months to show at a time. months = Int(3) #: True: Must be a List of Dates. False: Must be a Date instance. multi_select = Bool(False) #: When a user multi-selects entries and some of those entries are already #: selected and some are not, what should be the behavior for the seletion? #: #: Options: #: #: - 'toggle': Toggle each day to the opposite of the current state. #: - 'on': Always turn them on. #: - 'off': Always turn them off. #: - 'max_change': Change all to same state, with most days changing. #: For example 1 selected and 9 not, then they would all get selected. #: - 'min_change': Change all to same state, with min days changing. #: For example 1 selected and 9 not, then they would all get unselected. on_mixed_select = Enum("toggle", "on", "off", "max_change", "min_change") #: How much space to put between the individual months. padding = Int(5) #: Does the user have to hold down Shift for the left-click multiselect? shift_to_select = Bool(False) #: Style used when a date is selected. selected_style = Instance( CellFormat, kw={ "bold": True, "fgcolor": (255, 255, 255), "bgcolor": (0, 128, 0) }, )
class ExtractionTabularAdapter(BaseTabularAdapter): columns = [('Name', 'name'), ('Value', 'value'), ('Units', 'units')] name_width = Int(100) value_width = Int(200) units_width = Int(40)
class CompuatedValueTabularAdapter(BaseTabularAdapter): columns = [('Name', 'name'), ('Value', 'value'), (SIGMA_1, 'error'), ] name_width = Int(80) value_width = Int(80) units_width = Int(40)
class Foo(HasTraits): x = Int() y = Int() def _x_changed(self): side_effects.append("x") # add the second object notifier self.on_trait_change(object_handler2, name="anytrait")
class DummyParent(HasTraits): number = Int() number2 = Int() instance = Instance(Dummy, allow_none=True) instance2 = Instance(Dummy) income = Float() dummies = List(Dummy)
class DateEditor(EditorFactory): """ Editor factory for date/time editors. """ #------------------------------------------------------------------------- # Trait definitions: #------------------------------------------------------------------------- #-- ReadonlyEditor traits ------------------------------------------------ # Message to show when Date is None. message = Str('Undefined') # The string representation of the date to show. Uses time.strftime # format. strftime = Str('%B %d %Y (%a)') # An optional view to display when a read-only text editor is clicked: view = AView #-- CustomEditor traits -------------------------------------------------- # Should users be able to pick future dates when using the CustomEditor? allow_future = Bool(True) # How many months to show at a time. months = Int(3) # True: Must be a List of Dates. False: Must be a Date instance. multi_select = Bool(False) # When a user multi-selects entries and some of those entries are already # selected and some are not, what should be the behavior for the seletion? # Options:: # # 'toggle' -- Toggle each day to the opposite of the current state. # 'on' -- Always turn them on. # 'off' -- Always turn them off. # 'max_change' -- Change all to same state, with most days changing. # For example 1 selected and 9 not, then they would # all get selected. # 'min_change' -- Change all to same state, with min days changing. # For example 1 selected and 9 not, then they would # all get unselected. on_mixed_select = Enum('toggle', 'on', 'off', 'max_change', 'min_change') # How much space to put between the individual months. padding = Int(5) # Does the user have to hold down Shift for the left-click multiselect? shift_to_select = Bool(False)
class Band(HasTraits): center = Int(enter_set=True, auto_set=False) threshold = Int(enter_set=True, auto_set=False) color = Color use = Bool(False) def traits_view(self): v = View( HGroup(UItem('use'), Item('center'), Item('threshold'), UItem('color'))) return v #============= EOF =============================================
class NewModelBtDialog(NewModelDialog): model_name = Str(MODEL_BT_NAME) nclasses = Int(5) nannotators = Int(8) parameters_group = VGroup( Item(name='nclasses', editor=RangeEditor(mode='spinner', low=2, high=1000), label='Number of annotation classes:', width=100), Item(name='nannotators', editor=RangeEditor(mode='spinner', low=2, high=1000), label='Number of annotators:', width=100), )
class BasicConfigurator(AbstractConfigurator): """ A BasicConfigurator needs a network_size parameter that specifies the size of the initial network. network_size nodes of type node_type (specified in the body of the configurator) are created and are passed the arguments from additional_arguments specified in node_options. """ options = {"starting_network_size"} starting_network_size = Int(1000) node_type = Type node_options = Set(Str) def create_edges(self): pass def create_nodes(self): self.node_arguments = extract_sub_dictionary(self.full_parameters, self.node_options) node_ids = SequenceAsyncResult([ self.send(NodeManager.name, 'create_node', cls=self.node_type, parameters=self.node_arguments) for _r in xrange(self.starting_network_size) ]) self.node_identifiers = node_ids.get()
class FooDialog(HasTraits): """Test dialog that does nothing useful.""" my_int = Int(2) my_str = Str('hallo') traits_view = View(Item('my_int'), Item('my_str'), buttons=['OK'])
class Target(HasTraits): event = Event(Instance(SomeEvent)) event_count = Int(0) def _event_fired(self): self.event_count += 1
class Recorder(Agent): name = 'recorder' current_time = Int(-1) def setup(self): self.number_of_nodes = 1000 self.distributions = pd.DataFrame( data=nans((self.steps + 1, 3)), columns=['susceptible', 'infected', 'recovered'], index=arange(-1, self.steps)) self.distributions.ix[self.current_time] = 0 self.distributions.susceptible.ix[ self.current_time] = self.number_of_nodes self.send(BaseClock.name, 'register_observer', name=self.name) def ticked(self): self.current_time += 1 self.distributions.ix[self.current_time] =\ self.distributions.ix[self.current_time - 1] def node_infected(self, node): self.distributions.infected[self.current_time] += 1 self.distributions.susceptible[self.current_time] -= 1 def node_recovered(self, node): self.distributions.infected[self.current_time] -= 1 self.distributions.recovered[self.current_time] += 1 def _save_infected_ratio(self): df = self.distributions.dropna() df.to_csv('SIR_model.csv', index_label='step') def save_statistic(self): self._save_infected_ratio()
class FooDialog(HasTraits): """Test dialog that does nothing useful.""" my_int = Int(2) my_str = Str("hallo") traits_view = View(Item("my_int"), Item("my_str"), buttons=["OK"])
class DisallowNewTraits(HasStrictTraits): """ Make sure no extra traits are added. """ x = Int(10) traits_view = View(Item("x"), spring)
class ListUpdatesTest(HasTraits): a = List b = List events_received = Int(0) @on_trait_change("a[], b[]") def _receive_events(self): self.events_received += 1
class GitTagAdapter(GitObjectAdapter): columns = [('Name', 'name'), ('Message', 'message'), ('Date', 'date'), ('Commit', 'hexsha'), ('Commit Message', 'commit_message')] name_width = Int(60) commit_message_text = Property def _get_commit_message_text(self): return self._truncate_message(self.item.commit_message)
class Recorder(Agent): """ The Recorder Agent keeps track of the number of susceptible, infected and recovered nodes at each step. """ name = 'recorder' current_time = Int(-1) options = { 'steps', 'graph', } def setup(self): """ Initialization of the agent. """ self.number_of_nodes = self.graph.number_of_nodes() self.susceptible = self.number_of_nodes self.infected = 0 self.recovered = 0 # opens a connection to Mongo self.client = MongoClient() # resets the stats of old simulations self.client.drop_database('stats') self.db = self.client.stats self.distributions = self.db.distributions # tells the clock that it want to be notified when # a new step begins self.send(BaseClock.name, 'register_observer', name=self.name) def ticked(self): """ Receives this message from the Clock. """ self.distributions.insert({ 'current_time': self.current_time, 'susceptible': self.susceptible, 'infected': self.infected, 'recovered': self.recovered }) self.current_time += 1 def node_infected(self, node): """ The Activator signals each node that is infected. """ self.susceptible -= 1 self.infected += 1 def node_recovered(self, node): """ The Activator signals each node that recovers. """ self.infected -= 1 self.recovered += 1
class MappedWithDefault(HasTraits): married = Map({"yes": 1, "yeah": 1, "no": 0, "nah": 0}) default_calls = Int(0) def _married_default(self): self.default_calls += 1 return "yes"
class CommitAdapter(GitObjectAdapter): columns = [ ('ID', 'hexsha'), ('Date', 'date'), ('Message', 'message'), ('Author', 'author'), ('Email', 'email'), ] author_width = Int(100)
class Specimen(Node): state = Enum('S', 'I', 'R') remaining_infection_time = Int(-1) infection_probability = Float average_infection_length = Int std_infection_length = Int(3) infected_fraction = Float # DEBUG_SEND = True def infection_time(self): value = int( random.gauss(self.average_infection_length, self.std_infection_length)) tmp_solution.tduration[self.id] = value return value def initialize(self, state): self.state = state if state == 'I': self.remaining_infection_time = self.infection_time() self.send(Activator.name, 'infected', node=self.id) def infect(self): if self.state == 'S': self.state = 'I' self.remaining_infection_time = self.infection_time() self.send(Activator.name, 'infected', node=self.id) def activate(self): if (self.state == 'I' and self.remaining_infection_time > 0): for node in self.neighbors(): if random.random() < self.infection_probability: self.send(node, 'infect') self.remaining_infection_time -= 1 elif (self.state == 'I' and self.remaining_infection_time == 0): self.remaining_infection_time -= 1 self.state = 'R' self.send(Activator.name, 'not_infected', node=self.id) elif self.state in ('R', 'S'): pass else: self.send_log('I should not get here.')
class FlipBvecInputSpec(BaseInterfaceInputSpec): bvecs = File(exists=True, desc="Input diffusion gradient bvec file") flipping_axis = List(desc="List of axis to be flipped") delimiter = Str(desc="Delimiter used in the table") header_lines = Int(0, desc="Line number of table header") orientation = Enum(['v', 'h'], desc="Orientation of the table")
class GitObjectAdapter(TabularAdapter): hexsha_width = Int(80) message_width = Int(300) date_width = Int(120) font = '10' hexsha_text = Property message_text = Property def _get_hexsha_text(self): return self.item.hexsha[:8] def _get_message_text(self): return self._truncate_message(self.item.message) def _truncate_message(self, m): if len(m) > 200: m = '{}...'.format(m[:200]) return m
class NumberWithRangeEditor(HasTraits): """Dialog containing a RangeEditor in 'spinner' mode for an Int.""" number = Int() traits_view = View( Item(label="Range should be 3 to 8. Enter 1, then press OK"), Item("number", editor=RangeEditor(low=3, high=8, mode="text")), buttons=["OK"], )