def Dipole_Z_Matrix(input_par): index_map_l_m, index_map_box = Mod.Index_Map_M_Block(input_par) grid = Mod.Make_Grid(input_par["grid_spacing"], input_par["grid_size"], input_par["grid_spacing"]) matrix_size = grid.size * len(index_map_l_m) h = abs(grid[1] - grid[0]) Dipole_Matrix = PETSc.Mat().createAIJ([matrix_size, matrix_size], nnz=2, comm=PETSc.COMM_WORLD) istart, iend = Dipole_Matrix.getOwnershipRange() for i in range(istart, iend): l_block = index_map_l_m[floor(i/grid.size)][1] m_block = index_map_l_m[floor(i/grid.size)][0] grid_idx = i % grid.size if l_block < input_par["l_max"]: columon_idx = grid.size*index_map_box[(m_block, l_block + 1)] + grid_idx CG_Coeff = (l_block+1) / np.sqrt((2*l_block+1)*(2*l_block+3)) Dipole_Matrix.setValue(i, columon_idx, grid[grid_idx]*CG_Coeff) if abs(m_block) < l_block and l_block > 0: columon_idx = grid.size*index_map_box[(m_block, l_block - 1)] + grid_idx CG_Coeff = (l_block) / np.sqrt((2*l_block-1)*(2*l_block+1)) Dipole_Matrix.setValue(i, columon_idx, grid[grid_idx]*CG_Coeff) Dipole_Matrix.assemblyBegin() Dipole_Matrix.assemblyEnd() return Dipole_Matrix
def transmitMessage ( message ): # If the socket is not open, we'll dial. if Module.socketIsSuspended() == 0: SER.send('Dail socket, state is: %s\n' % Module.ATcommand('AT#SS=1')) if Module.socketDail( Config.API ) == 0: SER.send('Failed to open a socket\n') return 0 elif Module.socketResume() == 0: SER.send('Failed socket resume\n') response = Module.makeRequest(URL, ('[%s]' % message)) if ( response == 0 ): SER.send('Request failed\n') else: updateSettings(response) if ( Module.sendEscapeSequence() == 0 ): SER.send('Failed to escape, not in command mode\n') return 0
def BuildConfigurationFromFile(self, filename): # Delete the exiting configuration first self.DeleteConfiguration() # Build new configurations self.tree = ET.parse(filename) root = self.tree.getroot() modules = root.find("modules") for eachmodule in modules.findall('module') : model_name = eachmodule.find('name').text positionstr = eachmodule.find('position').text # print "position: ",self.StringToTuple(positionstr) module_position = self.StringToTuple(positionstr) jointanglestr = eachmodule.find('joints').text try: module_path = eachmodule.find('path').text except Exception, e: module_path = self.DEFAULT_PATH print "module path: ",module_path # print "joint angles: ",self.StringToTuple(jointanglestr) module_jointangle = self.StringToTuple(jointanglestr) if len(module_position) == 6: new_module = Module(model_name,module_position,module_jointangle,module_path) new_module.rotation_matrix = kinematics.rotz(module_position[5])* \ kinematics.roty(module_position[4])* \ kinematics.rotx(module_position[3]) elif len(module_position) == 7: new_module = Module(model_name,module_position,module_jointangle,module_path,True) new_module.rotation_matrix = kinematics.quatToRot(module_position[3:]) self.ModuleList.append(new_module) if self.ServerConnected == 1: self.PublishMessage(self.ModuleList[-1])
def Population_Calculator(Psi, FF_WF, input_par): Pop = {} M_N_Pop = {} Par = {} grid = Mod.Make_Grid(input_par["grid_spacing"], input_par["grid_size"]) l_range = input_par["l_max_bound_state"] * len(grid) + len(grid) pop_total = 0.0 for m in range(-1 * input_par["m_max_bound_state"], input_par["m_max_bound_state"] + 1): for n in range(input_par["n_max"]): Par[(m, n)] = Mod.Wave_Function_Pairity(FF_WF[(m, n)], input_par) pop = 0.0 for l in range(abs(m), input_par["l_max_bound_state"] + 1): x = FF_WF[(m, n)] y = Psi[(m, l)] pop += np.vdot( FF_WF[(m, n)][l * len(grid):l * len(grid) + len(grid)], Psi[(m, l)]) M_N_Pop[(m, n)] = pop M_N_Pop[(m, n)] = np.power(np.absolute(M_N_Pop[(m, n)]), 2.0) pop_total += M_N_Pop[(m, n)] print(pop_total) return M_N_Pop, Par
def make_computation_of_all_module(lst): resLst = [] for i in lst: modTest = Module(i) modTest.computeFuel() #print("la masse est de : ", i, " et le plein de carburant est de : ", modTest.getFuel()) resLst.append(modTest.getFuel()) #print(resLst) #print(len(lst)) #print(len(resLst)) return resLst
def test_computation(ms, resGoaled): modTest = Module(ms) modTest.computeFuel() resGiven = modTest.getFuel() if resGiven != resGoaled: print("\033[93mERROR\033[0m : for", ms, "as mass we only need :", resGoaled, "of fuel unit !\n------------------------>whereas you give : ", resGiven) else: print("\033[92mOK!\033[0m : for", ms, "it is", resGoaled, "the test passed ;-p")
def Dipole_X_Matrix(input_par): index_map_l_m, index_map_box = Mod.Index_Map_M_Block(input_par) grid = Mod.Make_Grid(input_par["grid_spacing"], input_par["grid_size"], input_par["grid_spacing"]) matrix_size = grid.size * len(index_map_l_m) h = abs(grid[1] - grid[0]) with open(sys.path[0] + "/wigner_3j.json") as file: wigner_3j_dict = json.load(file) Dipole_Matrix = PETSc.Mat().createAIJ([matrix_size, matrix_size], nnz=4, comm=PETSc.COMM_WORLD) istart, iend = Dipole_Matrix.getOwnershipRange() for i in range(istart, iend): l_block = index_map_l_m[floor(i/grid.size)][1] m_block = index_map_l_m[floor(i/grid.size)][0] grid_idx = i % grid.size if input_par["m_max"] == 0: Dipole_Matrix.setValue(i,i,0.0) continue if l_block < input_par["l_max"]: l_prime = l_block + 1 factor = pow(-1.0, m_block)*np.sqrt((2*l_block+1)*(2*l_prime+1)/2)*wigner_3j_dict[str((l_block,0,l_prime,0,1,0))] m_prime = m_block - 1 CG_Coeff = factor*(wigner_3j_dict[str((l_block,-1*m_block,l_prime,m_prime,1,-1))] - wigner_3j_dict[str((l_block,-1*m_block,l_prime,m_prime,1,1))]) columon_idx = grid.size*index_map_box[(m_prime, l_prime)] + grid_idx Dipole_Matrix.setValue(i, columon_idx, grid[grid_idx]*CG_Coeff) m_prime = m_block + 1 CG_Coeff = factor*(wigner_3j_dict[str((l_block,-1*m_block,l_prime,m_prime,1,-1))] - wigner_3j_dict[str((l_block,-1*m_block,l_prime,m_prime,1,1))]) columon_idx = grid.size*index_map_box[(m_prime, l_prime)] + grid_idx Dipole_Matrix.setValue(i, columon_idx, grid[grid_idx]*CG_Coeff) if l_block > 0: l_prime = l_block - 1 factor = pow(-1.0, m_block)*np.sqrt((2*l_block+1)*(2*l_prime+1)/2)*wigner_3j_dict[str((l_block,0,l_prime,0,1,0))] if -1*m_block < l_prime: m_prime = m_block - 1 CG_Coeff = factor*(wigner_3j_dict[str((l_block,-1*m_block,l_prime,m_prime,1,-1))] - wigner_3j_dict[str((l_block,-1*m_block,l_prime,m_prime,1,1))]) columon_idx = grid.size*index_map_box[(m_prime, l_prime)] + grid_idx Dipole_Matrix.setValue(i, columon_idx, grid[grid_idx]*CG_Coeff) if m_block < l_prime: m_prime = m_block + 1 CG_Coeff = factor*(wigner_3j_dict[str((l_block,-1*m_block,l_prime,m_prime,1,-1))] - wigner_3j_dict[str((l_block,-1*m_block,l_prime,m_prime,1,1))]) columon_idx = grid.size*index_map_box[(m_prime, l_prime)] + grid_idx Dipole_Matrix.setValue(i, columon_idx, grid[grid_idx]*CG_Coeff) Dipole_Matrix.assemblyBegin() Dipole_Matrix.assemblyEnd() return Dipole_Matrix
def InsertModel(self,*args): print "frob called with {} arguments".format(len(args)) insertedModel = False if self.InsertMethod.get() == "Position" : print "Method is position" module_position = (self.X_coor.get(),self.Y_coor.get(),self.Z_coor.get(),degree2rad(self.row.get()),degree2rad(self.pitch.get()),degree2rad(self.yaw.get())) print "Position tuple is ",module_position module_jointangle = (degree2rad(self.Joint0.get()),degree2rad(self.Joint1.get()),degree2rad(self.Joint2.get()),degree2rad(self.Joint3.get())) print "Joint angle tuple is ",module_jointangle new_module = Module(self.modelname.get(),module_position,module_jointangle,self.current_modeule_path) # Assign rotation matrix to new_module based on euler angles: new_module.rotation_matrix = kinematics.rotz(module_position[5])* \ kinematics.roty(module_position[4])* \ kinematics.rotx(module_position[3]) self.ModuleList.append(new_module) if self.ServerConnected == 1: self.PublishMessage(self.ModuleList[-1]) insertedModel = True else: print "Method is Connection" theOtherModule = self.findModule(self.connectedmodelvar.get()) if theOtherModule: module_jointangle= (degree2rad(self.Joint0.get()),degree2rad(self.Joint1.get()),degree2rad(self.Joint2.get()),degree2rad(self.Joint3.get())) print "Configuration generator joint angles: ",module_jointangle #-- Get module position and orientation. parent_face = self.Node2.get() new_module_face = self.Node1.get() (module_position, rotation_matrix, quaternion) = kinematics.get_new_position(theOtherModule, module_jointangle, parent_face, new_module_face) print 'XYZ: ' + str(module_position[0:3]) print 'RPY: ' + str(module_position[3:6]) print 'Quat: ' + str(quaternion) # -- new_module = Module(self.modelname.get(),tuple(list(module_position[0:3])+list(quaternion)),module_jointangle, self.current_modeule_path,True) # Add rotation matrix to new_module (necessary for kinematics) new_module.rotation_matrix = rotation_matrix self.ModuleList.append(new_module) print "Connected module name",self.connectedmodelvar.get() new_connection = Connection(self.modelname.get(),self.connectedmodelvar.get(),self.Node1.get(),self.Node2.get(),self.C_dis.get(),self.aoffset.get()) self.ConnectionList.append(new_connection) self.ModuleList[-1].connection(self.Node1.get(),self.ConnectionList[-1]) theOtherModule.connection(self.Node2.get(),self.ConnectionList[-1]) if self.ServerConnected == 1: self.PublishMessage(self.ModuleList[-1]) insertedModel = True if insertedModel: self.updateModuleList() self.nameIncrement() self.Rel_pos.select() self.DisableXYZInput() self.SaveEnable() print "Combox value", self.connectmodel.get() if self.connectmodel.get() != '': self.checkConnectivity()
def Proj_Bound_States_Out(input_par, psi, bound_states): idx_map_l_m, idx_map_box = Mod.Index_Map(input_par) grid = Mod.Make_Grid(input_par["grid_spacing"], input_par["grid_size"]) index_map_l_m, index_map_box = Mod.Index_Map(input_par) n_max = input_par["n_max"] for i in index_map_box: l = i[1] for n in range(l + 1, n_max + 1): psi[i] -= np.sum( bound_states[(n, l)] * psi[i]) * bound_states[(n, l)] return psi
def Psi_Plotter(input_par, Psi): grid = Mod.Make_Grid(input_par["grid_spacing"], input_par["grid_size"]) idx_map_l_m, idx_map_box = Mod.Index_Map(input_par) l_list = range(0, 10) for key in idx_map_box: l = key[1] if l in l_list: plt.plot(grid, np.absolute(Psi[key]), label=str(key)) plt.xlim(0, 10) plt.legend() plt.savefig("PsiI.png")
def initNetworkRelated ( ): # Unlock SIM card by entering PIN; Module.unlockSIM() SER.send('Done unlockSIM\n') if ( Module.attachNetwork( 20 ) == 0 ): SER.send('Failed attachNetwork\n') SER.send('Done attachNetwork\n') if ( Module.connectNetwork( Config.APN ) == 0 ): SER.send('Failed connectNetwork\n') SER.send('Done connectNetwork\n')
def initNetworkRelated(): # Unlock SIM card by entering PIN; Module.unlockSIM() SER.send('Done unlockSIM\n') if (Module.attachNetwork(20) == 0): SER.send('Failed attachNetwork\n') SER.send('Done attachNetwork\n') if (Module.connectNetwork(Config.APN) == 0): SER.send('Failed connectNetwork\n') SER.send('Done connectNetwork\n')
def Continuum_Wavefuncion_Maker(input_par): grid = Mod.Make_Grid(input_par["grid_spacing"], input_par["grid_size"], input_par["grid_spacing"]) ViewHDF5 = PETSc.Viewer() ViewHDF5.createHDF5("Continum.h5", mode=PETSc.Viewer.Mode.WRITE, comm=PETSc.COMM_WORLD) energy = 0.6874690338347257 for l in range(0, input_par["l_max"] + 1): if rank == 0: print("Calculating the eigenstates for l = " + str(l) + "\n") potential = eval("Pot." + input_par["potential"] + "(grid, l)") Hamiltonian = eval("TS.Build_Hamiltonian_" + input_par["order"] + "_Order(potential, grid, input_par)") Eigen_Value_Solver(Hamiltonian, input_par, l, energy, ViewHDF5) if rank == 0: print("Finished calculation for l = " + str(l) + "\n", "\n") ViewHDF5.destroy()
def convert(self): if len(self.__supplier.get_modules()) == 1: self.__main_module = list(self.__supplier.get_modules().keys())[0] m = Module.Module(self.__supplier) m.parse(self.__supplier.get_modules()[self.__main_module]) return m.get_bench_file()
def getOrCreateModule(self, moduleName): try: return self.modules[moduleName] except KeyError: newModule = Module.Module(moduleName) self.modules[moduleName] = newModule return newModule
def craw_start(): baseurl = 'http://www.xicidaili.com/nn/' # 西刺代理 # baseurl = 'http://m.66ip.cn/' # 抓取代理IP ip_detail = [] for page in range(1, 3): # url = 'http://ip84.com/dlgn/' + str(page) url = baseurl + str(page) + '.html' headers = Module.randHeader() request = urllib.request.Request(url=url, headers=headers) response = urllib.request.urlopen(request) content = response.read().decode('utf-8') print('爬取第' + str(page) + "页IP代理") pattern = re.compile('<td>(\d.*?)</td>') # 截取<td>与</td>之间第一个数为数字的内容 ip_page = re.findall(pattern, str(content)) ip_detail.extend(ip_page) time.sleep(random.choice(range(1, 3))) # 处理抓取内容 xiciproxy = open('xiciproxy.txt', 'w', encoding="utf-8") # 创建一个西刺代理的详细文档参考 xiciproxy.write('代理IP地址' + '\t' + '端口' + '\t' + '速度' + '\t' + '验证时间' + '\n') for i in range(0, len(ip_detail), 4): xiciproxy.write(ip_detail[i] + '\t' + ip_detail[i + 1] + '\t' + ip_detail[i + 2] + '\t' + ip_detail[i + 3] + '\n') # 整理代理IP格式 proxy_ip = open('Unverified_IP.txt', 'w') # 新建一个储存有效IP的文档 for i in range(0, len(ip_detail), 4): proxy_host = ip_detail[i] + ':' + ip_detail[i + 1] proxy_temp = proxy_host proxy_ip.write('%s\n' % str(proxy_temp)) proxy_ip.close() # 关闭文件 print('爬取完成')
def loadScript(self,lessonScriptPath): lessonScriptPath = self.completeLessonScriptPath(lessonScriptPath) courseName = 'STANDARD_COURSE' ###- TODO, implement get course name course = Course.Course(courseName,self.application) moduleName = self.getModuleNameFromLessonScriptPath(lessonScriptPath) lessons = {} module = Module.Module(moduleName,lessons,course) lessonName = self.getLessonNameFromLessonScriptPath(lessonScriptPath) pages = {} module.lessons[lessonName] = Lesson.Lesson(lessonName,pages,module) try : with open(lessonScriptPath,"r",encoding="utf-8") as scriptFile : for lessonScriptLine in scriptFile : if lessonScriptLine != '\n' : pageName = self.getPageNameFromLessonScriptLine(lessonScriptLine) pageScript = lessonScriptLine.strip() module.lessons[lessonName].pages[pageName] = Page.Page(pageName,pageScript,module.lessons[lessonName]) except : with open(lessonScriptPath,"+w",encoding="utf-8") as scriptFile : pass return module.lessons[lessonName]
def parseWasm(self): self.module = Module() self.parseMagic() self.parseVersion() while self.parseSection(): pass return self.module
def Bound_State_Plotter(input_par, m_n_array): BS, BE = Mod.Bound_State_Reader(input_par) grid = Mod.Make_Grid(input_par["grid_spacing"], input_par["grid_size"], input_par["grid_spacing"]) for m_n in m_n_array: m, n = m_n[0], m_n[1] wave_function = np.zeros(len(grid), dtype=complex) print(n, np.absolute(BE[(m, n)])) for l in range(0, input_par["l_max_bound_state"] + 1): wave_function += BS[(n, l, m)] plt.plot(grid, np.absolute(wave_function)) plt.xlim(0, 50) plt.savefig("WF.png")
def _parsemaps(self, maps): # Parse the maps mapre = re.compile( r'([0-9a-fA-F]+)-([0-9a-fA-F]+)\s+(....)\s+([0-9a-fA-F]+)\s+\S+\s+\S+\s+(.+)' ) for ml in maps.split('\n'): mat = mapre.match(ml) if mat: begin = long(mat.group(1), 16) end = long(mat.group(2), 16) perm = mat.group(3) offset = long(mat.group(4), 16) modpath = mat.group(5) # Exclude unacceptable modules if perm[2] != 'x': continue if modpath[:5] == '/dev/': continue if modpath == '[vectors]': continue if modpath == '[sigpage]': continue if modpath not in self._modules: self._modules[modpath] = Module(modpath, self._modcache) self._modules[modpath].add_map(begin, end, offset, perm)
def get_module(cfg): # todo 到Parameters定义处定义相关参数 mod = Module(cfg) mod.logger.info(str(mod)) filename = mod.cfg.cfg_path mod.logger.info("parameters saved to %s" % filename) return mod
def TISE(input_par): if rank == 0: start_time = time.time() print("Calculating States for H2+ \n ") print("R_0 = " + str(input_par["R_o"]) + "\n") grid = Mod.Make_Grid(input_par["grid_spacing"], input_par["grid_size"]) ViewHDF5 = PETSc.Viewer() ViewHDF5.createHDF5(input_par["Target_File"], mode=PETSc.Viewer.Mode.WRITE, comm=PETSc.COMM_WORLD) for m in range(0, input_par["m_max_bound_state"] + 1): if rank == 0: print("Calculating the States for m = " + str(m) + "\n") Hamiltonian = eval("Build_Hamiltonian_" + input_par["order"] + "_Order(input_par, grid, m)") Eigen_Value_Solver(Hamiltonian, input_par["n_max"], input_par, m, ViewHDF5) if rank == 0: total_time = (time.time() - start_time) / 60 print("Total time taken for calculating States is " + str(round(total_time, 1)) + " minutes !!!") print( "*****************************************************************" ) ViewHDF5.destroy()
def setUp(self): """Set up the testing environment""" self.module = Module.Module() self.dataunit = lib.DataUnit.CombinedDataUnit() self.ch1rdr = vtk.vtkLSMReader() self.ch2rdr = vtk.vtkLSMReader() self.ch1rdr.SetFileName("/Users/kallepahajoki/BioImageXD/Data/sample1_series12.lsm") self.ch2rdr.SetFileName("/Users/kallepahajoki/BioImageXD/Data/sample1_single.lsm")
def get_All_Testaments(self): cursor.execute("SELECT * FROM TESTAMENT") found = cursor.fetchall() testaments = [] for item in found: hydrate_testaments = Module.Testament() hydrate_testaments.hydrate(item) testaments.append(hydrate_testaments) return testaments
def get_All_Chapters(self, Book_id): self.Book_id = Book_id sql_query = ( "SELECT CHAPTER FROM CONTENT WHERE BOOK='%s' ") % self.Book_id cursor.execute(sql_query) chapters = cursor.fetchall() hydrate_chapter = Module.Content() hydrate_chapter.Chapter = chapters return hydrate_chapter
def get_module(self, module_name): if self.__predefined_modules is not None and module_name in self.__predefined_modules.keys(): r = Module.Module(self) r.parse(self.__predefined_modules[module_name]) return r try: input_data = open(self.__folder_path + module_name + '.txt', 'r') inputS = input_data.read() input_data.close() self.parse(inputS) r = Module.Module(self) r.parse(self.__predefined_modules[module_name]) return r except ModuleNotFoundError: raise Exception('Module not found')
def Dipole_Plot(file_name): time = np.loadtxt(file_name + "/time.txt") data_x = np.loadtxt(file_name + "/Dip_Acc_X.txt").view(complex) data_y = np.loadtxt(file_name + "/Dip_Acc_Y.txt").view(complex) input_par = Mod.Input_File_Reader(file_name + "/input.json") # laser_pulse, laser_time, total_polarization, total_poynting, elliptical_pulse = LP.Build_Laser_Pulse(input_par) print(round(np.average(data_x), 10)) print(round(np.average(data_y), 10))
def Eigen_State_Solver(input_par): if input_par["solver"] == "File": if rank == 0: print("Reading eigenstates from " + input_par["Target_File"] + "\n") energy, wave_function = Mod.Target_File_Reader(input_par) return energy, wave_function elif input_par["solver"] == "SLEPC": if rank == 0: print("Calculating the Eigenstates and storing them in " + input_par["Target_File"] + "\n") TISE.TISE(input_par) energy, wave_function = Mod.Target_File_Reader(input_par) return energy, wave_function else: print("\nArgumet for the solver must be 'File' or 'SLEPC' ")
def get_Content_Id(self, Book_Id, Chapter_Id): self.Book_Id = Book_Id self.Chapter_Id = Chapter_Id sql_query = ("SELECT ID FROM CONTENT WHERE BOOK='%s' AND CHAPTER='%s'" ) % (self.Book_Id, self.Chapter_Id) cursor.execute(sql_query) content_id = cursor.fetchall() hydrate_content = Module.Content() hydrate_content.ID = content_id return hydrate_content
def __init__(self, para, hostName, Logger): import Module import Utiles self._hostName = hostName self._taskFreq = para["taskFreq"] if "taskFreq" in para else 0 self._indexFreq = para["indexFreq"] if "indexFreq" in para else 15 self._Message = Utiles.Message(para["dictString"], Logger) self._Module = Module.Module(self._Message, para["indexUrl"], para["downloadUrl"], Logger) self._taskUrl = para["taskUrl"] if "taskUrl" in para else False self._resultUrl = para["resultUrl"] if "resultUrl" in para else False self._Logger = Logger
def get_All_Books(self, Testament_Id): self.Testament_Id = Testament_Id sql_query=("SELECT * FROM BOOK WHERE id in(SELECT BOOK FROM CONTENT WHERE TESTAMENT='%s' and id in(SELECT CONTENTID FROM FILE))")\ %self.Testament_Id cursor.execute(sql_query) books = cursor.fetchall() book = [] for items in books: hydrate_book = Module.Book() hydrate_book.hydrate(items) book.append(hydrate_book) return book
def transmitMessage(message): # If the socket is not open, we'll dial. if Module.socketIsSuspended() == 0: SER.send('Dail socket, state is: %s\n' % Module.ATcommand('AT#SS=1')) if Module.socketDail(Config.API) == 0: SER.send('Failed to open a socket\n') return 0 elif Module.socketResume() == 0: SER.send('Failed socket resume\n') response = Module.makeRequest(URL, ('[%s]' % message)) if (response == 0): SER.send('Request failed\n') else: updateSettings(response) if (Module.sendEscapeSequence() == 0): SER.send('Failed to escape, not in command mode\n') return 0
def solve(self, tra): if tra.type == "BC_TRANSACTION": try: descriptor, code = self.lookup(tra) except LookupException as e: #logger.warn(e) return except HardwareDescriptor: return if self.filter and not self.filter.isPass(tra, descriptor, code): return Module.getModule().call("SOLVING_START", tra, descriptor, code) if not Config.NOT_SOLVE: print("==============================") #print "#{}[{}] {} ==> {} / [{}]: {}".format(tra.debug_id, datetime.fromtimestamp(tra.time).strftime('%Y-%m-%d %H:%M:%S'), tra.from_proc_name, tra.to_proc_name, descriptor, code) print("#{} {} ==> {} / [{}]: {}".format(tra.debug_id, tra.from_proc_name, tra.to_proc_name, descriptor, code)) #print "{{{" result = self.sSolver.solve(descriptor, code, tra.parcel) #print "}}}" if result: print("\t{}({})".format(result[0], ", ".join(str(i) for i in result[1:]))) Module.getModule().call("SOLVING_SUCCESS", *result) else: Module.getModule().call("SOLVING_FAIL") """
def __init__(self, wheelsLeftPin = 23,\ wheelsRightPin = 24,\ CNY70EncodeMidPinLeft = 17,\ CNY70EncodeMidPinMid = 27,\ CNY70EncodeMidPinRight = 22,\ CNY70EncodeLeftPinLeft = 5,\ CNY70EncodeLeftPinMid = 6,\ CNY70EncodeLeftPinRight = 13,\ CNY70EncodeRightPinLeft = 16,\ CNY70EncodeRightPinMid = 20,\ CNY70EncodeRightPinRight = 21): self.wheels = Module.Wheels(wheelsLeftPin, wheelsRightPin) self.encodeMid = Module.CNY70Encode(CNY70EncodeMidPinLeft, CNY70EncodeMidPinMid, CNY70EncodeMidPinRight) self.encodeLeft = Module.CNY70Encode(CNY70EncodeLeftPinLeft, CNY70EncodeLeftPinMid, CNY70EncodeLeftPinRight) self.encodeRight = Module.CNY70Encode(CNY70EncodeRightPinLeft, CNY70EncodeRightPinMid, CNY70EncodeRightPinRight)
def initSettings ( ): # Set error reporting to numeric; Module.enableErrorReporting() SER.send('Done enableErrorReporting\n') # Don't send the (+++) escape sequence when suspending a socket; Module.skipEscape() SER.send('Done skipEscape\n') # Flow control is not connected; Module.disableFlowControl() SER.send('Done disableFlowControl\n')
def solve(self, tra): global json_output; if tra.type == "BC_TRANSACTION": try: descriptor, code = self.lookup(tra) except LookupException as e: #logger.warn(e) return except HardwareDescriptor: return if self.filter and not self.filter.isPass(tra, descriptor, code): return Module.getModule().call("SOLVING_START", tra, descriptor, code) if not Config.NOT_SOLVE: print "==============================" #print "#{}[{}] {} ==> {} / [{}]: {}".format(tra.debug_id, datetime.fromtimestamp(tra.time).strftime('%Y-%m-%d %H:%M:%S'), tra.from_proc_name, tra.to_proc_name, descriptor, code) __builtin__.json_output[tra.debug_id] = {} __builtin__.json_output[tra.debug_id]['Source'] = tra.from_proc_name __builtin__.json_output[tra.debug_id]['Target'] = tra.to_proc_name __builtin__.json_output[tra.debug_id]['Transact_code'] = code __builtin__.json_output[tra.debug_id]['Class'] = descriptor __builtin__.json_output[tra.debug_id]['Action'] = '?' __builtin__.json_output[tra.debug_id]['requestCode'] = '?' __builtin__.json_output[tra.debug_id]['resultCode'] = '?' __builtin__.json_output[tra.debug_id]['Extras'] = [] print "#{} {} ==> {} / [{}]: {}".format(tra.debug_id, tra.from_proc_name, tra.to_proc_name, descriptor, code) #print "{{{" __builtin__.debugid = tra.debug_id result = self.sSolver.solve(descriptor, code, tra.parcel) #print "}}}" if result: print "\t{}({})".format(result[0], ", ".join(str(i) for i in result[1:])) Module.getModule().call("SOLVING_SUCCESS", *result) __builtin__.json_output[tra.debug_id]['Result'] = { "Name":result[0], "Params":result[1:] } else: Module.getModule().call("SOLVING_FAIL") __builtin__.debugid = -1 """
import Module Module.data = 3 Module.printData()
# 2. Picking up a random location along the road (starting from Northernmost point of road as 0 metre , # 3. Providing it with a random direction (either North or South) # 4. Calculating it's distance from the antenna prob_Making_Call = (call_Rate_perHour/3600) * sim_Step_Size_sec rndm_Toss_1 = random.random() user_Calls = 'N' if (rndm_Toss_1 <= prob_Making_Call): # User wants to make a call user_Calls = 'Y' call_Attempts_Hour = call_Attempts_Hour + 1 if (user_Calls == 'Y'): # CALL FUNCTION TO GENERATE RANDOM LOCATION AND DIRECTION j = [] j = Module.location_Assign(i,road_Length_m,direction,perp_Distance_m) for indx in range(len(j)): i[indx] = (j[indx]) location = i[1] vehicle_Direction = i[2] distance_From_Antenna_m = i[3] # Check if User has an Active call from before if(len(i) > 6): user_Calls = 'Y' # Set up EIRP, Losses and RSL to be checked whether successful call establishment is possible or not if (user_Calls == 'Y'): # FADING VALUE CALCULATION fading_Value_dB_alpha = Module.fading_Calc()
#!/usr/bin/python import sys from Module import * if __name__ == "__main__": args = sys.argv args.pop(0) modules = [] instances ="" if(len(args) >0): for i in args: m = Module() m.updateFromFile(i) modules.append(m) instances = instances + m.getIntermediateNets() print instances for i in modules: print i else: print "pass in files to this script. the first is the top module. the rest are instances to be put in the testbench."
__author__ = "Avantha" import Module import random x = random.randrange(1, 1000) Module.fish() print(x)