Esempio n. 1
0
def Skew_Term_plot(sigma, v0, kappa, rho, theta):
    parameters = [sigma, v0, kappa, rho, theta]
    param_name = ['sigma', 'v0', 'kappa', 'rho', 'theta']
    chg_var = [parameters.index(v) for v in parameters
               if isinstance(v, list)][0]

    title = 'Impact of ' + param_name[chg_var]
    fig, ax = plt.subplots(nrows=1, ncols=2)
    fig.suptitle(title, size=20)

    if chg_var == 0:
        variable = sigma
        for var in variable:
            b = FFT(var, v0, kappa, rho, theta, S0=150, r=0.025, T=0.25)
            K_T_vol_analysis(b, alpha, ax, variable)
    elif chg_var == 1:
        variable = v0
        for var in variable:
            b = FFT(sigma, var, kappa, rho, theta, S0=150, r=0.025, T=0.25)
            K_T_vol_analysis(b, alpha, ax, variable)
    elif chg_var == 2:
        variable = kappa
        for var in variable:
            b = FFT(sigma, v0, var, rho, theta, S0=150, r=0.025, T=0.25)
            K_T_vol_analysis(b, alpha, ax, variable)
    elif chg_var == 3:
        variable = rho
        for var in variable:
            b = FFT(sigma, v0, kappa, var, theta, S0=150, r=0.025, T=0.25)
            K_T_vol_analysis(b, alpha, ax, variable)
    elif chg_var == 4:
        variable = theta
        for var in variable:
            b = FFT(sigma, v0, kappa, rho, var, S0=150, r=0.025, T=0.25)
            K_T_vol_analysis(b, alpha, ax, variable)
Esempio n. 2
0
def main():
    path = 'C:/Users/2015136133/Desktop/' #경로
    fft1 = FFT.FFT()
    fft2 = FFT.FFT()
    fft3 = FFT.FFT()

    startFun(fft1, path + 'fft1.wav') #FFT 과정을 수행함
    startFun(fft2, path + 'fft2.wav') #FFT 과정을 수행함
    startFun(fft3, path + 'fft3.wav') #FFT 과정을 수행함

    #fft1.showPltFFT()
    #fft2.showPltFFT()
    #fft3.showPltFFT()

    fftavg = [((fft1.fftdata[i] + fft2.fftdata[i] + fft3.fftdata[i]) / 3) for i in range(len(fft1.fftdata))]
    # fft1, 2, 3의 평균값을 fftavg에다 넣어줌
    fft4 = FFT.FFT()
    startFun(fft4,path + 'fft4.wav')

    cnt = 0
    for i in range(len(fft4.fftdata)):
        if errrate(fftavg[i],fft4.fftdata[i]) > 70:
            cnt+=1

    print((cnt/len(fftavg)*100), '% 입니다.')

    FFT.FFT.saveTextFile(fft1.freq, fftavg, path + 'avgfft.txt') #fft 평균을 txt로 저장
Esempio n. 3
0
def PCreateFFT(image, dir):
    """
    Create an FFT object suitable for FFTing an image
    
    Create an FFT for an efficient size equal to or larger than image
    One needed for each direction to be FFTed.
    returns  Python FFT object

    * image    = Image to be FFTed
    * dir      = FFT direction 1 -> R2C, 2 -> C2R
    """
    ################################################################
    # Checks
    if not Image.PIsA(image):
        raise TypeError("image MUST be a Python Obit Image")
    #
    # Get image info from descriptor
    desc = image.Desc
    descDict = desc.Dict
    rank = 2    # Only 2D FFTs
    dim  = descDict["inaxes"]
    # Compute size to be efficient
    i = 0
    effDim = []
    for x in dim:
        effDim.append(FFT.PSuggestSize(x))
        i = i+1
    effDim
    name = "FFT for " + Image.PGetName(image)
    out    = FFT.FFT(name, dir, 2, rank, effDim)
    return out
