Пример #1
0
def test_point(m=3):
    lb = 0 * np.ones(m)
    ub = 1 * np.ones(m)

    dom = BoxDomain(lb, ub)
    assert dom.is_point == False

    dom = BoxDomain(ub, ub)
    assert dom.is_point == True

    dom = BoxDomain(lb, ub)
    dom = dom.add_constraints(A_eq=np.ones((1, m)), b_eq=[0])
    assert dom.is_point == True
Пример #2
0
def test_poly_fit(dimension=2, degree=5, tol=1e-6):
    np.random.seed(0)
    dom = BoxDomain(-np.ones(dimension), np.ones(dimension))
    X = dom.sample(100)

    fXnoise = np.random.randn(X.shape[0])

    for bound in ['lower', 'upper', None]:
        for norm in [1, 2, np.inf]:
            for basis in [
                    'arnoldi', 'legendre', 'monomial', 'chebyshev', 'laguerre',
                    'hermite'
            ]:
                pa = PolynomialApproximation(degree,
                                             basis=basis,
                                             norm=norm,
                                             bound=bound)
                pa.fit(X, fXnoise)
                if bound == 'lower':
                    I = ~(pa(X) - tol <= fXnoise)
                    if np.sum(I) > 0:
                        print('%s lower:' % basis)
                        print(pa(X[I]), fXnoise[I])
                        assert False
                if bound == 'upper':
                    I = ~(pa(X) + tol >= fXnoise)
                    if np.sum(I) > 0:
                        print('%s upper:' % basis)
                        print(pa(X[I]), fXnoise[I])
                        assert False
Пример #3
0
def build_otl_circuit_domain():
    # Parameters
    # R_b1, R_b2, R_f, R_c1, R_c2, beta
    lb = np.array([50, 25, 0.5, 1.2, 0.25, 50])
    ub = np.array([150, 70, 3, 2.5, 1.2, 300])

    return BoxDomain(lb, ub)
Пример #4
0
def test_return_grad2(m=3):
	A = np.random.randn(m, m)
	A += A.T
	
	B = np.random.randn(m, m)
	B += B.T

	def func(x, return_grad = False):
		fx = [0.5*x.dot(A.dot(x)), 0.5*x.dot(B.dot(x))]

		if return_grad:
			grad = [A.dot(x), B.dot(x)]
			return fx, grad
		else:
			return fx
	
	dom = BoxDomain(-2*np.ones(m), 2*np.ones(m))

	fun = Function(func, dom, return_grad = True)	


	X = fun.domain.sample(4)
	fX, grads = fun(X, return_grad = True)
	assert fX.shape == (len(X), 2)
	assert grads.shape == (len(X), 2, m)
	
	for x, grad in zip(X, grads):
		assert np.all(np.isclose(grad, fun.grad(x)))
Пример #5
0
def test_vertex_eq(m = 5):
	np.random.seed(0)
	dom = BoxDomain(-np.ones(m), np.ones(m))
	dom = dom.add_constraints(A_eq = np.ones(m), b_eq = [0])
	Xhat = dom.sample(10)
	X0 = dom.sample(5)
	check_vertex_sample(dom, Xhat, X0)
Пример #6
0
def test_vertex_rectangular(m = 5):
	np.random.seed(0)
	dom = BoxDomain(-np.ones(m), np.ones(m))
	Xhat = dom.sample(10)
	X0 = dom.sample(100)
	L = np.ones((1, m))
	check_vertex_sample(dom, Xhat, X0, L = L)
Пример #7
0
def test_vertex_weight(m = 5):
	np.random.seed(0)
	dom = BoxDomain(-np.ones(m), np.ones(m))
	Xhat = dom.sample(10)
	X0 = dom.sample(100)
	L = np.diag(1./np.arange(1,m+1))
	check_vertex_sample(dom, Xhat, X0, L = L)
Пример #8
0
def test_poly_basis(dimension=2, degree=5):
    """ test different bases"""
    np.random.seed(0)
    basis = LegendreTensorBasis(degree, dim=dimension)
    coef = np.random.randn(len(basis))
    pf = PolynomialFunction(basis, coef)

    dom = BoxDomain(-np.ones(dimension), np.ones(dimension))
    X = dom.sample(100)
    fX = pf(X)
    Xtest = dom.sample(1000)
    fXtest = pf(Xtest)

    for basis in [
            'arnoldi', 'legendre', 'monomial', 'chebyshev', 'laguerre',
            'hermite'
    ]:
        print("basis ", basis)
        pa = PolynomialApproximation(degree, basis=basis)
        print("fitting")
        pa.fit(X, fX)
        print(pa.basis.V(Xtest).shape)
        print(pa(Xtest).shape)
        print(fXtest.shape)
        assert np.linalg.norm(pa(Xtest) - fXtest, np.inf) < 1e-7
