Пример #1
0
class LMSAdaptiveFilter:
    """ 
    The LMS Adaptive Filter.
    """

    def __init__(self, order, damping=0.5):
        self.order = order
        self.damping = damping
        self.X = Signal(order)
        self.Y = Signal(order)
        self.weights = [0] * order

    def is_signal_outlier(self, sig):
        X = np.array(self.X.signal)
        weights = np.array(self.weights)
        yest = weights.dot(X)
        c = (1.0 * (sig - yest)) / (1. * X.dot(X))
        weights = weights + self.damping * c * X
        self.X.add(sig)
        self.weights = list(weights)
        return self._check_est(yest)

    def _check_est(self, est):
        if self.Y.can_use():
            return est >= (2.0 * self.Y.sigma() + self.Y.mean())
        return False
    def move(self, Data_Point):
        t0 = self.drone.location()
        max_Location = Data_Point.get_Location()
        max_Signal = Data_Point.get_Signal()
        direction_of_travel = [
            max_Location[0] - t0[0], max_Location[1] - t0[1],
            max_Location[2] - t0[2]
        ]

        print(
            "\n\nDrone will move in %s --> %s direction and it is in %s location relative to its starting position"
            % (Data_Point.id, direction_of_travel, self.drone.location()))

        self.drone.moveFr(direction_of_travel[0] * 2)
        self.drone.moveRi(direction_of_travel[1] * 2)
        self.drone.moveUp(direction_of_travel[2] * 2)

        while (Signal(self.drone).calcSS() > max_Signal):
            max_Signal = Signal(self.drone).calcSS()
            self.drone.moveFr(direction_of_travel[0])
            self.drone.moveRi(direction_of_travel[1])
            self.drone.moveUp(direction_of_travel[2])

        self.drone.moveFr(direction_of_travel[0] * -1)
        self.drone.moveRi(direction_of_travel[1] * -1)
        self.drone.moveUp(direction_of_travel[2] * -1)
Пример #3
0
class Action(object):

    def __init__(self):
        super(Action, self).__init__()
        self._duration = 3.0
        self.execute_finished_signal = Signal()

    def get_duration(self):
        return self._duration

    def set_duration(self, duration):
        self._duration = duration

    #@abstractmethod
    def to_string(self):
        pass

    def deepcopy(self):
        action = self.__class__()
        action._duration = self._duration
        return action

    def serialize(self, stream):
        stream.serialize_data(self._duration)

    def deserialize(self, stream):
        self._duration = stream.deserialize_data()

    #@abstractmethod
    def execute(self):
        pass

    def _execute_finished(self):
        self.execute_finished_signal.emit()
Пример #4
0
def aliases_figure(f0, fs):
    t = np.linspace(0, 1, 50*fs)
    y = np.sin(f0 * 2*np.pi * t)
    sig = Signal(t, y)
    alias_sig = Signal(t, y)

    fig = sig.get_fig(size=(1080,300),title="Aliases of {} Hz signal".format(f0))
    alias_sig.update_line_opts({'line_color' : 'orange', 'line_alpha': 1})
    alias_sig.create_line_renderer(fig)

    alias_x = np.linspace(0, 1, fs, endpoint=False)
    alias_y = np.sin(f0 * 2*np.pi * alias_x)
    alias_points = ColumnDataSource({
        'x' : alias_x,
        'y' : alias_y,
        'y0': np.zeros(alias_x.size)
    })
    fig.circle(x='x', y='y', source=alias_points, fill_color='red', line_width=3, line_color='red')
    fig.segment(x0='x', x1='x', y0='y0', y1='y', source=alias_points,line_width=3, line_color='red')
    handle = show(fig, notebook_handle=True)

    def frame_gen(fv):
        return {'y': np.sin(fv*2*np.pi*t)}

    anim_sets = []
    for k in range(1, 6):
        f_previous = f0 + (k-1)*fs
        f_alias = f0 + k*fs
        frame_values = np.linspace(f_previous, f_alias, 60)
        anim = FrameAnimation(alias_sig.data_source(), frame_gen, frame_values)
        anim_sets.append(AnimationSet([anim]))
        anim_sets.append(AnimationSet([Pause(1)]))

    AnimateSets(anim_sets, handle).run()
Пример #5
0
def lorenz_example():
    '''Time Setting'''
    T = 20
    fs = 20
    dt = 1/fs
    
    '''Training Signal Setting'''
    signal_type = Lorenz(dt=dt, X0=[1.,1.,1.])
    signal = Signal(signal_type=signal_type, T=T)
    observer = Reservoir(dt=signal.dt, n=signal.Y.shape[0], m=signal.X.shape[0], alpha=0.2, beta=1e-8)
    observer.train(signal.Y, signal.X, show_time=False)

    '''Testing Signal Setting'''
    signal_type = Lorenz(dt=dt, X0=signal.X[:,-1])
    # signal_type = Lorenz(dt=dt, X0=np.random.uniform(-1,1,3))
    signal = Signal(signal_type=signal_type, T=T)
    X_hat = observer.run(signal.Y, show_time=False)

    fontsize = 20
    fig, axes = plt.subplots(3,1,figsize=(8,8), sharex=True)
    axes[0].plot(signal.t, signal.X[0], label=r'$U=x_1$')
    axes[0].legend(fontsize=fontsize-5, loc='lower right')
    axes[0].tick_params(labelsize=fontsize)
    for n in range(2):
        axes[n+1].plot(signal.t, signal.X[n+1], label=r'$x_{}$'.format(n+2))
        axes[n+1].plot(signal.t, X_hat[n+1], label=r'$\hat x_{}$'.format(n+2))
        axes[n+1].legend(fontsize=fontsize-5, loc='lower right', ncol=2)
        axes[n+1].tick_params(labelsize=fontsize)
    fig.add_subplot(111, frameon=False)
    plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
    plt.xlabel('\ntime $t$ [s]', fontsize=fontsize)
    plt.show()
    pass
Пример #6
0
    def __init__(self, context: SignalContext):
        Signal.__init__(self, context)
        TruncatingMixin.__init__(self)
        TilingMixin.__init__(self)

        self.buffer = np.array(self.data.data['buffer'], dtype=float)
        self.fs = int(self.data.data['fs'])
Пример #7
0
    def filter(self, input):
        output = Signal()
        output.y = sig.sosfilt(self.values, input.y)

        #print('***** Salida del filtro *****')
        #print(output.y)

        return output
Пример #8
0
 def __init__(self, n=10, k1=0.5, k2=0.5):
     Signal.__init__(self)
     self.set_type(Signal.Type.BAND)
     self.set_name('Dual Thrust')
     self.params = dict({DualThrust.N: n, DualThrust.K1: k1, DualThrust.K2: k2})
     self.d = None
     self.type = Signal.Type.BAND
     logger.info('Created signal %s' % self.name)
Пример #9
0
 def __init__(self, context: SignalContext):
     Signal.__init__(self, context)
     self.filter_cache: FilterCache = {}
     self.log = logging.getLogger(__name__)
     self.ht_cache = {}
     self.child = self.data.resolved_refs['child']
     self.target_fs = self.data.data['target_fs']
     self.source_fs = self.child.get_fs()
