Widget

class Widget(**kwargs: Any)[source]

A widget class for handling simulation parameters, coordinates and settings.

_esm

Path to the JavaScript file for the widget.

Type:

pathlib.Path

_css

Path to the CSS file for the widget.

Type:

pathlib.Path

decay_rates_input

List of decay rates as floats.

Type:

traitlets.List

amplitude_input

List of amplitudes as floats.

Type:

traitlets.List

location_input

List of locations as floats.

Type:

traitlets.List

width_input

List of widths as floats.

Type:

traitlets.List

skewness_input

List of skewness values as floats.

Type:

traitlets.List

timepoints_max_input

Maximum number of timepoints.

Type:

traitlets.Int

timepoints_stepsize_input

Step size for timepoints.

Type:

traitlets.Float

wavelength_min_input

Minimum wavelength value.

Type:

traitlets.Float

wavelength_max_input

Maximum wavelength value.

Type:

traitlets.Float

wavelength_stepsize_input

Step size for wavelength.

Type:

traitlets.Float

stdev_noise_input

Standard deviation of noise.

Type:

traitlets.Float

seed_input

Seed for random number generation.

Type:

traitlets.Int

add_gaussian_irf_input

Flag to add Gaussian IRF.

Type:

traitlets.Bool

irf_location_input

Location of the IRF center.

Type:

traitlets.Float

irf_width_input

Width of the IRF.

Type:

traitlets.Float

use_sequential_scheme_input

Flag to use sequential scheme.

Type:

traitlets.Bool

model_file_name_input

Name of the model file.

Type:

traitlets.Unicode

parameter_file_name_input

Name of the parameter file.

Type:

traitlets.Unicode

data_file_name_input

Name of the data file.

Type:

traitlets.Unicode

simulate

Trigger for simulation.

Type:

traitlets.Unicode

visualize_data

Flag to visualize data.

Type:

traitlets.Bool

Initialize the Widget instance and set up traitlet observers.

This constructor initializes the Widget instance by calling the parent class’s initializer and sets up an observer for the ‘simulate’ traitlet. The observer triggers the _simulate function whenever the ‘simulate’ traitlet changes.

Observers:
  • simulate: Calls the _simulate function when the ‘simulate’ traitlet changes.

Attributes Summary

__annotations__

__dict__

__doc__

__module__

__weakref__

list of weak references to the object (if defined)

_active_widgets

_all_trait_default_generators

_anywidget_commands

_comm_changed

_control_comm

_css

_default_keys

_descriptors

_dom_classes

CSS classes applied to widget DOM element

_esm

_holding_sync

_instance_inits

_log_default

_model_module

A trait for unicode strings.

_model_module_version

A trait for unicode strings.

_model_name

A trait for unicode strings.

_msg_callbacks

A trait whose value must be an instance of a specified class.

_property_lock

An instance of a Python dict.

_states_to_send

An instance of a Python set.

_static_immutable_initial_values

_trait_default_generators

_traits

_view_count

The number of views of the model displayed in the frontend.

_view_module

A trait for unicode strings.

_view_module_version

A trait for unicode strings.

_view_name

A trait for unicode strings.

_widget_construction_callback

_widget_types

add_gaussian_irf_input

A boolean (True, False) trait.

amplitude_input

An instance of a Python list.

comm

A trait which allows any value.

cross_validation_lock

A contextmanager for running a block with our cross validation lock set to True.

data_file_name_input

A trait for unicode strings.

decay_rates_input

An instance of a Python list.

irf_location_input

A float trait.

irf_width_input

A float trait.

keys

The traits which are synced.

layout

An instance trait which coerces a dict to an instance.

location_input

An instance of a Python list.

log

A trait whose value must be an instance of a specified class.

model_file_name_input

A trait for unicode strings.

model_id

Gets the model id of this widget.

parameter_file_name_input

A trait for unicode strings.

seed_input

An int trait.

simulate

A trait for unicode strings.

skewness_input

An instance of a Python list.

stdev_noise_input

A float trait.

tabbable

Is widget tabbable?

timepoints_max_input

An int trait.

timepoints_stepsize_input

A float trait.

tooltip

A tooltip caption.

use_sequential_scheme_input

A boolean (True, False) trait.

visualize_data

A boolean (True, False) trait.

wavelength_max_input

A float trait.

wavelength_min_input

A float trait.

wavelength_stepsize_input

A float trait.

widget_types

widgets

width_input

An instance of a Python list.

