Пример #1
0
class SegTrack(Track):
    """
    SegTrack Track as described at:
    https://github.com/igvteam/igv.js/wiki/Seg-Track
    """

    type = Unicode('seg', read_only=True).tag(sync=True)
    isLog = Bool(allow_none=True).tag(sync=True, **widget_serialization_no_none)
    displayMode = Unicode("EXPANDED").tag(sync=True) #  "EXPANDED", "SQUISHED", or "FILL"
    sort = InstanceDict(SortOrder).tag(sync=True, **widget_serialization)

    roi = List(InstanceDict(Track)).tag(sync=True, **widget_serialization_no_none) # regions of interest
Пример #2
0
class SpliceJunctionsTrack(Track):
    """
    SpliceJunctionsTrack as described at:
    https://github.com/igvteam/igv.js/wiki/SpliceJunctions
    """

    type = Unicode('spliceJunctions', read_only=True).tag(sync=True)
    # Display Options
    colorBy = Unicode('numUniqueReads').tag(sync=True) # "numUniqueReads", "numReads", "isAnnotatedJunction", "strand", "motif"
    colorByNumReadsThreshold = Int(5).tag(sync=True)
    thicknessBasedOn = Unicode('numUniqueReads').tag(sync=True) # "numUniqueReads", "numReads", "isAnnotatedJunction"
    bounceHeightBasedOn = Unicode('random').tag(sync=True) # "random", "distance", "thickness"
    labelUniqueReadCount = Bool(True).tag(sync=True)
    labelMultiMappedReadCount = Bool(True).tag(sync=True)
    labelTotalReadCount = Bool(False).tag(sync=True)
    labelMotif = Bool(False).tag(sync=True)
    labelAnnotatedJunction = Unicode(allow_none=True).tag(sync=True, **widget_serialization_no_none)

    # Filtering Options
    minUniquelyMappedReads = Int(0).tag(sync=True)
    minTotalReads = Int(0).tag(sync=True)
    maxFractionMultiMappedReads = Int(1).tag(sync=True)
    minSplicedAlignmentOverhang = Int(0).tag(sync=True)
    hideStrand = Unicode(allow_none=True).tag(sync=True, **widget_serialization_no_none) # None, "+" or "-"
    hideAnnotatedJunctions = Bool(False).tag(sync=True)
    hideUnannotatedJunctions = Bool(False).tag(sync=True)
    hideMotifs = List(Unicode).tag(sync=True, **widget_serialization)

    roi = List(InstanceDict(Track)).tag(sync=True, **widget_serialization_no_none) # regions of interest
Пример #3
0
class BeakerxBox(Box):
    def __init__(self, **kwargs):
        super(BeakerxBox, self).__init__(**kwargs)
        self.components = dict()

    _view_module = Unicode('@jupyter-widgets/controls').tag(sync=True)
    _model_module = Unicode('@jupyter-widgets/controls').tag(sync=True)
    _model_module_version = Unicode('*').tag(sync=True)
    _view_module_version = Unicode('*').tag(sync=True)

    layout = InstanceDict(BeakerxLayout).tag(sync=True, **widget_serialization)

    def _ipython_display_(self, **kwargs):
        data = {
            'application/vnd.jupyter.widget-view+json': {
                'version_major': 2,
                'version_minor': 0,
                'model_id': self._model_id
            },
            'method': 'display_data'
        },
        for component in self.components:
            self.components[component].fireInit()

        display(data, raw=True)

        self._handle_displayed(**kwargs)
Пример #4
0
class ReferenceGenome(Widget):
    """
    A class reflecting a reference genome as per IGV documentation.
    https://github.com/igvteam/igv.js/wiki/Reference-Genome
    """

    # Name of the widget view class in front-end
    _view_name = Unicode('ReferenceGenomeView').tag(sync=True)
    # Name of the widget model class in front-end
    _model_name = Unicode('ReferenceGenomeModel').tag(sync=True)
    # Name of the front-end module containing widget view
    _view_module = Unicode('jupyter-igv').tag(sync=True)
    # Name of the front-end module containing widget model
    _model_module = Unicode('jupyter-igv').tag(sync=True)
    # Version of the front-end module containing widget view
    _view_module_version = Unicode(EXTENSION_VERSION).tag(sync=True)
    # Version of the front-end module containing widget model
    _model_module_version = Unicode(EXTENSION_VERSION).tag(sync=True)

    id = Unicode(allow_none=True).tag(sync=True)
    name = Unicode(allow_none=True).tag(sync=True)
    fastaURL = Unicode().tag(sync=True)
    indexURL = Unicode(allow_none=True).tag(sync=True)
    cytobandURL = Unicode(allow_none=True).tag(sync=True)
    aliasURL = Unicode(allow_none=True).tag(sync=True)
    indexed = Bool(default_value=False).tag(sync=True)
    tracks = List(InstanceDict(Track)).tag(sync=True, **widget_serialization_no_none)
    chromosomeOrder = Unicode(allow_none=True).tag(sync=True)
    headers = Dict().tag(sync=True)
    wholeGenomeView = Bool(default_value=True).tag(sync=True)
