 CoCalc Public Filessupport / 2020-02-14-poset.sagews
Author: William A. Stein
Description: Jupyter notebook support/2015-06-04-141749-bokeh.ipynb
P=Poset((Subsets([1..3]),lambda A,B: A.issubset(B)))

latex.eval(str(latex(P))) ''
z = latex(P)

show??

   File: /cocalc/lib/python2.7/site-packages/smc_sagews/sage_salvus.py
Source:
def show(*objs, **kwds):
"""
Show a 2d or 3d graphics object (or objects), animation, or matplotlib figure, or show an
expression typeset nicely using LaTeX.

- display: (default: True); if True, use display math for expression (big and centered).

- svg: (default: True); if True, show 2d plots using svg (otherwise use png)

- d3: (default: True); if True, show graphs (vertices and edges) using an interactive D3 viewer
for the many options for this viewer, type

import smc_sagews.graphics
smc_sagews.graphics.graph_to_d3_jsonable?

If false, graphs are converted to plots and displayed as usual.

- renderer: (default: 'webgl'); for 3d graphics
- 'webgl' (fastest) using hardware accelerated 3d;
- 'canvas' (slower) using a 2d canvas, but may work better with transparency;
- 'tachyon' -- a ray traced static image.

- spin: (default: False); spins 3d plot, with number determining speed (requires mouse over plot)

- events: if given, {'click':foo, 'mousemove':bar}; each time the user clicks,
the function foo is called with a 2-tuple (x,y) where they clicked.  Similarly
for mousemove.  This works for Sage 2d graphics and matplotlib figures.

- viewer: optional string, set to "tachyon" for static ray-tracing view of 3d image

- background: string (default: 'transparent'), specifies background color for 3d images.
Ignored if viewer is set to 'tachyon' or if object type is Tachyon.
May be 'transparent' or any valid CSS color string, e.g.: 'red', '#00ff00', 'rgb(0,0,255)'.

- foreground: string, specifies frame color for 3d images. Defaults to 'gray' when
background is 'transparent', otherwise default is computed for visibility based on canvas
background.

ANIMATIONS:

- animations are by default encoded and displayed using an efficiently web-friendly
format (currently webm, which is **not supported** by Safari or IE).

- delay - integer (default: 20); delay in hundredths of a
second between frames.

- gif=False -- if you set gif=True, instead use an animated gif,
which is much less efficient, but works on all browsers.

You can also use options directly to the animate command, e.g., the figsize option below:

a = animate([plot(sin(x + a), (x, 0, 2*pi)) for a in [0, pi/4, .., 2*pi]], figsize=6)
show(a, delay=30)

EXAMPLES:

Some examples:

show(2/3)
show([1, 4/5, pi^2 + e], 1+pi)
show(x^2, display=False)
show(e, plot(sin))

Here's an example that illustrates creating a clickable image with events::

@interact
def f0(fun=x*sin(x^2), mousemove='', click='(0,0)'):
click = sage_eval(click)
g = plot(fun, (x,0,5), zorder=0) + point(click, color='red', pointsize=100, zorder=10)
ymax = g.ymax(); ymin = g.ymin()
m = fun.derivative(x)(x=click)
b =  fun(x=click) - m*click
g += plot(m*x + b, (click-1,click+1), color='red', zorder=10)
def h(p):
f0.mousemove = p
def c(p):
f0(click=p)
show(g, events={'click':c, 'mousemove':h}, svg=True, gridlines='major', ymin=ymin, ymax=ymax)
"""
# svg=True, d3=True,
svg = kwds.get('svg', True)
d3 = kwds.get('d3', True)
display = kwds.get('display', True)
for t in ['svg', 'd3', 'display']:
if t in kwds:
del kwds[t]
from smc_sagews import graphics

def show0(obj, combine_all=False):
# Either show the object and return None or
# return a string of html to represent obj.
if isinstance(obj, GRAPHICS_MODULES_SHOW):
show_2d_plot_using_matplotlib(obj, svg=svg, **kwds)
elif isinstance(obj, Animation):
show_animation(obj, **kwds)
elif isinstance(obj, Graphics3d):