Пример #10
0
    def __init__(self, fc, tfiltro):
        self.fc = fc
        self.tfiltro = tfiltro

        #Inicializo una señal S1
        self.S1 = Signal()

        #Inicializo una señal S2
        self.S2 = Signal()
def generate_signals(a_timer: PipelineTimer,
                     arb_id_dict: dict,
                     signal_pickle_filename: str,
                     normalize_strategy,
                     force=False):
    if path.isfile(signal_pickle_filename):
        if force:
            # Remove any existing pickled Signal dictionary and create one.
            remove(signal_pickle_filename)
        else:
            print(
                "\nSignal generation already completed and forcing is turned off. Using pickled data..."
            )
            return load(open(signal_pickle_filename, "rb"))

    a_timer.start_function_time()

    signal_dict = {}

    for k, arb_id in arb_id_dict.items():
        if not arb_id.static:
            for token in arb_id.tokenization:
                a_timer.start_iteration_time()

                signal = Signal(k, token[0], token[1])

                # Convert the binary ndarray to a list of string representations of each row
                temp1 = [
                    ''.join(str(x) for x in row)
                    for row in arb_id.boolean_matrix[:, token[0]:token[1] + 1]
                ]
                temp2 = zeros((temp1.__len__(), 1), dtype=uint64)
                # convert each string representation to int
                for i, row in enumerate(temp1):
                    temp2[i] = int(row, 2)

                # create an unsigned integer pandas.Series using the time index from this Arb ID's original data.
                signal.time_series = Series(temp2[:, 0],
                                            index=arb_id.original_data.index,
                                            dtype=float64)
                # Normalize the signal and update its meta-data
                signal.normalize_and_set_metadata(normalize_strategy)
                # add this signal to the signal dictionary which is keyed by Arbitration ID
                if k in signal_dict:
                    signal_dict[k][(arb_id.id, signal.start_index,
                                    signal.stop_index)] = signal
                else:
                    signal_dict[k] = {
                        (arb_id.id, signal.start_index, signal.stop_index):
                        signal
                    }

                a_timer.set_token_to_signal()

    a_timer.set_signal_generation()

    return signal_dict
Пример #12
0
def scramble(signal, algorythm):
    scrambledsignal = Signal(signal)

    if algorythm == "B8ZS":
        i = 0
        while i < (len(scrambledsignal.signal) - 7):
            if zeros(scrambledsignal, i, 8):
                scrambledsignal.voltage[i + 3] = 'V'
                scrambledsignal.voltage[i + 4] = 'B'
                scrambledsignal.voltage[i + 6] = 'B'
                scrambledsignal.voltage[i + 7] = 'V'
                i += 7
            i += 1
    else:
        i = 0
        j = 0
        while i < (len(scrambledsignal.signal) - 3):
            if scrambledsignal.signal[i] == '1':
                j += 1
            if zeros(scrambledsignal, i, 4):
                if j % 2 == 0:
                    scrambledsignal.voltage[i] = 'B'
                    scrambledsignal.voltage[i + 3] = 'V'
                    j = 0
                    i += 3
                elif j % 2 == 1:
                    scrambledsignal.voltage[i + 3] = 'V'
                    j = 0
                    i += 3
            i += 1

    return scrambledsignal
Пример #13
0
 def __init__(self):
     self.axes_changed = Signal()
     self.buttons_changed = Signal()
     self._axes = None
     self._buttons = None
     self._pressed_buttons = set()
     self._last_larm = None
     self._last_rarm = None
     self._last_lgrip = None
     self._last_rgrip = None
     rospy.Subscriber('korg_joy', Joy, self._joy_callback)
Пример #14
0
 def __init__(self, signals_dict, selected_signal_name):
     self.signals_dict = signals_dict
     self.my_signal_name = selected_signal_name
     #Make a copy of the original signal
     self.my_signal = Signal(selected_signal_name,
                             self.signals_dict[selected_signal_name]._signal_data.copy(),
                             self.signals_dict[selected_signal_name]._signal_type,
                             self.signals_dict[selected_signal_name]._signal_data_type)
     
     super(EditSignalWindow, self).__init__()
     self.setupUi(self)
     self.initUI()
Пример #15
0
    def __init__(self,
                 h5filename='test.h5',
                 prime1=20,
                 run_steps=10000,
                 write_interval=5000,
                 **kwargs):
        self.signal = Signal()
        self.exchange = orderbook.Orderbook(self.signal)
        self.h5filename = h5filename
        self.run_steps = run_steps + 1
        self.liquidity_providers = {}
        self.noise = kwargs.pop('Noise')
        # Set up noise traders
        if self.noise:
            self.noise_traders = self.buildNoiseTraders(
                kwargs['numNoise'], kwargs["NoiseSigma"])
            self.Lambda_nt = kwargs['Lambda_nt']
        # Set up fundamental traders
        self.fundamental = kwargs.pop("Fundamental")
        if self.fundamental:
            self.fundamentals = self.buildFundamentalTraders(
                kwargs['numFund'], kwargs["omega_Fund"], kwargs["FundSigma"])
            self.Lambda_ft = kwargs["Lambda_ft"]
        # Set up momentum traders
        self.momentum = kwargs.pop("Momentum")
        if self.momentum:
            self.momentums = self.buildMomentumTraders(kwargs["numMom"],
                                                       kwargs["omega_Mom"],
                                                       kwargs["MomInvLim"],
                                                       kwargs["MomTimeWindow"],
                                                       kwargs["shapeMom"])
            self.Lambda_mt = kwargs["Lambda_mt"]
        # Set up Market Makers
        self.marketmaker = kwargs.pop("MarketMaker")
        if self.marketmaker:
            self.marketmakers = self.buildMarketMakers(
                kwargs["numMMs"], kwargs["KatRisk"], kwargs["MMgamma"],
                kwargs["K"], kwargs["MMa"], kwargs["MMr"], kwargs["MMn"],
                kwargs["MMs"], kwargs["MMdelta"], kwargs["MMwindow"],
                kwargs["MMc"])
            self.Lambda_mm = kwargs["Lambda_mm"]

        self.traders, self.num_traders = self.makeAll()
        self.seedOrderbook()
        #        if self.provider:
        #            self.makeSetup(prime1, kwargs['Lambda0'])
        #        if self.pj:
        #            self.runMcsPJ(prime1, write_interval)
        #        else:
        self.runMcs(prime1, write_interval)
        self.exchange.trade_book_to_h5(h5filename)
        self.qTakeToh5()
        self.mmProfitabilityToh5()
Пример #16
0
    def convolution(signal1, signal2):
        result_points = []

        for n in range(len(signal1.points) + len(signal2.points) - 1):
            y = 0
            for k in range(len(signal1.points)):
                if 0 <= n - k < len(signal2.points):
                    y += signal1.points[k].y * signal2.points[n - k].y
            result_points.append(Point(n, y))

        result_signal = Signal(None, 0, len(signal1.points) + len(signal2.points) - 1, 1)
        result_signal.points = result_points
        return result_signal
