Ejemplo n.º 1
0
def run_models():

    while True:
        print("* Updating GP model *")
        predmeans, predvars, Xtest = gpmodel()
        temp_interp = interp(predmeans, predvars, Xtest)
        print("* Updating interpolator *")
        mean_interp, var_interp = temp_interp
        print("* Sleeping for 1 hour *")
        time.sleep(3600)
Ejemplo n.º 2
0
    def __init__(self, port):
        self.port = port
        self.address = 1
        self.method = 'rtu'
        self.baudrate = 115200
        self.bytesize = 8
        self.stopbits = 1
        self.timeout = 1
        self.parity = 'N'

        self.ObdicAddress = {}
        self.ObdicScale = {}
        self.ObdicUnit = {}
        self.ObdicEnum = {}  # "enumerated" bitwise parameters, returns bit key/name as string
        self.ObdicBit = {}  # "bit vector" bitwise parameters, returns bit key/name
        self.ObdicBits = {}
        self.RegsDic = {}

        self.socmap_volts, self.socmap_soc, self.socmap_ah, self.socmap_wh_volts, self.socmap_wh_wh = \
            [],[],[],[],[]

        with open(filepath + 'socmap_ahv.csv', mode='r') as file:
            reader = csv.reader(file, delimiter=',')
            for row in reader:  # If using own socmap, identify columns appropriately.
                self.socmap_ah.append(float(row[0]))
                self.socmap_volts.append(float(row[1]))
                self.socmap_soc.append(float(row[2]))
        self.socmap_volts = array(self.socmap_volts)
        self.socmap_soc = array(self.socmap_soc)
        self.socmap_ah = array(self.socmap_ah)
        file.close()

        with open(filepath + 'WhVmap.csv', mode='r') as file:
            reader = csv.reader(file, delimiter=',')
            for row in reader:  # If using own socmap, identify columns appropriately.
                self.socmap_wh_wh.append(float(row[0]))
                self.socmap_wh_volts.append(float(row[1]))
        self.socmap_wh_wh = array(self.socmap_wh_wh)
        self.socmap_wh_volts = array(self.socmap_wh_volts)
        file.close()

        #self.socmap_wh = []
        #for n, val in enumerate(self.socmap_volts):
        #    pass
            #self.socmap_wh.append(self.socmap_volts[])
        self.socmap = interp(self.socmap_volts, self.socmap_soc)
        self.ahmap = interp(self.socmap_volts, self.socmap_ah)
        self.wh_a2v_map = interp(self.socmap_ah, self.socmap_volts)
        self.whmap = interp(self.socmap_wh_volts, self.socmap_wh_wh)

        for parent in Obdic:  # InternalAppEntity/Parameters/ParameterDescription children
            scale = parent.find('Scale').text
            if scale == ('enum'):
                key = parent.find('Key').text
                address = int(parent.find('Address').text)
                self.ObdicAddress.update({key: address})
                Enumerations = parent.findall('Enumerations/string')  # Text string
                # print('Parent: ', key)
                for EnumBit, EnumKey in enumerate(
                        Enumerations):  # returns loop number from 0 for first term EnumBit, while EnumKey = iteration of each Enumerations element
                    self.ObdicEnum.update(
                        {key: {EnumKey.text: EnumBit}})  # Ordered to return bit controlling key:string e.g.
                    # 'Speed_Regulator_Mode: Torque Mode with Speed Limiting'
                    # print('Parent: ', key, 'Enumbit: ', EnumBit, 'Enumstring: ', EnumKey.text) #et.tostring(EnumKey, encoding='unicode'))
                    # ***print('Address: ', address, 'EnumParent: ', key, 'bit: ', EnumBit, 'key: ',
                    # EnumKey.text)  # ObdicEnum[key][EnumKey.text] to return positional bit
            else:
                if scale == ('bit vector'):
                    key = parent.find('Key').text
                    address = int(parent.find('Address').text)
                    self.ObdicAddress.update({key: address})
                    Bits = parent.findall('BitArray/Bit/Key')  # Overwrites previous instances in loop
                    for Bit, BitKey in enumerate(Bits):
                        self.ObdicBits[Bit] = BitKey.text
                        # print('Key: ', key, 'Bit: ', Bit, 'String: ', BitKey.text) ### !DESIRED OUTPUT!
                    if key not in self.ObdicBit:
                        self.ObdicBit[key] = self.ObdicBits.copy()  # MUST COPY otherwise simply points to overwritten dict!


                else:
                    try:  # Convert scale strings to integers where possible, floats where not
                        scale = int(scale)
                    except ValueError:
                        try:
                            scale = float(scale)
                        except ValueError:
                            pass
                            # print('Float scale error: ', scale, 'Scale type: ', type(scale))
                    key = parent.find('Key').text
                    address = int(parent.find('Address').text)
                    try:
                        unit = parent.find('Units').text
                    except AttributeError:
                        unit = 'None'
                    self.ObdicAddress.update({key: address})
                    self.ObdicUnit.update({key: unit})
                    self.ObdicScale.update({address: scale})
