Exemplo n.º 1
0
def save_graph(graph, n, p):
    #initialze Figure
    plt.figure(num=None, figsize=(20, 20), dpi=80)
    plt.axis('off')
    fig = plt.figure(figsize=(50, 40))

    pos = nx.circular_layout(graph)
    nx.draw_networkx_nodes(graph, pos)
    nx.draw_networkx_edges(graph, pos)
    nx.draw_networkx_labels(graph, pos)

    file_name = 'Q8_Assets/SmallWorld_N_' + str(n) + '_P_' + str(p) + '.pdf'
    plt.savefig(file_name, bbox_inches="tight")
    plt.close(fig)
    del fig
Exemplo n.º 2
0
 def draw_graph(self, node_type='', layout=''):
     if layout == 'spring':
         pos = nx.spring_layout(self.scgraph.code_graph)
     if layout == 'spectral':
         pos = nx.spectral_layout(self.scgraph.code_graph)
     if layout == 'planar':
         pos = nx.planar_layout(self.scgraph.code_graph)
     if layout == 'shell':
         pos = nx.shell_layout(self.scgraph.code_graph)
     if layout == 'circular':
         pos = nx.circular_layout(self.scgraph.code_graph)
     if layout == 'spiral':
         pos = nx.spiral_layout(self.scgraph.code_graph)
     if layout == 'random':
         pos = nx.random_layout(self.scgraph.code_graph)
     if node_type == 'cycles':
         self.scgraph.draw('cycles', layout)
     if node_type == 'dict':
         self.scgraph.draw('dict', layout)