Пример #5
0
class AlignmentTrack(Track):
    """
    AlignmentTrack as described at:
    https://github.com/igvteam/igv.js/wiki/Alignment-Track
    """

    type = Unicode('alignment', read_only=True).tag(sync=True)
    viewAsPairs = Bool(default_value=False).tag(sync=True)
    pairsSupported = Bool(default_value=True).tag(sync=True)
    coverageColor = Color(default_value="rgb(150, 150, 150)").tag(sync=True, **widget_serialization) # default: rgb(150, 150, 150)
    color = Color(default_value="rgb(170, 170, 170)").tag(sync=True, **widget_serialization) # default: rgb(170, 170, 170)
    deletionColor = Color(default_value="black").tag(sync=True, **widget_serialization)
    skippedColor = Color(default_value="rgb(150, 170, 170)").tag(sync=True, **widget_serialization) # default: rgb(150, 170, 170)
    insertionColor = Color(default_value="rgb(138, 94, 161)").tag(sync=True, **widget_serialization) # default: rgb(138, 94, 161)
    negStrandColor = Color(default_value="rgba(150, 150, 230, 0.75)").tag(sync=True, **widget_serialization) # default: rgba(150, 150, 230, 0.75)
    posStrandColor = Color(default_value="rgba(230, 150, 150, 0.75)").tag(sync=True, **widget_serialization) # default: rgb(138, 94, 161)
    # pairConnectorColor = Instance(Color, default_value="alignmentColor") # default: doc not clear
    colorBy = Unicode("none").tag(sync=True) # "none", "strand", "firstOfPairStrand", or "tag"
    colorByTag = Unicode().tag(sync=True) # TODO - doc not clear
    bamColorTag = Unicode("YC").tag(sync=True) # TODO - doc not clear
    samplingWindowSize = Int(100).tag(sync=True)
    samplingDepth = Int(100).tag(sync=True)
    alignmentRowHeight = Int(14).tag(sync=True)
    readgroup = Unicode("RG").tag(sync=True)
    sortOption = Instance(SortOption, allow_none=True).tag(sync=True, **widget_serialization_no_none)
    showSoftClips = Bool(False).tag(sync=True)
    showMismatches = Bool(True).tag(sync=True)

    # Paired-end and mate-pair coloring options.
    pairOrientation  = Unicode(allow_none=True).tag(sync=True, **widget_serialization_no_none)  #  ff, fr, or rf
    minFragmentLength = Int(allow_none=True).tag(sync=True, **widget_serialization_no_none)
    maxFragmentLength = Int(allow_none=True).tag(sync=True, **widget_serialization_no_none)

    roi = List(InstanceDict(Track)).tag(sync=True, **widget_serialization_no_none) # regions of interest
Пример #6
0
class FloatRangeSlider(_FloatRangeSlider.__base__):
    """ This is a fixed slider widget implementation, allowing values lower
    than 10^-6. This class should be removed at some point, when the slider
    implementation is fixed in ipywidgets. """
    _view_name = Unicode('FixedFloatRangeSliderView').tag(sync=True)
    _model_name = Unicode('FixedFloatRangeSliderModel').tag(sync=True)
    _view_module = Unicode('odysis').tag(sync=True)
    _model_module = Unicode('odysis').tag(sync=True)
    _view_module_version = Unicode(odysis_version).tag(sync=True)
    _model_module_version = Unicode(odysis_version).tag(sync=True)

    step = CFloat(0.01,
                  help="Minimum step to increment the value").tag(sync=True)
    orientation = CaselessStrEnum(
        values=['horizontal', 'vertical'],
        default_value='horizontal',
        help="Vertical or horizontal.").tag(sync=True)
    readout = Bool(
        True, help="Display the current value of the slider next to it.").tag(
            sync=True)
    readout_format = NumberFormat('.2e',
                                  help="Format for the readout").tag(sync=True)
    continuous_update = Bool(
        True,
        help="Update the value of the widget as the user is sliding the slider."
    ).tag(sync=True)
    disabled = Bool(False,
                    help="Enable or disable user changes").tag(sync=True)

    style = InstanceDict(SliderStyle).tag(sync=True, **widget_serialization)
class ExecuteButton(DOMWidget):
    _view_name = Unicode('ExecuteButtonView').tag(sync=True)
    _model_name = Unicode('ExecuteButtonModel').tag(sync=True)
    _view_module = Unicode('jupyter-button_execute').tag(sync=True)
    _model_module = Unicode('jupyter-button_execute').tag(sync=True)
    _view_module_version = Unicode('^0.4.0').tag(sync=True)
    _model_module_version = Unicode('^0.4.0').tag(sync=True)

    # Attributes
    button_text = Unicode('Execute next cells',
                          help="The button's caption.").tag(sync=True)
    n_next_cells = Int(1,
                       help="The number of cells to execute.").tag(sync=True)
    disabled = Bool(False, help="Disable the button").tag(sync=True)

    button_style = CaselessStrEnum(
        values=['primary', 'success', 'info', 'warning', 'danger', ''],
        default_value='',
        help="""Use a predefined styling for the button.""").tag(sync=True)

    style = InstanceDict(ButtonStyle).tag(sync=True, **widget_serialization)

    def __init__(self, **kwargs):
        super(ExecuteButton, self).__init__(**kwargs)
        self._click_handlers = CallbackDispatcher()
        self.on_msg(self._handle_button_msg)

    def on_click(self, callback, remove=False):
        """Register a callback to execute when the button is clicked.
        The callback will be called with one argument, the clicked button
        widget instance.
        Parameters
        ----------
        callback: The function to call
        remove: bool (optional)
            Set to true to remove the callback from the list of callbacks.
        """
        self._click_handlers.register_callback(callback, remove=remove)

    def click(self):
        """Programmatically trigger a click event.
        This will call the callbacks registered to the clicked button
        widget instance.
        """
        self._click_handlers(self)

    def _handle_button_msg(self, _, content, buffers):
        """Handle a msg from the front-end.
        Parameters
        ----------
        content: dict
            Content of the msg.
        """
        if content.get('event', '') == 'click':
            self.click()
