select...Case...EndSelect having problems with my code - bots

I'm trying to build an automatic answer for a simple math question where the number of total variables in the question depends on the position of the question mark, here are few examples:
What is 56 x 3 ?
What is 7 x 3 ?
What is 232 x 634 ?
I have created a code but I can't make it work, here is my code
#include <AutoItConstants.au3>
HotKeySet("{F4}", "ExitProg")
Func ExitProg()
Exit 0
EndFunc
MouseClick($MOUSE_CLICK_LEFT, 417, 659, 2, 1)
Send("^c")
Func valData()
$Chek = "What "
If ClipGet() == $Chek Then
Check()
Else
Do
MouseClick($MOUSE_CLICK_LEFT, 417, 659, 2, 3)
Send("^c")
Sleep(500)
Until ClipGet() == $Chek
EndIf
EndFunc
Func Check()
$Chek2 = "?"
Select
Case c1() == $Chek2
;two
cc1()
Case c2() == $Chek2
;three
cc2()
Case c3() == $Chek2
;four
cc3()
Case c4() == $Chek2
;five
cc4()
Case c5() == $Chek2
;six
cc5()
Case c6() == $Chek2
;seven
cc6()
Case c7() == $Chek2
;eight
cc7()
Case Else
Exit
EndSelect
EndFunc
Func c1()
MouseClick($MOUSE_CLICK_LEFT, 485, 643, 2, 1)
Send("^c")
EndFunc
Func c2()
MouseClick($MOUSE_CLICK_LEFT, 493, 644, 2, 1)
Send("^c")
EndFunc
Func c3()
MouseClick($MOUSE_CLICK_LEFT, 498, 645, 2, 1)
Send("^c")
EndFunc
Func c4()
MouseClick($MOUSE_CLICK_LEFT, 508, 647, 2, 1)
Send("^c")
EndFunc
Func c5()
MouseClick($MOUSE_CLICK_LEFT, 514, 645, 2, 1)
Send("^c")
EndFunc
Func c6()
MouseClick($MOUSE_CLICK_LEFT, 523, 645, 2, 1)
Send("^c")
EndFunc
Func c7()
MouseClick($MOUSE_CLICK_LEFT, 530, 645, 2, 1)
Send("^c")
EndFunc
Func cc1()
MouseClick($MOUSE_CLICK_LEFT, 453, 645, 2, 1)
Send("^c")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 1347, 197, 1, 1)
Send("^v")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 474, 645, 2, 1)
Send("^c")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 1347, 197, 1, 1)
Send("*")
Send("^v")
Send("{NUMPADENTER}")
EndFunc
Func cc2()
MouseClick($MOUSE_CLICK_LEFT, 453, 645, 2, 1)
Send("^c")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 1347, 197, 1, 1)
Send("^v")
SLeep(500)
MouseClick($MOUSE_CLICK_LEFT, 482, 645, 2, 1)
Send("^c")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 1347, 197, 1, 1)
Send("*")
Send("^v")
Send("{NUMPADENTER}")
EndFunc
Func cc3()
MouseClick($MOUSE_CLICK_LEFT, 453, 645, 2, 1)
Send("^c")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 1347, 197, 1, 1)
Send("^v")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 487, 645, 2, 1)
Send("^c")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 1347, 197, 1, 1)
Send("*")
Send("^v")
Send("{NUMPADENTER}")
EndFunc
Func cc4()
MouseClick($MOUSE_CLICK_LEFT, 453, 645, 2, 1)
Send("^c")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 1347, 197, 1, 1)
Send("^v")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 495, 645, 2, 1)
Send("^c")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 1347, 197, 1, 1)
Send("*")
Send("^v")
Send("{NUMPADENTER}")
EndFunc
Func cc5()
MouseClick($MOUSE_CLICK_LEFT, 453, 645, 2, 1)
Send("^c")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 1347, 197, 1, 1)
Send("^v")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 495, 645, 2, 1)
Send("^c")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 1347, 197, 1, 1)
Send("*")
Send("^v")
Send("{NUMPADENTER}")
EndFunc
Func cc6()
MouseClick($MOUSE_CLICK_LEFT, 453, 645, 2, 1)
Send("^c")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 1347, 197, 1, 1)
Send("^v")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 509, 645, 2, 1)
Send("^c")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 1347, 197, 1, 1)
Send("*")
Send("^v")
Send("{NUMPADENTER}")
EndFunc
Func cc7()
MouseClick($MOUSE_CLICK_LEFT, 453, 645, 2, 1)
Send("^c")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 1347, 197, 1, 1)
Send("^v")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 509, 645, 2, 1)
Send("^c")
Sleep(500)
MouseClick($MOUSE_CLICK_LEFT, 1347, 197, 1, 1)
Send("*")
Send("^v")
Send("{NUMPADENTER}")
EndFunc
valData()
MouseClick($MOUSE_CLICK_LEFT, 1349, 196, 1, 1) ;clicking the answer in calc
Send("^c")
Send("{DEL}")
MouseClick($MOUSE_CLICK_LEFT, 499, 706, 1, 1)
Send("^v")
Exit
Please help me! the output of this one is only searching for the question mark and after that is not doing anything.

