def compileString(src, dstfn=None, target='mips'): """Compiles string src; if dstfn is provided, the code is written to that file, otherwise printed on the screen""" global CG, html # used for init, genRec, genArray, progStart, genGlobalVars, \ # progEntry, progExit, procStart, genFormalParams, genActualPara, \ # genLocalVars, genProcEntry, genProcExit, genSelect, genIndex, \ # genVar, genConst, genUnaryOp, genBinaryOp, genRelation, genSeq, \ # genAssign, genCall, genRead, genWrite, genWriteln, genCond, \ # genIfThen, genThen, genIfElse, genTarget, genWhile if target == 'mips': import CGmips as CG elif target == 'ast': import CGast as CG elif target == 'pretty': import CGpretty as CG else: print('unknown target') return SC.init(src) ST.init() CG.init() p = program() if p != None and not SC.error: if dstfn == None: print(p) else: with open(dstfn, 'w') as f: f.write(p) # html starting and ending tags html = '<!DOCTYPE html><html><head><title>' + dstfn + '</title>' + css + '</head><body>' + html + '</body></html>' with open(dstfn + '.html', 'w') as f: f.write(html)
def calibrationObservation(shortList, t0, pitch, roll): # this function runs ST.py with the values from three stars from the "short List" # we still need data from the almanac but there's defintiely a way to leverage the astrometry data # t0[2] = t0[2] + 4 #lets worry about correcting the shorterList = [] for x in range(0, len(shortList)): for name in shortList[x]["names"]: # print shortList[x]['names'][name] print name starName = name if starName == "14Aql": shortList[x]["sha"] = [74, 16.375] shortList[x]["dec"] = [-3, 41.9393] shorterList.append(shortList[x]) elif starName == "15Aql": shortList[x]["sha"] = [73, 26.2652] shortList[x]["dec"] = [-4, 52.95334] shorterList.append(shortList[x]) elif starName == u"\u03bb Aql": shortList[x]["sha"] = [73.0, 26.26254] shortList[x]["dec"] = [-4, 52.95335] shorterList.append(shortList[x]) elif starName == "Vega": shortList[x]["sha"] = [80, 47.02134] shortList[x]["dec"] = [38, 47.1234] shorterList.append(shortList[x]) elif starName == "Sheliak": shortList[x]["sha"] = [77, 28.8012] shortList[x]["dec"] = [33, 21.7601] shorterList.append(shortList[x]) elif starName == "Sulafat": shortList[x]["sha"] = [75, 15.8444] shortList[x]["dec"] = [32, 41.3734] shorterList.append(shortList[x]) else: pass print "actually used observations are ===== %s" % shorterList observations = [] for x in shorterList: # have to define the gha as constants for now # gha0 = [17,17.8] # gha1 = [32, 20.3] gha0 = [32, 20.3] gha1 = [47, 33.7] Ho = x["ho"] sha = x["sha"] dec = x["dec"] observations.append(ST.Observation(t0, Ho, sha, gha0, gha1, dec, pitch)) f.write( "%s,%s,%s,%s,%s,%s,%s,%s,%s\n" % (x["ho"], x["newx"], x["newy"], x["pixelx"], x["pixely"], x["xOff"], x["yOff"], pitch, roll) ) print "OBSERVATIONS ====== %s" % observations ST.runLocateMeALot(observations)
def compileString(src, dstfn = None): """Compiles string src; if dstfn is provided, the code is written to that file, otherwise printed on the screen""" SC.init(src) ST.init() CG.init() p = program() if dstfn == None: print(p) else: with open(dstfn, 'w') as f: f.write(p);
def compileString(src, dstfn = None, target = 'wat'): global CG if target == 'wat': import CGwat as CG elif target == 'mips': import CGmips as CG elif target == 'ast': import CGast as CG else: print('unknown target'); return try: SC.init(src); ST.init(); p = program() if dstfn == None: print(p) else: with open(dstfn, 'w') as f: f.write(p) except Exception as msg: raise Exception(str(msg)) print(msg)
def compileString(src, dstfn=None, target='mips'): global CG if target == 'mips': import CGmips as CG elif target == 'ast': import CGast as CG else: print('unknown target') return SC.init(src) ST.init() p = program() if p != None and not SC.error: if dstfn == None: print(p) else: with open(dstfn, 'w') as f: f.write(p)
def computeHoFromImage(starList): # the leading theory is that this approximation will only work when the stars are closeby # that is, the small angle approximation works pixScale = 24.1 # 5 # arcsec/pixel pixDegrees = pixScale / 3600 K = 3600 / 24.2 imageWidth = 3872 # pix imageHeight = 2592 # pix xc = imageWidth / 2 yc = imageHeight / 2 naturalBias = -4.9399 # -11.0701857994#-5.25 #calc from lyra_oct9 basic optimum # naturalBias =-4.7598 #this is teh TRUE # naturalBias =-3.3920 # naturalBias = -4.9749 # naturalBias = -5.2764 # PITCH CALIBRATION SUPER IMPORTANT pitch = 62.62 # 39.76#62.62 #deg # i'll need to get the correct roll value from the IMU roll = -0.54 # 1.9 #-0.32-1.9056-3.19+4444#-0.5 # -2.4#-0.54 rollOffset = -4.7598 # basic optimal point # rollOffset = 0.4523 #this one is the TRUE # rollOffset = 10.4774 # rollOffset = -5.2764 # strip 'annotations' # starList = starList['annotations'] shortList = [] # make a short list of the stars we're really interested in for star in starList: # if the star has an alternate name its probably big or bright or both # if len(star['names'])>1: # pixel offsets star["newx"] = star["pixelx"] * ST.cosd(roll + rollOffset) + star["pixely"] * ST.sind(roll + rollOffset) star["newy"] = -star["pixelx"] * ST.sind(roll + rollOffset) + star["pixely"] * ST.cosd(roll + rollOffset) star["xOff"] = star["pixelx"] - xc star["yOff"] = yc - star["pixely"] # rotation will go here # compute offset from roll angle # i think the order we do the roll and pitch operations is kind of important # star['ho'] = pitch + star['yOff']*pixDegrees + naturalBias # i feel like its plus and the matlab is actually whats wrong star["ho"] = -pixDegrees * star["xOff"] * ST.sind(roll + rollOffset) + ( pixDegrees * star["yOff"] + (pitch + naturalBias) ) * ST.cosd(roll + rollOffset) # shortList.append(star) print star # print "\n\n\n shortList \n\n\n" %shortList return [starList, pitch, roll]
def lawOfCosines(sideA, sideB, sideC): # solves for the ANGLE given the three side lengths # this corresponds to the pixel lengths that we're already getting # from teh star camera # first compute the thing going into acos arg = sideA**2 + sideB**2 - sideC**2 arg = arg/(2*sideA*sideB) angle = ST.acosd(arg) return angle
def compileString(src, dstfn=None, suppress_errors=False): """Compiles string src; if dstfn is provided, the code is written to that file, otherwise printed on the screen. Returns the latest error message, if any""" SC.init(src, suppress_errors) ST.init() CG.init() try: p = program() #compounding errors can cause compiler to crash. exit when we can't continue except Exception as e: #errors = SC.getErrors() #print('COMPILER ERROR', e) pass errors = SC.getErrors() if not errors: if dstfn == None: print(p) else: with open(dstfn, 'w') as f: f.write(p) return errors
def __init__(self, k, s, graphclassobject = None): self.k = k self.s = s self.PG = graphclassobject self.Hext = [] self.Htopk = [] heapq._heapify_max(self.Hext) heapq.heapify(self.Htopk) self.St2 = ST.Search_Tree(self.PG.G.nodes) self.t = 0 self.prmc = 0.0 self.prune_basic = 0 self.prune_size_based = 0 self.prune3_antimonoton = 0 self.prune_lookahead = 0 self.prune_basic_c = 0 self.prune_size_based_c = 0 self.prune3_antimonoton_c = 0 self.prune_lookahead_c = 0 self.gench_ph1 = 0 self.gench_ph2 = 0 self.uptopk_ph1 = 0 self.add_ch_ph1 = 0
def __init__(self, filename): self.st = ST.ST() # 由符号名找到索引 self.keys = [] # 由索引找到符号名 self.file = open(filename) for i in self.file.readlines(): # 第一遍扫描通过读入字符串来构造索引 a = i.split(' ') for j in range(len(a)): if not self.st.contains(a[j]): self.st.put(a[j], self.st.size()) print "Done Reading " + filename self.keys = [0] * self.st.size() for stringName in self.st.keys(): #把所有的keys放到 self.keys[self.st.get(stringName)] = stringName self.G = graph.Graph(self.st.size()) #第二次扫描 self.file1 = open(filename) for i in self.file1.readlines(): a = i.split(' ') v = self.st.get(a[0]) for i in range(len(a)): w = self.st.get(a[i]) self.G.addEdge(v, w)
def calcD(Li, Bi, Lf, Bf): d = 60*m.sqrt((Li-Lf)**2*ST.cosd(Bf) + (Bi - Bf)**2) return d
import ST t = [0,53,13] ghaZero = [16,18.7] ghaOne = [31, 21.1] meanBias = 5.356 # total amount of diff. i need to get out of my system accounted = 2.7 # stuff i've actually been able to account for so far dt = -2 alshain = ST.Observation([0,53, 13+dt], 54.6176 - meanBias,[61, 10.299], ghaZero, ghaOne, [6,24.4]) altair2 = ST.Observation([0,53,13+dt], 56.3854 - meanBias, [62, 18.2504], ghaZero, ghaOne, [8,52.0993]) tarazed = ST.Observation([0,53,13+dt],57.4902 - meanBias, [63, 26.1049], ghaZero, ghaOne, [10, 36.7657]) obs = [alshain, altair2, tarazed] ST.runLocateMeALot(obs)
import numpy as np import torch import ST J = 8 L = 4 M = 512 N = 512 filter_set = ST.FiltersSet(M, N, J, L) # generate and save morlet filter bank. "single" means single precision save_dir = '#####' filter_set.generate_morlet(if_save=True, save_dir=save_dir, precision='single') # load filter bank filters_set = np.load( save_dir + 'filters_set_M' + str(M) + 'N' + str(N) + 'J' + str(J) + 'L' + str(L) + '_single.npy', allow_pickle=True )[0]['filters_set'] # define ST calculator ST_calculator = ST.ST_2D(filters_set, J, L, device='gpu') ############ DEFINE DATA ARRAY ######### data = np.empty((30, M, N), dtype=np.float32) ################## ST ################## # input data should be a numpy array of images with dimensions (N_image, M, N) # output are torch tensors with assigned computing device, e.g., cuda() or cpu
# testing the nautical almanac values import ST as ST p = [0.0231, 0.3058, -0.4001] Z = [267.2721, 151.6809, 358.9823] ans = [] [ans.append(p[i]*ST.sind(Z[i])) for i in range(0, len(p))] ans = sum(ans) print ans
try: fp = open(name, "r") except: print('Error on opening file\n') quit() content = fp.readlines() for line in content: strlist = line.split() g.insVertex(strlist[0], strlist[1], st) #main: st = ST.ST() name = 'file.txt' read_file(name, st) g = GRAPH.GRAPH(st.getDimention()) loadGraph(name, st, g) timePass = [] for i in range(g.getVertexNum()): timePass.append(0) timeEnd = [] for i in range(g.getVertexNum()): timeEnd.append(0)
mu=result[0] sigmav=result[1] p=MG.multivariateGaussian(X,mu,sigmav) VF.visualizeFit(X,mu,sigmav) plt.xlabel('Latency (ms)') plt.ylabel('Throughput (mb/s)') plt.title('The Gaussian distribution contours of the distribution fit to the dataset.') plt.axis(xmin=0,xmax=30,ymin=0,ymax=30) #plt.show() #Part Three: Find Outliers print 'Three: ============ Find Outliers...' Xval=data['Xval'] yval=data['yval'] pval=MG.multivariateGaussian(Xval,mu,sigmav) res=ST.selectThreshold(yval,pval) epsilon=res[0] F1=res[1] print 'Best epsilon found using cross-validataion: %8.2e' % epsilon print 'Best F1 on Cross Validation Set: %5.3f ' % F1 print '(you should see a value epsilon of about 8.99e-05)' outliners=np.where(p < epsilon) plt.plot(X[outliners,0],X[outliners,1],'ro',linewidth=2,markersize=10) plt.show() #Part Four: Multidimensional Outliers print 'Four: =========== Multidimensional Outliers...' data=sio.loadmat('ex8data2') X=data['X'] Xval=data['Xval']
def run(): while (1): try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: #Set up socket s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #Make sure socket can reuse the address s.bind((HOST, PORT)) #Bind the address and port to this socket print("Listening at " + HOST + ":" + str(PORT)) s.listen(1) global conn global SPT global HRTools global TTP global STProc global CTProc global COProc global HRSTProc conn, addr = s.accept() #Accept an incoming client connection with conn: print("Connected by:", addr) while (1): lock = Lock() data = (conn.recv(1024)).decode() print(data) if not data: break if ( data == "START0" ): #If the start signal from the client is recieved for default tools SPT = SP_TOOLS() sendToHost("DONE", lock) strt = 1 if (data == "START1"): HRTools = ST() sendToHost("DONE", lock) strt = 2 if (strt == 1): print(data) if ( data[:2] == "PC" ): #If the first two characters are PC, then start the pulse counter if ( isinstance(COProc, Process) ): #If the process already exists, kill it to prevent multiple processes forming COProc.terminate() print("starting counter") mode = int(data[2]) window = float(data[3:]) COProc = Process(target=counter, args=( window, mode, lock, )) #Pulse counter process COProc.start() if ( data == "ST" ): #If the client has activated the single channel inter rising edge timer if (isinstance(STProc, Process)): STProc.terminate() STProc = Process(target=ST_MOD, args=(lock, )) STProc.start() if (data[:2] == "CT"): #Coincidence timer if (isinstance(CTProc, Process)): CTProc.terminate() mode = data[2] CTProc = Process(target=CT_MOD, args=( lock, mode, )) CTProc.start() if (data[:2] == "PG"): #Signal generator PG_MOD( json.loads(data[2:]) ) #Deserialize the incoming data and call the pulse generator function if (data[:2] == "TT"): #Time tagger if ( data[2] == "0" ): #If the first argument is zero, then stop the time tagger and kill its child process if (isinstance(TTP, Process)): print("Stopping time tagger") SPT.TT_reset() TTP.terminate() else: if ( isinstance(TTP, Process) ): #If the child process already exists then kill it and start it again TTP.terminate() time = float(data[3:]) TTP = Process(target=TT_MOD, args=(time, lock)) TTP.start() if (data[:3] == "iDD"): #Input delay configuration vals = json.loads( data[3:] ) #Deserialize the incoming delay configuration DD_IDELAY( vals[0], vals[1], vals[2] ) #And pass it to the delay configuration function if (data == "XX"): if ( not (COProc is None) ): # If the process already exists, kill it to prevent multiple processes forming COProc.terminate() if (not (CTProc is None)): CTProc.terminate() if (not (STProc is None)): STProc.terminate() if ( not (TTP is None) ): # If the child process already exists then kill it and start it again TTP.terminate() strt = 0 if (strt == 2): if (data == "ST" ): # High resolution inter rising edge timer if (isinstance(HRSTProc, Process)): HRSTProc.terminate() HRSTProc = Process(target=HRST_start, args=(lock, )) HRSTProc.start() if (data[:2] == "DD"): dels = json.loads(data[2:]) HRST_change_delay(dels) if (data[:2] == "STOP"): if (not (HRSTProc is None)): HRSTProc.terminate() if (data == "XX"): if (not (HRSTProc is None)): HRSTProc.terminate() strt = 0 except Exception as e: print("Something happened " + str(e))
def __init__(self, d): self.d = d self.st1 = ST.ST()
def count_words_tree(sequences, l, searchLocation, strand='+-', overlap=False, error=0, spacing=(1, 1)): """Count each word of length l in sequences l -- oligonucleotide length searchLocation -- location tuple example (-200,-1) strand -- + or +- overlap -- allow auto-overlapping return N, H """ location = find_location(sequences) #H = {} #hash table key=oligonucleotide value=list of occurrence position N = {} #scanned base count per position fo each word size N[l] = [0] * (searchLocation[1] - searchLocation[0] + 1) scannedPositions = 0 scannedWords = 0 info = cli.Info(len(sequences), 1, 1) # # construct SuffixTree # st = ST.SuffixTree(maxDepth=l, overlapping=overlap, maxIUPAC=error, NExtension=spacing, storePosition=True) for s in sequences: info('Counting words in [%+05d:%+05d]' % (searchLocation[0], searchLocation[1])) a, b = max(searchLocation[0], s.location[0]), min(searchLocation[1], s.location[1] - l + 1) dna = s.get_dna((a, b + l + 1)) st.add_dna(dna, shift=a) for I in range(a, b + 1): i = I - s.location[0] w = dna[i:i + l] if w.find('N') >= 0: continue N[l][I - searchLocation[0]] += 1 #@DEBUG #ST.display(st.root, maxDepth=6, full=1) # # Count # #@DEBUG #keys = st.extract(minLength=l, maxLength=l).keys() #keys.sort() #print '\n'.join(keys) C = st.extract(minLength=l, maxLength=l) if strand == '+-': H = ST.get_positions_two_strands(C, overlap) else: H = ST.get_positions(C) return dict(N=N, H=H, scannedPositions=scannedPositions, scannedWords=scannedWords)