Exemplo n.º 1
0
    def __init__(self, v, t, dual=False, color=None):
        r"""
        EXAMPLES::

            sage: from EkEkstar import kFace
            sage: F = kFace((0,0,0),(1,2))
            sage: F
            [(0, 0, 0), (1, 2)]
        """
        self._vector = (ZZ**len(v))(v)
        self._vector.set_immutable()
        self._dual = dual

        if t in ZZ:
            self._type = (t, )
        else:
            self._type = t

        if not all((tt in ZZ and 1 <= tt <= len(v)) for tt in self._type):
            raise ValueError(
                'The type must be a tuple of integers between 1 and {}'.format(
                    len(v)))

        if color is not None:
            self._color = Color(color)
        else:
            sorted_types = list(
                combinations(range(1,
                                   len(v) + 1), len(self._type)))
            Col = rainbow(len(sorted_types))
            D = dict(zip(sorted_types, Col))
            self._color = Color(D.get(self.sorted_type(), 'black'))
Exemplo n.º 2
0
def parse_color(info, base=None):
    r"""
    Parses the color.

    It transforms a valid color string into a color object and
    a color object into an RBG tuple of length 3. Otherwise,
    it multiplies the info by the base color.

    INPUT:

    - ``info`` - color, valid color str or number
    - ``base`` - tuple of length 3 (optional, default: None)

    OUTPUT:

    A tuple or color.

    EXAMPLES:

    From a color::

        sage: from sage.plot.plot3d.texture import parse_color
        sage: c = Color('red')
        sage: parse_color(c)
        (1.0, 0.0, 0.0)

    From a valid color str::

        sage: parse_color('red')
        RGB color (1.0, 0.0, 0.0)
        sage: parse_color('#ff0000')
        RGB color (1.0, 0.0, 0.0)

    From a non valid color str::

        sage: parse_color('redd')
        Traceback (most recent call last):
        ...
        ValueError: unknown color 'redd'

    From an info and a base::

        sage: opacity = 10
        sage: parse_color(opacity, base=(.2,.3,.4))
        (2.0, 3.0, 4.0)
    """
    if isinstance(info, Color):
        return info.rgb()
    elif isinstance(info, str):
        try:
            return Color(info)
        except KeyError:
            raise ValueError("unknown color '%s'" % info)
    else:
        r, g, b = base
        # We don't want to lose the data when we split it into its respective components.
        if not r: r = 1e-5
        if not g: g = 1e-5
        if not b: b = 1e-5
        return (float(info * r), float(info * g), float(info * b))
Exemplo n.º 3
0
def color_selector(default=(0, 0, 1), label=None, widget=None, hide_box=False):
    """
    A widget for choosing a color.

    INPUT:

    - ``default`` -- initial value

    - ``label`` -- optional label

    - ``hide_box`` -- (boolean) if True, do not show the textbox

    EXAMPLES::

        sage: from sage.repl.ipython_kernel.all_jupyter import color_selector
        sage: w = color_selector("orange", label="color me"); w
        SageColorPicker(value='#ffa500', description=u'color me')
        sage: w.get_interact_value()
        RGB color (1.0, 0.6470588235294118, 0.0)
        sage: color_selector(Color(0.1, 0.2, 0.3))
        SageColorPicker(value='#19334c')
    """
    # widget argument is silently ignored
    kwds = {"value": Color(default).html_color(), "concise": hide_box}
    if label is not None:
        kwds["description"] = u(label)
    return SageColorPicker(**kwds)
Exemplo n.º 4
0
 def _(real_center=input_box(x_center, 'Real'),
     im_center=input_box(y_center, 'Imaginary'),
     width=input_box(image_width, 'Width of Image'),
     iterations=input_box(max_iteration, 'Max Number of Iterations'),
     level_sep=input_box(iteration_level, 'Iterations between Colors'),
     color_num=input_box(number_of_colors, 'Number of Colors'),
     image_color=color_selector(default=Color([j/255 for j in base_color]),
      label="Image Color", hide_box=True)):
     return fast_mandelbrot_plot(real_center, im_center, width,
      iterations, pixel_count, level_sep, color_num, image_color).show()
Exemplo n.º 5
0
    def get_interact_value(self):
        """
        Return a Sage :class:`Color` corresponding to the value of this
        widget.

        EXAMPLES::

            sage: from sage.repl.ipython_kernel.widgets import SageColorPicker
            sage: SageColorPicker().get_interact_value()
            RGB color (0.0, 0.0, 0.0)
        """
        return Color(self.value)
