def move(self, velocity, world, alreadyMoving, game): self.moving = True; if not alreadyMoving : self.movingTick = 0; self.oldX = self.posX; self.oldY = self.posY; self.newX = self.oldX + (self.velocity[0] * 16); self.newY = self.oldY + (self.velocity[1] * 16); tile = world.tileAt(self.newX, self.newY+6); if tile is not None and tile.occupied == True: self.posX = self.oldX; self.posY = self.oldY; self.moving = False; else : if tile is not None : tile.onSteppedOn(self, game); else : if self.movingTick > 8 : self.movingTick = 0; self.moving = False; if self.keepMoving : self.move(self.velocity, world, False); else : self.posX = MathUtils.lerp(self.oldX, self.newX, self.movingTick/8); self.posY = MathUtils.lerp(self.oldY, self.newY, self.movingTick/8); self.movingTick += 1;
def runCurrentAnimation(self, font, game) : if self.currentAnimation == "trainer_in" : if self.animationTimer <= 80 : self.player_image.image.set_alpha(MathUtils.lerp(0, 255, self.animationTimer / 80)); self.player_image.rect.x = MathUtils.lerp(-120, 240, self.animationTimer / 80); self.opponent_image.image.set_alpha(MathUtils.lerp(0, 255, self.animationTimer/80)); self.opponent_image.rect.x = MathUtils.lerp(880, 440, self.animationTimer/80); else : self.animationActive = False; self.animationTimer = 0; self.currentAnimation = "none"; elif self.currentAnimation == "opponent_exit" : if self.animationTimer <= 40 : self.opponent_image.image.set_alpha(MathUtils.lerp(255, 0, self.animationTimer/40)); if self.animationTimer == 41 : self.opponent_pokemon = self.opponnent.getPokemon(0); if self.animationTimer > 41 : self.animationActive = False; self.animationTimer = 0; self.currentAnimation = "None"; self.stepDone = True; elif self.currentAnimation == "player_exit" : if self.animationTimer <= 40 : self.player_image.image.set_alpha(MathUtils.lerp(255, 0, self.animationTimer/40)); if self.animationTimer == 41 : self.player_pokemon = self.player.getFirstPokemonAlive(); if self.animationTimer > 41 : self.animationActive = False; self.animationTimer = 0; self.currentAnimation = "None"; self.stepDone = True; self.updateStatus("opponent", self.opponent_pokemon, True, font); self.updateStatus("player", self.player_pokemon, True, font); elif self.currentAnimation == "player_attack" : if self.animationTimer <= 10 : self.player_pokemon_x = MathUtils.lerp(232, 280, self.animationTimer/10); elif self.animationTimer > 10 and self.animationTimer <= 20 : self.player_pokemon_x = MathUtils.lerp(280, 232, (self.animationTimer-10)/10) elif self.animationTimer == 21 : self.animationActive = False; self.animationTimer = 0; self.currentAnimation = "None"; self.stepDone = True; self.selectStep = False; self.attackStep = False; self.buttons = ["Attaque", "Inventaire", "Equipe", "Fuir"]; #self.nextStep(game, font); elif self.currentAnimation == "opponent_attack" : if self.animationTimer <= 10 : self.opponent_pokemon_x = MathUtils.lerp(440, 398, self.animationTimer/10); elif self.animationTimer > 10 and self.animationTimer <= 20 : self.opponent_pokemon_x = MathUtils.lerp(398, 440, (self.animationTimer-10)/10) elif self.animationTimer == 21 : self.animationActive = False; self.animationTimer = 0; self.currentAnimation = "None"; self.selectStep = False; self.attackStep = False; self.stepDone = True;
def has_property(l): x = pt[l[-1]] dx = get_digit(x) for j in range(0, len(l) - 1): xx = pt[l[j]] dxx = get_digit(xx) a = x + xx * pow(10, dx) b = xx + x * pow(10, dxx) if not mu.isPrimeAug(a, ppt) or not mu.isPrimeAug(b, ppt): return False return True
def growTree(self, data, columns, treeLevel): if treeLevel > self.maxTreeLevel: predVal = np.nan if self.isCategorical: values, counts = np.unique(data[self.targetCol].values, return_counts=True) frequents = values[counts == counts.max()] if len(frequents) > 1: if self.guessWithTie: predVal = MathUtils.randomChoose(frequents) else: raise ValueError( "BinaryTree::growTree: fail to grow tree because subset is not splittable and subset has multiple targets with highest frequency!" ) else: predVal = values[np.argmax(counts)] else: predVal = data[self.targetCol].mean() return TreeNode('', np.nan, predVal) while len(columns) > 0: col = MathUtils.randomChoose(columns) split_val = self.splitter.split(data) if np.isnan(split_val): columns.remove(col) else: data_l = data.loc[data[col] <= split_val] data_2 = data.loc[data[col] > split_val] left_child = self.growTree(data_l, columns.copy(), treeLevel + 1) right_child = self.growTree(data_2, columns.copy(), treeLevel + 1) return TreeNode(col, split_val, np.nan, left_child, right_child) # nothing left to split, just return a leaf node predVal = np.nan if self.isCategorical: values, counts = np.unique(data[self.targetCol].values, return_counts=True) frequents = values[counts == counts.max()] if len(frequents) > 1: if self.guessWithTie: predVal = MathUtils.randomChoose(frequents) else: raise ValueError( "BinaryTree::growTree: fail to grow tree because subset is not splittable and subset has multiple targets with highest frequency!" ) else: predVal = values[np.argmax(counts)] else: predVal = data[self.targetCol].mean() return TreeNode('', np.nan, predVal)
def update(dt): global counter global center_total global current_coeffs mode = counter % (num_of_coeffs * 2 + 1) #frame_ready = cam.wait_for_frame() #if frame_ready: # img2 = cam.latest_frame()/255 #else: # print('ahh') img2 = cam.grab_image(exposure_time='0.0005 millisecond') / 255 cx, cy = mu.center_cam(img2) total = mu.circular_integral_fast( img2, cx, cy, 10) / mu.circular_integral_fast(img2, cx, cy, 128) #total = mu.circular_integral_fast(img2, cx, cy, 8) #print(total - total2) #slm2.set_array(img2) delta = np.zeros(num_of_coeffs) if mode < num_of_coeffs * 2: delta[int(mode / 2)] = dx * (1 - 2 * (mode % 2)) if mode > 0 and mode % 2 == 1: center_total = total if mode > 0 and mode % 2 == 0: working_coeff = int(mode / 2) - 1 gradient[working_coeff] = (center_total - total) / (2.0 * dx) if mode == num_of_coeffs * 2: current_coeffs = current_coeffs + step * gradient pcoeffs = np.zeros(num_of_coeffs + first_coeff) pcoeffs[first_coeff:(num_of_coeffs + first_coeff)] = current_coeffs + delta slm.set_zernike_coeffs(pcoeffs, [brightness]) if mode == 0: print(pyglet.clock.get_fps()) print(total) print(pcoeffs) im = ax.imshow(img2) plt.pause(0.05) counter = counter + 1
def convert(self, numeral): number = int(numeral) if number < 0 or number > 99: return "NotSupported: Numbers should be Integers between 0 and 99." # raise Exception("Error: Numbers should be Integers between 0 and 99.") outcome_number = "" if MathUtils.MathUtils.is_a_ten(number): outcome_number = self.translator.get_tens( MathUtils.GetQuotientOfDivisionBy10(number)) else: if number < 20: outcome_number = self.translator.get_units(number) else: ten = MathUtils.MathUtils.get_quotient_of_division_by_10( number) remainder = MathUtils.MathUtils.get_remainder_of_division_by_10( number) outcome_number = self.translator.get_tens( ten) + " " + self.translator.get_units(remainder) return outcome_number
def jetcleaning(ak4_pt30_eta4p5_IDT, lep_looseID, ak4eta, lepeta, ak4phi, lepphi, DRCut): ## usage: (obj_to_clean, obj_cleaned_against, so on if debug_: print "njet, nlep", len(ak4_pt30_eta4p5_IDT), len(lep_looseID) jetCleanAgainstLep = [] pass_jet_index_cleaned = [] if len(ak4_pt30_eta4p5_IDT) > 0: for ijet in range(len(ak4_pt30_eta4p5_IDT)): pass_ijet_ilep_ = True if (len(lep_looseID) > 0): for ilep in range(len(lep_looseID)): if (bool(lep_looseID[ilep]) == False): continue pass_ijet_ilep_ = ( ak4_pt30_eta4p5_IDT[ijet] and lep_looseID[ilep] and (mathutil.Delta_R(ak4eta[ijet], lepeta[ilep], ak4phi[ijet], lepphi[ilep]) > DRCut)) if not pass_ijet_ilep_: break if debug_: print "-------- pass_ijet_ilep_ = ", pass_ijet_ilep_ jetCleanAgainstLep.append(pass_ijet_ilep_) if debug_: print "inside function pass_ijet_ilep_ = ", pass_ijet_ilep_ if debug_: print "inside function jetCleanAgainstLep = ", jetCleanAgainstLep return jetCleanAgainstLep
def __init__(self, test: CompSlowDecompTest, cutoff_modulus: float = 0.4): strain_comp = test.strain[test.compression_range] stress_comp = test.stress[test.compression_range] (strain, stress) = signal.savgol_filter((strain_comp, stress_comp), window_length=51, polyorder=3) ders = MathUtils.derivative(strain, stress) plateaud_indices = np.where( np.logical_and(ders < cutoff_modulus, strain_comp[:-1] > 0.05))[0] if plateaud_indices.size > 0: self.start_idx = plateaud_indices[0] self.end_idx = plateaud_indices[-1] self.stress = np.mean(stress[self.start_idx:self.end_idx]) else: # there is no plateau, so we return the point with lowest derivative strain_start_idx = np.where(strain > 0.05)[0][ 0] # assume that there are location beyond that strain min_derivative = np.min(ders[strain_start_idx:-1]) min_der_idx = np.where( ders == min_derivative)[0][0] # assume we can find the minimum self.start_idx = min_der_idx self.end_idx = min_der_idx self.stress = stress_comp[min_der_idx] self.strain_start = strain_comp[self.start_idx] self.strain_end = strain_comp[self.end_idx]
def init_car(size=1200): #先初始化carstates文件夹中的carstate文件 DataOperate.clear_carstates() exist = np.zeros(1426, dtype='int16') id = 0 # cars = [] while id < size: Ls = MathUtils.random_id() if exist[Ls] == 1: continue exist[Ls] = 1 ''' 车辆信息: id:车辆唯一标识 Lc(街道节点编号):当前位置 Pc:当前乘客人数 Ls:出租车的出发地 Ld(街道节点编号):出租车当前目的地 path:当前车辆的路径规划 batch_numbers:车辆上的乘客批数 Battery(单位:kwh):电池剩余电量 is_recharge(0:否,1:是):是否在充电 ''' #def __init__(self, id, Pc, Ls, Ld, batch_numbers, Battery, is_recharge) car = Car(id, 0, Ls, Ls, 0, 60, 0) # cars.append(car) #更新Lc节点的车辆状态表([车辆id,到达该节点的时间,目的地是否为该节点(1:是,0:否)]) DataOperate.append_carstate(Ls, [id, DatetimeUtils.cur_datetime(), 1]) DataOperate.update_car(car) id += 1
def regress(self): guess = self.beta[:-1].copy() beta0 = MathUtils.gradient(self, guess) # above beta0 is the regressed results for normalized X and Y, i.e. (Y-muY) / stdY = ((X-muX)/stdX).dot(beta0) # therefore we have beta[:-1] = beta0 * stdY / stdX, beta[-1] = beta0 * muX * stdY / stdX + muY self.beta[:-1] = beta0 * self.stdY / self.stdX self.beta[-1] = self.muY -(beta0 * self.muX * self.stdY / self.stdX).sum()
def fadeScreenIn(self, fadeTime) : self.fadeIn = True; if self.fadeImage.get_alpha() < 255 : self.fadeTime = fadeTime; self.fadeImage.set_alpha(MathUtils.lerp(0, 255, self.fadeProgress/self.fadeTime)) self.fadeProgress += 1; if self.fadeProgress > self.fadeTime : self.fadeProgress = 0; self.fadeTime = 0;
def fadeScreenOut(self, fadeTime) : self.fadeIn = False; if self.fadeImage.get_alpha() > 0 : self.fadeTime = fadeTime; self.fadeImage.set_alpha(MathUtils.lerp(255, 0, self.fadeProgress/self.fadeTime)) self.fadeProgress += 1; if self.fadeProgress > self.fadeTime : self.fadeTime = 0; self.fadeProgress = 0;
def my_request(): # 0.获取当前系统时间 now = DatetimeUtils.cur_datetime() # 1.随机生成1-55的数,代表多少分钟后执行定时任务 minute = 0.1 # 2.出发时间统一在请求发出的5分钟后 Tp = DatetimeUtils.datetime_add(now, minute + 5) # 3.随机生成需求座位数1-3 Pr = MathUtils.random_pr() # 4.随机生成出发地和目的地 Ls, Ld = MathUtils.random_sour_targ() # 5.生成Request对象 request = Request(Tp, Ls, Pr, Ld) # 6.写入到文件中 DataOperate.update_request(request) # 7.提交定时任务到定时任务服务器 execute_datetime = str(DatetimeUtils.datetime_add(str(Tp), -5)) ApschedulerClient.handle_request_job(request.id, execute_datetime)
def clickImage(win, path, threshold=0.9, imsrc=None): if imsrc is None: imsrc = getWindowCVimg(win) edit = getImage(path) result = aircv.find_template(imsrc, edit, threshold=threshold) if result: print("click", path) position = MathUtils.randomPosition(result['rectangle'], offset=31) saveImage(imsrc, [(position, position, position, position)]) clickPosition(win, position)
def random_request(hour): #0.获取当前系统时间 now = DatetimeUtils.cur_datetime() #1.随机生成1-55的数,代表多少分钟后执行定时任务 minute = MathUtils.random_time() #2.出发时间统一在请求发出的5分钟后 Tp = DatetimeUtils.datetime_add(now, 60 * hour + minute + 5) #3.随机生成需求座位数1-3 Pr = MathUtils.random_pr() #4.随机生成出发地和目的地 Ls, Ld = MathUtils.random_sour_targ() #5.生成Request对象 #def __init__(self, Tp, Ls, Pr, Ld, is_match_successful): request = Request(Tp, Ls, Pr, Ld, 0) #6.写入到文件中 DataOperate.update_request(request) #7.提交定时任务到定时任务服务器 execute_datetime = str(DatetimeUtils.datetime_add(str(Tp), -5)) ApschedulerClient.handle_request_job(request.id, execute_datetime)
def WRecoil_Phi_Wmass(nEle,elept,elephi,elepx_,elepy_,met_,metphi_): dummy=-9999.0 WenuRecoilPt=dummy; WenurecoilPhi=-10.0; We_mass=dummy; if nEle == 1: We_mass = MT(elept[0],met_, DeltaPhi(elephi[0],metphi_)) #transverse mass defined as sqrt{2pT*MET*(1-cos(dphi)} WenuRecoilPx = -( met_*math.cos(metphi_) + elepx_[0]) WenuRecoilPy = -( met_*math.sin(metphi_) + elepy_[0]) WenuRecoilPt = math.sqrt(WenuRecoilPx**2 + WenuRecoilPy**2) WenurecoilPhi = mathutil.ep_arctan(WenuRecoilPx,WenuRecoilPy) return WenuRecoilPt, WenurecoilPhi, We_mass
def plotCompressionDerivativesSmoothing(): for test in tests: strain_comp = test.strain[test.compression_range] stress_comp = test.stress[test.compression_range] (strain_comp, stress_comp) = signal.savgol_filter( (strain_comp, stress_comp), window_length=51, polyorder=3) pyplot.plot(strain_comp[:-1], MathUtils.derivative(strain_comp, stress_comp), color=PlottingUtil.lighten_color(getColor(test), .7), label=getLabel(test))
def ZRecoil_Phi_Zmass(nEle, eleCharge_, elepx_, elepy_, elepz_, elee_,met_,metphi_): dummy=-9999.0 ZeeRecoilPt=dummy; ZeerecoilPhi=-10.0; Zee_mass=dummy if nEle == 2: iele1=0 iele2=1 if eleCharge_[iele1]*eleCharge_[iele2]<0: Zee_mass = InvMass(elepx_[iele1],elepy_[iele1],elepz_[iele1],elee_[iele1],elepx_[iele2],elepy_[iele2],elepz_[iele2],elee_[iele2]) zeeRecoilPx = -( met_*math.cos(metphi_) + elepx_[iele1] + elepx_[iele2]) zeeRecoilPy = -( met_*math.sin(metphi_) + elepy_[iele1] + elepy_[iele2]) ZeeRecoilPt = math.sqrt(zeeRecoilPx**2 + zeeRecoilPy**2) ZeerecoilPhi = mathutil.ep_arctan(zeeRecoilPx,zeeRecoilPy) return ZeeRecoilPt, ZeerecoilPhi, Zee_mass
def TrouverClePrivee(n, c): """ Trouve la clé privée associée à une clé publique param n: n de la clé publique param c: d de la clé publique return: l'entier d de la clé publique """ divider = [d for d in range(2, int(math.sqrt(n))) if n%d == 0] p = divider[0] q = n/p d = int(MathUtils.inverseModulaire(c, (p - 1) * (q - 1))) return d
def random_chargings(size=300): chargings = [] i = 0 chargings_state_donedatetime = [] now = DatetimeUtils.cur_datetime() while i < size: charging = MathUtils.random_id() if chargings.count(charging) == 0: chargings.append(charging) chargings_state_donedatetime.append("'" + now + "'") i += 1 DataOperate.update_chargings(chargings) DataOperate.update_chargings_state(chargings_state_donedatetime)
def gatherStatistics(): for test in tests: strain_comp = test.strain[test.compression_range] stress_comp = test.stress[test.compression_range] strain_decomp = test.strain[test.decompression_range] stress_decomp = test.stress[test.decompression_range] compression_energy = abs( MathUtils.integral(strain_comp, stress_comp)[-1]) decompression_energy = abs( MathUtils.integral(strain_decomp, stress_decomp)[-1]) densities.append(test.limit_density) compression_energies.append(compression_energy) energy_diffs.append(compression_energy - decompression_energy) energy_ratios.append( (compression_energy - decompression_energy) / compression_energy) stress_t = stress_comp[100:] strain_t = strain_comp[100:] - strain_comp[0] min_secant_moduli.append(min(stress_t / strain_t)) max_tangent_moduli.append(TangentModulus.getTangentModulus(test).val) print("Density: " + str(test.limit_density) + ", Modulus: " + str(max_tangent_moduli[-1])) end_tangent_moduli.append( TangentModulus.getEndTangentModulus(test).val)
def charging_datetime(dist, soc, donedatetime): #计算出到达充电站后剩余的电量 soc -= MathUtils.dist_cost(dist) # print('soc = ', soc) #根据距离计算出到达充电站的时间 arrive_datetime = str(DatetimeUtils.datetime_add(DatetimeUtils.cur_datetime(), dist / 1000)) # print('arrive_datetime = ', arrive_datetime) # print('typeof arrive_datetime is', type(arrive_datetime)) #如果充电站完成对当前充电站最后一辆车充电的时间大于到达的时间,那么按完成时间开始算,否则按到达时间算 if donedatetime >= arrive_datetime: cd = str(DatetimeUtils.recharged_datetime(donedatetime, soc)) else: cd = str(DatetimeUtils.recharged_datetime(arrive_datetime, soc)) # print('typeof cd is ', type(cd)) # print('cd = ', cd) return cd
def recharged(carid, dist): print('车辆%s已到达目的地' % carid) #1.获取车辆信息 car = DataOperate.get_car(carid) #2.根据距离推断消耗的电量 cost = MathUtils.dist_cost(dist) #3.修改车辆信息 car.Battery -= cost car.batch_numbers = 0 car.Pc = 0 #4 获取系统当前的时间,格式为:'YYYY-mm-dd HH:MM:SS' str类型 now_datetime = DatetimeUtils.cur_datetime() #5.判断是否需要充电 #5.1需要充电 if car.Battery <= 10: #5.1.1 计算出到哪个充电站充电可以最快完成充电,方法中顺便修改充电站的状态信息,fastest_charging_datetime(str) fastest_charging_datetime, target = MatchingAlgorithm.fastest_charging_datetime( car.Ld, car.Battery) car.Ld = target car.Ls = car.Ld car.is_recharge = 1 # 提交定时任务修改车辆是否在充电的状态 ApschedulerClient.update_car_is_recharge(fastest_charging_datetime, carid) #车辆状态信息 carstate = [carid, fastest_charging_datetime, 1] # 在节点车辆状态表上拼接一行车辆状态信息 DataOperate.append_carstate(car.Ld, carstate) #不需要充电 else: car.Ls = car.Ld car.is_recharge = 0 # 车辆状态信息 # carstate = [carid, now_datetime, 1] #6.修改车辆信息 DataOperate.update_car(car)
def automatic_phase(cam, slm, start=0, end=0.5, num_of_samples=32, depth=0): max_depth = 2 if depth >= max_depth: return np.pi * (start + end) / 2 b_mag = 1 slm.set_centered_size(slm.screen_width, slm.screen_height) b_values = [] for i in range(num_of_samples): phase = start + (i * (end - start) / (num_of_samples - 1)) slm.set_array(np.ones((64, 64)) * np.exp(1.0j * np.pi * phase)) slm.draw() slm.swap_buffers() time.sleep(0.025) cam.fetch_avg() H, V, D, A = cam.get_pol() H, V, D, A = cam.get_pol() center_x, center_y = mu.center_cam(V, np.max(V) * 0.7) V_value = mu.circular_integral(V, center_x, center_y, 5) H_value = mu.circular_integral(H, center_x, center_y, 5) / V_value D_value = mu.circular_integral(D, center_x, center_y, 5) / V_value A_value = mu.circular_integral(A, center_x, center_y, 5) / V_value V_value = 1 HVtoDA = (H_value + V_value) / (D_value + A_value) a, b = mu.solveDM(H_value, V_value, HVtoDA * D_value, HVtoDA * A_value, np.pi * 0.1) b_mag = np.absolute(b) b_values.append(b_mag) print((b_mag, phase)) min_phase_loc = b_values.index(min(b_values)) best_phase = start + (min_phase_loc * (end - start) / (num_of_samples - 1)) print(best_phase) span = (end - start) / num_of_samples return automatic_phase(cam, slm, best_phase - 2 * span, best_phase + 2 * span, 64, depth + 1)
def automatic_exposure_and_framing(cam, size, target_exposure, exposure_tolerance): cam.set_pixel_format() cam.set_exposure(50) cam.set_offset(int(0), int(0)) cam.set_size(int(cam.sensor_width), int(cam.sensor_height)) time.sleep(0.2) cam.restart() automatic_exposure(cam, target_exposure, exposure_tolerance) x = 0 y = 0 for n in range(10): time.sleep(0.15) dy, dx = mu.center_cam(cam.fetch_buffer()) cam.queue_buffer() x = x + dx - (size / 2) y = y + dy - (size / 2) x = min(max(np.floor(x / 4) * 4, 0), cam.sensor_width - size) y = min(max(np.floor(y / 4) * 4, 0), cam.sensor_height - size) cam.set_size(int(size), int(size)) cam.set_offset(int(x), int(y))
def measure(cam, slm, phase_low, phase, mask, center=None, take_dual=False): slm.set_array(np.exp(1.0j * (phase_low + phase * mask))) slm.disable_filter() slm.draw() slm.swap_buffers() time.sleep(0.025) cam.fetch_avg() H, V, D, A = cam.get_pol() center_x, center_y = mu.center_cam(V, np.max(V) * 0.7) if not (center == None): center_x = center[0] center_y = center[1] print((center_x, center_y)) integral_radius = 3 V_value = mu.circular_integral(V, center_x, center_y, integral_radius) H_value = mu.circular_integral(H, center_x, center_y, integral_radius) / V_value D_value = mu.circular_integral(D, center_x, center_y, integral_radius) / V_value A_value = mu.circular_integral(A, center_x, center_y, integral_radius) / V_value V_value = 1 HVtoDA = (H_value + V_value) / (D_value + A_value) a, b = mu.solveDM(H_value, V_value, D_value * HVtoDA, A_value * HVtoDA, phase) if take_dual: a2, b2 = measure(cam, slm, phase_low, phase, 1.0 - mask, None, False) a = (a - a2) / 2 b = (b - b2) / 2 return a, b
import Permutation as pmt import MathUtils as mu prime_tab = mu.genPrimeTab(9999) tab_len = len(prime_tab) index = 0 for prime in prime_tab: if prime >= 1000: break index += 1 prime_tab = prime_tab[index:tab_len] def tmp_convert(lst): mult = 1000 result = 0 for num in lst: result += mult * int(num) mult /= 10 return result def tmp_count_sub(lst): subs_count = {} for i in range(0, len(lst) - 2): for j in range(i + 1, len(lst) - 1): for k in range(j + 1, len(lst)): if lst[k] - lst[j] == lst[j] - lst[i]: print(lst[i], lst[j], lst[k]) return
import MathUtils primeTab = [str(n) for n in MathUtils.genPrimeTab(1000000)] primeFac = [] count = 0 num = 11 for n in primeTab: if count > 11: break if int(n) < 10: continue isTrunck = True num = str(n) for i in range(1, len(num)): if not (num[0:i] in primeTab) or not (num[i::] in primeTab): isTrunck = False break if isTrunck: primeFac.append(n) count += 1 print("the {}th prime: {}".format(count, n)) print(primeFac)
def regress(self): self.beta = MathUtils.newtonRaphson(self, self.beta)
import MathUtils import Permutation as permutation num = 987654321 max = 2 while num > 0: if MathUtils.isPrime(num): max = num print("max prime: {}".format(num)) break if permutation.isBegin(list(str(num))): num = list(str(num / 10)).sort(reverse=True) num = int(str(num)) else: num = int(''.join(permutation.lastPermuteStr(list(str(num)))))
def runbbdm(txtfile): infile_ = [] outfilename = "" prefix = "Skimmed_" ikey_ = "" if not runInteractive: print "running for ", txtfile infile_ = TextToList(txtfile) outfile = txtfile.split('/')[-1].replace('.txt', '.root') #key_=txtfile[1] outfilename = outfile # prefix+key_+".root" print "outfilename", outfilename if runInteractive: infile_ = TextToList(txtfile) print "infile_ = ", infile_ #print "running code for ",infile_ prefix_ = '' # '/eos/cms/store/group/phys_exotica/bbMET/2017_skimmedFiles/locallygenerated/' if outputdir != '.': prefix_ = outputdir + '/' #print "prefix_", prefix_ outfilename = prefix_ + txtfile.split('/')[-1].replace('.txt', '.root') print 'outfilename', outfilename samplename = whichsample(outfilename) print("samplename = ", samplename) if runOn2016: triglist = trig.trigger2016 eletrig = trig.Electrontrigger2016 muontrig = trig.Muontrigger2016 mettrig = trig.METtrigger2016 photontrig = trig.Photontrigger2016 elif runOn2017: triglist = trig.trigger2017 eletrig = trig.Electrontrigger2017 muontrig = trig.Muontrigger2017 mettrig = trig.METtrigger2017 photontrig = trig.Photontrigger2017 elif runOn2018: triglist = trig.trigger2018 eletrig = trig.Electrontrigger2018 muontrig = trig.Muontrigger2018 mettrig = trig.METtrigger2018 photontrig = trig.Photontrigger2018 bins_pT = [ 20.0, 50.0, 80.0, 120.0, 200.0, 300.0, 400.0, 500.0, 700.0, 1000.0 ] bins_eta = [-2.5, -1.5, -0.5, 0.0, 0.5, 1.5, 2.5] h_btag_num_pass_mwp = TH2D("h_btag_num_pass_mwp", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) h_btag_num_fail_mwp = TH2D("h_btag_num_fail_mwp", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) h_btag_den = TH2D("h_btag_den", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) h_ctag_num_pass_mwp = TH2D("h_ctag_num_pass_mwp", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) h_ctag_num_fail_mwp = TH2D("h_ctag_num_fail_mwp", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) h_ctag_den = TH2D("h_ctag_den", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) h_lighttag_num_pass_mwp = TH2D("h_lighttag_num_pass_mwp", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) h_lighttag_num_fail_mwp = TH2D("h_lighttag_num_fail_mwp", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) h_lighttag_den = TH2D("h_lighttag_den", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) h_btag_num_pass_lwp = TH2D("h_btag_num_pass_lwp", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) h_btag_num_fail_lwp = TH2D("h_btag_num_fail_lwp", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) h_ctag_num_pass_lwp = TH2D("h_ctag_num_pass_lwp", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) h_ctag_num_fail_lwp = TH2D("h_ctag_num_fail_lwp", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) h_lighttag_num_pass_lwp = TH2D("h_lighttag_num_pass_lwp", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) h_lighttag_num_fail_lwp = TH2D("h_lighttag_num_fail_lwp", "", 6, array('d', bins_eta), 9, array('d', bins_pT)) passfilename = open("skim_configs/outfilename.txt", "w") passfilename.write(outfilename) passfilename.close() ## following can be moved to outputtree.py if we manage to change the name of output root file. outfilenameis = outfilename outfile = TFile(outfilenameis, 'RECREATE') ## following can be moved to outputtree.py if we manage to change the name of output root file. if runOn2016: jetvariables = branches.allvars2016 elif runOn2017: jetvariables = branches.allvars2017 elif runOn2018: jetvariables = branches.allvars2018 filename = infile_ ieve = 0 icount = 0 #print "running on", filename for df in read_root(filename, 'tree/treeMaker', columns=jetvariables, chunksize=125000): if runOn2016: var_zip = zip( df.runId, df.lumiSection, df.eventId, df.isData, df.mcWeight, df.prefiringweight, df.prefiringweightup, df.prefiringweightdown, df.pu_nTrueInt, df.pu_nPUVert, df.hlt_trigName, df.hlt_trigResult, df.hlt_filterName, df.hlt_filterResult, df.pfpatMet_smear, df.pfMetCorrPt, df.pfMetCorrPhi, df.pfMetCorrUnc, df.pfMetCorrSig, df.pfpatCaloMETPt, df.pfpatCaloMETPhi, df.pfTRKMETPt_, df.pfTRKMETPhi_, df.nEle, df.elePx, df.elePy, df.elePz, df.eleEnergy, df.eleIsPassVeto, df.eleIsPassLoose, df.eleIsPassTight, df.eleD0, df.eleDz, df.eleCharge, df.nPho, df.phoPx, df.phoPy, df.phoPz, df.phoEnergy, df.phoIsPassLoose, df.phoIsPassTight, df.nMu, df.muPx, df.muPy, df.muPz, df.muEnergy, df.isLooseMuon, df.isTightMuon, df.PFIsoLoose, df.PFIsoMedium, df.PFIsoTight, df.PFIsoVeryTight, df.muCharge, df.HPSTau_n, df.HPSTau_Px, df.HPSTau_Py, df.HPSTau_Pz, df.HPSTau_Energy, df.disc_decayModeFinding, df.disc_byLooseIsolationMVArun2017v2DBoldDMwLT2017, df.disc_byMediumIsolationMVArun2017v2DBoldDMwLT2017, df.disc_byTightIsolationMVArun2017v2DBoldDMwLT2017, df.disc_againstMuonLoose3, df.disc_againstMuonTight3, df.disc_againstElectronLooseMVA6, df.disc_againstElectronMediumMVA6, df.disc_againstElectronTightMVA6, df.nGenPar, df.genParId, df.genMomParId, df.genParSt, df.genParPx, df.genParPy, df.genParPz, df.genParE, df.THINnJet, df.THINjetPx, df.THINjetPy, df.THINjetPz, df.THINjetEnergy, df.THINbRegNNResolution, df.THINbRegNNCorr, df.THINisPUJetIDLoose, df.THINisPUJetIDMedium, df.THINisPUJetIDTight, df.THINjetPassIDLoose, df.THINjetDeepCSV_b, df.THINjetHadronFlavor, df.THINjetCEmEF, df.THINjetCHadEF, df.THINjetNEmEF, df.THINjetNHadEF, df.THINjetCMulti, df.THINjetNMultiplicity, df.THINjetCorrUncUp, df.THINjetNPV, df.FATnJet, df.FATjetPx, df.FATjetPy, df.FATjetPz, df.FATjetEnergy, df.FATgenjetpx, df.FATgenjetpy, df.FATgenjetpz, df.FATgenjetE, df.FATjetPassIDLoose, df.FATjet_DoubleSV, df.FATjet_probQCDb, df.FATjet_probHbb, df.FATjet_probQCDc, df.FATjet_probHcc, df.FATjet_probHbbc, df.FATjet_prob_bbvsLight, df.FATjet_prob_ccvsLight, df.FATjet_prob_TvsQCD, df.FATjet_prob_WvsQCD, df.FATjet_prob_ZHbbvsQCD, df.FATjetSDmass, df.FATN2_Beta1_, df.FATN2_Beta2_, df.FATjetCHSPRmassL2L3Corr, df.FATjetCHSSDmassL2L3Corr, df.FATjetTau1, df.FATjetTau2) elif runOn2017: var_zip = zip( df.runId, df.lumiSection, df.eventId, df.isData, df.mcWeight, df.prefiringweight, df.prefiringweightup, df.prefiringweightdown, df.pu_nTrueInt, df.pu_nPUVert, df.hlt_trigName, df.hlt_trigResult, df.hlt_filterName, df.hlt_filterResult, df.pfpatmodifiedMet_smear, df.pfmodifiedMetCorrPt, df.pfmodifiedMetCorrPhi, df.pfmodifiedMetCorrUnc, df.pfmodifiedMetCorrSig, df.pfpatCaloMETPt, df.pfpatCaloMETPhi, df.pfTRKMETPt_, df.pfTRKMETPhi_, df.nEle, df.elePx, df.elePy, df.elePz, df.eleEnergy, df.eleIsPassVeto, df.eleIsPassLoose, df.eleIsPassTight, df.eleD0, df.eleDz, df.eleCharge, df.nPho, df.phoPx, df.phoPy, df.phoPz, df.phoEnergy, df.phoIsPassLoose, df.phoIsPassTight, df.nMu, df.muPx, df.muPy, df.muPz, df.muEnergy, df.isLooseMuon, df.isTightMuon, df.PFIsoLoose, df.PFIsoMedium, df.PFIsoTight, df.PFIsoVeryTight, df.muCharge, df.HPSTau_n, df.HPSTau_Px, df.HPSTau_Py, df.HPSTau_Pz, df.HPSTau_Energy, df.disc_decayModeFinding, df.disc_byLooseIsolationMVArun2017v2DBoldDMwLT2017, df.disc_byMediumIsolationMVArun2017v2DBoldDMwLT2017, df.disc_byTightIsolationMVArun2017v2DBoldDMwLT2017, df.disc_againstMuonLoose3, df.disc_againstMuonTight3, df.disc_againstElectronLooseMVA6, df.disc_againstElectronMediumMVA6, df.disc_againstElectronTightMVA6, df.nGenPar, df.genParId, df.genMomParId, df.genParSt, df.genParPx, df.genParPy, df.genParPz, df.genParE, df.THINnJet, df.THINjetPx, df.THINjetPy, df.THINjetPz, df.THINjetEnergy, df.THINbRegNNResolution, df.THINbRegNNCorr, df.THINisPUJetIDLoose, df.THINisPUJetIDMedium, df.THINisPUJetIDTight, df.THINjetPassIDTight, df.THINjetDeepCSV_b, df.THINjetHadronFlavor, df.THINjetCEmEF, df.THINjetCHadEF, df.THINjetNEmEF, df.THINjetNHadEF, df.THINjetCMulti, df.THINjetNMultiplicity, df.THINjetCorrUncUp, df.THINjetNPV, df.FATnJet, df.FATjetPx, df.FATjetPy, df.FATjetPz, df.FATjetEnergy, df.FATgenjetpx, df.FATgenjetpy, df.FATgenjetpz, df.FATgenjetE, df.FATjetPassIDTight, df.FATjet_DoubleSV, df.FATjet_probQCDb, df.FATjet_probHbb, df.FATjet_probQCDc, df.FATjet_probHcc, df.FATjet_probHbbc, df.FATjet_prob_bbvsLight, df.FATjet_prob_ccvsLight, df.FATjet_prob_TvsQCD, df.FATjet_prob_WvsQCD, df.FATjet_prob_ZHbbvsQCD, df.FATjetSDmass, df.FATN2_Beta1_, df.FATN2_Beta2_, df.FATjetCHSPRmassL2L3Corr, df.FATjetCHSSDmassL2L3Corr, df.FATjetTau1, df.FATjetTau2) elif runOn2018: df['prefiringweight'] = 1.0 df['prefiringweightup'] = 1.0 df['prefiringweightdown'] = 1.0 var_zip = zip( df.runId, df.lumiSection, df.eventId, df.isData, df.mcWeight, df.prefiringweight, df.prefiringweightup, df.prefiringweightdown, df.pu_nTrueInt, df.pu_nPUVert, df.hlt_trigName, df.hlt_trigResult, df.hlt_filterName, df.hlt_filterResult, df.pfpatMet_smear, df.pfMetCorrPt, df.pfMetCorrPhi, df.pfMetCorrUnc, df.pfMetCorrSig, df.pfpatCaloMETPt, df.pfpatCaloMETPhi, df.pfTRKMETPt_, df.pfTRKMETPhi_, df.nEle, df.elePx, df.elePy, df.elePz, df.eleEnergy, df.eleIsPassVeto, df.eleIsPassLoose, df.eleIsPassTight, df.eleD0, df.eleDz, df.eleCharge, df.nPho, df.phoPx, df.phoPy, df.phoPz, df.phoEnergy, df.phoIsPassLoose, df.phoIsPassTight, df.nMu, df.muPx, df.muPy, df.muPz, df.muEnergy, df.isLooseMuon, df.isTightMuon, df.PFIsoLoose, df.PFIsoMedium, df.PFIsoTight, df.PFIsoVeryTight, df.muCharge, df.HPSTau_n, df.HPSTau_Px, df.HPSTau_Py, df.HPSTau_Pz, df.HPSTau_Energy, df.disc_decayModeFinding, df.disc_byLooseIsolationMVArun2017v2DBoldDMwLT2017, df.disc_byMediumIsolationMVArun2017v2DBoldDMwLT2017, df.disc_byTightIsolationMVArun2017v2DBoldDMwLT2017, df.disc_againstMuonLoose3, df.disc_againstMuonTight3, df.disc_againstElectronLooseMVA6, df.disc_againstElectronMediumMVA6, df.disc_againstElectronTightMVA6, df.nGenPar, df.genParId, df.genMomParId, df.genParSt, df.genParPx, df.genParPy, df.genParPz, df.genParE, df.THINnJet, df.THINjetPx, df.THINjetPy, df.THINjetPz, df.THINjetEnergy, df.THINbRegNNResolution, df.THINbRegNNCorr, df.THINisPUJetIDLoose, df.THINisPUJetIDMedium, df.THINisPUJetIDTight, df.THINjetPassIDTight, df.THINjetDeepCSV_b, df.THINjetHadronFlavor, df.THINjetCEmEF, df.THINjetCHadEF, df.THINjetNEmEF, df.THINjetNHadEF, df.THINjetCMulti, df.THINjetNMultiplicity, df.THINjetCorrUncUp, df.THINjetNPV, df.FATnJet, df.FATjetPx, df.FATjetPy, df.FATjetPz, df.FATjetEnergy, df.FATgenjetpx, df.FATgenjetpy, df.FATgenjetpz, df.FATgenjetE, df.FATjetPassIDTight, df.FATjet_DoubleSV, df.FATjet_probQCDb, df.FATjet_probHbb, df.FATjet_probQCDc, df.FATjet_probHcc, df.FATjet_probHbbc, df.FATjet_prob_bbvsLight, df.FATjet_prob_ccvsLight, df.FATjet_prob_TvsQCD, df.FATjet_prob_WvsQCD, df.FATjet_prob_ZHbbvsQCD, df.FATjetSDmass, df.FATN2_Beta1_, df.FATN2_Beta2_, df.FATjetCHSPRmassL2L3Corr, df.FATjetCHSSDmassL2L3Corr, df.FATjetTau1, df.FATjetTau2) for run, lumi, event, isData, mcWeight_,\ prefiringweight_, prefiringweightup_, prefiringweightdown_,\ pu_nTrueInt_, pu_nPUVert_,\ trigName_, trigResult_, filterName, filterResult,\ met_smear, met_, metphi_, metUnc_,\ metCorrSig, patCaloMETPt, patCaloMETPhi, TRKMETPt_, TRKMETPhi_,\ nele_, elepx_, elepy_, elepz_, elee_, elevetoid_, elelooseid_, eletightid_, eleD0_, eleDz_,\ eleCharge_, npho_, phopx_, phopy_, phopz_, phoe_, pholooseid_, photightID_,\ nmu_, mupx_, mupy_, mupz_, mue_, mulooseid_, mutightid_, muisoloose, muisomedium, muisotight, muisovtight, muCharge_,\ nTau_, tau_px_, tau_py_, tau_pz_, tau_e_, tau_dm_, tau_isLoose_, tau_isoMedium_, tau_isoTight_,\ Taudisc_againstLooseMuon, Taudisc_againstTightMuon, Taudisc_againstLooseElectron, Taudisc_againstMediumElectron, Taudisc_againstTightElectron,\ nGenPar_, genParId_, genMomParId_, genParSt_, genpx_, genpy_, genpz_, gene_,\ nak4jet_, ak4px_, ak4py_, ak4pz_, ak4e_, ak4bRegNNResolution, ak4bRegNNCorr,ak4PUJetIDLoose,ak4PUJetIDMedium,ak4PUJetIDTight,\ ak4PassID_, ak4deepcsv_, ak4flavor_, ak4CEmEF_, ak4CHadEF_, ak4NEmEF_, ak4NHadEF_, ak4CMulti_, ak4NMultiplicity_, ak4JEC_, ak4NPV_,\ fatnJet, fatjetPx, fatjetPy, fatjetPz, fatjetEnergy, fatgenjetPx, fatgenjetPy, fatgenjetPz, fatgenjetEnergy, fatjetPassID,\ fatjet_DoubleSV, fatjet_probQCDb, fatjet_probHbb, fatjet_probQCDc, fatjet_probHcc, fatjet_probHbbc,\ fatjet_prob_bbvsLight, fatjet_prob_ccvsLight, fatjet_prob_TvsQCD, fatjet_prob_WvsQCD, fatjet_prob_ZHbbvsQCD,\ fatjetSDmass, fatN2_Beta1_, fatN2_Beta2_, fatjetCHSPRmassL2L3Corr, fatjetCHSSDmassL2L3Corr, fatjetTau1, fatjetTau2\ in var_zip: if ieve % 1000 == 0: print("Processed", ieve, "Events") ieve = ieve + 1 # ------------------------------------------------- # MC Weights # ------------------------------------------------- # mcweight[0] = 0.0 # if isData == 1: # mcweight[0] = 1.0 # if not isData: # if mcWeight_ < 0: # mcweight[0] = -1.0 # if mcWeight_ > 0: # mcweight[0] = 1.0 # h_total.Fill(1.) # h_total_mcweight.Fill(1., mcweight[0]) # ------------------------------------------------- ## Trigger selection # ------------------------------------------------- eletrigdecision = False mudecision = False metdecision = False phodecision = False eletrigstatus = [(anautil.CheckFilter(trigName_, trigResult_, eletrig[itrig])) for itrig in range(len(eletrig))] mutrigstatus = [(anautil.CheckFilter(trigName_, trigResult_, muontrig[itrig])) for itrig in range(len(muontrig))] mettrigstatus = [(anautil.CheckFilter(trigName_, trigResult_, mettrig[itrig])) for itrig in range(len(mettrig))] photrigstatus = [(anautil.CheckFilter(trigName_, trigResult_, photontrig[itrig])) for itrig in range(len(photontrig))] eletrigdecision = boolutil.logical_OR(eletrigstatus) mutrigdecision = boolutil.logical_OR(mutrigstatus) mettrigdecision = boolutil.logical_OR(mettrigstatus) photrigdecision = boolutil.logical_OR(photrigstatus) # ------------------------------------------------------ ## Filter selection # ------------------------------------------------------ filterdecision = False filterstatus = [False for ifilter in range(len(filter_list))] filterstatus = [ anautil.CheckFilter(filterName, filterResult, filter_list[ifilter]) for ifilter in range(len(filter_list)) ] filterdecision = boolutil.logical_AND(filterstatus) if filterdecision == False and isData: continue # ------------------------------------------------------ ## PFMET Selection # -------------------------------------------------------- pfmetstatus = (met_ > 200.0) ''' **** * **** * * * *** * *** * * * **** **** **** ''' elept = getPt(elepx_, elepy_) eleeta = getEta(elepx_, elepy_, elepz_) elephi = getPhi(elepx_, elepy_) ele_pt10_eta2p5_vetoID = boolutil.logical_and3( (elept > 10.0), (elevetoid_), numpy.logical_and( numpy.logical_or( numpy.abs(eleeta) > 1.566, numpy.abs(eleeta) < 1.4442), (numpy.abs(eleeta) < 2.5))) ele_pt10_eta2p5_looseID = boolutil.logical_and3( (elept > 10.0), (elelooseid_), numpy.logical_and( numpy.logical_or( numpy.abs(eleeta) > 1.566, numpy.abs(eleeta) < 1.4442), (numpy.abs(eleeta) < 2.5))) ele_pt30_eta2p5_tightID = boolutil.logical_and3( (elept > 30.0), (eletightid_), numpy.logical_and( numpy.logical_or( boolutil.logical_and3( numpy.abs(eleeta) > 1.566, numpy.abs(eleD0_) < 0.10, numpy.abs(eleDz_) < 0.20), boolutil.logical_and3( numpy.abs(eleeta) < 1.4442, numpy.abs(eleD0_) < 0.05, numpy.abs(eleDz_) < 0.10)), (numpy.abs(eleeta) < 2.5))) pass_ele_veto_index = boolutil.WhereIsTrue(ele_pt10_eta2p5_vetoID) pass_ele_loose_index = boolutil.WhereIsTrue( ele_pt10_eta2p5_looseID) ''' ** * * * * * * * * * * * * * * * * * * * * ***** ''' mupt = getPt(mupx_, mupy_) mueta = getEta(mupx_, mupy_, mupz_) muphi = getPhi(mupx_, mupy_) mu_pt10_eta2p4_looseID_looseISO = boolutil.logical_and4( mupt > 10.0, numpy.abs(mueta) < 2.4, mulooseid_, muisoloose) mu_pt30_eta2p4_tightID_tightISO = boolutil.logical_and4( (mupt > 30.0), (numpy.abs(mueta) < 2.4), (mutightid_), (muisotight)) pass_mu_index = boolutil.WhereIsTrue( mu_pt10_eta2p4_looseID_looseISO) ''' ******* * * ****** * * * * * * ******* ******** * * * * * * * * * * ****** ''' phopt = getPt(phopx_, phopy_) phoeta = getEta(phopx_, phopy_, phopz_) phophi = getPhi(phopx_, phopy_) pho_pt15_eta2p5_looseID = boolutil.logical_and3( (phopt > 15.0), (numpy.abs(phoeta) < 2.5), (pholooseid_)) pass_pho_index = boolutil.WhereIsTrue(pho_pt15_eta2p5_looseID) cleanedPho_ag_ele = [] cleanedPho_ag_mu = [] pass_pho_index_cleaned = [] if npho_ > 0: #and ep_nEle > 0: cleanedPho_ag_ele = anautil.jetcleaning( pho_pt15_eta2p5_looseID, ele_pt10_eta2p5_looseID, phoeta, eleeta, phophi, elephi, 0.4) cleanedPho_ag_mu = anautil.jetcleaning( pho_pt15_eta2p5_looseID, mu_pt10_eta2p4_looseID_looseISO, phoeta, mueta, phophi, muphi, 0.4) cleanedPhoton = boolutil.logical_AND_List2( cleanedPho_ag_ele, cleanedPho_ag_mu) pass_pho_index_cleaned = boolutil.WhereIsTrue(cleanedPhoton) ## Fill variables for the CRs which require lepton. WenuRecoil = -1 WenuRecoilSmearPt = -1 Wenumass = -1 WenuPhi = -10 WmunuRecoil = -1 WmunuRecoilSmearPt = -1 Wmunumass = -1 WmunuPhi = -10 ZeeRecoil = -1 ZeeRecoilSmear = -1 Zeemass = -1 ZeePhi = -10 ZmumuRecoil = -1 ZmumuRecoilSmear = -1 Zmumumass = -1 ZmumuPhi = -10 GammaRecoil = -1 GammaRecoilSmearPt = -1 GammaPhi = -10 if debug_: print('Reached Fill variables') # ------------------ # Z CR # ------------------ ## for dielectron if len(pass_ele_loose_index) == 2: iele1 = pass_ele_loose_index[0] iele2 = pass_ele_loose_index[1] if eleCharge_[iele1] * eleCharge_[iele2] < 0: ee_mass = InvMass(elepx_[iele1], elepy_[iele1], elepz_[iele1], elee_[iele1], elepx_[iele2], elepy_[iele2], elepz_[iele2], elee_[iele2]) zeeRecoilPx = -(met_ * math.cos(metphi_) + elepx_[iele1] + elepx_[iele2]) zeeRecoilPy = -(met_ * math.sin(metphi_) + elepy_[iele1] + elepy_[iele2]) ZeeRecoilPt = math.sqrt(zeeRecoilPx**2 + zeeRecoilPy**2) if ee_mass > 60.0 and ee_mass < 120.0 and ZeeRecoilPt > 200.0: ZeeRecoil = ZeeRecoilPt Zeemass = ee_mass ZeePhi = mathutil.ep_arctan(zeeRecoilPx, zeeRecoilPy) zeeRecoilSmearPx = - \ (met_*math.cos(metphi_) + elepx_[iele1] + elepx_[iele2]) zeeRecoilSmearPy = - \ (met_*math.sin(metphi_) + elepy_[iele1] + elepy_[iele2]) ZeeRecoilSmearPt = math.sqrt(zeeRecoilSmearPx**2 + zeeRecoilSmearPy**2) if ee_mass > 60.0 and ee_mass < 120.0 and ZeeRecoilSmearPt > 200.0: ZeeRecoilSmear = ZeeRecoilSmearPt ## for dimu if len(pass_mu_index) == 2: imu1 = pass_mu_index[0] imu2 = pass_mu_index[1] if muCharge_[imu1] * muCharge_[imu2] < 0: mumu_mass = InvMass(mupx_[imu1], mupy_[imu1], mupz_[imu1], mue_[imu1], mupx_[imu2], mupy_[imu2], mupz_[imu2], mue_[imu2]) zmumuRecoilPx = -(met_ * math.cos(metphi_) + mupx_[imu1] + mupx_[imu2]) zmumuRecoilPy = -(met_ * math.sin(metphi_) + mupy_[imu1] + mupy_[imu2]) ZmumuRecoilPt = math.sqrt(zmumuRecoilPx**2 + zmumuRecoilPy**2) if mumu_mass > 60.0 and mumu_mass < 120.0 and ZmumuRecoilPt > 200.0: ZmumuRecoil = ZmumuRecoilPt Zmumumass = mumu_mass ZmumuPhi = mathutil.ep_arctan(zmumuRecoilPx, zmumuRecoilPy) zmumuRecoilSmearPx = - \ (met_*math.cos(metphi_) + mupx_[imu1] + mupx_[imu2]) zmumuRecoilSmearPy = - \ (met_*math.sin(metphi_) + mupy_[imu1] + mupy_[imu2]) ZmumuRecoilSmearPt = math.sqrt(zmumuRecoilSmearPx**2 + zmumuRecoilSmearPy**2) if mumu_mass > 60.0 and mumu_mass < 120.0 and ZmumuRecoilSmearPt > 200.0: ZmumuRecoilSmear = ZmumuRecoilSmearPt if len(pass_ele_loose_index) == 2: ZRecoilstatus = (ZeeRecoil > 200.0) or (ZeeRecoilSmear > 200.0) elif len(pass_mu_index) == 2: ZRecoilstatus = (ZmumuRecoil > 200.0) or (ZmumuRecoilSmear > 200.0) else: ZRecoilstatus = False if debug_: print 'Reached Z CR' # ------------------ # W CR # ------------------ ## for Single electron if len(pass_ele_loose_index) == 1: ele1 = pass_ele_loose_index[0] # transverse mass defined as sqrt{2pT*MET*(1-cos(dphi)} e_mass = MT(elept[ele1], met_, DeltaPhi(elephi[ele1], metphi_)) WenuRecoilPx = -(met_ * math.cos(metphi_) + elepx_[ele1]) WenuRecoilPy = -(met_ * math.sin(metphi_) + elepy_[ele1]) WenuRecoilPt = math.sqrt(WenuRecoilPx**2 + WenuRecoilPy**2) if WenuRecoilPt > 200.0: WenuRecoil = WenuRecoilPt Wenumass = e_mass WenuPhi = mathutil.ep_arctan(WenuRecoilPx, WenuRecoilPy) WenuRecoilSmearPx = - \ (met_*math.cos(metphi_) + elepx_[ele1]) WenuRecoilSmearPy = - \ (met_*math.sin(metphi_) + elepy_[ele1]) WenuRecoilSmearPt = math.sqrt(WenuRecoilSmearPx**2 + WenuRecoilSmearPy**2) ## for Single muon if len(pass_mu_index) == 1: mu1 = pass_mu_index[0] # transverse mass defined as sqrt{2pT*MET*(1-cos(dphi)} mu_mass = MT(mupt[mu1], met_, DeltaPhi(muphi[mu1], metphi_)) WmunuRecoilPx = -(met_ * math.cos(metphi_) + mupx_[mu1]) WmunuRecoilPy = -(met_ * math.sin(metphi_) + mupy_[mu1]) WmunuRecoilPt = math.sqrt(WmunuRecoilPx**2 + WmunuRecoilPy**2) if WmunuRecoilPt > 200.0: WmunuRecoil = WmunuRecoilPt Wmunumass = mu_mass WmunuPhi = mathutil.ep_arctan(WmunuRecoilPx, WmunuRecoilPy) WmunuRecoilSmearPx = - \ (met_*math.cos(metphi_) + mupx_[mu1]) WmunuRecoilSmearPy = - \ (met_*math.sin(metphi_) + mupy_[mu1]) WmunuRecoilSmearPt = math.sqrt(WmunuRecoilSmearPx**2 + WmunuRecoilSmearPy**2) if len(pass_ele_loose_index) == 1: WRecoilstatus = (WenuRecoil > 200.0) or (WenuRecoilSmearPt > 200.0) elif len(pass_mu_index) == 1: WRecoilstatus = (WmunuRecoil > 200.0) or (WmunuRecoilSmearPt > 200.0) else: WRecoilstatus = False if debug_: print 'Reached W CR' # ------------------ # Gamma CR # ------------------ ## for Single photon if len(pass_pho_index) >= 1: pho1 = pass_pho_index[0] GammaRecoilPx = -(met_ * math.cos(metphi_) + phopx_[pho1]) GammaRecoilPy = -(met_ * math.sin(metphi_) + phopy_[pho1]) GammaRecoilPt = math.sqrt(GammaRecoilPx**2 + GammaRecoilPy**2) if GammaRecoilPt > 200.0: GammaRecoil = GammaRecoilPt GammaPhi = mathutil.ep_arctan(GammaRecoilPx, GammaRecoilPy) GammaRecoilSmearPx = - \ (met_*math.cos(metphi_) + phopx_[pho1]) GammaRecoilSmearPy = - \ (met_*math.sin(metphi_) + phopy_[pho1]) GammaRecoilSmearPt = math.sqrt(GammaRecoilSmearPx**2 + GammaRecoilSmearPy**2) GammaRecoilStatus = (GammaRecoil > 200.0) or (GammaRecoilSmearPt > 200.0) if debug_: print 'Reached Gamma CR' if pfmetstatus == False and ZRecoilstatus == False and WRecoilstatus == False and GammaRecoilStatus == False: continue ''' ******* ***** ******* * * * * **** * * * * *** ***** * ''' ''' ak4pt = [getPt(ak4px_[ij], ak4py_[ij]) for ij in range(nak4jet_)] ak4eta = [getEta(ak4px_[ij], ak4py_[ij], ak4pz_[ij]) for ij in range(nak4jet_)] ak4phi = [getPhi(ak4px_[ij], ak4py_[ij]) for ij in range(nak4jet_)] ''' ak4pt = getPt(ak4px_, ak4py_) ak4eta = getEta(ak4px_, ak4py_, ak4pz_) ak4phi = getPhi(ak4px_, ak4py_) if runOn2016: #ak4PassID_Calc = [jetID_(ak4CEmEF_[ij],ak4CHadEF_[ij],ak4NEmEF_[ij],ak4NHadEF_[ij],ak4CMulti_[ij],ak4NMultiplicity_[ij],ak4eta[ij])[0] for ij in range(nak4jet_)] ak4PassID_Calc = ak4PassID_ if runOn2017: #ak4PassID_Calc = [jetID_(ak4CEmEF_[ij],ak4CHadEF_[ij],ak4NEmEF_[ij],ak4NHadEF_[ij],ak4CMulti_[ij],ak4NMultiplicity_[ij],ak4eta[ij])[1] for ij in range(nak4jet_)] ak4PassID_Calc = ak4PassID_ if runOn2018: #ak4PassID_Calc = [jetID_(ak4CEmEF_[ij],ak4CHadEF_[ij],ak4NEmEF_[ij],ak4NHadEF_[ij],ak4CMulti_[ij],ak4NMultiplicity_[ij],ak4eta[ij])[1] for ij in range(nak4jet_)] ak4PassID_Calc = ak4PassID_ #ak4_pt30_eta4p5_IDT = ( (ak4pt[ij] > 30.0) and (abs(ak4eta[ij]) < 4.5) and (ak4PassID_Calc[ij] ) ) for ij in range(nak4jet_)] ak4_pt30_eta4p5_IDT = boolutil.logical_and3( (ak4pt > 30.0), (numpy.abs(ak4eta) < 4.5), (ak4PassID_Calc)) ##--- jet cleaning jetCleanAgainstEle = [] jetCleanAgainstMu = [] pass_jet_index_cleaned = [] if len(ak4_pt30_eta4p5_IDT) > 0: DRCut = 0.4 jetCleanAgainstEle = anautil.jetcleaning( ak4_pt30_eta4p5_IDT, ele_pt10_eta2p5_vetoID, ak4eta, eleeta, ak4phi, elephi, DRCut) jetCleanAgainstMu = anautil.jetcleaning( ak4_pt30_eta4p5_IDT, mu_pt10_eta2p4_looseID_looseISO, ak4eta, mueta, ak4phi, muphi, DRCut) jetCleaned = boolutil.logical_AND_List3( ak4_pt30_eta4p5_IDT, jetCleanAgainstEle, jetCleanAgainstMu) pass_jet_index_cleaned = boolutil.WhereIsTrue(jetCleaned) if debug_: print "pass_jet_index_cleaned = ", pass_jet_index_cleaned, "nJets= ", len( ak4px_) ''' ******** * * * * * * * * * * * * * * ******** * * * * * * * * * * ******* ''' taupt = getPt(tau_px_, tau_py_) taueta = getEta(tau_px_, tau_py_, tau_pz_) tauphi = getPhi(tau_px_, tau_py_) tau_eta2p3_iDLdm_pt18 = boolutil.logical_AND_List4( (taupt > 18.0), (numpy.abs(taueta) < 2.3), (tau_isLoose_), (tau_dm_)) if debug_: print "tau_eta2p3_iDLdm_pt18 = ", tau_eta2p3_iDLdm_pt18 tau_eta2p3_iDLdm_pt18_looseEleVeto_looseMuVeto = boolutil.logical_and6( (taupt > 18.0), (numpy.abs(taueta) < 2.3), (tau_isLoose_), (tau_dm_), (Taudisc_againstLooseElectron), (Taudisc_againstLooseMuon)) tau_eta2p3_iDLdm_pt18_looseEleVeto_tightMuVeto = boolutil.logical_and6( (taupt > 18.0), (numpy.abs(taueta) < 2.3), (tau_isLoose_), (tau_dm_), (Taudisc_againstLooseElectron), (Taudisc_againstTightMuon)) tau_eta2p3_iDLdm_pt18_mediumEleVeto_looseMuVeto = boolutil.logical_and6( (taupt > 18.0), (numpy.abs(taueta) < 2.3), (tau_isLoose_), (tau_dm_), (Taudisc_againstMediumElectron), (Taudisc_againstLooseMuon)) tau_eta2p3_iDLdm_pt18_tightEleVeto_looseMuVeto = boolutil.logical_and6( (taupt > 18.0), (numpy.abs(taueta) < 2.3), (tau_isLoose_), (tau_dm_), (Taudisc_againstTightElectron), (Taudisc_againstLooseMuon)) tau_eta2p3_iDLdm_pt18_tightEleVeto_tightMuVeto = boolutil.logical_and6( (taupt > 18.0), (numpy.abs(taueta) < 2.3), (tau_isLoose_), (tau_dm_), (Taudisc_againstTightElectron), (Taudisc_againstTightMuon)) tau_eta2p3_iDLdm_pt18_looseEleVeto_looseMuVeto_index = boolutil.WhereIsTrue( tau_eta2p3_iDLdm_pt18_looseEleVeto_looseMuVeto) tau_eta2p3_iDLdm_pt18_looseEleVeto_tightMuVeto_index = boolutil.WhereIsTrue( tau_eta2p3_iDLdm_pt18_looseEleVeto_tightMuVeto) tau_eta2p3_iDLdm_pt18_mediumEleVeto_looseMuVeto_index = boolutil.WhereIsTrue( tau_eta2p3_iDLdm_pt18_mediumEleVeto_looseMuVeto) tau_eta2p3_iDLdm_pt18_tightEleVeto_looseMuVeto_index = boolutil.WhereIsTrue( tau_eta2p3_iDLdm_pt18_tightEleVeto_looseMuVeto) tau_eta2p3_iDLdm_pt18_tightEleVeto_tightMuVeto_index = boolutil.WhereIsTrue( tau_eta2p3_iDLdm_pt18_tightEleVeto_tightMuVeto) tauCleanAgainstEle = [] tauCleanAgainstMu = [] pass_tau_index_cleaned_DRBased = [] if len(tau_eta2p3_iDLdm_pt18) > 0: DRCut = 0.4 tauCleanAgainstEle = anautil.jetcleaning( tau_eta2p3_iDLdm_pt18, ele_pt10_eta2p5_looseID, taueta, eleeta, tauphi, elephi, DRCut) tauCleanAgainstMu = anautil.jetcleaning( tau_eta2p3_iDLdm_pt18, mu_pt10_eta2p4_looseID_looseISO, taueta, mueta, tauphi, muphi, DRCut) tauCleaned = boolutil.logical_AND_List3( tau_eta2p3_iDLdm_pt18, tauCleanAgainstEle, tauCleanAgainstMu) pass_tau_index_cleaned_DRBased = boolutil.WhereIsTrue( tauCleaned) if debug_: print "pass_tau_index_cleaned_DRBased", pass_tau_index_cleaned_DRBased for ithinjet in pass_jet_index_cleaned: #==================== for flavor 5 ================================== if ak4flavor_[ithinjet] == 5: h_btag_den.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) if ak4deepcsv_[ithinjet] > LWP: h_btag_num_pass_lwp.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) else: h_btag_num_fail_lwp.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) if ak4deepcsv_[ithinjet] > MWP: h_btag_num_pass_mwp.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) else: h_btag_num_fail_mwp.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) #==================== for flavor 4 ================================== if ak4flavor_[ithinjet] == 4: h_ctag_den.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) if ak4deepcsv_[ithinjet] > LWP: h_ctag_num_pass_lwp.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) else: h_ctag_num_fail_lwp.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) if ak4deepcsv_[ithinjet] > MWP: h_ctag_num_pass_mwp.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) else: h_ctag_num_fail_mwp.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) #==================== for light flavor ================================== if ak4flavor_[ithinjet] != 4 and ak4flavor_[ithinjet] != 5: h_lighttag_den.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) if ak4deepcsv_[ithinjet] > LWP: h_lighttag_num_pass_lwp.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) else: h_lighttag_num_fail_lwp.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) if ak4deepcsv_[ithinjet] > MWP: h_lighttag_num_pass_mwp.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) else: h_lighttag_num_fail_mwp.Fill(ak4eta[ithinjet], ak4pt[ithinjet]) outfile.cd() h_btag_num_pass_mwp.Write() h_btag_num_fail_mwp.Write() h_btag_num_pass_lwp.Write() h_btag_num_fail_lwp.Write() h_btag_den.Write() h_ctag_num_pass_mwp.Write() h_ctag_num_fail_mwp.Write() h_ctag_num_pass_lwp.Write() h_ctag_num_fail_lwp.Write() h_ctag_den.Write() h_lighttag_num_pass_mwp.Write() h_lighttag_num_fail_mwp.Write() h_lighttag_num_pass_lwp.Write() h_lighttag_num_fail_lwp.Write() h_lighttag_den.Write() outfile.Write() print "output written to ", outfilename end = time.clock() print "%.4gs" % (end - start)
import MathUtils as mu prime_tab = mu.genPrimeTab(1000000) k = 0 s = 2 pn = 0.0 total = 1.0 ratio = 100 while ratio > 0.1: len = 2 * k + 1 peri = 4 * len + 4 p = [ s + len, s + len + len + 1, s + len + 2 * (len + 1), s + len + 3 * (len + 1) ] total += 4 for pp in p: if mu.isPrimeAug(pp, prime_tab): pn += 1.0 ratio = pn / total k += 1 s += peri print(2 * (k - 1) + 3)
def test_Sigmoid(self): print("Testing Sigmoid") self.assertEqual(MathUtils.Sigmoid(0), 0.50000) self.assertAlmostEqual(MathUtils.Sigmoid(-3), 0.047426, 4)
import math import MathUtils prime_tab = MathUtils.genPrimeTab(1000000) print(len(prime_tab)) def GetFactors(num): factors = set([]) if num < 2: return factors while (not num in prime_tab): for factor in prime_tab: if factor > num: break remain = num * 1.0 / factor if int(remain) == remain: factors.add(factor) num = remain break if num > 1: factors.add(num) return factors def Result(): num = 2 consecutive_count = 0 while (consecutive_count < 4): factors = GetFactors(num)