Пример #8
0
class Event(CoreWidget):
    _model_name = Unicode('EventModel').tag(sync=True)
    _model_module = Unicode('ipyevents').tag(sync=True)
    source = InstanceDict(DOMWidget).tag(sync=True, **widget_serialization)
    watched_events = List().tag(sync=True)
    ignore_modifier_key_events = Bool(False).tag(sync=True)
    prevent_default_action = Bool(False).tag(sync=True)
    _supported_mouse_events = List([
        'click', 'auxclick', 'dblclick', 'mouseenter', 'mouseleave',
        'mousedown', 'mouseup', 'mousemove', 'wheel', 'contextmenu',
        'dragstart', 'drag', 'dragend', 'dragenter', 'dragover', 'dragleave',
        'drop'
    ]).tag(sync=True)
    _supported_key_events = List(['keydown', 'keyup']).tag(sync=True)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._dom_handlers = CallbackDispatcher()
        self.on_msg(self._handle_mouse_msg)

    @property
    def supported_key_events(self):
        return self._supported_key_events

    @property
    def supported_mouse_events(self):
        return self._supported_mouse_events

    @validate('watched_events')
    def _validate_watched_events(self, proposal):
        value = proposal['value']
        bad_events = [
            v for v in value if v not in self._supported_mouse_events +
            self._supported_key_events
        ]
        if bad_events:
            raise ValueError('The event(s) {} are not '
                             'supported.'.format(bad_events))
        return value

    def on_dom_event(self, callback, remove=False):
        """Register a callback to execute when a DOM event occurs.

        The callback will be called with one argument, an dict whose keys
        depend on the type of event.

        Parameters
        ----------
        remove: bool (optional)
            Set to true to remove the callback from the list of callbacks.
        """
        self._dom_handlers.register_callback(callback, remove=remove)

    def _handle_mouse_msg(self, _, content, buffers):
        self._dom_handlers(content)
Пример #9
0
class BeakerxHTML(HTML, EasyFormComponent):
    def __init__(self, *args, **kwargs):
        super(BeakerxHTML, self).__init__(**kwargs)
        if len(args) > 0:
            self.value = args[0]

    _model_module_version = Unicode('*').tag(sync=True)
    _view_module_version = Unicode('*').tag(sync=True)

    layout = InstanceDict(BeakerxLayout).tag(sync=True, **widget_serialization)
    style = None
Пример #10
0
class BeakerxCheckbox(Checkbox, EasyFormComponent):
    def __init__(self, **kwargs):
        super(BeakerxCheckbox, self).__init__(**kwargs)

    _view_module = Unicode('beakerx').tag(sync=True)
    _model_module = Unicode('beakerx').tag(sync=True)
    _model_module_version = Unicode('*').tag(sync=True)
    _view_module_version = Unicode('*').tag(sync=True)

    layout = InstanceDict(BeakerxLayout).tag(sync=True, **widget_serialization)
    style = None
Пример #11
0
class BeakerxVBox(VBox):
    def __init__(self, **kwargs):
        super(BeakerxVBox, self).__init__(**kwargs)

    _view_module = Unicode('@jupyter-widgets/controls').tag(sync=True)
    _model_module = Unicode('@jupyter-widgets/controls').tag(sync=True)
    _model_module_version = Unicode('*').tag(sync=True)
    _view_module_version = Unicode('*').tag(sync=True)

    layout = InstanceDict(BeakerxLayout).tag(sync=True, **widget_serialization)
    style = None
Пример #12
0
class InteractionTrack (Track):
    """
    InteractionTrack as described at:
    https://github.com/igvteam/igv.js/wiki/Interaction
    """

    type = Unicode('interaction', read_only=True).tag(sync=True)
    arcOrientation = Bool(True).tag(sync=True)
    thickness = Int(2).tag(sync=True)

    roi = List(InstanceDict(Track)).tag(sync=True, **widget_serialization_no_none) # regions of interest
Пример #13
0
class BeakerxTextArea(Textarea, EasyFormComponent):
    def __init__(self, **kwargs):
        super(BeakerxTextArea, self).__init__(**kwargs)

    _view_module = Unicode('beakerx').tag(sync=True)
    _model_module = Unicode('beakerx').tag(sync=True)
    _model_module_version = Unicode('*').tag(sync=True)
    _view_module_version = Unicode('*').tag(sync=True)

    cols = Int(default_value=-1).tag(sync=True)
    rows = Int(default_value=-1).tag(sync=True)
    layout = InstanceDict(BeakerxLayout).tag(sync=True, **widget_serialization)
    style = None
Пример #14
0
class BeakerxHBox(HBox):
    def __init__(self, children=None, **kwargs):
        super(BeakerxHBox, self).__init__(**kwargs)
        if children is not None:
            self.children += tuple(children)

    _view_module = Unicode('@jupyter-widgets/controls').tag(sync=True)
    _model_module = Unicode('@jupyter-widgets/controls').tag(sync=True)
    _model_module_version = Unicode('*').tag(sync=True)
    _view_module_version = Unicode('*').tag(sync=True)

    layout = InstanceDict(BeakerxLayout).tag(sync=True, **widget_serialization)
    style = None
Пример #15
0
class GwasTrack (Track):
    """
    GwasTrack as described at:
    https://github.com/igvteam/igv.js/wiki/GWAS
    """

    type = Unicode('gwas', read_only=True).tag(sync=True)
    min = Int(0).tag(sync=True)
    max = Int(25).tag(sync=True)
    # format = Unicode().tag(sync=True) #  'bed' or 'gwas' - format is already in Track -> validation only
    posteriorProbability = Bool(False).tag(sync=True)
    dotSize = Int(3).tag(sync=True)
    columns = Dict(key_trait=Unicode, value_trait=Int, allow_none=True).tag(sync=True, **widget_serialization_no_none)

    roi = List(InstanceDict(Track)).tag(sync=True, **widget_serialization_no_none) # regions of interest