def AllocateSmallGroups(G, n, teamCount, m, showAnimation, peopleNumbers,
                        peopleUnvisited):
    # Setup graph animation window

    # Display all nodes in a circular layout with labels
    pos = nx.circular_layout(G)
    if showAnimation:
        pylab.show()
        nx.draw_circular(G, with_labels=True)

    # Determine the number of edges will present in the clique
    #     by taking the number of teams and multiplying it by
    #     one less of itself
    cliqueEdges = teamCount * (teamCount - 1)

    # Determine the likely number of groups that will be allocated
    #     for each night by doing integer division with n divided by m
    # Sometimes, there will be less groups due to edge cases where a
    #     group would only have had one person
    numGroups = n // m

    # Create a list to contain the lists of each group for each night
    superList = []
    # Start a counter for the number of nights
    nightNum = 0
    # Create a list of the teams that were hosts the last night
    previousHosts = []

    # While there are still teams who have not visited a different team
    #     (Alternatively, if there are still edges missing to form a clique)
    while len(sum(list(peopleUnvisited.values()), [])) > 0:
        # Make a deep copy of the peopleUnvisited map as it currently is
        people = deepcopy(peopleUnvisited)
        # Create a list to hold the groups for this night
        # Create a list within this that will hold the number of individuals
        #     assigned to each group of this night
        night = [[]]
        # Create a list of the teams that are hosts for this night
        hostNames = []

        # Create the expected number of groups
        for i in range(numGroups):
            # Retrieve the list of unassigned teams
            peopleList = list(people.keys())
            peopleNum = len(peopleList)
            # If there is only one unassigned team, do not create a new
            #     group, but let the remainingGuests list allocate
            #     this team to an existing group
            if peopleNum == 1:
                break

            # Create a map for teams that could be a host for this group
            potentialHosts = {}
            # Populate the map with unassigned teams that
            #     were not hosts last night
            for person in Difference(peopleList, previousHosts):
                potentialHosts[person] = people[person]

            # If there are potential hosts for this group
            if len(potentialHosts) > 0:
                # Select the host that has been visited least, which
                #     is the same as host with most unvisited teams
                #     (Alternatively, node of smallest degree)
                host = max(potentialHosts,
                           key=lambda k: len(potentialHosts[k]))

                # Find the unassigned teams that were hosts last night, but
                #     are not hosts for this night
                previousHostOptions = Intersection(
                    peopleList, Difference(previousHosts, hostNames))
                if len(previousHostOptions) > 0:
                    # Reset the map to store possible hosts from last night
                    potentialHosts = {}
                    for person in previousHostOptions:
                        potentialHosts[person] = peopleUnvisited[person]
                    # Find the host that has been visited least, which
                    #     was a host last night, but not tonight
                    prevHost = max(potentialHosts,
                                   key=lambda k: len(potentialHosts[k]))
                    # If the host from last night has been visited less
                    #     than the host selected at the moment, then
                    #     select the host from last night instead
                    if (len(peopleUnvisited[host]) < len(
                            peopleUnvisited[prevHost])):
                        host = prevHost
            # Otherwise, if there are no unassigned teams that
            #     that were not hosts last night
            else:
                # Find the unassigned teams that were hosts last night, but
                #     are not hosts for this night
                previousHostOptions = Intersection(
                    peopleList, Difference(previousHosts, hostNames))
                if len(previousHostOptions) > 0:
                    # Reset the map to store possible hosts from last night
                    potentialHosts = {}
                    for person in previousHostOptions:
                        potentialHosts[person] = peopleUnvisited[person]
                    # Select the host that has been visited least, which
                    #     was a host last night, but not tonight
                    host = max(potentialHosts,
                               key=lambda k: len(potentialHosts[k]))
                # Otherwise, if there is no unassigned teams that could
                #     be hosts for this night, then do not create
                #     a group and just add any unassigned people
                #     using remainingGuests
                else:
                    break

            # Create a list for a new group for this night,
            #     starting with the selected host
            group = [host]
            # Initialize the initial list of the night list
            #     by setting the current size of this group
            #     to the number of individuals the host
            night[0].append(peopleNumbers[host])
            hostNames.append(host)
            # Since the host has been assigned to a group, remove them from map
            del people[host]

            # If the host already fills up the group
            if peopleNumbers[host] >= m:
                # Find any unassigned guests who have not yet visited this host
                potentialGuests = Intersection(peopleUnvisited[host],
                                               list(people.keys()))
                if len(potentialGuests) > 0:
                    # Add a guest anyway to this group, so that
                    #     this edge case is resolved by allowing teams
                    #     to visit this host, even though group is filled
                    guestToAdd = potentialGuests[0]
                    group.append(guestToAdd)
                    if showAnimation:
                        AnimateEdge(G, pos, guestToAdd, host)
                    # Increment group size by number of individuals of guest
                    night[0][i] += peopleNumbers[guestToAdd]
                    # Denote guest as assigned by removing from map
                    del people[guestToAdd]
                    # Remove guest from univisited list of host
                    peopleUnvisited[host].remove(guestToAdd)

            # While this group is not filled and there are unassigned guests
            while night[0][i] < m and len(list(people.keys())) > 0:
                guestToAdd = None
                peopleList = list(people.keys())
                peopleNum = len(peopleList)
                # Find any unassigned guests who have not yet visited this host
                potentialGuests = Intersection(peopleUnvisited[host],
                                               peopleList)
                potentialNum = len(potentialGuests)

                # If adding any guest at any point will overflow for this host
                if peopleNumbers[host] + 2 > m:
                    # Then add a guest anyway with preference toward unvisited
                    if potentialNum > 0:
                        guestToAdd = potentialGuests[0]
                    else:
                        guestToAdd = peopleList[0]

                # If there are potential guests but still no guest selected
                if potentialNum > 0 and guestToAdd is None:
                    # If a couple can fit
                    if night[0][i] + 2 <= m:
                        # Then add a couple, if one is available
                        for guest in potentialGuests:
                            if peopleNumbers[guest] == 2:
                                guestToAdd = guest
                                break

                    # Otherwise, if still no guest selected and
                    #     if a single can fit
                    if guestToAdd is None and night[0][i] + 1 <= m:
                        for guest in potentialGuests:
                            # Then add a single, if one is available
                            if peopleNumbers[guest] == 1:
                                guestToAdd = guest
                                break

                    # Otherwise, stop attempting to add guests to this group and
                    # simply allow the remainingGuests list to fill this group
                    if guestToAdd is None:
                        break
                # Otherwise, if there are, in fact, no potential guests and
                #     still no guest selected but there are unassigned guests
                elif potentialNum == 0 and guestToAdd is None and peopleNum > 0:
                    # Then add a guest anyway
                    guestToAdd = peopleList[0]
                    potentialIndex = 1
                    # Try the next guest if the current one will not fit
                    while (potentialIndex < peopleNum
                           and peopleNumbers[guestToAdd] + night[0][i] > m):
                        guestToAdd = peopleList[potentialIndex]
                        potentialIndex += 1

                # If there is a guest selected
                if guestToAdd is not None:
                    # Add the guest to this group
                    group.append(guestToAdd)
                    if showAnimation:
                        AnimateEdge(G, pos, guestToAdd, host)
                    # Increment group size by number of individuals of guest
                    night[0][i] += peopleNumbers[guestToAdd]
                    # Denote guest as assigned by removing from map
                    del people[guestToAdd]
                    # Remove guest from univisited list of host, if the
                    #     guest is still in that list
                    if guestToAdd in peopleUnvisited[host]:
                        peopleUnvisited[host].remove(guestToAdd)

            # Add this group to the current night
            night.append(group)

        # As a catch-all, compile a list of any guests that were not assigned
        #     in the current night
        remainingGuests = list(people.keys())
        # If there were any extra unassigned guests
        if len(remainingGuests) > 0:
            # Sort them with couples at the beginning
            sortedRemainingGuests = []
            for guest in remainingGuests:
                if peopleNumbers[guest] == 2:
                    sortedRemainingGuests.insert(0, guest)
                else:
                    sortedRemainingGuests.append(guest)
            # Add each guest to the smallest group
            for guest in sortedRemainingGuests:
                # Find the group with least number of individuals
                smallestGroupIndex = night[0].index(min(night[0]))
                # Find who the host is for that group
                host = night[smallestGroupIndex + 1][0]
                # Add the guest to that group
                night[smallestGroupIndex + 1].append(guest)
                if showAnimation:
                    AnimateEdge(G, pos, guest, host)
                # Increment group size by number of individuals of extra guest
                night[0][smallestGroupIndex] += peopleNumbers[guest]
                # Remove guest from univisited list of host, if the
                #     guest is still in that list
                if guest in peopleUnvisited[host]:
                    peopleUnvisited[host].remove(guest)

        # Add this filled night list to the list of lists
        superList.append(night)

        # Set the list of current hosts as the previous hosts for the next night
        previousHosts = hostNames

        # Increment the night counter
        nightNum += 1

        # Print out the details for the night, including the
        #     size of each group and the groups themselves
        print("Night #", nightNum)
        print("Group sizes are =", night[0])
        for j, group in enumerate(night[1:], start=1):
            print("Group #", j, "=", night[j])

        # Determine how much progress has been made on forming a clique
        if showAnimation:
            edges = G.number_of_edges()
        else:
            edges = cliqueEdges - len(sum(list(peopleUnvisited.values()), []))

        # Print out progress of algorithm as a percentage, which is
        #     how many edges have been added so far divided by
        #     the total number of edges required to form a clique
        print("Clique is", int(100 * (edges / cliqueEdges)),
              "% complete (" + str(edges), "of",
              str(cliqueEdges) + " edges).\n")

    return superList