Exemplo n.º 6
0
        def _(cx = input_box(c_real, '$Re(c)$'),
            cy = input_box(c_imag, '$Im(c)$'),
            real_center=input_box(x_center, 'Real Center'),
            im_center=input_box(y_center, 'Imaginary Center'),
            width=input_box(image_width, 'Width of Image'),
            iterations=input_box(max_iteration, 'Max Number of Iterations'),
            level_sep=input_box(iteration_level, 'Iterations between Colors'),
            color_num=input_box(number_of_colors, 'Number of Colors'),
            image_color=color_selector(default=Color([j/255 for j in base_color]),
             label="Image Color", hide_box=True),
            pt_color=color_selector(default=Color([j/255 for j in point_color]),
             label="Point Color", hide_box=True),
            mandel=checkbox(mandelbrot, label='Mandelbrot set')):

            if mandel:
                return julia_helper(cx, cy, real_center, im_center,
                 width, iterations, pixel_count, level_sep, color_num,
                 image_color, pt_color).show()

            else:
                return fast_julia_plot(cx, cy, real_center, im_center,
                 width, iterations, pixel_count, level_sep, color_num,
                 image_color).show()
Exemplo n.º 7
0
def geomrep(M1, B1=None, lineorders1=None, pd=None, sp=False):
    """
    Return a sage graphics object containing geometric representation of
    matroid M1.

    INPUT:

    - ``M1`` -- A matroid.
    - ``B1`` -- (optional) A list of elements in ``M1.groundset()`` that
      correspond to a basis of ``M1`` and will be placed as vertices of the
      triangle in the geometric representation of ``M1``.
    - ``lineorders1`` -- (optional) A list of ordered lists of elements of
      ``M1.grondset()`` such that if a line in geometric representation is
      setwise same as any of these then points contained will be traversed in
      that order thus overriding internal order deciding heuristic.
    - ``pd`` - (optional) A dictionary mapping ground set elements to their
      (x,y) positions.
    - ``sp`` -- (optional) If True, a positioning dictionary and line orders
      will be placed in ``M._cached_info``.

    OUTPUT:

    A sage graphics object of type <class 'sage.plot.graphics.Graphics'> that
    corresponds to the geometric representation of the matroid.

    EXAMPLES::

        sage: from sage.matroids import matroids_plot_helpers
        sage: M=matroids.named_matroids.P7()
        sage: G=matroids_plot_helpers.geomrep(M)
        sage: G.show(xmin=-2, xmax=3, ymin=-2, ymax=3)
        sage: M=matroids.named_matroids.P7()
        sage: G=matroids_plot_helpers.geomrep(M,lineorders1=[['f','e','d']])
        sage: G.show(xmin=-2, xmax=3, ymin=-2, ymax=3)

    .. NOTE::

            This method does NOT do any checks.
    """
    G = Graphics()
    # create lists of loops and parallel elements and simplify given matroid
    [M, L, P] = slp(M1, pos_dict=pd, B=B1)
    if B1 is None:
        B1 = list(M.basis())
    M._cached_info = M1._cached_info

    if M.rank() == 0:
        limits = None
        loops = L
        looptext = ", ".join([str(l) for l in loops])
        rectx = -1
        recty = -1
        rectw = 0.5 + 0.4 * len(loops) + 0.5  # controlled based on len(loops)
        recth = 0.6
        G += polygon2d(
            [[rectx, recty], [rectx, recty + recth],
             [rectx + rectw, recty + recth], [rectx + rectw, recty]],
            color='black',
            fill=False,
            thickness=4)
        G += text(looptext, (rectx + 0.5, recty + 0.3),
                  color='black',
                  fontsize=13)
        G += point((rectx + 0.2, recty + 0.3),
                   color=Color('#BDBDBD'),
                   size=300,
                   zorder=2)
        G += text('Loop(s)',
                  (rectx + 0.5 + 0.4 * len(loops) + 0.1, recty + 0.3),
                  fontsize=13,
                  color='black')
        limits = tracklims(limits, [rectx, rectx + rectw],
                           [recty, recty + recth])
        G.axes(False)
        G.axes_range(xmin=limits[0] - 0.5,
                     xmax=limits[1] + 0.5,
                     ymin=limits[2] - 0.5,
                     ymax=limits[3] + 0.5)
        return G
    elif M.rank() == 1:
        if M._cached_info is not None and \
           'plot_positions' in M._cached_info.keys() and \
           M._cached_info['plot_positions'] is not None:
            pts = M._cached_info['plot_positions']
        else:
            pts = {}
            gnd = sorted(M.groundset())
        pts[gnd[0]] = (1, float(2) / 3)
        G += point((1, float(2) / 3),
                   size=300,
                   color=Color('#BDBDBD'),
                   zorder=2)
        pt = [1, float(2) / 3]
        if len(P) == 0:
            G += text(gnd[0], (float(pt[0]), float(pt[1])),
                      color='black',
                      fontsize=13)
        pts2 = pts
        # track limits [xmin,xmax,ymin,ymax]
        pl = [list(x) for x in pts2.values()]
        lims = tracklims([None, None, None, None], [pt[0] for pt in pl],
                         [pt[1] for pt in pl])
    elif M.rank() == 2:
        nB1 = list(set(list(M.groundset())) - set(B1))
        bline = []
        for j in nB1:
            if M.is_dependent([j, B1[0], B1[1]]):
                bline.append(j)
        interval = len(bline) + 1
        if M._cached_info is not None and \
           'plot_positions' in M._cached_info.keys() and \
           M._cached_info['plot_positions'] is not None:
            pts2 = M._cached_info['plot_positions']
        else:
            pts2 = {}
            pts2[B1[0]] = (0, 0)
            pts2[B1[1]] = (2, 0)
            lpt = list(pts2[B1[0]])
            rpt = list(pts2[B1[1]])
            for k in range(len(bline)):
                cc = (float(1) / interval) * (k + 1)
                pts2[bline[k]] = (cc * lpt[0] + (1 - cc) * rpt[0],
                                  cc * lpt[1] + (1 - cc) * rpt[1])
            if sp is True:
                M._cached_info['plot_positions'] = pts2
        # track limits [xmin,xmax,ymin,ymax]
        pl = [list(x) for x in pts2.values()]
        lims = tracklims([None, None, None, None], [pt[0] for pt in pl],
                         [pt[1] for pt in pl])
        bline.extend(B1)
        ptsx, ptsy, x_i, y_i = createline(pts2, bline, lineorders1)
        lims = tracklims(lims, x_i, y_i)
        G += line(zip(x_i, y_i), color='black', thickness=3, zorder=1)
        pels = [
            p for p in pts2.keys() if any([M1.rank([p, q]) == 1 for q in P])
        ]
        allpts = [list(pts2[i]) for i in M.groundset()]
        xpts = [float(k[0]) for k in allpts]
        ypts = [float(k[1]) for k in allpts]
        G += points(zip(xpts, ypts),
                    color=Color('#BDBDBD'),
                    size=300,
                    zorder=2)
        for i in pts2:
            if i not in pels:
                pt = list(pts2[i])
                G += text(i, (float(pt[0]), float(pt[1])),
                          color='black',
                          fontsize=13)
    else:
        if M._cached_info is None or \
           'plot_positions' not in M._cached_info.keys() or \
           M._cached_info['plot_positions'] is None:
            (pts, trilines, nontripts,
             curvedlines) = it(M1, B1, list(set(M.groundset()) - set(B1)),
                               list(set(L) | set(P)))
            pts2 = addnontripts([B1[0], B1[1], B1[2]], nontripts, pts)
            trilines.extend(curvedlines)
        else:
            pts2 = M._cached_info['plot_positions']
            trilines = [
                list(set(list(x)).difference(L | P)) for x in M1.flats(2)
                if len(list(x)) >= 3
            ]
        pl = [list(x) for x in pts2.values()]
        lims = tracklims([None, None, None, None], [pt[0] for pt in pl],
                         [pt[1] for pt in pl])
        j = 0
        for ll in trilines:
            if len(ll) >= 3:
                ptsx, ptsy, x_i, y_i = createline(pts2, ll, lineorders1)
                lims = tracklims(lims, x_i, y_i)
                G += line(zip(x_i, y_i), color='black', thickness=3, zorder=1)
        pels = [
            p for p in pts2.keys() if any([M1.rank([p, q]) == 1 for q in P])
        ]
        allpts = [list(pts2[i]) for i in M.groundset()]
        xpts = [float(k[0]) for k in allpts]
        ypts = [float(k[1]) for k in allpts]
        G += points(zip(xpts, ypts),
                    color=Color('#BDBDBD'),
                    size=300,
                    zorder=2)
        for i in pts2:
            if i not in pels:
                pt = list(pts2[i])
                G += text(i, (float(pt[0]), float(pt[1])),
                          color='black',
                          fontsize=13)
        if sp is True:
            M1._cached_info['plot_positions'] = pts2
            M1._cached_info['plot_lineorders'] = lineorders1
    # deal with loops and parallel elements
    G, lims = addlp(M1, M, L, P, pts2, G, lims)
    G.axes(False)
    G.axes_range(xmin=lims[0] - 0.5,
                 xmax=lims[1] + 0.5,
                 ymin=lims[2] - 0.5,
                 ymax=lims[3] + 0.5)
    return G