Methods Summary

__copy__

__deepcopy__

__del__

Object disposal

__delattr__

Implement delattr(self, name).

__dir__

Default dir() implementation.

__eq__

Return self==value.

__format__

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__getstate__

__gt__

Return self>value.

__hash__

Return hash(self).

__init__

Initialize the Widget instance and set up traitlet observers.

__init_subclass__

Coerces _esm and _css to FileContents if they are files.

__le__

Return self<=value.

__lt__

Return self<value.

__ne__

Return self!=value.

__new__

__reduce__

Helper for pickle.

__reduce_ex__

Helper for pickle.

__repr__

Return repr(self).

__setattr__

Implement setattr(self, name, value).

__setstate__

__sizeof__

Size of object in memory, in bytes.

__str__

Return str(self).

__subclasshook__

Abstract classes can override this to customize issubclass().

_add_notifiers

_call_widget_constructed

Static method, called when a widget is constructed.

_compare

_gen_repr_from_keys

_get_embed_state

_get_trait_default_generator

Return default generator for a given trait

_handle_control_comm_msg

_handle_custom_msg

Called when a custom msg is received.

_handle_msg

_is_numpy

_lock_property

Lock a property-value pair.

_notify_observers

Notify observers of any event

_notify_trait

_register_validator

Setup a handler to be called when a trait should be cross validated.

_remove_notifiers

_repr_keys

_repr_mimebundle_

_send

Sends a message to the model in the front-end.

_should_send_property

Check the property lock (property_lock)

_trait_from_json

Convert json values to objects.

_trait_to_json

Convert a trait value to json.

add_class

Adds a class to the top level element of the widget.

add_traits

Dynamically add trait attributes to the Widget.

blur

Blur the widget.

class_own_trait_events

Get a dict of all event handlers defined on this class, not a parent.

class_own_traits

Get a dict of all the traitlets defined on this class, not a parent.

class_trait_names

Get a list of all the names of this class' traits.

class_traits

Get a dict of all the traits of this class.

close

Close method.

close_all

focus

Focus on the widget.

get_manager_state

Returns the full state for a widget manager for embedding

get_state

Gets the widget state, or a piece of it.

get_view_spec

handle_comm_opened

Static method, called when a widget is constructed.

handle_control_comm_opened

Class method, called when the comm-open message on the "jupyter.widget.control" comm channel is received

has_trait

Returns True if the object has a trait with the specified name.

hold_sync

Hold syncing any state until the outermost context manager exits

hold_trait_notifications

Context manager for bundling trait change notifications and cross validation.

notify_change

Called when a property has changed.

observe

Setup a handler to be called when a trait changes.

on_msg

(Un)Register a custom msg receive callback.

on_trait_change

DEPRECATED: Setup a handler to be called when a trait changes.

on_widget_constructed

Registers a callback to be called when a widget is constructed.

open

Open a comm to the frontend if one isn't already open.

remove_class

Removes a class from the top level element of the widget.

send

Sends a custom msg to the widget model in the front-end.

send_state

Sends the widget state, or a piece of it, to the front-end, if it exists.

set_state

Called when a state is received from the front-end.

set_trait

Forcibly sets trait attribute, including read-only attributes.

setup_instance

This is called before self.__init__ is called.

trait_defaults

Return a trait's default value or a dictionary of them

trait_events

Get a dict of all the event handlers of this class.

trait_has_value

Returns True if the specified trait has a value.

trait_metadata

Get metadata values for trait by key.

trait_names

Get a list of all the names of this class' traits.

trait_values

A dict of trait names and their values.

traits

Get a dict of all the traits of this class.

unobserve

Remove a trait change handler.

unobserve_all

Remove trait change handlers of any type for the specified name.

Methods Documentation

__copy__()[source]
__deepcopy__(memo)[source]
__del__()[source]

Object disposal

__delattr__(name, /)

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__(value, /)

Return self==value.

__format__(format_spec, /)

Default object formatter.

__ge__(value, /)

Return self>=value.

__getattribute__(name, /)

Return getattr(self, name).

__getstate__() dict[str, Any]
__gt__(value, /)

Return self>value.

__hash__()

Return hash(self).

__init__()[source]

Initialize the Widget instance and set up traitlet observers.

This constructor initializes the Widget instance by calling the parent class’s initializer and sets up an observer for the ‘simulate’ traitlet. The observer triggers the _simulate function whenever the ‘simulate’ traitlet changes.

