def test_mask(self):
        "Test generation of a mask"

        # 1. Test mask from problem discription
        myfft = fft.FFT()
        self.assertEqual(myfft.mask(2, 15), MASK_TEXT)

        # 2. Test masks from example
        myfft = fft.FFT()
        for num in range(1, 9):
            self.assertEqual(myfft.mask(num, 8), MASK_EXAMPLE[num])
Beispiel #2
0
    def setup_audio(self):
        """Setup audio file

        and setup the output.  device.output is a lambda that will send data to
        fm process or to the specified ALSA sound card
        """
        # Set up audio
        force_header = False

        if any([ax for ax in [".mp4", ".m4a", ".m4b"] if ax in self.song_filename]):
            force_header = True

        self.music_file = decoder.open(self.song_filename, force_header)

        self.sample_rate = self.music_file.getframerate()
        self.num_channels = self.music_file.getnchannels()

        self.fft_calc = fft.FFT(self.chunk_size,
                                self.sample_rate,
                                cm.hardware.gpio_len,
                                cm.audio_processing.min_frequency,
                                cm.audio_processing.max_frequency,
                                cm.audio_processing.custom_channel_mapping,
                                cm.audio_processing.custom_channel_frequencies)

        # setup output device
        self.set_audio_device()

        chunks_per_sec = ((16 * self.num_channels * self.sample_rate) / 8) / self.chunk_size
        self.light_delay = int(cm.lightshow.light_delay * chunks_per_sec)

        # Output a bit about what we're about to play to the logs
        num_frames = str(self.music_file.getnframes() / self.sample_rate)
        log.info("Playing: " + self.song_filename + " (" + num_frames + " sec)")
Beispiel #3
0
def cache_song(song_filename, chunk_size):
    music_file = audio_decoder.open(song_filename)
    sample_rate = music_file.getframerate()
    num_channels = music_file.getnchannels()
    logging.info("Sample rate: %s" % sample_rate)
    logging.info("Channels: %s" % num_channels)
    logging.info("Frame size: %s" % music_file.getsampwidth())

    fft_calc = fft.FFT(chunk_size, sample_rate, hc.GPIOLEN, _MIN_FREQUENCY,
                       _MAX_FREQUENCY, _CUSTOM_CHANNEL_MAPPING,
                       _CUSTOM_CHANNEL_FREQUENCIES)

    # Init cache matrix
    cache_matrix = np.empty(shape=[0, hc.GPIOLEN])
    cache_filename = os.path.dirname(song_filename) + "/." + os.path.basename(
        song_filename) + ".sync"
    cache_found = fft_calc.compare_config(cache_filename)

    if cache_found:
        mean, std, cache_matrix = load_cached_fft(fft_calc, cache_filename)
    else:
        # The values 12 and 1.5 are good estimates for first time playing back
        # (i.e. before we have the actual mean and standard deviations
        # calculated for each channel).
        mean = [12.0] * hc.GPIOLEN
        std = [1.5] * hc.GPIOLEN
        total = 0
        while True:
            data = music_file.readframes(chunk_size)
            if not data:
                break
            total += len(data)

            matrix = fft_calc.calculate_levels(data)
            # Add the matrix to the end of the cache
            cache_matrix = np.vstack([cache_matrix, matrix])

        for i in range(0, hc.GPIOLEN):
            std[i] = np.std([item for item in cache_matrix[:, i] if item > 0])
            mean[i] = np.mean(
                [item for item in cache_matrix[:, i] if item > 0])

        # Add mean and std to the top of the cache
        cache_matrix = np.vstack([mean, cache_matrix])
        cache_matrix = np.vstack([std, cache_matrix])

        # Save the cache using numpy savetxt
        np.savetxt(cache_filename, cache_matrix)

        # Save fft config
        fft_calc.save_config()

        logging.info("Cached sync data written to '." + cache_filename +
                     "' [" + str(len(cache_matrix)) + " rows]")

        logging.info("Cached config data written to '." +
                     fft_calc.config_filename)
    music_file.close()
    return mean, std, cache_matrix
    def test_empty_init(self):
        """Test default FFT object creation"""

        # 1. Create default FFT object
        myfft = fft.FFT()

        # 2. Make sure it has the default values
        self.assertEqual(myfft.pattern, fft.BASE_PATTERN)
    def test_value_init(self):
        "Test FFT object creation with values"

        # 1. Create Panel object with values
        myfft = fft.FFT(pattern=[1, 2, 3])

        # 2. Make sure it has the specified values
        self.assertEqual(myfft.pattern, [1, 2, 3])
