def start(self): while True: choice = self._getChoice(self._getMenu()) (n, X, Y, z, m) = self._getDataByChoice(choice) s = Spline(X, Y) print '%.20f' % s.getY(z) s.savePlot('grafico', m)
def initializeWithCM(Para): ''' Initialize value function and policies with the complete markets solution ''' #Initializing using deterministic stationary equilibrium but using interest rates comming from FB S = Para.P.shape[0] beta = Para.beta P = Para.P c = np.zeros((Para.nx, S, S)) xprime = np.zeros((Para.nx, S, S)) V = np.zeros((Para.nx, S)) for s_ in range(0, S): for i in range(0, Para.nx): x = Para.xgrid[i] cLS, lLS = LS.solveLucasStockey(x, s_, Para) uLS = Para.U.u(cLS, lLS, Para) V[i, s_] = P[s_, :].dot( np.linalg.solve(np.eye(S) - (Para.beta * P.T).T, uLS)) xprime[i, s_, :] = x c[i, s_, :] = cLS #Fit functions using splines. Linear for policies as they can be wonky Vf = [] c_policy = {} xprime_policy = {} for s_ in range(0, S): beta = (Para.P[s_, :] * Para.beta).sum() Vf.append( ValueFunctionSpline(Para.xgrid, V[:, s_], [1], Para.sigma, beta)) for s in range(0, S): c_policy[(s_, s)] = Spline(Para.xgrid, c[:, s_, s], [1]) xprime_policy[(s_, s)] = Spline(Para.xgrid, xprime[:, s_, s], [1]) return Vf, c_policy, xprime_policy
class posterioDistriubtion(object): def __init__(self, p_d, pdf, d): self.mu = Spline(p_d, pdf, d) self.moments = {} def fit(self, p_d, pdf, d): self.mu.fit(p_d, pdf, d) def __call__(self, p_d): if isinstance(p_d, float) or len(p_d) == 1: return self.mu.feval1d(float(p_d)) else: return self.mu(p_d) def getMoment(self, m): if not self.moments.has_key(m): if m == 1: self.moments[1] = quad(lambda p_d: p_d * self(p_d), 0.0, 1.0, full_output=1)[0] else: Ep_d = self.getMoment(1) mom = quad(lambda p_d: (p_d - Ep_d)**m * self(p_d), 0.0, 1.0, full_output=1)[0] if mom < 0: self.moments[m] = -(-mom)**(1.0 / m) else: self.moments[m] = mom**(1.0 / m) return self.moments[m] def getMoments(self, m=[1, 2, 3]): return np.array(map(self.getMoment, m))
class posterioDistriubtion(object): def __init__(self,p_d,pdf,d): self.mu = Spline(p_d,pdf,d) self.moments = {} def fit(self,p_d,pdf,d): self.mu.fit(p_d,pdf,d) def __call__(self,p_d): if isinstance(p_d,float) or len(p_d) ==1: return self.mu.feval1d(float(p_d)) else: return self.mu(p_d) def getMoment(self,m): if not self.moments.has_key(m): if m == 1: self.moments[1] = quad(lambda p_d: p_d*self(p_d),0.0,1.0,full_output=1)[0] else: Ep_d = self.getMoment(1) mom = quad(lambda p_d: (p_d-Ep_d)**m*self(p_d),0.0,1.0,full_output=1)[0] if mom < 0: self.moments[m] = -(-mom)**(1.0/m) else: self.moments[m] = mom**(1.0/m) return self.moments[m] def getMoments(self,m = [1,2,3]): return np.array(map(self.getMoment,m))
class ValueFunctionSpline: def __init__(self, X, y, k, sigma, beta): self.sigma = sigma self.beta = beta if sigma == 1.0: y = np.exp((1 - beta) * y) else: y = ((1 - beta) * (1.0 - sigma) * y)**(1.0 / (1.0 - sigma)) self.f = Spline(X, y, k) def fit(self, X, y, k): if self.sigma == 1.0: y = np.exp((1 - self.beta) * y) else: y = ((1 - self.beta) * (1.0 - self.sigma) * y)**(1.0 / (1.0 - self.sigma)) self.f.fit(X, y, k) def getCoeffs(self): return self.f.getCoeffs() def __call__(self, X, d=None): if d == None: if self.sigma == 1.0: return np.log(self.f(X, d)) / (1 - self.beta) else: return (self.f(X, d)**(1.0 - self.sigma)) / ( (1.0 - self.sigma) * (1 - self.beta)) if d == 1: return self.f(X)**(-self.sigma) * self.f(X, 1) / (1 - self.beta) raise Exception('Error: d must equal None or 1')
class ValueFunctionSpline: def __init__(self,X,y,k,sigma,beta): self.sigma = sigma self.beta = beta if sigma == 1.0: y = np.exp((1-beta)*y) else: y = ((1-beta)*(1.0-sigma)*y)**(1.0/(1.0-sigma)) self.f = Spline(X,y,k) def fit(self,X,y,k): if self.sigma == 1.0: y = np.exp((1-self.beta)*y) else: y = ((1-self.beta)*(1.0-self.sigma)*y)**(1.0/(1.0-self.sigma)) self.f.fit(X,y,k) def getCoeffs(self): return self.f.getCoeffs() def __call__(self,X,d = None): if d==None: if self.sigma == 1.0: return np.log(self.f(X,d))/(1-self.beta) else: return (self.f(X,d)**(1.0-self.sigma))/((1.0-self.sigma)*(1-self.beta)) if sum(d)==1: return self.f(X)**(-self.sigma) * self.f(X,d)/(1-self.beta) raise Exception('Error: d must equal None or 1')
def __init__(self, X, y, k, sigma, beta): self.sigma = sigma self.beta = beta if sigma == 1.0: y = np.exp((1 - beta) * y) else: y = ((1 - beta) * (1.0 - sigma) * y)**(1.0 / (1.0 - sigma)) self.f = Spline(X, y, k)
def __init__(self, lookahead_distance: float, path: Spline, resolution: int, track_width): # TODO: Support passing in a list of splines / maybe something that will append splines # into one big spline at the time of discretization? self.lookahead_distance = lookahead_distance self.path = path self.track_width = track_width for i in range(resolution): coord = path.get_xy(i / resolution) theta = path.angle_at(i / resolution) new_pose = Pose(coord[0], coord[1], theta) self.discrete_path.append(new_pose)
def main(): logger.info('Start') isShowMatrix = False isSaveMatrix = False dim = 1 if dim == 1: f = lambda x: x*x q = lambda x: (5-abs(x-5)*1)*2 domains = [[0,10,1]] elements = [2] elif dim == 2: f = lambda x,y: x*x q = lambda x,y: 0 domains = [[0,1,0.1],[0,1,0.1]] elements = [1,1] elif dim == 3: f = lambda x,y,z: (x*x+y*y)*z q = lambda x,y,z: ((x*x+y*y)*z)*np.random.rand(1)*0.01 + (100 if abs(x-2.5) < 1 and abs(y-2.5) < 1 else 0) domains = [[0,5,0.5],[0,5,0.5],[-1,1,0.2]] elements = [2,2,1] K = 10 f = PointsFabric(dim, f, q, domains) clear, noise = f.generate() s = Spline('input.txt', elements, K) s.MakeMatrix() if isSaveMatrix: np.savetxt('data/before_solveA.txt', s.A, fmt='%1.2e') np.savetxt('data/before_solveF.txt', s.F, fmt='%1.2f') if isShowMatrix: plt.matshow(s.A) ans = s.Solve() i = 0 for a in ans: try: if len(a) == s.nNodes * (2**dim): np.savetxt(f'data/answer_{i}.txt', a, fmt='%1.2f') i += 1 except Exception: pass p = Painter('data/answer_0.txt', dim, True, s._Spline__psi, K, s.elements, s.mx, s.kElem, s.h, clearPoints=noise) testFunc = lambda x,y,z: x+z p.Paint(True)
def fitPolicyFunction(Para, PolicyF): ''' Fits the policy functions given function PolicyF ''' cf, lf, muprimef, xif = {}, {}, {}, {} xf = [] S = len(Para.P) for s_ in range(S): Policies = vstack(map(lambda mu: PolicyF((mu, s_)), Para.domain[s_])) mugrid = Para.domain[s_] for s in range(S): cf[s_, s] = Spline(mugrid, Policies[:, s], [2]) lf[s_, s] = Spline(mugrid, Policies[:, s + S], [2]) muprimef[s_, s] = Spline(mugrid, Policies[:, s + 2 * S], [2]) xif[s_, s] = Spline(mugrid, Policies[:, s + 3 * S], [2]) xf.append(Spline(mugrid, Policies[:, 4 * S], [1])) return cf, lf, muprimef, xif, xf
def __init__(self,X,y,k,sigma,beta): self.sigma = sigma self.beta = beta if sigma == 1.0: y = np.exp((1-beta)*y) else: y = ((1-beta)*(1.0-sigma)*y)**(1.0/(1.0-sigma)) self.f = Spline(X,y,k)
def fitFunction(F, Para): ''' Fits the policy functions given function PolicyF ''' Fhat = [] S = len(Para.P) for s_ in range(S): mugrid = Para.domain[s_] Fs = hstack(map(lambda mu: F(mu, s_), mugrid)) Fhat.append(Spline(mugrid, Fs, [1])) return Fhat
def relative_gamma(xvals, yvals, T): # better values in kcal/mol yvals = [yi * KCALMOL for yi in yvals] # find maximum spl = Spline(xvals, yvals, tan="findiff", tension=0.0) spl.find_xtr("max") CVT_s, CVT_gibbs = spl.get_max() # undo kcal/mol CVT_gibbs = CVT_gibbs / KCALMOL # CVT values CVT_s = float(CVT_s) CVT_gamma = np.exp(-(CVT_gibbs / KB / T)) # Correct value, just in case if CVT_gamma > 1.0: CVT_gamma = 1.0 # data with more points (for plotting) npts = 20 * len(xvals) dx = (xvals[-1] - xvals[0]) / (npts) new_xx = [xvals[0] + ii * dx for ii in range(npts + 1)] new_yy = [spl(x) / KCALMOL for x in new_xx] # return return float(CVT_s), float(CVT_gamma), (new_xx, new_yy)
def parseLandmarksAndSplines(self): print("parse landmarks from xml") doc = minidom.parse('C:/Development/morphometry/Landmarks.xml') name = doc.getElementsByTagName("name")[0] print(name.firstChild.data) points = doc.getElementsByTagName("point") for point in points: id = point.getAttribute("id") name = point.getAttribute("name") x = point.getElementsByTagName("x")[0].firstChild.data y = point.getElementsByTagName("y")[0].firstChild.data z = point.getElementsByTagName("z")[0].firstChild.data #print("name: %s, x: %s, y: %s, z: %s" % #(name, x, y, z)) self.landmarks.append(Landmark(id, name, x, y, z, False)) splines = doc.getElementsByTagName("spline") for spline in splines: id = spline.getAttribute("id") name = spline.getAttribute("name") resolution = spline.getElementsByTagName("resolution")[0].firstChild.data splinepoints = spline.getElementsByTagName("splinepoint") #print (name) #print (resolution) landmarks = [] for splinepoint in splinepoints: landmark = splinepoint.firstChild.data landmarks.append(landmark) #print (landmark) self.splines.append(Spline(id, name, resolution, landmarks, 0)) for spline in self.splines: id = spline.id name = spline.name resolution = spline.resolution print ("spline id: %s, name: %s, resolution: %s" % (id, name, resolution)) for landmark in spline.landmarks: id = landmark print(" landmarks id: %s" % (id))
def main(): spline = Spline('dots.txt') print(spline.dots, spline.dots_count) spline.get_polynomials() try: file = open('result.txt', 'w', encoding='utf-8') except FileNotFoundError: print('Result file is nor founded') exit(2) for i in range(len(spline.polynomials)): print('F' + str(i + 1) + '(x) = ' + str(spline.polynomials[i])) file.write('F' + str(i + 1) + '(x) = ' + str(spline.polynomials[i]) + '\n') file.close() spline.get_plot()
def initializeFunctions(Para): #Initializing using deterministic stationary equilibrium but using interest rates comming from FB S = Para.P.shape[0] cFB, _ = computeFB(Para) lFB = (cFB + Para.g) / Para.theta ucFB = Para.U.uc(cFB, lFB, Para) EucFB = Para.P.dot(ucFB) Q = np.zeros((S * S, S * S)) #full (s_,s) transition matrix for s_ in range(0, S): for s in range(0, S): Q[s_:S * S:S, s_ * S + s] = Para.P[s_, s] c = np.zeros((Para.nx, S, S)) xprime = np.zeros((Para.nx, S, S)) V = np.zeros((Para.nx, S)) for i in range(0, Para.nx): u = np.zeros((S, S)) for s_ in range(0, S): x = Para.xgrid[i] def stationaryRoot(c): l = (c + Para.g) / Para.theta return c * Para.U.uc(c, l, Para) + l * Para.U.ul( c, l, Para) + (Para.beta - ucFB / (EucFB[s_])) * x res = root(stationaryRoot, cFB) #find root that holds x constant if not res.success: raise Exception(res.message) #find root that holds x constant c[i, s_, :] = res.x xprime[i, :] = x * np.ones(S) if Para.transfers: for s in range(0, S): c[i, s_, s] = min(c[i, s_, s], cFB[s]) #if you can achieve FB do it #Compute xprime from implementability constraint l = (c[i, s_, s] + Para.g[s]) / Para.theta xprime[i, s_, s] = (c[i, s_, s] * Para.U.uc(c[i, s_, s], l, Para) + l * Para.U.ul(c[i, s_, s], l, Para) - x * ucFB[s] / EucFB[s_]) / Para.beta l = (c[i, s_, :] + Para.g) / Para.theta u[s_, :] = Para.U.u(c[i, s_, :], l, Para) for s_ in range(0, S): beta = (Para.P[s_, :] * Para.beta).sum() #compute Value using transition matricies. Gives rough guess on value function v = np.linalg.solve(np.eye(S * S) - beta * Q, u.reshape(S * S)) V[i, s_] = Para.P[s_, :].dot(v[s_ * S:(s_ + 1) * S]) #Fit functions using splines. Linear for policies as they can be wonky Vf = [] c_policy = {} xprime_policy = {} for s_ in range(0, S): beta = (Para.P[s_, :] * Para.beta).sum() Vf.append( ValueFunctionSpline(Para.xgrid, V[:, s_], [1], Para.sigma, beta)) for s in range(0, S): c_policy[(s_, s)] = Spline(Para.xgrid, c[:, s_, s], [1]) xprime_policy[(s_, s)] = Spline(Para.xgrid, xprime[:, s_, s], [1]) return Vf, c_policy, xprime_policy
# -*- coding: utf-8 -*- """ Created on Tue Aug 13 11:34:48 2013 @author: dgevans """ from numpy import * from cpp_interpolator import interpolate from cpp_interpolator import interpolate_INFO from Spline import Spline INFO = interpolate_INFO(['spline','spline'],[10,5],[3,3]) x1 = linspace(0.,1.,10) x2 = linspace(0,1.,10) X = Spline.makeGrid([x1,x2]) def f(x): return log(1+x[1]) * exp(x[0]) Y = vstack(map(f,X)) fhat = interpolate(X,Y,INFO) x = linspace(0,1,20).reshape(-1,1) y = exp(x) INFO = interpolate_INFO(['hermite'],[19],[3]) ghat = interpolate(x,y,INFO)
from methods import * import os import csv import matplotlib.pyplot as plt from Spline import Spline from Lagrange import Lagrange if __name__ == "__main__": Lagrange() Spline()
import numpy as np from Spline import Spline import matplotlib.pyplot as plt x = np.linspace(0,1,10) y = np.exp(x) f = Spline(x,y) g = Spline(x,x) X = Spline.makeGrid([x,x]) def g(x,y): return 1/(0.5 +(x+y)**2) y = 1/(0.5 +(X[:,0]+X[:,1])**2) fV = Spline(X,y) xhat = 0.5*np.ones((1000,2)) xhat[:,0] = np.linspace(0,1,1000) plt.plot(xhat[:,0],map(g,xhat[:,0],xhat[:,1]),'b') plt.plot(xhat[:,0],fV(xhat),'g') plt.show() #print fV(xhat) #print fV(xhat,[1,0]) #print fV(xhat,[0,1])
def ispe(tcommon, drst, ispe_xy, tension): ''' V^LL --> V^HL ''' # points in rst points = sd.sorted_points(drst, hess=False) # Get imaginary frequency for TS (low-level) sTS, ETS_ll, xcc, gcc, Fcc = drst[sd.TSLABEL][0:5] ifreq, mu = get_ts_ifreq(xcc, gcc, Fcc, ETS_ll, tcommon) # convert x in ispe_xy to labels for idx, (l_i, V_i) in enumerate(ispe_xy): if l_i in points: s_i = drst[l_i][0] label_i = l_i else: s_i = float(l_i) label_i = None for point in points: if abs(drst[point][0] - s_i) < EPS_DLEVELS: label_i = point if label_i is None: raise Exc.DLEVELsthWrong(Exception) ispe_xy[idx] = (s_i, label_i, V_i) # sort points ispe_xy.sort() # only one point if len(ispe_xy) == 1: sx, lx, Ex_hl = ispe_xy[0] Ex_ll = drst[lx][1] # calculate energy difference diffE = Ex_ll - Ex_hl # points points = sd.sorted_points(drst, hess=False) # save old energies xx = [drst[point][0] for point in points] yyll = [drst[point][1] for point in points] # apply difference to all points for point in points: drst[point] = list(drst[point]) drst[point][1] = drst[point][1] - diffE drst[point] = tuple(drst[point]) # more than one point else: # reduce points of drst to those for DLEVEL s1, l1, E1_hl = ispe_xy[0] sn, ln, En_hl = ispe_xy[-1] drst = { point: drst[point] for point in points if in_interval(drst[point][0], s1, sn) } points = sd.sorted_points(drst, hess=False) # get s0 and L from lower level E1_ll, En_ll = drst[l1][1], drst[ln][1] s0, L = get_s0_L(E1_ll, ETS_ll, En_ll, mu, ifreq) # generate data for spline lxx, lyy = gen_data_for_spline(ispe_xy, drst, s0, L) # create spline spl = Spline(lxx, lyy, tension=tension) # save old energies xx = [drst[point][0] for point in points] yyll = [drst[point][1] for point in points] # modify drst for point in points: s, Vll = drst[point][0:2] z = s2z(s, s0, L) drst[point] = list(drst[point]) drst[point][1] = Vll - spl(z) drst[point] = tuple(drst[point]) # save new energies yyhl = [drst[point][1] for point in points] # return data return drst, points, xx, yyll, yyhl
from Spline import Spline import bellman from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() print rank Para = primitives_CRRA() agrid = hstack((linspace(Para.a_min,Para.a_min+1,10),linspace(Para.a_min+2,Para.a_max,5))) zgrid = linspace(Para.z_min,Para.z_max,10) Para.domain = Spline.makeGrid((agrid,zgrid)) r = 0.95*(1/Para.beta-1) Para.deg = [2,2] def V0(state,d=[0,0]): return 0. T = bellman.BellmanMap(Para,r) Vf = bellman.approximateValueFunction(T(V0),Para) for t in range(0,100): Vfnew = bellman.approximateValueFunction(T(Vf),Para) if rank == 0:
def __init__(self,p_d,pdf,d): self.mu = Spline(p_d,pdf,d) self.moments = {}
def __init__(self, p_d, pdf, d): self.mu = Spline(p_d, pdf, d) self.moments = {}
def test2(): ion() tv_nm = noise_model2D(1.0, 0, 0.1, 0.0) rv_nm = noise_model2D(0, 1.0, 0.0, 0.1) slip_nm = noise_model2D(0, 0, 0.01, 0.0) #make the papa of noise models here nm = motion_noise_model_slip(tv_nm, rv_nm, slip_nm) onm = observation_noise_model(0.1, 0.01, 0.0001) x, y, theta = [10, 20, 0] ax = gca() #make a simulator, load and plot the map print "simulator" mysim = simulator2D([x,y,theta], nm, onm, "../../data/maps/thickwean.map"); print "ogm" mymap = occupancy_grid_mapper(0.8,0.8, 0.5, 100, 100, 0.1, mysim.get_pose(), 0.2) myid = carmen_maptools.plot_map(mymap.map.get_map(), mymap.map.x_size, mymap.map.y_size); nn_plt, = plot([], [], 'ro'); orig_plt, = plot([], [], 'bx'); icp_plt, = plot([], [], 'gx'); robot_pose_plt, = plot([], [], 'ko'); robot_orient_plt, = plot([], [], 'k'); spline_plt, = plot([], [], 'b'); spline_pltc, = plot([], [], 'g'); #do some simulation for i in range(1000): mysim.simulate_motion(1.0, 0.6, 0.1); sim_meas = mysim.simulate_measurements(); mymap.update(mysim.get_pose(), sim_meas); x, y, theta = mymap.get_pose() if(mod(i, 5) == 0): carmen_maptools.plot_map(mymap.map.get_map(), mymap.map.x_size, mymap.map.y_size, cmap="binary"); ax.images = [ax.images[len(ax.images)-1]] #do some spline processing x, y, theta = mysim.get_pose() #spline = Spline(point(x, y, theta), point(22.0, 27.1, 0), 20.0, 20.0) spline = Spline(point(x, y, theta), point(19.0, 20.6, pi/8.0), 30.0, 40.0) X, Y = spline.getVals(arange(0, 1, 0.01)) spline_plt.set_data(X, Y); #to C type cspline = spline.toCtype() X, Y = cspline.value(arange(0, 1, 0.01)) spline_pltc.set_data(X, Y) isfree = mymap.map.path_free(cspline) if(isfree == 1): print "its free" elif(isfree == 0): print "hit obstacle" elif(isfree == -1): print "outside map" elif(isfree == -2): print "hit unknown" robot_pose_plt.set_data([x], [y]); robot_orient_plt.set_data([x, x+0.3*cos(theta)], [y, y+0.3*sin(theta)]); draw() show()
print rank Para = BGP_parameters() Para.P = np.array([[7.0/11.0, 4.0/11.0],[3.0/19.0,16.0/19.0]]) Para.psi = 0.6994 Para.theta_1 = np.array([3.9725,4.1379]) Para.theta_2 = np.array([0.9642,1.0358]) Para.g = .4199 Para.beta = np.array([0.98,.92]) Para.xmin = -3.0 Para.xmax = 3.0 Para.Rmin = 2.7 Para.Rmax = 3.7 Para.approxOrder = [2,2] xgrid =np.linspace(Para.xmin,Para.xmax,50) Rgrid = np.linspace(Para.Rmin,Para.Rmax,50) X = Spline.makeGrid([xgrid,Rgrid]) domain = np.vstack((X,X)) domain = zip(domain[:,0],domain[:,1],[0]*len(X)+[1]*len(X)) V0 = lambda state: initialize.completeMarketsSolution(state,Para) Para.domain = domain (Vf,c1_policy,c2_policy,Rprime_policy,xprime_policy),_ = Bellman.approximateValueFunctionAndPoliciesMPI(V0,Para) Vf,c1_policy,c2_policy,Rprime_policy,xprime_policy = Bellman.solveBellmanMPI(Vf,c1_policy,c2_policy,Rprime_policy,xprime_policy,Para) if rank == 0: policyFile = open('SolvedPolicyRules.data','w') cPickle.dump((Vf,c1_policy,c2_policy,Rprime_policy,xprime_policy,Para),policyFile) policyFile.close()
import primitives import numpy as np from Spline import Spline Para = primitives.BGP_parameters() Para.theta = np.array([3.3]) Para.g = np.array([.35,.37]) Para.xprime_bounds = np.array([-1.,1.]) Para.q_bounds = np.array([Para.Uc(2.1),Para.Uc(1.9)])*Para.beta/(1-Para.beta) Para.b_bounds = Para.xprime_bounds/(Para.q_bounds[1]) xGrid = np.linspace(Para.xprime_bounds[0],Para.xprime_bounds[1],10) bGrid = np.linspace(Para.b_bounds[0],Para.b_bounds[1],10) qGrid = np.linspace(Para.q_bounds[0],Para.q_bounds[1],10) X = Spline.makeGrid((xGrid,bGrid,qGrid)) S = len(Para.P) slist = [] for s in range(0,S): slist += [s]*len(X) Para.domain = zip(np.vstack([X]*S),slist) Para.deg = [2,2,2]