本文整理汇总了Python中function.Function类的典型用法代码示例。如果您正苦于以下问题:Python Function类的具体用法?Python Function怎么用?Python Function使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Function类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: grow
def grow(self, depth=None):
""" Grows a random child node by 1, limited by `depth` (if provided)
and arity restrictions. Returns the new node (or None if no
node can be expanded).
Args:
depth: int (default=None)
Returns:
Node instance (or None)
"""
# Creates a random permutation of child nodes
nodes_depths = list(self.descendants_and_self_with_depths())
shuffle(nodes_depths)
for node, d in nodes_depths:
if len(node.children) >= node.func.arity:
continue
if d >= depth:
continue
if d == depth - 1:
func = Function.random_terminal()
else:
func = Function.random_function()
child = Node(func)
node.add_child(child)
return child
# If no children can be expanded, return None
return None
示例2: test_cubic_derivative
def test_cubic_derivative(self):
a = cubic_derivative_approximation(
Function.power(Function.identity(), Function.constant(3)),
4, 10)
self.assertAlmostEqual(a(0), 0)
self.assertAlmostEqual(a(2), 8)
self.assertAlmostEqual(a(5), 125)
self.assertAlmostEqual(a(12), 1728)
self.assertAlmostEqual(a(-3), -27)
示例3: __init__
def __init__(self, cursor, comment):
Function.__init__(self, cursor, comment)
self.static = cursor.is_static_method()
self.virtual = cursor.is_virtual_method()
self.abstract = True
self._override = None
self.update_abstract(cursor)
示例4: mutate_float
def mutate_float(node, score_tree, eps=1e-1):
""" Takes a Node object and optimizes floats greedily.
Returns a new tree.
Args:
node: Node object to operate on
score_tree: function that takes a tree
and returns a fitness (as float)
eps: learning rate (as float) (default=1e-1)
Returns:
Node object
"""
# Copy the tree
new_tree = node.deepcopy()
# Find all floating leaves
floats = new_tree.all_floats()
if floats == []:
return None
has_changed = False
for f in floats:
value = f.func.func()
left_value = value - eps
right_value = value + eps
func = f.func
left_func = Function.make_float_function(left_value)
left_func = Function(left_func, 0, str(left_value))
right_func = Function.make_float_function(right_value)
right_func = Function(right_func, 0, str(right_value))
score = score_tree(new_tree)
f.func = left_func
left_score = score_tree(new_tree)
f.func = right_func
right_score = score_tree(new_tree)
max_ = max(left_score, score, right_score)
if abs(max_ - left_score) < 1e-10:
f.func = left_func
has_changed = True
elif abs(max_ - right_score) < 1e-10:
f.func = right_func
has_changed = True
else:
f.func = func
if not has_changed:
return None
return new_tree
示例5: recursively_generate_cubics
def recursively_generate_cubics(f, left, right, depth = 5):
for a in approximate(f, left, right):
if is_bounded(Function.sum(f, Function.product(
Function.constant(-1), a)), Interval(left, right),
Interval(-.008, .008)):
return [a]
if depth == 0:
return []
middle = (left + right) / 2
return recursively_generate_cubics(f, left, middle, depth-1) + \
recursively_generate_cubics(f, middle, right, depth-1)
示例6: test_depth
def test_depth(self):
f = Function.sum(Function.power(Function.identity(),
Function.constant(2)),
Function.identity())
# This requires splitting in half
self.assertTrue(is_bounded(f, Interval(-1,0), Interval(-3/4,1/2), 1))
self.assertEqual(is_bounded(f, Interval(-1,0), Interval(-3/4,1/2), 0),
None)
# This requires 3 levels of recursion
self.assertTrue(is_bounded(f, Interval(-1,0), Interval(-3/8,1/8), 3))
self.assertEqual(is_bounded(f, Interval(-1,0), Interval(-3/8,1/8), 2),
None)
# This requires 8 levels of recursion
self.assertTrue(is_bounded(f, Interval(-1,0), Interval(-65/256,1/256),
8))
self.assertEqual(is_bounded(f, Interval(-1,0), Interval(-65/256,1/256),
7), None)
示例7: __init__
def __init__(self, pt_left_bot, pt_right_top, win):
self.function = Function("0")
self.p1 = pt_left_bot
self.p2 = pt_right_top
self.graph_area = Rectangle(self.p1, self.p2)
self.win = win
self.accuracy = 0.1
self.objects_drawn = []
示例8: main
def main():
Maths.generateMathExpressions()
print("Available operators:")
for o in Maths.Expressions:
print(Maths.Expressions[o].getAbbreviation())
print("-------------------------")
f = Function("cos(3*x)+6/4*(x+3)", False)
print("RPN String", f.getRpnString())
for x in range (2, 11):
f.compute(x)
print("-------------------------")
f = Function("56*((6+2)/(8-x)*2^3", False)
print("RPN String", f.getRpnString()) #should give 56 6 2 + 8 7 - / 2 3 ^ * *
mainwindow = MainWindow("Function Drawer", 992, 512)
fx = f.computeRange(0, 10)
max_y = max(fx.values())
min_y = min(fx.values())
print(min_y, max_y)
mainwindow.setCoords(-1, min_y, 11, max_y)
for x in range(0, 11):
print(fx[x])
p = Point(x, fx[x])
p.draw(mainwindow)
input("Press a key to quit")
示例9: test_approx
def test_approx(self):
f = Function.identity()
for a in approximate(f, 0, 1):
self.assertTrue(isinstance(a, Function))
self.assertTrue(isinstance(a, CubicSpline))
# We may someday generate approximations that don't go through
# the endpoints, and remove these tests. Until then, they
# help verify that the approximation formulas are correct.
self.assertEqual(a(0.0), 0.0)
self.assertEqual(a(1.0), 1.0)
# (-x^2 - 1) ^ .5
bad = Function.power(Function.sum(Function.product(
Function.constant(-1),
Function.power(Function.identity(), Function.constant(2))),
Function.constant(-1)),
Function.constant(.5))
self.assertEqual(list(approximate(bad, 0, 1)), [])
示例10: create_full_tree
def create_full_tree(depth):
""" Creates a tree using the full method with depth `depth`.
Returns the root node.
Args:
depth: int
Returns:
Node instance
"""
if depth == 0:
# Generate a leaf node
terminal = Function.random_terminal()
node = Node(terminal)
return node
else:
# Generate an intermediate node
func = Function.random_function()
node = Node(func)
for _ in range(func.arity):
node.add_child(TreeMethods.create_full_tree(depth - 1))
return node
示例11: __init__
def __init__(self, t0, t1, f0, c0, c1, f1):
self.__t0 = t0
self.__t1 = t1
self.__f0 = f0
self.__c0 = c0
self.__c1 = c1
self.__f1 = f1
# The specific functional form will have consequences for the
# efficiency of interval arithmetic (and thus, slicing).
# t' = (t-t0)/(t1-t0)
t = Function.product(Function.sum(Function.identity(), Function.constant(-t0)),
Function.constant(1.0/(t1-t0)))
omt = Function.sum(Function.constant(1), Function.product(Function.constant(-1), t))
def term(const, f):
return Function.sum(Function.constant(const), Function.product(t, f))
a = -f0 + 3*c0 - 3*c1 + f1
b = 3*f0 - 6*c0 + 3*c1
c = -3*f0 + 3*c0
d = f0
WrappedFunction.__init__(self, term(d, term(c, term(b, Function.constant(a)))).weak_simplify())
示例12: test_simple
def test_simple(self):
self.assertTrue(is_bounded(Function.identity(), Interval(0,1),
Interval(0,1)))
self.assertFalse(is_bounded(Function.identity(), Interval(0,2),
Interval(0,1)))
self.assertFalse(is_bounded(Function.identity(), Interval(-1,1),
Interval(0,1)))
self.assertFalse(is_bounded(Function.identity(), Interval(-1,2),
Interval(0,1)))
self.assertTrue(is_bounded(Function.constant(0.), Interval(3,4),
Interval(0,1)))
self.assertFalse(is_bounded(Function.constant(2.), Interval(3,4),
Interval(0,1)))
示例13: create_grow_tree
def create_grow_tree(depth):
""" Creates a tree using the grow method with depth `depth`. Note
that since grow ends when all leaf nodes are 0-arity, it is
possible that the tree generated by this method has a depth
less than `depth`.
Args:
depth: int
Returns:
Node instance
"""
func = Function.random_function()
root = Node(func)
while True:
if root.grow(depth) is None:
break
return root
示例14: initialize_traj
def initialize_traj(self, mode):
# see comment at top of ll_prob.py for mode options
if self.trust_region_cnt is not None:
self.model.remove(self.trust_region_cnt)
self.clean(self.trust_temp)
for constraint in self.constraints:
constraint.clean()
obj = grb.QuadExpr()
for var in self.vars:
if var.get_val() is not None and var.recently_sampled:
obj += 1e5 * self.l2_norm_diff_squared(self.model, var)
elif var.get_val() is not None and var.is_resampled:
obj += 1 * self.l2_norm_diff_squared(self.model, var)
if mode == "straight":
obj += grb.quicksum(self.obj_quad)
elif mode == "l2":
for var in self.vars:
if var.get_val() is not None:
obj += self.l2_norm_diff_squared(self.model, var)
elif mode == "minvel":
for var in self.vars:
if var.hl_param.is_traj:
K = var.hl_param.num_dofs()
T = var.hl_param.num_timesteps()
KT = K * T
v = -1 * np.ones((KT - K, 1))
d = np.vstack((np.ones((KT - K, 1)), np.zeros((K, 1))))
# [:,0] allows numpy to see v and d as one-dimensional so
# that numpy will create a diagonal matrix with v and d as a diagonal
P = np.diag(v[:, 0], K) + np.diag(d[:, 0])
# minimum-velocity finite difference
Q = np.dot(np.transpose(P), P)
obj += Function.quad_expr((var.get_grb_vars(self) - var.get_val()).flatten(order="f"), Q)
else:
raise NotImplementedError
return self.optimize(objective=obj)
示例15: solve
def solve(n_cells, degree=3, with_plot=False):
# Problem
w = 3 * np.pi
x = Symbol("x")
u = sin(w * x)
f = -u.diff(x, 2)
# As Expr
u = Expression(u)
f = Expression(f)
# Space
# element = HermiteElement(degree)
poly_set = leg.basis_functions(degree)
dof_set = chebyshev_points(degree)
element = LagrangeElement(poly_set, dof_set)
mesh = IntervalMesh(a=-1, b=1, n_cells=n_cells)
V = FunctionSpace(mesh, element)
bc = DirichletBC(V, u)
# Need mass matrix to intefrate the rhs
M = assemble_matrix(V, "mass", get_geom_tensor=None, timer=0)
# NOTE We cannot you apply the alpha transform idea because the functions
# are mapped with this selective weight on 2nd, 3rd functions. So some rows
# of alpha would have to be multiplied by weights which are cell specific.
# And then on top of this there would be a dx = J*dy term. Better just to
# use the qudrature representations
# Mpoly_matrix = leg.mass_matrix(degree)
# M_ = assemble_matrix(V, Mpoly_matrix, Mget_geom_tensor, timer=0)
# Stiffness matrix for Laplacian
A = assemble_matrix(V, "stiffness", get_geom_tensor=None, timer=0)
# NOTE the above
# Apoly_matrix = leg.stiffness_matrix(degree)
# A_ = assemble_matrix(V, Apoly_matrix, Aget_geom_tensor, timer=0)
# Interpolant of source
fV = V.interpolate(f)
# Integrate in L2 to get the vector
b = M.dot(fV.vector)
# Apply boundary conditions
bc.apply(A, b, True)
x = spsolve(A, b)
# As function
uh = Function(V, x)
# This is a (slow) way of plotting the high order
if with_plot:
fig = plt.figure()
ax = fig.gca()
uV = V.interpolate(u)
for cell in Cells(mesh):
a, b = cell.vertices[0, 0], cell.vertices[1, 0]
x = np.linspace(a, b, 100)
y = uh.eval_cell(x, cell)
ax.plot(x, y, color=random.choice(["b", "g", "m", "c"]))
y = uV.eval_cell(x, cell)
ax.plot(x, y, color="r")
y = u.eval_cell(x, cell)
ax.plot(x, y, color="k")
plt.show()
# Error norm in CG high order
fine_degree = degree + 3
poly_set = leg.basis_functions(fine_degree)
dof_set = chebyshev_points(fine_degree)
element = LagrangeElement(poly_set, dof_set)
V_fine = FunctionSpace(mesh, element)
# Interpolate exact solution to fine
u_fine = V_fine.interpolate(u)
# Interpolate approx solution fine
uh_fine = V_fine.interpolate(uh)
# Difference vector
e = u_fine.vector - uh_fine.vector
# L2
if False:
Apoly_matrix = leg.mass_matrix(fine_degree)
get_geom_tensor = lambda cell: 1.0 / cell.Jac
# Need matrix for integration of H10 norm
else:
Apoly_matrix = leg.stiffness_matrix(fine_degree)
get_geom_tensor = lambda cell: cell.Jac
A_fine = assemble_matrix(V_fine, Apoly_matrix, get_geom_tensor, timer=0)
# Integrate the error
e = sqrt(np.sum(e * A_fine.dot(e)))
# Mesh size
#.........这里部分代码省略.........