Ejemplo n.º 3
0
if do_Corrections:
    for i in range(numPoints):
        thisPoint = points[i]
        thisPoint.calcCorrection(points)

if do_Map:
    sSize = 50
    iMap = np.zeros([sSize, sSize])
    xx = np.linspace(xmin, xmax, sSize)
    yy = np.linspace(ymin, ymax, sSize)

    for i in range(sSize):
        for j in range(sSize):
            x = (xmax - xmin) * j / sSize + xmin
            y = (ymax - ymin) * i / sSize + ymin
            val = interpolate.interp(x, y, points)
            iMap[i][j] = val[1]
            #print(x,y,val)
    plt.pcolor(xx, yy, iMap)
    plt.colorbar()

if do_NewSample:
    numNewSamples = 10
    numPoints = len(points)
    newPoints = []
    xs = np.zeros(numNewSamples)
    ys = np.zeros(numNewSamples)
    for i in range(numNewSamples):
        xn = random.random() * 2 + 6.0
        yn = random.random() * 2 + 6.0
        sn = interpolate.interp(x, y, points)
Ejemplo n.º 4
0
def splineEMD(x,resolution,inputResidual,step):
    """ produces a spline interpolated minimum and maximum envelope, and does the 
    EMD decomposition until the resolution requirement is met and then until the residual 
    is close enough to the original signal energy
    """
    
    signal = x                                                       #get copy of original signal
    t = np.linspace(0,len(signal)-1,len(signal))                    
    pX = np.linalg.norm(x)**2                                        #Original signal energy
    siglen = len(signal)                                             #Signal length
    #now we are ready to decompose the signal into IMFs

    imfs = []                                                        #empty matrix of IMFs and residue
    iniResidual = 0                                                #signal has not been sifted and so energies are equal
    count = 1
    osc = math.inf
    textrema = []
    yextrema = []
    while iniResidual < inputResidual and osc > 4: # monotone(signal) == False:
        #while the signal has some energy
        iImf = signal
        pSig = np.linalg.norm(signal)**2
        (discreteMin,discreteMax) = discreteMinMax(iImf)
        if len(discreteMin) < 1 and len(discreteMax) < 1:           #if signal has no extrema, you are done
            print('ending...')
            break
        (parabolicMin,parabolicMax) = interpolate.interp(iImf,discreteMin,discreteMax)
        (parabolicMin,parabolicMax) = extrap(iImf,parabolicMin,parabolicMax)
        topenv = CubicSpline(parabolicMax[:,0],parabolicMax[:,1])
        botenv = CubicSpline(parabolicMin[:,0],parabolicMin[:,1])
        mean = (botenv(t) + topenv(t))/2                             #take average of top and bottom of signals
        
        while True:          
            pImf = np.linalg.norm(iImf)**2                           # IMF energy
            pMean = np.linalg.norm(mean)**2                          # Mean energy
            if pMean == 0:
                break
            i  pMean > 0:
                res = 10*np.log10(pImf/pMean)                                   
            if res>resolution:
                break                                                #Resolution reached
            #Resolution not reached, so repeat process
            iImf = iImf - step*mean
            #print(mean)
            (discreteMin,discreteMax) = discreteMinMax(iImf)   
            (parabolicMin,parabolicMin) = interp(iImf, discreteMin, discreteMax) 
            (parabolicMin,parabolicMax) = extrap(iImf,discreteMin,discreteMax)
            #print(parabolicMin)
            #print(parabolicMax)
            topenv = CubicSpline(parabolicMax[:,0],parabolicMax[:,1])
            botenv = CubicSpline(parabolicMin[:,0],parabolicMin[:,1])
            mean = (topenv(t) + botenv(t))/2    
        
            
        textrema.append(parabolicMax[:,0])
        yextrema.append(parabolicMax[:,1])        
        fig = plt.figure()
        plt.plot(t,botenv(t),t,topenv(t),t,iImf,t,mean)
        plt.scatter(parabolicMin[:,0],parabolicMin[:,1])
        plt.scatter(parabolicMax[:,0],parabolicMax[:,1])
        plt.xlabel('time')
        plt.ylabel('Amplitude')
        plt.title('IMF %s' %count)
        plt.savefig('IMF %s' %count, dpi = fig.dpi)
        #iImf = [math.floor(x) for x in iImf]
        iImf = np.array(iImf)
        imfs = np.append(imfs,iImf,axis=0)                           #store IMF in list
        count = count + 1
        signal = signal - iImf                                       #subtract IMF from signal
        pSig = np.linalg.norm(signal)**2
        osc = len(discreteMax) + len(discreteMin)
        if pSig > 0:
            #print(10*np.log10(pX/pSig))                         #if the signal isn't a residual, calculate the power of the residual
            iniResidual = 10*np.log10(pX/pSig)
        else:
            iniResidual = math.inf