Пример #17
0
 def quantization(signal, Ts, n_bits):
     result_signal = Signal(None, None, None, None)
     result_signal.points = signal.quantization(Ts, n_bits)
     signal_to_draw = Signal(None, None, None, None, False)
     signal_to_draw.points.append(signal.points[0])
     new_ts = Ts / 2
     for i in range(1, len(signal.points)):
         signal_to_draw.points.append(
             Point(signal.points[i - 1].x + new_ts, signal.points[i - 1].y))
         signal_to_draw.points.append(
             Point(signal.points[i - 1].x + new_ts, signal.points[i].y))
     signal_to_draw.points.append(signal.points[-1])
     return result_signal, signal_to_draw
Пример #18
0
class Ps3Subscriber(object):

    top_button = 'top'
    right_button = 'right'
    bottom_button = 'bottom'
    left_button = 'left'

    select_button = 'select'
    start_button = 'start'

    square_button = 'square'
    triangle_button = 'triangle'
    cross_button = 'cross'
    circle_button = 'circle'

    def __init__(self):
        self.buttons_changed = Signal()
        self._buttons = None
        self._pressed_buttons = set()
        rospy.Subscriber('ps3_joy', Joy, self._joy_callback)

    def _joy_callback(self, joy_msg):
        if self._buttons != joy_msg.buttons:
            self._buttons = joy_msg.buttons
            self.buttons_changed.emit()

    def get_triggered_buttons(self):
        buttons = {
            4: self.top_button,
            5: self.right_button,
            6: self.bottom_button,
            7: self.left_button,
            0: self.select_button,
            3: self.start_button,
            15: self.square_button,
            12: self.triangle_button,
            14: self.cross_button,
            13: self.circle_button,
        }
        triggered = set()
        for index, value in enumerate(self._buttons):
            if index in buttons.keys():
                index = buttons[index]
            if value != 0:
                if index not in self._pressed_buttons:
                    self._pressed_buttons.add(index)
                    triggered.add(index)
            else:
                if index in self._pressed_buttons:
                    self._pressed_buttons.remove(index)
        return triggered
Пример #19
0
 def read_file(file_path):
     with open(file_path, 'r') as file:
         start_time = file.readline()
         duration_time = file.readline()
         frequency = file.readline()
         points = file.readline()
         points = points.split()
         signal_points = []
         for i in range(0, len(points), 2):
             signal_point = Point(float(points[i]), float(points[i + 1]))
             signal_points.append(signal_point)
         result = Signal(None, start_time, duration_time, frequency)
         result.points = signal_points
         return result
Пример #20
0
    def insertBuffer(self, target):
        for line in target:
            color = Signal.parseSignal(line)[0]
            if not color:
                return;
            location = Signal.parseSignal(line)[1]
            theTime = str(Signal.parseSignal(line)[2])

            #SQL Date format: YYYY-MM-DD
            splitResult = self.currentDate.split("_")
            theDate = splitResult[2] + "-" + splitResult[1] + "-" + splitResult[0]
            query = "INSERT INTO " + self.currentDate + " VALUES ( " + "'" + color + "'" + " ," + "'" + location + "'" + " ," + "'" + theDate + "'" + " ," + "'" + theTime + "'" + ");"
            self.cursor.execute(query)
            # Commit your changes in the database
            self.db.commit()
Пример #21
0
    def __init__(self, master):
        self._job = None
        self.max_time = 500
        # Create a container
        self.frame = Tkinter.Frame(master)
        self.master = master
        # Create 2 buttons
        self.kp = Tkinter.Scale(self.frame,
                                from_=1.,
                                to=10.,
                                resolution=0.1,
                                label="K  ",
                                command=self.resetparam)
        self.kp.pack()

        self.tau = Tkinter.Scale(self.frame,
                                 from_=1.,
                                 to=10.,
                                 resolution=0.1,
                                 label="τ   ",
                                 command=self.resetparam)
        self.tau.pack()

        self.theta = Tkinter.Scale(self.frame,
                                   from_=1.,
                                   to=9.,
                                   resolution=0.5,
                                   label="θ",
                                   command=self.resetparam)
        self.theta.pack()

        self.fig = Figure((10, 5))
        self.ax = self.fig.add_subplot(111)
        self.ax.set_xlim(0, 500)

        self.fig2 = Figure((10, 5))
        self.ax2 = self.fig2.add_subplot(111)

        sig = Signal(1, 1, 2, numPlots=0)
        sig.sys_simulation()
        self.masterRS = RollingSignal()
        self.masterRS.load_model(
            sig,
            directory=
            '/Users/RileyBallachay/Documents/Fifth Year/RNNSystemIdentification/Model Validation/MIMO 1x1/Checkpoints/'
        )

        self._roll_over(initial=True)
    def add_ase(self, signal: Signal):
        '''

        :param signal:the edfa's input signal, if the signal is wdm, then the lambda will use
        center lambda, correction needed in the future
        :return:
        '''

        if check_array.isscalar(signal.center_lambda_in_m):
            sigma = np.sqrt(self.nf_lin * PLANK * CLIGHT /
                            signal.center_lambda_in_m * (self.gain_lin - 1) *
                            signal.sps * signal.symbol_rate_in_hz)
        else:
            max_lam = np.max(signal.center_lambda_in_m)
            min_lam = np.min(signal.center_lambda_in_m)
            center = 2 * max_lam * min_lam / (max_lam + min_lam)
            sigma = np.sqrt(self.nf_lin * PLANK * CLIGHT / center *
                            (self.gain_lin - 1) * signal.sps *
                            signal.symbol_rate_in_hz)

        noise = 0.5 * sigma * (
            np.random.randn(2, signal.sps * signal.data_len) +
            1j * np.random.randn(2, signal.sps * signal.data_len))

        signal.data_sample = signal.data_sample + noise
Пример #23
0
 def sendSignal(self):           
     #send date, time and id
     #need to send to queue instead 
     dateTime = datetime.datetime.utcnow()
     print dateTime
     self.__signal = Signal.initializeSignal(self.__ID, self.__Location, dateTime)
     self.setEmptyFlag(False)
