Created
December 18, 2020 05:53
-
-
Save WitherOrNot/e9b80532313299178d34b848e3cdeeb5 to your computer and use it in GitHub Desktop.
Implement VIRP table for any configuration of resistors in a circuit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from gmpy2 import mpfr | |
from rich.console import Console | |
from rich.table import Table | |
class Resistor: | |
def __init__(self, resistance): | |
self.resistance = mpfr(resistance) | |
class Circuit: | |
def __init__(self, *wires): | |
self.wires = list(wires) | |
@property | |
def resistance(self): | |
return 1/sum([1/sum([x.resistance for x in wire]) for wire in self.wires]) | |
def virp(self, voltage): | |
table = [] | |
total_voltage = voltage | |
for wire in self.wires: | |
voltage = total_voltage | |
resistors = [part for part in wire if type(part) == Resistor] | |
circuits = [part for part in wire if type(part) == Circuit] | |
wire_res = sum([part.resistance for part in wire]) | |
current = voltage/wire_res | |
for res in resistors: | |
v_res = total_voltage*res.resistance/wire_res | |
power = v_res*current | |
table.append([v_res, current, res.resistance, power]) | |
voltage -= v_res | |
pre_circ_voltage = voltage | |
for i, circuit in enumerate(circuits): | |
voltage -= sum([sub_circuit.resistance*current for j, sub_circuit in enumerate(circuits) if i != j]) | |
v_circ = circuit.resistance*current | |
sub_table = circuit.virp(voltage) | |
table.extend(sub_table) | |
voltage = pre_circ_voltage | |
return table | |
def print_virp(c, voltage): | |
voltage = mpfr(voltage) | |
resistance = c.resistance | |
print("Total resistance:", "{0:.3f}".format(resistance)) | |
virp = c.virp(voltage) | |
table = Table("Resistor", "Voltage", "Current", "Resistance", "Power") | |
for n, row in enumerate(virp): | |
v, i, r, p = tuple(row) | |
table.add_row(str(n+1), "{0:.3f}".format(v), "{0:.3f}".format(i), "{0:.3f}".format(r), "{0:.3f}".format(p)) | |
table.add_row("Total", "{0:.3f}".format(voltage), "{0:.3f}".format(voltage/resistance), "{0:.3f}".format(resistance), "{0:.3f}".format(voltage*voltage/resistance)) | |
console = Console() | |
console.print(table) | |
#### MODIFY BELOW THIS LINE #### | |
voltage = 9 | |
c = Circuit( | |
[ | |
Resistor(4), | |
Circuit( | |
[ | |
Resistor(10) | |
], | |
[ | |
Resistor(6) | |
] | |
) | |
] | |
) | |
#### MODIFY ABOVE THIS LINE #### | |
print_virp(c, voltage) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment