def test_interpolation(self): x = [1.0, 2.5, 5] y = [2, 4, 6] new_x = [0.5 * i for i in range(11)] Interpolation().set_points(x=x, y=y) new_y = [Interpolation().interpolation_output(t) for t in new_x] plt.plot(x, y) plt.plot(new_x, new_y) plt.show() self.assertAlmostEqual(new_y[0], 0)
def __init__(self, filename, port, robot_name, zeros): #start action server self._base_topic = "" base_topic = self._base_topic self._robot_name = robot_name self._server = actionlib.SimpleActionServer(base_topic + "KeyframePlayer", KeyframePlayerAction, execute_cb=self.execute_cb, auto_start=False) self._face_pub = rospy.Publisher(base_topic + 'face_keyframes', FaceKeyframeRequest, queue_size=10) self._face_lookat = rospy.Publisher(base_topic + 'lookat', LookatRequest, queue_size=10) rospy.sleep(0.5) rospy.loginfo("Starting motor controller...") self.mc = MotorController(zeros, port) self.mc.set_a_all(0) rospy.loginfo("Success!") #read in behaviors and keyframes from json file to dictonary rospy.loginfo("Loading keyframes from file...") with open(filename, 'r') as data_file: data = json.load(data_file) self.KF_behavior_dict = data rospy.loginfo("Done loading keyframes.") self.i = Interpolation() self._current_pose = [0, 0, 0, 0, 0, 0] self.move_robot([0, 0, 0, 0, 0, 0], vlim=5) rospy.sleep(3.0) self._thread_dict = {"lookat": False, "idle": False} self._tb = tf.TransformBroadcaster() self._tl = tf.TransformListener() self._tf_thread = threading.Thread(target=self.pose_pub) self._tf_thread.start() #self._idle_thread = threading.Thread(target=self.idle) #self._idle_thread.start() self._thread_dict["idle"] = True self._thread_dict["preempt"] = False self._thread_dict["moving"] = True self._server.start() rospy.loginfo("Keyframe player server started.")
def test3g(self): # files = ['./testcases/3g3_m1.txt','./testcases/4g3_m2.txt'] # colide # check collision more times in long distance one # files = ['./testcases/g2_m1.txt','./testcases/3g2_m2.txt'] files = ['./testcases/4g3_m1.txt'] # files = ['./testcases/4g3_m2.txt'] # no result # files = ['./testcases/3g2_m2.txt','./testcases/3g3_m1.txt'] # use global is enough, or the last with local # files = ['./testcases/3g2_m1.txt','./testcases/3g2_m2.txt', './testcases/3g3_m1.txt'] files = [ './testcases/3g1_m0.txt', './testcases/3g1_m1.txt', './testcases/3g1_m2.txt', './testcases/4g1_m1.txt', './testcases/4g1_m2.txt', './testcases/3g2_m1.txt', './testcases/3g2_m2.txt', './testcases/3g3_m1.txt' ] for i in range(len(files)): fileName = files[i].split('/')[-1] sol = './out/' + fileName[:-4] + '_output.txt' prm = PRM(files[i]) flagPRM, ee1flag = prm.run_PRM(sol) # flagPRM=True if flagPRM: aa = test_robot(prm) qq = aa.load_output(sol) strlist = [] for j in qq: strlist.append(str(j)) # ee1flag=[] gginterpolat = Interpolation(strlist, ee1flag) interpolation_path = sol[:-4] + '_ip.txt' print("Run interpolation") gg = gginterpolat.run_Interpolate() write_sampling_config(interpolation_path, prm.num_segments, gg) result = tester_main(files[i], interpolation_path) if (result == 0): print(files[i] + ' success') else: print(files[i] + ' fails') else: print(files[i] + ' fails') result = 1 self.assertEqual(result, 0)
def new(self, pos, which_cur, pre_data=None, post_data=None): if which_cur == Curves.BEZIER_C0: self.selected = BezierC0(self.bz_points, self.bz_curves, self.bz_polygons) elif which_cur == Curves.BEZIER_C2: self.selected = BezierC2(self.bz_points, self.bz_curves, self.bz_polygons, self.bs_points, self.bs_curves, self.bs_polygons) elif which_cur == Curves.INTERPOLATION: self.selected = Interpolation() elif which_cur == Curves.SURFACE_C0: self.selected = SurfaceC0(pre_data, self.bz_points, self.bz_curves, self.bz_polygons) elif which_cur == Curves.SURFACE_C2: self.selected = SurfaceC2(pre_data, self.bz_points, self.bz_curves, self.bz_polygons) elif which_cur == Curves.SURFACE_PIPE: self.selected = Pipe(pre_data, self.bz_points, self.bz_curves, self.bz_polygons) elif which_cur == Curves.SURFACE_GREGORY: self.selected = GregoryGap(pre_data, self.bz_points, self.bz_curves, self.bz_polygons) self.selected.new(pos, post_data) self.add_child(self.selected) self.selected.set_screen_size(self.w, self.h)
def main(arglist): # def main(): inputfilename = arglist[0] sol = inputfilename + '_output.txt' # interpolation_path = sol[:-4] +'_ip.txt' interpolation_path = arglist[1] prm = PRM(inputfilename) flagPRM, ee1flag = prm.run_PRM(sol) # flagPRM=True aa = test_robot(prm) qq = aa.load_output(sol) strlist = [] for j in qq: strlist.append(str(j)) # ee1flag=[] gginterpolat = Interpolation(strlist, ee1flag) print("Run interpolation") gg = gginterpolat.run_Interpolate() write_sampling_config(interpolation_path, prm.num_segments, gg)
def test3g(self): files = ['./testcases/4g1_m1.txt'] for i in range(len(files)): fileName = files[i].split('/')[-1] sol = './out/' + fileName[:-4] + '_output.txt' prm = EST(files[i]) prm.run_EST(sol) aa = test_robot(prm) qq = aa.load_output(sol) strlist = [] for j in qq: strlist.append(str(j)) gginterpolat = Interpolation(strlist) interpolation_path = sol[:-4] + '_ip.txt' gg = gginterpolat.run_Interpolate() write_sampling_config(interpolation_path, prm.num_segments, gg) result = tester_main(files[i], interpolation_path) if (result == 0): print(files[i] + ' success') else: print(files[i] + ' fails') self.assertEqual(result, 0)
h3_tot.Add(h3) def returnContours(h): # https://root.cern/doc/master/classTHistPainter.html#HP16a h.Draw("CONT LIST") ROOT.gPad.Update() contours = ROOT.gROOT.GetListOfSpecials().FindObject("contours") graphs = [] for i in range(contours.GetSize()): g = contours.At(i).First() if g: g.SetFillColor(0) graphs.append(g) return copy.deepcopy(graphs) interpolate = Interpolation(p1,p2,p3) h4_tot = interpolate(h1_tot,h2_tot,'test') h1s_tot = interpolate.h1s h2s_tot = interpolate.h2s from IPython import embed #embed() for h1,h2,l1,l2,c1,c2 in zip([h1_tot,h1s_tot,h3_tot],\ [h2_tot,h2s_tot,h4_tot],\ [f"M_{{HH}} = {p1} GeV",f"M_{{HH}} = {p1} GeV (shifted at {p3} GeV)",f"M_{{HH}} = {p3} GeV (exact)"],\ [f"M_{{HH}} = {p2} GeV",f"M_{{HH}} = {p2} GeV (shifted at {p3} GeV)",f"M_{{HH}} = {p3} GeV (interpolated)"],\ [ROOT.kBlue+1,ROOT.kBlue+1,ROOT.kGreen+1],\ [ROOT.kRed+1,ROOT.kRed+1,ROOT.kMagenta+1]): h1.RebinX(20)
def main(): print( "\n----------------------Newton Backward Interpolation-------------------------\n\n" ) x_values = input('Give evenly separated x-values like 10 20 30 ...\t') x_values = x_values.split() for k in range(0, len(x_values)): try: x_values[k] = round(float(x_values[k]), 8) except ValueError: print("Sorry you give string") main() x_values.sort() h = round(float(x_values[1] - x_values[0]), 8) for i in range(1, len(x_values) - 1): if round(x_values[i + 1] - x_values[i], 8) != h: print( "Data points are not separated evenly. Please recheck and try again!!!" ) main() print( "-----------------------------------------------------------------------------\n\n\n" ) y_values = [] l = 0 while l < len(x_values): try: y = round( float( input('Give value of y corresponding to %s\t' % x_values[l])), 6) y_values.append(y) l += 1 except ValueError: print("Sorry you give string") l = l print( "-----------------------------------------------------------------------------\n\n\n" ) error = False while not error: try: x = float(input('Give Xs that you want to find: \t')) error = True except ValueError: print("Sorry you give string") error = False print( "-----------------------------------------------------------------------------\n\n\n" ) i = Interpolation(x_values, y_values, x) print( "----------------------------------End----------------------------------------\n\n\n" ) return
#! /usr/env python import sys from interpolation import Interpolation input_file_name = sys.argv[1] output_file_name = '' if len(sys.argv) > 2: output_file_name = sys.argv[2] ip = Interpolation() ip.from_file(input_file_name) ip.calculate() ip.render_output(output_file_name)
class SPRITEAnimator: # create messages that are used to publish feedback/result _feedback = cordial_sprite.msg.KeyframePlayerFeedback() _result = cordial_sprite.msg.KeyframePlayerResult() def __init__(self, filename, port, robot_name, zeros): #start action server self._base_topic = "" base_topic = self._base_topic self._robot_name = robot_name self._server = actionlib.SimpleActionServer(base_topic + "KeyframePlayer", KeyframePlayerAction, execute_cb=self.execute_cb, auto_start=False) self._face_pub = rospy.Publisher(base_topic + 'face_keyframes', FaceKeyframeRequest, queue_size=10) self._face_lookat = rospy.Publisher(base_topic + 'lookat', LookatRequest, queue_size=10) rospy.sleep(0.5) rospy.loginfo("Starting motor controller...") self.mc = MotorController(zeros, port) self.mc.set_a_all(0) rospy.loginfo("Success!") #read in behaviors and keyframes from json file to dictonary rospy.loginfo("Loading keyframes from file...") with open(filename, 'r') as data_file: data = json.load(data_file) self.KF_behavior_dict = data rospy.loginfo("Done loading keyframes.") self.i = Interpolation() self._current_pose = [0, 0, 0, 0, 0, 0] self.move_robot([0, 0, 0, 0, 0, 0], vlim=5) rospy.sleep(3.0) self._thread_dict = {"lookat": False, "idle": False} self._tb = tf.TransformBroadcaster() self._tl = tf.TransformListener() self._tf_thread = threading.Thread(target=self.pose_pub) self._tf_thread.start() #self._idle_thread = threading.Thread(target=self.idle) #self._idle_thread.start() self._thread_dict["idle"] = True self._thread_dict["preempt"] = False self._thread_dict["moving"] = True self._server.start() rospy.loginfo("Keyframe player server started.") def idle(self): current_pose = self._current_pose dofs = ['z', 'pa', 'ya'] dof_i = [2, 4, 5] movements = [1, 10, 10] last_direction = [1, 1, 1] while not rospy.is_shutdown(): if self._thread_dict["idle"] == False: rospy.sleep(0.1) else: i = random.choice(range(len(dofs))) target_dofs = [dofs[i]] target_positions = [[ current_pose[dof_i[i]] + last_direction[i] * movements[i] ]] last_direction[i] *= -1 self.move_through_frames(target_positions, [1.0], dofs=target_dofs) rospy.sleep(random.randrange(50, 400) / 100) def pose_pub(self): tf_rate = 1 / DELTA_T #hz r = rospy.Rate(tf_rate) while not rospy.is_shutdown(): pose = self._current_pose self._tb.sendTransform( (pose[0] / 100, pose[1] / 100, pose[2] / 100), tf.transformations.quaternion_from_euler( math.radians(pose[3]), math.radians(-pose[4]), math.radians(-pose[5])), rospy.Time.now(), "CoRDial/" + self._robot_name + "/platform_center", "CoRDial/" + self._robot_name + "/platform_zero") r.sleep() def move_robot(self, pose_6d, vlim=0, alim=0): rospy.loginfo("Moving to frame: " + str(pose_6d)) self.mc.set_a_all(alim) self.mc.set_v_all(vlim) frame = self.config_space(pose_6d) for m in range(6): if m % 2 == 1: frame[m] = -frame[m] for m in range(6): if self.mc.set_motor_angle(m, frame[m]): self._current_pose = pose_6d def lookat_point(self, pose3d, time=0): target = [i for i in self._current_pose] p, y = self.dir_to_point(pose3d, target) target[4] = p target[5] = -y keyframes = [target] times = [time] return self.move_through_frames(keyframes, times) def dir_to_point(self, pose3d, origin=[0, 0, 0]): x = pose3d[0] - origin[0] y = pose3d[1] - origin[1] z = pose3d[2] - origin[2] yaw = math.degrees(math.atan2(y, x)) pitch = math.degrees(math.atan2(z, math.sqrt(y * y + x * x))) return pitch, yaw def lookat_frame(self, frameid, time=0, vlim=0, alim=0): try: (trans, rot) = self._tl.lookupTransform( "CoRDial/" + self._robot_name + '/platform_zero', frameid, rospy.Time(0)) trans = map(lambda x: x * 100, trans) return self.lookat_point(trans) except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException): rospy.logwarn("Lookat server can't transform from frame " + frameid + " to " + "CoRDial/" + self._robot_name + '/platform_zero') return False def track_frame(self, frameid): rate = rospy.Rate(1) #Hz l = LookatRequest(follow_frame=True, frameid=frameid) self._face_lookat.publish(l) stop_lookat = False while not rospy.is_shutdown( ) and not self._server.is_preempt_requested() and not stop_lookat: self.lookat_frame(frameid) rate.sleep() stop_lookat = not self._thread_dict["lookat"] success = True if self._server.is_preempt_requested() or stop_lookat: l = LookatRequest(follow_frame=False) self._face_lookat.publish(l) rospy.loginfo('SPRITEAnimator: Preempted') self._server.set_preempted() if stop_lookat: success = True else: success = False return success def stop_tracking(self): self._thread_dict["lookat"] = False def adjust_timing(self, keyframes, times, max_v=50): #max_v in deg/s for i in range(len(keyframes) - 1): start = keyframes[i] target = keyframes[i + 1] motors_s = self.config_space(start) motors_t = self.config_space(target) d = [0, 0, 0, 0, 0, 0] for j in range(6): d[j] = abs(motors_t[j] - motors_s[j]) min_t = max(map(lambda dist: dist / max_v, d)) if times[i + 1] - times[i] < min_t: time_adj = min_t - (times[i + 1] - times[i]) rospy.logwarn( "Moving too quickly; adjusting frames after frame " + str(i) + " by " + str(time_adj) + " seconds") for j in range(i + 1, len(times)): times[j] = times[j] + time_adj return keyframes, times def time_adjusted_spline(self, keyframes, times, max_dx=60, max_dv=30): rospy.loginfo("Adjusting spline") spline = self.i.interpolate(keyframes, times) dt = 0.33 # 3Hz for initial check poses = self.i.get_poses(spline, dt) pre = poses[1:] post = poses[:-1] def broadcast_move_start(self): self._thread_dict["moving"] = True def broadcast_move_end(self): self._thread_dict["moving"] = False def catch_preemption(self): self._thread_dict["preempt"] = False def preempt_movement(self): if self._thread_dict["moving"] == True: self._thread_dict["preempt"] = True while self._thread_dict["preempt"]: rospy.sleep(0.05) rospy.sleep(0.1) def move_through_frames(self, keyframes, times, dofs=["x", "y", "z", "ra", "pa", "ya"]): self.broadcast_move_start() success = True r = rospy.Rate(1 / DELTA_T) # move to first pose TODO: LIMIT BY MOTOR SPEED start = self._current_pose all_dofs = ["x", "y", "z", "ra", "pa", "ya"] def fill_in_dofs(frame): outframe = [n for n in start] for i in range(len(dofs)): outframe[all_dofs.index(dofs[i])] = frame[i] return outframe keyframes = map(lambda f: fill_in_dofs(f), keyframes) keyframes = [start] + keyframes times = [0] + times if len(keyframes) == 2: check = False for i in range(6): check = check or not abs(keyframes[1][i] - keyframes[0][i]) < .01 if not check: rospy.logwarn("No movement needed; already at target") self.broadcast_move_end() return success keyframes, times = self.adjust_timing(keyframes, times) try: spline = self.i.interpolate(keyframes, times) except SystemError: rospy.logerr("Cannot interpolate; check your keyframes!") return False poses = self.i.get_poses(spline, DELTA_T) if self._server.is_preempt_requested( ) or self._thread_dict["preempt"] == True: rospy.loginfo('SPRITEAnimator: Preempted') self.catch_preemption() if self._server.is_preempt_requested(): self._server.set_preempted() success = False #TODO: clean up? else: #if no preempt, run the requested behavior goal start = rospy.Time.now() for i in range(len(poses)): if rospy.Time.now() - start > rospy.Duration(DELTA_T * i): continue frame = poses[i] if self._server.is_preempt_requested( ) or self._thread_dict["preempt"] == True: rospy.loginfo('SPRITEAnimator: Preempted') self.catch_preemption() success = False break else: #self.move_robot(frame) self.move_robot_timed(frame, DELTA_T) #TODO: publish TF r.sleep() self.broadcast_move_end() return success def move_robot_timed(self, pose_6d, time): rospy.loginfo("Moving to frame: " + str(pose_6d) + " in time " + str(time)) #self.mc.set_a_all(alim) #self.mc.set_v_all(vlim) frame = self.config_space(pose_6d) cur_frame = self.config_space(self._current_pose) #print "frame: " + str(cur_frame) for m in range(6): if m % 2 == 1: frame[m] = -frame[m] cur_frame[m] = -cur_frame[m] for m in range(6): speed = abs(cur_frame[m] - frame[m]) / time #print cur_frame[m]-frame[m] #print speed self.mc.set_speed(m, speed) if self.mc.set_motor_angle(m, frame[m]): self._current_pose = pose_6d def execute_cb(self, goal): rospy.loginfo("SPRITE Animator Server got goal: " + str(goal)) self._thread_dict["idle"] = False #self.preempt_movement() #only necessary if using idle success = True if goal.behavior == "lookat": l = LookatRequest(follow_frame=True, frameid=goal.args[0]) self._face_lookat.publish(l) time = 0 if len(goal.args) == 1 or len(goal.args) == 2: if len(goal.args) == 2: time = float(goal.args[1]) success = self.lookat_frame(goal.args[0], time=time) elif len(goal.args) == 4 or len(goal.args) == 3: if len(goal.args) == 4: time = float(goal.args[3]) success = self.lookat_point([ float(goal.args[0]), float(goal.args[1]), float(goal.args[2]) ], time=time) else: rospy.loginfo("Wrong number of arguments for lookat. Got: " + str(goal.args)) success = False rospy.sleep(0.5) l = LookatRequest(follow_frame=False, frameid=goal.args[0]) self._face_lookat.publish(l) elif goal.behavior == "watch": if len(goal.args) == 1: success = self.track_fame(goal.args[0]) else: rospy.loginfo("Wrong number of arguments for watch. Got: " + str(goal.args)) success = False elif goal.behavior == "watch_off": self.stop_tracking() elif goal.behavior == "headpose": if len(goal.args) == 3 or len(goal.args) == 4: time = 0 if len(goal.args) == 4: time = float(goal.args[3]) success = self.move_through_frames( [map(lambda s: float(s), goal.args)], [time], dofs=["ra", "pa", "ya"]) else: rospy.loginfo("Wrong number of arguments for watch. Got: " + str(goal.args)) success = False else: success = self.play_behavior(goal) #publish feedback of requested behavior if success: _feedback = goal.behavior self._server.publish_feedback(self._feedback) rospy.loginfo('SPRITEAnimator: Succeeded') self._server.set_succeeded(self._result) elif self._server.is_preempt_requested(): rospy.loginfo('SPRITEAnimator: Preempted') self._server.set_preempted() else: rospy.loginfo('SPRITEAnimator: Aborted') self._server.set_aborted() self._thread_dict["idle"] = True def play_behavior(self, goal): success = True behavior = goal.behavior if not behavior in self.KF_behavior_dict.keys(): rospy.logwarn("Invalid behavior: " + behavior + ", ignoring.") success = False else: frames = self.KF_behavior_dict[behavior]["keyframes"] keyframes = map(lambda f: f["pose"], frames) times = map(lambda f: float(f["time"]), frames) dofs = map(lambda s: str(s), self.KF_behavior_dict[behavior]["dofs"]) body_dofs = ["x", "y", "z", "ra", "pa", "ya"] body_indices = map(lambda d: dofs.index(d), filter(lambda s: s in dofs, body_dofs)) body_frames = map(lambda k: [k[j] for j in body_indices], keyframes) body_dofs = [dofs[i] for i in body_indices] face_indices = range(len(dofs)) for i in body_indices: face_indices.remove(i) if len(face_indices) > 0: face_frames = map(lambda k: [k[j] for j in face_indices], keyframes) face_frames = map(lambda l: Keyframe(positions=l), face_frames) face_dofs = [dofs[i] for i in face_indices] face_req = FaceKeyframeRequest(face_dofs=face_dofs, times=times, frames=face_frames) self._face_pub.publish(face_req) success = self.move_through_frames(body_frames, times, body_dofs) return success #takes a 1D array of 6 elements (x,x,y,u,v,w) and converts to hexapod terms def config_space(self, pose): x = -pose[0] y = pose[1] z = pose[2] u = pose[3] v = pose[4] w = pose[5] h = Hexapod() c = list(h.best_effort_ik(x, y, z, u, v, w)) return c #TODO - function needs def check_vel(x1, x2, dt): pass
vitessesY = [] abscisses = [] time = [] angles = [] vitesseAngulaire = [] rightSpeed = [] rightSpeedSetpoint = [] leftSpeed = [] leftSpeedSetpoint = [] speeds = (leftSpeed, rightSpeed) speedSetpoints = (leftSpeedSetpoint, rightSpeedSetpoint) interpolation = Interpolation() i = 0 posOver = False angleOver = False speedOver = [False, False] while (ligne != "DATAEND" and ligne): ligneEntiere = ligne ligne = ligne.split(",") ligne.insert(0, 0) #ligne.insert(0,0) #ligne.insert(0,0) if (len(ligne) == 7): try:
def makePlots(canvas, pdfName, m1, m2, m3, branches, cat, samples, xlabel): assert float(m1) < float(m2) assert float(m2) < float(m3) # if all([float(m)>=500 for m in [m1,m2,m3]]): # branch = 'HighMass' # elif all([float(m)<=500 for m in [m1,m2,m3]]): # branch = 'LowMass' # else: # raise RuntimeError(f'No mix in branch: m1={m1}, m2={m2}, m3={m3}') f1 = os.path.join(main_path.format(branch=branches[0], mass=m1), cat.format(mass=m1)) f2 = os.path.join(main_path.format(branch=branches[1], mass=m2), cat.format(mass=m2)) f3 = os.path.join(main_path.format(branch=branches[2], mass=m3), cat.format(mass=m3)) interpolate = Interpolation(float(m1), float(m3), float(m2)) hs = None for sample in samples: with TFileOpen(f1,'r') as F1, \ TFileOpen(f2,'r') as F2, \ TFileOpen(f3,'r') as F3: h_tmp = [ copy.deepcopy(F1.Get(sample.format(mass=m1))), copy.deepcopy(F2.Get(sample.format(mass=m2))), copy.deepcopy(F3.Get(sample.format(mass=m3))), ] if hs is None: hs = h_tmp else: for i in range(len(hs)): hs[i].Add(h_tmp[i]) names = [ f'True M_{{HH}} = {m1}', f'True M_{{HH}} = {m2}', f'True M_{{HH}} = {m3}', ] hs[0].SetLineColor(ROOT.kBlue + 1) hs[1].SetLineColor(ROOT.kOrange + 1) hs[2].SetLineColor(ROOT.kGreen + 1) # Interpolation # hs.insert(2, interpolate(hs[0], hs[2], 'interp')) names.insert(2, f'Interpolated M_{{HH}} = {m2}') hs[2].SetLineColor(ROOT.kRed + 1) hs[2].SetLineStyle(2) ints = [] errs = [] cdfs = [] hmax = 0. for h in hs: h.SetLineWidth(2) h.SetTitle(f"Shapes") h.GetXaxis().SetTitle(xlabel) cdf = copy.deepcopy(h) cdf.Scale(1. / cdf.Integral()) cdf = cdf.GetCumulative() cdf.SetTitle(f"CDF") cdf.GetXaxis().SetTitle(xlabel) cdf.GetYaxis().SetRangeUser(0, 1) cdfs.append(cdf) err = ctypes.c_double(0.) ints.append(h.IntegralAndError(1, h.GetNbinsX(), err)) errs.append(err.value) if h.GetNbinsX() > 200: h.Rebin(5) else: h.Rebin(1) hmax = max(hmax, h.GetMaximum()) hs[0].SetMaximum(hmax * 1.5) canvas.Clear() canvas.Divide(2) canvas.cd(1) #opt = 'HCP' opt = 'hist' for h in hs: h.Draw(opt) if 'same' not in opt: opt += ' same' leg1 = ROOT.TLegend(0.15, 0.6, 0.5, 0.9) for i in range(0, len(hs)): leg1.AddEntry( hs[i], f"#splitline{{{names[i]}}}{{Yield = {ints[i]:5.2f} +- {errs[i]:5.2f}}}" ) leg1.SetBorderSize(0) leg1.SetFillStyle(0) leg1.Draw() canvas.cd(2) opt = '' leg2 = ROOT.TLegend(0.15, 0.6, 0.55, 0.85) for i in range(0, len(hs)): cdfs[i].Draw(opt) if 'same' not in opt: opt += ' same' leg2.AddEntry(cdfs[i], names[i]) leg2.SetBorderSize(0) leg2.SetFillStyle(0) leg2.Draw() canvas.Print(pdfName)