Пример #16
0
class BeakerxButton(Button, EasyFormComponent):
    def __init__(self, **kwargs):
        super(BeakerxButton, self).__init__(**kwargs)

    _view_module = Unicode('@jupyter-widgets/controls').tag(sync=True)
    _model_module = Unicode('@jupyter-widgets/controls').tag(sync=True)
    _model_module_version = Unicode('*').tag(sync=True)
    _view_module_version = Unicode('*').tag(sync=True)
    align_self = Unicode('*').tag(sync=True)

    layout = InstanceDict(BeakerxLayout).tag(sync=True, **widget_serialization)
    style = None

    def actionPerformed(self, *args, **kwargs):
        pass
Пример #17
0
class BeakerxPassword(Password, EasyFormComponent):
    def on_value_change(self, change):
        self.fireChanged(change['new'])

    def __init__(self, **kwargs):
        super(BeakerxPassword, self).__init__(**kwargs)
        self.observe(self.on_value_change, names='value')

    _view_module = Unicode('beakerx').tag(sync=True)
    _model_module = Unicode('beakerx').tag(sync=True)
    _model_module_version = Unicode('*').tag(sync=True)
    _view_module_version = Unicode('*').tag(sync=True)

    size = Int(default_value=-1).tag(sync=True)
    layout = InstanceDict(BeakerxLayout).tag(sync=True, **widget_serialization)
    style = None
Пример #18
0
class VariantTrack(Track):
    """
    VariantTrack as described at:
    https://github.com/igvteam/igv.js/wiki/Variant-Track
    """

    type = Unicode('variant', read_only=True).tag(sync=True)
    displayMode = Unicode('EXPANDED').tag(sync=True)
    noCallColor = Color("rgb(250, 250, 250)").tag(sync=True)
    homvarColor = Color("rgb(17,248,254)").tag(sync=True)
    hetvarColor = Color("rgb(34,12,253)").tag(sync=True)
    homrefColor = Color("rgb(200, 200, 200)").tag(sync=True)
    squishedCallHeight = Int(1).tag(sync=True)
    expandedCallHeight = Int(10).tag(sync=True)

    roi = List(InstanceDict(Track)).tag(sync=True, **widget_serialization_no_none) # regions of interest
Пример #19
0
class WigTrack(Track):
    """
    WigTrack as described at:
    https://github.com/igvteam/igv.js/wiki/Wig-Track
    """

    type = Unicode('wig', read_only=True).tag(sync=True)
    autoscale = Bool(True).tag(sync=True)
    autoscaleGroup = Unicode(allow_none=True).tag(sync=True, **widget_serialization_no_none)
    min = Int(0).tag(sync=True)
    max = Int(allow_none=True).tag(sync=True, **widget_serialization_no_none)
    color = Color(default_value="rgb(150, 150, 150)").tag(sync=True)
    altColor = Color(allow_none=True).tag(sync=True, **widget_serialization_no_none)
    guideLines = List(trait=Instance(Guideline), allow_none=True).tag(sync=True, **widget_serialization_no_none)

    roi = List(InstanceDict(Track)).tag(sync=True, **widget_serialization_no_none) # regions of interest
Пример #20
0
class AnnotationTrack(Track):
    """
    AnnotationTrack as described at:
    https://github.com/igvteam/igv.js/wiki/Annotation-Track
    """

    type = Unicode('annotation', read_only=True).tag(sync=True)
    displayMode = Unicode(default_value = 'COLLAPSED').tag(sync=True)
    expandedRowHeight = Int (default_value = 30).tag(sync=True)
    squishedRowHeight = Int (default_value = 15).tag(sync=True)
    nameField = Unicode(default_value = 'Name').tag(sync=True)
    maxRows = Int (default_value = 500).tag(sync=True)
    searchable = Bool(default_value=False).tag(sync=True)
    filterTypes = List(Unicode, default_value=['chromosone', 'gene']).tag(sync=True, **widget_serialization_no_none)
    color = Color("rgb(0,0,150)").tag(sync=True)
    altColor = Color("rgb(0,0,150)").tag(sync=True)
    colorBy = Instance(FieldColors, allow_none=True).tag(sync=True, **widget_serialization_no_none)
    roi = List(InstanceDict(Track)).tag(sync=True, **widget_serialization_no_none) # regions of interest
Пример #21
0
class ToggleButtons(_Selection):
    """Group of toggle buttons that represent an enumeration.

    Only one toggle button can be toggled at any point in time.

    Parameters
    ----------
    {selection_params}

    tooltips: list
        Tooltip for each button. If specified, must be the
        same length as `options`.

    icons: list
        Icons to show on the buttons. This must be the name
        of a font-awesome icon. See `http://fontawesome.io/icons/`
        for a list of icons.

    button_style: str
        One of 'primary', 'success', 'info', 'warning' or
        'danger'. Applies a predefined style to every button.

    style: ToggleButtonsStyle
        Style parameters for the buttons.
    """
    _view_name = Unicode('ToggleButtonsView').tag(sync=True)
    _model_name = Unicode('ToggleButtonsModel').tag(sync=True)

    tooltips = TypedTuple(Unicode(),
                          help="Tooltips for each button.").tag(sync=True)
    icons = TypedTuple(
        Unicode(),
        help=
        "Icons names for each button (FontAwesome names without the fa- prefix)."
    ).tag(sync=True)
    style = InstanceDict(ToggleButtonsStyle).tag(sync=True,
                                                 **widget_serialization)

    button_style = CaselessStrEnum(
        values=['primary', 'success', 'info', 'warning', 'danger', ''],
        default_value='',
        allow_none=True,
        help="""Use a predefined styling for the buttons.""").tag(sync=True)