Observers:
  • simulate: Calls the _simulate function when the ‘simulate’ traitlet changes.

classmethod __init_subclass__(**kwargs: dict) None

Coerces _esm and _css to FileContents if they are files.

__le__(value, /)

Return self<=value.

__lt__(value, /)

Return self<value.

__ne__(value, /)

Return self!=value.

static __new__(*args: Any, **kwargs: Any) Any
__reduce__()

Helper for pickle.

__reduce_ex__(protocol, /)

Helper for pickle.

__repr__()[source]

Return repr(self).

__setattr__(name, value, /)

Implement setattr(self, name, value).

__setstate__(state: dict[str, Any]) None
__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

__subclasshook__()

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

_add_notifiers(handler: Callable[[...], Any], name: Sentinel | str, type: str | Sentinel) None
static _call_widget_constructed(widget)[source]

Static method, called when a widget is constructed.

_compare(a, b)[source]
_gen_repr_from_keys(keys)[source]
_get_embed_state(drop_defaults=False)[source]
_get_trait_default_generator(name: str) Any

Return default generator for a given trait

Walk the MRO to resolve the correct default generator according to inheritance.

classmethod _handle_control_comm_msg(msg)[source]
_handle_custom_msg(content, buffers)[source]

Called when a custom msg is received.

_handle_msg(*args, **kwargs)[source]
_is_numpy(x)[source]
_lock_property(**properties)[source]

Lock a property-value pair.

The value should be the JSON state of the property.

NOTE: This, in addition to the single lock for all state changes, is flawed. In the future we may want to look into buffering state changes back to the front-end.

_notify_observers(event: Bunch) None

Notify observers of any event

_notify_trait(name: str, old_value: Any, new_value: Any) None
_register_validator(handler: Callable[[...], None], names: tuple[str | Sentinel, ...]) None

Setup a handler to be called when a trait should be cross validated.

This is used to setup dynamic notifications for cross-validation.

If a validator is already registered for any of the provided names, a TraitError is raised and no new validator is registered.

Parameters:
  • handler (callable) –

    A callable that is called when the given trait is cross-validated. Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access) with the following attributes/keys:

    • owner : the HasTraits instance

    • value : the proposed value for the modified trait attribute

    • trait : the TraitType instance associated with the attribute

  • names (List of strings) – The names of the traits that should be cross-validated

_remove_notifiers(handler: Callable[[...], Any] | None, name: Sentinel | str, type: str | Sentinel) None
_repr_keys()
_repr_mimebundle_(**kwargs: dict) tuple[dict, dict] | None
_send(msg, buffers=None)[source]

Sends a message to the model in the front-end.

_should_send_property(key, value)[source]

Check the property lock (property_lock)

static _trait_from_json(x, self)[source]

Convert json values to objects.

static _trait_to_json(x, self)[source]

Convert a trait value to json.

add_class(className)

Adds a class to the top level element of the widget.

Doesn’t add the class if it already exists.

add_traits(**traits)[source]

Dynamically add trait attributes to the Widget.

blur()

Blur the widget.

classmethod class_own_trait_events(name: str) dict[str, EventHandler]

Get a dict of all event handlers defined on this class, not a parent.

Works like event_handlers, except for excluding traits from parents.

classmethod class_own_traits(**metadata: Any) dict[str, TraitType[Any, Any]]

Get a dict of all the traitlets defined on this class, not a parent.

Works like class_traits, except for excluding traits from parents.

classmethod class_trait_names(**metadata: Any) list[str]

Get a list of all the names of this class’ traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata: Any) dict[str, TraitType[Any, Any]]

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

close()[source]

Close method.

Closes the underlying comm. When the comm is closed, all of the widget views are automatically removed from the front-end.

classmethod close_all()[source]
focus()

Focus on the widget.

static get_manager_state(drop_defaults=False, widgets=None)[source]

Returns the full state for a widget manager for embedding

Parameters:
  • drop_defaults – when True, it will not include default value

  • widgets – list with widgets to include in the state (or all widgets when None)

Returns:

get_state(key=None, drop_defaults=False)[source]

Gets the widget state, or a piece of it.

Parameters:

key (unicode or iterable (optional)) – A single property’s name or iterable of property names to get.

Returns:

  • state (dict of states)

  • metadata (dict) – metadata for each field: {key: metadata}

get_view_spec()[source]
static handle_comm_opened(comm, msg)[source]

Static method, called when a widget is constructed.