Beispiel #6
0
 def __init__(self, model: str, market: EvalArgs, use_fft: bool, fft_alpha=None):
     self.model = model
     self.market = market
     if use_fft and model in fft.supported_models:
         self.price_impl = lambda pars, args: fft.FFT(model=model, args=args, alpha=fft_alpha).price(pars=pars)
     else:
         try:
             self.price_impl = lambda pars, args: optimization.models[self.model](pars=pars, args=args)
         except KeyError:
             raise ValueError(f"Unsupported model: {model}")
    def test_short(self):
        "Test short transformations"

        # 1. Create a transformer
        myfft = fft.FFT()

        # 2. Do the transformation
        digits = myfft.transform(PHASES[0], phases=4)

        # 3. Verify the results
        self.assertEqual(digits, [int(_) for _ in PHASES[4]])
Beispiel #8
0
def test_fft():
    spot = 100
    strikes = np.array([90, 100, 110])
    t = 1.2
    r = .008
    q = r
    args_vg = (spot, strikes, t, r, q, True)
    pars_vg = (.2, -.4, .1)
    vg_prices1 = vg.price_vg(pars=pars_vg, args=args_vg)
    vg_prices2 = fft.FFT(model='vg', args=args_vg).price(pars_vg)
    pass
Beispiel #9
0
def part_two(args, input_lines):
    "Process part two of the puzzle"

    # 1. Create the transfomer (Robots in Disguise)
    rid = fft.FFT()

    # 2. Transform the ingut
    solution = rid.real_signal(input_lines[0], watch=args.verbose)
    print("The eight-digits message embedded in the final output list is %s" % (str(solution)))

    # 3. Return result
    return solution is not None
Beispiel #10
0
    def test_phase(self):
        "Test phase transformations"

        # 1. Create a transformer
        myfft = fft.FFT()

        # 2. Get the starting digite
        digits = [int(_) for _ in PHASES[0]]

        # 3. Do four phases, checking the result
        for num in range(1, 5):
            digits = myfft.phase(digits)
            self.assertEqual(digits, [int(_) for _ in PHASES[num]])
Beispiel #11
0
def part_one(args, input_lines):
    "Process part one of the puzzle"

    # 1. Create the transfomer (Robots in Disguise)
    rid = fft.FFT()

    # 2. Transform the ingut
    result = rid.transform(input_lines[0], watch=args.verbose)
    solution = result[:8]
    print("The first eight digits in the final output list is %s" % (str(solution)))

    # 3. Return result
    return solution is not None
Beispiel #12
0
    def test_real_signal(self):
        "Test transformations of real_signals"

        # 1. Create a transformer
        myfft = fft.FFT()

        # 2. Loop for the three examples
        for num in range(3):

            # 3. Transform the digits
            digits = myfft.real_signal(REAL_INP[num])

            # 4. Verify the results
            self.assertEqual(digits, REAL_OUT[num])
Beispiel #13
0
    def test_larger(self):
        "Test transformations of larger inputs"

        # 1. Create a transformer
        myfft = fft.FFT()

        # 2. Loop for the three examples
        for num in range(3):

            # 3. Transform the digits
            digits = myfft.transform(LARGER_INP[num])

            # 4. Verify the results
            self.assertEqual('%d%d%d%d%d%d%d%d' %
                             (digits[0], digits[1], digits[2], digits[3],
                              digits[4], digits[5], digits[6], digits[7]),
                             LARGER_OUT[num])