Пример #24
0
 def __init__(self, context: SignalContext):
     Signal.__init__(self, context)
     self.num_taps = int(self.data.data["num_taps"])
     self.band_start = Hz(self.data.data["band_start"])
     self.band_stop = Hz(self.data.data["band_stop"])
     self.child = self.data.resolved_refs["child"]
     self.window = self.data.data["window"]
     self.ht_cache = {}
     self.target_fs = int(self.data.data["fs"])
     self.ht = firwin(
         self.num_taps,
         cutoff=(self.band_start, self.band_stop),
         window=self.window,
         fs=self.target_fs,
         pass_zero='bandpass',
     )
    def probe(self):
        print("Drone will start probing")

        if (Signal(self.drone).calcSS() > 0):
            print("\n\nThe drone found signal at %s" % (self.drone.location()))
            return self.run()

        self.drone.moveFr(100)
        if (Signal(self.drone).calcSS() > 0):
            print("\n\nThe drone found signal at %s" % (self.drone.location()))
            return self.run()

        self.drone.moveRi(100 * -1)
        if (Signal(self.drone).calcSS() > 0):
            print("\n\nThe drone found signal at %s" % (self.drone.location()))
            return self.run()

        self.drone.moveFr(100 * -1)
        if (Signal(self.drone).calcSS() > 0):
            print("\n\nThe drone found signal at %s" % (self.drone.location()))
            return self.run()

        self.drone.moveFr(100 * -1)
        if (Signal(self.drone).calcSS() > 0):
            print("\n\nThe drone found signal at %s" % (self.drone.location()))
            return self.run()

        self.drone.moveRi(100)
        if (Signal(self.drone).calcSS() > 0):
            print("\n\nThe drone found signal at %s" % (self.drone.location()))
            return self.run()

        self.drone.moveRi(100)
        if (Signal(self.drone).calcSS() > 0):
            print("\n\nThe drone found signal at %s" % (self.drone.location()))
            return self.run()

        self.drone.moveFr(100)
        if (Signal(self.drone).calcSS() > 0):
            print("\n\nThe drone found signal at %s" % (self.drone.location()))
            return self.run()

        self.drone.moveFr(100)
        if (Signal(self.drone).calcSS() > 0):
            print("\n\nThe drone found signal at %s" % (self.drone.location()))
            return self.run()

        self.drone.moveRi(100 * -1)
        self.drone.moveFr(100 * -1)

        print("No animal was found on probing\n\n")
Пример #26
0
 def zoh(signal):
     reconstructed_signal = Signal(None, None, None, None, False)
     reconstructed_signal.points.append(signal.points[0])
     for i in range(1, len(signal.points)):
         reconstructed_signal.points.append(
             Point(signal.points[i].x, signal.points[i - 1].y))
         reconstructed_signal.points.append(signal.points[i])
     return reconstructed_signal
Пример #27
0
 def visualizeSignal(self):
     # Keep input data in case of modifications
     viz_signal_data = self.input_data.copy()
     if len(self.selected_variables) > 0 : 
         viz_signal_data = viz_signal_data.loc[:,self.selected_variables]
         viz_signal_data = pd.DataFrame(viz_signal_data.values, viz_signal_data.index, self.selected_variables)
         
         # get signal's type
         viz_signal_type = 0 if(len(viz_signal_data.columns) == 1) else 1
         
         viz_signal = Signal(str(self.lineEdit_signal_name.text()), viz_signal_data, viz_signal_type, self.my_data_type)
         viz_signal.plot_signal()
     else :
         mess = QtGui.QMessageBox.warning(self,
                         'Warning Message',
                         "You must define at least one variable to plot.")
         return
Пример #28
0
def verify_fs(*args: Signal, **kwargs: Signal):
    pairs = []
    for name, child in kwargs.items():
        pairs.append((name, child.get_fs()))
    for idx, child in enumerate(args):
        pairs.append((idx, child.get_fs()))

    if len(set(map(lambda pair: pair[1], pairs))) > 1:
        raise ValueError(f"Child signals do not have matching FS: {pairs}")
Пример #29
0
class GameLoop():
    
    """
    Primary Game Loop class
    
    DO NOT USE ATTRIBUTES ON YOUR OWN!
    USE METHODS INSTEAD!
    """

    __instance = None
    _update_signal = Signal()
    _cancelation_token = False

    @staticmethod
    def getInstance():
        """Gets instance of GameLoop class. GameLoop is a singleton."""
        if GameLoop.__instance==None:
            GameLoop()
        return GameLoop.__instance

    def __new__(cls):
        if cls.__instance is None:
            cls.__instance = super(GameLoop, cls).__new__(cls)
            cls.__instance._start_loop()
        return cls.__instance

    def connect_to_update(self, method):
        """Use this method to connect your method to primary game loop"""
        self._update_signal.connect(method)

    def disconnect_from_update(self,method):
        self._update_signal.disconnect(method)

    def _start_loop(self):
        """
        Starts the game loop.
        Not necessary to start it yourself.
        It starts automatically on class creation.
        """
        self.p = tread.Thread(target=self._loop)
        self.p.start()

    def cancel(self):
        """
        Stops Game Loop.
        After this is called you will need to manualy call the _start_loop() method to restart the Game Loop.
        """
        GameLoop.getInstance()._cancelation_token = True

    def _loop(self):
        """Do not call this method!"""
        while True:
            if GameLoop.getInstance()._cancelation_token==True:
                break
            self._update_signal.notify_all()
            sleep(1/60)
Пример #30
0
 def add_output(self, nm, **kwargs):
     """This will create a signal ending in _s and an output ending in _o, drive the signal with the
     expression, and drive the """
     y0 = Signal(nm + "_s", **kwargs)
     y1 = Signal(nm + "_o", **kwargs)
     self.signals.add(y0)
     self.outputs.add(y1)
     if "clk" in kwargs:
         self.clocks_by_name[nm + "_s"] = kwargs["clk"]
     else:
         if self.disable_clk_rendering:
             pass
         else:
             self.clocks_by_name[nm + "_s"] = self.default_clk
     self.clocks_by_name[nm + "_o"] = "__async__"
     self.expressions_by_name[
         nm +
         "_s"] = " (others => '0')"  # todo: somehow put a useful expression in here
     self.expressions_by_name[nm + "_o"] = nm + "_s"
Пример #31
0
def play_signal(signal: Signal,
                fs: int,
                start: Optional[Frames] = None,
                end: Optional[Frames] = None):
    start = to_frames(start if start is not None else 0)
    end = to_frames(end if end is not None else signal.get_range(fs)[1])
    buffer = signal.get_temporal(fs, start, end)

    # Ensure that highest value is in 16-bit range
    audio = buffer / np.max(np.abs(buffer)) * (2 ** 15 - 1)

    # Convert to 16-bit data
    audio = audio.astype(np.int16)

    # Start playback
    play_obj = sa.play_buffer(audio, 1, 2, fs)

    # Wait for playback to finish before exiting
    play_obj.wait_done()
Пример #32
0
 def __init__(self, path, annotations_path):
     self.file = pyedflib.EdfReader(path)
     self.number_of_signal = self.file.signals_in_file
     self.signals_list = []
     for i in np.arange(self.number_of_signal):
         self.signals_list.append(   \
             Signal(self.file.getLabel(i), self.file.readSignal(i),  \
                    self.file.getSampleFrequency(i)))
     self.annotations_file = pyedflib.EdfReader(annotations_path)
     self.annotations = self.annotations_file.readAnnotations()
Пример #33
0
    def step(self):
        """method to perform one step - propagate signals and update carrier state"""
        self.propagate()

        for station in self.connected_stations:
            signature = station.broadcast(
                self.carrier, self.get_signal(station.place_of_connection))
            if signature is not None:
                signal_to_the_right = Signal(
                    starting_pos=station.place_of_connection,
                    signature=signature,
                    direction=Directions.RIGHT)
                signal_to_the_left = Signal(
                    starting_pos=station.place_of_connection,
                    signature=signature,
                    direction=Directions.LEFT)
                self.inserted_signals.append(signal_to_the_right)
                self.inserted_signals.append(signal_to_the_left)
        # apply changes to the carrier
        self.update_carrier()