# _extra_kwds processing follows the example of
# src/smc_sagews/smc_sagews/graphics.py:show_3d_plot_using_threejs()
extra_kwds = {} if obj._extra_kwds is None else obj._extra_kwds
for k in [
'spin',
'renderer',
'viewer',
'frame',
'height',
'width',
'background',
'foreground',
'aspect_ratio',
]:
if k in extra_kwds and k not in kwds:
kwds[k] = obj._extra_kwds[k]

if kwds.get('viewer') == 'tachyon':
show_3d_plot_using_tachyon(obj, **kwds)
else:
if kwds.get('viewer') == 'threejs':
del kwds['viewer']
if kwds.get('online'):
del kwds['online']
salvus.threed(obj, **kwds)
# graphics.show_3d_plot_using_threejs(obj, **kwds)
elif isinstance(obj, Tachyon):
show_3d_plot_using_tachyon(obj, **kwds)
elif isinstance(
obj, (sage.graphs.graph.Graph, sage.graphs.digraph.DiGraph)):
if d3:
show_graph_using_d3(obj, **kwds)
else:
show(obj.plot(), **kwds)
elif is_string(obj):
return obj
elif isinstance(obj, (list, tuple)):
v = []
for a in obj:
b = show0(a)
if b is not None:
v.append(b)
if combine_all:
return ' '.join(v)
s = ', '.join(v)
if isinstance(obj, list):
return '[%s]' % s
else:
return '(%s)' % s
elif is_dataframe(obj):
html(obj.to_html(), hide=False)
else:
__builtins__['_'] = obj
s = str(sage.misc.latex.latex(obj))
if r'\text{\texttt' in s and 'tikzpicture' not in s:
# In this case the mathjax latex mess is so bad, it is better to just print and give up!
print(obj)
return
# Add anything here that Sage produces and mathjax can't handle, and
# which people complain about... (obviously, I wish there were a way to
# know -- e.g., if Sage had a way to tell whether latex it produces
# will work with mathjax or not).
if '\\begin{tikzpicture}' in s or '\\raisebox' in s:
# special case -- mathjax has no support for tikz or \raisebox so we just immediately display it (as a png); this is
# better than nothing.
sage.misc.latex.latex.eval(s)
return ''
elif r'\begin{tabular}' in s:
# tabular is an environment for text, not formular.
# Sage's tabular should actually use \array!
sage.misc.latex.latex.eval(s)
return ''
# default
elif display:
return "$\\displaystyle %s$" % s
else:
return "$%s$" % s

sys.stdout.flush()
sys.stderr.flush()
s = show0(objs, combine_all=True)

if six.PY3:
from html import escape
elif six.PY2:
# deprecated in py3
from cgi import escape

if s is not None:
if len(s) > 0:
if display:
salvus.html("<div align='center'>%s</div>" % escape(s))
else:
salvus.html("<div>%s</div>" % escape(s))
sys.stdout.flush()
sys.stderr.flush()


show(P) view(P) P.plot() show(P) type(P)

<class 'sage.combinat.posets.posets.FinitePoset_with_category'>
show??

   File: /cocalc/lib/python2.7/site-packages/smc_sagews/sage_salvus.py