Пример #22
0
class BeakerxDOMWidget(DOMWidget):
    _model_module_version = Unicode('*').tag(sync=True)
    _view_module_version = Unicode('*').tag(sync=True)
    _view_module = Unicode('@jupyter-widgets/controls').tag(sync=True)
    _model_module = Unicode('@jupyter-widgets/controls').tag(sync=True)

    def __init__(self, **kwargs):
        super(BeakerxDOMWidget, self).__init__(**kwargs)

    layout = InstanceDict(BeakerxLayout).tag(sync=True, **widget_serialization)

    def _ipython_display_(self, **kwargs):
        data = {
            'application/vnd.jupyter.widget-view+json': {
                'version_major': 2,
                'version_minor': 0,
                'model_id': self._model_id
            }
        }
        display(data, raw=True)

        self._handle_displayed(**kwargs)
Пример #23
0
class Map(DOMWidget, InteractMixin):
    _view_name = Unicode('LeafletMapView').tag(sync=True)
    _model_name = Unicode('LeafletMapModel').tag(sync=True)
    _view_module = Unicode('jupyter-leaflet').tag(sync=True)
    _model_module = Unicode('jupyter-leaflet').tag(sync=True)

    _view_module_version = Unicode(EXTENSION_VERSION).tag(sync=True)
    _model_module_version = Unicode(EXTENSION_VERSION).tag(sync=True)

    # Map options
    center = List(def_loc).tag(sync=True, o=True)
    zoom_start = Int(12).tag(sync=True, o=True)
    zoom = Int(12).tag(sync=True, o=True)
    max_zoom = Int(18).tag(sync=True, o=True)
    min_zoom = Int(1).tag(sync=True, o=True)
    interpolation = Unicode('bilinear').tag(sync=True, o=True)
    crs = Enum(values=allowed_crs, default_value='EPSG3857').tag(sync=True)

    # Specification of the basemap
    basemap = Union(
        (Dict(), Instance(TileLayer)),
        default_value=dict(
            url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
            max_zoom=19,
            attribution=
            'Map data (c) <a href="https://openstreetmap.org">OpenStreetMap</a> contributors'
        ))
    modisdate = Unicode('yesterday').tag(sync=True)

    # Interaction options
    dragging = Bool(True).tag(sync=True, o=True)
    touch_zoom = Bool(True).tag(sync=True, o=True)
    scroll_wheel_zoom = Bool(False).tag(sync=True, o=True)
    double_click_zoom = Bool(True).tag(sync=True, o=True)
    box_zoom = Bool(True).tag(sync=True, o=True)
    tap = Bool(True).tag(sync=True, o=True)
    tap_tolerance = Int(15).tag(sync=True, o=True)
    world_copy_jump = Bool(False).tag(sync=True, o=True)
    close_popup_on_click = Bool(True).tag(sync=True, o=True)
    bounce_at_zoom_limits = Bool(True).tag(sync=True, o=True)
    keyboard = Bool(True).tag(sync=True, o=True)
    keyboard_pan_offset = Int(80).tag(sync=True, o=True)
    keyboard_zoom_offset = Int(1).tag(sync=True, o=True)
    inertia = Bool(True).tag(sync=True, o=True)
    inertia_deceleration = Int(3000).tag(sync=True, o=True)
    inertia_max_speed = Int(1500).tag(sync=True, o=True)
    # inertia_threshold = Int(?, o=True).tag(sync=True)
    # fade_animation = Bool(?).tag(sync=True, o=True)
    # zoom_animation = Bool(?).tag(sync=True, o=True)
    zoom_animation_threshold = Int(4).tag(sync=True, o=True)
    # marker_zoom_animation = Bool(?).tag(sync=True, o=True)
    fullscreen = Bool(False).tag(sync=True, o=True)

    options = List(trait=Unicode()).tag(sync=True)

    style = InstanceDict(MapStyle).tag(sync=True, **widget_serialization)
    default_style = InstanceDict(MapStyle).tag(sync=True,
                                               **widget_serialization)
    dragging_style = InstanceDict(MapStyle).tag(sync=True,
                                                **widget_serialization)

    zoom_control = Bool(True)
    attribution_control = Bool(True)

    @default('dragging_style')
    def _default_dragging_style(self):
        return {'cursor': 'move'}

    @default('options')
    def _default_options(self):
        return [name for name in self.traits(o=True)]

    south = Float(def_loc[0], read_only=True).tag(sync=True)
    north = Float(def_loc[0], read_only=True).tag(sync=True)
    east = Float(def_loc[1], read_only=True).tag(sync=True)
    west = Float(def_loc[1], read_only=True).tag(sync=True)

    layers = Tuple().tag(trait=Instance(Layer),
                         sync=True,
                         **widget_serialization)

    @default('layers')
    def _default_layers(self):
        basemap = self.basemap if isinstance(self.basemap,
                                             TileLayer) else basemap_to_tiles(
                                                 self.basemap, self.modisdate)

        basemap.base = True

        return (basemap, )

    bounds = Tuple(read_only=True)
    bounds_polygon = Tuple(read_only=True)

    @observe('south', 'north', 'east', 'west')
    def _observe_bounds(self, change):
        self.set_trait('bounds',
                       ((self.south, self.west), (self.north, self.east)))
        self.set_trait('bounds_polygon',
                       ((self.north, self.west), (self.north, self.east),
                        (self.south, self.east), (self.south, self.west)))

    def __init__(self, **kwargs):
        self.zoom_control_instance = None
        self.attribution_control_instance = None

        super(Map, self).__init__(**kwargs)
        self.on_msg(self._handle_leaflet_event)

        if self.zoom_control:
            self.zoom_control_instance = ZoomControl()
            self.add_control(self.zoom_control_instance)

        if self.attribution_control:
            self.attribution_control_instance = AttributionControl(
                position='bottomright')
            self.add_control(self.attribution_control_instance)

    @observe('zoom_control')
    def observe_zoom_control(self, change):
        if change['new']:
            self.zoom_control_instance = ZoomControl()
            self.add_control(self.zoom_control_instance)
        else:
            if self.zoom_control_instance is not None and self.zoom_control_instance in self.controls:
                self.remove_control(self.zoom_control_instance)

    @observe('attribution_control')
    def observe_attribution_control(self, change):
        if change['new']:
            self.attribution_control_instance = AttributionControl(
                position='bottomright')
            self.add_control(self.attribution_control_instance)
        else:
            if self.attribution_control_instance is not None and self.attribution_control_instance in self.controls:
                self.remove_control(self.attribution_control_instance)

    _layer_ids = List()

    @validate('layers')
    def _validate_layers(self, proposal):
        '''Validate layers list.

        Makes sure only one instance of any given layer can exist in the
        layers list.
        '''
        self._layer_ids = [l.model_id for l in proposal.value]
        if len(set(self._layer_ids)) != len(self._layer_ids):
            raise LayerException(
                'duplicate layer detected, only use each layer once')
        return proposal.value

    def add_layer(self, layer):
        if isinstance(layer, dict):
            layer = basemap_to_tiles(layer)
        if layer.model_id in self._layer_ids:
            raise LayerException('layer already on map: %r' % layer)
        self.layers = tuple([l for l in self.layers] + [layer])

    def remove_layer(self, layer):
        if layer.model_id not in self._layer_ids:
            raise LayerException('layer not on map: %r' % layer)
        self.layers = tuple(
            [l for l in self.layers if l.model_id != layer.model_id])

    def substitute_layer(self, old, new):
        if isinstance(new, dict):
            new = basemap_to_tiles(new)
        if old.model_id not in self._layer_ids:
            raise LayerException(
                'Could not substitute layer: layer not on map.')
        self.layers = tuple(
            [new if l.model_id == old.model_id else l for l in self.layers])

    def clear_layers(self):
        self.layers = ()

    controls = Tuple().tag(trait=Instance(Control),
                           sync=True,
                           **widget_serialization)
    _control_ids = List()

    @validate('controls')
    def _validate_controls(self, proposal):
        '''Validate controls list.

        Makes sure only one instance of any given layer can exist in the
        controls list.
        '''
        self._control_ids = [c.model_id for c in proposal.value]
        if len(set(self._control_ids)) != len(self._control_ids):
            raise ControlException(
                'duplicate control detected, only use each control once')
        return proposal.value

    def add_control(self, control):
        if control.model_id in self._control_ids:
            raise ControlException('control already on map: %r' % control)
        self.controls = tuple([c for c in self.controls] + [control])

    def remove_control(self, control):
        if control.model_id not in self._control_ids:
            raise ControlException('control not on map: %r' % control)
        self.controls = tuple(
            [c for c in self.controls if c.model_id != control.model_id])

    def clear_controls(self):
        self.controls = ()

    def __iadd__(self, item):
        if isinstance(item, Layer):
            self.add_layer(item)
        elif isinstance(item, Control):
            self.add_control(item)
        return self

    def __isub__(self, item):
        if isinstance(item, Layer):
            self.remove_layer(item)
        elif isinstance(item, Control):
            self.remove_control(item)
        return self

    def __add__(self, item):
        if isinstance(item, Layer):
            self.add_layer(item)
        elif isinstance(item, Control):
            self.add_control(item)
        return self

    # Event handling
    _interaction_callbacks = Instance(CallbackDispatcher, ())

    def _handle_leaflet_event(self, _, content, buffers):
        if content.get('event', '') == 'interaction':
            self._interaction_callbacks(**content)

    def on_interaction(self, callback, remove=False):
        self._interaction_callbacks.register_callback(callback, remove=remove)
