Beispiel #1
0
    def plot(self, value=None, policy=None, iq=None, **kwargs):
        """Plots the values of the states as a color matrix with two sliders.
        
        Parameters
        ----------
        value : array, shape=(n_mdps,n_qs,n_rows,n_cols) 
            The value function.
            
        policy : array, shape=(n_mdps,n_qs,n_rows,n_cols) 
            The policy to be visualized. It is optional.
            
        save : str
            The name of the file the image will be saved to. It is optional
        """

        if iq:
            val = value[iq] if value is not None else None
            pol = policy[iq] if policy is not None else None
            self.mdp.plot(val, pol, **kwargs)
        else:
            # A helper function for the sliders
            def plot_value(i, q):
                val = value[i, q] if value is not None else None
                pol = policy[i, q] if policy is not None else None
                self.mdp.plot(val, pol, **kwargs)

            i = IntSlider(value=0, min=0, max=self.shape[0] - 1)
            q = IntSlider(value=self.oa.q0, min=0, max=self.shape[1] - 1)
            interact(plot_value, i=i, q=q)
Beispiel #2
0
    def __init__(self, value, type='Float', min=1, max=10, step=1, **kwargs):

        self.value = int(value)
        description = kwargs[
            'name'] if 'no_name' in kwargs and kwargs['no_name'] else 'value'
        self.__slider = IntSlider(value,
                                  min,
                                  max,
                                  description=description,
                                  continuous_update=False)
        # self.__min_ipt = IntText(min, description='min')
        # self.__max_ipt = IntText(max, description='max')
        # self.__step_ipt = BoundedIntText(step, description='step', min=1, step=step)

        self.__slider.observe(self.__on_slider_changed, names='value')
        # self.__min_ipt.observe(self.__on_min_changed, names='value')
        # self.__max_ipt.observe(self.__on_max_changed, names='value')
        # self.__step_ipt.observe(self.__on_step_changed, names='value')

        kwargs['children'] = [
            self.__slider,
            # self.__min_ipt,
            # self.__max_ipt,
            # self.__step_ipt
        ]
        super().__init__(**kwargs)
Beispiel #3
0
def init(dummy):
    global series
    series = simulate_series(simulation_data)
    p = interact(plot_data,
                 rho_0=FloatSlider(min=0.01, max=0.2, step=0.01, value=0.01),
                 f=IntSlider(0, 0, 10))
    return series
Beispiel #4
0
def TrajectorySliderView(traj, frame=0, **kwargs):
    """IPython notebook widget for viewing trajectories in the browser with
    an interactiver slider.

    Parameters
    ----------
    traj : Trajectory
        Trajectory for which you want the viewer.
    frame : int, default=0
        Frame to set the slider to by default

    Other Parameters
    ----------------
    kwargs : string
        See TrajectoryView for all available options.

    See Also
    --------
    TrajectoryView: IPython notebook widget for displaying trajectories in the
    browser with WebGL.
    """
    widget = TrajectoryView(traj, frame=frame, **kwargs)

    def slide(frame):
        widget.frame = frame

    s = IntSlider(min=0, max=traj.n_frames - 1, value=frame)
    slider = interactive(slide, frame=s)

    container = Box()
    container.children = [widget, slider]

    return container
Beispiel #5
0
def test_state_schema():
    from ipywidgets.widgets import IntSlider, Widget
    import json
    import jsonschema
    s = IntSlider()
    state = Widget.get_manager_state(drop_defaults=True)
    with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../', 'state.schema.json')) as f:
        schema = json.load(f)
    jsonschema.validate(state, schema)
Beispiel #6
0
def plot_records():
    """Launch interactive plotting widget."""
    # Get list of record names
    record_names = [file.split('.')[0] for file in os.listdir(os.path.join(DATA_DIR, 'raw')) if '.dat' in file]

    _ = interact(
        plot_record,
        record_name_id=IntSlider(value=0, min=0, max=len(record_names)-1, description='record_name', disabled=False),
        record_names=fixed(record_names)
    )
Beispiel #7
0
    def simulate(self, policy, start=None, T=None, plot=True, animation=None):
        """Simulates the environment and returns a trajectory obtained under the given policy.
        
        Parameters
        ----------
        policy : array, size=(n_pairs,n_qs,n_rows,n_cols)
            The policy.
        
        start : int
            The start state of the MDP.
            
        T : int
            The episode length.
        
        plot : bool 
            Plots the simulation if it is True.
            
        Returns
        -------
        episode: list
            A sequence of states
        """
        T = T if T else np.prod(self.shape[:-1])
        state = (self.shape[0] - 1,
                 self.oa.q0) + (start if start else self.mdp.random_state())
        episode = [state]
        for t in range(T):
            states, probs = self.transition_probs[state][policy[state]]
            state = states[np.random.choice(len(states), p=probs)]
            episode.append(state)

        if plot:

            def plot_agent(t):
                self.mdp.plot(policy=policy[episode[t][:2]],
                              agent=episode[t][2:])

            t = IntSlider(value=0, min=0, max=T - 1)
            interact(plot_agent, t=t)

        if animation:
            pad = 5
            if not os.path.exists(animation):
                os.makedirs(animation)
            for t in range(T):
                self.mdp.plot(policy=policy[episode[t][:2]],
                              agent=episode[t][2:],
                              save=animation + os.sep + str(t).zfill(pad) +
                              '.png')
                plt.close()
            os.system('ffmpeg -r 3 -i ' + animation + os.sep + '%0' +
                      str(pad) + 'd.png -vcodec libx264 -y ' + animation +
                      '.mp4')

        return episode
Beispiel #8
0
def init(dummy):
    global series
    global initialised
    series = simulate_series(simulation_data)

    if initialised == False:
        p = interact(plot_data,
                     rho_0=FloatSlider(min=0.01,
                                       max=0.2,
                                       step=0.01,
                                       value=0.01),
                     f=IntSlider(0, 0, 10))
        initialised = True
Beispiel #9
0
def create_slider(symbol: sp.Symbol) -> "Slider":
    r"""Create an `int` or `float` slider, depending on Symbol assumptions.

    The description for the slider is rendered as LaTeX from the
    `~sympy.core.symbol.Symbol` name.

    >>> create_slider(sp.Symbol("a"))
    FloatSlider(value=0.0, description='\\(a\\)')
    >>> create_slider(sp.Symbol("n0", integer=True))
    IntSlider(value=0, description='\\(n_{0}\\)')
    """
    description = Rf"\({sp.latex(symbol)}\)"
    if symbol.is_integer:
        return IntSlider(description=description)
    return FloatSlider(description=description)