Esempio n. 4
0
def compress(filename="lena.mn",
             output_filename="lena",
             compression_factor=.5):
    '''Writes a compressed mnc file. 
  The number of values kept is the (orginal number)*(compression_factor). 
  This version of the compression function acts on square images only.'''
    data = read_mn(filename)
    transformed_data = FFT(data)
    col_length = len(transformed_data)  #also equals the number of rows
    row_length = len(transformed_data[0])  #also equals the number of columns
    #flatten the array:
    transformed_data = transformed_data.reshape(
        (1, np.multiply(*transformed_data.shape)))[0]
    #given a compression factor, compression threshold is the value below which the...
    #function throws away frequency in the FFT data
    compression_threshold = {'real': 0, 'imag': 0}
    compression_threshold['real'] = find_threshold(transformed_data.real,
                                                   compression_factor)
    compression_threshold['imag'] = find_threshold(transformed_data.imag,
                                                   compression_factor)
    #by symmetry, the lower half of the data can be reproduced by the top half, excluding the first row
    upper_half = np.array(transformed_data[:(col_length / 2 + 1) * row_length])
    #split FFT data into two pieces, real and imag
    uh_real = upper_half.real
    uh_imag = upper_half.imag
    #throw away small values using compression threshold
    uh_real = np.array(
        [i if abs(i) > compression_threshold['real'] else 0 for i in uh_real])
    uh_imag = np.array(
        [i if abs(i) > compression_threshold['imag'] else 0 for i in uh_imag])
    #writes to mnc file
    write_mnc(output_filename + ".mnc",
              np.around(uh_real).astype('int'),
              np.around(uh_imag).astype('int'), (len(data), len(data)),
              (1, 0, 1, 0))
Esempio n. 5
0
    def __init__(self, input_token, threaded=True, kwargs_dict={}):
        """
            The class implements the math processor abstract class
            the arguments in **kwargs are: 
                window_duration 
                window_start 
                number_of_steps 
                animated (if False means only one single frame of fft is calculated)
        """
        window_duration_text = 'window_duration'
        window_start_text = 'window_start'
        number_of_steps_text = 'number_of_steps'
        animated_text = 'animated'

        if (not window_duration_text in kwargs_dict
                or not window_start_text in kwargs_dict
                or not number_of_steps_text in kwargs_dict
                or not animated_text in kwargs_dict):
            raise NecessaryArgNotPresent

        self.__window_duration = kwargs_dict[window_duration_text]
        self.__window_start = kwargs_dict[window_start_text]
        self.__number_of_steps = kwargs_dict[number_of_steps_text]
        self.__animated = kwargs_dict[animated_text]

        super().__init__(input_token, threaded)
        ## The queue to hold fft responses as a function of their
        ## start time
        self.__fft_frames_queue = queue.Queue()
        self.__fft_calculator = FFT.FFT()
Esempio n. 6
0
def pdata():
    while (endFlag == 0):
        for i in range(16):
            data = sdr.read_samples(CHUNK)
    #	data=[0.1+0.1j]*CHUNK
        F = FFT.FFT(data, level)
        q.put(F)
    print('endFlag=', endFlag)
    exit()
Esempio n. 7
0
 def recolectar(self, *args):
     xp = self.xp.get()
     hp = self.hp.get()
     if (xp & hp):
         messagebox.showinfo(message="Solo debe marcar una opción", title="Resultado")
         return;
     if ((not xp) & (not hp)):
         messagebox.showinfo(message="Debe marcar una opción", title="Resultado")
         return;
     if (xp & (not hp)):
         x = self.x.get()
         messagebox.showinfo(message=FFT(formato(x)), title="Resultado")
     if ((not xp) & hp):
         x = self.x.get()
         messagebox.showinfo(message=IFFT(formato(x)), title="Resultado")
Esempio n. 8
0
def getSpectrogram(x):
    spectrums = []
    i = 0
    ##    print len(x)
    while i < len(
            x
    ) - windowSize - 1:  # I ignore the last incomplete window, or we could deal with it using padding technique
        # For a new window, initiate a list
        waves = []
        for j in range(0, windowSize):
            waves.append(x[i + j])
        win = FFT.FFT(waves)
        spectrums.append(win)
        i = i + overlap
    return spectrums