Пример #34
0
    def sendSignal(self, pinNumber):
    #note that a timedelta is needed due to the use of two sensors
    a = self.__timestamp + datetime.timedelta(milliseconds=500)
    if datetime.datetime.now() > a:
        print "signal callback from signal: " + str(pinNumber)

        #record the current time and create the string that will be stored into the database
        self.__timestamp = datetime.datetime.now()
        self.__signal = Signal.initializeSignal(self.__ID, self.__Location, self.__timestamp)
        #indicate that a signal was detected
        self.setEmptyFlag(False)

    #sets the sensor to the appropriate GPIO pin. The pins are set according to the colour of bin that the sensor is placed in. Each bin has two sensors and the pins have been optimized to make cable management easier.
    def setGPIOPin(self, ID):
        if ID is "black":
            self.__gpiopin1 = 16 
            self.__gpiopin2 = 18
            return
        elif ID is "green":
            self.__gpiopin1 = 7
            self.__gpiopin2 = 11
            return
        elif ID is "blue":
            self.__gpiopin1 = 12 
            self.__gpiopin2 = 22
            return
        elif ID is "grey":
            self.__gpiopin1 = 35
            self.__gpiopin2 = 37
            return
        else:
            return 

    #sets the empty flag to the given empty variable, also used by Queue class
    def setEmptyFlag(self, empty):
        self.__isEmpty = empty
        
    #returns the empty flag, used by Queue class    
    def isEmpty(self):
        return self.__isEmpty

    def getSignal(self):
        self.setEmptyFlag(True)
        return self.__signal
Пример #35
0
	def quickAppendBuffer(self, target):
		date = time.strftime("%d_%m_%Y") #get current date
		if not self.isCurrentDate(date): #check if the date has changed
			self.setCurrentDate(date);
		#create file according to date, location and bin color
		filePathBlack = self.relfilePath + self.__currentDate + "_" + self.__locationID + "_" + "black" + self.__fileExtension;
		filePathGreen = self.relfilePath + self.__currentDate + "_" + self.__locationID + "_" + "green" + self.__fileExtension;
		filePathBlue = self.relfilePath + self.__currentDate + "_" + self.__locationID + "_" + "blue" + self.__fileExtension;
		filePathGrey = self.relfilePath + self.__currentDate + "_" + self.__locationID + "_" + "grey" + self.__fileExtension;
		if not os.path.isfile(filePathBlack): #create a new file if new date
			self.quickInit(filePathBlack);
		if not os.path.isfile(filePathGreen): #create a new file if new date
			self.quickInit(filePathGreen);
		if not os.path.isfile(filePathBlue): #create a new file if new date
			self.quickInit(filePathBlue);
		if not os.path.isfile(filePathGrey): #create a new file if new date
			self.quickInit(filePathGrey);
		currentFileBlack = open(filePathBlack, 'a');
		currentFileGreen = open(filePathGreen, 'a');
		currentFileBlue = open(filePathBlue, 'a');
		currentFileGrey = open(filePathGrey, 'a');
		for line in target:
			color = Signal.parseSignal(line)[0];
			if not color:
				return;
			if color == "black":
				print("TEST... Printing color: " + color + " to the filepath: " + filePathBlack);
				currentFileBlack.write(line + '\n');
			if color == "green":
				print("TEST... Printing color: " + color + " to the filepath: " + filePathGreen);
				currentFileGreen.write(line + '\n');
			if color == "blue":
				print("TEST... Printing color: " + color + " to the filepath: " + filePathBlue);
				currentFileGreen.write(line + '\n');
			if color == "grey":
				print("TEST... Printing color: " + color + " to the filepath: " + filePathGrey);
				currentFileGreen.write(line + '\n');
				
		currentFileBlack.close();
		currentFileGreen.close();
		currentFileBlue.close();
		currentFileGrey.close();
Пример #36
0
 def parse_file(self, path, max_peaks=0, dB = None, time_domain = None):
     """ Invoked when a new file needs to be parsed. Will raise an exception if the file contains syntax errors
         Emits the message 'SIGNAL CHANGED' if the file was cached succesfully
     """
   
     self.signal = None
     self.fft_signal = None
   
     try:
         config = ConfigParser.RawConfigParser()
         config.read(path)
         
         nbits = config.getint('SIGNAL', 'nbits')
         rate = config.getint('SIGNAL', 'rate')
         dataString = config.get('SIGNAL', 'data').split('\n')
         data = map(string.atoi, dataString)
     
         self.signal = Signal(nbits, rate, data)
         self.fft_signal = self.signal.FFT(dB, time_domain)
     
     finally:
         self.cache_signal()
         self.cache_fft_signal(max_peaks)
         pub.sendMessage("SIGNAL CHANGED")
Пример #37
0
def test_initializeSignal():
    dateTime = datetime.datetime.utcnow()
    testSignal = Signal.initializeSignal("green","Nest",dateTime)
    assert testSignal == ("green,Nest," + str(dateTime))
Пример #38
0
class Model:
    """ Holds all the pertinent information regarding the signals.
        It also caches the information so it isn't re-calculated unnecesarily (for example when re-dimensioning windows)
        It communicates with the Controller by emiting messages.
    """

    FFT_METHODS = ['process_gain', 'noise_floor', 'SFDR', 'SINAD', 'THD', 'SNR', 'ENOB']

    def __init__(self):
        self.signal = None
        self.fft_signal = None
        self.cache_signal()
        self.cache_fft_signal()
        
    def parse_file(self, path, max_peaks=0, dB = None, time_domain = None):
        """ Invoked when a new file needs to be parsed. Will raise an exception if the file contains syntax errors
            Emits the message 'SIGNAL CHANGED' if the file was cached succesfully
        """
      
        self.signal = None
        self.fft_signal = None
      
        try:
            config = ConfigParser.RawConfigParser()
            config.read(path)
            
            nbits = config.getint('SIGNAL', 'nbits')
            rate = config.getint('SIGNAL', 'rate')
            dataString = config.get('SIGNAL', 'data').split('\n')
            data = map(string.atoi, dataString)
        
            self.signal = Signal(nbits, rate, data)
            self.fft_signal = self.signal.FFT(dB, time_domain)
        
        finally:
            self.cache_signal()
            self.cache_fft_signal(max_peaks)
            pub.sendMessage("SIGNAL CHANGED")
    
    def reprocess_fft(self, window, slices, max_peaks):
        """ Invoked when the FFT controls on tab 3 have been changed. re-calculates fft
            Emits the message 'FFT CHANGED' when done calculating
        """
        

        if self.signal is None:
            self.fft_signal = None
        else:
            # TODO: figure out how window, slices and max_peax change the way fft is calculated
            # maybe they define dB and time_domain?
            dB = None
            time_domain = None
            
            self.fft_signal = self.signal.FFT(dB, time_domain)
          
        self.cache_fft_signal(max_peaks)
        pub.sendMessage("FFT CHANGED")
        
    
    def cache_signal(self):
        """ Invokes all methods in Signal and caches their result for later use (mainly window resizing)
            Resets values to safe values (0, []) if there was an error while processing the signal definition file
        """
    
        if self.signal is None:
            self.data = []
            self.INL, self.max_INL = [], 0
            self.DNL, self.max_DNL = [], 0
            self.histogram, self.ideal_histogram = [], []
        else:
            self.data = self.signal.data
            self.INL, self.max_INL = self.signal.INL()
            self.DNL, self.max_DNL = self.signal.DNL()
            self.histogram, self.ideal_histogram = self.signal.histogram(), self.signal.ideal_histogram()
    
    def cache_fft_signal(self, max_peaks=0):
        """ Invokes all methods in FFTSignal and caches their result for later use (mainly window resizing)
            Resets values to safe values (0, []) if there was an error while processing the signal definition file
        """

        if self.fft_signal is None:
            self.fft = []
            self.harmonic_peaks = []
            for name in Model.FFT_METHODS: 
                setattr(self, name, 0)
        else:
            self.fft = self.fft_signal.fft
            self.harmonic_peaks = self.fft_signal.harmonic_peaks(max_peaks)
            for name in Model.FFT_METHODS: 
                setattr( self, name, getattr(self.fft_signal, name)() )
