def Passgang(matrixnew,extractedstep): ACC = Init.getData(matrixnew,sensors=["RNS","LLL"],datas=["acc"],specifiedDatas="x") ACC2 = Init.getData(matrixnew,sensors=["LNS","RLL"],datas=["acc"],specifiedDatas="x") ACC = Ableitung(ACC[:,:],[2,3],1)[:,2:] ACC2 = Ableitung(ACC2[:,:],[2,3],1)[:,2:] zeitverschiebung =[] zeitverschiebunglinks =[] for i in range(0,len(extractedstep)): maxpos = (np.argmax(ACC2[(extractedstep[i,0]):(extractedstep[i,1]),0])) minpos= (np.argmax(ACC2[(extractedstep[i,0]):(extractedstep[i,1]),1])) print abs(maxpos-minpos) print "_______" print (extractedstep[i,1]-extractedstep[i,0]) zeitverschiebung.append(float(abs(maxpos-minpos))/float((extractedstep[i,1]-extractedstep[i,0]))) maxpos = (np.argmax(ACC[(extractedstep[i,0]):(extractedstep[i,1]),0])) minpos= (np.argmax(ACC[(extractedstep[i,0]):(extractedstep[i,1]),1])) zeitverschiebunglinks.append(float(abs(maxpos-minpos))/float((extractedstep[i,1]-extractedstep[i,0]))) vereinigung=[] for j in range(0,len(zeitverschiebunglinks)): if(zeitverschiebung[j]>=zeitverschiebunglinks[j]): vereinigung.append(zeitverschiebunglinks[j]) else: vereinigung.append(zeitverschiebung[j]) plt.plot(vereinigung) plt.show() return vereinigung
def Random_dummy(atomlist, box): max_index = Rebuild.Max_index(atomlist) other_index = Random.Return_index_Other(atomlist) num_dummy = Calc_dummy(atomlist) choose_index, choose_list = [], [] while len(choose_index) < num_dummy: new_index = nr.choice(other_index, 1) monoindex = atomlist.search_index(new_index).Monomer_print_index() for index in monoindex: if index in other_index: other_index.remove(index) choose_index.append(new_index) choose_list.append(atomlist.search_index(new_index)) choose_list = Init.Atomlist(choose_list) dummylist = [] for atom in choose_list.value: bx, by, bz = box.x, box.y, box.z carbon = atom.neighbour[0] rx, ry, rz = atom.x * bx, atom.y * by, atom.z * bz Rx, Ry, Rz = carbon.x * bx, carbon.y * by, carbon.z * bz vect1 = np.array([Rx - rx, Ry - ry, Rz - rz]) vect1 = vect1 / np.linalg.norm(vect1) * 5 #Estimated Radii qx, qy, qz = (np.array([Rx, Ry, Rz]) + vect1).tolist() dummy = Dummy(qx / bx, qy / by, qz / bz, 'X' + str(max_index + 1) + 'x', max_index + 1) max_index = max_index + 1 atomlist.value.append(dummy) dummylist.append(dummy) dummylist = Init.Atomlist(dummylist) print('Successful Creat Dummy Atoms') return atomlist, dummylist
def update_node_position(movement_matrix, node_position, start_t, update_period, animation, nodelist, com_nodelist, controller): print('开始时间:', start_t) active_route = [] current_move = movement_matrix[np.nonzero( movement_matrix[:, 0].A == start_t)[0], :] print(current_move) for value in current_move: for i in range(2, 4): node_position[int(value[0, 1]), i + 2] = value[0, i] speed_x = node_position[:, 4] - node_position[:, 2] speed_y = node_position[:, 5] - node_position[:, 3] for i in range(0, int(1.0 / gp.update_period)): node_position[:, 2] = node_position[:, 2] + speed_x * gp.update_period node_position[:, 3] = node_position[:, 3] + speed_y * gp.update_period node_id_position = node_position[:, [1, 2, 3]] if nodelist == [] or com_nodelist == []: nodelist.extend(Init.init_node(node_id_position, controller)) com_nodelist.extend( Init.get_communication_node(node_id_position.shape[0])) print('所有通信节点:', com_nodelist) # active_route = simulation(node_id_position,nodelist,com_nodelist,i,active_route) # print(active_route) if animation: plt.clf() plt.plot(node_position[:, 2], node_position[:, 3], '.m') plt.pause(0.01)
def Stockaufsatz(matrixnew,extractedstep,Einheitsvektor ="rE1"): re1 = Init.getData(matrixnew,sensors=["RNS","LNS"],datas=[ Einheitsvektor]) ACC = Init.getData(matrixnew,sensors=["RNS","LNS"],datas=["acc"],specifiedDatas="x") ACCright = Ableitung(ACC[:,:],[2],1)[:,2:] ACCleft = Ableitung(ACC[:,:],[3],1)[:,2:] Vektor = np.zeros((len(re1),3)) Vektor[:,2] = 1 anlematrixre1 = angle(re1[:,2:5],Vektor) anlematrixre = angle(re1[:,5:8],Vektor) anglestickright = anlematrixre1[:,0] anglestickleft = anlematrixre[:,0] rightpeak = [] leftpeak = [] for i in range(0,len(extractedstep)): posleft = (np.argmax(ACCleft[(extractedstep[i,0]):(extractedstep[i,1]),0])) leftpeak.append(anglestickleft[(extractedstep[i,0])+posleft,0]) posright = (np.argmax(ACCright[(extractedstep[i,0]):(extractedstep[i,1]),0])) rightpeak.append(anglestickright[(extractedstep[i,0])+posright,0]) print rightpeak return rightpeak,leftpeak
def BWError(): if os.path.exists("Output/"): if Init.SystemJudge() == 0: os.system("rm -r Output") else: os.system("rmdir /s /q directory") NameArr = Pretreatment.FigureInput(1) try: if NameArr == -1: return except: pass #Figure traversal for kase in range(0, len(NameArr)): img = np.array(Image.open(NameArr[kase]).convert("L")) """ for i in range(0, len(img)): for j in range(0, len(img[i])): if random.randint(1, 50) == 1: img[i][j] += np.random.normal(img[i][j], 64) img[i][j] = max(0, img[i][j]) img[i][j] = min(255, img[i][j]) """ Name = "Figure_" Name += str(Init.GetTime()) Name += ".png" Pretreatment.Output(img, Name, 2)
def lhc_study(i, scandir, cm=True): if type(scandir) in (tuple, list): cmdir, herwigdir = scandir else: herwigdir, cmdir = scandir, scandir name = 'lhc' hevents = osp.join(herwigdir, Init.ident_to_path(i)) cmevents = osp.join(cmdir, Init.ident_to_path(i)) cardname = osp.join(hevents, "MGcard.dat") Hcardname = osp.join(hevents, "H.dat") # Hruncardname = osp.join(events,"Hrun.dat") Hconfigtmp = osp.join(hevents, "herwigMRSSM") hepmcpath = osp.join(hevents, name + ".hepmc") CMfile = osp.join(cmevents, "CM.dat") slhafile = osp.join(cmevents, "SPheno.spc.MRSSM") SLHA.flavor_order(slhafile, toRSSM=True) lhepath = None # lhc.genlhe(slhafile,process,name,events,cardname,nofevents) # lhc.HerwigCM(slhafile,process,name,events,Hcardname,Hconfigtmp,Hconfigbase, # Htemplate,lhepath,hepmcpath, analyses,CMfile,nofevents) Hconfigbase = Hconf_process lhc.full_herwig(slhafile, name, hevents, Hcardname, Hconfigtmp, Hconfigbase, Htemplate, hepmcpath, nofevents) if cm: lhc.CM_run(name, cmevents, analyses, hepmcpath, CMfile, nofevents, cleanup=True)
def Read_Model(MODEL_FILE): import numpy as np from copy import deepcopy import os import Init model_path = "" for i in range(0, len(MODEL_FILE)): model_path = os.path.join(model_path, MODEL_FILE[i]) File = open(model_path, "r") FileLine = File.readline() information = FileLine[0: -1] print("Model Information:") print(information) FileLine = File.readline() initial_t, final_t, delta_t = Init.FileReadLine(FileLine, mode = "float") initial_val = [] states = [] Jacobian = [] FileLine = File.readline() while 1: if not FileLine: break array = Init.FileReadLine(FileLine, mode = "float") if len(states) == 0: initial_val = deepcopy(array) if len(array) == len(initial_val): states.append(np.array(array)) else: array = np.matrix(np.reshape(np.matrix(array), (len(initial_val), len(initial_val)))) Jacobian.append(array) FileLine = File.readline() return information, initial_val, initial_t, final_t, delta_t, states, Jacobian
def lhc_study(i, scandir, cm=True): if type(scandir) in (tuple, list): cmdir, herwigdir = scandir else: herwigdir, cmdir = scandir, scandir name = 'lhc' hevents = osp.join(herwigdir, Init.ident_to_path(i)) cmevents = osp.join(cmdir, Init.ident_to_path(i)) cardname = osp.join(hevents, "MGcard.dat") Hcardname = osp.join(hevents, "H.dat") # Hruncardname = osp.join(events,"Hrun.dat") Hconfigtmp = osp.join(hevents, "herwigMSSM") hepmcpath = osp.join(hevents, name + ".hepmc") CMfile = osp.join(cmevents, "CM.dat") slhafile = osp.join(cmevents, "SPheno.spc.MSSM") SLHA.flavor_order(slhafile) lhepath = None Hconfigbase = Hconf_process lhc.full_herwig(slhafile, name, hevents, Hcardname, Hconfigtmp, Hconfigbase, Htemplate, hepmcpath, nofevents) if cm: #sigma,Kfac = lhc.get_Kfac("SPheno.spc.MSSM", cmevents, "sqsum") #if sigma>0: # lhc.CM_run(name,cmevents,analyses,hepmcpath,CMfile, # nofevents,sigma=sigma,cleanup=False) #else: lhc.CM_run(name, cmevents, analyses, hepmcpath, CMfile, nofevents, cleanup=True)
def Start(inputfile='PVDF-model.cif', size=2000, dm=15, mv=[0, 0]): size = size / 2 box, atomlist = Init.Split_file(inputfile) num = int(pow(size / len(atomlist.value), 1 / 2) + 1) print('Now Generating a Supercell of ', 1, '*', num, '*', num, '\n') print('######## Now Initializing Supercell ########\n') modbox = Modbox(box.x, box.y, box.z, num, dm) modbox.divide_box(mv) modbox.add_atomlist() #print('Though required size was ',size,', in total we make ',len(modbox.atomlist.value),' atoms\n') print('######## Now Generating Plasticizer ########\n') numplast = Dummy.Calc_dummy(modbox.atomlist1) Add_plastic(modbox, numplast) modbox.add_atomlist() print('Though required size was ', size * 2, ', in total we make ', len(modbox.atomlist1.value + modbox.atomlist2.value), ' atoms, including ', len(modbox.atomlist2.value), ' atoms from plasticizers\n') mass1 = Dummy.Calc_mass(modbox.atomlist1) mass2 = Dummy.Calc_mass(modbox.atomlist2) print('The actual Mass Ratio is ', mass2 / (mass1 + mass2) * 100, '\n') Build.build_poscar(modbox.atomlist1, modbox, filename='Polymer') Build.build_poscar(modbox.atomlist2, modbox, filename='Plastic') Build.build_poscar(Init.Atomlist(modbox.atomlist1.value + modbox.atomlist2.value), modbox, filename='Combine')
def _Init(): "Initialize Cmtest" if Globals.Debug: print("In this Function %s" % __name__) global Linux_gbl global Erc global Force if not os.name == "nt": Linux_gbl = 'Ubuntu' # Added 3/4/10 to support Ubuntu install try: with open("/etc/*release", r) as fh: for line in fh: if re.search(r"Ubuntu", line): Linux_gbl = 'Ubuntu' elif re.search(r"Fedora", line): Linux_gbl = 'Fedora' elif re.search(r"CentOS", line): Linux_gbl = 'CentOS' else: Linux_gbl = 'unknown' print( "Un-suported linux type found, I am going to die now" ) exit() except: print( "Un-suported linux type found, are we Windows? I am going to die now" ) if not Debug: exit() #else we are NT print("Debug in _Init %i" % Globals.Debug) Init.Init_All(0) Globals.Erc = 101 Globals.Erc = 0 Init.Init_Also(0) return
def scaninit(): point = MSSM_LHC() points = [] for x in range(1000, 5001, 400): # m1 for y in range(400, 2001, 200): # msq pointtmp = point[:] pointtmp[0] = 0 #pointtmp[13] = x #pointtmp[1] = y pointtmp[2] = 5000 pointtmp[3] = x * x pointtmp[4] = y * y pointtmp[7] = x * x pointtmp[8] = y * y pointtmp[9] = x * x pointtmp[10] = y * y points.append(pointtmp) print len(points) switches = [0, 0, 1, 0, 0, 0, 0] print scanpath, dbdir Init.init_struc(points, scanpath, zip(parameter, para_types), switches, createSLHAinMSSMfull, dbdir, makedb=True)
def fun(i, scanpath): j = 0 lim = 3 i = str(i) filename = osp.join(scanpath, Init.ident_to_path(i), "SPheno.spc." + model) sphenofunc(i, scanpath) for m, val in enumerate(value): if type(val) in (list, tuple): result = SLHA.getvalues(filename, [val]) value[m] = float(result[0]) # interpret as SLHA line and return wanted value while j < lim: j += 1 try: val = [float(x) for x in SLHA.getvalues(filename, outpar)] paramval = [float(x) for x in SLHA.getvalues(filename, param)] ## check if spectrum was created, except OSError as e: break print val, paramval if all([abs(x) < eps for x in measure(val, value)]): break else: os.remove(filename) newpar = func(val, value, paramval) pointpath = osp.join(scanpath, Init.ident_to_path(i)) Init.changeSLHA(osp.join(pointpath, i + ".SLHA.in"), createSLHAin, param, newpar) sphenofunc(i, scanpath)
def rerun_CM(i, scandir): if type(scandir) in (tuple, list): cmdir, herwigdir = scandir else: herwigdir, cmdir = scandir, scandir name = 'lhc' hevents = osp.join(herwigdir, Init.ident_to_path(i)) cmevents = osp.join(cmdir, Init.ident_to_path(i)) cardname = osp.join(hevents, "MGcard.dat") Hcardname = osp.join(hevents, "H.dat") # Hruncardname = osp.join(events,"Hrun.dat") Hconfigtmp = osp.join(hevents, "herwigMRSSM") hepmcpath = osp.join(hevents, name + ".hepmc") CMfile = osp.join(cmevents, "CM.dat") slhafile = osp.join(cmevents, "SPheno.spc.MRSSM") lhepath = None lhc.CM_run_no_delphes(name, cmevents, analyses, hepmcpath, CMfile, nofevents, lhepath=lhepath)
def main(): Init.initialize() Financial.download() Financial.analyze() Draw.draw(where="1", order="roi", sort="DESC", draw_candle_stick=True, draw_roi=False, draw_share_holder=False, save_fig=True)
def wrapper(i, scandir): try: out = readHandW(i, scandir) #point = [i]+readHB(i,scandir)+readHS(i,scandir) print i except IOError: pass else: point = [int(i)] + [float(x) for x in out] Init.register_point(outdb, 'mhmw', point)
def OnMenuFileMenuopenCaseMenu(self, event): import Init import dlgDataSource self.SetCursor(wx.HOURGLASS_CURSOR) Init.InitGlobals() dlg = wx.FileDialog(self, "Open Case", ".", "", "*.cfi", wx.OPEN) try: if dlg.ShowModal() == wx.ID_OK: success = True msg = "" Globals.CurrentCaseFile = dlg.GetPath().encode('utf-8', 'replace') busy = wx.BusyInfo("It might take some good few minutes depending on the evidence size...") wx.Yield() if DBFunctions.GetCaseSettings(Globals.CurrentCaseFile): Init.InitAllDBFileNames() DBFunctions.GetCaseEvidences(Globals.CurrentCaseFile) for key in Globals.EvidencesDict: dlg = dlgDataSource.create(self, key) dlg.ShowModal() #print 'wait' #Globals.MACFileName = Globals.CurrentCase.CaseName + Constants.MACExtension #Globals.KeywordsFileName = Globals.CurrentCase.CaseName + Constants.KeywordsExtension #Globals.TextCatFileName = Globals.CurrentCase.CaseName + Constants.TextCatExtension DBFunctions.LoadMACMinMaxValues() DBFunctions.UpdateDatabaseTables() else: msg = "Couldn't open Case File: %s!"%Globals.CurrentCaseFile success = False if not success: dlg = wx.MessageDialog(self, msg , 'Error', wx.OK | wx.ICON_ERROR) try: #Globals.CaseOpen = False #self.ShowCaseProperties(False) dlg.ShowModal() #return finally: dlg.Destroy() else: Globals.CaseOpen = True self.SetTitle("MAKE2 - " + Globals.CurrentCaseFile) #self.ShowDirectoryTreeView() self.notebookCase.Show(True) self.ShowCaseProperties(True) finally: dlg.Destroy() self.SetCursor(wx.STANDARD_CURSOR)
def add_atomlist(self): atomlist_tot1 = [] atomlist_tot2 = [] for box in self.boxlist: atomlist_tot1 = atomlist_tot1 + box.atomlist.value for box in self.otherboxlist: atomlist_tot2 = atomlist_tot2 + box.atomlist.value self.atomlist1 = Init.Atomlist(atomlist_tot1) self.atomlist1.reindex() self.atomlist2 = Init.Atomlist(atomlist_tot2) self.atomlist2.reindex()
def __Init(): global __init if __init != 1: Init.__Init() global redis_db redis_db = Init.redis_db __init_XYTGrid() __init = 1 else: pass return 0
def read_CM2(i, scandir): """read all signal regions evaluated, first checks if result exists""" results = osp.join(scandir, Init.ident_to_path(i), 'lhc_cm', 'result.txt') if not osp.exists(results): print "s.th. wrong with CheckMATE, no result for " + i raise IOError results = osp.join(scandir, Init.ident_to_path(i), 'lhc_cm', "evaluation", "best_signal_regions.txt") out = lhc.read_CMresults(results) print out return out
def Pretreatment(FileDir, SufixSet, ModelFolder, Parameter): import numpy as np from PIL import Image import cv2 import os from keras.utils import to_categorical print("Train model start, data reading", end="\r") #Initial data set Data = [] #Get files direction if not os.path.exists(FileDir): return 2, [], [] if len(SufixSet) == 0: return 3, [], [] for i in range(0, len(SufixSet)): if SufixSet[i] == "yuv": return 4, [], [] if not os.path.exists(ModelFolder): return 6, [], [] Files1 = Init.GetSufixFile(FileDir + "/0", SufixSet) Files2 = Init.GetSufixFile(FileDir + "/1", SufixSet) #Build the sign Result = [0 for n in range(len(Files1))] Files1 += Files2 Result += [1 for n in range(len(Files2))] if len(Files1) == 0 or len(Files2) == 0: return 5, [], [] #Get image data and down sample for i in range(0, len(Files1)): img = np.array(Image.open(Files1[i]).convert("L")) Data.append(cv2.resize(img, (Parameter[1], Parameter[2]))) print("Data read succeed, training surround initial", end="\r") os.environ["CUDA_VISIBLE_DEVICES"] = "0" Data = np.array(Data) Result = np.array(Result) Data = Data.reshape(-1, Parameter[1], Parameter[2], 1) Data = Data / 255 Result = to_categorical(Result) return 0, np.array(Data), np.array(Result)
def write_more_wrapper(read_func, table, i, scandir, db): """ higher order functions for all writing, expects a list of several entries for one parameter point """ try: out = read_func(i, scandir) print i except IOError: print "IOError for" + i pass else: for part in out: point = [int(i)] + list(part) Init.register_point(db, table, point)
def read_param(param, spec_file, i, scandir): """ specialized SLHA read functions from scan path naming """ i = str(i) filename = osp.join(scandir, Init.ident_to_path(i), spec_file) return SLHA.getvalues(filename, param)
def Fussabrollen(matrixnew,extractedstep): ACC = Init.getData(matrixnew,sensors=["RLL","LLL"],datas=["acc"],specifiedDatas="x") ACCright = Ableitung(ACC[:,:],[2],1)[:,2:] ACCleft = Ableitung(ACC[:,:],[3],1)[:,2:] anlematrixre1 = winkelgesamt(matrixnew,Sensoren=["RUA","RLA"]) anlematrixre = winkelgesamt(matrixnew,Sensoren=["LUA","LLA"]) anglestickright = anlematrixre1 anglestickleft = anlematrixre plt.plot(anglestickleft) plt.plot(anglestickright) plt.show() rightpeak = [] leftpeak = [] for i in range(0,len(extractedstep)): posleft = (np.argmax(ACCleft[(extractedstep[i,0]):(extractedstep[i,1]),0])) leftpeak.append(anglestickleft[(extractedstep[i,0])+posleft]) posright = (np.argmax(ACCright[(extractedstep[i,0]):(extractedstep[i,1]),0])) rightpeak.append(anglestickright[(extractedstep[i,0])+posright]) print rightpeak return rightpeak,leftpeak
def aufrechtgehen(matrixnew, extractedstep): back = Init.getData(matrixnew,sensors=["STE","CEN"],datas=[ "rE1"]) Vektor = np.zeros((len(back),3)) Vektor[:,0] = 1 angleSTEmovement = angle(back[:,2:5],Vektor) angleCENmovement = angle(back[:,5:8],Vektor) Vektor[:,0] = 0 Vektor[:,2] = 1 angleSTEupwards = angle(back[:,2:5],Vektor) angleCENupwards = angle(back[:,5:8],Vektor) angleSTEupwardsstep = [] angleSTEmovementstep =[] angleSTEmovementstep = [] angleCENupwardsstep = [] for i in range(0,len(extractedstep)): angleCENupwardsstep.append(np.sum(angleCENupwards[(extractedstep[i,0]):(extractedstep[i,1])])/((extractedstep[i,1])-(extractedstep[i,0]))) angleSTEupwardsstep.append(np.sum(angleSTEupwards[(extractedstep[i,0]):(extractedstep[i,1])])/((extractedstep[i,1])-(extractedstep[i,0]))) plt.subplot(2,1,1) plt.plot(angleSTEupwardsstep) plt.subplot(2,1,2) plt.plot(angleCENupwardsstep) plt.show() difference = (np.absolute([x-y for x,y in zip(angleCENupwardsstep,angleSTEupwardsstep)])) return angleSTEupwardsstep,angleCENupwardsstep, difference
def read_HS(i, scandir): """ produces needed hs output """ out = readfile( osp.join(scandir, Init.ident_to_path(i), "HiggsSignals_results.dat")) return out[-1][-7:]
def run_base(running_func, scanpath, db, parallel=True, method=None, ncores=20): runfunc = run_on_dir(scanpath, db=db) if not method: method = Init.get_allpointids(db, "points") if type(running_func) in (tuple, list): for func in running_func: try: runfunc(func, method=method, parallel=parallel, ncores=ncores) except Exception as err: #print "trouble with "+ func.__name__ + " for "+ db print err pass else: try: runfunc(running_func, method=method, parallel=parallel, ncores=ncores) except Exception as err: #print "trouble with "+ running_func.__name__+ " for "+ db print err pass
def sensorwinkel(matrixnew, extractedstep, Sensoren= ["RUA","RLA"]): re1 = Init.getData(matrixnew,sensors=Sensoren,datas=[ "rE1","rE2","rE3"]) anlematrixre1 = angle(re1[:,11:14],re1[:,2:5]) anglearm = anlematrixre1[:,0] anlematrixre1 = angle(re1[:,14:17],re1[:,5:8]) anglearm2 = anlematrixre1[:,0] anlematrixre1 = angle(re1[:,17:20],re1[:,8:11]) anglearm3 = anlematrixre1[:,0] anglecomb= [ ] for i in range(0,len(anglearm)): anglecomb.append(np.sqrt((np.square(anglearm2[i,0]))+(np.square(anglearm[i,0]))+(np.square(anglearm3[i,0])))) print anglecomb maxanglearm = [] minanglearm = [] for i in range(0,len(extractedstep)): maxpos = (np.argmax(anglecomb[(extractedstep[i,0]):(extractedstep[i,1])])) maxanglearm.append((anglecomb[(extractedstep[i,0])+maxpos])) minpos= (np.argmin(anglecomb[(extractedstep[i,0]):(extractedstep[i,1])])) minanglearm.append(anglecomb[(extractedstep[i,0])+minpos]) angleE = np.c_[minanglearm,maxanglearm] print "---------------------------------------------------------------------" angleE= 180-angleE return angleE
def MainFunction(): #CRIEA Start! if os.path.exists("Output/"): if Init.SystemJudge() == 0: os.system("rm -r Output") else: os.system("rmdir /s /q directory") NameArr = Pretreatment.FigureInput(1) try: if NameArr == -1: return except: pass #Figure traversal for kase in range(0, len(NameArr)): img = np.array(Image.open(NameArr[kase]).convert("L")) img = Pretreatment.BFSmooth(img) [Tobimg, NodeInfo] = Algorithm.Toboggan(img) [Upground, Background] = Algorithm.HandSeed(Tobimg, img, Surround) Seeds = Upground | Background ProbBlock = [] VarL = 0 if Method == "Lap": NodeInfo, VarL = Functions.SeedFirst(NodeInfo, Seeds) LapEqu = Algorithm.Laplacian(NodeInfo, VarL) ProbBlock = Functions.LinearEquation(LapEqu, len(NodeInfo) - VarL, VarL) """
def read_HB(i, scandir): """ produces need hb output """ out = readfile( osp.join(scandir, Init.ident_to_path(i), "HiggsBounds_results.dat")) return out[-1][-4:-1]
def FouriorTrans(): if os.path.exists("Output/"): if Init.SystemJudge() == 0: os.system("rm -r Output") else: os.system("rmdir /s /q directory") NameArr = Pretreatment.FigureInput(1) try: if NameArr == -1: return except: pass #Figure traversal for kase in range(0, len(NameArr)): img = np.array(Image.open(NameArr[kase]).convert("L")) Statistic = [0 for n in range(0, 260)] TTL = 0 for i in range(0, len(img)): for j in range(0, len(img[i])): Statistic[img[i][j]] += 1 TTL += 1 #Drecrete PDE Prob = [0.00 for n in range(260)] for i in range(0, len(Prob)): Prob[i] = Statistic[i] / TTL #HF = np.fft.fft(Prob).real fig1 = plt.figure() ax = fig1.add_subplot(111) plt.xlim(-1, 260) plt.ylim(0, 0.2) #Printing loop for i in range(0, len(Prob)): ax.add_patch(patches.Rectangle((i, 0), 1, Prob[i], color = 'black')) Name = "" Hajimari = False for i in range(len(NameArr[kase]) - 1, -1, -1): if NameArr[kase][i] == ".": Hajimari = True continue elif NameArr[kase][i] == "/": break else: if Hajimari == False: continue else: Name = NameArr[kase][i] + Name Name += "_Histogram.png" print(Name) plt.savefig(Name) return
def control_movement(animation): np.set_printoptions(suppress=True) config_file_path = r'grid.config.tcl' mobile_file_path = r'tiexi.tcl' node_num, sim_time = get_sim_parameter(config_file_path) movement_matrix, init_position_matrix = get_position(mobile_file_path) init_position_arranged = init_position_matrix[np.lexsort( init_position_matrix[:, ::-1].T)] node_position = init_position_arranged[0] node_position = np.insert(node_position, 0, values=np.zeros(node_num), axis=1) node_position = np.column_stack((node_position, node_position[:, 2:4])) node_position = np.insert(node_position, 6, values=np.zeros(node_num), axis=1) plt.ion() nodelist = [] com_nodelist = [] controller = Init.init_controller(node_num) for i in range(0, sim_time + 1): update_node_position(movement_matrix, node_position, i, 0.1, animation, nodelist, com_nodelist, controller)
def Initialize(pScene): # Init the scene global g_Engine g_Engine = Init.InitScene(pScene) # Start the engine g_Engine.StartStop(True)
def GetAve(): import GetTRNG import os import Init FileName = "RandomNumberList" if not os.path.exists(FileName): GetTRNG.MainFunction(1000) GetAve() return File = open(FileName, "r") FileLine = File.readline() if len(FileLine) <= 10: GetTRNG.MainFunction(1000) GetAve() return Str1 = "" Str2 = "" for i in range(0, len(FileLine)): if i < 8: Str1 += FileLine[i] else: Str2 += FileLine[i] File.close() os.remove(FileName) File = open(FileName, "a") File.write(Str2) File.close() Init.LogWrite("PRNG Initialization succeed", "0") Seed = 0 try: Seed = int(Str1) except ValueError: Init.LogWrite("Saving TRNG error", "1") return RandNum = [] for i in range(0, 1000): Seed = MT19937(Seed).extract_number() RandNum.append(Seed) return RandNum
def main(): parameter = interval_para[0] y_min = 999999999 y_max = -999999999 para_list = [parameter] list_rem = 0 fx_list = [[]] while 1: print(parameter, interval_para[1], end="\r") #x = [random.random(), random.random()] x = [0.1, 0.1] fx = f(x, parameter) #print("0 " + str(fx)) for i in range(0, total_iteration_time): #plt.plot([x, fx], [fx, fx], color[kase]) x = fx fx = f(x, parameter) if i > record_time: if not Block_min_max: if y_min > fx[memory_dimension]: y_min = fx[memory_dimension] if y_max < fx[memory_dimension]: y_max = fx[memory_dimension] fx_list[list_rem].append(fx[memory_dimension]) parameter += distance_para if parameter > interval_para[1]: break para_list.append(parameter) fx_list.append([]) list_rem += 1 #Init.ArrOutput(fx_list, Mode = 0) print() #print(y_max, y_min) #print(para_list, int((y_max - y_min) / distance_y) + 1) if Block_min_max: y_min = min_max_boundary[0] y_max = min_max_boundary[1] img = [[255 for n in range(len(para_list))] for n in range(int((y_max - y_min) / distance_y) + 1)] print(len(para_list), len(fx_list)) for i in range(0, len(para_list) - 2): #print(i, len(para_list), end = "\r") for j in range(0, len(fx_list[i]) - 1): #print(j, end = "\r") if fx_list[i][j] > y_max or fx_list[i][j] < y_min: continue loc_y = int((y_max - fx_list[i][j]) / distance_y) loc_x = i img[loc_y][loc_x] = 0 #print() img = np.float32(img) #print() Init.ImageIO(file_dir="./img.png", img=np.float32(img), io="o", mode="grey", backend="opencv")
def write_wrapper(read_func, table, i, scandir, db): """ higher order functions for all writing """ try: out = read_func(i, scandir) # point = [i]+readHB(i,scandir)+readHS(i,scandir) print i except IOError: pass else: try: point = [int(i)] + out Init.register_point(db, table, point) except: pass
def findsync(dataMatrix): datamatrix = Init.getData(dataMatrix,sensors=["STE"],datas=[ "acc"]) signal= dataMatrix[:,2] maxAbsValue, maxAbsFreq = FourierTransformation.maxAbsFreq(signal) Filtered = FeatureKonstruktion.filter(datamatrix,[2,3,4],maxAbsFreq) plt.plot(Filtered[:,2:]) plt.show()
def winkelgesamt(matrixnew,Sensoren= ["RUA","RLA"]): re1 = Init.getData(matrixnew,sensors=Sensoren,datas=[ "rE1","rE2","rE3"]) print len(matrixnew) anlematrixre1 = angle(re1[:,11:14],re1[:,2:5]) anglearm = anlematrixre1[:,0] anlematrixre1 = angle(re1[:,14:17],re1[:,5:8]) anglearm2 = anlematrixre1[:,0] anlematrixre1 = angle(re1[:,17:20],re1[:,8:11]) anglearm3 = anlematrixre1[:,0] anglecomb= [ ] plt.plot(anglearm) plt.plot(anglearm2) plt.plot(anglearm3) plt.show() for i in range(0,len(anglearm)): anglecomb.append(np.sqrt((np.square(anglearm2[i,0]))+(np.square(anglearm[i,0]))+(np.square(anglearm3[i,0])))) print len(anglecomb) return anglecomb
import Init import Display import Action if __name__ == '__main__': # PYGAME INIT pygame.init() Game.screen = pygame.display.set_mode((Const.windowHeight, Const.windowLength)) Game.screen.fill(Colour.darkGrey) pygame.display.set_caption('SupNetwork') clock = pygame.time.Clock() # DISPLAY Init.array() Display.all_cell() # GAME LOOP while True: for event in pygame.event.get(): clock.tick(30) if event.type == MOUSEBUTTONUP: x, y = event.pos if Const.margin < x < Const.margin+Const.cellSize*Const.gameSize \ and Const.margin < y < Const.margin+Const.cellSize*Const.gameSize: Action.click(x, y) if event.type == QUIT: pygame.quit()
''' Created on 2011-7-14 @author: zheng ''' import Constant, Init, P4, Build, Sign, Upload, Email, Check import sys if __name__ == '__main__': Init.system_init() project=Init.init_choice(len(sys.argv)) project.project_init() P4.download( project ) P4.getDescribe (project , "1") # Check.check( project ) # Build.build( project ) # Sign.sign( project) # Upload.upload( project )
def __init__(self): Init._Init()
def __del__(self): Init._Shutdown()
# # Copyright (C) 2004 Daniel Larsson # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # import Init # Add the languages we support Init.add_translation('remus-server', 'sv', 'Swedish', 'sv_SE.ISO8859-1', '/images/sv.png') Init.add_translation('remus-server', 'en', 'English', 'en_US.ISO8859-1', '/images/en.png')
Log.log("Game over, displaying game state") matrix = [ [(x, y) in board.blocks for x in xrange(board.blocks_width)] for y in xrange(board.blocks_height) ] Matrix.put(matrix, f="_") if ((len(self.highscores) < HIGHSCORES or any(board.score > score["score"] for score in self.highscores)) and not Shared.options.get("uber_tetromino") and not Shared.options.get("flip_tetromino") ): self.addJob("name_inputbox", Jobs.InputBox(self, "New Highscore!\nName: ")) self.running = self.getName else: self.addJob("window-game_over", Jobs.Notification(self, "window-game_over", "Game Over")) self.addJob("endtimer", Jobs.TimedExecution(self, self.quitGame, seconds=3, anykey=True)) def eventHandler(self, event): if event.type == QUIT: self.quit() elif event.type == KEYDOWN: if event.key == Shared.keymap["game"]["pause"]: self.call(Menus.PauseMenu, sound_enabled=False, caption="Tetris - Paused") if event.key == Shared.keymap["game"]["player1"]["uber_tetromino"] and Shared.options["gameplay"].get("uber_tetromino"): self.jobs.interface.addJob("tetromino", makeUberTetromino(self.jobs.interface.jobs.board)) if __name__ == '__main__': import Init Init.initGame(TetrisGame, caption="Loltris").run()
doc = """ Usage: loltris [--loglevel=n] [--dev] loltris (-h | --help | --version | -v) Options: loltris --help,-h Loltris documentation loltris --version,-v Print the loltris version and exit loltris --loglevel=n Set loglevel, 0="ONLY CRITICAL" 5="ALL" """ import sys import docopt from Globals import * nice_version = "Loltris v{}".format(VERSION) args = docopt.docopt(doc, version=nice_version) ## Launch the game if args["-h"] or args["--help"]: print(doc) sys.exit() if args["-v"]: print(nice_version) sys.exit() import Menus import Init Init.initGame(Menus.MainMenu, caption="Loltris").run()
# # Copyright (C) 2004 Daniel Larsson # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # import Init # Add the languages we support Init.add_translation('remus-audiostore', 'sv', 'Svenska', 'sv_SE.ISO8859-1', '/images/sv.png') Init.add_translation('remus-audiostore', 'en', 'English', 'en_US.ISO8859-1', '/images/en.png')