Beispiel #10
0
def init(button):
    global series
    global initialised
    series = simulate_series(simulation_data)

    if initialised == False:
        #p = interact(plot_data, rho_0=FloatSlider(min=0.01, max=0.2, step=0.01, value=0.01, continuous_update=False), f=IntSlider(min=0, max=10, step=1, value=0,continuous_update=False))
        interact(plot_data,
                 rho_0=FloatSlider(min=0.01,
                                   max=0.2,
                                   step=0.01,
                                   value=0.01,
                                   continuous_update=False),
                 f=IntSlider(min=0,
                             max=10,
                             step=1,
                             value=0,
                             continuous_update=False))
        button.description = 'Reset'
        initialised = True
    def plot_obs_probs(self, b):
        """Plots the heatmap of the observation probabilities of the given beacon b.
        
        Parameters
        ----------
        b : int
            The id of the beacon
            
        """
        obs_probs_reshaped = np.zeros(
            (self.rssi_range, self.width, self.length))
        for o in range(self.rssi_range):
            obs_probs_reshaped[o] = self.obs_probs[b, o].reshape(
                (self.length, self.width))
        xs = np.arange(self.width)
        ys = np.arange(self.length)

        def plot(o):
            """Plots the heatmap of the probabilities of observing the signal strength o.

            Parameters
            ----------
            o : int
                The signal strength

            """
            plt.figure(figsize=(8, 7))
            plt.pcolormesh(xs,
                           ys,
                           obs_probs_reshaped[o],
                           cmap='YlGnBu',
                           vmin=0,
                           vmax=1)
            plt.colorbar(label='Probability')
            plt.xlabel('x')
            plt.ylabel('y')
            plt.title('$P(O^{(' + str(b) + ')}_t=' + str(o) + '|S_t)$')

        w = IntSlider(value=0, min=0, max=self.rssi_range - 1)

        interact(plot, o=w)
Beispiel #12
0
 def plot_list(self,value_list,policy_list=None):
     """Plots the list of state values with a slider.
     
     Parameters
     ----------
     value_list : list of arrays with shape=(n_mdps,n_qs,n_rows,n_cols) 
         The list value functions.
         
     policy_list : list of arrays with  shape=(n_mdps,n_qs,n_rows,n_cols) 
         The policy to be visualized. It is optional.
     """
     # A helper function for the slider
     def plot_value(t):
         if policy_list is not None:
             self.plot(value_list[t],policy_list[t])
         else:
             self.plot(value_list[t])
         
     T = len(value_list)
     w=IntSlider(value=0,min=0,max=T-1)
     
     interact(plot_value,t=w)
Beispiel #13
0
def julia_plot(c=-1,
               x_center=0.0,
               y_center=0.0,
               image_width=4.0,
               max_iteration=500,
               pixel_count=500,
               base_color='steelblue',
               iteration_level=1,
               number_of_colors=50,
               point_color='yellow',
               interact=False,
               mandelbrot=True,
               period=None):
    r"""
    Plots the Julia set of a given complex `c` value. Users can specify whether
    they would like to display the Mandelbrot side by side with the Julia set.

    The Julia set of a given `c` value is the set of complex numbers for which
    the function `Q_c(z)=z^2+c` is bounded under iteration. The Julia set can
    be visualized by plotting each point in the set in the complex plane.
    Julia sets are examples of fractals when plotted in the complex plane.

    ALGORITHM:

    Define the map `Q_c(z) = z^2 + c` for some `c \in \mathbb{C}`. For every
    `p \in \mathbb{C}`, if `|Q_{c}^{k}(p)| > 2` for some `k \geq 0`,
    then `Q_{c}^{n}(p) \to \infty`. Let `N` be the maximum number of iterations.
    Compute the first `N` points on the orbit of `p` under `Q_c`. If for
    any `k < N`, `|Q_{c}^{k}(p)| > 2`, we stop the iteration and assign a color
    to the point `p` based on how quickly `p` escaped to infinity under
    iteration of `Q_c`. If `|Q_{c}^{i}(p)| \leq 2` for all `i \leq N`, we assume
    `p` is in the Julia set and assign the point `p` the color black.

    INPUT:

    - ``c`` -- complex (optional - default: ``-1``), complex point `c` that
      determines the Julia set.

    - ``period`` -- list (optional - default: ``None``), returns the Julia set
      for a random `c` value with the given (formal) cycle structure.

    - ``mandelbrot`` -- boolean (optional - default: ``True``), when set to
      ``True``, an image of the Mandelbrot set is appended to the right of the
      Julia set.

    - ``point_color`` -- RGB color (optional - default: ``'tomato'``),
      color of the point `c` in the Mandelbrot set (any valid input for Color).

    - ``x_center`` -- double (optional - default: ``-1.0``), Real part
      of center point.

    - ``y_center`` -- double (optional - default: ``0.0``), Imaginary part
      of center point.

    - ``image_width`` -- double (optional - default: ``4.0``), width of image
      in the complex plane.

    - ``max_iteration`` -- long (optional - default: ``500``), maximum number
      of iterations the map `Q_c(z)`.

    - ``pixel_count`` -- long (optional - default: ``500``), side length of
      image in number of pixels.

    - ``base_color`` -- RGB color (optional - default: ``'steelblue'``), color
      used to determine the coloring of set (any valid input for Color).

    - ``iteration_level`` -- long (optional - default: 1), number of iterations
      between each color level.

    - ``number_of_colors`` -- long (optional - default: 30), number of colors
      used to plot image.

    - ``interact`` -- boolean (optional - default: ``False``), controls whether
      plot will have interactive functionality.

    OUTPUT:

    24-bit RGB image of the Julia set in the complex plane.

    EXAMPLES::

        sage: julia_plot()
        1001x500px 24-bit RGB image

    To display only the Julia set, set ``mandelbrot`` to ``False``::

        sage: julia_plot(mandelbrot=False)
        500x500px 24-bit RGB image

    To display an interactive plot of the Julia set in the Notebook,
    set ``interact`` to ``True``::

        sage: julia_plot(interact=True)
        interactive(children=(FloatSlider(value=-1.0, description=u'Real c'...

    To return the Julia set of a random `c` value with (formal) cycle structure
    `(2,3)`, set ``period = [2,3]``::

        sage: julia_plot(period=[2,3])
        1001x500px 24-bit RGB image

    To return all of the Julia sets of `c` values with (formal) cycle structure
    `(2,3)`::

        sage: period = [2,3] # not tested
        ....: R.<c> = QQ[]
        ....: P.<x,y> = ProjectiveSpace(R,1)
        ....: f = DynamicalSystem([x^2+c*y^2, y^2])
        ....: L = f.dynatomic_polynomial(period).subs({x:0,y:1}).roots(ring=CC)
        ....: c_values = [k[0] for k in L]
        ....: for c in c_values:
        ....:     julia_plot(c)
    """
    if period is not None:
        R = PolynomialRing(QQ, 'c')
        c = R.gen()
        x, y = ProjectiveSpace(R, 1, 'x,y').gens()
        f = DynamicalSystem([x**2 + c * y**2, y**2])
        L = f.dynatomic_polynomial(period).subs({x: 0, y: 1}).roots(ring=CC)
        c = L[randint(0, len(L) - 1)][0]

    c = CC(c)
    c_real = c.real()
    c_imag = c.imag()

    base_color = Color(base_color)
    point_color = Color(point_color)

    if interact:
        from ipywidgets.widgets import FloatSlider, IntSlider, ColorPicker, interact
        widgets = dict(
            c_real=FloatSlider(min=-2.0,
                               max=2.0,
                               step=EPS,
                               value=c_real,
                               description="Real c"),
            c_imag=FloatSlider(min=-2.0,
                               max=2.0,
                               step=EPS,
                               value=c_imag,
                               description="Imag c"),
            x_center=FloatSlider(min=-1.0,
                                 max=1.0,
                                 step=EPS,
                                 value=x_center,
                                 description="Real center"),
            y_center=FloatSlider(min=-1.0,
                                 max=1.0,
                                 step=EPS,
                                 value=y_center,
                                 description="Imag center"),
            image_width=FloatSlider(min=EPS,
                                    max=4.0,
                                    step=EPS,
                                    value=image_width,
                                    description="Image width"),
            max_iteration=IntSlider(min=0,
                                    max=600,
                                    value=max_iteration,
                                    description="Iterations"),
            pixel_count=IntSlider(min=10,
                                  max=600,
                                  value=pixel_count,
                                  description="Pixels"),
            level_sep=IntSlider(min=1,
                                max=20,
                                value=iteration_level,
                                description="Color sep"),
            color_num=IntSlider(min=1,
                                max=100,
                                value=number_of_colors,
                                description="# Colors"),
            base_color=ColorPicker(value=base_color.html_color(),
                                   description="Base color"),
        )
        if mandelbrot:
            widgets["point_color"] = ColorPicker(
                value=point_color.html_color(), description="Point color")
            return interact(**widgets).widget(julia_helper)
        else:
            return interact(**widgets).widget(fast_julia_plot)

    if mandelbrot:
        return julia_helper(c_real, c_imag, x_center, y_center, image_width,
                            max_iteration, pixel_count, iteration_level,
                            number_of_colors, base_color, point_color)

    else:
        return fast_julia_plot(c_real, c_imag, x_center, y_center, image_width,
                               max_iteration, pixel_count, iteration_level,
                               number_of_colors, base_color)
