def parse_responses(self, received): print(received) # Only take up to semicolon received = received.split(";")[0] # Should get json back try: response = json.loads(received) except json.JSONDecodeError as e: print(e) # If it fails, return 'null' circuit return Circuit() # Start building the circuit circuit = Circuit() # Check for root_component if "root" in response: root_component = response["root"] else: root_component = "" circuit.set_root(root_component) # Get the connections if "connections" in response: for connection in response["connections"]: # Double check the format is correct if "-" in connection: circuit.add_connection( Connection( connection.split("-")[0], connection.split("-")[1])) return circuit
def publish(): rospy.init_node("node3", anonymous=False) pub = rospy.Publisher('/gazebo/set_model_state', ModelState, queue_size=10) rate = rospy.Rate(200) nodo = ModelState() nodo.model_name = "prius_hybrid_1" circuit = Circuit() circuit.run() for i in range(2 * (len(circuit.points)) / 3, len(circuit.points)): position = circuit.points[i] previous_position = circuit.points[i - 1] nodo = calculate_position_and_orientation(nodo, position, previous_position) pub.publish(nodo) rate.sleep() while not rospy.is_shutdown(): for i in range(len(circuit.points)): position = circuit.points[i] previous_position = circuit.points[i - 1] nodo = calculate_position_and_orientation(nodo, position, previous_position) pub.publish(nodo) rate.sleep()
def getCircuits(self): focus_goal = (math.floor(self.focus_ratio * self.num_of_circuits * self.num_of_exerecises)) if (self.focus != '') else 0 while (self.num_of_circuits > 0): circuit = Circuit(self.filtered_exercise_list, self.num_of_exerecises, self.focus, focus_goal, self.no_weights, self.no_stability_ball, self.no_machines) self.circuits.append(circuit) self.num_of_circuits -= 1 focus_goal -= circuit.focused_count
def __init__(self, parent, controller, show_settings, height, width): super().__init__(parent) self["style"] = "Background.TFrame" self["height"] = height self["width"] = width self.parent = parent self.func = None self.start, self.end = 0, 0 self.controller = controller self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.circuit = Circuit(self, height=height, width=.8 * width) self.circuit.grid(row=0, column=0, sticky="NSEW") self.control_panel = Control_Panel(self, height=height, width=.2 * width) self.control_panel.grid(row=0, column=1, sticky="NSEW") self.handle_entries_change()
def clique_n2_th18n(n, k, edges): clauses = [] for i in range(1, n + 1): for j in range(i + 1, n + 1): if (i, j) not in edges: clauses += [[-i, -j]] c = Circuit(input_labels=[f'x{i}' for i in range(1, n + 1)], gates={}) c.outputs = add_thn(c, c.input_labels, k, is5n=False) def makesatvar(s): if s[0] == 'x': return int(s[1:]) else: return int(s[1:]) + n + 1 for gate in c.gates.keys(): var = makesatvar(gate) pr1 = makesatvar(c.gates[gate][0]) pr2 = makesatvar(c.gates[gate][1]) op = c.gates[gate][2] clauses += [[pr1, pr2, var if op[0] == '1' else -var]] clauses += [[pr1, -pr2, var if op[1] == '1' else -var]] clauses += [[-pr1, pr2, var if op[2] == '1' else -var]] clauses += [[-pr1, -pr2, var if op[3] == '1' else -var]] clauses += [[makesatvar(c.outputs)]] save_cnf_formula_to_file('clique.cnf', clauses, n + len(c.gates)) return clauses, '18n'
def test_mpc(t, n, c_path, n_triples, all_inputs, result, reflect=False): triples = gen_triples(t, n, n_triples) mq = Queue() queues = [Queue() for _ in range(n)] processes = [] itypes = [] for i in all_inputs[0]: if i in [0, 1]: itypes.append('V') else: itypes.append('S') c = Circuit(c_path, itypes) for i in range(n): p = Process(target=run_circuit_process, args=(t, n, c, i + 1, queues, mq, all_inputs[i], triples[i])) processes.append(p) start = time.time() for p in processes: p.start() t1 = Process(target=consumer, args=(mq, n, result, t, processes, reflect)) t1.start() for p in processes: p.join() t1.join() print(f"time: {round(time.time()-start, 4)} seconds") while not mq.empty(): mq.get() mq.close() for q in queues: q.close() q.join_thread() mq.join_thread()
def test_simple_descent(verbose=False): x = Input() mean = Parameter(0) func = Circuit([x], [(x - mean) * (x - mean)]) sample_size = 100 n_epochs = 20 learning_rate = 0.1 np.random.seed(0) data = np.random.random(sample_size) if verbose: print("Data mean:", data.mean()) for epoch in range(n_epochs): ders = Mapping() values = [] for point in data: values.append(func([point])) func.back_prop([1]) param_der = func.get_param_ders() assert approx(param_der[mean]) == -2 * (point - mean.val) ders = ders + param_der func.update_params((-learning_rate / sample_size) * ders) if verbose: print("{:<2}: param={:<8.6} loss={:.6}".format( epoch, mean.val, np.mean(values))) assert abs(mean.val - data.mean()) < (1 - learning_rate / 0.5)**n_epochs + 1e-10
def test_cleartext_dist32(): x = 4060000 y = 7390000 cx = 4063500 cy = 7396000 rsq = 64000000 answer = 1 if ((x - cx)**2 + (y - cy)**2) < rsq else 0 inputs = [0 for _ in range(32)] x_bits = [int(b) for b in bin(x)[2:]] if len(x_bits) < 32: x_bits = [0 for _ in range(32 - len(x_bits))] + x_bits y_bits = [int(b) for b in bin(y)[2:]] if len(y_bits) < 32: y_bits = [0 for _ in range(32 - len(y_bits))] + y_bits cx_bits = [int(b) for b in bin(cx)[2:]] if len(cx_bits) < 32: cx_bits = [0 for _ in range(32 - len(cx_bits))] + cx_bits cy_bits = [int(b) for b in bin(cy)[2:]] if len(cy_bits) < 32: cy_bits = [0 for _ in range(32 - len(cy_bits))] + cy_bits rsq_bits = [int(b) for b in bin(rsq)[2:]] if len(rsq_bits) < 32: rsq_bits = [0 for _ in range(32 - len(rsq_bits))] + rsq_bits inputs.extend(x_bits[::-1]) inputs.extend(y_bits[::-1]) inputs.extend(cx_bits[::-1]) inputs.extend(cy_bits[::-1]) inputs.extend(rsq_bits[::-1]) c = Circuit("bristol_circuits/dist32.txt", ['V' for _ in range(192)]) out_bit = asyncio.run(c.evaluate(inputs)) assert out_bit[0] == answer, "computed wrong value"
def exp_check_verilog_modelsim(): for ckt in ["c17", "c432", "c499", "c880", "c1908"]: print("\nCircuit: " + ckt) circuit = Circuit(ckt) LoadCircuit(circuit, "v") circuit.lev() path = "../data/modelsim/golden_IO_from_verilog/golden_" + ckt + "_10_b.txt" circuit.golden_test(path)
def compile(self): circuit = Circuit() for instruction in self.instructions: self.handle_instruction(instruction, circuit) return circuit
def control_thread(conn, c_name, thread_cnt, N, idx): circuit = Circuit(c_name) circuit.read_circuit() circuit.lev() one_count_list, zero_count_list, sen_count_list = circuit.STAFAN_multithreading( thread_cnt, N, idx) conn.send((one_count_list, zero_count_list, sen_count_list)) conn.close()
def FoxPropagationTest(n=200): '''Propagation test proposed by friend. Current model generates some inertia depending on wires number.''' dt = 0.001 V0 = 100. N = 100 Tab0, Tab1 = [], [] System1 = Circuit(dt) a = System1.AddSource(V0) b = System1.AddGround() R = 200. ab0 = System1.AddResistor(a, b, R) for i in range(N): System1.TimeStep() Tab0.append(ab0.GetCurrent()) Time0 = [i * dt for i in range(N)] plt.plot(Time0, Tab0) System2 = Circuit(dt) a = System2.AddSource(V0) b = System2.AddNode() ab1 = System2.AddResistor(a, b, R / n) for i in range(n - 2): c = System2.AddNode() bc = System2.AddResistor(b, c, R / n) b = c d = System2.AddGround() bd = System2.AddResistor(b, d, R / n) for i in range(N): System2.TimeStep() Tab1.append(bd.GetCurrent()) Time1 = [i * dt for i in range(N)] plt.plot(Time1, Tab1) plt.show()
def lol2(): circuit = Circuit(input_labels=['i1', 'i2', 'i3', 'i4', 'i5']) x1, x2, x3, x4, x5 = circuit.input_labels a0, a1 = add_sum3(circuit, [x1, x2, x3]) b0, b1 = add_sum3(circuit, [a0, x4, x5]) w1, w2 = add_sum2(circuit, [a1, b1]) circuit.outputs = [b0, w1, w2] check_sum_circuit(circuit) print(circuit)
def main(): # Parse the command-line arguments. args = get_args() circuit_file = args.circuit_file[0] output_file = args.output_file if output_file: output_file = output_file[0] format_csv = args.format_csv # If the file exists, then check if it is a supported input file. if os.path.isfile(circuit_file): # If it is a supported input file, then parse it. if circuit_file.endswith(".in"): # Create a new Circuit object consisting of the gates from the input file. circuit = Circuit(circuit_file, output_file, format_csv) print("INFO:: Printing gates in circuit...") print() # Print the list of gates sorted by ID. circuit.print_gates() print() # Prompt the user for desired outputs. print("INFO:: Use spaces to select multiples (e.g., 1 4 6).") print( "INFO:: To calculate all gates, just press 'Enter' without inputting anything." ) selected_output = input("INPUT:: Select gates: ") # Validate the selected outputs to ensure they are in range. print("INFO:: Validating selected outputs...") selected_outputs = validate_selected_outputs( selected_output.split(), len(circuit.get_gates())) # Generate the truth table for the selected outputs. if output_file: print("INFO:: Outputting truth table to \"" + output_file + "\"...") else: print("INFO:: Printing truth table for selected outputs...") print( " This may take awhile for large numbers of inputs because of 2^n combinations..." ) print(" Total Combinations: " + str(pow(2, circuit.get_num_of_general_input_values()))) if output_file is None: print() circuit.print_truth_table(selected_outputs) # Otherwise, display an error. else: print("ERROR:: Invalid file: \"" + circuit_file + "\"") print(" File must be of extension .in (e.g. circuit1.in).") # Otherwise, display an error. else: print("ERROR:: Cannot find file at path \"" + circuit_file + "\"")
def test_eval_order(self): c = Circuit(2) f = AdditionGate("F") g = AdditionGate("G") h = ScalarMultGate(2, "H") c.add_gate(h, ["INPUT1"]) c.add_gate(f, ["H","INPUT0"]) c.add_gate(g, ["F", "H"], True) self.assertEqual(c.eval_order(), ['H', 'F', 'G', 'OUTPUT'])
def load_neurohdf(filename, hdf5path, memmapped=False): """ Loads the circuit from a NeuroHDF file as exported from CATMAID Parameters ---------- filename : str Path to the NeuroHDF file hdfpath : str HDF5 path to the irregular dataset containing the circuit e.g. /Microcircuit """ if memmapped: raise NotImplementedError('Memmapped HDF5 reading not yet implemented') circuit = Circuit() f = h5py.File(filename, 'r') circuitdata_group=f[hdf5path] vertices_group = circuitdata_group.get('vertices') connectivity_group = circuitdata_group.get('connectivity') metadata_group = circuitdata_group.get('metadata') def helpdict(v): helpdict = dict.fromkeys( v.attrs.keys() ) for k in helpdict: helpdict[k] = v.attrs.get(k) return helpdict for k,v in vertices_group.items(): if k == 'id': circuit.vertices = vertices_group[k].value else: circuit.vertices_properties[k] = dict.fromkeys( [const.DATA, const.METADATA] ) circuit.vertices_properties[k][const.DATA] = v.value circuit.vertices_properties[k][const.METADATA] = helpdict(v) print('Added vertices {0}'.format(k)) for k,v in connectivity_group.items(): if k == 'id': circuit.connectivity = connectivity_group[k].value else: circuit.connectivity_properties[k] = dict.fromkeys( [const.DATA, const.METADATA] ) circuit.connectivity_properties[k][const.DATA] = v.value circuit.connectivity_properties[k][const.METADATA] = helpdict(v) print('Added connectivity {0}'.format(k)) if metadata_group: for k,v in metadata_group.items(): circuit.metadata[k] = dict.fromkeys( [const.DATA, const.METADATA] ) circuit.metadata[k][const.DATA] = v.value circuit.metadata[k][const.METADATA] = helpdict(v) print('Added metadata {0}'.format(k)) circuit._remap_vertices_id2indices() f.close() return circuit
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 __init__(self, vectors): pygame.init() self.screen = pygame.display.set_mode(screen_size) self.car = Car(0., START_POINT) self.circuit = Circuit() self.circuit_img = self.circuit.img_no_cp # pour tester les collisions, le checkpoint n'est pas important self.clock = pygame.time.Clock() self.running = True self.vectors = vectors self.score = 0. self.checkpoint = 0
def __init__(self): pygame.init() pygame.display.set_caption("Car tutorial") width = 1280 height = 720 self.screen = pygame.display.set_mode((width, height)) self.clock = pygame.time.Clock() self.ticks = 60 self.exit = False self.circuit = Circuit(self.screen)
def test_cleartext_unnormalized_subregion_example(): answer = 300 inputs = [0 for _ in range(64)] + [1 for _ in range(1200)] c = Circuit("bristol_circuits/unnormalized_subregion_100_10.txt", ['V' for _ in range(1264)]) out_bits = asyncio.run(c.evaluate(inputs)) out_string = ''.join([str(i) for i in list(reversed(out_bits))]) for i in range(10): assert eval('0b' + out_string[i * 64:(i + 1) * 64]) == answer, "computed wrong value"
def test_circuit_resistance(): circuit = Circuit() battery = VoltageSource(circuit, 9) # 9 volts resistor = Resistor(circuit, 10) # 1 ohm battery.negative = resistor.positive battery.positive = resistor.negative = circuit._ground print circuit.graph.edges() mna = circuit.assemble_mna_equation() stuff = mna.simulate(10.0, 0.1) circuit.draw() plt.savefig('crkt1.png')
def run_circuit_process(t, n, c_path, index, queues, main_queue, inputs, triples): print(f"starting node {index}") shamir = Shamir(t, n) messenger = MockMessenger(t, n, index, queues) c = Circuit(c_path) outputs = c.evaluate(inputs, shamir=shamir, messenger=messenger, triples=triples) main_queue.put(outputs) print(f"closing node {index}")
def as_circuit(self): """ Transforms an n-qubit Pauli to a serial circuit on n qubits. Neglects global phases. :rtype: :class:`qecc.Circuit` """ gatelist = [] for idx, letter in enumerate(self.op): if letter != "I": gatelist.append((letter, idx)) return Circuit(*gatelist)
def main(): parser = argparse.ArgumentParser() parser.add_argument("-ckt", type=str, required=True, help="name of the ircuit, e.g. c17, no extension") parser.add_argument("-tp", type=int, required=True, help="name of the ircuit, e.g. c17, no extension") parser.add_argument("-cpu", type=int, required=True, help="name of the ircuit, e.g. c17, no extension") args = parser.parse_args() print("\n======================================================") print("Run | circuit: {} | Test Count: {} | CPUs: {}".format( args.ckt, args.tp, args.cpu)) start_time = time.time() circuit = Circuit(args.ckt) circuit.read_circuit() circuit.lev() # inputnum = len(circuit.input_num_list) # limit = [0, pow(2, inputnum)-1] # for i in range(100): # b = ('{:0%db}'%inputnum).format(randint(limit[0], limit[1])) # list_to_logicsim = [] # for j in range(inputnum): # list_to_logicsim.append(int(b[j])) # circuit.logic_sim(list_to_logicsim) # print(b) # # print_nodes(circuit) # observability() need to follow controllability() circuit.SCOAP_CC() circuit.SCOAP_CO() # circuit.STAFAN_CS(100) # circuit.STAFAN_B() circuit.STAFAN(args.tp, num_proc=args.cpu) # circuit.co_ob_info() graph = circuit.gen_graph() suffix = round(math.log10(args.tp)) fname = ("10e" + str(suffix)) if (suffix % 1 == 0) else str(args.tp) fname = "./../data/graph/" + args.ckt + "_" + fname + ".graphml" print("Saving graph in ", fname) nx.write_graphml(graph, fname) print("Saved!") print("Total simulation ime: {:.2f} seconds".format(time.time() - start_time)) print()
def exp_check_c432_behavioral( mode="ckt", tp=100, ): if mode not in ["ckt", "v"]: raise NameError("mode {} is not accepted".format(mode)) print( "Checking c432 behavioral golden with c432 in {} format".format(mode)) circuit = Circuit("c432") LoadCircuit(circuit, mode) circuit.lev() check_c432_logicsim(circuit, tp, mode)
def main(): parser = argparse.ArgumentParser() parser.add_argument("-ckt", type=str, required=True, help="circuit name, c17, no extension") parser.add_argument("-tp", type=int, required=False, help="number of tp for random sim") parser.add_argument("-cpu", type=int, required=False, help="number of parallel CPUs") args = parser.parse_args() print("\n======================================================") print("Run | circuit: {} | Test Count: {} | CPUs: {}".format( args.ckt, args.tp, args.cpu)) print("======================================================\n") #Ting-Yu # for c in ['c17','c432','c499','c880','c1355','c1908','c2670','c3540','c5315','c6288','c7552']: # checker = Checker(c, args.tp) # if checker.check_PI_PO() == False: # print('#################################') # continue # checker.modelsim_wrapper() # checker.check_ckt_verilog('verilog') # checker.check_ckt_verilog('ckt') # print('#################################') # #exit() circuit = Circuit(args.ckt) #circuit.read_verilog() circuit.read_ckt() circuit.lev() """ Testing PFS """ print("PFS starts") pfs = PFS(circuit) #pfs.add_fault("full",None) #print(pfs.single([1,1,1,1,0])) pfs.fs_exe(tp_num=args.tp, t_mode='rand', r_mode='b', fault_list_type="full", fname=None) # circuit.FD_new_generator() exit()
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_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')