Source:
def show(*objs, **kwds):
"""
Show a 2d or 3d graphics object (or objects), animation, or matplotlib figure, or show an
expression typeset nicely using LaTeX.

- display: (default: True); if True, use display math for expression (big and centered).

- svg: (default: True); if True, show 2d plots using svg (otherwise use png)

- d3: (default: True); if True, show graphs (vertices and edges) using an interactive D3 viewer
for the many options for this viewer, type

import smc_sagews.graphics
smc_sagews.graphics.graph_to_d3_jsonable?

If false, graphs are converted to plots and displayed as usual.

- renderer: (default: 'webgl'); for 3d graphics
- 'webgl' (fastest) using hardware accelerated 3d;
- 'canvas' (slower) using a 2d canvas, but may work better with transparency;
- 'tachyon' -- a ray traced static image.

- spin: (default: False); spins 3d plot, with number determining speed (requires mouse over plot)

- events: if given, {'click':foo, 'mousemove':bar}; each time the user clicks,
the function foo is called with a 2-tuple (x,y) where they clicked.  Similarly
for mousemove.  This works for Sage 2d graphics and matplotlib figures.

- viewer: optional string, set to "tachyon" for static ray-tracing view of 3d image

- background: string (default: 'transparent'), specifies background color for 3d images.
Ignored if viewer is set to 'tachyon' or if object type is Tachyon.
May be 'transparent' or any valid CSS color string, e.g.: 'red', '#00ff00', 'rgb(0,0,255)'.

- foreground: string, specifies frame color for 3d images. Defaults to 'gray' when
background is 'transparent', otherwise default is computed for visibility based on canvas
background.

ANIMATIONS:

- animations are by default encoded and displayed using an efficiently web-friendly
format (currently webm, which is **not supported** by Safari or IE).

- delay - integer (default: 20); delay in hundredths of a
second between frames.

- gif=False -- if you set gif=True, instead use an animated gif,
which is much less efficient, but works on all browsers.

You can also use options directly to the animate command, e.g., the figsize option below:

a = animate([plot(sin(x + a), (x, 0, 2*pi)) for a in [0, pi/4, .., 2*pi]], figsize=6)
show(a, delay=30)

EXAMPLES:

Some examples:

show(2/3)
show([1, 4/5, pi^2 + e], 1+pi)
show(x^2, display=False)
show(e, plot(sin))

Here's an example that illustrates creating a clickable image with events::

@interact
def f0(fun=x*sin(x^2), mousemove='', click='(0,0)'):
click = sage_eval(click)
g = plot(fun, (x,0,5), zorder=0) + point(click, color='red', pointsize=100, zorder=10)
ymax = g.ymax(); ymin = g.ymin()
m = fun.derivative(x)(x=click)
b =  fun(x=click) - m*click
g += plot(m*x + b, (click-1,click+1), color='red', zorder=10)
def h(p):
f0.mousemove = p
def c(p):
f0(click=p)
show(g, events={'click':c, 'mousemove':h}, svg=True, gridlines='major', ymin=ymin, ymax=ymax)
"""
# svg=True, d3=True,
svg = kwds.get('svg', True)
d3 = kwds.get('d3', True)
display = kwds.get('display', True)
for t in ['svg', 'd3', 'display']:
if t in kwds:
del kwds[t]
from smc_sagews import graphics

def show0(obj, combine_all=False):
# Either show the object and return None or
# return a string of html to represent obj.
if isinstance(obj, GRAPHICS_MODULES_SHOW):
show_2d_plot_using_matplotlib(obj, svg=svg, **kwds)
elif isinstance(obj, Animation):
show_animation(obj, **kwds)
elif isinstance(obj, Graphics3d):

# _extra_kwds processing follows the example of
# src/smc_sagews/smc_sagews/graphics.py:show_3d_plot_using_threejs()
extra_kwds = {} if obj._extra_kwds is None else obj._extra_kwds
for k in [
'spin',
'renderer',
'viewer',
'frame',
'height',
'width',
'background',
'foreground',
'aspect_ratio',
]:
if k in extra_kwds and k not in kwds:
kwds[k] = obj._extra_kwds[k]

if kwds.get('viewer') == 'tachyon':
show_3d_plot_using_tachyon(obj, **kwds)
else:
if kwds.get('viewer') == 'threejs':
del kwds['viewer']
if kwds.get('online'):
del kwds['online']
salvus.threed(obj, **kwds)
# graphics.show_3d_plot_using_threejs(obj, **kwds)
elif isinstance(obj, Tachyon):
show_3d_plot_using_tachyon(obj, **kwds)
elif isinstance(
obj, (sage.graphs.graph.Graph, sage.graphs.digraph.DiGraph)):
if d3:
show_graph_using_d3(obj, **kwds)
else:
show(obj.plot(), **kwds)
elif is_string(obj):
return obj
elif isinstance(obj, (list, tuple)):
v = []
for a in obj:
b = show0(a)
if b is not None:
v.append(b)
if combine_all:
return ' '.join(v)
s = ', '.join(v)
if isinstance(obj, list):
return '[%s]' % s
else:
return '(%s)' % s
elif is_dataframe(obj):
html(obj.to_html(), hide=False)
else:
__builtins__['_'] = obj
s = str(sage.misc.latex.latex(obj))
if r'\text{\texttt' in s and 'tikzpicture' not in s:
# In this case the mathjax latex mess is so bad, it is better to just print and give up!
print(obj)
return
# Add anything here that Sage produces and mathjax can't handle, and
# which people complain about... (obviously, I wish there were a way to
# know -- e.g., if Sage had a way to tell whether latex it produces
# will work with mathjax or not).
if '\\begin{tikzpicture}' in s or '\\raisebox' in s:
# special case -- mathjax has no support for tikz or \raisebox so we just immediately display it (as a png); this is
# better than nothing.
sage.misc.latex.latex.eval(s)
return ''
elif r'\begin{tabular}' in s:
# tabular is an environment for text, not formular.
# Sage's tabular should actually use \array!
sage.misc.latex.latex.eval(s)
return ''
# default
elif display:
return "$\\displaystyle %s$" % s
else:
return "$%s$" % s

