Skip to content

Commit

Permalink
Avoid using element equality for finding elements in circuit
Browse files Browse the repository at this point in the history
Note the following change:

Before:
```julia
julia> R = resistor(1000); circ = Circuit();

julia> add!(circ, R)
Symbol("##296")

julia> add!(circ, R)
Symbol("##296")

julia> ACME.nb(circ)
1
```
After:
```julia
julia> R = resistor(1000); circ = Circuit();

julia> add!(circ, R)
Symbol("##296")

julia> add!(circ, R)
Symbol("##297")

julia> ACME.nb(circ)
2
```
I.e. the same element can now be added twice. In general, element
instances should not have an identity, so the new behaviour seems more
reasonable. (The same `R` could already be added to another circuit
without having any effect on its presence in the first one, for
example.)
  • Loading branch information
martinholters committed Jan 16, 2023
1 parent 5264b87 commit 5dfdbc8
Showing 1 changed file with 6 additions and 12 deletions.
18 changes: 6 additions & 12 deletions src/circuit.jl
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright 2015, 2016, 2017, 2018, 2019, 2020, 2021 Martin Holters
# Copyright 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2023 Martin Holters
# See accompanying license file.

export Circuit, add!, connect!, disconnect!, @circuit, composite_element
Expand Down Expand Up @@ -53,9 +53,8 @@ function incidence(c::Circuit)
j = sizehint!(Int[], 2nb(c))
v = sizehint!(Int[], 2nb(c))
for (row, pins) in enumerate(c.nets), (elemname, pinname) in pins
elem = c.elements[elemname]
offset = branch_offset(c, elem)
bps = elem.pins[pinname]
offset = branch_offset(c, elemname)
bps = c.elements[elemname].pins[pinname]
for (branch, polarity) in bps
push!(i, row)
push!(j, offset + branch)
Expand Down Expand Up @@ -93,11 +92,6 @@ Adds the element `elem` to the circuit `c`, creating and returning a new, unique
reference designator, leaving its pins unconnected.
"""
function add!(c::Circuit, elem::Element)
for (k, v) in c.elements
if v == elem
return k
end
end
designator = gensym()
add!(c, designator, elem)
return designator
Expand Down Expand Up @@ -135,10 +129,10 @@ function Base.delete!(c::Circuit, designator::Symbol)
delete!(c.elements, designator)
end

function branch_offset(c::Circuit, elem::Element)
function branch_offset(c::Circuit, designator::Symbol)
offset = 0
for el in elements(c)
el == elem && return offset
for (des, el) in c.elements
des === designator && return offset
offset += nb(el)
end
throw(ArgumentError("Element not found in circuit"))
Expand Down

0 comments on commit 5dfdbc8

Please sign in to comment.