Beispiel #14
0
                 f=IntSlider(min=0,
                             max=10,
                             step=1,
                             value=0,
                             continuous_update=False))
        button.description = 'Reset'
        initialised = True


###############################################################################

style = {'description_width': '30%'}

nn_widget = IntSlider(min=100,
                      max=2000,
                      step=50,
                      value=1000,
                      description='network size',
                      style=style)
np_widget = FloatSlider(min=0.001,
                        max=0.05,
                        step=0.001,
                        value=0.006,
                        description='network density',
                        style=style)

D_widget = IntSlider(min=10,
                     max=100,
                     step=1,
                     value=50,
                     description='D - number of disease related genes',
                     style=style)
Beispiel #15
0
                                       max=0.2,
                                       step=0.01,
                                       value=0.01,
                                       continuous_update=False),
                     f=IntSlider(min=0,
                                 max=10,
                                 step=1,
                                 value=0,
                                 continuous_update=False))
        button_init.description = 'Reset'
        initialised = True


###############################################################################

nn_widget = IntSlider(min=100, max=2000, step=100, value=1000)
np_widget = FloatSlider(min=0.005, max=0.05, step=0.005, value=0.005)

D_widget = IntSlider(min=10, max=100, step=1, value=50)
p_widget = FloatSlider(min=0.0, max=1.0, step=0.1, value=0.5)

P_widget = IntSlider(min=5, max=50, step=5, value=20)
A_widget = FloatSlider(min=0.0, max=1.0, step=0.1, value=0.5)

params = interact(set_params,
                  nn=nn_widget,
                  np=np_widget,
                  D=D_widget,
                  p=p_widget,
                  P=P_widget,
                  A=A_widget)
Beispiel #16
0
def RGB_colourspace_models_transformation_matrix_widget():

    title_Label = Label('RGB Colourspace Models Transformation Matrix')
    title_Label.add_class('widget-title')

    default_layout = {'flex': '1 1 auto', 'width': 'auto'}
    input_colourspace_Dropdown = Dropdown(
        options=sorted(colour.RGB_COLOURSPACES), layout=default_layout)

    output_colourspace_Dropdown = Dropdown(
        options=sorted(colour.RGB_COLOURSPACES), layout=default_layout)

    chromatic_adaptation_transforms_Dropdown = Dropdown(
        options=sorted(colour.CHROMATIC_ADAPTATION_TRANSFORMS),
        layout=default_layout)

    formatter_Dropdown = Dropdown(
        options=['str', 'repr', 'Nuke'], layout=default_layout)

    decimals_IntSlider = IntSlider(value=10, max=15, layout=default_layout)

    RGB_to_RGB_matrix_Textarea = Textarea(rows=3, layout=default_layout)
    RGB_to_RGB_matrix_Textarea.add_class('widget-output-textarea')

    def set_RGB_to_RGB_matrix_Textarea():
        M = colour.RGB_to_RGB_matrix(
            colour.RGB_COLOURSPACES[input_colourspace_Dropdown.value],
            colour.RGB_COLOURSPACES[output_colourspace_Dropdown.value],
            chromatic_adaptation_transforms_Dropdown.value)

        with colour.utilities.numpy_print_options(
                formatter={
                    'float':
                    ('{{:0.{0}f}}'.format(decimals_IntSlider.value)).format
                },
                threshold=np.nan):
            if formatter_Dropdown.value == 'str':
                M = str(M)
            elif formatter_Dropdown.value == 'repr':
                M = repr(M)
            else:
                M = NUKE_COLORMATRIX_NODE_TEMPLATE.format(
                    nuke_format_matrix(M, decimals_IntSlider.value),
                    '{0}_to_{1}'.format(
                        input_colourspace_Dropdown.value.replace(' ', '_'),
                        output_colourspace_Dropdown.value.replace(' ', '_')))

            RGB_to_RGB_matrix_Textarea.rows = len(M.split('\n'))
            RGB_to_RGB_matrix_Textarea.value = M

    def on_input_change(change):
        if change['type'] == 'change' and change['name'] == 'value':
            set_RGB_to_RGB_matrix_Textarea()

    input_colourspace_Dropdown.observe(on_input_change)
    output_colourspace_Dropdown.observe(on_input_change)
    chromatic_adaptation_transforms_Dropdown.observe(on_input_change)
    formatter_Dropdown.observe(on_input_change)
    decimals_IntSlider.observe(on_input_change)

    set_RGB_to_RGB_matrix_Textarea()

    widget = Box([
        VBox(
            [
                title_Label,
                Textarea(
                    'This widget computes the colour transformation '
                    'matrix from the Input RGB Colourspace to the '
                    'Output RGB Colourspace using the given '
                    'Chromatic Adaptation Transform.',
                    rows=2,
                    layout=default_layout),
                Label('Input RGB Colourspace'),
                input_colourspace_Dropdown,
                Label('Output RGB Colourspace'),
                output_colourspace_Dropdown,
                Label('Chromatic Adaptation Transform'),
                chromatic_adaptation_transforms_Dropdown,
                Label('Formatter'),
                formatter_Dropdown,
                HBox([Label('Decimals:'), decimals_IntSlider]),
                Label('RGB Transformation Matrix'),
                RGB_to_RGB_matrix_Textarea,
            ],
            layout={
                'border': 'solid 2px',
                'width': '55%'
            })
    ])

    return widget
Beispiel #17
0
def RGB_colourspace_models_chromatically_adapted_primaries_widget():

    title_Label = Label(
        'RGB Colourspace Models Chromatically Adapted Primaries')
    title_Label.add_class('widget-title')

    default_layout = {'flex': '1 1 auto', 'width': 'auto'}
    input_colourspace_Dropdown = Dropdown(
        options=sorted(colour.RGB_COLOURSPACES), layout=default_layout)

    illuminant_Dropdown = Dropdown(
        options=sorted(
            colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']),
        layout=default_layout)

    chromatic_adaptation_transforms_Dropdown = Dropdown(
        options=sorted(colour.CHROMATIC_ADAPTATION_TRANSFORMS),
        layout=default_layout)

    formatter_Dropdown = Dropdown(
        options=['str', 'repr'], layout=default_layout)

    decimals_IntSlider = IntSlider(value=10, max=15, layout=default_layout)

    primaries_Textarea = Textarea(rows=3, layout=default_layout)
    primaries_Textarea.add_class('widget-output-textarea')

    def set_primaries_Textarea():
        input_colourspace = colour.RGB_COLOURSPACES[
            input_colourspace_Dropdown.value]

        P = colour.chromatically_adapted_primaries(
            input_colourspace.primaries, input_colourspace.whitepoint,
            colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer'][
                illuminant_Dropdown.value],
            chromatic_adaptation_transforms_Dropdown.value)

        with colour.utilities.numpy_print_options(
                formatter={
                    'float':
                    ('{{:0.{0}f}}'.format(decimals_IntSlider.value)).format
                },
                threshold=np.nan):
            if formatter_Dropdown.value == 'str':
                P = str(P)
            elif formatter_Dropdown.value == 'repr':
                P = repr(P)

            primaries_Textarea.rows = len(P.split('\n'))
            primaries_Textarea.value = P

    def on_input_change(change):
        if change['type'] == 'change' and change['name'] == 'value':
            set_primaries_Textarea()

    input_colourspace_Dropdown.observe(on_input_change)
    illuminant_Dropdown.observe(on_input_change)
    chromatic_adaptation_transforms_Dropdown.observe(on_input_change)
    formatter_Dropdown.observe(on_input_change)
    decimals_IntSlider.observe(on_input_change)

    set_primaries_Textarea()

    widget = Box([
        VBox(
            [
                title_Label,
                Textarea(
                    'This widget computes the Chromatically Adapted Primaries '
                    'of the given RGB Colourspace Model to the given '
                    'Illuminant using the '
                    'given Chromatic Adaptation Transform.',
                    rows=3,
                    layout=default_layout),
                Label('Input RGB Colourspace'),
                input_colourspace_Dropdown,
                Label('Illuminant'),
                illuminant_Dropdown,
                Label('Chromatic Adaptation Transform'),
                chromatic_adaptation_transforms_Dropdown,
                Label('Formatter'),
                formatter_Dropdown,
                HBox([Label('Decimals:'), decimals_IntSlider]),
                Label('RGB Transformation Matrix'),
                primaries_Textarea,
            ],
            layout={
                'border': 'solid 2px',
                'width': '55%'
            })
    ])

    return widget
Beispiel #18
0
    ax.set_xlim([0, days])
    ax.set_ylim([0, initial_salary * 1.1])
    ax.set_xlabel('Days')
    ax.set_ylabel('Capital $')
    ax.legend(loc='best')
    ax.grid()

    slider = plt.show()