sys.stdout.flush()
sys.stderr.flush()
s = show0(objs, combine_all=True)

if six.PY3:
from html import escape
elif six.PY2:
# deprecated in py3
from cgi import escape

if s is not None:
if len(s) > 0:
if display:
salvus.html("<div align='center'>%s</div>" % escape(s))
else:
salvus.html("<div>%s</div>" % escape(s))
sys.stdout.flush()
sys.stderr.flush()


show(P) P.plot??

   File: /ext/sage/sage-8.9_1804/local/lib/python2.7/site-packages/sage/combinat/posets/posets.py
Source:
def plot(self, label_elements=True, element_labels=None,
layout='acyclic', cover_labels=None,
**kwds):
r"""
Return a Graphic object for the Hasse diagram of the poset.

If the poset is ranked, the plot uses the rank function for
the heights of the elements.

INPUT:

- Options to change element look:

* element_colors - a dictionary where keys are colors and values
are lists of elements
* element_color - a color for elements not set in
element_colors
* element_shape - the shape of elements, like 's' for
square; see https://matplotlib.org/api/markers_api.html for the list
* element_size (default: 200) - the size of elements
* label_elements (default: True) - whether to display
element labels
* element_labels (default: None) - a dictionary where keys
are elements and values are labels to show

- Options to change cover relation look:

* cover_colors - a dictionary where keys are colors and values
are lists of cover relations given as pairs of elements
* cover_color - a color for elements not set in
cover_colors
* cover_style - style for cover relations: 'solid',
'dashed', 'dotted' or 'dashdot'
* cover_labels - a dictionary, list or function representing
labels of the covers of the poset. When set to None (default)
no label is displayed on the edges of the Hasse Diagram.
* cover_labels_background - a background color for cover
relations. The default is "white". To achieve a transparent
background use "transparent".

- Options to change overall look:

* figsize (default: 8) - size of the whole plot
* title - a title for the plot
* fontsize - fontsize for the title
* border (default: False) - whether to draw a border over the
plot

.. NOTE::

All options of :meth:GenericGraph.plot
<sage.graphs.generic_graph.GenericGraph.plot> are also available
through this function.

EXAMPLES:

This function can be used without any parameters::

sage: D12 = posets.DivisorLattice(12)
sage: D12.plot()
Graphics object consisting of 14 graphics primitives

Just the abstract form of the poset; examples of relabeling::

sage: D12.plot(label_elements=False)
Graphics object consisting of 8 graphics primitives
sage: d = {1: 0, 2: 'a', 3: 'b', 4: 'c', 6: 'd', 12: 1}
sage: D12.plot(element_labels=d)
Graphics object consisting of 14 graphics primitives
sage: d = {i:str(factor(i)) for i in D12}
sage: D12.plot(element_labels=d)
Graphics object consisting of 14 graphics primitives

Some settings for coverings::

sage: d = {(a, b): b/a for a, b in D12.cover_relations()}
sage: D12.plot(cover_labels=d, cover_color='gray', cover_style='dotted')
Graphics object consisting of 21 graphics primitives

To emphasize some elements and show some options::

sage: L = LatticePoset({0: [1, 2, 3, 4], 1: , 2: [6, 7],
....:                   3: [5, 9], 4: [5, 6, 10, 11], 5: ,
....:                   6: , 7: [12, 8, 9], 8: , 9: ,
....:                   10: , 11: , 12: })
sage: F = L.frattini_sublattice()
sage: F_internal = [c for c in F.cover_relations() if c in L.cover_relations()]
sage: L.plot(figsize=12, border=True, element_shape='s',
....:        element_size=400, element_color='white',
....:        element_colors={'blue': F, 'green': L.double_irreducibles()},
....:        cover_color='lightgray', cover_colors={'black': F_internal},
....:        title='The Frattini\nsublattice in blue', fontsize=10)
Graphics object consisting of 39 graphics primitives

TESTS:

We check that label_elements and element_labels are honored::

sage: def get_plot_labels(P): return sorted(t.string for t in P if isinstance(t, sage.plot.text.Text))
sage: P1 = Poset({ 0:[1,2], 1:, 2:[3,4] })
sage: P2 = Poset({ 0:[1,2], 1:, 2:[3,4] }, facade=True)
sage: get_plot_labels(P1.plot(label_elements=False))
[]
sage: get_plot_labels(P1.plot(label_elements=True))
[u'0', u'1', u'2', u'3', u'4']
sage: element_labels = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e'}
sage: get_plot_labels(P1.plot(element_labels=element_labels))
[u'a', u'b', u'c', u'd', u'e']
sage: get_plot_labels(P2.plot(element_labels=element_labels))
[u'a', u'b', u'c', u'd', u'e']

The following checks that :trac:18936 has been fixed and labels still work::

sage: P = Poset({0: [1,2], 1:})
sage: heights = {1 : , 2 : , 3 : [2,3]}
sage: P.plot(heights=heights)
Graphics object consisting of 8 graphics primitives
sage: elem_labels = {0 : 'a', 1 : 'b', 2 : 'c', 3 : 'd'}
sage: P.plot(element_labels=elem_labels, heights=heights)
Graphics object consisting of 8 graphics primitives

The following checks that equal labels are allowed (:trac:15206)::

sage: P = Poset({1: [2,3]})
sage: labs = {i: P.rank(i) for i in range(1, 4)}
sage: labs
{1: 0, 2: 1, 3: 1}
sage: P.plot(element_labels=labs)
Graphics object consisting of 6 graphics primitives

The following checks that non-hashable labels are allowed (:trac:15206)::

sage: P = Poset({1: [2,3]})
sage: labs = {1: [2, 3], 2: [], 3: []}
sage: labs
{1: [2, 3], 2: [], 3: []}
sage: P.plot(element_labels=labs)
Graphics object consisting of 6 graphics primitives

Plot of the empty poset::

sage: P = Poset({})
sage: P.plot()
Graphics object consisting of 0 graphics primitives
"""
from collections import defaultdict
graph = self.hasse_diagram()

