def __init__(self, rs, Container=SortedList): """Given rs, a list of the ohm values of the available resistances, create a Toolkit""" resistances = sorted(rs) self.resistors = defaultdict(Container) for r in resistances: self.resistors[0].add(Resistor(r)) self.resistors[1].add(Resistor(r)) self.max_size = 1
def main(): data = "" if sys.version_info[0] < 3: data = raw_input("Enter color codes: ").upper() else: data = input("Enter color codes: ").upper() resistor = Resistor(data.split(" ")) resistor.output()
def run_test_circuit_3(name): R1 = Resistor('R1', [1, 0], 2) # 2 Ohm R2 = Resistor('R2', [1, 2], 1) # 1 Ohm R3 = Resistor('R3', [2, 0], 5) # 1 Ohm V4 = VoltageSource('V4', [1, 0], 4) # 1 Volt test_circuit = Circuit() test_circuit.add_components([R1, R2, R3, V4]) test_circuit.solve_DC('HM10') # DC test_circuit.print_matrix() test_circuit.print_results()
def run_test_circuit_4(name): G2 = Conductor('G2', [1, 0], 0.25) # 0.5 1/Ohm R1 = Resistor('R1', [1, 2], 1) # 2 Ohm R3 = Resistor('R3', [2, 0], 5) # 4 Ohm I4 = CurrentSource('I4', [0, 1], 2) # 0.5 Ampere test_circuit = Circuit() test_circuit.add_components([R1, G2, R3, I4]) test_circuit.solve_DC() # DC test_circuit.print_matrix() test_circuit.print_results()
def run_test_circuit_sweep(name): G2 = Conductor('G2', [0, 1], 0.25) # 0.5 1/Ohm # R2 = Resistor('R2', [0, 1], 0.25) # 0.5 1/Ohm R1 = Resistor('R1', [1, 2], 1) # 2 Ohm R3 = Resistor('R3', [2, 0], 5) # 4 Ohm I4 = CurrentSource('I4', [0, 1], 2) # 0.5 Ampere test_circuit = Circuit() test_circuit.add_components([R1, G2, R3, I4]) res = test_circuit.solve_DC_sweep(I4, 2, 8, 1) # DC print(res['result']) test_circuit.draw_VA_plot('VA', I4, res)
def test_resistor_init(self): # Setup res = Resistor(470, 5) # Exercise # Verify self.assertEqual(470, res.value) self.assertEqual(5, res.tolerance)
def add_comp(self, comp, x, y): """ Adds a component to the sprite group of a given type and position""" xpos, ypos = self.grid_snap(x, y) new_component = None if comp == 'r': value = input('Please enter a resistor value (-1 to cancel): ') value = int(value) if not value == -1: new_component = Resistor(value, xpos, ypos) else: print('canceling') elif comp == 'v': value = 5 new_component = Voltage(value, xpos, ypos) self.vcc = new_component elif comp == 'g': value = 0 new_component = Ground(xpos, ypos) else: print('Not an existing component') #just for debugging if not new_component is None: self.components.add(new_component) self.graph.update({(xpos, ypos): (comp, value)}) #component info for analysis self.connections[new_component] = list() print(self.graph)
def closest(self, ohms, k=1, tolerance=0.1, n=1): """Return the k resistors we can build with less than n resistors, with an equivalent resistance closest to ohms. Exclude any results that are outside the tolerance (e.g. 0.1 ==> +/-10%)""" candidates = [] # Iterate over all known buckets using <= k resistors cap = max(self.max_size, k) + 1 for i in range(1, cap): # Find the closest resistors above and below. rs = self.resistors[i] r = Resistor(ohms) under = rs.find_le(r) over = rs.find_ge(r) if over == under: over = None # avoid duplicates if under and withinTolerance(ohms, tolerance, under): candidates.append(under) if over and withinTolerance(ohms, tolerance, over): candidates.append(over) candidates.sort(key=lambda r: abs(ohms - r.ohms)) return candidates[:k]
def add_comp(self, comp, x, y): """ Adds a component to the sprite group of a given type and position""" xpos, ypos = self.grid_snap(x, y) if comp == 'r': self.components.add(Resistor(100, xpos, ypos)) #if type 'r', make a resistor else: print('Not an existing component')
def run_test_circuit_2(name): R1 = Resistor('R1', [0, 1], 5) # 5 Ohm V2 = VoltageSource('V2', [0, 1], 1) # 1 Volt test_circuit = Circuit() test_circuit.add_components([R1, V2]) test_circuit.solve_DC() # DC test_circuit.print_matrix() test_circuit.print_results()
def run_test_circuit_6(name): I1 = CurrentSource('I1', [0, 1], 2, (2, 0.002)) # 2 Ampere R2 = Resistor('R2', [1, 0], 3) # 1 Ohm L3 = Inductor('L3', [1, 0], 0.001, 0) # 0.01 H # I_start = 0.1 test_circuit = Circuit(gpu=True) test_circuit.add_components([I1, R2, L3]) res = test_circuit.solve_AC(0, 0.1, 0.001) # test_circuit.print_results() test_circuit.draw_plot(name, I1, res, 'I') test_circuit.draw_plot(name, R2, res, 'V') test_circuit.draw_plot(name, L3, res, 'V')
def __init__(self): self.components = pg.sprite.Group() # Adds the sideboard components to click on self.r = Resistor(100, 200, 150) self.components.add(self.r) # TO DO: Make so that it picks which image to load based on which # component was clicked self.comp_type = None #component that is clicked self.view = None self.controller = None
def run_test_circuit_7(name): I1 = CurrentSource('I1', [2, 0], 2, (2, 0.2, 0.1)) # 2 Ampere R2 = Resistor('R2', [1, 0], 1) # 1 Ohm L3 = Inductor('L3', [2, 0], 0.01, ) # 0.01 H # I_start = 0. C4 = Capacitor('C4', [1, 2], 0.00001) # 0.00001 F #U_start = 0. test_circuit = Circuit() test_circuit.add_components([I1, R2, L3, C4]) res = test_circuit.solve_AC(0, 0.001, 0.000002) test_circuit.print_results() test_circuit.draw_plot(name, I1, res, 'I') test_circuit.draw_plot(name, R2, res, 'V') test_circuit.draw_plot(name, L3, res, 'V') test_circuit.draw_plot(name, C4, res, 'I')
def run_test_circuit_5(name): I2 = CurrentSource('I1', [0, 1], 2, (2, 0.23, 0.1)) # 2 Ampere R1 = Resistor('R2', [1, 0], 10) # 1 Ohm C3 = Capacitor('C3', [1, 0], 1e-6, 0) # 1e-6 F # U_start = 0 argument test_circuit = Circuit() test_circuit.add_components([R1, I2, C3]) # test_circuit.solve_DC() # DC res = test_circuit.solve_AC(0, 1e-4, 0.5e-7) # AC # print(res['result']) test_circuit.print_results() test_circuit.print_matrix() test_circuit.draw_plot(name, I2, res, 'I') test_circuit.draw_plot(name, R1, res, 'V') test_circuit.draw_plot(name, C3, res, 'I')
def run_test_circuit_4(name): R1 = Resistor('R1', [1, 2], 1) # 1 Ohm R2 = Resistor('R2', [2, 0], 1) # 1 Ohm I3 = CurrentSource('I3', [1, 0], 1) # 1 Ampere R4 = Resistor('R4', [3, 2], 1) # 1 Ohm R5 = Resistor('R5', [4, 1], 1) # 1 Ohm R6 = Resistor('R6', [4, 0], 1) # 1 Ohm R7 = Resistor('R7', [3, 1], 1) # 1 Ohm test_circuit = Circuit(gpu=True) test_circuit.add_components([R1, R2, I3, R4, R5, R6, R7]) test_circuit.solve_DC() # DC test_circuit.print_results()
def biggestGap(self, k): """Return the resistance of the resistor that is least-buildable using k resistors of this toolkit. More concretely, compute ratio = r[i] / r[i-1] for all i, and return the value halfway between r[i], r[i-1] for the largest such ratio""" if k not in self.resistors: raise ValueError rs = self.resistors[k] ratios = [rs[i].ohms / rs[i - 1].ohms for i in range(1, len(rs))] topRatio, topIndex = -1, -1 for i, ratio in enumerate(ratios): if ratio > topRatio: topRatio, topIndex = ratio, i above, below = rs[topIndex + 1], rs[topIndex] mid = Resistor((above.ohms + below.ohms) / 2) return (below, mid, above)
def main(): output = "" arguments = get_arguments() resistor = Resistor(arguments['colors']).full_form() # Value of the resistor. if arguments['options']['c']: # Cientific notation output += colored(resistor[0][3], 'cyan', attrs=['bold']) elif arguments['options']['u'] == 'h': # In ohms output += colored(resistor[0][0], 'cyan', attrs=['bold']) elif arguments['options']['u'] == 'k': # In kiloohms output += colored(resistor[0][1], 'cyan', attrs=['bold']) elif arguments['options']['u'] == 'm': # In megaohms output += colored(resistor[0][2], 'cyan', attrs=['bold']) # Tolerance of the resistor. output += " " if arguments['options']['p']: output += colored(resistor[1][1], 'blue') else: output += colored(resistor[1][0], 'blue') # TCR if given. output += " " output += colored(resistor[2], 'magenta', attrs=['dark']) if resistor[2] != None else "" if arguments['options']['s']: for u in units: output = output.replace(u, colored(u, 'white')) output = output.replace('%', colored('%', 'white')) else: for u in units: output = output.replace( u, colored(units_sym[units.index(u)], 'white')) output = output.replace('%', colored('%', 'white')) output = output.replace('+-', '±') print(output)
def __init__(self): self.components = pg.sprite.Group() # Adds the sideboard components to click on self.r = Resistor(100, 80, 165) self.components.add(self.r) self.v = Voltage(5, 80, 260, 0, 60, 60) #200 450 self.components.add(self.v) self.g = Ground(80, 360, 0, 140, 140) #200 550 self.components.add(self.g) #stores components and their connections self.graph = dict() self.connections = dict() self.wires = list() self.vcc = None self.first_click = True self.comp_type = None #component that is clicked self.view = None self.controller = None self.analysis = None
## CH09 P9.30 from resistor import Resistor r1 = Resistor(6.2, 5) print(r1.getNominal()) print(r1.getTolerance()) print(r1.getActualResistance()) print(r1.colorDecode('Red', 'Violet', 'Green', 'Gold'))
# # # ########## # # # # # # #### ###### ###### # # I4 # # # # # # #### # R2 # # R3 # # # # # # # # # ###### ###### # # # # # # # # # ########## 0 ############################# # from resistor import Resistor from conductivity import Conductor from current_source import CurrentSource from circuit import Circuit if __name__ == '__main__': R1 = Resistor('R1', [1, 0], 2) # 2 Ohm R2 = Resistor('R2', [1, 2], 1) # 1 Ohm R3 = Resistor('R3', [2, 0], 1) # 1 Ohm I4 = CurrentSource('I4', [1, 0], 1) # 1 Ampere test_circuit = Circuit() test_circuit.add_components([R1, R2, R3, I4]) test_circuit.solve_DC('HM10') test_circuit.print_matrix() test_circuit.print_results('HM10') # test_circuit.print()
## Ch09 P9.31 from resistor import Resistor from voltagedivider import VoltageDivider for i in range(10): r1 = Resistor(250, 5) r2 = Resistor(750, 5) v1 = VoltageDivider(r1, r2) print(v1.getNominalGain()) print(v1.getActualGain())
## CH09 P9.29 from resistor import Resistor r1 = Resistor(6.2, 5) print(r1.getNominal()) print(r1.getTolerance()) print(r1.getActualResistance())
def test_add_resistors(self): res_1 = Resistor(1000) res_2 = Resistor(330) res = res_1 + res_2 self.assertEqual(1000+330, res.value)
def test_default_value(self): # Setup res = Resistor(1000) self.assertEqual(1000, res.value) self.assertEqual(2, res.tolerance)
def main(): # Parse Input if len(sys.argv) == 1: print(("Usage: python3.7 resistancematcher <target>" " <tolerance %> <num resistors> <input file>")) return elif len(sys.argv) < 5: print("Expected 4 arguments, got " + str(len(sys.argv) - 1) + ".") return # Check Input try: target = float(sys.argv[1]) assert target > 0 except (ValueError, AssertionError) as e: print("Error: Invalid target value '" + sys.argv[1] + "'.") return try: tolerance = float(sys.argv[2]) assert tolerance >= 0 and tolerance < 100 except (ValueError, AssertionError) as e: print("Error: Invalid tolerance value '" + sys.argv[2] + "'.") return try: num_resistors = int(sys.argv[3]) assert num_resistors > 0 and num_resistors <= 10 except (ValueError, AssertionError) as e: print("Error: Invalid number of resistors '" + sys.argv[3] + "'.") return try: input_file = sys.argv[4] resistors_file = open(input_file, "r") except FileNotFoundError: print("Error: Input file '" + input_file + "' not found.") return # Read input_file resistors = [] line = resistors_file.readline() line_no = 1 while line: try: resistor = float(line) assert resistor > 0 resistors.append(resistor) line = resistors_file.readline() line_no += 1 except (ValueError, AssertionError) as e: print("Error: Invalid value '" + line.strip() + "' on line " + str(line_no) + ".") return if len(resistors) == 0: print("Empty input file.") # Display arguments print("Max resistors in parallel: " + str(num_resistors)) print("Tolerance: " + str(tolerance) + " %") # Run program resistors = sorted(resistors) sol = Resistor.calc_resistors(target, tolerance, num_resistors, resistors) if len(sol.resistorList) > 0: print("Target resistance of " + str(target) + " ohms is possible with " + str(sol.resistorList) + " ohm resistors.") print("Best fit: {:0.5} ohms".format(sol.resistance)) print("Percent error: {:0.3} %".format(sol.error)) else: print("Target resistance of " + str(target) + " ohms is not possible.")
#from pyb import I2C #ANSCHLUS LINKS (Seite des micro usbs), LCD Rechts import pyb import lcd160cr from resistor import Resistor res = Resistor() res.set_resistor(3000.0)