Exemplo n.º 8
0
def addlp(M, M1, L, P, ptsdict, G=None, limits=None):
    """
    Return a graphics object containing loops (in inset) and parallel elements
    of matroid.

    INPUT:

    - ``M`` -- A matroid.
    - ``M1`` -- A simple matroid corresponding to ``M``.
    - ``L`` -- List of elements in ``M.groundset()`` that are loops of matroid
      ``M``.
    - ``P`` -- List of elements in ``M.groundset()`` not in
      ``M.simplify.groundset()`` or ``L``.
    - ``ptsdict`` -- A dictionary containing elements in ``M.groundset()`` not
      necessarily containing elements of ``L``.
    - ``G`` -- (optional) A sage graphics object to which loops and parallel
      elements of matroid `M` added .
    - ``limits``-- (optional) Current axes limits [xmin,xmax,ymin,ymax].

    OUTPUT:

    A 2-tuple containing:

    1. A sage graphics object containing loops and parallel elements of
       matroid ``M``
    2. axes limits array

    EXAMPLES::

        sage: from sage.matroids import matroids_plot_helpers
        sage: M=Matroid(ring=GF(2), matrix=[[1, 0, 0, 0, 1, 1, 1,0,1],
        ....: [0, 1, 0, 1, 0, 1, 1,0,0],[0, 0, 1, 1, 1, 0, 1,0,0]])
        sage: [M1,L,P]=matroids_plot_helpers.slp(M)
        sage: G,lims=matroids_plot_helpers.addlp(M,M1,L,P,{0:(0,0)})
        sage: G.show(axes=False)

    .. NOTE::

            This method does NOT do any checks.

    """
    if G is None:
        G = Graphics()
    # deal with loops
    if len(L) > 0:
        loops = L
        looptext = ", ".join([str(l) for l in loops])
        if (limits is None):
            rectx = -1
            recty = -1
        else:
            rectx = limits[0]
            recty = limits[2] - 1
        rectw = 0.5 + 0.4 * len(loops) + 0.5  # controlled based on len(loops)
        recth = 0.6
        G += polygon2d(
            [[rectx, recty], [rectx, recty + recth],
             [rectx + rectw, recty + recth], [rectx + rectw, recty]],
            color='black',
            fill=False,
            thickness=4)
        G += text(looptext, (rectx + 0.5, recty + 0.3),
                  color='black',
                  fontsize=13)
        G += point((rectx + 0.2, recty + 0.3),
                   color=Color('#BDBDBD'),
                   size=300,
                   zorder=2)
        G += text('Loop(s)',
                  (rectx + 0.5 + 0.4 * len(loops) + 0.1, recty + 0.3),
                  fontsize=13,
                  color='black')
        limits = tracklims(limits, [rectx, rectx + rectw],
                           [recty, recty + recth])
    # deal with parallel elements
    if len(P) > 0:
        # create list of lists where inner lists are parallel classes
        pcls = []
        gnd = sorted(list(M1.groundset()))
        for g in gnd:
            pcl = [g]
            for p in P:
                if M.rank([g, p]) == 1:
                    pcl.extend([p])
            pcls.append(pcl)
        ext_gnd = list(M.groundset())
        for pcl in pcls:
            if len(pcl) > 1:
                basept = list(ptsdict[pcl[0]])
                if len(pcl) <= 2:
                    # add side by side
                    ptsdict[pcl[1]] = (basept[0], basept[1] - 0.13)
                    G += points(zip([basept[0]], [basept[1] - 0.13]),
                                color=Color('#BDBDBD'),
                                size=300,
                                zorder=2)
                    G += text(pcl[0], (float(basept[0]), float(basept[1])),
                              color='black',
                              fontsize=13)
                    G += text(pcl[1],
                              (float(basept[0]), float(basept[1]) - 0.13),
                              color='black',
                              fontsize=13)
                    limits = tracklims(limits, [basept[0]], [basept[1] - 0.13])
                else:
                    # add in a bracket
                    pce = sorted([str(kk) for kk in pcl])
                    l = newlabel(set(ext_gnd))
                    ext_gnd.append(l)
                    G += text(
                        l + '={ ' + ", ".join(pce) + ' }',
                        (float(basept[0]), float(basept[1] - 0.2) - 0.034),
                        color='black',
                        fontsize=13)
                    G += text(l, (float(basept[0]), float(basept[1])),
                              color='black',
                              fontsize=13)
                    limits = tracklims(limits, [basept[0]],
                                       [(basept[1] - 0.2) - 0.034])
    return G, limits