Exemplo n.º 4
0
w = 3
h = 3

G = nx.from_numpy_array(allSC[0])
# pos = nx.spring_layout(G,scale=9)
# pos = nx.circular_layout(G)
pos = nx.fruchterman_reingold_layout(G)
# pos = nx.random_layout(G)
# pos = nx.spectral_layout(G)
# pos = nx.shell_layout(G)
# pos = nx.layout(G)

bestCount = 400
best_i = 0
th_best = -1
pos = nx.circular_layout(G)
# pos = nx.kamada_kawai_layout(G)
list = []
mul = 1
# mul = 2.5
# for i in listL2:
for i in range(allSC.shape[0]):
    for th in [0.05]:  # for L2 FC
        # for th in [0.03]:  # for full corr FC

        sc = getNormalizedMatrix_np(allSC[i])
        # sc = getNormalizedMatrix_np(allSC[i])
        sc[sc < th] = 0
        tfc = getNormalizedMatrix_np(np.copy(trueFC[i]))
        # tfc = np.copy(trueFC[i])
        # tfc[tfc!=0]=1
    def draw(self, node_type='', layout=''):
        """
        Draw graph with vertices, edges, and faces labeled by colored nodes and their integer indices
        corresponding to the qubit indices for the surface code
        """
        if not node_type in ['cycles', 'dict']:
            raise ValueError('node_type can be "cycles" or "dict"')

        if layout == 'spring':
            pos = nx.spring_layout(self.code_graph)
        if layout == 'spectral':
            pos = nx.spectral_layout(self.code_graph)
        if layout == 'planar':
            pos = nx.planar_layout(self.code_graph)
        if layout == 'shell':
            pos = nx.shell_layout(self.code_graph)
        if layout == 'circular':
            pos = nx.circular_layout(self.code_graph)
        if layout == 'spiral':
            pos = nx.spiral_layout(self.code_graph)
        if layout == 'random':
            pos = nx.random_layout(self.code_graph)
        # white nodes
        nx.draw_networkx_nodes(self.code_graph,
                               pos,
                               nodelist=list(self.alpha),
                               node_color='c',
                               node_size=500,
                               alpha=0.3)
        # vertex nodes
        nx.draw_networkx_nodes(self.code_graph,
                               pos,
                               nodelist=list(self.sigma),
                               node_color='b',
                               node_size=500,
                               alpha=0.6)
        # face nodes
        nx.draw_networkx_nodes(self.code_graph,
                               pos,
                               nodelist=list(self.phi),
                               node_color='r',
                               node_size=500,
                               alpha=0.6)
        # edges
        nx.draw_networkx_edges(self.code_graph, pos, width=1.0, alpha=0.5)

        labels = {}

        if node_type == 'cycles':
            '''
            label nodes the cycles of sigma, alpha, and phi
            '''
            for node in self.alpha_dict:
                # stuff = self.alpha_dict[node]
                labels[node] = f'$e$({node})'
            for node in self.sigma_dict:
                # something = self.sigma_dict[node]
                labels[node] = f'$v$({node})'
            for node in self.phi_dict:
                # something2 = self.phi_dict[node]
                labels[node] = f'$f$({node})'
            nx.draw_networkx_labels(self.code_graph, pos, labels, font_size=12)

        if node_type == 'dict':
            '''
            label nodes with v, e, f and indices given by node_dict corresponding to
            qubit indices of surface code
            '''

            for node in self.alpha_dict:
                # stuff = self.alpha_dict[node]
                labels[node] = f'$e$({self.alpha_dict[node]})'
            for node in self.sigma_dict:
                # something = self.sigma_dict[node]
                labels[node] = f'$v$({self.sigma_dict[node]})'
            for node in self.phi_dict:
                # something2 = self.phi_dict[node]
                labels[node] = f'$f$({self.phi_dict[node]})'
            nx.draw_networkx_labels(self.code_graph, pos, labels, font_size=12)

        # plt.axis('off')
        # plt.savefig("labels_and_colors.png") # save as png
        plt.show()  # display