[Python] Getting values of contour within polygon path

Discussão em 'Python' iniciado por Stack, Março 3, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following issue. I have a function of two variables defined on a regular grid via np.meshgrid and I would like to get the coordinates of the points on some contour, within a bounding region given by a polygon.

    The relevant code for this is the following:

    import numpy as np
    import numpy.linalg as linalg
    import matplotlib.pyplot as plt
    from matplotlib.patches import RegularPolygon


    def H_tau_1(kx,ky):
    return -t*(1 + np.exp( 2j*(1/2)*kx) )
    def H_tau_2(kx,ky):
    return -t*(1 + np.exp(2j*((1/4)*kx + (np.sqrt(3)/4)*ky) ) )
    def H_tau_3(kx,ky):
    return -t*(1 + np.exp(2j*( (-1/4)*kx + (np.sqrt(3)/4)*ky) ) )
    def mu_grid(mu,kx,ky):
    return mu*np.ones((kx.shape[0],ky.shape[0]))
    def xi(mu,kx,ky):
    H_mat = np.array([
    [-mu_grid(mu,kx,ky), -t*(1 + np.exp(2j*( (-1/4)*kx + (np.sqrt(3)/4)*ky) ) ), -t*(1 + np.exp(-2j*(1/2)*kx) )],
    [-t*(1 + np.exp(-2j*( (-1/4)*kx + (np.sqrt(3)/4)*ky) ) ), -mu_grid(mu,kx,ky), -t*(1 + np.exp(-2j*((1/4)*kx + (np.sqrt(3)/4)*ky) ) )],
    [-t*(1 + np.exp(2j*(1/2)*kx) ),-t*(1 + np.exp(2j*((1/4)*kx + (np.sqrt(3)/4)*ky) ) ),-mu_grid(mu,kx,ky)]

    ])

    t=1
    klin = np.linspace(-1,1,2*Nk+1)[1:]*2*(np.pi)
    kx,ky= np.meshgrid(klin,klin)
    xii = xi(mu,kx,ky)
    Nk = 100

    figc,axc=plt.subplots()

    cs=axc.contour(kx,ky,xii[:,:,1],[0.2],colors='blue')
    radius=linalg.norm([0,2*np.pi/np.sqrt(3)])/(np.sqrt(3)/2)
    hexagon = RegularPolygon(([0,0]), numVertices=6, radius=radius, edgecolor='k',fill=False)
    axc.add_patch(hexagon)
    cs.set_clip_path(hexagon)
    plt.show()


    I understand that cs.set_clip_path(hexagon) is only used for plotting purposes. Is there a way to get the coordinates given by cs.allsegs for the contours inside the hexagon? Output without cs.set_clip_path(hexagon).. That is, the coordinates of the contour given by the following plot (https://i.sstatic.net/cnKrh8gY.png)

    Thanks a lot!

    Continue reading...

Compartilhe esta Página