interact(main,
         initial_salary=IntSlider(min=0,
                                  max=25000,
                                  step=500,
                                  value=15000,
                                  description='Initial Salary',
                                  style=style,
                                  layout=slider_layout),
         savings_ratio=FloatSlider(min=0,
                                   max=1,
                                   step=0.01,
                                   value=0.2,
                                   description='Savings Ratio',
                                   style=style,
                                   layout=slider_layout),
         extraordinary_expenses=FloatSlider(
             min=0,
             max=1,
             step=0.005,
             description='Extraordinary Expenses',
Beispiel #19
0
def init():
    series = simulate_series(simulation_data)
    p = interact(plot_data,
                 rho_0=FloatSlider(min=0.01, max=0.2, step=0.01, value=0.01),
                 f=IntSlider(0, 0, 10))
Beispiel #20
0
def julia_plot(f=None, **kwds):
    r"""
    Plots the Julia set of a given polynomial ``f``. Users can specify whether
    they would like to display the Mandelbrot side by side with the Julia set
    with the ``mandelbrot`` argument. If ``f`` is not specified, this method
    defaults to `f(z) = z^2-1`.

    The Julia set of a polynomial ``f`` is the set of complex numbers `z` for
    which the function `f(z)` is bounded under iteration. The Julia set can
    be visualized by plotting each point in the set in the complex plane.
    Julia sets are examples of fractals when plotted in the complex plane.

    ALGORITHM:

    Let `R_c = \bigl(1 + \sqrt{1 + 4|c|}\bigr)/2` if the polynomial is of the
    form `f(z) = z^2 + c`; otherwise, let `R_c = 2`.
    For every `p \in \mathbb{C}`, if `|f^{k}(p)| > R_c` for some `k \geq 0`,
    then `f^{n}(p) \to \infty`.  Let `N` be the maximum number of iterations.
    Compute the first `N` points on the orbit of `p` under `f`. If for
    any `k < N`, `|f^{k}(p)| > R_c`, we stop the iteration and assign a color
    to the point `p` based on how quickly `p` escaped to infinity under
    iteration of `f`. If `|f^{i}(p)| \leq R_c` for all `i \leq N`, we assume
    `p` is in the Julia set and assign the point `p` the color black.

    INPUT:

    - ``f`` -- input polynomial (optional - default: ``z^2 - 1``).

    - ``period`` -- list (optional - default: ``None``), returns the Julia set
      for a random `c` value with the given (formal) cycle structure.

    - ``mandelbrot`` -- boolean (optional - default: ``True``), when set to
      ``True``, an image of the Mandelbrot set is appended to the right of the
      Julia set.

    - ``point_color`` -- RGB color (optional - default: ``'tomato'``),
      color of the point `c` in the Mandelbrot set (any valid input for Color).

    - ``x_center`` -- double (optional - default: ``-1.0``), Real part
      of center point.

    - ``y_center`` -- double (optional - default: ``0.0``), Imaginary part
      of center point.

    - ``image_width`` -- double (optional - default: ``4.0``), width of image
      in the complex plane.

    - ``max_iteration`` -- long (optional - default: ``500``), maximum number
      of iterations the map `f(z)`.

    - ``pixel_count`` -- long (optional - default: ``500``), side length of
      image in number of pixels.

    - ``base_color`` -- hex color (optional - default: ``'steelblue'``), color
      used to determine the coloring of set (any valid input for Color).

    - ``level_sep`` -- long (optional - default: 1), number of iterations
      between each color level.

    - ``number_of_colors`` -- long (optional - default: 30), number of colors
      used to plot image.

    - ``interact`` -- boolean (optional - default: ``False``), controls whether
      plot will have interactive functionality.

    OUTPUT:

    24-bit RGB image of the Julia set in the complex plane.

    .. TODO::

        Implement the side-by-side Mandelbrot-Julia plots for general one-parameter families
        of polynomials.

    EXAMPLES:

    The default ``f`` is `z^2 - 1`::

        sage: julia_plot()
        1001x500px 24-bit RGB image

    To display only the Julia set, set ``mandelbrot`` to ``False``::

        sage: julia_plot(mandelbrot=False)
        500x500px 24-bit RGB image

    ::

        sage: R.<z> = CC[]
        sage: f = z^3 - z + 1
        sage: julia_plot(f)
        500x500px 24-bit RGB image

    To display an interactive plot of the Julia set in the Notebook,
    set ``interact`` to ``True``. (This is only implemented for polynomials of
    the form ``f = z^2 + c``)::

        sage: julia_plot(interact=True)
        interactive(children=(FloatSlider(value=-1.0, description=u'Real c'...

        ::

        sage: R.<z> = CC[]
        sage: f = z^2 + 1/2
        sage: julia_plot(f,interact=True)
        interactive(children=(FloatSlider(value=0.5, description=u'Real c'...

    To return the Julia set of a random `c` value with (formal) cycle structure
    `(2,3)`, set ``period = [2,3]``::

        sage: julia_plot(period=[2,3])
        1001x500px 24-bit RGB image

    To return all of the Julia sets of `c` values with (formal) cycle structure
    `(2,3)`::

        sage: period = [2,3] # not tested
        ....: R.<c> = QQ[]
        ....: P.<x,y> = ProjectiveSpace(R,1)
        ....: f = DynamicalSystem([x^2+c*y^2, y^2])
        ....: L = f.dynatomic_polynomial(period).subs({x:0,y:1}).roots(ring=CC)
        ....: c_values = [k[0] for k in L]
        ....: for c in c_values:
        ....:     julia_plot(c)

    Polynomial maps can be defined over a polynomial ring or a fraction field,
    so long as ``f`` is polynomial::

        sage: R.<z> = CC[]
        sage: f = z^2 - 1
        sage: julia_plot(f)
        1001x500px 24-bit RGB image

    ::

        sage: R.<z> = CC[]
        sage: K = R.fraction_field(); z = K.gen()
        sage: f = z^2-1
        sage: julia_plot(f)
        1001x500px 24-bit RGB image

    Interact functionality is not implemented if the polynomial is not of the
    form `f = z^2 + c`::

        sage: R.<z> = CC[]
        sage: f = z^3 + 1
        sage: julia_plot(f, interact=True)
        Traceback (most recent call last):
        ...
        NotImplementedError: The interactive plot is only implemented for ...
    """

    # extract keyword arguments
    period = kwds.pop("period", None)
    mandelbrot = kwds.pop("mandelbrot", True)
    point_color = kwds.pop("point_color", 'tomato')
    x_center = kwds.pop("x_center", 0.0)
    y_center = kwds.pop("y_center", 0.0)
    image_width = kwds.pop("image_width", 4.0)
    max_iteration = kwds.pop("max_iteration", 500)
    pixel_count = kwds.pop("pixel_count", 500)
    base_color = kwds.pop("base_color", 'steelblue')
    level_sep = kwds.pop("level_sep", 1)
    number_of_colors = kwds.pop("number_of_colors", 30)
    interacts = kwds.pop("interact", False)

    f_is_default_after_all = None

    if period:  # pick a random c with the specified period
        R = PolynomialRing(CC, 'c')
        c = R.gen()
        x, y = ProjectiveSpace(R, 1, 'x,y').gens()
        F = DynamicalSystem([x**2 + c * y**2, y**2])
        L = F.dynatomic_polynomial(period).subs({x: 0, y: 1}).roots(ring=CC)
        c = L[randint(0, len(L) - 1)][0]

    base_color = Color(base_color)
    point_color = Color(point_color)

    EPS = 0.00001

    if f is not None and period is None:  # f user-specified and no period given

        # try to coerce f to live in a polynomial ring
        S = PolynomialRing(CC, names='z')
        z = S.gen()
        try:
            f_poly = S(f)
        except TypeError:
            R = f.parent()
            if not (R.is_integral_domain() and
                    (CC.is_subring(R) or CDF.is_subring(R))):
                raise ValueError('Given `f` must be a complex polynomial.')
            else:
                raise NotImplementedError(
                    'Julia sets not implemented for rational functions.')

        if (f_poly - z * z) in CC:  # f is specified and of the form z^2 + c.
            f_is_default_after_all = True
            c = f_poly - z * z
        else:  # f is specified and not of the form z^2 + c
            if interacts:
                raise NotImplementedError(
                    "The interactive plot is only implemented for "
                    "polynomials of the form f = z^2 + c.")
            else:
                return general_julia(f_poly, x_center, y_center, image_width,
                                     max_iteration, pixel_count, level_sep,
                                     number_of_colors, base_color)

    # otherwise we can use fast_julia_plot for z^2 + c
    if f_is_default_after_all or f is None or period is not None:

        # specify default c = -1 value if f and period were not specified
        if not f_is_default_after_all and period is None:
            c = -1

        c = CC(c)
        c_real = c.real()
        c_imag = c.imag()

        if interacts:  # set widgets
            from ipywidgets.widgets import FloatSlider, IntSlider, \
                                           ColorPicker, interact
            widgets = dict(
                c_real=FloatSlider(min=-2.0,
                                   max=2.0,
                                   step=EPS,
                                   value=c_real,
                                   description="Real c"),
                c_imag=FloatSlider(min=-2.0,
                                   max=2.0,
                                   step=EPS,
                                   value=c_imag,
                                   description="Imag c"),
                x_center=FloatSlider(min=-1.0,
                                     max=1.0,
                                     step=EPS,
                                     value=x_center,
                                     description="Real center"),
                y_center=FloatSlider(min=-1.0,
                                     max=1.0,
                                     step=EPS,
                                     value=y_center,
                                     description="Imag center"),
                image_width=FloatSlider(min=EPS,
                                        max=4.0,
                                        step=EPS,
                                        value=image_width,
                                        description="Width"),
                max_iteration=IntSlider(min=0,
                                        max=1000,
                                        value=max_iteration,
                                        description="Iterations"),
                pixel_count=IntSlider(min=10,
                                      max=1000,
                                      value=pixel_count,
                                      description="Pixels"),
                level_sep=IntSlider(min=1,
                                    max=20,
                                    value=level_sep,
                                    description="Color sep"),
                color_num=IntSlider(min=1,
                                    max=100,
                                    value=number_of_colors,
                                    description="# Colors"),
                base_color=ColorPicker(value=base_color.html_color(),
                                       description="Base color"),
            )
            if mandelbrot:
                widgets["point_color"] = ColorPicker(
                    value=point_color.html_color(), description="Point color")
                return interact(**widgets).widget(julia_helper)
            else:
                return interact(**widgets).widget(fast_julia_plot)
        elif mandelbrot:  # non-interactive with mandelbrot
            return julia_helper(c_real, c_imag, x_center, y_center,
                                image_width, max_iteration, pixel_count,
                                level_sep, number_of_colors, base_color,
                                point_color)
        else:  # non-interactive without mandelbrot
            return fast_julia_plot(c_real, c_imag, x_center, y_center,
                                   image_width, max_iteration, pixel_count,
                                   level_sep, number_of_colors, base_color)
Beispiel #21
0
def mandelbrot_plot(f=None, **kwds):
    r"""
    Plot of the Mandelbrot set for a one parameter family of polynomial maps.

    The family `f_c(z)` must have parent ``R`` of the
    form ``R.<z,c> = CC[]``.

    REFERENCE:

    [Dev2005]_

    INPUT:

    - ``f`` -- map (optional - default: ``z^2 + c``), polynomial family used to
      plot the Mandelbrot set.

    - ``parameter`` -- variable (optional - default: ``c``), parameter variable
      used to plot the Mandelbrot set.

    - ``x_center`` -- double (optional - default: ``-1.0``), Real part of center
      point.

    - ``y_center`` -- double (optional - default: ``0.0``), Imaginary part of
      center point.

    - ``image_width`` -- double (optional - default: ``4.0``), width of image
      in the complex plane.

    - ``max_iteration`` -- long (optional - default: ``500``), maximum number of
      iterations the map ``f_c(z)``.

    - ``pixel_count`` -- long (optional - default: ``500``), side length of
      image in number of pixels.

    - ``base_color`` -- RGB color (optional - default: ``[40, 40, 40]``) color
      used to determine the coloring of set.

    - ``level_sep`` -- long (optional - default: 1) number of iterations
      between each color level.

    - ``number_of_colors`` -- long (optional - default: 30) number of colors
      used to plot image.

    - ``interact`` -- boolean (optional - default: ``False``), controls whether
      plot will have interactive functionality.

    OUTPUT:

    24-bit RGB image of the Mandelbrot set in the complex plane.

    EXAMPLES:

    ::

        sage: mandelbrot_plot()
        500x500px 24-bit RGB image

    ::

        sage: mandelbrot_plot(pixel_count=1000)
        1000x1000px 24-bit RGB image

    ::

        sage: mandelbrot_plot(x_center=-1.11, y_center=0.2283, image_width=1/128, # long time
        ....: max_iteration=2000, number_of_colors=500, base_color=[40, 100, 100])
        500x500px 24-bit RGB image

    To display an interactive plot of the Mandelbrot in the Notebook, set
    ``interact`` to ``True``. (This is only implemented for ``z^2 + c``)::

        sage: mandelbrot_plot(interact=True)
        interactive(children=(FloatSlider(value=0.0, description=u'Real center', max=1.0, min=-1.0, step=1e-05),
        FloatSlider(value=0.0, description=u'Imag center', max=1.0, min=-1.0, step=1e-05),
        FloatSlider(value=4.0, description=u'Width', max=4.0, min=1e-05, step=1e-05),
        IntSlider(value=500, description=u'Iterations', max=1000),
        IntSlider(value=500, description=u'Pixels', max=1000, min=10),
        IntSlider(value=1, description=u'Color sep', max=20, min=1),
        IntSlider(value=30, description=u'# Colors', min=1),
        ColorPicker(value='#ff6347', description=u'Base color'), Output()),
        _dom_classes=(u'widget-interact',))

    ::

        sage: mandelbrot_plot(interact=True, x_center=-0.75, y_center=0.25,
        ....: image_width=1/2, number_of_colors=75)
        interactive(children=(FloatSlider(value=-0.75, description=u'Real center', max=1.0, min=-1.0, step=1e-05),
        FloatSlider(value=0.25, description=u'Imag center', max=1.0, min=-1.0, step=1e-05),
        FloatSlider(value=0.5, description=u'Width', max=4.0, min=1e-05, step=1e-05),
        IntSlider(value=500, description=u'Iterations', max=1000),
        IntSlider(value=500, description=u'Pixels', max=1000, min=10),
        IntSlider(value=1, description=u'Color sep', max=20, min=1),
        IntSlider(value=75, description=u'# Colors', min=1),
        ColorPicker(value='#ff6347', description=u'Base color'), Output()),
        _dom_classes=(u'widget-interact',))

    Polynomial maps can be defined over a multivariate polynomial ring or a
    univariate polynomial ring tower::

        sage: R.<z,c> = CC[]
        sage: f = z^2 + c
        sage: mandelbrot_plot(f)
        500x500px 24-bit RGB image

    ::

        sage: B.<c> = CC[]
        sage: R.<z> = B[]
        sage: f = z^5 + c
        sage: mandelbrot_plot(f)
        500x500px 24-bit RGB image

    When the polynomial is defined over a multivariate polynomial ring it is
    necessary to specify the parameter variable (default parameter is ``c``)::

        sage: R.<a,b> = CC[]
        sage: f = a^2 + b^3
        sage: mandelbrot_plot(f, parameter=b)
        500x500px 24-bit RGB image

    Interact functionality is not implemented for general polynomial maps::

        sage: R.<z,c> = CC[]
        sage: f = z^3 + c
        sage: mandelbrot_plot(f, interact=True)
        Traceback (most recent call last):
        ...
        NotImplementedError: Interact only implemented for z^2 + c
    """
    parameter = kwds.pop("parameter", None)
    x_center = kwds.pop("x_center", 0.0)
    y_center = kwds.pop("y_center", 0.0)
    image_width = kwds.pop("image_width", 4.0)
    max_iteration = kwds.pop("max_iteration", None)
    pixel_count = kwds.pop("pixel_count", 500)
    level_sep = kwds.pop("level_sep", 1)
    number_of_colors = kwds.pop("number_of_colors", 30)
    interacts = kwds.pop("interact", False)
    base_color = kwds.pop("base_color", Color('tomato'))
    # Check if user specified maximum number of iterations
    given_iterations = True
    if max_iteration is None:
        # Set default to 500 for z^2 + c map
        max_iteration = 500
        given_iterations = False

    from ipywidgets.widgets import FloatSlider, IntSlider, ColorPicker, interact
    widgets = dict(
        x_center=FloatSlider(min=-1.0,
                             max=1.0,
                             step=EPS,
                             value=x_center,
                             description="Real center"),
        y_center=FloatSlider(min=-1.0,
                             max=1.0,
                             step=EPS,
                             value=y_center,
                             description="Imag center"),
        image_width=FloatSlider(min=EPS,
                                max=4.0,
                                step=EPS,
                                value=image_width,
                                description="Width"),
        max_iteration=IntSlider(min=0,
                                max=1000,
                                value=max_iteration,
                                description="Iterations"),
        pixel_count=IntSlider(min=10,
                              max=1000,
                              value=pixel_count,
                              description="Pixels"),
        level_sep=IntSlider(min=1,
                            max=20,
                            value=level_sep,
                            description="Color sep"),
        color_num=IntSlider(min=1,
                            max=100,
                            value=number_of_colors,
                            description="# Colors"),
        base_color=ColorPicker(value=Color(base_color).html_color(),
                               description="Base color"),
    )

    if f is None:
        # Quadratic map f = z^2 + c

        if interacts:
            return interact(**widgets).widget(fast_mandelbrot_plot)

        else:
            return fast_mandelbrot_plot(x_center, y_center, image_width,
                                        max_iteration, pixel_count, level_sep,
                                        number_of_colors, base_color)

    else:
        if parameter is None:
            c = var('c')
            parameter = c

        P = f.parent()

        if P.base_ring() is CC or P.base_ring() is CDF:
            if is_FractionField(P):
                raise NotImplementedError(
                    "coefficients must be polynomials in the parameter")
            gen_list = list(P.gens())
            parameter = gen_list.pop(gen_list.index(parameter))
            variable = gen_list.pop()

        elif P.base_ring().base_ring() is CC or P.base_ring().base_ring(
        ) is CDF:
            if is_FractionField(P.base_ring()):
                raise NotImplementedError(
                    "coefficients must be polynomials in the parameter")
            phi = P.flattening_morphism()
            f = phi(f)
            gen_list = list(f.parent().gens())
            parameter = gen_list.pop(gen_list.index(parameter))
            variable = gen_list.pop()

        elif P.base_ring() in FunctionFields():
            raise NotImplementedError(
                "coefficients must be polynomials in the parameter")

        else:
            raise ValueError("base ring must be a complex field")

        if f == variable**2 + parameter:
            # Quadratic map f = z^2 + c
            if interacts:
                return interact(**widgets).widget(fast_mandelbrot_plot)

            else:
                return fast_mandelbrot_plot(x_center, y_center, image_width,
                                            max_iteration, pixel_count,
                                            level_sep, number_of_colors,
                                            base_color)
        else:
            if interacts:
                raise NotImplementedError(
                    "Interact only implemented for z^2 + c")
            else:
                # Set default of max_iteration to 50 for general polynomial maps
                # This prevents the function from being very slow by default
                if not given_iterations:
                    max_iteration = 50

                # Mandelbrot of General Polynomial Map
                return polynomial_mandelbrot(f, parameter, x_center, y_center, \
                 image_width, max_iteration, pixel_count, level_sep, \
                 number_of_colors, base_color)
    def plot(self, probs=None, path=None, title=None):
        """Plots the heatmap of the given probabilities (or a list of probabilities) with the path if it is specified.
        
        Parameters
        ----------
        probs : array, shape(n_states), optional
            A probability vector of the states. If it is None, then path must be provided.

        path : array, shape(T), optional
            A sequence of states. If it is None, then probs must be provided.

        title : str, optional
            Either of 'prediction', 'monitoring', or 'hindsight'. It will be used to determine the title of the plot.

        """
        if path is not None:
            T = len(path)
            path_2d = [(s % self.width, s // self.width) for s in path]

        if probs is None:
            probs_reshaped = np.zeros((T, self.width, self.length))
        else:
            probs = [probs] if not isinstance(probs, list) and len(
                probs.shape) == 1 else probs
            probs = np.array(probs)
            T = probs.shape[0]

            probs_reshaped = np.zeros((T, self.width, self.length))
            for t in range(T):
                probs_reshaped[t] = probs[t].reshape((self.length, self.width))

        xs = np.arange(self.width)
        ys = np.arange(self.length)

        def plot(t):
            """Plots the heatmap of the grid of probabilities at time t.

            Parameters
            ----------
            t : int
                The time step

            """
            plt.figure(figsize=(8, 7))
            plt.pcolormesh(xs,
                           ys,
                           probs_reshaped[t],
                           cmap='YlGnBu',
                           vmin=0,
                           vmax=0.01)
            plt.colorbar(label='Probability')
            plt.xlabel('x')
            plt.ylabel('y')
            if probs is not None:
                if title == 'prediction':
                    plt.title('Prediction: $P(S_{' + str(t) + '})$')
                elif title == 'monitoring':
                    if t == 0:
                        prob_text = 'S_0'
                    elif t == 1:
                        prob_text = 'S_1|O_1'
                    else:
                        prob_text = 'S_{' + str(t) + '}|O_{1:' + str(t) + '}'
                    plt.title('Monitoring: $P(' + prob_text + ')$')
                elif title == 'hindsight':
                    plt.title('Hindsight: $P(S_{' + str(t) + '}|O_{1:' +
                              str(T) + '})$')

            if path is not None:
                t_min = max(t - 8, 0)
                plt.plot([path_2d[t_min][0], path_2d[t_min][0]],
                         [path_2d[t_min][1], path_2d[t_min][1]],
                         'r*',
                         label='Actual Path')
                for tt in range(t_min + 1, t + 1):
                    plt.plot([path_2d[tt - 1][0], path_2d[tt][0]],
                             [path_2d[tt - 1][1], path_2d[tt][1]],
                             '-*',
                             color='orange')
                plt.plot(path_2d[t][0],
                         path_2d[t][1],
                         'o',
                         color='red',
                         markersize=12,
                         markeredgewidth=1.5,
                         markeredgecolor='green')
                plt.legend()

        w = IntSlider(value=0, min=0, max=T - 1)
        interact(plot, t=w)

        @abstractmethod
        def predict(self, probs):
            """Predicts the next state. It computes P(S_{t+1}|O_{1:t}) using probs, which is P(S_{t}|O_{1:t});
            and the transition probabilities P(S_{t+1}|S_{t}).
            Note that none of the probabilities needs to be normalized.

            Parameters
            ----------
            probs : array, shape(n_states)
                The probability vector of the states, which represents P(S_{t}|O_{1:t})

            Returns
            -------
            array, shape(n_states)
                The predicted probabilities, P(S_{t+1}|O_{1:t})

            """
            pass

        @abstractmethod
        def update(self, probs, o):
            """Updates the probabilities using the observations. It computes probs*P(O_{t}|S_{t}).
            If it is called from the method monitor, then probs represents P(S_{t}|O_{1:t-1})
            and the resulting vector will be proportional to P(S_{t}|O_{1:t}).
            Similarly, if it is called from the method backwards, probs represents P(O_{t+1:T}|S_{t})
            and it will return a vector that is proportional to P(O_{t:T}|S_{t}).

            Parameters
            ----------
            probs : array, shape(n_states)
                The probability vector of the states

            o : array, shape(n_beacons)
                The observation vector, RSSI values received from each beacon

            Returns
            -------
            array, shape(n_states)
                The updated probabilities, P(S_{t}|O_{1:t}) or P(O_{t:T}|S_{t}) depending on the context

            """
            pass

        @abstractmethod
        def monitor(self, T, observations):
            """Returns the monitoring probabilities for T time steps using the sequence of observations.
            In other words, it computes P(S_{t}|O_{1:t}) for each t.
            This procedure is also called filtering, and the algorithm is known as forward algorithm.

            Parameters
            ----------
            T : int
                The number of time steps

            observations: array, shape(T, n_beacons)
                The sequence of observations received

            Returns
            -------
            array, shape(T, n_states)
                The monitoring probabilities, P(S_{t}|O_{1:t}) for each t

            """
            pass

        @abstractmethod
        def postdict(self, probs):
            """Predicts the previous state. It computes P(O_{t:T}|S_{t-1}) using probs, which is P(O_{t:T}|S_{t});
            and the transition probabilities P(S_{t}|S_{t-1}).
            Note that none of the probabilities needs to be normalized.

            Parameters
            ----------
            probs : array, shape(n_states)
                The probability vector of the states, which represents P(O_{t:T}|S_{t})

            Returns
            -------
            array, shape(n_states)
                The postdicted probabilities, P(O_{t:T}|S_{t-1})

            """
            pass

        @abstractmethod
        def backwards(self, T, observations):
            """Returns the backwards probabilities for T time steps using the sequence of observations.
            In other words, it computes P(O_{t+1:T}|S_{t}) for each t.

            Parameters
            ----------
            T : int
                The number of time steps

            observations: array, shape(T, n_beacons)
                The sequence of observations received

            Returns
            -------
            array, shape(T, n_states)
                The backwards probabilities, P(O_{t+1:T}|S_{t}) for each t

            """
            pass

        @abstractmethod
        def hindsight(self, T, observations):
            """Computes the hindsight probabilities by combining the monitoring and backwards probabilities.
            It returns P(S_{t}|O_{1:T}) for each t.

            Parameters
            ----------
            T : int
                The number of time steps

            observations: array, shape(T, n_beacons)
                The sequence of observations received

            Returns
            -------
            array, shape(T, n_states)
                The hindsight probabilities, P(S_{t}|O_{1:T}) for each t

            """
            pass
Beispiel #23
0
def mandelbrot_plot(x_center=-1.0,
                    y_center=0.0,
                    image_width=4.0,
                    max_iteration=500,
                    pixel_count=500,
                    base_color='steelblue',
                    iteration_level=1,
                    number_of_colors=30,
                    interact=False):
    r"""
    Interactive plot of the Mandelbrot set for the map `Q_c(z) = z^2 + c`.

    ALGORITHM:

    Let each pixel in the image be a point `c \in \mathbb{C}` and define the
    map `Q_c(z) = z^2 + c`. If `|Q_{c}^{k}(c)| > 2` for some `k \geq 0`, it
    follows that `Q_{c}^{n}(c) \to \infty`. Let `N` be the maximum number of
    iterations. Compute the first `N` points on the orbit of `0` under `Q_c`.
    If for any `k < N`, `|Q_{c}^{k}(0)| > 2`, we stop the iteration and assign
    a color to the point `c` based on how quickly `0` escaped to infinity under
    iteration of `Q_c`. If `|Q_{c}^{i}(0)| \leq 2` for all `i \leq N`, we assume
    `c` is in the Mandelbrot set and assign the point `c` the color black.

    REFERENCE:

    [Dev2005]_

    INPUT:

    - ``x_center`` -- double (optional - default: ``-1.0``), Real part
      of center point.

    - ``y_center`` -- double (optional - default: ``0.0``), Imaginary part
      of center point.

    - ``image_width`` -- double (optional - default: ``4.0``), width of
      image in the complex plane.

    - ``max_iteration`` -- long (optional - default: ``500``), maximum number
      of iterations the map ``Q_c(z)``.

    - ``pixel_count`` -- long (optional - default: ``500``), side length
      of image in number of pixels.

    - ``base_color`` -- RGB color (optional - default: ``'steelblue'``) color
      used to determine the coloring of set (any valid input for Color).

    - ``iteration_level`` -- long (optional - default: 1) number of iterations
      between each color level.

    - ``number_of_colors`` -- long (optional - default: 30) number of colors
      used to plot image.

    - ``interact`` -- boolean (optional - default: ``False``), controls
      whether plot will have interactive functionality.

    OUTPUT:

    24-bit RGB image of the Mandelbrot set in the complex plane.

    EXAMPLES:

    ::

        sage: mandelbrot_plot()
        500x500px 24-bit RGB image

    ::

        sage: mandelbrot_plot(pixel_count=1000)
        1000x1000px 24-bit RGB image

    ::

        sage: mandelbrot_plot(x_center=-1.11, y_center=0.2283, image_width=1/128,
        ....: max_iteration=2000, number_of_colors=500, base_color=[40, 100, 100])
        500x500px 24-bit RGB image

    To display an interactive plot of the Mandelbrot set in the Jupyter
    Notebook, set ``interact`` to ``True``::

        sage: mandelbrot_plot(interact=True)
        interactive(children=(FloatSlider(value=-1.0, description=u'Real center'...

    ::

        sage: mandelbrot_plot(interact=True, x_center=-0.75, y_center=0.25,
        ....:     image_width=1/2, number_of_colors=75)
        interactive(children=(FloatSlider(value=-0.75, description=u'Real center'...
    """
    base_color = Color(base_color)

    if interact:
        from ipywidgets.widgets import FloatSlider, IntSlider, ColorPicker, interact
        widgets = dict(
            x_center=FloatSlider(min=-1.0,
                                 max=1.0,
                                 step=EPS,
                                 value=x_center,
                                 description="Real center"),
            y_center=FloatSlider(min=-1.0,
                                 max=1.0,
                                 step=EPS,
                                 value=y_center,
                                 description="Imag center"),
            image_width=FloatSlider(min=EPS,
                                    max=4.0,
                                    step=EPS,
                                    value=image_width,
                                    description="Image width"),
            max_iteration=IntSlider(min=0,
                                    max=600,
                                    value=max_iteration,
                                    description="Iterations"),
            pixel_count=IntSlider(min=10,
                                  max=600,
                                  value=pixel_count,
                                  description="Pixels"),
            level_sep=IntSlider(min=1,
                                max=20,
                                value=iteration_level,
                                description="Color sep"),
            color_num=IntSlider(min=1,
                                max=100,
                                value=number_of_colors,
                                description="# Colors"),
            base_color=ColorPicker(value=base_color.html_color(),
                                   description="Base color"),
        )
        return interact(**widgets).widget(fast_mandelbrot_plot)

    return fast_mandelbrot_plot(x_center, y_center, image_width, max_iteration,
                                pixel_count, iteration_level, number_of_colors,
                                base_color)