Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

buttons on interact acting twice first time

Hi

Ubuntu 18.04 Jupyter notebook SageMath 9.0

Q1):

I can't find why the first time I click on r or on t buttons it produces 2 rotations or 2 reflections, then only one as it should do, every other time.(maybe there is something wrong in my code ? ) (to enlarge the output cell, menu cell -> Current output → toggle scrolling and click on left side of the output cell)

Q2):

why this code do not work on SageCell ?

or is there a bug in interact button ? https://ask.sagemath.org/question/48338/interact-button-reacting-twice/

#%matplotlib notebook
#import matplotlib.pyplot as plt
#from matplotlib.animation import FuncAnimation
#import animatplot as amp
#
import numpy as np
from scipy.spatial import distance
from sage.plot.point import Point

#np.set_printoptions(linewidth=110)

""" choose side number of the 2D polygon """
var('n')
n=6

maL=[]
shiftAngle=-2*pi/(2*n)
for i in range(1,n+1) :
    maL.append([cos(i*2*pi/n+shiftAngle),sin(i*2*pi/n+shiftAngle)])

#mL=[[1,1],[-1,1],[-1,-1],[1,-1]]
m=matrix(maL).transpose()

max = 1.5 # figure span
figsizeV=5

def chooseColor(colorsNumber):
    if 'colorL' not in locals():
        colorL=[]
        for i in range(0,colorsNumber) :
            colorL.append([random(),random(),random()])
        #show(colorL)


    D=distance.cdist(colorL, colorL, 'cityblock')

    Dm=matrix(D)
    DvL=[]
    for v in (Dm.columns()):
        DvL.append((sum(v)))
    #show(DvL)




    keys = range(len(DvL))
    DvDict=dict(zip(DvL, keys))
    #show(DvDict)
    DvDictSorted={k: v for k, v in sorted(DvDict.items(), key=lambda item: item[0],reverse=True)}
    #show(DvDictSorted)

    colorSortedL=[]
    for key,val in DvDictSorted.items():
        colorSortedL.append(colorL[val])
        #print (key, "=>", val)
    return colorSortedL

rot=matrix(SR,[[cos(2*pi/n),-sin(2*pi/n)],[sin(2*pi/n),cos(2*pi/n)]])
#ref=matrix(SR,[[cos(2*2*pi/n),sin(2*2*pi/n)],[sin(2*2*pi/n),-cos(2*2*pi/n)]])
ref=matrix(SR,[[cos(pi),sin(pi)],[sin(pi),-cos(pi)]])

# fill up color list only if color list does not exist
try: colorSortedL
except NameError: colorSortedL = None

if colorSortedL ==None :

    colorSortedL=chooseColor(2*n)
    #print("https://www.youtube.com/watch?v=L5GEnUuhilw&t=204s")

    #show(LatexExpr(r"\mathrm{rotation_{matrix}} = \begin{bmatrix}\cos{2\pi \over n} & -\sin{2\pi \over n} \\[8pt] \sin{2\pi \over n} & \cos{2\pi \over n}\end{bmatrix} "))
    #show(LatexExpr(r"\mathrm{reflexion_{matrix}} = \left(\begin{array}{rr} \cos 2 \theta & \sin 2 \theta  \\ \
    #                                     \sin 2 \theta  & -\cos 2 \theta \end{array}\right)"))
    #show("rotation Matrix :\t",rot)
    #show("reflexion Matrix :\t",ref)
    #show(maL)
#show(colorSortedL)