Пример #39
0
 def __init__(self):
     self.buttons_changed = Signal()
     self._buttons = None
     self._pressed_buttons = set()
     rospy.Subscriber('ps3_joy', Joy, self._joy_callback)
Пример #40
0
 def __init__(self, order, damping=0.5):
     self.order = order
     self.damping = damping
     self.X = Signal(order)
     self.Y = Signal(order)
     self.weights = [0] * order
Пример #41
0
def test_parseSignal():
    dateTime = datetime.datetime.utcnow()
    testSignal = Signal.initializeSignal("green","Nest",dateTime)
    expectedSignal = ("green,Nest," + str(dateTime)).split(Signal.delim)
    assert Signal.parseSignal(testSignal) == expectedSignal
Пример #42
0
class KontrolSubscriber(object):

    previous_button = 'previous'
    play_button = 'play'
    next_button = 'next'
    repeat_button = 'repeat'
    stop_button = 'stop'
    record_button = 'record'

    top1_button = 'top1'
    bottom1_button = 'bottom1'
    top2_button = 'top2'
    bottom2_button = 'bottom2'

    top6_button = 'top6'
    bottom6_button = 'bottom6'
    top7_button = 'top7'
    bottom7_button = 'bottom7'

    top8_button = 'top8'
    bottom8_button = 'bottom8'
    top9_button = 'top9'
    bottom9_button = 'bottom9'

    def __init__(self):
        self.axes_changed = Signal()
        self.buttons_changed = Signal()
        self._axes = None
        self._buttons = None
        self._pressed_buttons = set()
        self._last_larm = None
        self._last_rarm = None
        self._last_lgrip = None
        self._last_rgrip = None
        #************
        rospy.Subscriber('korg_joy', Joy, self._joy_callback)
        #rospy.Subscriber('/joy', Joy, self._joy_callback)
        #************

    def _joy_callback(self, joy_msg):
        if self._axes != joy_msg.axes:
            self._axes = joy_msg.axes
            self.axes_changed.emit()
        if self._buttons != joy_msg.buttons:
            self._buttons = joy_msg.buttons
            self.buttons_changed.emit()

    def is_valid_action_set(self):
        if self._buttons is None:
            return False
        if len(self._buttons) < 25:
            return False
        mode = self._buttons[24]
        if mode == 3:
            return False
        return True

    def get_action_set(self):
        set = ActionSet()
        if self._axes is None or self._buttons is None:
            # default action to test without hardware slider
            return DefaultAction()

        if not self.is_valid_action_set():
            return None

        mode = self._buttons[24]

        head = Pr2MoveHeadAction()
        head_data = [-self._axes[9], -self._axes[0]]
        self._set_transformed_data(head, head_data)
        set.add_action(head)

        torso = Pr2MoveTorsoAction()
        torso_data = [self._axes[8]]
        self._set_transformed_data(torso, torso_data)
        set.add_action(torso)

        if mode != 3:
            larm_data = []
            larm_data.extend(self._axes[1:7])
            larm_data.append(self._axes[16])
            larm_data[0] = -larm_data[0]
            larm_data[1] = -larm_data[1]
            larm_data[2] = -larm_data[2]
            larm_data[4] = -larm_data[4]
            larm_data[6] = -larm_data[6]

            rarm_data = []
            rarm_data.extend(self._axes[1:7])
            rarm_data.append(self._axes[16])
            rarm_data[1] = -rarm_data[1]

            lgrip_data = [self._axes[7]]
            rgrip_data = [lgrip_data[0]]

        if mode == 0 or mode == 1:
            larm = Pr2MoveLeftArmAction()
            self._set_transformed_data(larm, larm_data)
            set.add_action(larm)
            self._last_larm = larm

            lgrip = Pr2MoveLeftGripperAction()
            self._set_transformed_data(lgrip, lgrip_data)
            set.add_action(lgrip)
            self._last_lgrip = lgrip
        elif mode == 2:
            if self._last_larm is not None:
                set.add_action(self._last_larm.deepcopy())
            if self._last_lgrip is not None:
                set.add_action(self._last_lgrip.deepcopy())

        if mode == 0 or mode == 2:
            rarm = Pr2MoveRightArmAction()
            self._set_transformed_data(rarm, rarm_data)
            set.add_action(rarm)
            self._last_rarm = rarm

            rgrip = Pr2MoveRightGripperAction()
            self._set_transformed_data(rgrip, rgrip_data)
            set.add_action(rgrip)
            self._last_rgrip = rgrip
        elif mode == 1:
            if self._last_rarm is not None:
                set.add_action(self._last_rarm.deepcopy())
            if self._last_rgrip is not None:
                set.add_action(self._last_rgrip.deepcopy())

        duration = self._transform_value(self._axes[17], 0.5, 5.0)
        set.set_duration(duration)

        return set

    def get_joint_values(self):
        values = {}
        set = self.get_action_set()
        for action in set._actions:
            is_degree = isinstance(action, Pr2JointTrajectoryAction) and not isinstance(action, Pr2MoveTorsoAction)
            for index, data in enumerate(action._joints):
                name = data['label']
                value = action._values[index]
                if is_degree:
                    value = value * math.pi / 180.0
                values[name] = value
        return values

    def get_triggered_buttons(self):
        buttons = {
            18: self.previous_button,
            19: self.play_button,
            20: self.next_button,
            21: self.repeat_button,
            22: self.stop_button,
            23: self.record_button,
            0: self.top1_button,
            1: self.bottom1_button,
            2: self.top2_button,
            3: self.bottom2_button,
            10: self.top6_button,
            11: self.bottom6_button,
            12: self.top7_button,
            13: self.bottom7_button,
            14: self.top8_button,
            15: self.bottom8_button,
            16: self.top9_button,
            17: self.bottom9_button,
        }
        triggered = set()
        for index, value in enumerate(self._buttons):
            if index in buttons.keys():
                index = buttons[index]
            if value == 1:
                if index not in self._pressed_buttons:
                    self._pressed_buttons.add(index)
                    triggered.add(index)
            else:
                if index in self._pressed_buttons:
                    self._pressed_buttons.remove(index)
        return triggered

    def _set_transformed_data(self, action, data):
        assert(len(action._joints) == len(data))
        transformed = []
        for index, joint in enumerate(action._joints):
            min_value = joint['min']
            max_value = joint['max']
            value = self._transform_value(data[index], min_value, max_value)
            transformed.append(value)
        action.set_values(transformed)
        #print 'joints', action._joints
        #print 'data', data

    def _transform_value(self, value, min_value, max_value):
        assert(value >= -1 and value <= 1)
        value = (value + 1.0) / 2.0
        value = min_value + value * (max_value - min_value)
        assert(value >= min_value)
        assert(value <= max_value)
        return value