This is basically the same answer as user4157124 already gave. I just broke it down to a one-liner (sacrifying the error handling; if the question doesn't match the given format, $x will be empty anyway).
ClipPut("What is 14 x 36 ?")
$x = Execute(StringRegExpReplace(ClipGet(), '^What is (\d*) x (\d*) \?$', "$1*$2"))
ConsoleWrite($x & #CRLF)
Also the REGEX Pattern [^\d]*(\d+)[^\d]+(\d+).* works (even more reliable in case there are stray spaces in or around the question)
(There is a more elegant way to get the question with GUICtrlRead(), but the implemention depends on how exactly the source program is built)
EDIT (just for troubleshooting):
As I can't see your screen, please run the following for troubleshooting:
MouseClick("Primary", 479, 802, 3, 10) ; slowed down to verify that the cursor goes to the right position
Send("^c")
$x = ClipGet()
ConsoleWrite('Whole question: "' & $x & '"' & #CRLF)
$x = StringRegExpReplace(ClipGet(), 'What is (\d*) x (\d*) \?$', "$1*$2")
ConsoleWrite('Math part: "' & $x & '"' & #CRLF)
$x = Execute($x)
ConsoleWrite('Result: "' & $x & '"' & #CRLF)
; MouseClick("Primary", 480, 844, 1, 1)
; Send($x)
Please report back the exact output from the console, so I can see, where things start to go wrong.

Related

ortools vrp does not give me any solution

I want solve a vehicle routing problem with ORTools, both distance and duration matrix will be used.
but the problem is when I change the matrix , it wouldn't give me any solutions anymore!
there are 2 groups of matrixes. with the commented matrixes there is solution, but with the other group, there is not. do you have any idea why this is happening:
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
def create_data_model():
"""Stores the data for the problem."""
data = {}
#data['distance_matrix']=[[0, 329, 146, 157, 318, 528, 457, 242, 491, 335, 471, 456, 391, 128, 461, 555, 460], [329, 0, 399, 384, 544, 493, 339, 378, 108, 243, 125, 394, 136, 561, 505, 315, 447], [146, 399, 0, 262, 471, 316, 297, 227, 548, 377, 267, 430, 383, 154, 234, 188, 400], [157, 384, 262, 0, 440, 271, 383, 525, 223, 367, 511, 354, 112, 539, 159, 152, 373], [318, 544, 471, 440, 0, 423, 112, 381, 346, 512, 161, 239, 581, 291, 284, 145, 143], [528, 493, 316, 271, 423, 0, 380, 196, 409, 212, 199, 277, 387, 515, 391, 261, 318], [457, 339, 297, 383, 112, 380, 0, 379, 298, 267, 482, 247, 462, 256, 296, 533, 200], [242, 378, 227, 525, 381, 196, 379, 0, 156, 230, 551, 555, 338, 372, 403, 358, 506], [491, 108, 548, 223, 346, 409, 298, 156, 0, 140, 532, 405, 531, 129, 220, 482, 222], [335, 243, 377, 367, 512, 212, 267, 230, 140, 0, 418, 440, 526, 255, 455, 296, 430], [471, 125, 267, 511, 161, 199, 482, 551, 532, 418, 0, 439, 285, 181, 254, 208, 304], [456, 394, 430, 354, 239, 277, 247, 555, 405, 440, 439, 0, 397, 229, 121, 385, 147], [391, 136, 383, 112, 581, 387, 462, 338, 531, 526, 285, 397, 0, 544, 205, 197, 226], [128, 561, 154, 539, 291, 515, 256, 372, 129, 255, 181, 229, 544, 0, 150, 204, 516], [461, 505, 234, 159, 284, 391, 296, 403, 220, 455, 254, 121, 205, 150, 0, 192, 544], [555, 315, 188, 152, 145, 261, 533, 358, 482, 296, 208, 385, 197, 204, 192, 0, 138], [460, 447, 400, 373, 143, 318, 200, 506, 222, 430, 304, 147, 226, 516, 544, 138, 0]]
data['distance_matrix']=[[0, 228, 299, 301, 235, 208, 405, 447, 144, 579], [228, 0, 343, 288, 357, 426, 530, 510, 122, 490], [299, 343, 0, 236, 228, 523, 274, 377, 397, 530], [301, 288, 236, 0, 594, 523, 289, 397, 154, 380], [235, 357, 228, 594, 0, 558, 370, 444, 173, 558], [208, 426, 523, 523, 558, 0, 219, 278, 504, 507], [405, 530, 274, 289, 370, 219, 0, 195, 283, 257], [447, 510, 377, 397, 444, 278, 195, 0, 407, 417], [144, 122, 397, 154, 173, 504, 283, 407, 0, 273], [579, 490, 530, 380, 558, 507, 257, 417, 273, 0]]
data['time_matrix']=[[0, 205, 519, 308, 428, 574, 399, 138, 573, 541], [205, 0, 447, 578, 296, 536, 135, 345, 198, 315], [519, 447, 0, 209, 438, 174, 231, 382, 104, 522], [308, 578, 209, 0, 235, 264, 492, 305, 134, 538], [428, 296, 438, 235, 0, 600, 177, 435, 204, 556], [574, 536, 174, 264, 600, 0, 476, 119, 183, 476], [399, 135, 231, 492, 177, 476, 0, 497, 208, 167], [138, 345, 382, 305, 435, 119, 497, 0, 344, 454], [573, 198, 104, 134, 204, 183, 208, 344, 0, 422], [541, 315, 522, 538, 556, 476, 167, 454, 422, 0]]
data['cost_matrix']=[[0, 160, 135, 433, 581, 453, 336, 329, 343, 237], [160, 0, 313, 596, 576, 458, 264, 380, 348, 354], [135, 313, 0, 591, 391, 211, 561, 236, 304, 414], [433, 596, 591, 0, 539, 253, 427, 300, 214, 118], [581, 576, 391, 539, 0, 243, 521, 499, 560, 255], [453, 458, 211, 253, 243, 0, 571, 216, 121, 314], [336, 264, 561, 427, 521, 571, 0, 425, 271, 165], [329, 380, 236, 300, 499, 216, 425, 0, 425, 549], [343, 348, 304, 214, 560, 121, 271, 425, 0, 176], [237, 354, 414, 118, 255, 314, 165, 549, 176, 0]]
data['num_vehicles'] = 4
data['depot'] = 0
return data
def print_solution(data, manager, routing, assignment):
"""Prints assignment on console."""
total_cost ,total_distance,total_time= 0,0,0
print('Objective: {}'.format(assignment.ObjectiveValue()))
distance_dimension=routing.GetDimensionOrDie('Distance')
time_dimension=routing.GetDimensionOrDie('Time')
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
route_cost = 0
route_distance = 0
route_time = 0
while not routing.IsEnd(index):
plan_output += ' {} -> '.format(manager.IndexToNode(index))
distance_var=distance_dimension.CumulVar(index)
time_var=time_dimension.CumulVar(index)
previous_index = index
index = assignment.Value(routing.NextVar(index))
route_cost += routing.GetArcCostForVehicle(previous_index, index, vehicle_id)
route_distance+=assignment.Value(distance_var)
route_time+=assignment.Value(time_var)
plan_output += '{}\n'.format(manager.IndexToNode(index))
plan_output += 'Cost of the route: {0}\nDistance of the route: {1}m\nTime of route: {2}\n'.format(
route_cost,
route_distance,
route_time)
print(plan_output)
total_cost += route_cost
total_time+=route_time
total_distance+=route_distance
print('Total Cost of all routes: {}\nTotal Distance of all routes: {}\nTotal Time of all routes: {}\n'.format(total_cost,total_distance,total_time))
def get_routes(manager, routing, solution, num_routes):
"""Get vehicle routes from a solution and store them in an array."""
# Get vehicle routes and store them in a two dimensional array whose
# i,j entry is the jth location visited by vehicle i along its route.
routes = []
for route_nbr in range(num_routes):
index = routing.Start(route_nbr)
route = [manager.IndexToNode(index)]
while not routing.IsEnd(index):
index = solution.Value(routing.NextVar(index))
route.append(manager.IndexToNode(index))
routes.append(route)
return routes
def main():
# Instantiate the data problem.
data = create_data_model()
# Create the routing index manager.
manager = pywrapcp.RoutingIndexManager(len(data['cost_matrix']), data['num_vehicles'], data['depot'])
# Create Routing Model.
routing = pywrapcp.RoutingModel(manager)
# Create and register a transit callback.
def cost_callback(from_index, to_index):
"""Returns the distance between the two nodes."""
# Convert from routing variable Index to distance matrix NodeIndex.
from_node = manager.IndexToNode(from_index)
to_node = manager.IndexToNode(to_index)
return data['cost_matrix'][from_node][to_node]
transit_callback_index = routing.RegisterTransitCallback(cost_callback)
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
# Add Cost constraint.
routing.AddDimension(
transit_callback_index,
0, # no slack
3000, # vehicle maximum travel distance
False, # start cumul to zero
'Cost')
cost_dimension = routing.GetDimensionOrDie('Cost')
cost_dimension.SetGlobalSpanCostCoefficient(1000)
#Add Distance constraint.
def distance_callback(from_index,to_index):
from_node = manager.IndexToNode(from_index)
to_node = manager.IndexToNode(to_index)
return data['distance_matrix'][from_node][to_node]
distance_callback_index=routing.RegisterTransitCallback(distance_callback)
routing.AddDimension(
distance_callback_index,
0,
3000,
False,
'Distance')
distance_dimension=routing.GetDimensionOrDie('Distance')
#Add Time constraint.
def time_callback(from_index,to_index):
from_node = manager.IndexToNode(from_index)
to_node = manager.IndexToNode(to_index)
return data['time_matrix'][from_node][to_node]
time_callback_index=routing.RegisterTransitCallback(time_callback)
routing.AddDimension(
time_callback_index,
0,
300,
False,
'Time')
time_dimension=routing.GetDimensionOrDie('Time')
# Setting first solution heuristic.
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.first_solution_strategy = (routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
search_parameters.solution_limit = 100
search_parameters.time_limit.seconds = 3
# Solve the problem.
assignment = routing.SolveWithParameters(search_parameters)
# Print solution on console.
if assignment:
print_solution(data, manager, routing, assignment)
routes = get_routes(manager, routing, assignment, data['num_vehicles'])
# Display the routes.
for i, route in enumerate(routes):
print('Route', i, route)
if __name__ == '__main__':
main()
None could mean that it did not find a solution. Most likely your limits are too low
by increasing the limits, it works fine.
but for better understanding, it's better to check solver status. time limit errors mostly refer to the low limitations.
in this example we have many value more than 300 in time matrix but the maximum time for every vehicle is 300.so there is not a feasible solution for this problem.

Using Capacity Constraint with Pickup and Delivery

Being new to OR-Tools libraries I am unable to modify the existing code for my requirements. I have a requirement to add capacity constraint with pickup and delivery i.e a person will deliver items items as mentioned in pickup and delivery algo, but there will be a constraint how much items he can accommodate with him. I tried using code for capacity constraint with pickup and delivery code, but didn't get success. Here is a sample code:
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
def create_data_model():
"""Stores the data for the problem."""
data = {}
data['distance_matrix'] = [
[
0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354,
468, 776, 662
],
[
548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674,
1016, 868, 1210
],
[
776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164,
1130, 788, 1552, 754
],
[
696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822,
1164, 560, 1358
],
[
582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708,
1050, 674, 1244
],
[
274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628,
514, 1050, 708
],
[
502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856,
514, 1278, 480
],
[
194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320,
662, 742, 856
],
[
308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662,
320, 1084, 514
],
[
194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388,
274, 810, 468
],
[
536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764,
730, 388, 1152, 354
],
[
502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114,
308, 650, 274, 844
],
[
388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194,
536, 388, 730
],
[
354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0,
342, 422, 536
],
[
468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536,
342, 0, 764, 194
],
[
776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274,
388, 422, 764, 0, 798
],
[
662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730,
536, 194, 798, 0
],
]
data['pickups_deliveries'] = [
[1, 6],
[2, 10],
[4, 3],
[5, 9],
[7, 8],
[15, 11],
[13, 12],
[16, 14],
]
data['num_vehicles'] = 4
data['depot'] = 0
data['vehicle_capacities'] = [15,15,15,15]
data['demands'] = [0, 1, 1, 3, 6, 3, 6, 8, 8, 1, 2, 1, 2, 6, 6, 8, 8]
return data
def print_solution(data, manager, routing, assignment):
"""Prints assignment on console."""
total_distance = 0
total_load = 0
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
route_distance = 0
route_load = 0
while not routing.IsEnd(index):
node_index = manager.IndexToNode(index)
route_load += data['demands'][node_index]
plan_output += ' {0} Load({1}) -> '.format(node_index, route_load)
previous_index = index
index = assignment.Value(routing.NextVar(index))
route_distance += routing.GetArcCostForVehicle(
previous_index, index, vehicle_id)
plan_output += ' {0} Load({1})\n'.format(manager.IndexToNode(index),
route_load)
plan_output += 'Distance of the route: {}m\n'.format(route_distance)
plan_output += 'Load of the route: {}\n'.format(route_load)
print(plan_output)
total_distance += route_distance
total_load += route_load
print('Total distance of all routes: {}m'.format(total_distance))
print('Total load of all routes: {}'.format(total_load))
def main():
"""Entry point of the program."""
# Instantiate the data problem.
data = create_data_model()
# Create the routing index manager.
manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
data['num_vehicles'], data['depot'])
# Create Routing Model.
routing = pywrapcp.RoutingModel(manager)
# Define cost of each arc.
def distance_callback(from_index, to_index):
"""Returns the manhattan distance between the two nodes."""
# Convert from routing variable Index to distance matrix NodeIndex.
from_node = manager.IndexToNode(from_index)
to_node = manager.IndexToNode(to_index)
return data['distance_matrix'][from_node][to_node]
transit_callback_index = routing.RegisterTransitCallback(distance_callback)
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
# Add Capacity constraint.
def demand_callback(from_index):
"""Returns the demand of the node."""
# Convert from routing variable Index to demands NodeIndex.
from_node = manager.IndexToNode(from_index)
return data['demands'][from_node]
demand_callback_index = routing.RegisterUnaryTransitCallback(
demand_callback)
routing.AddDimensionWithVehicleCapacity(
demand_callback_index,
0, # null capacity slack
data['vehicle_capacities'], # vehicle maximum capacities
True, # start cumul to zero
'Capacity')
# Add Distance constraint.
dimension_name = 'Distance'
routing.AddDimension(
transit_callback_index,
0, # no slack
3000, # vehicle maximum travel distance
True, # start cumul to zero
dimension_name)
distance_dimension = routing.GetDimensionOrDie(dimension_name)
distance_dimension.SetGlobalSpanCostCoefficient(100)
# Define Transportation Requests.
for request in data['pickups_deliveries']:
pickup_index = manager.NodeToIndex(request[0])
delivery_index = manager.NodeToIndex(request[1])
routing.AddPickupAndDelivery (pickup_index, delivery_index)
routing.solver().Add(routing.VehicleVar(pickup_index) == routing.VehicleVar(delivery_index))
routing.solver().Add(distance_dimension.CumulVar(pickup_index) <= distance_dimension.CumulVar(delivery_index))
# Setting first solution heuristic.
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.first_solution_strategy = (
routing_enums_pb2.FirstSolutionStrategy.PARALLEL_CHEAPEST_INSERTION)
# Solve the problem.
assignment = routing.SolveWithParameters(search_parameters)
print(assignment)
# Print solution on console.
if assignment:
print("1")
print_solution(data, manager, routing, assignment)
if __name__ == '__main__':
main()
There is no solution because the total demand is greater than the total vehicle capacity. The demand is 70 the capacity is 60.
For anyone having trouble getting a solution to this problem, I'll just leave it here instead of creating a new question and writing the solution myself. There might be something in this answer you might've missed.
Lets first understand how capacity constraint works in plain English
What is the demands array?
It is a unit of quantity which the vehicle will have to carry upon going to that location.
What is the vehicle_capacities array?
It is the maximum quantity in units which a particular vehicle can carry.
Now moving on to pickup & delivery
In this case however, our 'vehicles' don't carry an additional weight/quantity (in units) upon reaching the delivery location. Instead, it will release the quantity (in units) which it carried from the pickup location.
So, our demands array will change accordingly.
Considering this is our pickup_deliveries array
data['pickups_deliveries'] = [
[1, 6],
[2, 10],
[4, 3],
[5, 9],
[7, 8],
[15, 11],
[13, 12],
[16, 14],
]
Our demands array should look something like:
data['demands'] = [0, 1, 2, -6, 6, 10, -1, 8, -8, -10, -2, -9, -4, 4, -13, 9, 13]
Where each delivery location will release that same amount of quantity which we picked up from the pickup location.
Side Note (Not related to question but might help you)
When using pickup and delivery with capacity constraint or combining it with any other constraint like time window or even multiple start end, it makes the job a whole lot easier if we first specify depots and then pickup1 then drop1, then pickup2 then drop2, etc.
Eg:
data['num_vehicles'] = 4
# put all vehicles at the start of your 'addresses' array (i.e. they will be the first rows in the distance / time matrices)
data['starts'] = [0, 1, 2, 3]
data['ends'] = [0, 1, 2, 3]
# then simply, from the next 2 indices start defining the pickups and drops
# i.e. 4 is pickup1 5 is drop1, 6 is pickup2 7 is drop2, etc. (this also makes it easier for dynamic input)
# i.e. if num_vehicles is 3 -> next 2 -> 3,4 (since index starts from 0)
data['pickups_deliveries'] = [
[4, 5],
[6, 7],
[8, 9],
[10, 11],
[12, 13],
[14, 15]
]
# then 0 to num_vehicle values will be 0 (since depots won't have weight in normal condition unless you have something...)
# and the rest of the numbers will be pairs of pickups and drop weights i.e. what is picked up is dropped so (num,-num) for 1 pickup-drop pair etc.
data['demands'] = [0, 0, 0, 0, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1]
data['vehicle_capacities'] = [1, 1, 1, 1] # this depends on your problem.
# here I have considered that a vehicle can only carry one thing at a time

'NoneType' object has no attribute 'update when saving model in keras2

background:
keras2+tensorflow1.9.0+python3.5
I have a model build like this:
def Build_SiameseNet():
input_shape = (7, 128, 128, 1)
model = Sequential()
model.add(Conv3D(8, (2, 7, 7), input_shape=input_shape, name='Conv_1', padding='same', kernel_initializer=W_init,
bias_initializer=b_init, strides=(1, 1, 1))) # 9 13 17
model.add(BatchNormalization(axis=1))
model.add(Activation('relu', name='Act_1'))
# model.add(MaxPooling3D(pool_size=(1,3,3),strides=(1,2,2)))
model.add(Conv3D(32, (2, 5, 5), name='Conv_2', strides=(1, 1, 1), kernel_initializer=W_init,
bias_initializer=b_init))
model.add(BatchNormalization(axis=1))
model.add(Activation('relu', name='Act_2'))
model.add(AveragePooling3D(pool_size=(1, 2, 2)))
model.add(Conv3D(128, (2, 3, 3), name='Conv_3', strides=(1, 1, 1), kernel_initializer=W_init,
bias_initializer=b_init))
model.add(BatchNormalization(axis=1))
model.add(Activation('relu', name='Act_3'))
model.add(AveragePooling3D(pool_size=(1, 2, 2)))
model.add(Conv3D(256, (2, 3, 3), name='Conv_4', strides=(1, 1, 1), kernel_initializer=W_init,
bias_initializer=b_init))
model.add(BatchNormalization(axis=1))
model.add(Activation('relu', name='Act_4'))
model.add(AveragePooling3D(pool_size=(1, 2, 2)))
model.add(Conv3D(512, (2, 3, 3), name='Conv_5', strides=(1, 1, 1), kernel_initializer=W_init,
bias_initializer=b_init))
model.add(BatchNormalization(axis=1))
model.add(Activation('relu', name='Act_5'))
# model.add(LocallyConnected2D())
model.add(AveragePooling3D(pool_size=(3, 4, 4)))
model.add(Flatten(name='Flatten'))
# model.add(Dense(24,name='FC_1',kernel_regularizer=regularizers.l1_l2(0.001,0.01)))
model.add(Dropout(0.5, name='Dropout'))
model.add(Activation('relu', name='Act_6'))
# model.add(Dense(1000, activation='relu'))
model.summary()
# Copy the net
left_input = Input(input_shape)
right_input = Input(input_shape)
encoded_l = model(left_input)
encoded_r = model(right_input)
# merge outputs of two net
L1_layer = Lambda(lambda tensors: K.abs(tensors[0] - tensors[1]))
L1_distance = L1_layer([encoded_l, encoded_r])
prediction = Dense(1, activation='sigmoid')(L1_distance)
siamese_net = Model(inputs=[left_input, right_input], outputs=prediction)
optimizer = optimizers.Adam(lr=3e-2, decay=1e-4)
siamese_net.compile(loss="binary_crossentropy", optimizer=optimizer, metrics=['accuracy'])
return siamese_net
I want to save the model after fit by fit_generator, and I look up the Documentation.
There is a Q&A named "How can I save a Keras model?" in FAQ of Documentation .it say model.save() will meet my requirement.And than I try as this:
his = model.fit_generator(self.generate(batch_size)...)
model.save('asd0314.h5')
err informations:
Traceback (most recent call last):
File "/usr/local/pycharm-community-2017.2.4/helpers/pydev/pydevd.py", line 1599, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "/usr/local/pycharm-community-2017.2.4/helpers/pydev/pydevd.py", line 1026, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/usr/local/pycharm-community-2017.2.4/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/mashuyang/PycharmProjects/SiameseNet/copy0307LightSiamese0.98/SiameseNet_lighNet.py", line 65, in <module>
loss_line, acc_line, model_trained = loader.train(model, batch_size, epoch)
File "/home/mashuyang/PycharmProjects/SiameseNet/copy0307LightSiamese0.98/Siamese_Loader.py", line 148, in train
model.save('asd0314.h5')
File "/usr/local/lib/python3.5/dist-packages/keras/engine/topology.py", line 2580, in save
save_model(self, filepath, overwrite, include_optimizer)
File "/usr/local/lib/python3.5/dist-packages/keras/models.py", line 111, in save_model
'config': model.get_config()
File "/usr/local/lib/python3.5/dist-packages/keras/engine/topology.py", line 2421, in get_config
return copy.deepcopy(config)
File "/usr/lib/python3.5/copy.py", line 155, in deepcopy
y = copier(x, memo)
File "/usr/lib/python3.5/copy.py", line 243, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python3.5/copy.py", line 155, in deepcopy
y = copier(x, memo)
File "/usr/lib/python3.5/copy.py", line 218, in _deepcopy_list
y.append(deepcopy(a, memo))
File "/usr/lib/python3.5/copy.py", line 155, in deepcopy
y = copier(x, memo)
File "/usr/lib/python3.5/copy.py", line 243, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python3.5/copy.py", line 155, in deepcopy
y = copier(x, memo)
File "/usr/lib/python3.5/copy.py", line 243, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python3.5/copy.py", line 155, in deepcopy
y = copier(x, memo)
File "/usr/lib/python3.5/copy.py", line 223, in _deepcopy_tuple
y = [deepcopy(a, memo) for a in x]
File "/usr/lib/python3.5/copy.py", line 223, in <listcomp>
y = [deepcopy(a, memo) for a in x]
File "/usr/lib/python3.5/copy.py", line 155, in deepcopy
y = copier(x, memo)
File "/usr/lib/python3.5/copy.py", line 223, in _deepcopy_tuple
y = [deepcopy(a, memo) for a in x]
File "/usr/lib/python3.5/copy.py", line 223, in <listcomp>
y = [deepcopy(a, memo) for a in x]
File "/usr/lib/python3.5/copy.py", line 182, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python3.5/copy.py", line 297, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python3.5/copy.py", line 155, in deepcopy
y = copier(x, memo)
File "/usr/lib/python3.5/copy.py", line 243, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python3.5/copy.py", line 182, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python3.5/copy.py", line 297, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python3.5/copy.py", line 155, in deepcopy
y = copier(x, memo)
File "/usr/lib/python3.5/copy.py", line 243, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python3.5/copy.py", line 182, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python3.5/copy.py", line 306, in _reconstruct
y.__dict__.update(state)
AttributeError: 'NoneType' object has no attribute 'update'
who can help me please~ i just want to save the model. I had tried in using his.history.save_model and save_modle(his.history.model) ,both of that are not work.

Primality testing: How to make sure not to test numbers which are multiples of already tested numbers?

Here is my code:
from math import sqrt
def isPrime(value):
a = []
for i in range(1, int(sqrt(value)) + 1):
if value <= 3:
return value
if value % 2 == 0:
break
if value % i == 0:
a.append(i)
i += 1
continue
elif value % i != 0:
a = a
continue
if len(a) == 1:
return value
else:
pass
I want to be able to use this for testing big numbers too, but as fast as possible.
Primality testing with the Rabin-Miller algorithm
Used Wikipedia: Primality testing
import math
def initial_data(number):
count = 0
goree = number - 1
floor = number // 2
while goree % 2 == 0:
goree //= 2
count += 1
results = [floor, count]
return results
def test_values(num):
test_vals = []
if num < 2047:
test_vals = [2]
elif num < 1373653:
test_vals = [2, 3]
elif num < 9080191:
test_vals = [31, 73]
elif num < 25326001:
test_vals = [2, 3, 5]
elif num < 3215031751:
test_vals = [2, 3, 5, 7]
elif num < 4759123141:
test_vals = [2, 7, 61]
elif num < 1122004669633:
test_vals = [2, 13, 23, 1662803]
elif num < 2152302898747:
test_vals = [2, 3, 5, 7, 11]
elif num < 3474749660383:
test_vals = [2, 3, 5, 7, 11, 13]
elif num < 341550071728321:
test_vals = [2, 3, 5, 7, 11, 13, 17]
elif num < 3825123056546413051:
test_vals = [2, 3, 5, 7, 11, 13, 17, 19, 23]
elif num < 2**64:
test_vals = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
elif num < 318665857834031151167461:
test_vals = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
elif num < 3317044064679887385961981:
test_vals = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
return test_vals
def rabin_miller(num):
base_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,
199, 211, 223, 227, 229, 233, 239,241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449,
457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521,523, 541, 547, 557, 563, 569, 571, 577, 587,
593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661,673, 677, 683, 691, 701, 709,
719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853,
857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991,
997]
if num <= 1:
return False
elif num in base_primes:
return True
else:
for value in base_primes: # making sure value does not have prime factors in
if num not in base_primes and num % value == 0:
return False
data = initial_data(num)
s = data[1]
d = data[0]
res = False
testing_values = []
if num < 3317044064679887385961981:
testing_values = test_values(num) # Get values of a to be used from test_values
else:
testing_values = [2, min(num - 1, int(2 * (math.log1p(num - 1))**2))]
for a in testing_values:
for r in range(1, s + 1):
power = (2**r)*d
if pow(a, d, num) != 1 and pow(a, power, num) != 1:
res = False
elif pow(a, d, num) == 1 or pow(a, power, num) == 1:
return True
else:
continue
if res:
return False
else:
return False
print(rabin_miller(5547337572376305111955330958342147474062293202868155909393))
This will work very fast for values greater than 64-bits, any hint and comment aimed at improving this code both in accuracy and efficiency (time efficiency) are welcomed.
The base_primes list was obtained using and improved version of the
code in this question: Primality testing: How to make sure not to
test numbers which are multiples of already tested numbers?
Here is an implementation of the randomized test:
import random
#The following function finds s and d in
#n-1 = 2^s*d with d odd
def findSD(n):
s = 0
d = n-1
while d % 2 == 0:
s = s + 1
d = d//2
return s,d
def checkBase(a,n):
s,d = findSD(n)
x = pow(a,d,n)
if x == 1 or x == n-1:
return "probable prime"
else:
for i in range(s-1):
x = pow(x,2,n)
if x == 1:
return "composite"
elif x == n-1:
return "probable prime"
#if you get to this stage, -1 not reached despite s-1
#squarings -- so must be composite
return "composite"
def MSR(n,k):
#tests is an odd number is prime
for i in range(k):
a = random.randint(2,n-2)
if checkBase(a,n) == "composite":
return "composite"
#if you get here n has survived k potential witnesses, so
return "probable prime"
def prime(n):
smallPrimes = [2,3,5,7,11,13,17,19]
for p in smallPrimes:
if n == p:
return True
elif n % p == 0:
return False
if MSR(n,20) == "composite":
return False
else:
return True
def prime(n):
smallPrimes = [2,3,5,7,11,13,17,19]
for p in smallPrimes:
if n == p:
return True
elif n % p == 0:
return False
if MSR(n,20) == "composite":
return False
else:
return True
You can use it to fish for primes:
def findPrime(maxN):
while True:
n = random.randint(3,maxN)
if prime(n):
return n
Typical run:
>>> findPrime(2**512)
3416363469318261052788311737860856549293100664891633139661459849835325883152102949928216754211470387640525391249585700324869443369023574938398397274187333

Palindrome in Python not working

I am trying to make a simple program that displays the palindrome numbers between 2 numbers in Python3 but it doesn't seem to work. I get only 4 output which are 1,2,4 and 8. What about the other numbers like 11, 22, 33, ..., 111, 121,131,..., 191, 222, etc?
Here is my code. I can't figure out why it's not working.
a = 0
b = 500
a += 1
for i in range(a,b):
if(str(a) == str(a)[::-1]):
print(a)
a += a
Maybe
for i in range (0, 500):
if str(i) == str(i)[::-1]:
print(i)
>>> palindromes = [a for a in range(500) if str(a) == str(a)[::-1]]
>>> palindromes
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131,
141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303,
313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474,
484, 494]
That shows you the principle. If you want to do it in a function, you can use yield instead of constructing the whole list in memory (much more efficient):
>>> def palindromes(a, b):
... """Return palindromes in closed interval from a to b"""
... for i in range(a, b):
... if str(i) == str(i)[::-1]:
... yield i
...
>>> list(palindromes(0, 500))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494]

Resources