def getRotAndReflexionMatrix(rotAndRefSerie) :

    global m
    #show(rot,ref)
    global rotAndReflexionMatricesL
    global rotAndRefMemo
    mrt=m
    #show("rotAndRefMemo before:\t", rotAndRefMemo,"rotAndRefSerie :\t", rotAndRefSerie)
    rotAndRefMemot=deepcopy(deepcopy(rotAndRefMemo) + deepcopy(rotAndRefSerie))
    #show("rotAndRefMemo :\t", rotAndRefMemot,"rotAndRefSerie :\t", rotAndRefSerie)
    rotAndReflexionMatricesL=[]
    for c in rotAndRefMemot :
        if c=='r' :
            mrt=rot*mrt
            rotAndReflexionMatricesL.append(mrt)

        elif c=='t' :
            mrt=ref*mrt
            rotAndReflexionMatricesL.append(mrt)
        elif c=='c' :
            #clear
            mrt=m
            rotAndReflexionMatricesL=[m]
            rotAndRefMemot=[ ]

        else :
            #clear
            mrt=m
            rotAndReflexionMatricesL=[ ]
            rotAndRefMemot=[ ]

            print("only i or r or t please")
    #show("rotAndRefMemo :\t", rotAndRefMemo,"rotAndRefSerie :\t", rotAndRefSerie)
    rotAndRefMemo=deepcopy(rotAndRefMemot)
    return mrt



def buildMatriceFigPlots(matricesL):
    figPlotsL=[]
    figPlot=plot(0, ymin=-1.25, ymax=1.25)

    for matrice in matricesL :
        matriceL=list(matrice.transpose())
        figPlot=(list_plot(matriceL,color='black',size=40,figsize=(figsizeV,figsizeV)))
        for i in range(0,len(matriceL)) :
            #show(matriceL[i])
            figPlot+=text(str(i), matriceL[i], fontsize=50, rgbcolor=colorSortedL[i] )
            figPlot+= polygon([matriceL[i],matriceL[(i+1)%n],(0,0)],fill=True, thickness=4, rgbcolor=colorSortedL[i])

        figPlot += circle((0,0), 1)
        #figPlot += polygon(matriceL,fill=False, thickness=4, color='orange')

        figPlotsL.append(figPlot)
    #for c in range(0,t.dimensions()[1]) :
            #for r in range(0,t.dimensions()[0]) :
            #    show(r,":\t",r,":\t",t[r,c])
    return figPlotsL


try: rotAndReflexionMatrix
except NameError: rotAndReflexionMatrix = None

if rotAndReflexionMatrix ==None :
    rotAndReflexionMatrix=m

try: rotAndReflexionMatricesL
except NameError: rotAndReflexionMatricesL = None

if rotAndReflexionMatricesL ==None :
    rotAndReflexionMatricesL=[]

try: rotAndRefMemo
except NameError: rotAndRefMemo = None
#    
if rotAndRefMemo ==None :
    rotAndRefMemo=[]

try: matricesFigPlotsL
except NameError: matricesFigPlotsL = None

if matricesFigPlotsL ==None :
    matricesFigPlotsL=[]    


animateTest=False

from IPython.core.display import display, HTML
#display(HTML("<style>.container { height:100% !important; }</style>"))
display(HTML("<style>.container { width:80% !important; }</style>"))


@interact
def _(aMap=selector(['c','r', 't'],buttons=True)):
    rotAndRef=list(aMap)
    #show("rotAnd Reflexion sequence: \t",rotAndRef)

    global rotAndReflexionMatrix 
    global rotAndReflexionMatricesL
    rotAndReflexionMatrix=getRotAndReflexionMatrix(rotAndRef)
    #show("rotAndReflexionMatrix : \t",rotAndReflexionMatrix)

    #show("rotAndReflexionMatricesL : \t",rotAndReflexionMatricesL)

    # plot list of matrices
    matricesFigPlotsL=buildMatriceFigPlots(rotAndReflexionMatricesL)

    if animateTest :
        # show animated sequence
        a=animate(matricesFigPlotsL,ymin=-max,ymax=max,axes_labels=['x','y'],fontsize=14,figsize=(figsizeV,figsizeV))
        a.show(delay=200,iterations=1)
    else:
        #only show the completed sequence at the end
        if matricesFigPlotsL!=[] :
            show(matricesFigPlotsL[-1])

buttons on interact acting twice first time

