コード例 #1
0
class Ticker:
    def __init__(self, lookback, exchange, symbol, bid, ask, updated_at):

        self.exchange = exchange
        self.symbol = symbol
        self.bid = bid
        self.ask = ask
        self.updated_at = updated_at

        self.bid_lookback = RingBuffer(capacity=lookback, dtype=object)
        self.ask_lookback = RingBuffer(capacity=lookback, dtype=object)

    def get_bid(self):
        return self.bid

    def get_ask(self):
        return self.ask

    def get_time(self):
        return self.updated_at

    def update(self, data):

        self.bid = data['bid']
        self.ask = data['ask']

        self.updated_at = data['time']

        self.bid_lookback.append(self.bid)
        self.ask_lookback.append(self.ask)
コード例 #2
0
    def __init__(self, name, limits, setpoints, duration, gait_generator=None):
        self.setpoints_history = RingBuffer(capacity=100, dtype=list)
        self.setpoints_redo_list = RingBuffer(capacity=100, dtype=list)
        self.gait_generator = gait_generator

        super(ModifiableJointTrajectory, self).__init__(name, limits, setpoints, duration)
        self.interpolated_setpoints = self.interpolate_setpoints()
コード例 #3
0
 def __init__(self,
              state_inputs,
              init_size=int(5e4),
              max_size=int(1e5),
              prioritized=False):
     self.init_size = init_size
     self.max_size = max_size
     self.prioritized = prioritized
     self.size = 0
     self.state_inputs = state_inputs
     self.buffers = {}
     for elem in TRANSITION_ELEMS:
         if elem in ['s', 's_next']:
             self.buffers[elem] = {}
             for key in state_inputs.keys():
                 self.buffers[elem][key] = \
                     RingBuffer(
                         capacity=max_size,
                         dtype=(np.float32, state_inputs[key]))
         elif elem is 'a':
             self.buffers[elem] = \
                 RingBuffer(
                     capacity=max_size,
                     dtype=(np.float32, state_inputs['actions']))
         else:
             self.buffers[elem] = \
                 RingBuffer(
                     capacity=max_size,
                     dtype=np.float32)
コード例 #4
0
class CausalVelocityFilter():
    """Calculates the derivative of data that's appended to the
    internal buffer and allows you to get a moving average of the
    derivative with window size defined by the init.
    """
    def __init__(self, windowSize):
        """Initializes self.
        windowSize defines the width of the moving average buffer.
        Too narrow and it doesn't do much filtering, too wide and it
        lags behind the acutal derivative
        """

        self._derivativeBuffer = RingBuffer(windowSize)
        self._previousDatum = 0.0

    def get_datum(self):
        """Get the present rate of change of the incomimg data"""

        return np.mean(self._derivativeBuffer)

    def append(self, datum, timeElapsed):
        """Add a measurement and an elapsed time to the filter's
        internal buffer to be able to find the rate of change.
        """

        self._derivativeBuffer.append(
            (datum - self._previousDatum) / timeElapsed)
        self._previousDatum = datum
コード例 #5
0
    def __init__(self, view, robot):
        self.view = view

        # Default values
        self.gait_directory = None

        self.playback_speed = 100
        self.time_slider_thread = None
        self.current_time = 0
        self.robot = robot

        empty_subgait_file = os.path.join(
            rospkg.RosPack().get_path('march_rqt_gait_generator'),
            'resource/empty_gait/empty_subgait/empty_subgait.subgait')
        self.subgait = ModifiableSubgait.from_file(robot, empty_subgait_file,
                                                   self)
        self.settings_changed_history = RingBuffer(capacity=100, dtype=list)
        self.settings_changed_redo_list = RingBuffer(capacity=100, dtype=list)

        standing = Subgait.from_file(robot, empty_subgait_file)
        previous_subgait_controller = SideSubgaitController(
            view=self.view.side_subgait_view['previous'], default=standing)
        next_subgait_controller = SideSubgaitController(
            view=self.view.side_subgait_view['next'], default=standing)
        self.side_subgait_controller = {
            'previous': previous_subgait_controller,
            'next': next_subgait_controller
        }

        self.connect_buttons()
        self.view.load_gait_into_ui(self.subgait)
        for joint in self.subgait.joints:
            self.connect_plot(joint)