Esempio n. 9
0
    v0 = 0.09
    kappa = 0.5
    rho = 0.25
    theta = 0.12

    S0 = 150
    K = 150
    r = 0.025
    T = 0.25

    n = 10
    B = K * 2.7
    alpha = 1.5

    # (b) i
    b = FFT(sigma, v0, kappa, rho, theta, S0, r, T)
    # K_vol_analysis(b, alpha, n, B, K)

    # (b) ii
    T_vol_analysis(b, alpha, n, B, K)

    # # (b) iii
    # Impact of Sigma
    Skew_Term_plot([0.5, 0.6, 0.7], 0.09, 0.5, 0.25, 0.12)
    # Impact of V0
    Skew_Term_plot(0.4, [0.1, 0.12, 0.14], 0.5, 0.25, 0.12)
    # Impact of k
    Skew_Term_plot(0.4, 0.09, [0.6, 0.8, 1.0], 0.25, 0.12)
    # Impact of rho
    Skew_Term_plot(0.4, 0.09, 0.5, [0.35, 0.45, 0.55], 0.12)
    # # Impact of theta
Esempio n. 10
0
def joint_all_data(first_day_data, data, last_day_data):
    data = np.append(first_day_data, data)
    data = np.append(data, last_day_data)
    return data

if __name__ == "__main__":
    first_day_date,first_day_data,date_list,data,last_day_date,last_day_data, imputation_array = \
        readone('/media/demcare/1.4T_Linux/UKBiobank/sample.csv')
    #print first_day_date,first_day_data.shape
    #print date_list,data.shape
    #print last_day_date,last_day_data.shape
    data = joint_all_data(first_day_data, data, last_day_data)
    #print data
    #d= np.asarray([d],dtype='float64')
    fs = 1/5.0
    FFT.FFT('CPU',data,fs)
    '''x = T.matrix('x', dtype='float64')
    rfft = fft.rfft(x, norm='ortho')
    #rfft = fft.rfft(x)
    f_rfft = theano.function([x], rfft)

    import time
    start = time.time()
    out = f_rfft(d)
    print time.time() - start

    start = time.time()
    f, Pxx_den = signal.periodogram(d, fs)
    print time.time() - start

    start = time.time()
Esempio n. 11
0
    S0 = 282
    r = 0.015
    q = 0.0177
    T = 1
    Option_params = [S0, T, r, q]

    ### problem 2 ###
    steps = 250
    N = 100000

    ### problem 3 ###
    K = 285
    simu_S = Simu_Heston_Path(steps, N, Option_params, Heston_params)
    euro_simu = cal_Euro(simu_S, r, T, K, opt_type='c')
    euro_FFT = FFT(Heston_params, T, S0, r, q).Heston_fft(alpha=1.5,
                                                          K=K,
                                                          B=K * 2.5)
    print('European Call price through Simulation is:', euro_simu)
    print('European Call price through FFT is:', euro_FFT)

    ### problem 4 ###
    K1 = 285
    K2 = 315
    simu_S = Simu_Heston_Path(steps, N, Option_params, Heston_params)
    UAO_price = cal_UpAndOut(simu_S, r, T, K1, K2)
    print('Up-And-Out Call price through simulation is:', UAO_price)

    Ns = np.logspace(1, 4.9, 400)
    UpAndOut = []
    for sample_N in Ns:
        sample_index = np.random.choice(N, int(sample_N), replace=False)
Esempio n. 12
0
            ionames += [
                'io_in_bits_%s_real' % (count),
                'io_in_bits_%s_imag' % (count)
            ]
        self.iofile_bundle.Members[name].verilog_connectors=\
                self.tb.connectors.list(names=ionames)
        self.iofile_bundle.Members[name].verilog_io_condition = 'initdone'

        self.tb.generate_contents()


if __name__ == "__main__":
    import matplotlib.pyplot as plt
    from FFT import *
    from FFT.controller import controller as FFT_controller
    dut = FFT()
    dut2 = FFT()
    dut.model = 'py'
    dut2.model = 'sv'
    #dut2.interactive_verilog=True
    len = 16 * 64
    phres = 64
    fsig = 25e6
    indata=2**10*np.exp(1j*2*np.pi/phres*(np.arange(len)*np.round(fsig/dut.Rs*phres)))\
            .reshape(-1,64)
    controller = FFT_controller()
    controller.reset()
    dut.io_in.Data = indata
    dut2.io_in.Data = indata
    dut.control_write = controller.control_write
    dut2.control_write = controller.control_write
Esempio n. 13
0
def cal_Heston_price(K, Ks, T, alpha, params):
    prices = FFT(params, T).Heston_fft(alpha, K, B=K * 2.5, Ks=Ks)
    return prices
Esempio n. 14
0
def PImageFFT(inImage, outAImage, outPImage, err):
    """
    FFTs an Image
    
    FFT inImage and write as real and imaginary as full plane (hermetian) 

    * inImage   = input Obit Python Image 1
      Any BLC and/or TRC set will be honored
    * outAImage = output Obit Python Amplitude image of FFT
      must be defined but not instantiated
    * outPImage = output Obit Python Phase (deg) image of FFT
      must be defined but not instantiated
    * err       = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not Image.PIsA(inImage):
        raise TypeError("inImage MUST be a Python Obit Image")
    if not Image.PIsA(outAImage):
        raise TypeError("outAImage MUST be a Python Obit Image")
    if not Image.PIsA(outPImage):
        raise TypeError("outPImage MUST be a Python Obit Image")
    if not err.IsA():
        raise TypeError("err MUST be an OErr")
    #
    # Clone output images
    inImage.Clone(outAImage, err)
    inImage.Clone(outPImage, err)
    OErr.printErrMsg(err, "Error initializing images")

    # Size of FFT
    inImage.Open(Image.READONLY, err)
    inImage.Read(err)
    OErr.printErrMsg(err, "Error reading input")
    inHead = inImage.Desc.Dict
    FFTdim = [
        FFT.PSuggestSize(inHead["inaxes"][0]),
        FFT.PSuggestSize(inHead["inaxes"][1])
    ]

    # Create float arrays for FFT size
    inFArray = FArray.FArray("inF", naxis=FFTdim)
    outFArray = FArray.FArray("outF", naxis=FFTdim)

    # Create FFT for full complex FFT
    FFTfor = FFT.FFT("FFT", 1, 1, 2, FFTdim)

    # Create complex arrays for FFT size
    inCArray = CArray.CArray("inC", naxis=FFTdim)
    outCArray = CArray.CArray("outC", naxis=FFTdim)

    #Loop over planes
    nplane = inImage.Desc.Dict['inaxes'][2]
    for iax in range(1, nplane + 1):
        inImage.GetPlane(None, [iax, 1, 1, 1, 1], err)
        OErr.printErrMsg(err, "Error reading input")
        # Pad input into work FArray
        FArray.PPad(inImage.FArray, inFArray, 1.0)
        # and God said "The center of an FFT will be at the corners"
        FArray.PCenter2D(inFArray)
        # Zero output FArray and use as imaginary part
        FArray.PFill(outFArray, 0.0)
        # Copy input to scratch CArray
        CArray.PComplex(inFArray, outFArray, inCArray)

        # FFT
        FFT.PC2C(FFTfor, inCArray, outCArray)

        # Extract amplitude, write
        CArray.PAmp(outCArray, outFArray)
        # and God said "The center of an FFT will be at the corners"
        FArray.PCenter2D(outFArray)
        outAImage.FArray = FeatherUtil.PExtract(FFTfor, outFArray,
                                                outAImage.FArray, err)
        OErr.printErrMsg(err, "Error extracting output amplitude plane")
        outAImage.PutPlane(outAImage.FArray, [iax, 1, 1, 1, 1], err)

        # Extract phase, write
        CArray.PPhase(outCArray, outFArray)
        # To degrees
        FArray.PSMul(outFArray, 57.2956)
        # and God said "The center of an FFT will be at the corners"
        FArray.PCenter2D(outFArray)
        outPImage.FArray = FeatherUtil.PExtract(FFTfor, outFArray,
                                                outPImage.FArray, err)
        OErr.printErrMsg(err, "Error extracting output phase plane")
        outPImage.PutPlane(outPImage.FArray, [iax, 1, 1, 1, 1], err)
        # Error?
        OErr.printErrMsg(err, "Error writing output phase image")
        # end loop over planes

    # Fix headers
    outAImage.Open(Image.READWRITE, err)
    FFTHeaderUpdate(outAImage, FFTdim, err)
    outAImage.Close(err)
    OErr.printErrMsg(err, "Error writing output amplitude image")

    outPImage.Open(Image.READWRITE, err)
    FFTHeaderUpdate(outPImage, FFTdim, err)
    outPImage.Close(err)
    OErr.printErrMsg(err, "Error writing output phase image")

    # get any BLC, TRC for history
    info = inImage.List.Dict
    blc = [1, 1, 1, 1, 1, 1, 1]
    if 'BLC' in info:
        blc = info["BLC"][2]
    trc = [0, 0, 0, 0, 0, 0, 0]
    if 'TRC' in info:
        trc = info["TRC"][2]

    # Write history
    i = 0
    imtype = ("Amplitude", "Phase")
    for outImage in (outAImage, outPImage):
        inHistory = History.History("history", inImage.List, err)
        outHistory = History.History("history", outImage.List, err)
        # Copy History
        # FITS? - copy header
        if ("FileType" in info) and (info["FileType"][2][0] == 0):
            History.PCopyHeader(inHistory, outHistory, err)
        #Not needed History.PCopy(inHistory, outHistory, err)
        # Add this programs history
        outHistory.Open(History.READWRITE, err)
        outHistory.TimeStamp(" Start Obit PImageFFT", err)
        outHistory.TimeStamp(OSystem.PGetPgmName() + " BLC = " + str(blc), err)
        outHistory.TimeStamp(OSystem.PGetPgmName() + " TRC = " + str(trc), err)
        outHistory.TimeStamp(OSystem.PGetPgmName() + " type = " + imtype[i],
                             err)
        i += 1
        outHistory.Close(err)
Esempio n. 15
0
import LEDWall
import FFT
import SharedVariables
import pong
from pong_flask_resource import PongControl
import threading
import sys
import time
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
import numpy as np

shared_vars = SharedVariables.SharedVariables()

ledwall = LEDWall.LEDWall()
fft = FFT.FFT()
pong_game = pong.Pong()

flaskApp = Flask(__name__)
flaskApi = Api(flaskApp)

threads = []


def kill_threads():
    shared_vars.kill_threads = True
    for t in threads:
        t.join()
    threads.clear()
    shared_vars.kill_threads = False
    ledwall.show_color((0, 0, 0))
Esempio n. 16
0
inHead = inImage.Desc.Dict
FFTdim = [FFT.PSuggestSize(inHead["inaxes"][0]), FFT.PSuggestSize(inHead["inaxes"][1])]

# Create float arrays for FFT size
inFArray  = FArray.FArray("inF", naxis=FFTdim)
outFArray = FArray.FArray("outF", naxis=FFTdim)

# Pad input into work FArray
FArray.PPad(inImage.FArray, inFArray, 1.0)
# and God said "The center of an FFT will be at the corners"
FArray.PCenter2D(inFArray)
# Zero output FArray and use as imaginary part
FArray.PFill(outFArray, 0.0)

# Create FFT for full complex FFT
FFTfor = FFT.FFT("FFT", 1, 1, 2, FFTdim)

# Create complex arrays for FFT size
inCArray  = CArray.CArray("inC", naxis=FFTdim)
outCArray = CArray.CArray("outC", naxis=FFTdim)

# Copy input to scratch CArray
CArray.PComplex(inFArray, outFArray, inCArray)

# FFT
FFT.PC2C(FFTfor, inCArray, outCArray)

# Extract amplitude
CArray.PAmp(outCArray, outFArray)
# and God said "The center of an FFT will be at the corners"
FArray.PCenter2D(outFArray)