Пример #43
0
 def __init__(self):
     super(Action, self).__init__()
     self._duration = 3.0
     self.execute_finished_signal = Signal()
Пример #44
0
class EditSignalWindow(QtGui.QMainWindow, Ui_EditSignalWindow):
    
    signalEdited = QtCore.pyqtSignal() #signal emitted when the signal is ready to send
    
    def __init__(self, signals_dict, selected_signal_name):
        self.signals_dict = signals_dict
        self.my_signal_name = selected_signal_name
        #Make a copy of the original signal
        self.my_signal = Signal(selected_signal_name,
                                self.signals_dict[selected_signal_name]._signal_data.copy(),
                                self.signals_dict[selected_signal_name]._signal_type,
                                self.signals_dict[selected_signal_name]._signal_data_type)
        
        super(EditSignalWindow, self).__init__()
        self.setupUi(self)
        self.initUI()
        
        
    def initUI(self):
        #Define slots
        self.radioButton_select_all_variables.toggled.connect(self.selectAllVariables)
        self.tableWidget_signal_preview.itemSelectionChanged.connect(self.updateVariableSelection)
        self.pushButton_rename_signal.clicked.connect(self.renameSignal)
        self.pushButton_resample_signal.clicked.connect(self.resampleSignal)
        self.pushButton_interpolate_signal.clicked.connect(self.interpolateSignal)
        self.pushButton_cut_signal.clicked.connect(self.cutSignal)
        self.pushButton_rename_variable.clicked.connect(self.renameVariable)
        self.pushButton_remove_variable.clicked.connect(self.removeVariable)
        self.pushButton_normalize_variable.clicked.connect(self.normalizeVariable)
        self.pushButton_convertIntoBinary.clicked.connect(self.convertVariableIntoBinary)
        self.pushButton_visualize.clicked.connect(self.visualizeSignal)
        self.pushButton_apply_changes.clicked.connect(self.applyChanges)
        
        # Display the name of the selected signal for edition
        self.label_selected_signal_name.setFont(large_font)
        self.label_selected_signal_name.setText(self.my_signal._signal_name)
        
        # Display signal preview
        self.displaySignalPreview()
        
        #Enabled buttons
        self.pushButton_rename_variable.setEnabled(False)
        self.pushButton_remove_variable.setEnabled(False)
        self.pushButton_normalize_variable.setEnabled(False)
        self.pushButton_convertIntoBinary.setEnabled(False)
        
        # Display the window
        self.show()
    
    
    def displaySignalPreview(self):
        self.tableWidget_signal_preview.setSelectionBehavior(QtGui.QAbstractItemView.SelectColumns)
        
        #Display a signal preview in table widget
        self.tableWidget_signal_preview.setColumnCount(1 + len(self.my_signal._signal_data.columns));
        self.tableWidget_signal_preview.setRowCount(10);
        
        #Display signal columns names
        Qcol_list = QtCore.QStringList()
        Qcol_list.append(self.my_signal._signal_data.index.name)
        for col_name in self.my_signal._signal_data.columns.values :
            Qcol_list.append(col_name)
        self.tableWidget_signal_preview.setHorizontalHeaderLabels(Qcol_list)
        
        # Display the 10 first lines of the signal
        for row_idx in range(10):
            item=QtGui.QTableWidgetItem()
            item.setText(QtCore.QString(str(self.my_signal._signal_data.index[row_idx])))
            self.tableWidget_signal_preview.setItem(row_idx, 0, item)
            col_idx = 1
            for value in self.my_signal._signal_data.iloc[row_idx,:] :
                item=QtGui.QTableWidgetItem()
                item.setText(QtCore.QString.number(value))
                self.tableWidget_signal_preview.setItem(row_idx, col_idx, item)
                col_idx += 1
                
        self.tableWidget_signal_preview.resizeColumnsToContents()

    
    def selectAllVariables(self, checked):
        if checked:
            self.tableWidget_signal_preview.selectAll()
        else:
            self.tableWidget_signal_preview.clearSelection()
    
    
    def updateVariableSelection(self):
        # Get selected variable in preview Tab widget
        selected_var_idx = [self.tableWidget_signal_preview.selectedIndexes()[i].column()
                            for i in range(len(self.tableWidget_signal_preview.selectedIndexes()))]
        selected_var_idx = sorted(set(selected_var_idx))

        if len(selected_var_idx) == 0:
            self.pushButton_rename_variable.setEnabled(False)
            self.pushButton_remove_variable.setEnabled(False)
            self.pushButton_normalize_variable.setEnabled(False)
            self.pushButton_convertIntoBinary.setEnabled(False)
        else:
            self.pushButton_rename_variable.setEnabled(True)
            self.pushButton_remove_variable.setEnabled(True)
            self.pushButton_normalize_variable.setEnabled(True)
            self.pushButton_convertIntoBinary.setEnabled(True)
       
        if len(selected_var_idx) >= len(self.my_signal._signal_data.columns):
            self.pushButton_remove_variable.setEnabled(False)
        
    
    def renameSignal(self):
        new_name, ok = QtGui.QInputDialog.getText(self, 'Rename Signal', 
            "Enter the new signal's name for " + self.my_signal._signal_name + " :")
        
        if ok:
            if str(new_name) in self.signals_dict.keys():
                mess = QtGui.QMessageBox.warning(self,
                                                'Warning Message',
                                                "This signal's name already exist.")
            else :
                self.my_signal._signal_name = str(new_name).strip()
                self.label_selected_signal_name.setFont(large_font)
                self.label_selected_signal_name.setText(self.my_signal._signal_name)

    
    
    def resampleSignal(self):
        rule, ok = QtGui.QInputDialog.getText(self, 'Resample Signal', 
            "Give a rule for the resampling (ex: 100ms) :")
        if ok : 
            self.my_signal._signal_data = self.signals_dict[self.my_signal_name]._signal_data.resample(rule=str(rule))
            self.displaySignalPreview()

    
    def interpolateSignal(self):
        limit, ok = QtGui.QInputDialog.getInt(self, 'Interpolate Signal', 
            "Give a maximal number of consecutive NaN values to fill :", value = 0, min = 0) 
        
        if ok :
            self.my_signal._signal_data = self.my_signal._signal_data.interpolate(limit=limit, inplace = False)
            self.displaySignalPreview()
    
    
    def cutSignal(self):
        index_begin, ok = QtGui.QInputDialog.getInt(self, 'Cut Signal', 
            "Give the first index of the cut signal :", value = 0, min = 0)
        
        if ok :
            index_end, ok2 = QtGui.QInputDialog.getInt(self, 'Cut Signal', 
            "Give the last index of the cut signal :", value = index_begin + 1, min = index_begin + 1)
            
            if ok2 :
                if index_end >= len(self.my_signal._signal_data.index) : 
                    reply = QtGui.QMessageBox.information(self, 'Info',
                                "The given last index is higher than the length of the signal. \n" +
                                "The cut will go up to the signal's end ")
                    index_end = len(self.my_signal._signal_data.index) - 1
                self.my_signal._signal_data = self.my_signal._signal_data[index_begin : index_end]
                self.displaySignalPreview()
            
            
    def renameVariable(self):
        # Get selected variable in preview Tab widget
        selected_var_idx = [self.tableWidget_signal_preview.selectedIndexes()[i].column()
                            for i in range(len(self.tableWidget_signal_preview.selectedIndexes()))]
        selected_var_idx = sorted(set(selected_var_idx))
        
        selected_variables = []
        for i in selected_var_idx:
            if i != 0: #ignore if TimeIndex is selected
                selected_variable = self.my_signal._signal_data.columns.values[i-1]
        
                new_name, ok = QtGui.QInputDialog.getText(self, 'Rename Variable ', 
                    "Enter the new variable's name for " + selected_variable + " :")
                if ok:
                    self.my_signal._signal_data.rename(columns={selected_variable : str(new_name).strip()}, inplace = True)
                    self.displaySignalPreview()
        
    
    def removeVariable(self):
        # Get selected variable in preview Tab widget
        selected_var_idx = [self.tableWidget_signal_preview.selectedIndexes()[i].column()
                            for i in range(len(self.tableWidget_signal_preview.selectedIndexes()))]
        selected_var_idx = sorted(set(selected_var_idx))
        
        selected_variables = []
        for i in selected_var_idx:
            if i != 0: #ignore if TimeIndex is selected
                selected_variable = self.my_signal._signal_data.columns.values[i-1]
        
                reply = QtGui.QMessageBox.question(self, 'Message',
                    "Do you want to remove "+ selected_variable +" variable?",
                    QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.Yes)
                
                if reply == QtGui.QMessageBox.Yes:
                    old_signal_type = self.my_signal._signal_type
                    old_signal_data_type = self.my_signal._signal_data_type
                    self.my_signal._signal_data.drop(selected_variable, axis=1, inplace=True)
                    
                    # Update signal type
                    new_signal_type = 0 if(len(self.my_signal._signal_data.columns) == 1) else 1
                    if old_signal_type != new_signal_type :
                        self.my_signal._signal_type = new_signal_type
                        reply = QtGui.QMessageBox.information(self, 'Info',
                                self.my_signal._signal_name + " is now a Univariate signal. ")
                        
                    #Update signal data type
                    self.updateSignalDataType(old_signal_data_type)                                       
        self.displaySignalPreview()
        
        
    def normalizeVariable(self):
        # Get selected variable in preview Tab widget
        selected_var_idx = [self.tableWidget_signal_preview.selectedIndexes()[i].column()
                            for i in range(len(self.tableWidget_signal_preview.selectedIndexes()))]
        selected_var_idx = sorted(set(selected_var_idx))
        
        selected_variables = []
        for i in selected_var_idx:
            if i != 0: #ignore if TimeIndex is selected
                selected_variable = self.my_signal._signal_data.columns.values[i-1]
                
                min_value, min_ok = QtGui.QInputDialog.getInt(self, 'Normalize Variable', 
                "Give a minimal value for the normalization of " + selected_variable + " :", value = 0)
                if min_ok:
                    max_value, max_ok = QtGui.QInputDialog.getInt(self, 'Normalize Variable', 
                    "Give a maximal value for the normalization of " + selected_variable + " :", value = min_value + 1)
                    if max_ok:
                        self.my_signal._signal_data[selected_variable] = Normalize.Normalize(
                                            pd.DataFrame(self.my_signal._signal_data[selected_variable]),
                                            min_value, max_value)
                        self.displaySignalPreview()
    
    
    def convertVariableIntoBinary(self):
        # Get selected variable in preview Tab widget
        selected_var_idx = [self.tableWidget_signal_preview.selectedIndexes()[i].column()
                            for i in range(len(self.tableWidget_signal_preview.selectedIndexes()))]
        selected_var_idx = sorted(set(selected_var_idx))
        
        selected_variables = []
        for i in selected_var_idx:
            if i != 0: #ignore if TimeIndex is selected
                selected_variable = self.my_signal._signal_data.columns.values[i-1]
                
                mean_data = np.mean(self.my_signal._signal_data[selected_variable].values)
                thresh, ok = QtGui.QInputDialog.getDouble(self, 'Convert Variable into Binary', 
                    "Give a threshold for the conversion into binary of " + selected_variable + " :", value = mean_data)
                if ok:
                    reply = QtGui.QMessageBox.question(self, 'Message',
                            "Do you want to maximize " + selected_variable + " ?",
                            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.Yes)
                    if reply == QtGui.QMessageBox.Yes:
                        maximize = True
                    else:
                        maximize = False
                    
                    old_signal_data_type = self.my_signal._signal_data_type
                    self.my_signal._signal_data[selected_variable] = ConvertContinueToBinary.ConvertContinueToBinary(
                                            pd.DataFrame(self.my_signal._signal_data[selected_variable]),
                                            thresh, maximize)
                    
                    #Update signal data type
                    self.updateSignalDataType(old_signal_data_type)
                    self.displaySignalPreview()


    def updateSignalDataType(self, old_signal_data_type):
        # update signal data type
        is_categorical = True
        col_idx = 0
        while is_categorical and col_idx < len(self.my_signal._signal_data.columns) :
            number_val = len(sorted(set(self.my_signal._signal_data.iloc[:,col_idx])))
            if number_val > 2:
                is_categorical = False
            col_idx += 1;
        new_signal_data_type = 1 if(is_categorical) else 0
        
        if old_signal_data_type != new_signal_data_type :
            self.my_signal._signal_data_type = new_signal_data_type
            str_my_data_type = "Continuous" if(new_signal_data_type==0) else "Categorical"
            reply = QtGui.QMessageBox.information(self, 'Info',
                    self.my_signal._signal_name + " is now a " + str_my_data_type +" signal. ")
                        
        
    def visualizeSignal(self):
        # Get selected variable in preview Tab widget
        selected_var_idx = [self.tableWidget_signal_preview.selectedIndexes()[i].column()
                            for i in range(len(self.tableWidget_signal_preview.selectedIndexes()))]
        selected_var_idx = sorted(set(selected_var_idx))

        selected_variables = []
        for i in selected_var_idx:
            if i != 0: #ignore if TimeIndex is selected
                selected_variables.append(self.my_signal._signal_data.columns.values[i-1])
        if len(selected_variables) == 0 : 
            selected_variables = self.my_signal._signal_data.columns   
        self.my_signal.plot_signal(selected_variables)


    def applyChanges(self):
        self.close()
        
    def closeEvent(self, event):
        reply = QtGui.QMessageBox.question(self, 'Message',
            "Do you want to apply changes to "+ self.my_signal_name +" signal?",
            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.Yes)

        if reply == QtGui.QMessageBox.Yes:
            self.signalEdited.emit()
            event.accept() # let the window close
        else:
            event.accept() # let the window close