Пример #24
0
class IgvBrowser(widgets.DOMWidget):
    """An IGV browser widget."""
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.on_msg(self._custom_message_handler)

    out = widgets.Output()

    # Name of the widget view class in front-end
    _view_name = Unicode('IgvBrowser').tag(sync=True)
    # Name of the widget model class in front-end
    _model_name = Unicode('IgvModel').tag(sync=True)
    # Name of the front-end module containing widget view
    _view_module = Unicode('jupyter-igv').tag(sync=True)
    # Name of the front-end module containing widget model
    _model_module = Unicode('jupyter-igv').tag(sync=True)
    # Version of the front-end module containing widget view
    _view_module_version = Unicode(EXTENSION_VERSION).tag(sync=True)
    # Version of the front-end module containing widget model
    _model_module_version = Unicode(EXTENSION_VERSION).tag(sync=True)

    # Widget specific property.
    # Widget properties are defined as traitlets. Any property tagged with `sync=True`
    # is automatically synced to the frontend *any* time it changes in Python.
    # It is synced back to Python from the frontend *any* time the model is touched.
    genome = InstanceDict(ReferenceGenome).tag(sync=True,
                                               **widget_serialization_no_none)
    tracks = List(InstanceDict(Track)).tag(sync=True,
                                           **widget_serialization_no_none)
    doubleClickDelay = Int(default_value=500).tag(sync=True)
    flanking = Int(default_value=1000).tag(sync=True)
    genomeList = Unicode(allow_none=True).tag(
        sync=True, **widget_serialization_no_none)  # optional URL
    locus = (Unicode() | List(Unicode())).tag(sync=True,
                                              **widget_serialization_no_none)
    minimumBases = Int(default_value=40).tag(sync=True)
    queryParametersSupported = Bool(default=False).tag(sync=True)
    search = InstanceDict(SearchService,
                          allow_none=True).tag(sync=True,
                                               **widget_serialization_no_none)
    showAllChromosomes = Bool(default_value=True).tag(sync=True)
    showAllChromosomeWidget = Bool(default_value=True).tag(sync=True)
    showNavigation = Bool(default_value=True).tag(sync=True)
    showSVGButton = Bool(default_value=False).tag(sync=True)
    showRuler = Bool(default_value=True).tag(sync=True)
    showCenterGuide = Bool(default_value=False).tag(sync=True)
    # trackDefaults = # missing documentation
    roi = List(InstanceDict(AnnotationTrack)).tag(
        sync=True, **widget_serialization_no_none)  # regions of interest
    oauthToken = Unicode(allow_none=True).tag(sync=True)
    apiKey = Unicode(allow_none=True).tag(sync=True)
    clientId = Unicode(allow_none=True).tag(sync=True)

    def add_track(self, track):
        # List subscript does not work for empty List, so handling this case manually.
        if len(self.tracks) == 0:
            self.tracks = [track]
        else:
            self.tracks = self.tracks[:] + [track]

    def remove_track(self, track):
        self.tracks = [t for t in self.tracks if t != track]

    def add_roi(self, roi):
        # List subscript does not work for empty List, so handling this case manually.
        if len(self.roi) == 0:
            self.roi = [roi]
        else:
            self.roi = self.roi[:] + [roi]

    def remove_all_roi(self):
        self.roi = []

    def search(self, symbol):
        self.send({"type": "search", "symbol": symbol})
        print("Search completed. Check the widget instance for results.")

    def dump_json(self):
        print("Dumping browser configuration to browser.out")
        self.send({"type": "dump_json"})

    @out.capture()
    def _custom_message_handler(self, _, content, buffers):
        if content.get('event', '') == 'return_json':
            self._return_json_handler(content)

    @out.capture()
    def _return_json_handler(self, content):
        print(content['json'])
