def TestAddNewVariables(self): """Test we can add new variables along with defining mathematics. """ doc = self.LoadModel('heart/src/odes/cellml/LuoRudy1991.cellml') p = protocol.Protocol(doc.model, multi_stage=True) # Add a new 'I_total' variable and computation I_total = self.NewVariable(u'membrane,I_total', u'microA_per_cm2') p.inputs.add(I_total) currents = map(lambda i: u'membrane,i_' + i, ['Na', 'si', 'b']) currents.append(u'membrane,I_stim') currents.append(u'membrane,potassium_currents') rhs = self.NewApply(u'plus', currents) defn = self.NewAssign(u'membrane,I_total', rhs) p.inputs.add(defn) # Add a variable to the protocol component one = self.NewVariable(u'one', u'dimensionless', initial_value=u'1') p.inputs.add(one) self.assertRaises(KeyError, doc.model.get_component_by_name, u'protocol') # Apply protocol to model p.modify_model() # Check the changes self.assertEqual( I_total, doc.model.get_variable_by_name(u'membrane', u'I_total')) self.assertEqual(I_total.component, doc.model.get_component_by_name(u'membrane')) self.assertEqual(I_total.component, I_total.xml_parent) self.assertEqual(I_total.get_type(), pycml.VarTypes.Computed) self.assertEqual(I_total.get_dependencies()[0], defn) self.assertEqual(I_total.component, defn.component) self.assertEqual(str(defn), 'I_totali_Nai_sii_bI_stimpotassium_currents') self.assertEqual(one, doc.model.get_variable_by_name(u'protocol', u'one')) self.assertEqual(one.component, doc.model.get_component_by_name(u'protocol')) self.assertEqual(one.component.name, u'protocol') self.assertEqual(one.model, doc.model) self.assertEqual(one.get_type(), pycml.VarTypes.Constant) # Now apply a new protocol, to create a protocol_ component # Also checks connection creation p2 = protocol.Protocol(doc.model, multi_stage=True) two = self.NewVariable(u'two', u'millisecond') two_defn = self.NewAssign(u'two', u'membrane,time') p2.inputs.update([two, two_defn]) self.assertRaises(KeyError, doc.model.get_component_by_name, u'protocol_') p2.modify_model() self.assertEqual(two, doc.model.get_variable_by_name(u'protocol_', u'two')) self.assertEqual(two.component, doc.model.get_component_by_name(u'protocol_')) self.assertEqual(two.component.name, u'protocol_') self.assertEqual(two.model, doc.model) self.assertNotEqual(one.component, two.component)
def TestChangeInitialValue(self): doc = self.LoadModel('heart/src/odes/cellml/LuoRudy1991.cellml') p = protocol.Protocol(doc.model, multi_stage=True) # Change initial value for V v_init = u'-80' new_V = self.NewVariable(u'membrane,V', u'millivolt', initial_value=v_init, interfaces={u'public': u'out'}) p.inputs.add(new_V) # Check we are actually changing things V = doc.model.get_variable_by_name('membrane', 'V') self.failIfEqual(V.initial_value, v_init) time = doc.model.get_variable_by_name(u'environment', u'time') dv_dt = V.get_ode_dependency(time) # Apply protocol to model p.modify_model() # Check the changes V = doc.model.get_variable_by_name('membrane', 'V') self.assert_(V is new_V) self.assertEqual(V.initial_value, v_init) self.assertEqual(V.get_type(), pycml.VarTypes.State) self.assertEqual(V.get_dependencies(), []) self.assert_(V.get_ode_dependency(time) is dv_dt) # An error case: changing interfaces is not allowed new_V = self.NewVariable(u'membrane,V', u'millivolt', initial_value=v_init, interfaces={u'public': u'none'}) p.inputs = [new_V] self.assertRaises(AssertionError, p.modify_model) new_V = self.NewVariable(u'membrane,V', u'millivolt', initial_value=v_init) p.inputs = [new_V] self.assertRaises(AssertionError, p.modify_model)
def piskvork_game(): """ play gomoku game using trained model and piskvork interface """ board = np.zeros((3, 19, 19), np.int8) running = [1] protocol = protocol.Protocol(board, running) thread = Thread(protocol) thread.start() while running[0]: args = protocol.pullCmd() cmd = args[0].lower() del args[0] if cmd == "none": pass elif cmd == "start": print("OK") elif cmd == "turn": try: pos = args[0].split(',') board[0][int(pos[1])][int(pos[0])] = '2' except: print("ERROR") print("DEBUG", "Calculating the next move") # ADD OWN TURN CALCULATION # print(x + "," + y) elif cmd == "begin": print("DEBUG", "Calculating the next move") # ADD OWN TURN CALCULATION # print(x + "," + y) pass else: print("ERROR") thread.join()
def test3_download_file(sgw_addr, sgw_port, filename): # 使用偏移下载接口 p = protocol.Protocol(sgw_addr, sgw_port) p.launch() rc = p.getfile3(filename) p.finish() return rc
def test1_stage1(sgw_addr, sgw_port, filename): """上传文件""" p = protocol.Protocol(sgw_addr, sgw_port) p.launch() rc = p.putfile1(filename) p.finish() return rc
def recv_func(self, client): print(f"[{client.addr}]\trecv thread started for client!") while True: try: # this pings the client for each iteration of and checks if it is still connected # the sleep to make sure that it will be sent and not interfere with other stuff client.conn.send(b"!ping") sleep(0.5) data = client.conn.recv(512) except: # if client is disconnected then close connection and remove client from the list self.user_disconnect(client) break if data != b"": p = protocol.Protocol() p.parse(data) p.respond_clients(self.clients, client.nick) else: continue
def main(mds_addr, mds_port, study_state): p = protocol.Protocol(mds_addr=mds_addr, mds_port=mds_port) p.launch() x = p.query1(study_state) p.finish() print("receive payload:") print("{}".format(x))
def addSocket(self, sock): self.__sock_list.append(sock) prot = protocol.Protocol(sock) for i in self.__handlers: prot.registerMethodHandler(i, self.__handlers[i]) self.__protocol_list.append(prot)
def receive_cb(self, data): self._recvbuff += data proto = protocol.Protocol() if proto.unpackage(self._recvbuff) == False: return self._recvbuff = self._recvbuff[proto.size():len(self._recvbuff)] self.handleMessage(proto)
def test6_stage3(sgw_addr, sgw_port, studyid): """获取 studyid 文件列表""" # print("test6_stage3") p = protocol.Protocol(sgw_addr, sgw_port) p.launch() filestat = p.getfilelist1(studyid) p.finish() return filestat["filelist"]
def sendData(self, type, data): message = protocol.Protocol() buffer = message.package(type, data) self._stream.write(buffer) logging.debug("Send message %d size %d: %s", type, len(buffer), data) self._stream.read_bytes(1024, self.on_receive, streaming_callback=self.on_receive_stream, partial=True)
def TestChangeMathsToState(self): """Test changing the mathematical definition of a variable to type State. Covers the cases of variables originally of type State, Computed, and Constant. """ doc = self.LoadModel('heart/src/odes/cellml/LuoRudy1991.cellml') p = protocol.Protocol(doc.model, multi_stage=True) # state->state: membrane,V V = doc.model.get_variable_by_cmeta_id('membrane_voltage') self.failUnlessEqual(V.get_type(), pycml.VarTypes.State) time = doc.model.get_variable_by_name(u'membrane', u'time') V_old = V.get_ode_dependency(time) currents = map(lambda i: u'membrane,i_' + i, ['Na', 'si', 'K', 'b']) currents = self.NewApply(u'plus', currents) rhs = self.NewApply(u'divide', [currents, u'membrane,C']) V_new = self.NewOde(u'membrane,V', u'environment,time', rhs) V_new_str = str(V_new) p.inputs.add(V_new) # constant->state: membrane,T T = doc.model.get_variable_by_name(u'membrane', u'T') self.assertEqual(T.get_type(), pycml.VarTypes.Constant) self.assertEqual(T.get_dependencies(), []) T_new = self.NewOde(u'membrane,T', u'membrane,time', (u'1', u'K_per_ms')) p.inputs.add(T_new) p.inputs.add( self.NewUnits(u'K_per_ms', [{ 'units': 'kelvin' }, { 'units': 'millisecond', 'exponent': '-1' }])) # computed->state: membrane,FonRT FonRT = doc.model.get_variable_by_name(u'membrane', u'FonRT') self.assertEqual(FonRT.get_type(), pycml.VarTypes.Computed) FonRT_old = FonRT.get_dependencies()[0] FonRT_new = self.NewOde(u'membrane,FonRT', u'membrane,time', (u'0', u'per_millivolt_millisecond')) # TODO: FonRT now has no initial condition; this is a validation warning so OK... p.inputs.add(FonRT_new) # Apply protocol to model p.modify_model() # Check the changes self.assertEqual(V, doc.model.get_variable_by_name(u'membrane', u'V')) self.assertEqual(V_old.xml_parent, None) self.assertNotEqual(V_old, V.get_ode_dependency(time)) self.assertEqual(V_new, V.get_ode_dependency(time)) self.assertEqual(V.get_type(), pycml.VarTypes.State) self.assertNotEqual(str(V_new), V_new_str) # Variable refs get renamed self.assertEqual(str(V_new), 'timeVi_Nai_sii_Ki_bC') self.assertEqual(T.get_type(), pycml.VarTypes.State) self.assertEqual(T_new, T.get_ode_dependency(time)) self.assertEqual(FonRT.id, u'FonRT') self.assertEqual(FonRT.get_type(), pycml.VarTypes.State) self.assertEqual(FonRT_new, FonRT.get_ode_dependency(time)) self.assertEqual(FonRT.get_dependencies(), []) self.assertEqual(FonRT_old.xml_parent, None)
def get1(sgw_addr, sgw_port, filepath): p = protocol.Protocol(sgw_addr, sgw_port) p.launch() rc = p.getfile1(filepath) if rc: print("file {} successfully downloaded!".format(filepath)) else: print("file {} download failed!".format(filepath)) p.finish()
def upload_entry(sgw_addr, sgw_port, nr_files, nr_threads, self_tid): n = self_tid while n < nr_files: p = protocol.Protocol(sgw_addr, sgw_port) p.launch() filepath = "{:016d}".format(n) p.putfile1(filepath) p.finish() n += nr_threads
def onconnect(self, sender): # Connect to the Arduino if dummy: print 'dummy' chip = protocol.DummyProtocol() else: try: chip = protocol.Protocol() except serial.SerialException: print 'cannot connect: falling back to dummy' chip = protocol.DummyProtocol() ticks = 0 t0 = None start = True while True: if t0 is None: t0 = time.time() # Read from chip #print 'chipread' chip.lock_read() chip_info = chip.jsonread() if chip_info is None: print 'r/fail' continue if start: print chip_info start = False # Send to JS #print 'jssend' sender.send_message(json.dumps(chip_info)) # Get spec back from JS #print 'jsread' ret = json.loads(sender.read_next_message()) cmd = chip.next_cmd() if cmd == 'load': # Send back to the chip #print 'chipsend' chip.write(ret['sys_state'], int(ret['p1']) if ret['p1'] else 0, int(ret['p2']) if ret['p2'] else 0) else: print 'oops', cmd ticks += 1 if ticks % 100 == 0: t = time.time() print ':: %d: %f Hz' % (ticks, 100 / (t - t0)) t0 = t
def getProtocol(use_sim): if use_sim: print("\n##### Connecting to simulation #####\n") connection = simulation.Connection("build/pipe.out", "build/pipe.in") else: print("\n##### Connecting to FPGA: #####\n") #Correct port can be set as env. device = os.getenv("DEVICE", "/dev/ttyUSB2") connection = uart.Connection(device) return protocol.Protocol(connection)
def TestChangeMathsToComputed(self): """Test changing the mathematical definition of a variable to type Computed. Covers the cases of variables originally of type State, Computed, and Constant. """ doc = self.LoadModel('heart/src/odes/cellml/LuoRudy1991.cellml') p = protocol.Protocol(doc.model, multi_stage=True) # Add maths setting Cai to a constant, thus replacing the ODE (state->computed) # TODO: What would happen if dCai/dt was used in the model? Cai = doc.model.get_variable_by_name( u'intracellular_calcium_concentration', u'Cai') time = doc.model.get_variable_by_name(u'environment', u'time') ode = Cai.get_ode_dependency(time) Cai_const = self.NewAssign(u'intracellular_calcium_concentration,Cai', (u'0.0002', u'millimolar')) p.inputs.add(Cai_const) self.failUnlessEqual(Cai.get_type(), pycml.VarTypes.State) # Change computed defintion for g_K (computed->computed) g_K = doc.model.get_variable_by_name( u'time_dependent_potassium_current', u'g_K') g_K_const = self.NewAssign(u'time_dependent_potassium_current,g_K', (u'0.282', u'milliS_per_cm2')) p.inputs.add(g_K_const) old_g_K = g_K.get_dependencies()[0] self.failUnlessEqual(g_K.get_type(), pycml.VarTypes.Computed) # Change PR_NaK from constant->computed (with same value) PR_NaK = doc.model.get_variable_by_name( u'time_dependent_potassium_current', u'PR_NaK') PR_NaK_const = self.NewAssign( u'time_dependent_potassium_current,PR_NaK', (PR_NaK.initial_value, PR_NaK.units)) p.inputs.add(PR_NaK_const) self.failUnlessEqual(PR_NaK.get_type(), pycml.VarTypes.Constant) # Apply protocol to model p.modify_model() # Check the changes self.assertEqual( Cai, doc.model.get_variable_by_name( u'intracellular_calcium_concentration', u'Cai')) self.assertEqual(ode.xml_parent, None) self.assertRaises(translators.MathsError, Cai.get_ode_dependency, time) self.assertEqual(Cai.get_dependencies()[0], Cai_const) self.assertEqual(Cai.get_type(), pycml.VarTypes.Computed) self.assertEqual(old_g_K.xml_parent, None) self.assertEqual(g_K.get_dependencies()[0], g_K_const) self.assertEqual(g_K.get_type(), pycml.VarTypes.Computed) self.assertEqual( PR_NaK, doc.model.get_variable_by_name(u'time_dependent_potassium_current', u'PR_NaK')) self.failIf(hasattr(PR_NaK, u'initial_value')) self.assertEqual(PR_NaK.get_dependencies()[0], PR_NaK_const) self.assertEqual(PR_NaK.get_type(), pycml.VarTypes.Computed)
def send_file_change(host, port, id_, root, filemtime, modify_table, filename, s): modify_table[filename] = filemtime logging.info("send file %s", filename) if s is None: s = protocol.Protocol(host, port) send_relet_file(s, id_, root, filename) buff, _ = s.recv(1024) logging.info("Response was: %s", str(buff)) changed = True return (modify_table, s, changed)
def download_entry(sgw_addr, sgw_port, nr_files, nr_threads, self_tid): n = self_tid while n < nr_files: p = protocol.Protocol(sgw_addr, sgw_port) p.launch() filepath = "{:016d}".format(n) rc = p.getfile1(filepath) if rc: pass else: print("file {} download failed!".format(filepath)) p.finish() n += nr_threads
def test6_stage2(sgw_addr, sgw_port, dirname, studyid, filelist): """上传生成的目录,上传的文件路径前面要求没有路径分隔符""" # print("test6_stage2") abscurpath = os.path.abspath(os.curdir) levelpath = studyops.calcpath(studyid) p = protocol.Protocol(sgw_addr, sgw_port) p.launch() os.chdir(dirname) for filename in filelist.keys(): filepath = os.sep.join((levelpath, studyid, filename)) p.putfile1(filepath) p.finish() os.chdir(abscurpath)
def test1_stage2(sgw_addr, sgw_port, old_name, new_name): """下载文件""" shutil.move(old_name, new_name) p = protocol.Protocol(sgw_addr, sgw_port) p.launch() rc = p.getfile2(old_name) p.finish() if rc: # print("file {} successfully download!".format(old_name)) pass else: # print("file {} download failed!".format(new_name)) pass return rc
def init_test_case(): try: client = ssh_client.SshClient(hostname, username, password) cmd_ctrl = remote_cmd.CmdCtrl(cmd_sender=client.exec_cmd, multi_cmd_sender=client.exec_multi_cmd, file_uploader=client.upload, file_downloader=client.download) proto = protocol.Protocol() test_case = TestCase(cmd_ctrl, proto) return test_case, client except Exception as e: LOG.error(e) exit()
def receive_cb(self, data): #logging.debug('receive data: %s', data); totallen = len(data) self._recvbuff += data while True: proto = protocol.Protocol() if proto.unpackage(self._recvbuff) == False: break self.handleMessage(proto) if totallen > proto.size() + proto.headsize(): self._recvbuff = self._recvbuff[proto.size() + proto.headsize()] else: self._recvbuff = "" break
def _network_weechat_msg(self, source_object, message): """Called when a message is received from WeeChat.""" # pylint: disable=bare-except try: proto = protocol.Protocol() if len(message.get_data()) >= 5: decoded_message = proto.decode(message.get_data()) self.parse_message(decoded_message) else: print("Error, length of received message is {} bytes.".format( len(message.get_data()))) except: print('Error while decoding message from WeeChat:\n%s' % traceback.format_exc()) self.net.disconnect_weechat()
def __init__(self, ip, port=10000, output_fun=None): # self.motor_control = MotorControl() # self.wheel_encoder = WheelEncoder() self.protocal = protocol.Protocol(output_fun) self.listen_socket = socket.socket() #创建套接字 self.listen_socket.bind((ip, port)) #绑定地址和端口号 self.listen_socket.listen(1) #监听套接字, 最多允许一个连接 self.listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #设置套接字 # self.listen_socket.setsockopt(socket.SOL_SOCKET, 20, self.rec_callback) if output_fun is not None: self.print = output_fun.output else: self.print = print self.print('Sck waiting...')
def train(agent, env, config): # get the default brain brain_name = env.brain_names[0] train_log = protocol.Protocol(config) for i_episode in range(1, config["max_num_episodes"] + 1): _run_train_episode(agent, env, brain_name, train_log) train_log.episode_update() train_log.write_statistics() print("\r", train_log, "\n", end="") mean_reward = np.mean(np.mean(train_log.episode_rewards[-100:])) if mean_reward >= config["average_score_for_solving"]: print( '\nEnvironment solved in {:d} episodes!\tAverage Score: {:.2f}' .format(i_episode - 100, mean_reward)) break
def set_files_source(self,reset=True,f_name='',fnkw_ts='',dstdir=''): if reset: self.stop() # self.srcdir = os.path.dirname(f_name) print('f_name: ', f_name) fnstr = f_name.split("/")[-2:] if len(f_name.split("/"))>1 else f_name.split("\\")[-2:] self.input = '_'.join(fnstr) if self.srcdir and f_name.endswith('sx'): drv = FD.Driver(f_name) pkg_handler = PackageHandler(self) self.data_retriever = PRO.Protocol(drv,'sxFile') self.data_retriever.set_sys_info_handler(pkg_handler) self.data_retriever.set_mic_data_handler(pkg_handler) self.data_retriever.set_imu_data_handler(pkg_handler) self.data_retriever.set_ecg_data_handler(pkg_handler) self.data_retriever.set_endingTX_callback(self.endingTX_callback) go = self.setRec(dstdir,fnkw_ts) if go: print('going to start Engine again for recording!') self.start()
def scrape_sheet(df, segment, last_row_dic, skater_list, conn_dic): protocol_coords = find_protocol_coordinates(df) logger.debug(f"Protocol coordinates are {protocol_coords}") for c in protocol_coords: prot = protocol.Protocol(df=df, protocol_coordinates=c, segment=segment, last_row_dic=last_row_dic, skater_list=skater_list, conn_dic=conn_dic) for i in prot.row_range: for j in prot.col_range: if "Skating Skills" in str(df.iloc[i, j]): if ENABLE_DEBUGGING_PAUSE: input("Found pcs hit Enter to continue") try: prot.parse_pcs_table(df, i, j, last_row_dic) except ValueError as ve: sys.exit( f"Encountered error reading PCS row in {segment.name} {segment.year} " f"{segment.discipline} {segment.segment}, {dict(vars(prot.skater))}: {ve}" ) elif "Elements" in str(df.iloc[i, j]): try: if ENABLE_DEBUGGING_PAUSE: input("Found elements hit Enter to continue") prot.parse_tes_table(df, i, j, last_row_dic) except ValueError as ve: sys.exit( f"Encountered error reading TES row in {segment.name} {segment.year} " f"{segment.discipline} {segment.segment}, {dict(vars(prot.skater))}: {ve}" ) elif "Deductions" in str(df.iloc[i, j]) and j < 4: if ENABLE_DEBUGGING_PAUSE: input("Found deductions hit Enter to continue") prot.parse_deductions(df, i, j, segment) segment.protocol_list.append(prot)
def main(): logger = logging.getLogger("pump19") logger.info("Pump19 started.") client_config = config.get_config("irc") client = protocol.Protocol(**client_config) loop = client.loop cmdhdl_config = config.get_config("cmd") cmdhdl = command.CommandHandler(client, loop=loop, **cmdhdl_config) logger.info("Starting 18 Games and Counting Scheduler") coro_18gac = functools.partial(cmdhdl.handle_command_18gac, "#loadingreadyrun", None, extra=4) sched_18gac = schedulrr.ScheduLRR("0 8 * * thu", coro_18gac, loop) def shutdown(): logger.info("Shutdown signal received.") sched_18gac.stop() client.shutdown() loop.add_signal_handler(signal.SIGTERM, shutdown) logger.info("Running protocol activity.") client.start() sched_18gac.start() loop.run_forever() # before we stop the event loop, make sure all tasks are done pending = asyncio.Task.all_tasks(loop) if pending: loop.run_until_complete(asyncio.wait(pending, timeout=5)) loop.close() logger.info("Protocol activity ceased.") logger.info("Exiting...")
def decode(self, message): """ Decode a binary message received from WeeChat/relay. Return True if OK, False if error. """ try: proto = protocol.Protocol() msgd = proto.decode( message, separator='\n' if self.args.debug > 0 else ', ') print('') if self.args.debug >= 2 and msgd.uncompressed: # display raw message print('\x1b[32m--> message uncompressed ({0} bytes):\n' '{1}\x1b[0m' ''.format(msgd.size_uncompressed, protocol.hex_and_ascii(msgd.uncompressed, 20))) # display decoded message print('\x1b[32m--> {0}\x1b[0m'.format(msgd)) except: traceback.print_exc() print('Error while decoding message from WeeChat') return False return True