コード例 #6
0
    def __init__(self, state_shape, n_actions, epsilon=None):
        self.capacity = 100000
        self.state_memory = RingBuffer(capacity=self.capacity,
                                       dtype=(np.uint8, state_shape))
        self.next_state_memory = RingBuffer(capacity=self.capacity,
                                            dtype=(np.uint8, state_shape))
        self.action_memory = RingBuffer(capacity=self.capacity, dtype=np.uint8)
        self.reward_memory = RingBuffer(capacity=self.capacity,
                                        dtype=np.uint16)
        self.done_memory = RingBuffer(capacity=self.capacity, dtype=np.bool)

        self.n_actions = n_actions
        self.state_shape = state_shape
        self.gamma = 0.99

        if epsilon is None:
            self.epsilon = 1.0
            self.epsilon_decay = 0.9997
            self.epsilon_min = 0.05
            self.decay_epsilon = True
        else:
            self.epsilon = epsilon
            self.decay_epsilon = False

        self.q = None
コード例 #7
0
    def __init__(
        self,
        checkpoint: Path,
        threshold: float = 0.9,
        smoothing: int = 5,
        timeout: float = 1.0,
    ):
        self.device = torch.device(
            "cuda" if torch.cuda.is_available() else "cpu")
        self.model, self.config = model_from_checkpoint(checkpoint,
                                                        device=self.device)
        self.model = self.model.eval().to(self.device)
        self.extractor = init_feature_extractor(self.config)
        self.threshold = threshold
        self.smoothing = smoothing
        self.timeout = timeout

        self.input_samples = self.config.fft_window_step * (
            self.model.input_size - 1)
        self.preds_buffer = RingBuffer(self.smoothing, "float32")
        self.raw_input_buffer = RingBuffer(capacity=self.input_samples,
                                           dtype="float32")
        self.raw_input_buffer.extend(
            np.zeros(self.input_samples, dtype="float32"))
        self.cooldown_time = 0
コード例 #8
0
    def import_gait(self):
        file_name, f = self.view.open_file_dialogue()

        if file_name != '':
            gait = ModifiableSubgait.from_file(self.robot, file_name, self)
        else:
            gait = None

        if gait is None:
            rospy.logwarn('Could not load gait %s', file_name)
            return
        if gait.gait_type is None or gait.gait_type == '':
            gait.gait_type = 'walk_like'
        self.subgait = gait

        was_playing = self.time_slider_thread is not None
        self.stop_time_slider_thread()

        self.view.load_gait_into_ui(self.subgait)
        for joint in self.subgait.joints:
            self.connect_plot(joint)
        self.current_time = 0

        if was_playing:
            self.start_time_slider_thread()

        self.gait_directory = '/'.join(file_name.split('/')[:-3])
        rospy.loginfo('Setting gait directory to %s', str(self.gait_directory))
        self.view.change_gait_directory_button.setText(self.gait_directory)

        # Clear undo and redo history
        self.settings_changed_history = RingBuffer(capacity=100, dtype=list)
        self.settings_changed_redo_list = RingBuffer(capacity=100, dtype=list)