Hi

Ubuntu 18.04 Jupyter notebook SageMath 9.0

Q1):

I can't find why the first time I click on r or on t buttons it produces 2 rotations or 2 reflections, then only one as it should do, every other time.(maybe there is something wrong in my code ? ) (to enlarge the output cell, menu cell -> Current output → toggle scrolling and click on left side of the output cell)

Q2):

why this code do not work on SageCell , but works in my local server ?

precision: each time I change button then back to the other button is acting twice again !

or is there a bug in interact button ? https://ask.sagemath.org/question/48338/interact-button-reacting-twice/

#%matplotlib notebook
#import matplotlib.pyplot as plt
#from matplotlib.animation import FuncAnimation
#import animatplot as amp
#
import numpy as np
from scipy.spatial import distance
from sage.plot.point import Point

#np.set_printoptions(linewidth=110)

""" choose side number of the 2D polygon """
var('n')
n=6

maL=[]
shiftAngle=-2*pi/(2*n)
for i in range(1,n+1) :
    maL.append([cos(i*2*pi/n+shiftAngle),sin(i*2*pi/n+shiftAngle)])

#mL=[[1,1],[-1,1],[-1,-1],[1,-1]]
m=matrix(maL).transpose()

max = 1.5 # figure span
figsizeV=5

def chooseColor(colorsNumber):
    if 'colorL' not in locals():
        colorL=[]
        for i in range(0,colorsNumber) :
            colorL.append([random(),random(),random()])
        #show(colorL)


    D=distance.cdist(colorL, colorL, 'cityblock')

    Dm=matrix(D)
    DvL=[]
    for v in (Dm.columns()):
        DvL.append((sum(v)))
    #show(DvL)




    keys = range(len(DvL))
    DvDict=dict(zip(DvL, keys))
    #show(DvDict)
    DvDictSorted={k: v for k, v in sorted(DvDict.items(), key=lambda item: item[0],reverse=True)}
    #show(DvDictSorted)

    colorSortedL=[]
    for key,val in DvDictSorted.items():
        colorSortedL.append(colorL[val])
        #print (key, "=>", val)
    return colorSortedL

rot=matrix(SR,[[cos(2*pi/n),-sin(2*pi/n)],[sin(2*pi/n),cos(2*pi/n)]])
#ref=matrix(SR,[[cos(2*2*pi/n),sin(2*2*pi/n)],[sin(2*2*pi/n),-cos(2*2*pi/n)]])
ref=matrix(SR,[[cos(pi),sin(pi)],[sin(pi),-cos(pi)]])

# fill up color list only if color list does not exist
try: colorSortedL
except NameError: colorSortedL = None

if colorSortedL ==None :

    colorSortedL=chooseColor(2*n)
    #print("https://www.youtube.com/watch?v=L5GEnUuhilw&t=204s")

    #show(LatexExpr(r"\mathrm{rotation_{matrix}} = \begin{bmatrix}\cos{2\pi \over n} & -\sin{2\pi \over n} \\[8pt] \sin{2\pi \over n} & \cos{2\pi \over n}\end{bmatrix} "))
    #show(LatexExpr(r"\mathrm{reflexion_{matrix}} = \left(\begin{array}{rr} \cos 2 \theta & \sin 2 \theta  \\ \
    #                                     \sin 2 \theta  & -\cos 2 \theta \end{array}\right)"))
    #show("rotation Matrix :\t",rot)
    #show("reflexion Matrix :\t",ref)
    #show(maL)
#show(colorSortedL)



