def testobjecterror(value): try: pytave.feval(1, "test_return", value) print "FAIL:", (value, ) except pytave.ObjectConvertError: pass except Exception, e: print "FAIL", (value, ), e
def testvalueerror(*value): try: pytave.feval(1, *value) fail(value) except pytave.ValueConvertError: pass except Exception, e: fail(value, e)
def example(name,N,rel_err,eta=1): # select the problem if name in [ 'phillips','shaw' ]: (A,b,x) = pytave.feval(3,name,N) elif name=='ilaplace': (A,b,x,tLAP) = pytave.feval(4,'i_laplace',N,1) else: raise Exception("I don't know problem "+name) # 1 dimension arrays are 2dim in octave. Let's flat them! b = b.flatten() x = x.flatten() # colors for the plot colors = { 'real' : 'blue', 'tsvd' : 'red', 'tik' : 'green', 'newtik' : 'black' } # calculate the error and disturb b with it err = numpy.linalg.norm(b,2) * rel_err e = numpy.random.randn(b.size) e = err / numpy.linalg.norm(e,2) *e tilde_b = b + e # dictionary for the computed solutions tilde_x = {} errors = {} # regularize the problem, 'real' is a dummy method for the real solution for method in [ 'real', 'tsvd', 'tik', 'newtik' ]: if method is not 'real': tilde_x[method] = reg.solve(A,tilde_b,eta*err,method) errors[method] = (numpy.linalg.norm(tilde_x[method] - x,2))/numpy.linalg.norm(x,2) #print ( method + " " + str((numpy.linalg.norm(tilde_x[method] - x,2))/numpy.linalg.norm(x,2)) ) else: tilde_x[method] = x #pylab.plot(tilde_x[method],colors[method],label=method) # plot the solutions for method in [ 'real', 'tsvd', 'tik', 'newtik' ]: pylab.plot(tilde_x[method],colors[method],label=method) if name is 'shaw': pylab.legend(loc='upper left') else: pylab.legend(loc='upper right') pylab.title(name+" " + str( rel_err*100 ) + "%") pylab.savefig(name+'_'+str(int(rel_err*1000))+'.png') #pylab.show() pylab.clf() return errors
def initialize(): """Create initial sampling points.""" AiLHS = pytave.feval(1, "initial_pts_Nd", ninit, amin, amax, N) AiLHS = numpy.array(AiLHS) Ai = numpy.zeros([ninit,3]) for i in range(0,ninit): x = pytave.feval(1, "find_near_pt", AiLHS[0, i,:], N, spc, amin, amax) x = numpy.array(x) Ai[i,:] = x[0][0] return Ai
def testexpect(value, expected): try: nvalue, = pytave.feval(1, "test_return", value) if not equals(value, nvalue): fail("sent in %s, expecting %s, got %s", (value, expected, nvalue)) except TypeError, e: fail(value, e)
def testequal(value): try: nvalue, = pytave.feval(1, "test_return", value) if not equals(value, nvalue): fail("as %s != %s" % (value, nvalue)) except TypeError, e: fail(value, e)
def ptilde(self, Pp, Pg): """ Calculate transition probabilities Parameters ------------ Pp : ndarray, shape (n, k) Conditional choice probabilities for provinces Pg : ndarray, shape (n, 2 k) Conditional choice probabilities for the government Returns --------- P : ndarray Transition probability matrix Notes ----------- Takes conditional choice probabilities :math:`P` as an input and returns the transition matrix :math:`\\tilde{P}`. This is a wrapper for the matlab function **Ptilde**. """ return pytave.feval(1, "Ptilde", Pp, Pg, self.model())[0]
def phigprov(self, Pp, Pg, theta): """ Calculate transition probabilities Parameters ------------ Pp : ndarray, shape (n, k) Conditional choice probabilities for provinces Pg : ndarray, shape (n, 2 k) Conditional choice probabilities for the government theta : ndarray, shape (5, ) Parameters Returns --------- V : ndarray Observable state values Notes ----------- Takes conditional choice probabilities :math:`P` and :math:`\theta` as an input and returns values :math:`V^P`. This is the mapping :math:`\Phi` in part (b) of the assignment. This is a wrapper for the matlab function **Phigprov**. """ theta = sp.atleast_2d(theta) return pytave.feval(1, "Phigprov", Pp, Pg, theta, self.model())[0]
def new_p(self, Pp, Pg, theta): """ Calculate transition probabilities Parameters -------------- Pp : ndarray, shape (n, k) Conditional choice probabilities for provinces Pg : ndarray, shape (n, 2 k) Conditional choice probabilities for the government theta : ndarray, shape (5, ) Parameters Returns --------- Pp : ndarray, shape (n, k) New conditional choice probabilities for provinces Pg : ndarray, shape (n, 2 k) New conditional choice probabilities for the government Notes ----------- Takes conditional choice probabilities :math:`P` and :math:`\theta` as an input and returns new conditional choice values. This is the mapping :math:`\Psi` in part (c) of the assignment. This is a wrapper for the matlab function **NewP**. """ theta = sp.atleast_2d(theta) return pytave.feval(2, "NewP", Pp, Pg, theta, self.model())
def interpolate(self,points): derivs = numpy.row_stack( [numpy.zeros((1,self.d)), numpy.eye(self.d)] ) resp = pytave.feval(1,'my_funeval',points.T,derivs)[0] val = resp[:,:,0] dval = resp[:,:,1:] val = val.T dval = numpy.rollaxis(dval,0,3) return [val,dval]
def interpolate(self, points): derivs = numpy.row_stack([numpy.zeros((1, self.d)), numpy.eye(self.d)]) resp = pytave.feval(1, 'my_funeval', points.T, derivs)[0] val = resp[:, :, 0] dval = resp[:, :, 1:] val = val.T dval = numpy.rollaxis(dval, 0, 3) return [val, dval]
def testmatrix(value): try: nvalue, = pytave.feval(1, "test_return", value) class1, = pytave.feval(1, "class", value) class1 = class1.tostring() class2, = pytave.feval(1, "class", nvalue) class2 = class2.tostring() if not equals(value, nvalue): fail("as %s != %s" % (value, nvalue)) if value.shape != nvalue.shape: fail("Size check failed for: %s. Expected shape %s, got %s with shape %s" \ %(value, value.shape, nvalue, nvalue.shape)) if class1 != class2: fail("Type check failed for: %s. Expected %s. Got %s." % (value, class1, class2)) except TypeError, e: fail("Execute failed: %s" % value, e)
def __init__(self,atype, smin, smax, orders): self.smin = smin self.smax = smax self.bounds = numpy.row_stack([smin,smax]) self.d = len(smin) self.orders = orders self.__interp__ = pytave.feval(1, 'create_space', atype, orders, smin,smax) # we don't really need it here.. self.grid = self.__interp__[0]['points'][0,0].T
def search(Aall, Jall, curr_bestA, theta, upb, lob, N, amin, amax, spc, delta): """Search step.""" # make sure that all points are unique (Am, Jm) = pytave.feval(2, "dsmerge", Aall, Jall) next_ptsall = [] next_pts = None max_no_searches = 100 no_searches = 0 while next_pts == None and no_searches < max_no_searches: next_ptsall, min_est, max_mse_pt = pytave.feval( 3, "krig_min_find_MADS_oct", Am, Jm, curr_bestA, theta, upb, lob, N, amin, amax, spc, delta) next_pts = check_for_new_points(next_ptsall, Aall) no_searches += 1 return next_pts
def poll(Aall, Jall, curr_bestA, N, delta, spc, amin, amax): """Perform the poll step.""" poll_pts = None try: poll_ptsall = pytave.feval( 1, "MADS_poll_ptsNd3_oct", curr_bestA, N, delta, spc, amin, amax) poll_ptsall = poll_ptsall[0] poll_pts = check_for_new_points(poll_ptsall, Aall) poll_pts = pytave.feval( 1, "sort_poll_pts", Aall, Jall, poll_pts, theta, upb, lob, N, amin, amax) except Exception as e: print " This poll DID NOT work, must refine." return poll_pts
def __init__(self, atype, smin, smax, orders): self.smin = smin self.smax = smax self.bounds = numpy.row_stack([smin, smax]) self.d = len(smin) self.orders = orders self.__interp__ = pytave.feval(1, 'create_space', atype, orders, smin, smax) # we don't really need it here.. self.grid = self.__interp__[0]['points'][0, 0].T
def testsetget(variables, name, value): try: variables[name] = value if name not in variables: fail("set/get: %s: Should exist, not there." % name) result, = pytave.feval(1, "isequal", value, variables[name]) if not result: fail("set/get: %s -> %s: results diverged" % (name, value)) except Exception, e: fail("set/get: %s" % name, e)
def eigenvalue_problem(A, M): """Solve the eigenvalue problem with first available backend.""" if backends[0] == "oct2py": import oct2py as op octave = op.Oct2Py() e, l = octave.eig(A.array(), M.array()) elif backends[0] == "pytave": import pytave e, l = pytave.feval(2, "eig", A.array(), M.array()) return e, l
def get_smoothed_fieldmap(fm, fmmag, epi_qform, epi_shape): import pytave # FIXME: how do I automatically get the correct directory here? pytave.addpath('/home/bobd/git/nims/nimsutil') xform = np.dot(np.linalg.inv(fm.get_qform()), epi_qform) fm_pixdim = np.array(fm.get_header().get_zooms()[0:3]) fm_mag_data = fm_mag.get_data().mean(3).squeeze() # clean up with a little median filter and some greyscale open/close. # We'll use a structure element that is about 5mm (rounded up to the nearest pixdim) filter_size = 5.0/fm_pixdim fm_mag_data = ndimage.median_filter(fm_mag_data, filter_size.round().astype(int)) fm_mag_data = ndimage.morphology.grey_opening(fm_mag_data, filter_size.round().astype(int)) fm_mag_data = ndimage.morphology.grey_closing(fm_mag_data, filter_size.round().astype(int)) # Total image volume, in cc: fm_volume = np.prod(fm_pixdim) * np.prod(fm.get_shape()) / 1000 # typical human cranial volume is up to 1800cc. There's also some scalp and maybe neck, # so we'll say 2500cc of expected tissue volume. mag_thresh = np.percentile(fm_mag_data, max(0.0,100.0*(1.0-2500.0/fm_volume))) mask = ndimage.binary_opening(fm_mag_data>mag_thresh, iterations=2) # Now delete all the small objects, just keeping the largest (which should be the brain!) label_im,num_objects = ndimage.measurements.label(mask) h,b = np.histogram(label_im,num_objects) mask = label_im==b[h==max(h[1:-1])] mask_volume = np.prod(fm_pixdim) * max(h[1:-1]) / 1000.0 mask_sm = ndimage.gaussian_filter(mask.astype(np.float), filter_size) fm_Hz = fm.get_data().astype(np.float).squeeze() fm_Hz_sm = ndimage.gaussian_filter(fm_Hz * mask_sm, filter_size/2) fm_final = np.empty(epi_shape[0:3]) ndimage.affine_transform(fm_Hz_sm, xform[0:3,0:3], offset=xform[0:3,3], output_shape=epi_shape[0:3], output=fm_final) [xxBc,yyBc,zzBc] = np.mgrid[0:epi_shape[0],0:epi_shape[1],0:epi_shape[2]] # grid the epi, get location of each sampled voxel # Now apply the transform. The following is equivalent to dot(xform,coords), where "coords" is the # list of all the (homogeneous) coords. Writing out the dot product like this is just faster and easier. xxB = xxBc*xform[0,0] + yyBc*xform[0,1] + zzBc*xform[0,2] + xform[0,3] yyB = xxBc*xform[1,0] + yyBc*xform[1,1] + zzBc*xform[1,2] + xform[1,3] zzB = xxBc*xform[2,0] + yyBc*xform[2,1] + zzBc*xform[2,2] + xform[2,3] # use local linear regression to smooth and interpolate the fieldmaps. fm_smooth_param = 7.5/np.array(fm.get_header().get_zooms()[0:3]) # Want 7.5mm in voxels, so =7.5/mm_per_vox fm_smooth = pytave.feval(1,'localregression3d',fm.get_data(),xxB+1,yyB+1,zzB+1,np.array([]),np.array([]),fm_smooth_param,fm_mag.get_data())[0] return fm_smooth
def callMethod(self, msg): curPath = sys.path[0] logFilePath = curPath + "/contactjson.txt" logging.basicConfig(filename=logFilePath, level=logging.DEBUG) logging.debug("OLDLoading contact service") outputPictureName = "picturem.png" pytave.feval(0, "addpath", curPath) pytave.feval(0, "addpath", curPath + "/kMeans") pytave.feval(0, "addpath", curPath + "/pytave") outputPicture = curPath + "/kMeansPictures/" + outputPictureName pytave.feval(0, "exec", curPath + "/kMeansPictures/" + msg, outputPicture) ###TODO: implement compression algorithm here in order to put logging information during running # A = pytave.feval(1, "imread", '/home/aprovodi/simpleserver/VLayouts/output/services/bird_small.png') # B = A[0] / 255.0 # Divide by 255 so that all values are in the range 0 - 1 # os.mkdir("/home/aprovodi/simpleserver/VLayouts/temp/zhopa") # pytave.feval(1, "imwrite", B, "/home/aprovodi/simpleserver/VLayouts/temp/picture.jpg") # result = curPath + "/kMeansPictures/" + msg return outputPictureName
import numpy, pytave A = numpy.random.random([2, 2]) e = pytave.feval(1, "eig", A) print 'Eigenvalues:', e
if Ai.shape ==(3,): curr_bestA = Ai else: curr_bestA = Ai[i,:] curr = [curr_bestJ, curr_bestA, nit, neval, prev_it] cost_improve = 1 improve = 1 if improve == 0 and nit > 1: cost_improve = 0 elif nit == 1: cost_improve = 1 return cost_improve, curr_bestA, curr_bestJ # add SMF to the octave load path pytave.feval(0, "addpath", "SMF") # number of parameters N = 3 # min and max values for the parameters amin = numpy.array([100, 0.1, 0.1]) amax = numpy.array([10000, 1.0, 0.5 ]) # initial guess curr_best = [] curr_bestJ = 1000000 curr_bestA = numpy.array([1000, 0.5, 0.5]) # resolution of the Latin hyper cube spc = 5*numpy.ones([1,N])
arr2ch = Numeric.array(["abc", "def"], Numeric.Character) arr1o = Numeric.array([[1.0, "abc", 2 + 3j]], Numeric.PyObject) arr2o = Numeric.array([[1.0, "abc", 2 + 3j], [4.0, arr1i, "def"]], Numeric.PyObject) alimit_int32 = Numeric.array([[-2147483648, 2147483647]], Numeric.Int32) alimit_int16 = Numeric.array([[-32768, 32767, -32769, 32768]], Numeric.Int16) alimit_int8 = Numeric.array([[-128, 127, -129, 128]], Numeric.Int8) alimit_uint8 = Numeric.array([[0, 255, -1, 256]], Numeric.UnsignedInt8) # This eval call is not to be seen as a encouragement to use Pytave # like this. Create a separate .m-file with your complex Octave code. pytave.eval(0, "function [result] = test_return(arg); result = arg; endfunction") pytave.feval(1, "test_return", 1) def equals(a, b): return Numeric.alltrue(Numeric.ravel(a == b)) def fail(msg, exc=None): print "FAIL:", msg traceback.print_stack() if exc is not None: traceback.print_exc(exc) print "" def testequal(value):
bc = [None, None] u, v = TrialFunction(V), TestFunction(V) p, q = TrialFunction(Q), TestFunction(Q) p00 = inner(u, v) * dx a00 = div(u) * div(v) * dx + inner(u, v) * dx a01 = div(v) * p * dx a10 = div(u) * q * dx a11 = p * q * dx P00 = assemble(p00) A00 = assemble(a00) A10 = assemble(a10) A01 = assemble(a01) A11 = assemble(a11) e = pytave.feval(1, "check_eigs_vs", A11.array(), A01.array(), A00.array(), P00.array()) e = pytave.feval(1, "abs", e[0]) e = pytave.feval(1, "sort", e[0]) e = e[0] print " condition number 1 - div RT ", e[-1] / e[0], e[-1] / e[1] p00 = inner(u, v) * dx a00 = inner(u, v) * dx a01 = div(v) * p * dx a10 = div(u) * q * dx # a11 = p*q*dx + inner(grad(p),grad(q))*dx alpha = 1.0 n = FacetNormal(mesh) h = CellSize(mesh) h_avg = (h('+') + h('-')) / 2
import numpy, pytave A = numpy.random.random([2, 2]) B = numpy.random.random([2, 2]) e, v = pytave.feval(2, "eig", A, B) print 'Eigenvalues:', e print 'Eigenvectors:', v
import numpy, pytave A = numpy.random.random([2,2]) e = pytave.feval(1, "eig", A) print 'Eigenvalues:', e
def testvalueok(*value): try: pytave.feval(1, *value) except Exception, e: print "FAIL", (value, ), e
def set_values(self,values): pytave.feval(0,'set_coeffs',values.T)[0]
def __call__(self, points): derivs = numpy.zeros((1,self.d)) values = pytave.feval(1,'my_funeval',points.T,derivs)[0] return values.T
for N in Ns: mesh = UnitSquare(N, N) V = VectorFunctionSpace(mesh, "Lagrange", 2) Q = FunctionSpace(mesh, "Lagrange", 1) bc = [DirichletBC(V, Constant((0,0)), boundary), None] u, v = TrialFunction(V), TestFunction(V) p, q = TrialFunction(Q), TestFunction(Q) a00 = inner(epsilon(u), epsilon(v))*dx a01 = div(v)*p*dx a10 = div(u)*q*dx a11 = p*q*dx AA, AArhs = block_symmetric_assemble([[a00, a01], [a10, a11]], bcs=bc) e = pytave.feval(1, "check_eigs", AA[0,0].array(), AA[1,0].array(), AA[1,1].array()) e = pytave.feval(1, "abs", e[0]) e = pytave.feval(1, "sort", e[0]) e = e[0] print " condition number 1 - eps ", e[-1]/e[0], e[-1]/e[1] a00 = div(u)*div(v)*dx + inner(u,v)*dx a01 = div(v)*p*dx a10 = div(u)*q*dx a11 = p*q*dx AA, AArhs = block_symmetric_assemble([[a00, a01], [a10, a11]], bcs=bc)
def interpolate(self,points): derivs = numpy.row_stack( [numpy.zeros((1,self.d)), numpy.eye(self.d)] ) resp = pytave.feval(1,'my_funeval',points.T,derivs)[0] val = resp[:,:,0] dval = resp[:,:,1:] val = val.T dval = numpy.rollaxis(dval,0,3) return [val,dval] if __name__ == '__main__': pytave.feval(0,'addpath','/home/pablo/Programmation/compecon/CEtools') pytave.feval(0,'addpath','/home/pablo/Documents/Research/Thesis/Chapter_1/code/') orders = numpy.array( [ 5, 5 ] ) smin = numpy.array( [ 0.9, 0.5 ] ) smax = numpy.array( [ 1.1, 2 ] ) f = lambda x: x[0:1,:] * x[1:2,:] interp = CEInterpolation('spli',smin,smax,orders) values = f(interp.grid) print values
for N in Ns: mesh = UnitSquare(N, N) V = VectorFunctionSpace(mesh, "Lagrange", 2) Q = FunctionSpace(mesh, "Lagrange", 1) bc = [DirichletBC(V, Constant((0, 0)), boundary), None] u, v = TrialFunction(V), TestFunction(V) p, q = TrialFunction(Q), TestFunction(Q) a00 = inner(epsilon(u), epsilon(v)) * dx a01 = div(v) * p * dx a10 = div(u) * q * dx a11 = p * q * dx AA, AArhs = block_symmetric_assemble([[a00, a01], [a10, a11]], bcs=bc) e = pytave.feval(1, "check_eigs", AA[0, 0].array(), AA[1, 0].array(), AA[1, 1].array()) e = pytave.feval(1, "abs", e[0]) e = pytave.feval(1, "sort", e[0]) e = e[0] print " condition number 1 - eps ", e[-1] / e[0], e[-1] / e[1] a00 = div(u) * div(v) * dx + inner(u, v) * dx a01 = div(v) * p * dx a10 = div(u) * q * dx a11 = p * q * dx AA, AArhs = block_symmetric_assemble([[a00, a01], [a10, a11]], bcs=bc) e = pytave.feval(1, "check_eigs", AA[0, 0].array(), AA[1, 0].array(), AA[1, 1].array()) e = pytave.feval(1, "abs", e[0])
def fit_values(self, values): pytave.feval(0, 'set_coeffs', values.T)[0]
p, q = TrialFunction(Q), TestFunction(Q) p00 = inner(u,v)*dx a00 = div(u)*div(v)*dx + inner(u,v)*dx a01 = div(v)*p*dx a10 = div(u)*q*dx a11 = p*q*dx P00 = assemble(p00) A00 = assemble(a00) A10 = assemble(a10) A01 = assemble(a01) A11 = assemble(a11) e = pytave.feval(1, "check_eigs_vs", A11.array(), A01.array(), A00.array(), P00.array()) e = pytave.feval(1, "abs", e[0]) e = pytave.feval(1, "sort", e[0]) e = e[0] print " condition number 1 - div RT ", e[-1]/e[0], e[-1]/e[1] p00 = inner(u,v)*dx a00 = inner(u,v)*dx a01 = div(v)*p*dx a10 = div(u)*q*dx # a11 = p*q*dx + inner(grad(p),grad(q))*dx alpha = 1.0 n = FacetNormal(mesh) h = CellSize(mesh) h_avg = (h('+') + h('-'))/2
#!/usr/bin/python import pytave try: pytave.feval( 1, "", ) except pytave.OctaveError, e: print "test ok" except: print "test fail" try: pytave.feval( 1, "cell", ) except pytave.ValueConvertError, e: print "test ok" except: print "test fail" try: pytave.feval(1, "sin", {"asdf": "asdf"}) except pytave.ObjectConvertError, e: print "test ok" except: print "test fail"
values = pytave.feval(1, 'my_funeval', points.T, derivs)[0] return values.T def interpolate(self, points): derivs = numpy.row_stack([numpy.zeros((1, self.d)), numpy.eye(self.d)]) resp = pytave.feval(1, 'my_funeval', points.T, derivs)[0] val = resp[:, :, 0] dval = resp[:, :, 1:] val = val.T dval = numpy.rollaxis(dval, 0, 3) return [val, dval] if __name__ == '__main__': pytave.feval(0, 'addpath', '/home/pablo/Programmation/compecon/CEtools') pytave.feval(0, 'addpath', '/home/pablo/Documents/Research/Thesis/Chapter_1/code/') orders = numpy.array([5, 5]) smin = numpy.array([0.9, 0.5]) smax = numpy.array([1.1, 2]) f = lambda x: x[0:1, :] * x[1:2, :] interp = CEInterpolation('spli', smin, smax, orders) values = f(interp.grid) print values
def __call__(self, points): derivs = numpy.zeros((1, self.d)) values = pytave.feval(1, 'my_funeval', points.T, derivs)[0] return values.T
import numpy, pytave A = numpy.random.random([2,2]) B = numpy.random.random([2,2]) e, v = pytave.feval(2, "eig", A, B) print 'Eigenvalues:', e print 'Eigenvectors:', v