本文整理汇总了Python中Problem.Problem类的典型用法代码示例。如果您正苦于以下问题:Python Problem类的具体用法?Python Problem怎么用?Python Problem使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Problem类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: search
def search(iterations, population, low_bound, high_bound, max_vel, C1, C2, topology, pso_type):
problem = Problem()
fitness = []
pop = create_population(population)
collection = list(enumerate(pop, start=0))
gbest = update_global_best(pop)
lbest = gbest
fbest = gbest
for ite in xrange(iterations):
for i, particle in collection:
if topology == "local":
lbest = update_local_best(pop, i, lbest)
update_velocity(particle, lbest, max_vel, C1, C2, ite, pso_type)
elif topology == "focal":
fbest = update_local_best(pop, i, fbest)
update_velocity(particle, fbest, max_vel, C1, C2, ite, pso_type)
else:
update_velocity(particle, gbest, max_vel, C1, C2, ite, pso_type)
update_position(particle, low_bound, high_bound)
particle.cost = problem.sphere(particle.position)
update_personal_best(particle)
gbest = update_global_best(pop, gbest)
print "Iteration: ", ite, "Fitness: ", gbest.cost
fitness.append(gbest.cost)
return gbest, fitness
示例2: __init__
def __init__(self, name="timedependent"):
"""
Constructor.
"""
Problem.__init__(self, name)
self._loggingPrefix = "PrTD "
return
示例3: verifyConfiguration
def verifyConfiguration(self):
"""
Verify compatibility of configuration.
"""
Problem.verifyConfiguration(self)
self.formulation.verifyConfiguration()
return
示例4: _configure
def _configure(self):
"""
Set members based using inventory.
"""
Problem._configure(self)
self.elasticPrestep = self.inventory.elasticPrestep
self.formulation = self.inventory.formulation
self.checkpointTimer = self.inventory.checkpointTimer
return
示例5: initialize
def initialize(self):
problem = Problem()
parameters = Parameters()
problem_type = parameters.problem_type
low_bound, high_bound = parameters.set_bounds(problem_type)
self.position = np.random.uniform(low_bound, high_bound, parameters.dimension)
self.velocity = np.random.uniform(parameters.min_vel, parameters.max_vel, parameters.dimension)
self.cost = problem.cost_function(self.position)
self.best_position = self.position[:]
self.best_cost = self.cost
示例6: merge
def merge(self, lengths, demands):
problem = Problem(stockLength=self.descriptors.stockLength)
for i, length in enumerate(lengths):
if i == len(lengths) - 1 or length != lengths[i + 1]:
order = Order(length, demands[i])
problem.addOrder(order)
else:
demands[i + 1] += demands[i]
return problem
示例7: init
def init(v0, T, dt, N, parameters):
problem = Problem(parameters)
problem.set_initial_condition(v0);
c = Solver(problem)
c.set_timestep(dt)
v = c.solve(T)
time = linspace(0,dt*N,N);
return time, v
示例8: _configure
def _configure(self):
"""
Set members based using inventory.
"""
Problem._configure(self)
self.faultId = self.inventory.faultId
self.formulation = self.inventory.formulation
self.checkpointTimer = self.inventory.checkpointTimer
return
示例9: verifyConfiguration
def verifyConfiguration(self):
"""
Verify compatibility of configuration.
"""
Problem.verifyConfiguration(self)
self.formulation.verifyConfiguration()
if not "numImpulses" in dir(self.source) or not "numComponents" in dir(self.source):
raise ValueError("Incompatible source for green's function impulses "
"with id '%d' and label '%s'." % \
(self.source.id(), self.source.label()))
return
示例10: checkpoint
def checkpoint(self):
"""
Save problem state for restart.
"""
Problem.checkpoint()
# Save state of this object
raise NotImplementedError, "TimeDependent::checkpoint() not implemented."
# Save state of children
self.formulation.checkpoint()
return
示例11: next_problem
def next_problem(self):
assert(self._v_message)
# FIXME
l = len(self._collection)
r = randint(0, l - 1)
f = open(join(self._directory, self._collection[r]))
self._problem = Problem(f.read())
transform = Transform()
self._to_board = transform.to_board
self._from_board = transform.from_board
self._fix_color = transform.fix_color
self._model = BoardModel()
if self.to_move() == Color.B:
self._v_message.set('Black to move')
else:
self._v_message.set('White to move')
self._model.setup_position(self._problem.get_setup())
self._board_widget.update_board()
示例12: main
def main():
"""
Main method, where the magic is done. This method creates and initializes the original state.
Then, applying the selected search algorithm, it calculates and it writes the correct solution.
:return:
"""
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--algorithm', required=True, type=str, default='DFS',
help='Set the search algorithm desired.')
parser.add_argument('-d', '--depth', default=9, type=int,
help='Set the maximum depth.')
parser.add_argument('-i', '--increase', default=1, type=int,
help='Set the increase in each iteration.')
parser.add_argument('-r', '--random', default=False, type=bool,
help='Initial state configuration is randomly generated.')
parser.add_argument('-f', '--file', default='../terrain.txt', type=str,
help='Route to load your initial state configuration.')
parser.add_argument('-o', '--output', default='successors.txt', type=str,
help='File to write the solution.')
args = parser.parse_args()
terrain = State(0, 0, 0, 0, 0, 0, 0) # Initial state. Initialized at 0.
operations = Problem(0, 0, args.file, terrain)
if args.random: # Generate the terrain randomly
operations.generate_terrain(terrain)
else:
if operations.file_format_correct():
operations.read_file(terrain)
else:
print("File {} has not a valid format.".format(args.file))
exit(1)
# Search algorithm to calculate the solution
sol = Search_Algorithm().search(operations, args.algorithm, args.depth, args.increase)
if sol is None:
print('No se ha encontrado una solución')
else:
operations.write_file(sol, args.output)
示例13:
import csv
from Problem import Problem
reader = csv.reader(open("A1Ratings.csv","rU"))
problem=Problem()
for row in reader:
problem.loadline(row)
average_ratings=dict(zip(problem.movienames,[('%.2f')%f for f in problem.meanRatings()]))
average_ratings=sorted(average_ratings.iteritems(),key=lambda d:d[1], reverse=True)
print average_ratings
most_ratings=dict(zip(problem.movienames,[f for f in problem.mostRatings()]))
most_ratings=sorted(most_ratings.iteritems(),key=lambda d:d[1],reverse=True)
print most_ratings
higher_ratings=dict(zip(problem.movienames,[('%.2f')%f for f in problem.rating4()]))
higher_ratings=sorted(higher_ratings.iteritems(),key=lambda d:d[1],reverse=True)
print higher_ratings
rel=dict(zip(problem.movienames[1:],[('%.2f')%f for f in problem.getRelevance()]))
rel=sorted(rel.iteritems(),key=lambda d:d[1],reverse=True)
print rel
示例14: test
def test(i, solver, choice, problem):
xtol = 1E-12
N = 2**i
mesh = UnitSquareMesh(N, N, 'crossed')
n_cells = mesh.num_cells()
n_obtuse_cells = len(obtuse_cells(mesh))
if problem == "point":
A = array([1.0, 0.0])
point_distance = Problem(MyPoint(A))
elif problem == "line":
A = array([0., 0.])
B = array([1., 0.])
point_distance = Problem(Segment(A, B))
if solver == "Q1":
# set up the linear problem
V = FunctionSpace(mesh, "CG", 1)
u = Function(V)
u_exact = Function(V)
fixed_dofs = []
point_distance.init(u, fixed_dofs)
point_distance.exact_solution(u_exact)
solver1 = Geometric(V)
start = clock()
n_sweeps = solver1.solve(u, fixed_dofs, xtol=xtol)
stop = clock() - start
l1 = assemble(abs(u - u_exact)*dx)
l2 = assemble((u - u_exact)**2*dx)
# set up the quadratic problem
W = FunctionSpace(mesh, "CG", 2)
v = interpolate(u, W)
v_exact = Function(W)
fixed_dofs = []
point_distance.init(v, fixed_dofs)
point_distance.exact_solution(v_exact)
solver2 = Quadratic(W, choice)
start = clock()
n_sweeps = solver2.solve(v, fixed_dofs, xtol=xtol, order_vector=v.vector())
stop = clock() - start
if solver == "Q2":
# set up the linear problem
V = FunctionSpace(mesh, "CG", 1)
u = Function(V)
u_exact = Function(V)
fixed_dofs = []
point_distance.init(u, fixed_dofs)
point_distance.exact_solution(u_exact)
solver1 = Geometric(V)
n_sweeps = solver1.solve(u, fixed_dofs, xtol=xtol)
# set up the quadratic problem
W = FunctionSpace(mesh, "CG", 2)
v = interpolate(u, W)
xxx = Function(W)
xxx.vector()[:] = v.vector().array()
v_exact = Function(W)
Fixed_dofs = []
point_distance.init(v, Fixed_dofs)
point_distance.exact_solution(v_exact)
#print fixed_dofs
#for i in range(W.dim()):
# print i, xxx.vector()[i], v.vector()[i],
# if i in fixed_dofs:
# print "<--"
# else:
# print
solver2 = Quad(W, choice)
start = clock()
n_sweeps = solver2.solve(v, Fixed_dofs, xtol=xtol)
stop = clock() - start
if solver == "Q3":
# set up the quadratic problem
W = FunctionSpace(mesh, "CG", 2)
v = Function(W)
v_exact = Function(W)
fixed_dofs = []
point_distance.init(v, fixed_dofs)
point_distance.exact_solution(v_exact)
solver2 = QuadraticRatic(W, choice)
start = clock()
n_sweeps = solver2.solve(v, fixed_dofs, xtol=xtol)
stop = clock() - start
if solver == "Q4":
# set up the linear problem
V = FunctionSpace(mesh, "CG", 1)
#.........这里部分代码省略.........
示例15: str
print "\n******** STATISTICS *********"
print "Final cost: "+ str(final_cost)
if __name__ == "__main__":
search_strategy = int(raw_input("Search algorithm? (BFS = 0, DFS = 1, DLS = 2, IDS = 3, UC = 4, AStar = 5)\n"))
if not search_strategy in range(6):
print("Invalid search algorithm. Exiting...")
sys.exit(0)
prune = raw_input("Execute prune? (Y/N)\n")
print "Looking for nodes " + str(sys.argv[6:])
initial_state = State(Node_Map(sys.argv[1]), sys.argv[6:])
boundary_coordinates = (sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
problem = Problem(State_Space(boundary_coordinates), initial_state)
problem.build_hash_table()
timestamp1 = datetime.datetime.now()
path = search(problem, search_strategy)
print "Time taken to accomplish the search: " + str(datetime.datetime.now() - timestamp1)
global number_of_generated_nodes
print "Number of generated nodes: " + str(number_of_generated_nodes)
sys.exit(0)