def setup_audio(song_filename):
    """Setup audio file

    and setup setup the output device.output is a lambda that will send data to
    fm process or to the specified ALSA sound card

    :param song_filename: path / filename to music file
    :type song_filename: str
    :return: output, fm_process, fft_calc, music_file
    :rtype tuple: lambda, subprocess, fft.FFT, decoder
    """
    # Set up audio
    force_header = False

    if any([ax for ax in [".mp4", ".m4a", ".m4b"] if ax in song_filename]):
        force_header = True

    music_file = decoder.open(song_filename, force_header)

    sample_rate = music_file.getframerate()
    num_channels = music_file.getnchannels()

    fft_calc = fft.FFT(CHUNK_SIZE, sample_rate, hc.GPIOLEN,
                       cm.audio_processing.min_frequency,
                       cm.audio_processing.max_frequency,
                       cm.audio_processing.custom_channel_mapping,
                       cm.audio_processing.custom_channel_frequencies)

    # setup output device
    output = set_audio_device(sample_rate, num_channels)

    chunks_per_sec = ((16 * num_channels * sample_rate) / 8) / CHUNK_SIZE
    light_delay = int(cm.audio_processing.light_delay * chunks_per_sec)

    # Output a bit about what we're about to play to the logs
    nframes = str(music_file.getnframes() / sample_rate)
    log.info("Playing: " + song_filename + " (" + nframes + " sec)")

    return output, fft_calc, music_file, light_delay
Beispiel #15
0
def audio_in():
    """Control the lightshow from audio coming in from a USB audio card"""
    sample_rate = cm.lightshow()['audio_in_sample_rate']
    input_channels = cm.lightshow()['audio_in_channels']

    # Open the input stream from default input device
    audio_in_card = cm.lightshow()['audio_in_card']
    stream = aa.PCM(aa.PCM_CAPTURE, aa.PCM_NORMAL, audio_in_card)
    stream.setchannels(input_channels)
    stream.setformat(aa.PCM_FORMAT_S16_LE)  # Expose in config if needed
    stream.setrate(sample_rate)
    stream.setperiodsize(CHUNK_SIZE)

    logging.debug("Running in audio-in mode - will run until Ctrl+C "
                  "is pressed")
    print "Running in audio-in mode, use Ctrl+C to stop"

    # Start with these as our initial guesses - will calculate a rolling
    # mean / std as we get input data.
    mean = np.array([12.0] * hc.GPIOLEN, dtype='float64')
    std = np.array([1.5] * hc.GPIOLEN, dtype='float64')
    count = 2

    running_stats = running_stats.Stats(hc.GPIOLEN)

    # preload running_stats to avoid errors, and give us a show that looks
    # good right from the start
    running_stats.preload(mean, std, count)

    try:
        hc.initialize()
        fft_calc = fft.FFT(CHUNK_SIZE, sample_rate, hc.GPIOLEN, _MIN_FREQUENCY,
                           _MAX_FREQUENCY, _CUSTOM_CHANNEL_MAPPING,
                           _CUSTOM_CHANNEL_FREQUENCIES, input_channels)

        # Listen on the audio input device until CTRL-C is pressed
        while True:
            length, data = stream.read()
            if length > 0:
                # if the maximum of the absolute value of all samples in
                # data is below a threshold we will disreguard it
                audio_max = audioop.max(data, 2)
                if audio_max < 250:
                    # we will fill the matrix with zeros and turn the
                    # lights off
                    matrix = np.zeros(hc.GPIOLEN, dtype="float64")
                    logging.debug("below threshold: '" + str(audio_max) +
                                  "', turning the lights off")
                else:
                    matrix = fft_calc.calculate_levels(data)
                    running_stats.push(matrix)
                    mean = running_stats.mean()
                    std = running_stats.std()

                update_lights(matrix, mean, std)

    except KeyboardInterrupt:
        pass

    finally:
        print "\nStopping"
        hc.clean_up()