Ejemplo n.º 5
0
ys2 = np.asarray(ys2)

#for i in range(numSamples):
#    print(xs[i],ys1[i],ys2[i],rs[i])

sSize = 50

iMap = np.zeros([sSize, sSize])
xx = np.linspace(y1min, y1max, sSize)
yy = np.linspace(y2min, y2max, sSize)

for i in range(sSize):
    for j in range(sSize):
        x = (y1max - y1min) * j / sSize + y1min
        y = (y2max - y2min) * i / sSize + y2min
        val = interpolate.interp(x, y, xs, ys1, ys2, rs, weights)
        iMap[i][j] = val[0]
        print(x, y, val)
plt.pcolor(xx, yy, iMap)
plt.colorbar()

plt.scatter(ys1, ys2, s=rs * (y1max - y1min))
'''
numNewSamples = 10
ynew1 = np.zeros(numNewSamples)
ynew2 = np.zeros(numNewSamples)
xnews = np.zeros([numNewSamples,numInputs])
for i in range(numNewSamples):
    yn1 = random.random()*2+6.0
    yn2 = random.random()*2+6.0
    xn  = interpolate.interp(yn1,yn2,xs,ys1,ys2,rs,weights)
Ejemplo n.º 6
0
from netCDF4 import Dataset
import numpy as np
import seawater as sw 
import datetime as td
import tricubic
from interpolate import interp

dataset = Dataset(r'/Users/brownscholar/Desktop/Internships/dataset-armor-3d-rep-weekly_1574699840388.nc')

pressure = dataset['depth']
temperture = dataset['to']
salinity = dataset['so']

pressure_interp = interp(temperture[0,:,:,:])
print("interpolated!!!")

# print(pressure.shape)
# print(temperture.shape)
# print(salinity.shape)

pressure_3d = np.zeros((31,80,27))

# for depth_level in pressure:
# 	print(np.repeat(depth_level,80*27).reshape((80,27)))


for i in range(0,31):
	#print(np.repeat(pressure[i],80*27).reshape((80,27)))
	pressure_3d[:] = np.repeat(pressure[i],80*27).reshape((80,27))
	#print(pressure_3d[i,:,:])
Ejemplo n.º 7
0
from interpolate import interpolate as interp
import numpy as np

N = 500
n = 20

x = np.linspace(0, 15, n)
y = np.cos(x)
z = np.linspace(0, 15, N)  # points for interpolation

interpcos = interp(x, y)  # initialze class interp

S_quad, S_quad_int, S_quad_der = interpcos.quad(z)  # quadratic interpolation

for i in range(0, N):
    if i < n:
        print(
            str(z[i]) + ' ' + str(S_quad[i]) + ' ' + str(S_quad_int[i]) + ' ' +
            str(S_quad_der[i]) + ' ' + str(x[i]) + ' ' + str(y[i]))
    else:
        print(
            str(z[i]) + ' ' + str(S_quad[i]) + ' ' + str(S_quad_int[i]) + ' ' +
            str(S_quad_der[i]))