Пример #25
0
class Event(CoreWidget):
    """
    Add browser event handling to a jupyter widget.

    Parameters
    ----------

    source : ipywidgets-compatible widget
        The widget to be watched for events.

    watched_events : list
        List of the browser events to observe on the source.

    ignore_modifier_key_events : bool
        If ``True``, ignore key presses of modifier keys
        ('Shift', 'Control', 'Alt', 'Meta'). Useful when keys mouse events
        with modifiers are watched but you want ot ignore the modifiers by
        themselves. Default is ``False``.

    prevent_default_actions : bool
        If ``True``, do not carry out default action associated with browser
        event. One use is to prevent the browser's display of a context menu
        when right-clicking. Default is ``False``.

    xy_coordinate_system : str or ``None``
        If not ``None``, set the ``xy`` attribute to the current mouse
        position. Use `data` to get the coordinates in whatever is most
        "natural" for the widget (e.g. pixel location in an image). The
        full list of allowed coordinate systems is available through
        the ``supported_xy_coordinates`` attribute of the
        `~ipyevents.Event` widget.

    throttle_or_debounce : {``None``, 'throttle', 'debounce'}
        Method to use, if any, for limiting event rate. 'throttle is primarily
        useful for 'mousemove' and 'wheel' events. 'debounce' can be useful
        for limiting repeated key strokes or clicks. In a nutshell, throtttling
        sets a limit on the rate at which events will be passed while
        debouncing imposes a minimum time between events before a new event is
        passed. Default is ``None``.

    wait : int
        The wait time, in milliseconds, for throttling or debouncing.

    Properties
    ----------

    xy : tuple of int or float
        Location of mouse, only set if `~ipyevents.Event.xy_coordinate_system`
        is not ``None``.

    supported_key_events
        List of keyboard events that can be watched.

    supported_mouse_events
        List of mouse events that can be watched.

    supported_xy_coordinates
        List of supported xy coordinate systems that can be returned
        in `~ipyevents.Event.xy`.
    """
    _model_name = Unicode('EventModel').tag(sync=True)
    _model_module = Unicode('ipyevents').tag(sync=True)
    _model_module_version = Unicode(EXTENSION_SPEC_VERSION).tag(sync=True)
    source = InstanceDict(DOMWidget).tag(sync=True, **widget_serialization)
    watched_events = List().tag(sync=True)
    ignore_modifier_key_events = Bool(False).tag(sync=True)
    prevent_default_action = Bool(False).tag(sync=True)
    xy_coordinate_system = Unicode(allow_none=True).tag(sync=True,
                                                        default=None)
    xy = List().tag(sync=True)
    wait = Integer().tag(sync=True, default=0)
    throttle_or_debounce = Unicode(allow_none=True).tag(sync=True,
                                                        default=None)
    _supported_mouse_events = List([
        'click', 'auxclick', 'dblclick', 'mouseenter', 'mouseleave',
        'mousedown', 'mouseup', 'mousemove', 'wheel', 'contextmenu',
        'dragstart', 'drag', 'dragend', 'dragenter', 'dragover', 'dragleave',
        'drop'
    ]).tag(sync=True)
    _supported_key_events = List(['keydown', 'keyup']).tag(sync=True)

    _xy_coordinate_system_allowed = [
        None,  # Not tracking mouse x/y
        'data',  # "natural" coordinates for the widget (e.g. image)
        'client',  # Relative to the visible part of the web page
        'offset',  # Relative to the padding edge of widget
        'page',  # Relative to the whole document
        'relative',  # Relative to the widget
        'screen'  # Relative to the screen
    ]

    _throttle_debounce_allowed = [
        None,  # No throttling or debounce
        'throttle',  # Throttle the rate at which events are
        # passed from front end to back.
        'debounce'  # Debounce events, i.e. impose minimum delay before
        # triggering events from the front end to the back.
    ]

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._dom_handlers = CallbackDispatcher()
        self.on_msg(self._handle_mouse_msg)

    @property
    def supported_key_events(self):
        return self._supported_key_events

    @property
    def supported_mouse_events(self):
        return self._supported_mouse_events

    @property
    def supported_xy_coordinates(self):
        return self._xy_coordinate_system_allowed

    @validate('watched_events')
    def _validate_watched_events(self, proposal):
        value = proposal['value']
        supported_events = (self._supported_mouse_events +
                            self._supported_key_events)
        bad_events = [v for v in value if v not in supported_events]
        if bad_events:
            message = ('The event(s) {bad} are not supported. The supported '
                       'events are:\n {good}'.format(bad=bad_events,
                                                     good=supported_events))
            raise ValueError(message)
        return value

    @validate('xy_coordinate_system')
    def _xy_coordinate_system(self, proposal):
        value = proposal['value']
        if value not in self._xy_coordinate_system_allowed:
            message = ('The coordinates {bad} are not supported. The '
                       'supported coordinates are:'
                       '\n {good}'.format(
                           bad=value, good=self._xy_coordinate_system_allowed))
            raise ValueError(message)
        return value

    @validate('wait')
    def _validate_wait(self, proposal):
        value = proposal['value']
        if value < 0:
            message = ('wait must be set to a non-negative integer. ')
            raise ValueError(message)
        elif not self.throttle_or_debounce:
            self.throttle_or_debounce = 'throttle'

        return value

    @validate('throttle_or_debounce')
    def _validate_throttle_debounce(self, proposal):
        value = proposal['value']
        if value not in self._throttle_debounce_allowed:
            message = (
                'The event rate limiting method {bad} is not supported. '
                'The supported methods are:'
                '\n {good}'.format(bad=value,
                                   good=self._throttle_debounce_allowed))
            raise ValueError(message)
        return value

    def on_dom_event(self, callback, remove=False):
        """Register a callback to execute when a DOM event occurs.

        The callback will be called with one argument, an dict whose keys
        depend on the type of event.

        Parameters
        ----------
        remove: bool (optional)
            Set to true to remove the callback from the list of callbacks.
        """
        self._dom_handlers.register_callback(callback, remove=remove)

    def reset_callbacks(self):
        """Remove any previously defined callback."""
        self._dom_handlers.callbacks.clear()

    def _handle_mouse_msg(self, _, content, buffers):
        self._dom_handlers(content)