Beispiel #16
0
    def audio_in(self):
        """Control the lightshow from audio coming in from a real time audio"""

        self.sample_rate = cm.lightshow.input_sample_rate
        self.num_channels = cm.lightshow.input_channels

        stream_reader, outq = self.set_audio_source()

        log.debug("Running in %s mode - will run until Ctrl+C is pressed" %
                  cm.lightshow.mode)
        print "Running in %s mode, use Ctrl+C to stop" % cm.lightshow.mode

        # setup light_delay.
        chunks_per_sec = (
            (16 * self.num_channels * self.sample_rate) / 8) / self.chunk_size
        light_delay = int(cm.lightshow.light_delay * chunks_per_sec)
        matrix_buffer = deque([], 1000)

        self.set_audio_device()

        # Start with these as our initial guesses - will calculate a rolling mean / std
        # as we get input data.
        # preload running_stats to avoid errors, and give us a show that looks
        # good right from the start
        count = 2
        running_stats = RunningStats.Stats(cm.hardware.gpio_len)
        running_stats.preload(self.mean, self.std, count)

        hc.initialize()
        fft_calc = fft.FFT(self.chunk_size, self.sample_rate,
                           cm.hardware.gpio_len,
                           cm.audio_processing.min_frequency,
                           cm.audio_processing.max_frequency,
                           cm.audio_processing.custom_channel_mapping,
                           cm.audio_processing.custom_channel_frequencies, 1)

        if self.server:
            self.network.set_playing()

        songcount = 0

        # Listen on the audio input device until CTRL-C is pressed
        while True:

            if cm.lightshow.mode == 'stream-in':
                try:
                    streamout = outq.get_nowait().strip('\n\r')
                except Empty:
                    pass
                else:
                    print streamout
                    if cm.lightshow.stream_song_delim in streamout:
                        songcount += 1
                        streamout = streamout.replace('\033[2K', '')
                        streamout = streamout.replace(
                            cm.lightshow.stream_song_delim, '')
                        streamout = streamout.replace('"', '')
                        os.system("/bin/echo " + "Now Playing \"" + streamout +
                                  "\"" + " >" + cm.home_dir +
                                  "/logs/now_playing.txt")

                        if cm.lightshow.songname_command:
                            os.system(cm.lightshow.songname_command +
                                      ' "Now Playing ' + streamout + '"')

                    if cm.lightshow.stream_song_exit_count > 0 and songcount > cm.lightshow.stream_song_exit_count:
                        break

            try:
                data = stream_reader()

            except OSError as err:
                if err.errno == errno.EAGAIN or err.errno == errno.EWOULDBLOCK:
                    continue
            try:
                self.output(data)
            except aa.ALSAAudioError:
                continue

            if len(data):
                # if the maximum of the absolute value of all samples in
                # data is below a threshold we will disregard it
                audio_max = audioop.max(data, 2)
                if audio_max < 250:
                    # we will fill the matrix with zeros and turn the lights off
                    matrix = np.zeros(cm.hardware.gpio_len, dtype="float32")
                    log.debug("below threshold: '" + str(audio_max) +
                              "', turning the lights off")
                else:
                    matrix = fft_calc.calculate_levels(data)
                    running_stats.push(matrix)
                    self.mean = running_stats.mean()
                    self.std = running_stats.std()

                matrix_buffer.appendleft(matrix)

                if len(matrix_buffer) > light_delay:
                    matrix = matrix_buffer[light_delay]
                    self.update_lights(matrix)