def getRotAndReflexionMatrix(rotAndRefSerie) :

    global m
    #show(rot,ref)
    global rotAndReflexionMatricesL
    global rotAndRefMemo
    mrt=m
    #show("rotAndRefMemo before:\t", rotAndRefMemo,"rotAndRefSerie :\t", rotAndRefSerie)
    rotAndRefMemot=deepcopy(deepcopy(rotAndRefMemo) + deepcopy(rotAndRefSerie))
    #show("rotAndRefMemo :\t", rotAndRefMemot,"rotAndRefSerie :\t", rotAndRefSerie)
    rotAndReflexionMatricesL=[]
    for c in rotAndRefMemot :
        if c=='r' :
            mrt=rot*mrt
            rotAndReflexionMatricesL.append(mrt)

        elif c=='t' :
            mrt=ref*mrt
            rotAndReflexionMatricesL.append(mrt)
        elif c=='c' :
            #clear
            mrt=m
            rotAndReflexionMatricesL=[m]
            rotAndRefMemot=[ ]

        else :
            #clear
            mrt=m
            rotAndReflexionMatricesL=[ ]
            rotAndRefMemot=[ ]

            print("only i or r or t please")
    #show("rotAndRefMemo :\t", rotAndRefMemo,"rotAndRefSerie :\t", rotAndRefSerie)
    rotAndRefMemo=deepcopy(rotAndRefMemot)
    return mrt



def buildMatriceFigPlots(matricesL):
    figPlotsL=[]
    figPlot=plot(0, ymin=-1.25, ymax=1.25)

    for matrice in matricesL :
        matriceL=list(matrice.transpose())
        figPlot=(list_plot(matriceL,color='black',size=40,figsize=(figsizeV,figsizeV)))
        for i in range(0,len(matriceL)) :
            #show(matriceL[i])
            figPlot+=text(str(i), matriceL[i], fontsize=50, rgbcolor=colorSortedL[i] )
            figPlot+= polygon([matriceL[i],matriceL[(i+1)%n],(0,0)],fill=True, thickness=4, rgbcolor=colorSortedL[i])

        figPlot += circle((0,0), 1)
        #figPlot += polygon(matriceL,fill=False, thickness=4, color='orange')

        figPlotsL.append(figPlot)
    #for c in range(0,t.dimensions()[1]) :
            #for r in range(0,t.dimensions()[0]) :
            #    show(r,":\t",r,":\t",t[r,c])
    return figPlotsL


try: rotAndReflexionMatrix
except NameError: rotAndReflexionMatrix = None

if rotAndReflexionMatrix ==None :
    rotAndReflexionMatrix=m

try: rotAndReflexionMatricesL
except NameError: rotAndReflexionMatricesL = None

if rotAndReflexionMatricesL ==None :
    rotAndReflexionMatricesL=[]

try: rotAndRefMemo
except NameError: rotAndRefMemo = None
#    
if rotAndRefMemo ==None :
    rotAndRefMemo=[]

try: matricesFigPlotsL
except NameError: matricesFigPlotsL = None

if matricesFigPlotsL ==None :
    matricesFigPlotsL=[]    


animateTest=False

from IPython.core.display import display, HTML
#display(HTML("<style>.container { height:100% !important; }</style>"))
display(HTML("<style>.container { width:80% !important; }</style>"))


@interact
def _(aMap=selector(['c','r', 't'],buttons=True)):
    rotAndRef=list(aMap)
    #show("rotAnd Reflexion sequence: \t",rotAndRef)

    global rotAndReflexionMatrix 
    global rotAndReflexionMatricesL
    rotAndReflexionMatrix=getRotAndReflexionMatrix(rotAndRef)
    #show("rotAndReflexionMatrix : \t",rotAndReflexionMatrix)

    #show("rotAndReflexionMatricesL : \t",rotAndReflexionMatricesL)

    # plot list of matrices
    matricesFigPlotsL=buildMatriceFigPlots(rotAndReflexionMatricesL)

    if animateTest :
        # show animated sequence
        a=animate(matricesFigPlotsL,ymin=-max,ymax=max,axes_labels=['x','y'],fontsize=14,figsize=(figsizeV,figsizeV))
        a.show(delay=200,iterations=1)
    else:
        #only show the completed sequence at the end
        if matricesFigPlotsL!=[] :
            show(matricesFigPlotsL[-1])