Пример #26
0
class Event(CoreWidget):
    _model_name = Unicode('EventModel').tag(sync=True)
    _model_module = Unicode('ipyevents').tag(sync=True)
    _model_module_version = Unicode(EXTENSION_SPEC_VERSION).tag(sync=True)
    source = InstanceDict(DOMWidget).tag(sync=True, **widget_serialization)
    watched_events = List().tag(sync=True)
    ignore_modifier_key_events = Bool(False).tag(sync=True)
    prevent_default_action = Bool(False).tag(sync=True)
    xy_coordinate_system = Unicode(allow_none=True,
                                   default=None).tag(sync=True)
    xy = List().tag(sync=True)
    _supported_mouse_events = List([
        'click', 'auxclick', 'dblclick', 'mouseenter', 'mouseleave',
        'mousedown', 'mouseup', 'mousemove', 'wheel', 'contextmenu',
        'dragstart', 'drag', 'dragend', 'dragenter', 'dragover', 'dragleave',
        'drop'
    ]).tag(sync=True)
    _supported_key_events = List(['keydown', 'keyup']).tag(sync=True)

    _xy_coordinate_system_allowed = [
        None,  # Not tracking mouse x/y
        'data',  # "natural" coordinates for the widget (e.g. image)
        'client',  # Relative to the visible part of the web page
        'offset',  # Relative to the padding edge of widget
        'page',  # Relative to the whole document
        'relative',  # Relative to the widget
        'screen'  # Relative to the screen
    ]

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._dom_handlers = CallbackDispatcher()
        self.on_msg(self._handle_mouse_msg)

    @property
    def supported_key_events(self):
        return self._supported_key_events

    @property
    def supported_mouse_events(self):
        return self._supported_mouse_events

    @validate('watched_events')
    def _validate_watched_events(self, proposal):
        value = proposal['value']
        supported_events = (self._supported_mouse_events +
                            self._supported_key_events)
        bad_events = [v for v in value if v not in supported_events]
        if bad_events:
            message = ('The event(s) {bad} are not supported. The supported '
                       'events are:\n {good}'.format(bad=bad_events,
                                                     good=supported_events))
            raise ValueError(message)
        return value

    @validate('xy_coordinate_system')
    def _xy_coordinate_system(self, proposal):
        value = proposal['value']
        if value not in self._xy_coordinate_system_allowed:
            message = ('The coordinates {bad} are not supported. The '
                       'supported coordinates are:'
                       '\n {good}'.format(
                           bad=value, good=self._xy_coordinate_system_allowed))
            raise ValueError(message)
        return value

    def on_dom_event(self, callback, remove=False):
        """Register a callback to execute when a DOM event occurs.

        The callback will be called with one argument, an dict whose keys
        depend on the type of event.

        Parameters
        ----------
        remove: bool (optional)
            Set to true to remove the callback from the list of callbacks.
        """
        self._dom_handlers.register_callback(callback, remove=remove)

    def reset_callbacks(self):
        """Remove any previously defined callback."""
        self._dom_handlers.callbacks.clear()

    def _handle_mouse_msg(self, _, content, buffers):
        self._dom_handlers(content)