def audio_in():
    """Control the lightshow from audio coming in from a real time audio"""
    global streaming
    stream_reader = None
    streaming = None
    songcount = 0

    sample_rate = cm.lightshow.input_sample_rate
    num_channels = cm.lightshow.input_channels

    if cm.lightshow.mode == 'audio-in':
        # Open the input stream from default input device
        streaming = aa.PCM(aa.PCM_CAPTURE, aa.PCM_NORMAL,
                           cm.lightshow.audio_in_card)
        streaming.setchannels(num_channels)
        streaming.setformat(aa.PCM_FORMAT_S16_LE)  # Expose in config if needed
        streaming.setrate(sample_rate)
        streaming.setperiodsize(CHUNK_SIZE)

        stream_reader = lambda: streaming.read()[-1]

    elif cm.lightshow.mode == 'stream-in':

        outq = Queue()

        if cm.lightshow.use_fifo:
            streaming = subprocess.Popen(cm.lightshow.stream_command_string,
                                         stdin=subprocess.PIPE,
                                         stdout=subprocess.PIPE,
                                         preexec_fn=os.setsid)
            io = os.open(cm.lightshow.fifo, os.O_RDONLY | os.O_NONBLOCK)
            stream_reader = lambda: os.read(io, CHUNK_SIZE)
            outthr = Thread(target=enqueue_output,
                            args=(streaming.stdout, outq))
        else:
            # Open the input stream from command string
            streaming = subprocess.Popen(cm.lightshow.stream_command_string,
                                         stdin=subprocess.PIPE,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE)
            stream_reader = lambda: streaming.stdout.read(CHUNK_SIZE)
            outthr = Thread(target=enqueue_output,
                            args=(streaming.stderr, outq))

        outthr.daemon = True
        outthr.start()

    log.debug("Running in %s mode - will run until Ctrl+C is pressed" %
              cm.lightshow.mode)
    print "Running in %s mode, use Ctrl+C to stop" % cm.lightshow.mode

    # setup light_delay.
    chunks_per_sec = ((16 * num_channels * sample_rate) / 8) / CHUNK_SIZE
    light_delay = int(cm.audio_processing.light_delay * chunks_per_sec)
    matrix_buffer = deque([], 1000)

    output = set_audio_device(sample_rate, num_channels)

    # Start with these as our initial guesses - will calculate a rolling mean / std
    # as we get input data.
    mean = np.array([12.0 for _ in range(hc.GPIOLEN)], dtype='float32')
    std = np.array([1.5 for _ in range(hc.GPIOLEN)], dtype='float32')
    count = 2

    running_stats = RunningStats.Stats(hc.GPIOLEN)

    # preload running_stats to avoid errors, and give us a show that looks
    # good right from the start
    running_stats.preload(mean, std, count)

    hc.initialize()
    fft_calc = fft.FFT(CHUNK_SIZE, sample_rate, hc.GPIOLEN,
                       cm.audio_processing.min_frequency,
                       cm.audio_processing.max_frequency,
                       cm.audio_processing.custom_channel_mapping,
                       cm.audio_processing.custom_channel_frequencies, 1)

    if server:
        network.set_playing()

    # Listen on the audio input device until CTRL-C is pressed
    while True:

        try:
            streamout = outq.get_nowait().strip('\n\r')
        except Empty:
            pass
        else:
            print streamout
            if cm.lightshow.stream_song_delim in streamout:
                songcount += 1
                if cm.lightshow.songname_command:
                    streamout = streamout.replace('\033[2K', '')
                    streamout = streamout.replace(
                        cm.lightshow.stream_song_delim, '')
                    streamout = streamout.replace('"', '')
                    os.system(cm.lightshow.songname_command +
                              ' "Now Playing ' + streamout + '"')

            if cm.lightshow.stream_song_exit_count > 0 and songcount > cm.lightshow.stream_song_exit_count:
                break

        try:
            data = stream_reader()

        except OSError as err:
            if err.errno == errno.EAGAIN or err.errno == errno.EWOULDBLOCK:
                continue
        try:
            output(data)
        except aa.ALSAAudioError:
            continue

        if len(data):
            # if the maximum of the absolute value of all samples in
            # data is below a threshold we will disregard it
            audio_max = audioop.max(data, 2)
            if audio_max < 250:
                # we will fill the matrix with zeros and turn the lights off
                matrix = np.zeros(hc.GPIOLEN, dtype="float32")
                log.debug("below threshold: '" + str(audio_max) +
                          "', turning the lights off")
            else:
                matrix = fft_calc.calculate_levels(data)
                running_stats.push(matrix)
                mean = running_stats.mean()
                std = running_stats.std()

            matrix_buffer.appendleft(matrix)

            if len(matrix_buffer) > light_delay:
                matrix = matrix_buffer[light_delay]
                update_lights(matrix, mean, std)
Beispiel #18
0
import fft
import sys

filename = sys.argv[1]
f = fft.FFT(filename)
print(f.process(100))

Beispiel #19
0
import fft
import matplotlib.pyplot as plt
import numpy as np
import sys

lattice = fft.FFT(2, 32, mass=0.5)

steps = int(50000)
ones = []
twos = []
threes = []
fours = []
total_actions = []