Пример #9
0
def build_borehole_domain():
    # Parameters
    # r_w, r, T_u, H_u, T_l, H_l, L, K_w
    lb = np.array([0.05, 100, 63070, 990, 63.1, 700, 1120, 9855])
    ub = np.array([0.15, 50e3, 115600, 1110, 116, 820, 1680, 12045])

    return BoxDomain(lb, ub)
Пример #10
0
def build_oas_design_domain(n_cp=3):
    # Twist
    domain_twist = BoxDomain(-1 * np.ones(n_cp),
                             1 * np.ones(n_cp),
                             names=['twist %d' % (i, ) for i in range(1, 4)])
    # Thick
    domain_thick = BoxDomain(
        0.005 * np.ones(n_cp),
        0.05 * np.ones(n_cp),
        names=['thickness %d' % (i, ) for i in range(1, 4)])
    # Root Chord
    domain_root_chord = BoxDomain(0.7, 1.3, names=['root chord'])
    # Taper ratio
    domain_taper_ratio = BoxDomain(0.75, 1.25, names=['taper ratio'])

    return TensorProductDomain(
        [domain_twist, domain_thick, domain_root_chord, domain_taper_ratio])
Пример #11
0
def test_vertex_low_rank_nonrandomize(m = 5):
	np.random.seed(0)
	dom = BoxDomain(-np.ones(m), np.ones(m))
	Xhat = dom.sample(10)
	X0 = dom.sample(100)
	L = np.diag(1./np.arange(1,m+1))
	L[0,0] = 0.
	check_vertex_sample(dom, Xhat, X0, L = L, randomize = False)
Пример #12
0
def test_sample_grid(m=3):
    lb = 0 * np.ones(m)
    ub = 1 * np.ones(m)

    dom = BoxDomain(lb, ub)

    X = dom.sample_grid(5)
    assert len(X) == 5**m
Пример #13
0
def build_beam_domain():
    # Note the book has an invalid range for height "(20mm > b > 250 mm)" and breadth "(10 mm > b > 50mm)"
    # Here we follow the dimensions implied in the corresponding matlab code
    # b = x(1)*0.045 +0.005
    # h = x(2)*0.23 + 0.02
    # I assume these definitions are in meters
    domain = BoxDomain([5e-3, 0.02], [50e-3, 0.25],
                       names=['breadth (m)', 'height (m)'])
    return domain
Пример #14
0
def build_golinski_design_domain():
    return BoxDomain([2.6, 0.7, 7.3, 7.3, 2.9, 5.0],
                     [3.6, 0.8, 8.3, 8.3, 3.9, 5.5],
                     names=[
                         "width of gear face", "teeth module",
                         "shaft 1 length between bearings",
                         "shaft 2 length between bearings",
                         "diameter of shaft 1", "diameter of shaft 2"
                     ])
Пример #15
0
def test_func():
	client = Client(processes = False)
	dom = BoxDomain(-1,1)
	fun = Function(func, dom, dask_client = client)
	X = dom.sample(5)
	res = fun.eval_async(X)
	for r, x in zip(res, X):
		print(r.result())
		assert np.isclose(x, r.result())
Пример #16
0
def test_isinside(m=5):
    np.random.seed(0)
    dom = BoxDomain(-10 * np.ones(m), -5 * np.ones(m))

    X = dom.sample(10)

    Xg = dom.sample_grid(2)
    hull = ConvexHullDomain(Xg)

    assert np.all(hull.isinside(X))
Пример #17
0
def test_fill_distance(m = 5):
	dom = BoxDomain(-np.ones(m), np.ones(m))
	Xhat = dom.sample(10)
	X0 = dom.sample(1e2)
	x = seq_maximin_sample(dom, Xhat, X0 = X0)
	

	d = np.min(cdist(x.reshape(1,-1), Xhat))
	
	d2 = fill_distance_estimate(dom, Xhat, X0 = X0)
	assert np.isclose(d, d2)