コード例 #9
0
class RingbufferMonitor(Monitor):
    def __init__(self,
                 capacity=100,
                 key='training_loss',
                 name='ringbuffer_monitor'):
        super().__init__(name=name)
        self.capacity = capacity
        self.key = key
        self.value_buffer = None
        self.step_buffer = RingBuffer(capacity=capacity, dtype='float32')

        self.previous_session_steps = 0
        self.last_step = 0

    def start_session(self, num_steps, **kwargs):
        self.previous_session_steps += self.last_step

    def write(self, data, step, **kwargs):
        if self.key in data.keys():
            value = data[self.key]

            if isinstance(value, Tensor):
                dtype = value.data.cpu().numpy().dtype
                value = self._to_scalar(value)
            else:
                dtype = np.array(value).dtype

            if self.value_buffer is None:
                self.value_buffer = RingBuffer(capacity=self.capacity,
                                               dtype=dtype)

            self.value_buffer.append(value)
            self.step_buffer.append(step + self.previous_session_steps)

        self.last_step = math.ceil(step)

    def mean(self, *args, **kwargs):
        return np.array(self.value_buffer).mean(*args, **kwargs)

    def std(self, *args, **kwargs):
        return np.array(self.value_buffer).std(*args, **kwargs)

    @property
    def movement_index(self):
        steps = self.step_buffer
        if len(steps) < self.capacity:
            # not enough information gathered yet to say...
            return None
        else:
            step_difference = (steps[-1] - steps[0])
            midpoint = np.argmax(steps >= steps[0] + (step_difference // 2))

            values = np.array(self.value_buffer)

            first = values[:midpoint]
            last = values[midpoint:]

            d = (np.abs(first.mean() - last.mean()) /
                 (2 * np.sqrt(first.std() * last.std())))
            return d
コード例 #10
0
    def __init__(self,
                 latent_size,
                 stddv_p,
                 stddv,
                 hot_start,
                 N,
                 batch_size,
                 accuracy_bloomf=0.01,
                 static=False):
        self.i = 0
        self.I = 0
        self.BI = 1

        #self.guessed_z = []

        self.DYNAMIC = False
        self.hot_start = hot_start
        self.latent_size = latent_size
        self.stddv_p = stddv_p
        self.stddv = stddv
        self.LOG = False
        self.STATIC = static
        self.init_att_size = 0
        self.N = N

        self.batch_size = batch_size
        self.accuracy_bloomf = accuracy_bloomf

        self.matched_i = 0

        self.P = []

        if not self.STATIC:
            self.guessed_z = RingBuffer(capacity=self.memory_bank_size,
                                        dtype=(np.float32, self.latent_size))
コード例 #11
0
class SensirionSBPlot(QWidget):
    def __init__(self, plot_title, color, bufferSize):
        super().__init__()
        masterLayout = QVBoxLayout()
        self.pen = mkPen(color, width=1.25)

        layout = QVBoxLayout()
        self.group = QGroupBox(plot_title)
        self.plot = PlotWidget()
        self.plot.getPlotItem().showGrid(x=True, y=True, alpha=1)
        if "qdarkstyle" in sys.modules:
            self.plot.setBackground((25, 35, 45))
        self.buffer = RingBuffer(capacity=bufferSize, dtype=float)

        self.group.setLayout(layout)
        layout.addWidget(self.plot)
        masterLayout.addWidget(self.group)

        self.setLayout(masterLayout)

    def change_capacity(self, value):
        if value > len(self.buffer):
            newBuf = RingBuffer(capacity=value, dtype=float)
            newBuf.extend(self.buffer)
            self.buffer = newBuf

        elif value < len(self.buffer):
            newBuf = RingBuffer(capacity=value, dtype=float)
            newBuf.extend(self.buffer[:-value])
            self.buffer = newBuf

    def update_plot(self, sample):
        self.plot.clear()
        self.buffer.append(sample)
        self.plot.plot(self.buffer, pen=self.pen, symbolPen=self.pen, symbol='o', symbolSize=5, name="symbol ='o'")
コード例 #12
0
def init_buf():
    '''Initialize buffer'''
    buf = RingBuffer(p.winsamp, dtype=np.int16)
    eps = np.finfo(float).eps
    for _ in range(p.winsamp):
        buf.append(eps)
    return buf
コード例 #13
0
def main():
    window = RingBuffer(capacity=100, dtype=(float, 4))
    with open("log.json", "r") as data_file:
        for line in data_file:
            data = ujson.loads(line)
            if data['data']['cpu']['percent'] < 50:
                window.append(
                    [data['data']['cpu']['percent'], data['ts'], 0, 0])
                print(np.mean(window, 0)[0])
コード例 #14
0
    def __init__(self, current_time):
        self._flow_rate_sample_times = RingBuffer(2)
        self._flow_rate_sample_times.append(current_time)

        self._tidal_volume_filter = TidalVolume(current_time)
        self._peep_filter = PEEP(0.1)
        self._pip_filter = PIP(0.1)
        self._most_recent_pressure = 0.0
        self._most_recent_flow_rate = 0.0
コード例 #15
0
    def __init__(self, windowSize):
        """Initializes self.
        windowSize defines the width of the moving average buffer.
        Too narrow and it doesn't do much filtering, too wide and it
        lags behind the acutal derivative
        """

        self._derivativeBuffer = RingBuffer(windowSize)
        self._previousDatum = 0.0
コード例 #16
0
ファイル: tests.py プロジェクト: fpdotmonkey/numpy_ringbuffer
 def test_negative_indices_give_recent_data_with_unfull_buffer(self):
     r = RingBuffer(10)
     for i in range(5):
         r.append(i)
     for i in reversed(range(-len(r), 0)):
         self.assertAlmostEqual(r[i],
                                r[i + 5],
                                msg="Fails to index from the back of "
                                "the filled portion of the buffer "
                                "given a negative index.")
コード例 #17
0
    def __init__(self, lookback, exchange, symbol, bid, ask, updated_at):

        self.exchange = exchange
        self.symbol = symbol
        self.bid = bid
        self.ask = ask
        self.updated_at = updated_at

        self.bid_lookback = RingBuffer(capacity=lookback, dtype=object)
        self.ask_lookback = RingBuffer(capacity=lookback, dtype=object)
コード例 #18
0
ファイル: tests.py プロジェクト: pourhouse/numpy_ringbuffer
    def test_sizes(self):
        r = RingBuffer(5, dtype=(int, 2))
        self.assertEqual(r.maxlen, 5)
        self.assertEqual(len(r), 0)
        self.assertEqual(r.shape, (0, 2))

        r.append([0, 0])
        self.assertEqual(r.maxlen, 5)
        self.assertEqual(len(r), 1)
        self.assertEqual(r.shape, (1, 2))
コード例 #19
0
    def __init__(self, capacity=100,
            key='training_loss',
            name='ringbuffer_monitor'):
        super().__init__(name=name)
        self.capacity = capacity
        self.key = key
        self.value_buffer = None
        self.step_buffer = RingBuffer(capacity=capacity, dtype='float32')

        self.previous_session_steps = 0
        self.last_step = 0
コード例 #20
0
ファイル: server.py プロジェクト: sduquemesa/SONO
    def __init__(self, port_name = 'COM6', baud_rate = 9600, stack_size = 100, num_data_bytes = 2, data_types = [], data_length = []):

        self.port = port_name
        self.baud = baud_rate
        self.stack_size = stack_size
        self.num_data_bytes = num_data_bytes
        self.data_types = data_types
        self.data_length = data_length
        # self.numData = numData              # TO ERASE!
        self.rawdata_bytes = bytearray(num_data_bytes)

        # give an array for each type of data and store them in a ring buffer of size len(self.data_types)
        self.data = RingBuffer(capacity = stack_size, dtype=(float, (len(self.data_types),)))
        self.data_to_append = np.zeros( shape=(len(self.data_types),) )

        self.is_run = True
        self.is_receiving = False
        self.thread = None
        self.plot_timer = 0
        self.previous_timer = 0
        # self.csvData = []

        # define binning for polar heatmap
        self.min_sensor_distance = 20
        self.max_sensor_distance = 200
        self.radius_bins_heatmap = np.linspace(self.min_sensor_distance,self.max_sensor_distance, 16)
        self.angle_bins_heatmap = np.linspace(-0.1,2*np.pi-0.1, 40)

        ### MIDI Settings ###
        self.mido_outports = mido.get_output_names()
        print("Trying to connect to MIDI port:", self.mido_outports[1])
        try:
            self.midi_outport = mido.open_output(self.mido_outports[1])
            print("Connected to MIDI port:", self.mido_outports[1])
        except IOError:
            print("Error connecting to MIDI port:", self.mido_outports[1])
            sys.exit(1)

        #[F2,G#2, C3, C#3, D#3, F3] C# Major scale
        # self.notes = [41, 44, 48, 49, 51, 53, 58, 60]
        # self.note_status = [False]*len(self.notes)

        #[F#2,G#2, C3, C#3, D#3, F3, G#3, A#4]
        self.notes = [42, 44, 48, 49, 51, 53, 58, 60]
        self.note_status = [False]*len(self.notes)

        print('\nTrying to connect to: ' + str(port_name) + ' at ' + str(baud_rate) + ' BAUD.')
        try:
            self.serial_connection = serial.Serial(port_name, baud_rate, timeout=4)
            print('Connected to ' + str(port_name) + ' at ' + str(baud_rate) + ' BAUD.\n')
        except:
            print("Failed to connect with " + str(port_name) + ' at ' + str(baud_rate) + ' BAUD.')
            sys.exit(1)
コード例 #21
0
ファイル: audiostream.py プロジェクト: behinger/bandotuner
class AudioStream(object):
    def __init__(self,rate=8192,T=4):
        # stream constants
        self.RATE = rate
        self.CHUNK = int(self.RATE/100) # 40 times per second
        #self.FORMAT = pyaudio.paFloat32
        self.CHANNELS = 1
        self.pause = False
        self.T =T # 
        
        self.init_buff()
        # stream object
#        self.p = pyaudio.PyAudio()
        self.stream = sd.InputStream(channels=1,
		     samplerate=rate, callback=self.fill_buffer, blocksize=self.CHUNK)
        self.stream.start()
        #self.stream = self.p.open(
        #    format=pyaudio.paInt16,
        #    channels=1, rate=self.RATE,
        #    input=True, frames_per_buffer=self.CHUNK,
            # Run the audio stream asynchronously to fill the buffer object.
            # This is necessary so that the input device's buffer doesn't
            # overflow while the calling thread makes network requests, etc.
        #    stream_callback=self.fill_buffer,
        #    )
        
    def init_buff(self):
        # at first I wanted to extend the data previously recorded, but obviously they were recorded at a different sampling rate. We therefore have to start anew
        self.buffsize =int(self.RATE*self.T)
        #self.buff = deque(maxlen=self.buffsize)
        self.buff = RingBuffer(capacity=self.buffsize)#,dtype=np.int16)
        self.fftwindow = hann(self.buffsize)
    def fill_buffer(self, in_data, frame_count, time_info, status_flags):
            """Continuously collect data from the audio stream, into the buffer."""
            #d_converted = np.fromstring(in_data, 'int16')
            #print(d_converted)
            #print(in_data)
            self.buff.extend(in_data[:,0])
            #self.buff.extend(in_data[1::2])
            #return None, pyaudio.paContinue
        
    def calc_fft(self):
        data = np.array(self.buff)
        if data.shape[0]!= self.buffsize:
            print('loading samples %i%%'%(data.shape[0]/self.buffsize*100))
            return(None)
        data = np.multiply(data,self.fftwindow)
        yf = fft(data)
        yf = yf[1:int(yf.shape[0]/2)]
        fftdata =   np.abs(yf)

        return(fftdata)
コード例 #22
0
ファイル: audioplot.py プロジェクト: zhangzhe1103/gst-python
    def do_set_caps(self, icaps, ocaps):
        in_info = GstAudio.AudioInfo()
        in_info.from_caps(icaps)
        out_info = GstVideo.VideoInfo()
        out_info.from_caps(ocaps)

        self.convert_info = GstAudio.AudioInfo()
        self.convert_info.set_format(GstAudio.AudioFormat.S32,
                                     in_info.rate,
                                     in_info.channels,
                                     in_info.position)
        self.converter = GstAudio.AudioConverter.new(GstAudio.AudioConverterFlags.NONE,
                                                     in_info,
                                                     self.convert_info,
                                                     None)

        self.fig = plt.figure()
        dpi = self.fig.get_dpi()
        self.fig.patch.set_alpha(0.3)
        self.fig.set_size_inches(out_info.width / float(dpi),
                                 out_info.height / float(dpi))
        self.ax = plt.Axes(self.fig, [0., 0., 1., 1.])
        self.fig.add_axes(self.ax)
        self.ax.set_axis_off()
        self.ax.set_ylim((GLib.MININT, GLib.MAXINT))
        self.agg = self.fig.canvas.switch_backends(FigureCanvasAgg)
        self.h = None

        samplesperwindow = int(in_info.rate * in_info.channels * self.window_duration)
        self.thinning_factor = max(int(samplesperwindow / out_info.width - 1), 1)

        cap = int(samplesperwindow / self.thinning_factor)
        self.ax.set_xlim([0, cap])
        self.ringbuffer = RingBuffer(capacity=cap)
        self.ringbuffer.extend([0.0] * cap)
        self.frame_duration = Gst.util_uint64_scale_int(Gst.SECOND,
                                                        out_info.fps_d,
                                                        out_info.fps_n)
        self.next_time = self.frame_duration

        self.agg.draw()
        self.background = self.fig.canvas.copy_from_bbox(self.ax.bbox)

        self.samplesperbuffer = Gst.util_uint64_scale_int(in_info.rate * in_info.channels,
                                                          out_info.fps_d,
                                                          out_info.fps_n)
        self.next_offset = self.samplesperbuffer
        self.cur_offset = 0
        self.buf_offset = 0

        return True
コード例 #23
0
def find_convergence_episode(rewards_list, buffer_size=3):
    import numpy as np
    from numpy_ringbuffer import RingBuffer

    convergence_buffer = RingBuffer(capacity=buffer_size)
    res = -1
    for index, reward_value in enumerate(rewards_list):
        convergence_buffer.append(reward_value)
        if (len(np.unique(convergence_buffer)) == 1
                and len(convergence_buffer) == 3):
            res = index - 1
            return res

    return res
コード例 #24
0
 def __init__(self):
     super().__init__()
     capacity = 256
 
     self.buffer1 = RingBuffer(capacity=capacity, dtype=np.float32)
     self.buffer2 = RingBuffer(capacity=capacity, dtype=np.float32)
     self.buffer3 = RingBuffer(capacity=capacity, dtype=np.float32)
     self.buffer4 = RingBuffer(capacity=capacity, dtype=np.float32)
     
     self.plot = PlotWidget()
     self.plot.getPlotItem().showGrid(x=True, y=True, alpha=1)
     self.plot.addLegend()
     if "qdarkstyle" in sys.modules:
         self.plot.setBackground((25, 35, 45))
         
     self.bufferSizeEdit = QLineEdit()
     self.bufferSizeEdit.setText(str(capacity))
     self.bufferSizeEdit.setValidator(QRegExpValidator(QRegExp("[0-9]*")))
     self.bufferSizeEdit.editingFinished.connect(self.change_capacity)
     
     self.layout = QVBoxLayout()
     
     group = QGroupBox("Combined controller plot")
     
     layout = QVBoxLayout()
     layout.addWidget(self.plot)
     
     innerLayout = QHBoxLayout()
     innerLayout.addWidget(QLabel("Buffer size"))
     innerLayout.addWidget(self.bufferSizeEdit)
     layout.addLayout(innerLayout)
     
     group.setLayout(layout)
     self.layout.addWidget(group)
     self.setLayout(self.layout)
コード例 #25
0
    def __init__(self,
                 default,
                 view,
                 lock_checked=False,
                 default_checked=False,
                 subgait=None):
        self._lock_checked = lock_checked
        self._default_checked = default_checked
        self._subgait = subgait
        self._default = default
        self.view = view

        self.settings_history = RingBuffer(capacity=100, dtype=list)
        self.settings_redo_list = RingBuffer(capacity=100, dtype=list)
コード例 #26
0
	def __init__(self, worker_id, hparams, processing_queue):
		self.id = worker_id
		self.hparams = hparams

		self.processing_queue = processing_queue
		self.inbox_queue = mp.Queue()
		self.experience_queue = mp.Queue()

		self.global_obs = dict()
		self.state = RingBuffer(capacity=self.hparams['state_dim'], dtype=np.float32)

		self.process = mp.Process(
			target=self.run
		)
コード例 #27
0
ファイル: Block.py プロジェクト: kingkong135/Sudoku-solver
    def __init__(self):
        self.img = None
        self.number = 0

        self.prev_guesses = RingBuffer(capacity=5, dtype=(float, (10)))

        self.fontsize = 0
        self.block_pos = (0, 0)
        self.physical_pos = (0, 0)

        self.n = 0

        # Guesses the number every self.maxtimer frames (10), to not overuse resources
        self.maxtimer = 10
        self.timer = self.maxtimer - 1
コード例 #28
0
class CausalIntegralFilter():
    def __init__(self, initial_value, initial_time):
        self._y = initial_value
        self._t_buffer = RingBuffer(2)
        self._t_buffer.append(initial_time)

    def append_integral_value(self, y):
        self._y = y

    def append(self, dydt, t):
        self._t_buffer.append(t)
        self._y += dydt * (self._t_buffer[-1] - self._t_buffer[-2])

    def get_datum(self):
        return self._y
コード例 #29
0
    def __init__(self, channel_len, window_class, window_overlap,
                 sampling_freq, ring_lock):
        global ring_data
        threading.Thread.__init__(self)
        Saving.__init__(self)

        self.clf = None
        self.window_class = window_class  # seconds
        self.window_overlap = window_overlap  # seconds
        self.sampling_freq = sampling_freq
        self.counter = -1
        self.ring_lock = ring_lock
        self.flag_channel_same_len = False

        self.__ring_channel_len = len(ring_data)
        self.__channel_len = channel_len

        self.data_raw = [
            RingBuffer(capacity=int(self.window_class * self.sampling_freq),
                       dtype=np.float64)
            for __ in range(self.__ring_channel_len)
        ]

        self.channel_decode = []

        self.prediction = []
        # self.prediction = [[] for __ in range(self.__channel_len)]

        Display.__init__(self, self.__channel_len)
コード例 #30
0
 def __init__(self,
              name,
              MIN_PITCH,
              MAX_PITCH,
              rescale_range,
              smoothing=50):
     self.name = name
     self.MIN_PITCH = MIN_PITCH
     self.MAX_PITCH = MAX_PITCH
     self.min_pitch_range = float('inf')
     self.max_pitch_range = float('-inf')
     self.rescale_range = rescale_range
     self.img = np.zeros((512, 512, 3), np.uint8)
     self.smooth_buffer = RingBuffer(capacity=smoothing, dtype=np.int)
     self.all_pitches = []
     self.full_signal = []
コード例 #31
0
ファイル: audioplot.py プロジェクト: MathieuDuponchelle/blog
    def do_set_caps(self, icaps, ocaps):
        in_info = GstAudio.AudioInfo()
        in_info.from_caps(icaps)
        out_info = GstVideo.VideoInfo()
        out_info.from_caps(ocaps)

        self.convert_info = GstAudio.AudioInfo()
        self.convert_info.set_format(GstAudio.AudioFormat.S32,
                                     in_info.rate,
                                     in_info.channels,
                                     in_info.position)
        self.converter = GstAudio.AudioConverter.new(GstAudio.AudioConverterFlags.NONE,
                                                     in_info,
                                                     self.convert_info,
                                                     None)

        self.fig = plt.figure()
        dpi = self.fig.get_dpi()
        self.fig.patch.set_alpha(0.3)
        self.fig.set_size_inches(out_info.width / float(dpi),
                                 out_info.height / float(dpi))
        self.ax = plt.Axes(self.fig, [0., 0., 1., 1.])
        self.fig.add_axes(self.ax)
        self.ax.set_axis_off()
        self.ax.set_ylim((GLib.MININT, GLib.MAXINT))
        self.agg = self.fig.canvas.switch_backends(FigureCanvasAgg)
        self.h = None

        samplesperwindow = int(in_info.rate * in_info.channels * self.window_duration)
        self.thinning_factor = max(int(samplesperwindow / out_info.width - 1), 1)

        cap = int(samplesperwindow / self.thinning_factor)
        self.ax.set_xlim([0, cap])
        self.ringbuffer = RingBuffer(capacity=cap)
        self.ringbuffer.extend([0.0] * cap)
        self.frame_duration = Gst.util_uint64_scale_int(Gst.SECOND,
                                                        out_info.fps_d,
                                                        out_info.fps_n)
        self.next_time = self.frame_duration

        self.agg.draw()
        self.background = self.fig.canvas.copy_from_bbox(self.ax.bbox)

        self.samplesperbuffer = Gst.util_uint64_scale_int(in_info.rate * in_info.channels,
                                                          out_info.fps_d,
                                                          out_info.fps_n)
        self.next_offset = self.samplesperbuffer
        self.cur_offset = 0
        self.buf_offset = 0

        return True
コード例 #32
0
ファイル: audioplot.py プロジェクト: MathieuDuponchelle/blog
class AudioPlotFilter(GstBase.BaseTransform):
    __gstmetadata__ = ('AudioPlotFilter','Filter', \
                      'Plot audio waveforms', 'Mathieu Duponchelle')

    __gsttemplates__ = (Gst.PadTemplate.new("src",
                                            Gst.PadDirection.SRC,
                                            Gst.PadPresence.ALWAYS,
                                            OCAPS),
                        Gst.PadTemplate.new("sink",
                                            Gst.PadDirection.SINK,
                                            Gst.PadPresence.ALWAYS,
                                            ICAPS))
    __gproperties__ = {
        "window-duration": (float,
                   "Window Duration",
                   "Duration of the sliding window, in seconds",
                   0.01,
                   100.0,
                   DEFAULT_WINDOW_DURATION,
                   GObject.ParamFlags.READWRITE
                  )
    }

    def __init__(self):
        GstBase.BaseTransform.__init__(self)
        self.window_duration = DEFAULT_WINDOW_DURATION

    def do_get_property(self, prop):
        if prop.name == 'window-duration':
            return self.window_duration
        else:
            raise AttributeError('unknown property %s' % prop.name)

    def do_set_property(self, prop, value):
        if prop.name == 'window-duration':
            self.window_duration = value
        else:
            raise AttributeError('unknown property %s' % prop.name)

    def do_transform(self, inbuf, outbuf):
        if not self.h:
            self.h, = self.ax.plot(np.array(self.ringbuffer),
                                   lw=0.5,
                                   color='k',
                                   path_effects=[pe.Stroke(linewidth=1.0,
                                                           foreground='g'),
                                                 pe.Normal()])
        else:
            self.h.set_ydata(np.array(self.ringbuffer))

        self.fig.canvas.restore_region(self.background)
        self.ax.draw_artist(self.h)
        self.fig.canvas.blit(self.ax.bbox)

        s = self.agg.tostring_argb()

        outbuf.fill(0, s)
        outbuf.pts = self.next_time
        outbuf.duration = self.frame_duration

        self.next_time += self.frame_duration

        return Gst.FlowReturn.OK

    def __append(self, data):
        arr = np.array(data)
        end = self.thinning_factor * int(len(arr) / self.thinning_factor)
        arr = np.mean(arr[:end].reshape(-1, self.thinning_factor), 1)
        self.ringbuffer.extend(arr)

    def do_generate_output(self):
        inbuf = self.queued_buf
        _, info = inbuf.map(Gst.MapFlags.READ)
        res, data = self.converter.convert(GstAudio.AudioConverterFlags.NONE,
                                            info.data)
        data = memoryview(data).cast('i')

        nsamples = len(data) - self.buf_offset

        if nsamples == 0:
            self.buf_offset = 0
            inbuf.unmap(info)
            return Gst.FlowReturn.OK, None

        if self.cur_offset + nsamples < self.next_offset:
            self.__append(data[self.buf_offset:])
            self.buf_offset = 0
            self.cur_offset += nsamples
            inbuf.unmap(info)
            return Gst.FlowReturn.OK, None

        consumed = self.next_offset - self.cur_offset

        self.__append(data[self.buf_offset:self.buf_offset + consumed])
        inbuf.unmap(info)

        _, outbuf = GstBase.BaseTransform.do_prepare_output_buffer(self, inbuf)

        ret = self.do_transform(inbuf, outbuf)

        self.next_offset += self.samplesperbuffer

        self.cur_offset += consumed
        self.buf_offset += consumed

        return ret, outbuf

    def do_transform_caps(self, direction, caps, filter_):
        if direction == Gst.PadDirection.SRC:
            res = ICAPS
        else:
            res = OCAPS

        if filter_:
            res = res.intersect(filter_)

        return res

    def do_fixate_caps(self, direction, caps, othercaps):
        if direction == Gst.PadDirection.SRC:
            return othercaps.fixate()
        else:
            so = othercaps.get_structure(0).copy()
            so.fixate_field_nearest_fraction("framerate",
                                             DEFAULT_FRAMERATE_NUM,
                                             DEFAULT_FRAMERATE_DENOM)
            so.fixate_field_nearest_int("width", DEFAULT_WIDTH)
            so.fixate_field_nearest_int("height", DEFAULT_HEIGHT)
            ret = Gst.Caps.new_empty()
            ret.append_structure(so)
            return ret.fixate()

    def do_set_caps(self, icaps, ocaps):
        in_info = GstAudio.AudioInfo()
        in_info.from_caps(icaps)
        out_info = GstVideo.VideoInfo()
        out_info.from_caps(ocaps)

        self.convert_info = GstAudio.AudioInfo()
        self.convert_info.set_format(GstAudio.AudioFormat.S32,
                                     in_info.rate,
                                     in_info.channels,
                                     in_info.position)
        self.converter = GstAudio.AudioConverter.new(GstAudio.AudioConverterFlags.NONE,
                                                     in_info,
                                                     self.convert_info,
                                                     None)

        self.fig = plt.figure()
        dpi = self.fig.get_dpi()
        self.fig.patch.set_alpha(0.3)
        self.fig.set_size_inches(out_info.width / float(dpi),
                                 out_info.height / float(dpi))
        self.ax = plt.Axes(self.fig, [0., 0., 1., 1.])
        self.fig.add_axes(self.ax)
        self.ax.set_axis_off()
        self.ax.set_ylim((GLib.MININT, GLib.MAXINT))
        self.agg = self.fig.canvas.switch_backends(FigureCanvasAgg)
        self.h = None

        samplesperwindow = int(in_info.rate * in_info.channels * self.window_duration)
        self.thinning_factor = max(int(samplesperwindow / out_info.width - 1), 1)

        cap = int(samplesperwindow / self.thinning_factor)
        self.ax.set_xlim([0, cap])
        self.ringbuffer = RingBuffer(capacity=cap)
        self.ringbuffer.extend([0.0] * cap)
        self.frame_duration = Gst.util_uint64_scale_int(Gst.SECOND,
                                                        out_info.fps_d,
                                                        out_info.fps_n)
        self.next_time = self.frame_duration

        self.agg.draw()
        self.background = self.fig.canvas.copy_from_bbox(self.ax.bbox)

        self.samplesperbuffer = Gst.util_uint64_scale_int(in_info.rate * in_info.channels,
                                                          out_info.fps_d,
                                                          out_info.fps_n)
        self.next_offset = self.samplesperbuffer
        self.cur_offset = 0
        self.buf_offset = 0

        return True