# Identify the Loops in the Node Network

Before we can do any circuit analysis, we need to identify loops of component connectivity in our circuit. This will enable us to apply well known circuit analysis theorems such as KVL, and KVC.

An algorithm to identify loops is:

• traverse from part to part until we get back to the start part
• if we hit a dead end, then rewind and try another branch
• to begin another loop search, pick on a part that is not in any other loop and start from there

We may build a stack of parts as we traverse the parts (adding to it and winding it back). And use a recursive function to traverse the tree of paths.

Here is some code that I came up with to do this:

``````func get_loops(pgs_, net_nodes_):
var loops_ = []
# Get loops from net
for node in net_nodes_:
for pin in node:
if not_in_loop(loops_, pin):
var stack = []
var _e = try_get_loop(pin, node, stack, pgs_, loops_)
var out_pin = false
for pin_ in stack:
# Assign sinks only for the pins connecting to the next part in the loop
if out_pin:
assign_sinks_to_part(pin_, pgs_, net_nodes_)
out_pin = not out_pin
return loops_

func try_get_loop(from_pin, start_node, stack_, pgs_, loops_):
for to_node in net_nodes:
for to_pin in to_node:
# Find another pin on the same part
if to_pin != from_pin and from_pin[0] == to_pin[0]:
# If isolated, the pin must be on same side
if pgs_.parts[to_pin[0]].isolated and from_pin[2] != to_pin[2]:
continue
# If tagged as series, new pin must be adjacent
if pgs_.parts[to_pin[0]].series:
if abs(from_pin[1] - to_pin[1]) > 1.1:
continue
# Can't connect to itself
if to_pin in stack_:
continue
# Can't connect to node that already has 2 connections
var n = 0
for pin in to_node:
if pin in stack_:
n += 1
if n > 1:
continue
# The pin is OK to add to the loop
stack_.append(from_pin)
stack_.append(to_pin)
# Check for completion of the loop
if to_node == start_node:
loops_.append(stack_)
prints("Stack:", stack_)
return true
# Get next pin on same node
for pin in to_node:
# Can't have the same pin in a loop
if not pin in stack_:
if try_get_loop(pin, start_node, stack_, pgs_, loops_):
return true
return false
``````

The next task will be to do DC analysis of the circuit.

## More Devlog entries

Most recent first