Пример #18
0
def build_robot_arm_domain():
    # Parameters
    # theta 1-4, L 1-4
    lb = np.array([0, 0, 0, 0, 0, 0, 0, 0])
    ub = np.array([2 * np.pi, 2 * np.pi, 2 * np.pi, 2 * np.pi, 1, 1, 1, 1])
    return BoxDomain(lb,
                     ub,
                     names=[
                         'theta_1', 'theta_2', 'theta_3', 'theta_4', 'L_1',
                         'L_2', 'L_3', 'L_4'
                     ])
Пример #19
0
def test_closest_point(m=5):
    Ls = [np.eye(m)]
    ys = [np.zeros(m)]
    rhos = [1]
    dom1 = LinQuadDomain(Ls=Ls, ys=ys, rhos=rhos)

    dom2 = BoxDomain([2], [3])
    dom = dom1 * dom2
    x0 = np.zeros(m + 1)
    x = dom.closest_point(x0)
    assert np.all(np.isclose(x[0:m], 0))
    assert np.all(np.isclose(x[-1], 2))
Пример #20
0
def test_box(m=10):
    dom = BoxDomain(-np.ones(m), np.ones(m))
    assert len(dom) == m

    x = dom.corner(np.ones(m))
    assert np.all(np.isclose(x, np.ones(m)))

    A = np.ones((1, m))
    b = np.zeros(1)
    dom2 = dom.add_constraints(A_eq=A, b_eq=b)
    x = dom2.sample()
    assert np.isclose(np.dot(A, x), b)
Пример #21
0
def build_hartmann_domain():
    # Ranges are taken from GCSW17, Table 2
    # The second parameter 'fluid density' does not appear in either function
    return BoxDomain(
        [0.05, 0.5, 0.5, 0.1],
        [0.2, 3, 3, 1],
        names=[
            'fluid viscosity',  # mu
            'applied pressure gradient',  # d p_0/ dx
            'resistivity',  # eta
            'applied magnetic field'  # B_0
        ])
Пример #22
0
def test_maximin(N = 11, m = 5):
	dom = BoxDomain(-np.ones(m), np.ones(m))
	L = np.ones((1,m))
	X = psdr.maximin_block(dom, N, L = L, maxiter = 500)
	print(X)
	d = L.dot(X.T).flatten()
	d = np.sort(d)
	print(d)
	d_expect = np.linspace(-m,m, N)
	print(d_expect)
	assert np.all(np.isclose(d, d_expect, atol = 1e-5))
		
	# Now do a 2-d version
	L = np.random.randn(2, m)
	X = psdr.maximin_block(dom, N, L = L, maxiter = 50, verbose = True)
Пример #23
0
def build_borehole_domain():
    r""" Constructs a deterministic domain associated with the borehole function

	Returns
	-------
	dom: BoxDomain
		Domain associated with the borehole function
	"""
    # Parameters
    # r_w, r, T_u, H_u, T_l, H_l, L, K_w
    lb = np.array([0.05, 100, 63070, 990, 63.1, 700, 1120, 9855])
    ub = np.array([0.15, 50e3, 115600, 1110, 116, 820, 1680, 12045])

    return BoxDomain(
        lb, ub, names=['r_w', 'r', 'T_u', 'H_u', 'T_l', 'H_l', 'L', 'K_w'])
Пример #24
0
def no_test_lipschitz_sample(N = 5, m = 3):
	dom = BoxDomain(-np.ones(m), np.ones(m))
	# Add an inequality constraint so some combinations aren't feasible
	dom = dom.add_constraints(A = np.ones((1,m)), b = np.ones(1))
	Ls = [np.random.randn(1,m) for j in range(2)]

	# Limit the number of iterations to reduce computational cost
	X = psdr.lipschitz_sample(dom, N, Ls, maxiter = 3, jiggle = False)
	print(X)
	assert np.all(dom.isinside(X))

	# Verify that each point is distinct in projections
	for L in Ls:
		y = L.dot(X.T).T
		print(y)
		assert np.min(pdist(y)) > 0, "points not distinct in projection"
Пример #25
0
def test_lambda():
	dom = BoxDomain(-1,1)
	def f(x):
		return x	
	#f = lambda x: x
	print('about to start client')
	
	# We use a threaded version for sanity
	# https://github.com/dask/distributed/issues/2515
	client = Client(processes = False)
	print(client)
	fun = Function(f, dom, dask_client = client)

	x = dom.sample(1)
	res = fun.eval_async(x)
	print(x, res.result())
	assert np.isclose(x, res.result())