classmethod handle_control_comm_opened(comm, msg)[source]

Class method, called when the comm-open message on the “jupyter.widget.control” comm channel is received

has_trait(name: str) bool

Returns True if the object has a trait with the specified name.

hold_sync()[source]

Hold syncing any state until the outermost context manager exits

hold_trait_notifications() Any

Context manager for bundling trait change notifications and cross validation.

Use this when doing multiple trait assignments (init, config), to avoid race conditions in trait notifiers requesting other trait values. All trait notifications will fire after all values have been assigned.

notify_change(change)[source]

Called when a property has changed.

observe(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters:
  • handler (callable) – A callable that is called when a trait changes. Its signature should be handler(change), where change is a dictionary. The change dictionary at least holds a ‘type’ key. * type: the type of notification. Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: * owner : the HasTraits instance * old : the old value of the modified trait attribute * new : the new value of the modified trait attribute * name : the name of the modified trait attribute.

  • names (list, str, All) – If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

  • type (str, All (default: 'change')) – The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler.

on_msg(callback, remove=False)[source]

(Un)Register a custom msg receive callback.

Parameters:
  • callback (callable) –

    callback will be passed three arguments when a message arrives:

    callback(widget, content, buffers)
    

  • remove (bool) – True if the callback should be unregistered.

on_trait_change(handler: EventHandler | None = None, name: Sentinel | str | None = None, remove: bool = False) None

DEPRECATED: Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

If remove is True and handler is not specified, all change handlers for the specified name are uninstalled.

Parameters:
  • handler (callable, None) – A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self).

  • name (list, str, None) – If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

  • remove (bool) – If False (the default), then install the handler. If True then unintall it.

static on_widget_constructed(callback)[source]

Registers a callback to be called when a widget is constructed.

The callback must have the following signature: callback(widget)

open()[source]

Open a comm to the frontend if one isn’t already open.

remove_class(className)

Removes a class from the top level element of the widget.

Doesn’t remove the class if it doesn’t exist.

send(content, buffers=None)[source]

Sends a custom msg to the widget model in the front-end.

Parameters:
  • content (dict) – Content of the message to send.

  • buffers (list of binary buffers) – Binary buffers to send with message

send_state(key=None)[source]

Sends the widget state, or a piece of it, to the front-end, if it exists.

Parameters:

key (unicode, or iterable (optional)) – A single property’s name or iterable of property names to sync with the front-end.

set_state(sync_data)[source]

Called when a state is received from the front-end.

set_trait(name: str, value: Any) None

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs: Any) None

This is called before self.__init__ is called.

trait_defaults(*names: str, **metadata: Any) dict[str, Any] | Sentinel

Return a trait’s default value or a dictionary of them

Notes

Dynamically generated default values may depend on the current state of the object.

classmethod trait_events(name: str | None = None) dict[str, EventHandler]

Get a dict of all the event handlers of this class.

Parameters:

name (str (default: None)) – The name of a trait of this class. If name is None then all the event handlers of this class will be returned instead.

Return type:

The event handlers associated with a trait name, or all event handlers.

trait_has_value(name: str) bool

Returns True if the specified trait has a value.

This will return false even if getattr would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated.

Example

class MyClass(HasTraits):
    i = Int()


mc = MyClass()
assert not mc.trait_has_value("i")
mc.i  # generates a default value
assert mc.trait_has_value("i")
trait_metadata(traitname: str, key: str, default: Any | None = None) Any

Get metadata values for trait by key.

trait_names(**metadata: Any) list[str]

Get a list of all the names of this class’ traits.

trait_values(**metadata: Any) dict[str, Any]

A dict of trait names and their values.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

Return type:

A dict of trait names and their values.

Notes

Trait values are retrieved via getattr, any exceptions raised by traits or the operations they may trigger will result in the absence of a trait value in the result dict.

traits(**metadata: Any) dict[str, TraitType[Any, Any]]

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

unobserve(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters:
  • handler (callable) – The callable called when a trait attribute changes.

  • names (list, str, All (default: All)) – The names of the traits for which the specified handler should be uninstalled. If names is All, the specified handler is uninstalled from the list of notifiers corresponding to all changes.

  • type (str or All (default: 'change')) – The type of notification to filter by. If All, the specified handler is uninstalled from the list of notifiers corresponding to all types.

unobserve_all(name: str | Any = traitlets.All) None

Remove trait change handlers of any type for the specified name. If name is not specified, removes all trait notifiers.