rename = {'element_color': 'vertex_color',
'element_colors': 'vertex_colors',
'element_size': 'vertex_size',
'element_shape': 'vertex_shape',
'cover_color': 'edge_color',
'cover_labels_background': 'edge_labels_background',
'cover_colors': 'edge_colors',
'cover_style': 'edge_style',
'border': 'graph_border'}
for param in rename:
tmp = kwds.pop(param, None)
if tmp is not None:
kwds[rename[param]] = tmp

heights = kwds.pop('heights', None)
if heights is None:
rank_function = self.rank_function()
if rank_function: # use the rank function to set the heights
heights = defaultdict(list)
for i in self:
heights[rank_function(i)].append(i)
# if relabeling is needed
if label_elements and element_labels is not None:
from sage.misc.element_with_label import ElementWithLabel
relabeling = dict((self(element), ElementWithLabel(self(element), label))
for (element, label) in element_labels.items())
graph = graph.relabel(relabeling, inplace = False)
if heights is not None:
for key in heights:
heights[key] = [relabeling[i] for i in heights[key]]

if cover_labels is not None:
if callable(cover_labels):
for (v, w) in graph.edges(labels=False):
graph.set_edge_label(v, w, cover_labels(v, w))
elif isinstance(cover_labels, dict):
for (v, w) in cover_labels:
graph.set_edge_label(self(v), self(w),
cover_labels[(v, w)])
else:
for (v, w, l) in cover_labels:
graph.set_edge_label(self(v), self(w), l)
cover_labels = True
else:
cover_labels = False

return graph.plot(vertex_labels=label_elements,
edge_labels=cover_labels,
layout=layout,
heights=heights,
**kwds)