Пример #26
0
def test_mult_output(M= 10,m = 5):
	dom = BoxDomain(-np.ones(m), np.ones(m))
	X = dom.sample(M)

	a = np.random.randn(m)
	b = np.random.randn(m)

	def fun_a(X):
		return a.dot(X.T)
	
	def fun_b(X):
		return b.dot(X.T)
	
	def fun(X):
		return np.vstack([X.dot(a), X.dot(b)]).T


	print("Single function with multiple outputs")
	for vectorized in [True, False]:
		myfun = Function(fun, dom, vectorized = vectorized)
		print(fun(X))
		print("vectorized", vectorized)
		print(myfun(X).shape)
		assert myfun(X).shape == (M, 2) 
		print(myfun(X[0]).shape)
		assert myfun(X[0]).shape == (2,)

		fX = fun(X)
		for i, x in enumerate(X):
			assert np.all(np.isclose(fX[i], fun(x)))
	
	print("Two functions with a single output each")
	for vectorized in [True, False]:
		myfun = Function([fun_a, fun_b], dom, vectorized = vectorized)
		print(fun(X))
		print("vectorized", vectorized)
		print(myfun(X).shape)
		assert myfun(X).shape == (M, 2) 
		print(myfun(X[0]).shape)
		assert myfun(X[0]).shape == (2,)
		
		fX = fun(X)
		for i, x in enumerate(X):
			assert np.all(np.isclose(fX[i], fun(x)))
Пример #27
0
def test_vertex_full(m = 2):
	np.random.seed(0)
	dom = BoxDomain(-np.ones(m), np.ones(m))
	
	Xhat = dom.sample(10)
	#check_vertex(dom, Xhat)

	# Check with degenerate points
	Xhat[1] = Xhat[0]
	#check_vertex(dom, Xhat)

	# Check with a Lipschitz matrix
	np.random.seed(0)
	Xhat = dom.sample(5)
	#L = np.random.randn(m,m)
	L = np.diag(np.arange(1, m+1))
	print(L)
	print("Checking with a Lipschitz matrix")
	check_vertex(dom, Xhat, L = L)
Пример #28
0
def test_cheb(m=5):
    lb = -np.ones(m)
    ub = np.ones(m)
    dom = BoxDomain(lb, ub)
    A = np.ones((1, m))
    b = np.zeros(1, )

    dom2 = dom.add_constraints(A, b)

    center, radius = dom2.chebyshev_center()
    print center
    print radius

    assert dom2.isinside(center), "Center must be inside"

    for i in range(100):
        p = np.random.randn(m)
        p /= np.linalg.norm(p)
        assert dom2.extent(center, p) >= radius, "violated radius assumption"
Пример #29
0
def test_bad_scaling():

    # TODO: This fails with ub = 1e7
    # This is mainly due to solver tolerances
    lb = [-1, 1e7]
    ub = [1, 2e7]
    dom1 = BoxDomain(lb=lb, ub=ub)
    dom2 = LinQuadDomain(lb=lb, ub=ub, verbose=True)

    # Check quality of solution
    p = np.ones(len(dom1))
    # this calls an algebraic formula
    x1 = dom1.corner(p)
    # whereas this calls a linear program
    x2 = dom2.corner(p)
    for x1_, x2_, lb_, ub_ in zip(x1, x2, dom2.lb, dom2.ub):
        print("x1:%+15.15e x2:%+15.15e delta:%+15.15e; lb: %+5.2e ub: %+5.2e" %
              (x1_, x2_, np.abs(x1_ - x2_), lb_, ub_))
    assert np.all(np.isclose(x1, x2, rtol=1e-4, atol=1e-4))
Пример #30
0
def test_constraints(m=3):
    np.random.seed(0)

    dom = BoxDomain(-1 * np.ones(m), np.ones(m))

    # Lower pyramid portion
    dom_con = dom.add_constraints(A=np.ones((1, m)), b=np.ones(1))

    # Convex hull describes the same space as dom_con
    X = dom.sample_grid(2)
    hull = ConvexHullDomain(X, A=dom_con.A, b=dom_con.b)

    # Check that the same points are inside
    X = dom.sample(100)
    assert np.all(hull.isinside(X) == dom_con.isinside(X))

    # Check sampling
    X = hull.sample(100)
    assert np.all(dom_con.isinside(X))