def newerSectorializeDegrees(self, empirical_distribution, binomial, incident_degrees_, max_degree_empirical, minimum_count, num_agents): # compute bins [start, end] prob_min = minimum_count / num_agents llimit = 0 rlimit = 0 self.bins = bins = [] self.empirical_probs = empirical_probs = [] while (rlimit < len(incident_degrees_)): if (sum(empirical_distribution[llimit:]) > prob_min): prob_empirical = 0 while True: prob_empirical = sum(empirical_distribution[llimit:rlimit + 1]) if prob_empirical >= prob_min: break else: rlimit += 1 bins.append((llimit, rlimit)) empirical_probs.append(prob_empirical) rlimit += 1 llimit = rlimit else: # last bin print("last bin less probable than prob_min") rlimit = len(incident_degrees_) - 1 bins.append((llimit, rlimit)) prob_empirical = sum(empirical_distribution[llimit:rlimit + 1]) empirical_probs.append(prob_empirical) rlimit += 1 binomial_probs = [] for i, bin_ in enumerate(bins): llimit = bin_[0] rlimit = bin_[1] ldegree = incident_degrees_[llimit] - 1 rdegree = incident_degrees_[rlimit] binomial_prob = binomial.cdf(rdegree) - binomial.cdf(ldegree) binomial_probs.append(binomial_prob) # calcula probabilidades em cada bin # compara as probabilidades distribution_compare = list(A(empirical_probs) < A(binomial_probs)) self.binomial_probs = binomial_probs self.distribution_compare0 = distribution_compare if sum(distribution_compare): tindex = distribution_compare.index(True) tindex2 = distribution_compare[::-1].index(True) periphery_degrees = incident_degrees_[:tindex] intermediary_degrees = incident_degrees_[tindex:-tindex2] hub_degrees = incident_degrees_[-tindex2:] else: periphery_degrees = incident_degrees_[:] intermediary_degrees = [] hub_degrees = [] return periphery_degrees, intermediary_degrees, hub_degrees
def ft(img, x, y, ψ=ϕ, Δ=0b11): N, M = img.shape xx, yy = int(x), int(y) n, m = A(*rclp(xx - Δ, xx + Δ, N)), A(*rclp(yy - Δ, yy + Δ, M)) fx, fy = ψ(x - n), ψ(y - m) fxy = tendot(fx, fy, axes=0) img = img[clp(xx - Δ, N):clp(xx + Δ, N), clp(yy - Δ, M):clp(yy + Δ, M)] return tendot(fxy, img)
def __init__(self, flight_controller=None, verbose=True): """ Keeps track of the data and runs the simulation for a single flight """ # Simulation settings self.simulation_resolution = 0.1 # Size of time steps [s] (0.03=30fps for nice animations) self.max_runtime = 10.0 # Maximum allowed simulation time [s] self.gravitational_field = A([0.0, -9.81]) # Vector acc. due to gravity [m/s^2] self.verbose = verbose # Simulation verbosity True/False for printing updates on/off # Initialise the rocket self.rocket = Rocket() # Initial conditions # (all of these arrays will be appended to as the simulation runs) self.status = A([1]).astype('int') # Status (0=Crashed, 1=Flying, 2=Landed) self.angle = A([0.0]) # Angle of thrust (zero points to ground) [rads] self.time = A([0.0]) # Time [s] self.position = A([[0.0, 100]]) # Position vector [m] self.velocity = A([[0.0, 0.0]]) # Velocity vector [m/s] self.acceleration = A([self.gravitational_field]) # Acceleration vector [m/s^2] self.mass = A([self.rocket.hull_mass + # Total mass of rocket [kg] self.rocket.fuel_mass]) self.throttle = A([0.0]) # Throttle position (from 0 to 1, 1 being full power) # Check the flight controller function if callable(flight_controller): self.flight_controller = flight_controller else: self.flight_controller = template_controller
def newSectorializeDegrees(self, empirical_distribution, binomial_distribution, incident_degrees_): distribution_compare = A(empirical_distribution) < A( binomial_distribution) self.distribution_compare = distribution_compare tindex = list(distribution_compare).index(True) tindex2 = list(distribution_compare[::-1]).index(True) periphery_degrees = incident_degrees_[:tindex] intermediary_degrees = incident_degrees_[tindex:-tindex2] hub_degrees = incident_degrees_[-tindex2:] return periphery_degrees, intermediary_degrees, hub_degrees
def run(self): """ Runs the simulation given this flight's initial conditions and flight controller """ # Get the initital state vector state = self.state_vector(self.mode) i, done = 1, False # Start at time step 1 and run until max_runtime or the rocket lands/crashes while (not done) and (self.time[i - 1] < self.max_runtime): # Get the throttle position throttle = self.flight_controller(A([state])) # If rocket is out of fuel, cut the throttle if self.mass[i - 1] <= self.rocket.hull_mass: throttle = 0 # Update the flight based on the throttle chosen by the controller state, reward, done = self.update(throttle) # Print the current status if self.verbose: update_text = 'T: {:05.2f} | {:<6}'.format( self.time[i - 1] + self.simulation_resolution, self.status_string()) print('\r', update_text, end='') # Iterate i += 1
def thrust_parse(j, mode=0): """ j in binary gives the appropriate thrust selection: Translation: Input 0 1 2 4 5 6 Output... Main 0 0 0 1 1 1 2^2 Left 0 0 1 0 0 1 2^1 Right 0 1 0 0 1 0 2^0 """ if mode == 0: thrust = A([j, 0, 0]) else: if j > 2: k = j + 1 else: k = j thrust = A([x for x in '{0:03b}'.format(k)]).astype(int) return thrust
def update(self, throttle): """ Updates the position, velocity and mass of the rocket at each timestep, given the previous state and the current throttle setting """ # Set delta t for convenience dt = self.simulation_resolution # Mass expulsion needed to achieve the specified thrust delta_m = (throttle * self.rocket.max_thrust * dt) / self.rocket.exhaust_velocity[1] # Update the total mass self.mass = np.append(self.mass, [self.mass[-1] - delta_m]) # Update the throttle self.throttle = np.append(self.throttle, [throttle]) # Update the acceleration based on the mass expulsion above delta_v = self.rocket.exhaust_velocity * np.log(self.mass[-2] / self.mass[-1]) total_a = (delta_v / dt) + self.gravitational_field self.acceleration = np.append(self.acceleration, [total_a], axis=0) # Update the velocity, position and time self.velocity = np.append(self.velocity, [self.velocity[-1] + total_a * dt], axis=0) self.position = np.append(self.position, [self.position[-1] + self.velocity[-1] * dt], axis=0) self.time = np.append(self.time, [self.time[-1] + dt]) # Check if rocket has landed safely if ((self.position[-1][1] <= 0.0) and (norm(self.velocity[-1]) <= self.rocket.impact_velocity)): self.status = np.append(self.status, [2]) self.position[-1] = A([self.position[-1][0], 0])[np.newaxis, :] # Check if rocket has crashed elif self.position[-1][1] <= 0.0: self.status = np.append(self.status, [0]) self.position[-1] = A([self.position[-1][0], 0])[np.newaxis, :] else: self.status = np.append(self.status, [1])
def __init__(self): """ Holds all the constant attributes of the rocket Units for each quantity are in the square brackets """ self.hull_mass = 1000 # Mass of the rocket w/o fuel [kg] self.fuel_mass = 5000 # Initial mass of the fuel only [kg] self.width = 2 # Width [m] self.height = 20 # Height [m] self.impact_velocity = 5.0 # Speed above which rocket crashes on impact [m/s] self.exhaust_velocity = A([0, 200 * 9.81]) # Specific impulse of engine [s] self.max_thrust = 100000 # Maximum thust of engine [N]
def state_vector(self, mode): """ Returns the state vector for the current state. The state vector is different in each mode... 0 [y pos, y vel] 1 [x pos, y pos, x vel, y vel] 2 [x pos, y pox, x vel, y vel, angle, angular vel] All positions and velocities are normalised by the size of the simulation so that they're roughly around 0-1. """ if mode == 0: # state = A([ self.position[-1][1] / self.sim_scale, self.velocity[-1][1] / self.sim_scale ]) elif mode == 1: state = A([ self.position[-1][0] / self.sim_scale, self.position[-1][1] / self.sim_scale, self.velocity[-1][0] / self.sim_scale, self.velocity[-1][1] / self.sim_scale ]) elif mode == 2: state = A([ self.position[-1][0] / self.sim_scale, self.position[-1][1] / self.sim_scale, self.velocity[-1][0] / self.sim_scale, self.velocity[-1][1] / self.sim_scale, self.angle[-1] / np.pi, self.angular_v[-1] / np.pi ]) else: state = None return state
def produce_out(val_dl, model, int2en, int2spql, interval=(20, 30)): model.eval() x, y = next(iter(val_dl)) x, y = x.transpose(1, 0), y.transpose(1, 0) probs = seq2seq(V(x.long())) if isinstance(probs, tuple): probs = probs[0] preds = A(probs.max(2)[1].cpu()) for i in range(interval[0], interval[1]): print(' '.join([int2en[o] for o in x[:, i] if o not in [0, 1, 2]])) print(''.join([int2spql[o] for o in y[:, i] if o not in [0, 1, 2]])) print(''.join([int2spql[o] for o in preds[:, i] if o not in [0, 1, 2]])) print()
def __getitem__(self, idx): return A(self.x[idx]), A(self.y[idx])
# Copyright (c) 2013 Stefan Seefeld # All rights reserved. # # This file is part of OpenVSIP. It is made available under the # license contained in the accompanying LICENSE.BSD file. from vsip import vector from vsip import matrix from vsip.selgen.generation import ramp from vsip.math.matvec import dot, prod import numpy as np from numpy import array as A v1 = ramp(float, 0, 1, 8) v2 = ramp(float, 1, 2, 8) d = dot(v1, v2) assert d == np.dot(A(v1), A(v2)) v1 = vector(array=np.arange(4, dtype=float)) m1 = matrix(array=np.arange(16, dtype=float).reshape(4, 4)) m2 = matrix(array=np.arange(16, dtype=float).reshape(4, 4)) # vector * matrix v3 = prod(v1, m1) assert (A(v3) == np.tensordot(A(v1), A(m1), (0, 0))).all() # matrix * vector v3 = prod(m1, v1) assert (A(v3) == np.tensordot(A(m1), A(v1), (1, 0))).all() # matrix * matrix m3 = prod(m1, m2) assert (A(m3) == np.tensordot(A(m1), A(m2), (1, 0))).all()
def save_and_clear_input(): global Ans try: Ans=A(eval(input_var.get())) except: pass clear_input()
def update(self, throttle): """ Updates the position, velocity and mass of the rocket at each timestep, given the previous state and the current throttle setting """ # Set some numbers for convenience dt = self.simulation_resolution ve = self.rocket.exhaust_velocity # PHYSICS UPDATES ------------------------------------- # Convert throttle selection to vector: ([M, L, R]) M, L, R = thrust_parse(throttle, self.mode) delta_m_M = (M * self.rocket.main_thrust * dt) / ve delta_m_L = (L * self.rocket.side_thrust * dt) / ve delta_m_R = (R * self.rocket.side_thrust * dt) / ve # Update the total mass self.mass = np.append( self.mass, [self.mass[-1] - (delta_m_M + delta_m_L + delta_m_R)]) # Update the throttle self.throttle = np.append(self.throttle, [throttle]) # Update the acceleration based on the mass expulsion above # Note this calculation always uses the initial mass of the rocket # so the engine achieves the same acceleration regardless of how much fuel is in the rocket # Left/Right delta-v if self.mode < 2: delta_v_L = A([ve, 0]) * np.log( (self.mass[0] + delta_m_L) / self.mass[0]) delta_v_R = A([-ve, 0]) * np.log( (self.mass[0] + delta_m_R) / self.mass[0]) self.angular_v = np.append(self.angular_v, [0.0]) self.angle = np.append(self.angle, [0.0]) delta_v_M = A([0, ve]) * np.log( (self.mass[0] + delta_m_M) / self.mass[0]) total_a = ((delta_v_L + delta_v_R + delta_v_M) / dt) + self.gravitational_field # Angular delta-v else: delta_v_L = A([-ve]) * np.log( (self.mass[0] + delta_m_L) / (self.mass[0])) delta_v_R = A([ve]) * np.log( (self.mass[0] + delta_m_R) / (self.mass[0])) angular_a = (delta_v_L + delta_v_R) / (dt * self.rocket.height / 2) self.angular_v = np.append(self.angular_v, self.angular_v[-1] + angular_a * dt) self.angle = np.append( self.angle, angle_wrap(self.angle[-1] + self.angular_v[-1] * dt)) delta_v_M = A([ -ve * np.sin(self.angle[-1]), ve * np.cos(self.angle[-1]) ]) * np.log((self.mass[0] + delta_m_M) / (self.mass[0])) total_a = (delta_v_M / dt) + self.gravitational_field # Update the acceleration self.acceleration = np.append(self.acceleration, [total_a], axis=0) # Update the velocity, position and time self.velocity = np.append(self.velocity, [self.velocity[-1] + total_a * dt], axis=0) self.position = np.append(self.position, [self.position[-1] + self.velocity[-1] * dt], axis=0) self.time = np.append(self.time, [self.time[-1] + dt]) # Update the bounding rectangle self.b_h = np.append( self.b_h, A([ self.rocket.height * np.abs(np.cos(self.angle[-1])) + self.rocket.width * np.abs(np.sin(self.angle[-1])) ])) self.b_w = np.append( self.b_w, A([ self.rocket.height * np.abs(np.sin(self.angle[-1])) + self.rocket.width * np.abs(np.cos(self.angle[-1])) ])) # Collision check status_, done = self.status_check() self.status = np.append(self.status, [status_]) # Calculate the reward reward_ = self.reward_function(self) self.score = np.append(self.score, [reward_]) return self.state_vector(self.mode), reward_, done
def animate(self, filename, debug): hull_colour = '#3b4049' accent_colour = '#ffffff' thrust_colour = '#e28b44' # Intitialise figure booster_width = self.flight.rocket.width * 0.3 frame_scale = self.flight.sim_scale / 2 self.leg_height = self.flight.rocket.height * 0.2 self.fig, self.ax = subplots(figsize=(8, 8), dpi=150) self.ax.imshow(A([np.linspace(0.0, 1.0, 101)] * 101).T, cmap=plt.get_cmap('Blues'), vmin=0.0, vmax=2.0, origin='lower', extent=[-frame_scale, frame_scale, 0, 2 * frame_scale]) self.ax.set(xlim=[-frame_scale, frame_scale], ylim=[-10.0, 2 * frame_scale], ylabel='Altitude (m)', xlabel='', xticks=[]) self.ax.grid(False) # Find centre of rocket self.pos_x_0 = self.flight.position[0][0] self.pos_y_0 = self.flight.position[0][1] # Flight data telemetry = 'Status: {:>7s}\nT Vel: {:>7.2f}\nH Vel: {:>7.2f}\nV Vel: {:>7.2f}\nA Vel: {:>7.2f}\nScore: {:>7.2f}'.format( self.flight.status_string(0), norm(self.flight.velocity[0]), self.flight.velocity[0][0], self.flight.velocity[0][1], self.flight.angular_v[0], self.flight.score[0]) self.telemetry = self.ax.text(-0.9 * frame_scale, 1.9 * frame_scale, telemetry, ha='left', va='top', fontname='monospace', alpha=0.8) # Body of rocket self.body = Rectangle( (self.pos_x_0 - self.flight.rocket.width / 2, self.pos_y_0 - (self.flight.rocket.height / 2 - self.leg_height)), self.flight.rocket.width, self.flight.rocket.height - self.leg_height, angle=0.0, color=hull_colour, zorder=2) # Main thruster self.main = Ellipse( (self.pos_x_0, self.pos_y_0 - (self.flight.rocket.height / 2 - self.leg_height)), self.flight.rocket.width * 0.8, 2 * self.leg_height * thrust_parse(self.flight.throttle[0], mode=self.flight.mode)[0], angle=0.0, color=thrust_colour, zorder=1) # L Booster self.LBooster = Ellipse( (self.pos_x_0 - self.flight.rocket.width / 2, self.pos_y_0 + (0.5 * self.flight.rocket.height - 2 * booster_width)), self.flight.rocket.width * 2 * thrust_parse(self.flight.throttle[0], mode=self.flight.mode)[1], booster_width * 2, color=thrust_colour) # L Booster self.RBooster = Ellipse( (self.pos_x_0 + self.flight.rocket.width / 2, self.pos_y_0 + (0.5 * self.flight.rocket.height - 2 * booster_width)), self.flight.rocket.width * 2 * thrust_parse(self.flight.throttle[0], mode=self.flight.mode)[2], booster_width * 2, color=thrust_colour) # Legs self.legs = Polygon(A( [[ self.pos_x_0 - (self.flight.rocket.width / 2 + 0.5 * self.leg_height), self.pos_y_0 - self.flight.rocket.height / 2 ], [self.pos_x_0, self.pos_y_0 - 0.5 * self.leg_height], [ self.pos_x_0 + (self.flight.rocket.width / 2 + 0.5 * self.leg_height), self.pos_y_0 - self.flight.rocket.height / 2 ]]), closed=False, fill=False, edgecolor=hull_colour, zorder=1, lw=2.0) # Landing area self.ground = Rectangle((-frame_scale, -10), 2 * frame_scale, 10, color='#4c91ad', zorder=0) self.base = Rectangle((-self.flight.base_size, -5), 2 * self.flight.base_size, 5, color='#bdbfc1', zorder=1) # Draw objects to canvas self.patches = [ self.body, self.main, self.LBooster, self.RBooster, self.legs ] ts = self.ax.transData # Translate and rotate everything else tr = Affine2D().rotate_around(self.flight.position[0][0], self.flight.position[0][1], self.flight.angle[0]) transform = tr + ts if debug: self.com = self.ax.plot([self.pos_x_0], [self.pos_y_0], 'x', ms=20, lw=2.0) self.ax.plot(self.flight.position[:, 0], self.flight.position[:, 1], '--k', alpha=0.8) b_h = self.flight.rocket.height b_w = self.flight.rocket.height self.bbox = Rectangle( (self.pos_x_0 - b_w / 2, self.pos_y_0 - b_h / 2), b_w, b_h, edgecolor='k', fill=False, lw=2.0) self.ax.add_artist(self.bbox) for p in self.patches: self.ax.add_artist(p) p.set_transform(transform) self.ax.add_artist(self.ground) self.ax.add_artist(self.base) self.fig.tight_layout() # Add an extra second to the end of the animation extra_frames = int(1.0 / self.flight.simulation_resolution) # Animate the plot according to teh update function (below) movie = FuncAnimation( self.fig, self.update_animation, interval=(1000 * self.flight.simulation_resolution), frames=(len(self.flight.position + extra_frames)), fargs=[debug]) movie.save(filename)
def __init__(self, flight_controller=None, reward_function=None, verbose=True, mode=0): """ Keeps track of the data and runs the simulation for a single flight. Requires a flight controller (see starting notebook) and a reward function (see starting notebook). Verbose=True/False turns on/off printing the status as it runs. Can be run in one of three modes: 0 Vertical motion only, all horizontal motion set to zero. In this mode the throttle can only have two values: 0 Main booster off 1 Main booster on 1 As above plus left/right motion. The R/L boosters move the rocket L/R respectively. Throttle has six possible values: Throttle value 0 1 2 3 4 5 Booster M 0 0 0 1 1 1 L 0 0 1 0 0 1 R 0 1 0 0 1 0 2 As in mode 0 plus ACW/CW rotation. Throttle takes the same values as mode 1 but now the R/L boosters rotate the rocket ACW/CW respectively. """ # Initialise the rocket # Units for quantities are in [square brackets] self.rocket = Rocket() # Simulation constants self.simulation_resolution = 0.1 # dt [s] self.max_runtime = 30.0 # Max time before sim ends [s] self.gravitational_field = A([0.0, -9.81]) # Field strength [m/s^2] self.verbose = verbose self.sim_scale = 10.0 * self.rocket.height # Height of sim 'roof' [m] self.base_size = 20.0 # Size of the safe landing zone [m] self.mode = mode # Initial conditions # (all of these arrays will be appended to as the simulation runs) self.status = A([0]).astype('int') self.time = A([0.0]) self.score = A([0.0]) # Random starting position near the top of the screen initial_x = np.random.uniform(-self.sim_scale / 2 + self.rocket.height, self.sim_scale / 2 - self.rocket.height) initial_y = np.random.uniform(self.sim_scale / 2 + self.rocket.height, self.sim_scale - self.rocket.height) self.position = A([[initial_x * int(self.mode > 0), initial_y]]) # Initial angle pointing (more or less) towards the base initial_angle = np.arctan2(initial_x, initial_y) self.angle = A([initial_angle]) * int(self.mode == 2) # Initial angular velocity of zero self.angular_v = A([0.0]) # Random starting velocity in the direction of the base for mode==2, # completely random for mode==1 initial_v = np.random.uniform(-25.0, -10.0) initial_v_x = (np.sin(initial_angle) * initial_v * int(self.mode == 2)) + (int(self.mode == 1) * np.random.uniform(-10.0, 10.0)) initial_v_y = np.cos(initial_angle) * initial_v self.velocity = A([[initial_v_x * int(self.mode > 0), initial_v_y]]) # Initial a = g self.acceleration = A([self.gravitational_field]) # Initial mass = fuel + hull mass self.mass = A([self.rocket.hull_mass + self.rocket.fuel_mass]) # Throttle begins in the off position self.throttle = A([0]) # Bounding rectangle of the rocket for collision checks # (this has to rotate as the rocket rotates in mode 2) self.b_h = A([ self.rocket.height * np.abs(np.cos(self.angle[0])) + self.rocket.width * np.abs(np.sin(self.angle[0])) ]) self.b_w = A([ self.rocket.height * np.abs(np.sin(self.angle[0])) + self.rocket.width * np.abs(np.cos(self.angle[0])) ]) # Assign the passed functions self.flight_controller = flight_controller self.reward_function = reward_function
landA = [] scoreA = [] episodeA = [i for i in range(episodes)] for i in range(episodes+1): # Initialise a new flight. This randomises the initial conditions each time flight = Flight(flight_controller=flight_controller, reward_function=reward_function, mode=mode) # Get the initital state vector done, total_reward = False, 0 state = A([flight.state_vector(mode)]) # Update the flight until it crashes while not done: # Get the action from the flight controller action = flight_controller(state) # Update the flight and get the reward and the new state next_state, reward, done = flight.update(action) # Add the reward from the previous step to the total total_reward += reward # Transform the state vector (Keras only takes 2D) next_state = np.reshape(next_state, [1, input_size])
import pandas as pd from pathlib import Path import matplotlib.pyplot as plt plt.style.use('dark_background') from heapq import merge from multiprocessing import Pool import heapq from spectral_librarian.non_overlapping_intervals import OpenClosed, OpenOpen from spectral_librarian.cluster import PeakCluster, peak_distance_clusters, ppm_dist_clusters from spectral_librarian.array_ops import arrayfy from spectral_librarian.get_our_data import spectra_clusters from spectral_librarian.models import polyfit sp = max(spectra_clusters, key=len) MZ = A([p.mz for p in sp.peaks()]) N = A([p.spec_no for p in sp.peaks()]) dMZ = np.diff(MZ) def spectral_peak_repeats(peak_clusters): return Counter(cnt for pc in peak_clusters for cnt in pc.which_spectra().values()) def left_right_intervals(peak_clusters, d=0): L = []; R = [] for pc in peak_clusters: L.append(pc[ 0].mz-d) R.append(pc[-1].mz+d) return np.array(L), np.array(R) SPR = spectral_peak_repeats
ret = [] points = cutter.GetOutput().GetPoints() for i in range(points.GetNumberOfPoints()): point = points.GetPoint(i) ret.append(point) return ret if __name__ == "__main__": b1 = (0, 1, 0, 1, 0, 1) b2 = (0.3, 1.7, 1.25, 2.25, 2.75, 4) c1 = addCube(b1, (1, 0, 0)) c2 = addCube(b2, (0, 1, 0)) l = A(c2.GetCenter()) - A(c1.GetCenter()) p1 = cut(c1, l) p2 = cut(c2, l) ''' for q in p1: for p in p2: addLine(p,q, (1,1,1)) ''' pts = [] for i in [0, 1]: for j in [2, 3]: for k in [4, 5]: #addLine((b1[i], b1[j], b1[k]), (b2[i], b2[j], b2[k]), (1,1,1)) pts.append((b1[i], b1[j], b1[k]))
from pathlib import Path import matplotlib.pyplot as plt plt.style.use('dark_background') from heapq import merge from multiprocessing import Pool import heapq from spectral_librarian.get_data import list_spectra_clusters from spectral_librarian.non_overlapping_intervals import OpenClosed, OpenOpen from spectral_librarian.cluster import PeakCluster, peak_distance_clusters from spectral_librarian.array_ops import arrayfy from spectral_librarian.get_our_data import spectra_clusters max_cluster = max(spectra_clusters, key=len) MZ = A([p.mz for p in max_cluster.peaks()]) dMZ = np.diff(MZ) for pc in peak_distance_clusters(self.peaks(), initial_distance): if len(pc) > len(self)*quorum and pc.peaks_from_different_spectra(): distance = max_cluster.refine_intracluster_distance(.1, 0.95) PC = list(max_cluster.peak_clusters(.9, distance)) max_pc = max(PC, key=len) # problem still there l_pc, r_pc = max_pc.split(233.153) l_pc.which_spectra()