code: def find_cycles(sub_network, weight='x_pu'):
      
      branches_bus0 = sub_network.branches()["bus0"]
      branches_i = branches_bus0.index
  
      #reduce to a non-multi-graph for cycles with > 2 edges
      mgraph = sub_network.graph(weight=weight, inf_weight=False)
      graph = nx.OrderedGraph(mgraph)
  
      cycles = nx.cycle_basis(graph)
  
      #number of 2-edge cycles
      num_multi = len(mgraph.edges()) - len(graph.edges())
  
      sub_network.C = dok_matrix((len(branches_bus0),len(cycles)+num_multi))
  
      for j,cycle in enumerate(cycles):
  
          for i in range(len(cycle)):
              branch = next(iterkeys(mgraph[cycle[i]][cycle[(i+1)%len(cycle)]]))
              branch_i = branches_i.get_loc(branch)
              sign = +1 if branches_bus0.iat[branch_i] == cycle[i] else -1
              sub_network.C[branch_i,j] += sign
  
      #counter for multis
      c = len(cycles)
  
      #add multi-graph 2-edge cycles for multiple branches between same pairs of buses
      for u,v in graph.edges():
          bs = list(mgraph[u][v].keys())
          if len(bs) > 1:
              first = bs[0]
              first_i = branches_i.get_loc(first)
              for b in bs[1:]:
                  b_i = branches_i.get_loc(b)
                  sign = -1 if branches_bus0.iat[b_i] == branches_bus0.iat[first_i] else +1
                  sub_network.C[first_i,c] = 1
                  sub_network.C[b_i,c] = sign
                  c+=1
docs: Find all cycles in the sub_network and record them in sub_network.C.
  
      networkx collects the cycles with more than 2 edges; then the 2-edge cycles
      from the MultiGraph must be collected separately (for cases where there
      are multiple lines between the same pairs of buses).
  
      Cycles with infinite impedance are skipped.