def update_progress(progress):
    barLength = 50  # Modify this to change the length of the progress bar
    status = ""
    if isinstance(progress, int):
        progress = float(progress)
    if not isinstance(progress, float):
        progress = 0
        status = "error: progress var must be float\r\n"
    if progress < 0:
        progress = 0
        status = "Halt...\r\n"
    if progress >= 1:
        progress = 1
        status = "Done...\r\n"
    block = int(round(barLength * progress))
    text = "\rPercent: [{0}] {1}% {2}".format( "#"*block +\
import hardware_adapter
import services.Service
import configuration_manager
from log import setup_logger

cm = configuration_manager.Configuration()

GPIO_LEN = 6

config_path = os.path.dirname(
    os.path.realpath(__file__)) + '/../config/mopidy.conf'
logger = setup_logger("Light Show Service")
decay = np.zeros(GPIO_LEN, dtype='float32')
fft_calc = fft.FFT(cm.light_show.chunk_size, cm.light_show.sample_rate,
                   GPIO_LEN, cm.light_show.min_frequency,
                   cm.light_show.max_frequency,
                   cm.light_show.custom_channel_mapping,
                   cm.light_show.custom_channel_frequencies, 1)


class LightShowService(services.Service.Service):
    def __init__(self):
        super().__init__()
        self.requires_gpio = True
        self.process = None

    def run(self):
        hardware_adapter.enable_gpio()
        setup_fifo()
        self.process = subprocess.Popen(['mopidy', '--config', config_path],
                                        stdout=subprocess.PIPE,
Beispiel #21
0
    def calculate(self, **kwargs):
        ''' Calculate power/bispectrum for catalog 
        '''

        # FFt files
        D_fft = spec_fft.FFT('data', self.catalog, **kwargs)
        D_fft_file = D_fft.file_name

        R_fft = spec_fft.FFT('random', self.catalog, **kwargs)
        R_fft_file = R_fft.file_name

        # if FFT file does not exist
        if not os.path.isfile(D_fft_file):
            D_fft.calculate()

        if not os.path.isfile(R_fft_file):
            R_fft.calculate()

        spec_code = spec_fort.fortran_code(self.Type, self.catalog, **kwargs)
        spec_exe = spec_fort.fortran_code2exe(spec_code)

        # code and exe modification time
        spec_code_mod_time = os.path.getmtime(spec_code)
        if not os.path.isfile(spec_exe):
            spec_exe_mod_time = 0
        else:
            spec_exe_mod_time = os.path.getmtime(spec_exe)

        # if code was changed since exe file was last compiled then
        # compile spec code
        if spec_exe_mod_time < spec_code_mod_time:
            spec_fort.compile_fortran_code(spec_code)

        spec = self.catalog['spec']
        if self.Type == 'power':
            # power spectrum code input:
            #    random fft file, data fft file, powerspectrum file, Lbox, Nbins
            spec_cmd = ' '.join([
                spec_exe, R_fft_file, D_fft_file, self.file_name,
                str(spec['sscale']),
                str(spec['grid'] / 2)
            ])

        elif self.Type == 'bispec':  # bispectrum
            # double check that the counts are there
            # hardcoded
            count_file = '/home/users/rs123/Code/Fortran/counts2quad_n360_nmax40_ncut3_s3'
            self.count_file = count_file

            if not os.path.isfile(count_file):
                raise NotImplementedError('Count File does not exist')

            # bispectrum code input:
            #   period/data, random fft file, data fft file, bispectrum file
            spec_cmd = ' '.join(
                [spec_exe, '2', R_fft_file, D_fft_file, self.file_name])

        print spec_cmd
        subprocess.call(spec_cmd.split())

        return None
Beispiel #22
0
                    type=int,
                    help='fft frame size')
parser.add_argument('--fft_step', default=256, type=int, help='fft step')
parser.add_argument('--phase_smooth',
                    default=4,
                    type=int,
                    help='phase smoothing')

args = parser.parse_args(''.split())

jack_to_accumulator = queue.Queue(maxsize=128)
accumulator_to_delay_tracker = queue.Queue(maxsize=128)
delay_tracker_to_fft = queue.Queue(maxsize=128)
fft_to_graphics = queue.Queue(maxsize=128)

jcli = jack_client.JackClient(jack_to_accumulator, args.num_channels, 'shark')
acc = accumulator.Accumulator(jack_to_accumulator,
                              accumulator_to_delay_tracker, args.accumulator)
dtracker = delay_tracker.DelayTracker(accumulator_to_delay_tracker,
                                      delay_tracker_to_fft)
fftop = fft.FFT(delay_tracker_to_fft, fft_to_graphics, fft_params=args)
render = display.Display(fft_to_graphics,
                         jcli.client.samplerate,
                         fft_params=args)

render.start()
fftop.start()
dtracker.start()
acc.start()
jcli.activate()
def cache_song(song_filename):
    """Play the next song from the play list (or --file argument)."""
    # Initialize FFT stats
    matrix = [0 for _ in range(GPIOLEN)] # get length of gpio and assign it to a variable

    # Set up audio
    if song_filename.endswith('.wav'):
        musicfile = wave.open(song_filename, 'r')
    else:
        musicfile = decoder.open(song_filename)

    sample_rate = musicfile.getframerate()
    num_channels = musicfile.getnchannels()

    fft_calc = fft.FFT(CHUNK_SIZE,
                       sample_rate,
                       GPIOLEN,
                       _MIN_FREQUENCY,
                       _MAX_FREQUENCY,
                       _CUSTOM_CHANNEL_MAPPING,
                       _CUSTOM_CHANNEL_FREQUENCIES)

    song_filename = os.path.abspath(song_filename)

    # create empty array for the cache_matrix
    cache_matrix = np.empty(shape=[0, GPIOLEN])
    cache_filename = \
        os.path.dirname(song_filename) + "/." + os.path.basename(song_filename) + ".sync"

    # The values 12 and 1.5 are good estimates for first time playing back 
    # (i.e. before we have the actual mean and standard deviations 
    # calculated for each channel).
    mean = [12.0 for _ in range(GPIOLEN)]
    std = [1.5 for _ in range(GPIOLEN)]

    # Process audio song_filename
    row = 0
    data = musicfile.readframes(CHUNK_SIZE) # move chunk_size to configuration_manager

    while data != '':
        # No cache - Compute FFT in this chunk, and cache results
        matrix = fft_calc.calculate_levels(data)

        # Add the matrix to the end of the cache 
        cache_matrix = np.vstack([cache_matrix, matrix])

        # Read next chunk of data from music song_filename
        data = musicfile.readframes(CHUNK_SIZE)
        row = row + 1

    # Compute the standard deviation and mean values for the cache
    for i in range(0, GPIOLEN):
        std[i] = np.std([item for item in cache_matrix[:, i] if item > 0])
        mean[i] = np.mean([item for item in cache_matrix[:, i] if item > 0])

    # Add mean and std to the top of the cache
    cache_matrix = np.vstack([mean, cache_matrix])
    cache_matrix = np.vstack([std, cache_matrix])

    # Save the cache using numpy savetxt
    np.savetxt(cache_filename, cache_matrix)
Beispiel #24
0
import fft
import sys

import logging
logging.getLogger("fft").setLevel(logging.DEBUG)

filename = sys.argv[1]
f = fft.FFT(filename, 10000)
print(f.process(100))
Beispiel #25
0
import matplotlib.pyplot as plt 
import rsg
import numpy as np
import fft

plt.style.use('bmh')

harmonics_count = 8
frequency = 1500
N = 1024

signals = rsg.generateSignal(harmonics_count,frequency,N)
AFFT = np.abs(fft.FFT(signals))

fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)
fig.subplots_adjust(hspace=0.5)
fig.set_size_inches(12,6)

ax1.plot(signals)
ax1.set_xlim(0, int(N/4))
ax1.set(xlabel='Time', ylabel='Signal(t)',
        title='Random generated signals')

ax2.plot(AFFT)
ax2.set_xlim(0, int(N/4))
ax2.set(xlabel='Time', ylabel='Freq (Hz)',
        title='Frequency spectrum(FFT)')      

fig.savefig("plot(fft).png")
plt.show()
Beispiel #26
0
import rsg
import fft
import numpy as np
from time import perf_counter

harmonics_count = 8
frequency = 1500

for i in range(2, 13):
    N = 2**i
    signals = rsg.generateSignal(harmonics_count, frequency, N)

    t_start = perf_counter()
    fft.FFT(signals)
    t_end = perf_counter()
    time1 = t_end - t_start

    t_start = perf_counter()
    np.fft.fft(signals)
    t_end = perf_counter()
    time2 = t_end - t_start

    print("N = 2^{0} ".format(i))
    print("time : {0}s (my fft)".format(time1))
    print("time : {0}s (numpy fft)\n".format(time2))