Exemplo n.º 9
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)
Exemplo n.º 10
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)
Exemplo n.º 11
0
def Texture(id=None, **kwds):
    r"""
    Return a texture.

    INPUT:

    - ``id`` - a texture (optional, default: None), a dict, a color, a
      str, a tuple, None or any other type acting as an ID. If ``id`` is
      None and keyword ``texture`` is empty, then it returns a unique texture object.
    - ``texture`` - a texture
    - ``color`` - tuple or str, (optional, default: (.4, .4, 1))
    - ``opacity`` - number between 0 and 1 (optional, default: 1)
    - ``ambient`` - number (optional, default: 0.5)
    - ``diffuse`` - number (optional, default: 1)
    - ``specular`` - number (optional, default: 0)
    - ``shininess`` - number (optional, default: 1)
    - ``name`` - str (optional, default: None)
    - ``**kwds`` - other valid keywords

    OUTPUT:

    A texture object.

    EXAMPLES:

    Texture from integer ``id``::

        sage: from sage.plot.plot3d.texture import Texture
        sage: Texture(17)
        Texture(17, 6666ff)

    Texture from rational ``id``::

        sage: Texture(3/4)
        Texture(3/4, 6666ff)

    Texture from a dict::

        sage: Texture({'color':'orange','opacity':0.5})
        Texture(texture..., orange, ffa500)

    Texture from a color::

        sage: c = Color('red')
        sage: Texture(c)
        Texture(texture..., ff0000)

    Texture from a valid string color::

        sage: Texture('red')
        Texture(texture..., red, ff0000)

    Texture from a non valid string color::

        sage: Texture('redd')
        Texture(redd, 6666ff)

    Texture from a tuple::

        sage: Texture((.2,.3,.4))
        Texture(texture..., 334c66)

    Now accepting negative arguments, reduced modulo 1::

        sage: Texture((-3/8, 1/2, 3/8))
        Texture(texture..., 9f7f5f)

    Textures using other keywords::

        sage: Texture(specular=0.4)
        Texture(texture..., 6666ff)
        sage: Texture(diffuse=0.4)
        Texture(texture..., 6666ff)
        sage: Texture(shininess=0.3)
        Texture(texture..., 6666ff)
        sage: Texture(ambient=0.7)
        Texture(texture..., 6666ff)
    """
    if isinstance(id, Texture_class):
        return id
    if 'texture' in kwds:
        t = kwds['texture']
        if is_Texture(t):
            return t
        else:
            raise TypeError("texture keyword must be a texture object")
    if isinstance(id, dict):
        kwds = id
        if 'rgbcolor' in kwds:
            kwds['color'] = kwds['rgbcolor']
        id = None
    elif isinstance(id, Color):
        kwds['color'] = id.rgb()
        id = None
    elif isinstance(id, str) and id in colors:
        kwds['color'] = id
        id = None
    elif isinstance(id, tuple):
        kwds['color'] = Color(id).rgb()
        id = None
    if id is None:
        id = _new_global_texture_id()
    return Texture_class(id, **kwds)
Exemplo n.º 12
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)
Exemplo n.º 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)
Exemplo n.º 14
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)
Exemplo n.º 15
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)