Optimization Algorithms (MEAP V02) Alaa Khamis download
Optimization Algorithms (MEAP V02) Alaa Khamis download
install download
https://ebookmeta.com/product/optimization-algorithms-
meap-v02-alaa-khamis/
https://ebookmeta.com/product/smart-mobility-exploring-
foundational-technologies-and-wider-impacts-1st-edition-alaa-
khamis/
https://ebookmeta.com/product/algorithms-for-convex-
optimization-1st-edition-vishnoi/
https://ebookmeta.com/product/nature-inspired-optimization-
algorithms-with-java-a-look-at-optimization-techniques-shashank-
jain/
https://ebookmeta.com/product/the-new-spaghetti-cookbook-
delicious-spaghetti-recipes-for-pasta-lovers-2nd-edition-
booksumo-press/
Understanding the New Proxy Wars 1st Edition Peter
Bergen
https://ebookmeta.com/product/understanding-the-new-proxy-
wars-1st-edition-peter-bergen/
https://ebookmeta.com/product/battle-world-a-litrpg-series-1st-
edition-cassius-lange-castor-2/
https://ebookmeta.com/product/cfa-2024-level-iii-schwesernotes-
book-5-1st-edition-kaplan-schweser/
https://ebookmeta.com/product/quick-compendium-of-clinical-
pathology-4th-edition-daniel-d-mais/
https://ebookmeta.com/product/the-art-of-reinforcement-learning-
fundamentals-mathematics-and-implementations-with-python-1st-
edition-michael-hu-2/
Introduction to Nursing Research: Incorporating
Evidence-Based Practice 6th Edition Carol Boswell
https://ebookmeta.com/product/introduction-to-nursing-research-
incorporating-evidence-based-practice-6th-edition-carol-boswell/
MEAP Edition
Manning Early Access Program
Optimization Algorithms
AI techniques for design, planning, and control problems
Version 2
Optimization problems are ubiquitous in different aspects of life. This book is written for
practitioners interested in solving ill-structured search and optimization problems using modern
derivative-free algorithms. This book will get you up to speed with the core concepts of search
and optimization and endow you with the ability to deal with practical design, planning and
control problems.
Without assuming any prior knowledge of search and optimization and with an intermediate
knowledge of data structures and Python, this book has been written to take most anyone from
never solving search and optimization problems to being a well-rounded search and optimization
practitioner able to select, implement and adapt the right solver for the right problem.
This book grew out of several courses related to search and optimization taught by me at
different universities and training centers in industry. My 25 years working as an AI and Robotics
professor in the academia and as a technical leader in industry have given me a wealth of
experiences to share with you through this book.
By the end of the book, you should understand:
• How to deal with discrete and continuous ill-structured optimization problems using
deterministic and stochastic derivative-free search and optimization techniques
• How to apply deterministic graph search algorithms to solve graph problems
• How to apply nature-inspired algorithms to find optimal or near-optimal solutions for
practical design, planning and control problems
• How to use machine learning methods to solve search and optimization problems
• How to solve the search dilemma by achieving trade-off between search space exploration
and exploitation using algorithm parameter adaptation
• How to use state-of-the-art Python libraries related to search and optimization
I do believe that learning is the common ground between the author and the reader. I hope
that what you’ll get access to will be of immediate use to you. I also look forward to learning
from your valuable feedback to develop the best book possible. Please let me know your
thoughts in the liveBook Discussion forum on what’s been written so far and what you’d like to
see in the rest of the book.
Thanks again for your interest and for purchasing the MEAP!
in an unknown external environment. Honeybee colonies focus their foraging efforts on only
the most profitable patches and build their honeycombs with a shape that economizes labor
and wax. Fish swimming in schools or cruising in the same direction minimize total energy
usage by exploiting pressure fields created by the other fish. At the same time, migratory
birds utilize separation, alignment, and cohesion-based optimization to avoid mid-air
collisions and increase flight endurance. Non-biological phenomena also tend towards
efficiency. For example, light traveling between two different media will refract along an
angle that minimizes the travel time.
As technology has developed, computer-based optimization is now an inescapable reality
of the digital era. Transportation network companies (TNCs) like Uber, Lyft, and DiDi route
drivers efficiently during passenger trips and direct drivers to ride-hailing hotspots during idle
periods to minimize passenger wait time. As urbanization intensifies worldwide, local
emergency services depend on efficient dispatching and routing platforms to select and route
the appropriate vehicles, equipment, and personnel to respond to incidents across
increasingly complex metropolitan road networks. Airliners need to solve several optimization
problems such as flight planning, fleet assignment, crew scheduling, aircraft routing and
aircraft maintenance planning. Healthcare systems also handle optimization problems such
as hospital resource planning, emergency procedure management, patient admission
scheduling, surgery scheduling and pandemic containment. Industry 4.0, a major customer
of optimization technology, deals with complex optimization problems such as smart
scheduling/rescheduling, assembly line balancing, supply-chain optimization, and operational
efficiency. Smart cities deal with large-scale optimization problems such as stationary asset
optimal assignments, mobile asset deployment, energy optimization, water control, pollution
reduction, waste management and bushfire containment. These examples show how
ubiquitous and important optimization is as a way to maximize operational efficiency in
different domains.
scale of the problem is so tiny that implementing these kinds of changes may not lead to
noticeable impact.
In larger scale problems such as fleet assignment and dispatching, multi-criteria
stochastic vehicle routing, resource allocation, crew scheduling, applying search and
optimization techniques to a problem must be a qualified decision. Some firms or industries
may not benefit from excessive process changes due to a lack of expertise or resources to
implement those changes. There may also be the concern of a potential lack of follow-
through from stakeholders. Implementing the changes could also cost more than the savings
obtained through the optimization process. Later in this book, we will see how these costs
can be accounted for when developing search and optimization algorithms.
Without assuming any prior knowledge of search and optimization and with an
intermediate knowledge of data structures and Python, this book has been written to take
most anyone from never solving search and optimization problems to being a well-rounded
search and optimization practitioner able to select, implement and adapt the right solver for
the right problem. For managers or professionals involved in the high-level technological
decisions at their workplace, these skills can be critical in understanding software-based
approaches, their opportunities, and limitations when discussing process improvement. In
contrast, IT professionals will find these skills more directly applicable when considering
options for developing or selecting new software suites and technologies for in-house use.
The following subsection describes the methodology we will follow throughout this book.
Figure 1.1 Book methodology. Each algorithm will be introduced following a structure that goes from
explanation to application.
Throughout this book, several classical and real-world optimization problems are
considered to show how to use search and optimization algorithms discussed in the book.
Figure 1.2 shows examples of these optimization/search problems.
Real-world design problems or strategic functions deal with situations when time is not as
important as the quality of the solution and users are willing to wait (sometimes even a few
days) to get optimal solutions. Planning problems or tactical functions need to be solved in a
time span between a few seconds to a few minutes. While control problems or operational
functions need to be solved repetitively and quickly, in a time span between few milliseconds
to a few seconds. In order to find a solution during such a short period of time, optimality is
usually traded in for speed gains. In the next chapter, more thorough discussion of these
problem types is provided.
It is highly recommended that you first perform the necessary hand iterations for the
examples following each algorithm and then try to recreate the Python implementations
yourself. Feel free to play around with the parameters and problem scale in the code; one of
the advantages of running optimization algorithms through software is the ability to tune for
optimality.
Figure 1.3 Feasible/acceptable solutions fall within the constraints of the problem. Search spaces may display
a combination of global, strong local, and weak local minima.
These optimum seeking methods, also known as optimization techniques, are generally
studied as a part of operations research (OR). OR, also referred to as decision or
management science, is a field that originated at the beginning of World War II due to the
urgent need for assignment of scarce resources in military operations. It is a branch of
mathematics concerned with applying advanced scientific analytical methods to decision-
making and management problems to find the best or optimal solutions.
Optimization problems can generally be stated as follows:
Find X which optimizes ƒ
Subject to a possible set of equality and inequality constraints:
gi(X)= 0, i=1,2,…,m
hj(X)<=0, j=1,2,…,p
Equation 1.1
where
• X=(x1, x2,…,xn)T is the vector representing the decision variables
• ƒ(X)=(ƒ1(X), ƒ2(X),…, ƒM(X)) is the vector of objectives to be optimized
• gi(X) is a set of equality constraints
• hj(X) is a set of inequality constraints
The following subsections describe three main components of optimization problems:
decision variables, objective functions, and constraints.
Q=5,000-20x
Equation 1.2
Where x is the ticket price and Q is the expected number of tickets to be sold. Thus, the
company expects the following scenarios:
• if the company charges nothing or x=0, the company will give away 5,000 tickets for
free;
• If the ticket price is x=$250, the company will get no attendees as the expected
number of tickets to be sold will be zero and
• If the ticket price x<$250, the company will sell some number of tickets
0<=Q<=5,000.
The profit f(x) the event organizer can expect to earn can be calculated according to the
following:
Profit=Revenue-Costs
Equation 1.3
where Revenue=Qx and costs=a+Qb. Altogether, the profit (or objective) function looks
like this:
Equation 1.4
In this problem, there is a single decision variable x, which is the price of the ticket. The
predefined parameters include fixed costs a and variable costs b. The ticket price lower
bound xLB and upper bound xUB are considered boundary constraints. Solving this
optimization problem focuses on finding the best value of x that maximizes the profit ƒ(x).
Example: In the earlier ticket pricing problem, assume that: a=50,000, b=60, xLB =0 and
xUB=250. Using these values, we have a profit function: ƒ(x)=-20x2+6,200x-350,000.
Following derivative-based approach, we can simply derive the function to find its maximum:
dƒ/dx=-40x+6,200=0 or 40x=6,200. Thus, the optimal number of tickets to sell is 155,
which yields a net profit of $130,500 as shown in Figure 1.5.
Figure 1.5 Ticket pricing problem. The optimal pricing which maximizes profits is $155 per ticket.
Figure 1.6 Electric vehicle design problem for maximizing EPA range and minimizing acceleration time.
256 possible solutions (44) and two optimal solutions. Neither of the two optimal solutions is
inherently or objectively better than the other. The only requirement of the problem is to
satisfy the given constraints.
1.3.3 Constraints
Constrained optimization problems have a set of equality and/or inequality constraints gi(X),
lj(X) that restrict the values assigned to the unknowns. In addition, most problems have a
set of boundary constraints, which define the domain of values for each variable.
Furthermore, constraints can be hard (must be satisfied) or soft (desirable to satisfy).
Consider the following examples from a school timetabling problem:
• Not having multiple lectures in the same room at the same time is a hard constraint
• Not having a teacher give multiple lectures at the same time is also a hard
constraint
• Guaranteeing a minimum of three teaching days for every teacher may be a soft
constraint
• Locating back-to-back lectures in nearby rooms may be a soft constraint
• Avoiding scheduling very early or very late lectures may also be a soft constraint
As another example of hard and soft constraints, navigation apps such as Google Maps,
Apple Maps, Waze, or HERE WeGo may allow users to set preferences for routing.
• Avoiding ferries, toll roads, and highways would be hard constraints
• Avoiding busy intersections, highways during rush hour, or school zones during drop-
off and pick-up times might be soft constraints
Soft constraints can be modeled by incorporating a reward/penalty function as part of the
objective function. The function rewards solutions that satisfy the soft constraints and
penalize those that do not.
Example: Assume that there are 10 parcels to be loaded in the cargo bike from Figure
1.7. Each parcel has its own weight, profit, and efficiency value (profit per kg). The goal is to
select the parcels to be loaded in such a way that the utility function ƒ1 is maximized and the
weight function ƒ2 is minimized. This is a classic example of a combinatorial problem.
Equation 1.5
𝑛𝑛 𝑛𝑛
Equation 1.6
where ωi is the weight of package i and C is the maximum capacity of the bike. A penalty of
50 is added if and only if the total weight of the added parcels exceeds the maximum
capacity.
Figure 1.7 The cargo bike loading problem is an example of a problem with a soft constraint. While the weight
of the packages can exceed the bike’s capacity, a penalty will be applied when the bike is overweight.
Soft constraints can also be used to make the search algorithm more adaptive. For
example, the severity of the penalty can be dynamically changed as the algorithm
progresses, imposing less strict penalties at first to encourage exploration, while becoming
more severe near the end to generate a result largely bound by the constraint.
• Any knowledge that the problem solver can acquire about the problem can be
represented in one or more problem spaces.
• If the actual problem involves acting upon the external world, then the definition of
state changes and of the effects upon the state of applying any operator reflects with
complete accuracy in one or more problem spaces the laws (laws of nature) that
govern the external world.
• All these conditions hold in the strong sense that the basic processes postulated
require only practicable amounts of computation and the information postulated is
effectively available to the processes—that is, available with the help of only
practicable amounts of search.
Assume that we are planning a robotic pick-and-place task in an inspection system. In
this scenario, the robot waits until receiving a signal from a presence sensor, which indicates
the existence of a defected workpiece over the conveyer belt. The robot stops the conveyer
belt and picks the defected piece and deposits it in a waste box. The robot reactivates the
movement of the conveyer belt after depositing the defected piece. After the operation, the
robot returns to its initial position and the cycle repeats itself again. As illustrated in Figure
1.8, this problem has the following well-structured components:
• Feasible States: position and speed of the robot arm and orientation and status
(open or close and orientation) of its end-effector (gripper)
• Operator (successor): robot arm motion control command to move from one point
to another following a certain singularity-free trajectory (positions or joint angles in
space and motion speed) and end-effector control (orientation and open or close).
• Goal: pick and place a defected workpiece regardless its orientation
• Solution/Path: optimal sequence through state space for fastest pick-and-place
operation
• Stopping Criteria: defected workpiece is picked from the conveyer belt and is placed
in the waste box and robot returns to home position
• Evaluation Criteria: pick-and-place duration and/or success rate of pick-and-place
process.
Figure 1.8 A well-structured problem will have a defined problem space, operators, and evaluation criteria.
As you can see, the work environment is highly structured, static and fully observable. An
optimal pick-and-place plan can be generated and executed with high level of certainty. This
pick-and-place problem can be considered as WSP.
Figure 1.9 Elevator dispatching problem. With four elevator cars and ten floors, this problem has 1022 possible
states.
In this problem, the following objective functions can be considered in this optimal
dispatching problem:
• Minimizing the average waiting time: how long the user waits before getting on an
elevator
• Minimizing the average system time: how long the user waits before being dropped
off at the destination floor
• Minimizing the percentage of the users whose waiting time exceeds 60 seconds.
• Ensuring fairness in serving all the users of the elevators.
This optimal dispatching problem is an example of ISP as the problem space has a
dynamic nature and partial observability; it is impossible to predict the user calls and
destinations. Moreover, the search space is huge due to the extremely high number of
possible states. There are 1022 possible states:
• 218 possible combinations of the 18 hall call buttons, i.e., up, and down buttons, at
each floor except the first and the last floor.
• 240 possible combinations of the 40 elevator buttons if each elevator has 10 buttons.
• 184 possible combinations of the position and directions of the elevators.
The total number of states for a problem as simple as dispatching this small building’s
elevators is more than the number of stars in the universe!
search space. Thus, all optimization techniques are in reality just search methods, where the
goal is to find feasible solutions to satisfy constraints and maximizes (or minimizes) the
objective functions. We define “search” as the systematic examination of feasible states,
starting from the initial state, and ending (hopefully) at the goal state. However, while we
explore the feasible search space, the question is if we find a few reasonably good
neighboring solutions, should we exploit this region or should we explore more looking for
better solutions in other regions of the feasible search space?
This exploration-exploitation or diversification-intensification dilemma is one of the most
important problems in search and optimization and in life as well. We apply exploration-
exploitation tactics in our life. When we move to a new city, we start by exploring different
stores and restaurants and then focus on shortlisted options around us. During midlife crisis,
some middle-aged individuals start to feel bored getting stuck in daily routine and lifestyle
without clear satisfactory accomplishment and tend to take more explorative actions. US
immigration system tries to avoid exploiting specific segments of applicants (e.g., family,
skilled-workers, refugees and asylees) and enables more diversity through computer-
generated lottery. In social insects like honeybees, foraging for food sources is performed by
two different worker groups, recruits and scouts (5-25% of the foragers). Recruits focus on a
specific food source while scouts are novelty seekers who keep scouting around for rich
nectar. In search and optimization, exploration-exploitation dilemma represents the tradeoff
between exploring new unvisited states/solutions in the search space and exploiting the elite
solutions found in a certain neighborhood in the search space (Figure 1.10).
Exploration (or diversification) is the process of investigating new regions in the feasible
search space with the hope of finding other promising solutions. On the other hand,
exploitation (or intensification) is the process of directing the search agent to focus on an
attractive region of the search space where good solutions have been already found.
Figure 1.10 Search Dilemma. There is always a tradeoff between branching out to new areas of the search
space or focusing on an area with known “good” or elite solutions.
1.6 Summary
• Optimization is a search process for finding the “best” solutions to a problem that
provide the best objective function values, possibly subject to a given set of hard
(must be satisfied) and soft (desirable to satisfy) constraints.
• Ill-structured problems are complex, discrete, or continuous problems without exact
differentiable mathematical models and/or algorithmic solutions or general problem
solvers. They usually have dynamic and/or partially observable large search spaces
that cannot be handled by classical optimization methods.
• Stochastic algorithms are non-greedy algorithms that explicitly use randomness to
find the global optimal or near-optimal solution in a reasonably practical time. In
many real-life applications, quickly finding a near-optimal solution is better than
spending a large amount of time in search for an optimal solution.
• Two key concepts you’ll see frequently in future chapters are
exploration/diversification and exploitation/intensification. Handling this search
dilemma by achieving a trade-off between exploration and exploitation will allow the
algorithm to find optimal or near-optimal solutions without getting trapped in local
optima in an attractive region of the search space and without spending large amount
of time.
Figure 2.1 Optimization problem classification. An optimization problem can be broken down into its
constituent parts, which form the basis of the classification of such problems.
The following subsections explain these types in greater detail and provide examples for
each type of optimization problem.
0.3% reduction in fuel economy. If we are only looking for the optimal vehicle speed for
maximum fuel economy, the problem is a univariate optimization problem. Finding the
optimal speed and optimal acceleration for maximum fuel economy is a bivariate
optimization problem, while finding optimal speed, acceleration, and tire pressure is a
multivariate problem.
Problem classification also varies according to the type of the decision variables. A
continuous problem involves continuous-valued variables where xj ∈ R. In contrast, if xj ∈ Z,
the problem is an integer, or discrete optimization problem. A mixed-integer problem has
both continuous-valued and integer-valued variables. For example, optimizing elevator speed
and acceleration (continuous variables) and the sequence of picking up passengers (discrete
variable) is a mixed-integer problem. Problems where the solutions are sets, combinations,
or permutations of integer-valued variables are referred to as combinatorial optimization
problems.
Figure 2.2 Combinations and permutations. Both combinations and permutations have variants with and without
repetition. The difference lies in the fact that permutations respect order and are thus ordered combinations.
For example, assume that we are designing a fitness plan to include multiple fitness activities. Five types of fitness
exercises are available to be included in the fitness plan, namely, jogging, swimming, biking, yoga, and aerobics. In a
weekly plan, if we are to choose only 3 out of these 5 exercises and the repetition is allowed, the number of possible
combinations will be: (n+r-1)!/r!(n-1)! = (5+3-1)!/3!(5-1)! = 7!/(3!×4!) =35. This means that we can generate 35
different fitness plans by selecting 3 out of the available 5 exercises and by allowing repetition.
However, if repetition is not allowed, the number of possible combinations will be: C(n,r)=n!/r!(n-r)!=5!/(3!×2!)=10.
This formula is often called “n choose r” (such as “5 choose 3’) and is also known as the “Binomial Coefficient”. This
means that we can generate only 10 plans if we don’t want to repeat any of the exercises.
In both cases of combination with and without repetition, the fitness plan doesn’t include the order of performing
the included exercises. If we are to respect specific order, the plan in this case will take the form of a permutation. If
repeating exercises is allowed, the number of possible permutations to select 3 exercises out of the 5 available
exercises will be: nr=53=125. However, if repetition is not allowed, the number of possible permutations will be:
P(n,r)=n!/(n-r)!=5!/(5-3)!=60.
Combinatorics can be implemented fairly easily in Python using code from scratch, but there are excellent
resources available in the form of libraries, such as sympy. For example, the Binomial Coefficient can be calculated in
sympy using the following simple code:
See Appendix-A and the documentation for sympy for more on implementing combinatorics in Python.
Figure 2.3 TSP in Greater Toronto Area (GTA). The traveling salesman must visit all the 13 cities, and wishes to
select the “best” path, whether that be distance, time, or some other criterion.
The naive solution’s complexity is O(n!). These means that there are n!=13!=
6,227,020,800 possible tours in case of ATSP. This makes both STSP and ATSP, NP-hard
problems. However, dynamic programming (DP) algorithms enable reduced complexity.
Dynamic programming is a method of solving optimization problems by breaking them down
into smaller subproblems and solving each subproblem independently. For example, the
complexity of Bellman-Held-Karp algorithm [1] is of O(2n×n²). Different solvers and
algorithms with different level of computational complexities and approximation ratios such
as Concorde TSP Solver, 2-opt/3-opt algorithm, branch and bound algorithms, Christofides
algorithm or Christofides–Serdyukov algorithm, Bellman–Held–Karp algorithm, Lin-Kernighan
algorithm, metaheuristics-based algorithms, graph neural networks or deep reinforcement
learning methods. For example, Christofides algorithm [2] is a polynomial-time
Problem Types
Decision problems are commonly classified based on their levels of complexities. These classes can be also applied
to optimization problems given the fact that optimization problems can be converted into decision-making problems.
For example, the optimization problem whose objective is to find an optimal or near-optimal solution within a feasible
search space can be paraphrased as a decision-making problem, which answers the question: “Is there is an optimal
or a near-optimal solution within the feasible search space?” The answer will be {“yes” or “no”} or {“True” or “False”}. A
generally-accepted notion of algorithm's efficiency is that its running time is polynomial. Problems that can be solved
in polynomial time are known as tractable. Figure 2.4 shows different types of problems and gives examples of
commonly used benchmark/toy and real-life application of each type.
Figure 2.4 Problem classes based on hardness and completeness. Problems can be categorized into NP-hard, NP-
complete, NP, or P.
For example, a complexity class P represents all decision problems that can be solved in polynomial time by
deterministic algorithms (i.e., algorithms that do not guess at a solution). The NP or Nondeterministic Polynomial
problems are problems whose solutions are hard to find but easy to verify and are solved by a non-deterministic
algorithm in polynomial time. NP-complete problems are problems that are both NP-hard and verifiable in polynomial
time. Finally, a problem is NP-hard if it is at least as hard as the hardest problem in NP-complete. NP-hard problems
are usually solved by approximation or heuristic solvers as it is hard to find efficient exact algorithms to solve such
kind of problems.
number) and gives the number of ways to partition a set of n objects into k non-empty
subsets:
𝑘𝑘
𝑛𝑛 1 𝑘𝑘
𝑆𝑆(𝑛𝑛, 𝑘𝑘) = � � = �(−1)𝑖𝑖 � � (𝑘𝑘 − 𝑖𝑖)𝑛𝑛
𝑘𝑘 𝑘𝑘! 𝑖𝑖
𝑖𝑖=0
Equation 2.1
Let's consider smart cart clustering as an example. Shopping and luggage carts are
commonly found in shopping malls and large airports. Shoppers or travelers pick up these
carts at designated points and leave them in arbitrary places. It is a considerable task to re-
collect them, and it is therefore beneficial if a “smarter” version of these carts could draw
themselves together automatically to the nearest assembly points as illustrated in Figure 2.5.
Figure 2.5 Smart Cart Clustering. Unused shopping or luggage carts congregate near designated assembly
points to make collection and redistribution easier.
In practice, this problem is considered an NP-hard problem, as the search space can be
very large based on the number of available carts and number of assembly points. In order
to cluster these carts effectively, the centers of clustering (centroids) must be found. The
carts in each cluster will then be directed to the assembly point closest to the centroids. For
example, assume that there are 50 carts to be clustered around 4 assembly points. This
means that n=50 and c=4. Stirling numbers can be generated using the sympy library. To do
so, simply call the stirling function on two numbers n and k.
The number is 5.3×1028 and if n is increased to 100, the number becomes 6.7×1058.
Enumerating all possible partitions for large problems is practically not feasible.
#A Unimodal function
#B Multimodal function
#C Deceptive function [3]
Figure 2.6 Unimodal, multimodal, and deceptive functions. Unimodal functions have one global optimum,
while multimodal functions can have many. Deceptive functions contain false optima close to the value of
objective function at global minimum, which can cause some algorithms to get stuck.
If the quantity to be optimized is expressed using only one objective function, the
problem is referred to as a mono-objective or single-objective optimization problem (such as
convex or concave functions). A multi-objective problem specifies multiple objectives to be
simultaneously optimized. Problems without an explicit objective function are called
Constraint-Satisfaction Problems (CSP). The goal in this case is to find a solution that
satisfies a given set of constraints. The N-queen problem is an example of CSP. In this
problem, the aim is to put n queens on an n×n board with no two queens on the same row,
column, or diagonal, as illustrated in Figure 2.7. In this 4-queen problem, there are 5
conflicts in the first state ({Q1,Q2}, {Q1,Q3},{Q2,Q3},{Q2,Q4} and {Q3,Q4}). After
moving Q4, the number of conflicts reduces by 2 and after moving Q3, the number of
conflicts is only 1, which is between Q1 and Q2.
Figure 2.7 N-Queen Problem. This problem has no objective function, rather, only a set of constraints that
must be satisfied.
By keep moving or placing the pieces, we can reach to the goal state where number of
conflicts is zero, which means that there is no any queen that could attach any other queen
board_size = 4
board = np.full((board_size, board_size), False) #A
return False
board[0][0] = True #D
col = 1
states = [deepcopy(board)]
while col < board_size:
row = 0
while row < board_size:
if not can_attack(board, row, col): #E
board[row][col] = True
col += 1
states.append(deepcopy(board))
break
row += 1
if row == board_size: #F
board = np.delete(board, 0, 1)
new_col = [[False]] * board_size
board = np.append(board, new_col, 1)
states.append(deepcopy(board))
col -= 1
continue
We define a function called can_attack to detect if a newly placed piece can attack a
previously placed piece. A piece can attack another piece if it is in the same row, column, or
diagonal.
Figure 2.8 N-Queens Solution. The first piece is trivially placed in the first position. The second piece must be
placed either in the 3rd position or the 4th position, as the first two can be attacked. By placing it in the 3rd
position however, the 3rd piece cannot be placed. Thus, the first piece is removed (the board is “slid” one
column over), and we reattempt. This continues until a solution is found.
The full code for this problem, including the code used to generate visualizations, can be
found in the code file for Listing 2.2. The solution algorithm is as follows:
1. Moving from top to bottom in a column, the algorithm attempts to place the piece
while avoiding conflicts. For the first column, this will default to Q1 = 0.
2. Moving to the next column, if a piece cannot be placed at row 0, it will be placed at
row 1, and so on.
3. When a piece has been placed, the algorithm moves to the next column.
4. If it is impossible to place a piece in a given column, the first column of the entire
board is removed, and the current column is reattempted.
Constraint programming solvers available in Google OR-Tools can be also used to solve
this n×n queen problem. Listing 2.3 shows the steps of the solution using OR-Tools.
board_size = 4 #B
model = cp_model.CpModel() #C
model.AddAllDifferent(queens) #E
solver = cp_model.CpSolver() #G
solver.parameters.enumerate_all_solutions = True #G
solver.Solve(model) #G
all_queens = range(board_size) #F
state=[]
for i in all_queens:
for j in all_queens:
if solver.Value(queens[j]) == i:
# There is a queen in column j, row i.
state.append(True)
else:
state.append(None)
states=np.array(state).reshape(-1, board_size)
fig = plt.figure(figsize=(5,5)) #H
markers = [
x.tolist().index(True) if True in x.tolist() else None
for x in np.transpose(states)
] #H
res = np.add.outer(range(board_size), range(board_size)) % 2 #H
plt.imshow(res, cmap="binary_r") #H
plt.xticks([]) #H
plt.yticks([]) #H
plt.plot(markers, marker="*", linestyle="None", markersize=100/board_size, color="y") #H
2.1.3 Constraints
Constrained problems have equality and/or inequality hard or soft constraints. Hard
constraints must be satisfied, while soft constraints are nice to satisfy (but are not
mandatory). If there are no constraints to be considered aside from the boundary
constraints, the problem is an unconstrained optimization problem. Let’s revisit the ticket
pricing problem introduced in subsection 1.3.1 of the previous chapter. There a wide range of
derivative-based solvers in Python that can handle such kind of differentiable mathematical
optimization problem (see Appendix A). Listing 2.4 shows how to solve this simple ticket
pricing problem using SciPy. SciPy is a library containing a collection of valuable tools for all
things computation.
def f(x): #A
return -(-20*x**2+6200*x-350000)/1000
This code finds the optimal ticket price in the range between $0 and $250 that maximizes
the profit. As you may have noticed the profit formula is converted into a minimization
problem by adding a negative sign in the objective function to match with the minimize
function in scipy.optimize. A minus sign was added in print function to convert it back into
profit.
What if we imposed an equality constraint on this problem? Let’s assume that due to
incredible international demand for our event, we now consider using a different event
planning company and opening up virtual attendance for our conference, so that
international guests can also participate. Interested participants can now choose between
attending the event in person or joining via live stream. All participants, whether in-person
or virtual, will still receive a physical welcome package, which is limited to 10,000 units.
Thus, in order to ensure a “full” event, we must either sell 10,000 in person tickets, 10,000
virtual tickets, or some combination thereof. This new event company is charging us a
$1,000,000 flat rate for the event, and thus we want to sell as many tickets as possible
(exactly 10,000). Below are the equations associated with this problem:
Let x be the number of physical ticket sales, and y be the number of virtual ticket sales.
Additionally, let f(x,y) be the function for profits generated from the event, where
f(x,y)=155x+(0.001x3/2+70)y-1000000
Equation 2.2
Essentially, we earn $155 profit on in-person attendance, and the profit for online
attendance is $70, but increases by some amount the more physical attendance we have
(let’s say that as the event looks “more crowded”, we can charge more for online attendees).
Assuming that we’re adding the constraint function: x+y≤10000, which shows that the
combined ticket sales cannot exceed 10,000. The problem is now a bivariate mono-objective
constrained optimization problem. It is possible to convert this constrained optimization
problem to unconstrained optimization using Lagrange multiplier λ. We can use sympy to
implement Lagrange multipliers to solve for the optimal mix of virtual and physical ticket
sales. The idea is to take the partial derivatives of the objective functions and the constraints
with respect to the decision variables x and y to form the unconstrained optimization
equations to be used by the SymPy solver as illustrated in Figure 2.10.
Figure 2.10 Steps of solving ticket pricing problem using Lagrange method
Listing 2.5 shows the Python implementation using SymPy. SymPy is an open-source
Python library for symbolic mathematics. Capabilities include, but are not limited to,
statistics, physics, geometry, calculus, equation solving, combinatorics, discrete math,
cryptograph and parsing. See Appendix-A for more information about SymPy.
f=155*x+(0.001*x**sym.Rational(3,2)+70)*y-1000000 #B
g=x+y-10000 #C
lamda=sym.symbols('lambda') #D
Lagr=f-lamda*g
sol=sym.solve(eqs,[x,y,lamda], dict=True) #F
By solving the above three equations, we get x and y values that correspond to the
optimized quantities for virtual and physical ticket sales. From Listing 2.5, we can see that
the best way to sell tickets is to sell 6,424 in-person tickets and 3,576 online ticket profits.
This results in a maximum profit of $2,087,260.533.
• Conservation: x1+x2+x3=1
In this problem, both the objective function and the constraints are linear so we call it
linear programming problem. There are several Python libraries that can be used for solving
mathematical optimization problems (see Appendix A). Let’s consider solving the animal feed
mix problem using PuLP. PuLP is a Python linear programming library. It allows users to
define linear programming problems and to solve them using optimization algorithms such as
COIN-OR's linear and integer programming solvers. See Appendix A for more information
about PuLP and other mathematical programming solvers. Listing 2.6 shows the steps of
solving the animal feed mix problem using PuLP.
model +=0.008 <= 0.001*x1 + 0.38*x2 + 0.002*x3 <= 0.012, 'Calcium limits' #D
model += 0.09*x1 + 0.5*x3 >=0.22, 'Minimum protein' #D
model += 0.02*x1 + 0.08*x3 <=0.05, 'Maximum fiber' #D
model += x1+x2+x3 == 1, 'Conservation' #D
model.solve() #E
for v in model.variables(): #F
print(v.name, '=', round(v.varValue,2)*100, '%') #F
As you can see in this listing, we start by importing PuLP and creating a model as linear
programming problem. We then define LP Variables with the specified associated parameters
such as name, lower bound and upper bound on each variable’s range and type of the
variable (e.g., Integer, Binary or Continuous). A solver is then used to solve the problem.
PuLP supports several solvers such as GLPK, GUROBI, CPLEX and MOSEK. The default solver
in PuLP is Cbc (Coin-or branch and cut). Running this code gives the following output:
Corn = 65.0%
Limestone = 3.0%
Soybean_meal = 32.0%
Total cost of the mixture per kg = 49.16$
················
E así presentado, el dicho señor Gonzalo de Guzmán dijo que lo
oyó e quél está presto de hacer lo que sea justicia e convenga al
servicio de Su Majestad, testigo Jerónimo Hernández e Suero de
Cangas, e que ayer lunes veinte e tres deste dicho mes lo
rescibieron en cabildo e hasta agora no ha entendido en cosa alguna
de lo que Su Majestad le manda.
················
E después desto, en la dicha cibdad de Santiago, lunes, treinta
días del dicho mes e del dicho año, el dicho señor Gonzalo de
Guzmán, en presencia de mí el dicho escribano, dijo respondiendo á
los requerimientos hechos por el dicho Licenciado, que si él ha
mandado pregonar quel término en que ha de hacer el dicho
Licenciado residencia que corra desde primero de agosto, ha seido
porquél tiene información de testigos de la mucha distancia de
camino que hay desde las villas desta isla á esta cibdad, adonde es
nescesidad, pues él ha seido juez en la dicha isla en todas las dichas
villas, e conviene al servicio de Su Majestad e bien de los vecinos
della que se sepa e sea notorio como el dicho Licenciado ha de
hacer la dicha residencia, porque si alguna persona dél se sintiere
agraviado ó de algunos de sus tenientes e oficiales, pidan su justicia,
si quisiere, como Su Majestad lo manda, e quel dicho Licenciado
hasta agora no tiene de qué ni por qué quejarse ni agraviarse,
porque como es notorio, el dicho señor Gonzalo de Guzmán, por
mandado de Su Majestad, ha solamente cuatro ó cinco días que
recibió el cargo e hasta agora él no ha entendido, salvo en lo que
conviene al servicio de Su Majestad, e informarse por testigos del
tiempo ques necesario que se dé para la dicha residencia, por
manera que en toda la isla sea notorio, e que en lo que dice que
tome letrado por asesor, que cuando sea tiempo él hará en ello lo
que Su Majestad le manda, e que si el dicho Licenciado dice que no
puede esperar el dicho tiempo á cabsa de la mucha costa que tiene
e que no es vecino desta isla, que á toda ella es notorio como él ha
tomado en sí e tiene indios en mucha cantidad, que son más de para
tres, e aun cuatro vecinos, especialmente los que fueron de Pedro
de Miranda, alcalde e vecino que fué en esta dicha cibdad, e los que
fueron de Rodrigo de Baeza, vecino desta dicha cibdad, e los que
fueron del adelantado Diego Velázquez, que haya gloria, que tenía
en la provincia de Bayte, entre los cuales, como es notorio, que
siendo el dicho Adelantado repartidor tomó los mejores de la dicha
provincia, e en más cantidad, con los cuales el dicho Licenciado, así
trayéndolos como los trae á sacar oro, como en otras granjerías que
en esta isla tiene, podían honestamente e muy bien los dichos tres ó
cuatro vecinos sustentarse, e que en lo que dice que habiendo seido
alcalde e regidor e heredero del dicho señor Adelantado el dicho
señor Gonzalo de Guzmán que Su Majestad había proveído que le
tomasen la dicha residencia, que como por las provisiones de Su
Majestad conste le fué notorio de todo lo susodicho, á cabsa de lo
cual él no tiene que decir cosa sobrello, salvo el dicho señor Gonzalo
de Guzmán complir lo que Su Majestad manda, e que como dicho
tiene, si él mandó que el término de la dicha residencia corriese
desde primero de agosto fué por lo que arriba se contiene, e demás
porque como es notorio en esta dicha isla, el dicho Licenciado ha
tenido en la villa de San Cristóbal de la Habana tratos e
contrataciones, e hay de la dicha villa á esta cibdad cerca de
trescientas leguas, e asimismo ha tenido las dichas contrataciones
en la villa de la Trenidad, que hay della á esta cibdad ciento e
cincuenta leguas, e más, como consta por la información que
sobrello ha recibido, á cabsa de lo cual mal podrían saber en las
dichas villas en los dichos cincuenta días como el dicho Licenciado e
sus oficiales han de hacer la dicha residencia, e que en lo que dice
que por haber sido juez ha de ser conservado e guardado mucho su
honor, que después quel dicho Licenciado dejó el dicho cargo e el
dicho señor Gonzalo de Guzmán le tiene, siempre lo ha tratado muy
bien e como él bien sabe, que con todos los buenos del pueblo ó con
la mayor parte dellos el dicho señor Gonzalo de Guzmán ha ido á la
posada del dicho Licenciado, ques en postrero de la dicha cibdad, á
le sacar e acompañar para que saliese á holgar e á pasear, e quél
todas las veces que fuere necesario tratar á su persona del dicho
Licenciado lo hará como á persona que ha tenido cargo de Su
Majestad, e quél y el dicho Licenciado sabe que alguna persona le
haya tratado después que dejó el dicho cargo de manera que no
deba, que siendo sabedor dello es presto de hacer cumplimiento de
justicia, e asimismo dijo quel bachiller Parada no sabe dónde está,
porque como es notorio á todos, no está en esta isla, por lo cual el
dicho señor Gonzalo de Guzmán no tiene que responder á lo sobrello
dicho por el dicho Licenciado, e questo da por respuesta no
consintiendo en sus protestaciones ni alguna dellas, e mandó á mí el
dicho escribano que si el dicho Licenciado pidiese testimonio no se lo
diese de esta su respuesta, e que vaya todo debajo de un signo.
Testigos que fueron presentes, Juan de Almagro e Andrés Ruano e
Gonzalo Hernández e Gonzalo de Guzmán.
················
Otrosí digo que ya su merced sabe como Pero Núñez de Guzmán
e su cuñado Pedro de Paz, oficiales de Su Majestad, e otras ciertas
personas, á causa de ciertas informaciones que en cosas
complideras al servicio de Su Majestad usando e teniendo yo el
cargo de teniente de gobernador en estas islas e por les haber
tomado residencia e condenádoles conforme á derecho, tovieron
formas como debajo de otras maneras se quejaron á Su Majestad
pidiendo residencia contra mí, e agora publicaron que porque no
queden falsos de lo que ansí escribieron á Su Majestad me ponen e
buscan quejas e demandas contra mí e por ser como son los dichos
oficiales hombres que tienen mano e muchas cosas que pueden
dañar á muchas personas, no osa procurador ni otra persona
ayudarme en las dichas cabsas, especial viendo como ven por la
manera que va e del amistad que vuestra merced con los dichos
oficiales e vecinos tiene, e agora el dicho señor Gonzalo de Guzmán,
juez susodicho, estando como están todos los pleitos e cabsas que
contra mí se tratan en grado de probanzas, por haber como ha
veinte e nueve días que los dichos pleitos penden e corren de mi
residencia, porque yo no puedo probar lo que á mi derecho conviene
sin haber fecho ni dicho cosa alguna por do pena merezca, me
tienen detenido en mi casa e á cabsa que yo parezca e quede
culpado en los dichos procesos porque pido e requiero al dicho señor
Gonzalo de Guzmán una e dos e más veces según desuso es
derecho, pues yo no he hecho cosa por do merezca estar preso
mayormente, pues no se ha fecho cosa por donde merezca muerte
ni perdimiento de miembro especialmente, pues estoy en residencia
e como tal juez que fago residencia debo de gozar e gozo de todas
las preminencias e libertades que á los susodichos son dadas e
otorgadas mayormente, pues soy notorio fijo de hidalgo, según que
es muy público e manifiesto, e siendo como soy Licenciado e
graduado por examen público, por lo cual ansimesmo debo de gozar
e gozo de todas e cualesquier preminencias e libertades que á los
susodichos son otorgadas, que su merced no añada agravio á
agravio ó fuerza á fuerza, antes me dé lugar á que yo salga de la
dicha carcelería que me tiene puesta para que yo atienda á mis
pleitos e alegue de mi derecho por manera que se parezca la verdad
e yo pueda mostrar mi inocencia e descargos, e quel dicho señor
Gonzalo de Guzmán guarde e faga guardar todas las preminencias
que en la dicha residencia se me deben ansí e según e de la manera
que se me guardaban, e con el acatamiento que se me debían
guardar al tiempo que yo tenía el dicho cargo de teniente de
gobernador, porque Dios dejase quien por él así lo faga e no
consienta ni dé lugar debajo de disimulación e risa que personas que
me tienen odio e apasionadas como en los semejantes casos se
suelen hacer, pidan por escrito ó fuera dél con palabras feas, ó digan
cosas no lícitas, porque demás de hacer su merced lo que debe
conforme á derecho, excusará pasiones e enojos que de allí se
podían suceder, pues ve la manera que los susodichos oficiales e sus
allegados, por ser como son amigos e tan unidos con el dicho señor
Gonzalo de Guzmán e que todo se les ha de sufrir e desimular, por
quien cada cosa e pleito que en la dicha Abdiencia se trata fablan
con mucha pasión e aceleramiento atrayendo e induciendo ó yendo
muchas personas que piden e molestan ante vuestra merced e de
cómo lo pido e requiero al dicho señor Gonzalo de Guzmán, vos lo
pido por testimonio e á los presentes sean testigos, e pido este abto
supuesto que el proceso de la pesquisa secreta, e protesto de
ayudarme dél e deste dicho requerimiento para que todos mis
pleitos e cabsas que en grado de residencia ante su merced contra
mí se trata, e que si á cabsa destar así detenido no hiciere mi
probanza legítima e tal cual basta para probar mis desculpas e
descargos no sea á mi cargo, antes á culpa del dicho señor Gonzalo
de Guzmán. El licenciado Altamirano.
················
Interrogatorio de oficio de justicia.
Por las preguntas siguientes sean preguntados los testigos de la
pesquisa secreta de la residencia que yo, Gonzalo de Guzmán, por
mandado de Su Majestad, tomo al licenciado Altamirano, juez de
residencia e teniente de gobernador que fué en esta isla Fernandina
e sus tenientes que han seido, e á los alguaciles e regidores desta
cibdad e de las otras villas desta isla:
1.ª Primeramente sean preguntados si conoscen al dicho
licenciado Juan Altamirano e a Francisco Osorio, tenientes en esta
cibdad, e á Francisco Aceituno, e á Francisco de Agüero, alguacil
mayor, e á Juan de Almagro, otrosí alguacil, e si conoscen al tesorero
Diego Núñez de Guzmán e al licenciado Pedro de Paz e Andrés de
Duero e á Diego de Soto, vecinos desta cibdad.
2.ª Item si saben que los dichos Licenciado e tenientes en el
dicho tiempo que tovieron el cargo tovieron arancel de los derechos
quellos e sus oficiales e escribanos solian llevar, e puesto en lugar
público e de letra legible en manera que se pudiese bien leer, e si el
dicho arancel si fué guardado por el dicho licenciado Altamirano ó
alguno dellos e los sobredichos tenientes e alguaciles e escribanos,
no guardando el dicho arancel, llevaban más derechos de los
contenidos en el dicho arancel, digan e declaren lo que saben.
3.ª Item si saben que los dichos tenientes ó algunas de las
sobredichas justicias hayan gastado promesas e dádivas que se
dieron á ellos ó á sus mujeres ó hijos, de manera que de las dichas
promesas ó dádivas viniese á ellos el provecho.
4.ª Item si saben, etc., que los dichos Licenciado, tenientes e
justicias hayan tenido parcialidad con regidores ó caballeros e otras
personas, no teniendo todos igualmente en justicia, e digan e
declaren lo que cerca desto saben, e si saben quel dicho Licenciado
ha comprado e vendido e cambiado algunas cosas ó ha tenido
ganado e otras granjerías en esta isla.
5.ª Item si saben, etc., que los dichos Licenciado, tenientes e las
otras sobredichas justicias ó alguaciles hayan llevado derechos de
ejecuciones de algunos autos ú obligaciones ó consentido llevar, no
siendo pagado primero el dueño de la debda, ó habiéndose dado por
contento, ó hayan llevado más derechos de los cuales venían según
que está en costumbre desta isla de les llevar los tales derechos ó
más de lo que mandan las leyes e ordenanzas del reino.
6.ª Item si saben que los dichos Licenciado e tenientes ó las
otras justicias ó alguno dellos hayan llevado algunas penas sin ser
sentenciadas las partes e oídas en sentencia pasada en cosa juzgada
ó hayan hecho iguala por sí ó por otra persona en las dichas penas
antes de serle sentenciada como dicho es pasada en cosa juzgada.
7.ª Item si saben, etc., que los dichos Licenciado e tenientes e
alguno dellos hayan llevado parte de sentencias que condenaron á
alguna persona.
8.ª Item si saben, etc., que los dichos Licenciado, tenientes e las
otras justicias ó alguno dellos hayan llevado derechos de homecillos
en caso que no sea de muerte de homes ó mujeres, y en caso que el
culpado no merezca la pena de muerte ó si hayan llevado la pena de
la sangre antes de ser sentenciada la cabsa e lo más de lo que debía
llevar.
9.ª Item si saben, etc., que los dichos Licenciado, tenientes e
justicias ó alguno dellos hayan arrendado los derechos de
alguacilazgo ó alcaldías ó cárcel ó entregas ó mayordomías ó
escribanías ó otros oficios, que eran á ellos de proveer por respeto
de los oficios que tenían, digan e declaren lo que cerca desto saben,
ó si saben que hayan hecho conveniencias ó igualas con los
escribanos e alguaciles ó con alguno que toviese los dichos oficios.
10. Item si saben que los dichos Licenciado, tenientes e las otras
justicias ó alguno dellos hayan dejado de ejecutar las penas de las
premáticas á los que dicen mal á nuestro Señor, e si saben que
alguna vez hayan dejado de ejecutar la dicha pena por amistad ó
enemistad, e no mandando e no cumpliendo á que esté treinta días
en la cárcel e las otras penas contenidas en las dichas premáticas.
11. Item si saben que los dichos Licenciado e tenientes pusieron
diligencia cerca de las ordenanzas desta isla, haciendo guardar las
buenas ordenanzas, enmendando las que se debían enmendar e
procurando de hacer otras complideras al bien e provecho desta isla,
especialmente como los oficiales fuesen elegidos sin parcialidad,
cómo e de qué manera pusieron deligencia que en esta isla e cibdad
estuviesen bien proveidos de carne e pescado e otros
mantenimientos, poniéndoles precios razonables, e digan e declaren
lo que desto saben.
12. Item si saben quel dicho Licenciado e sus tenientes han
castigado los pecados públicos, así como amancebados e blasfemias
de Dios nuestro Señor e de su bendita Madre, e digan lo que saben.
13. Item si saben que los dichos Licenciado e tenientes e las
otras justicias hayan consentido juegos de naipes ó dados, ú otros
juegos vedados.
14. Item si saben que los dichos Licenciado, tenientes e las otras
dichas justicias hayan hecho algunas derramas sobre las dichas villas
e pueblos e villas desta isla, e quién las cobró e en qué se gastaron,
e digan e declaren lo que cerca desto saben.
15. Item si saben, etc., que los dichos tenientes e otras justicias
hayan llevado dádivas por repartimiento desta cibdad ó de alguna
villa e lugar desta isla ó si le hayan dado los dichos regidores e
consejeros desta dicha cibdad ó de otra villa ó lugar desta dicha isla.
16. Item si saben que hayan consentido los dichos Licenciado e
tenientes e las sobredichas justicias que han sido en arriendar los
propios de las cibdades e villas desta dicha isla e oficiales del
concejo del tal pueblo por sí ó por personas interpuestas, e si saben
que los regidores las hayan arrendado de manera que hayan
consentido arrendar á personas que otras no osasen ni quisiesen
sobrepujar las dichas rentas.
17. Item si saben que los dichos Licenciado e tenientes e las
otras justicias hayan puesto deligencia para que las obras públicas
desta cibdad e de las villas e lugares desta dicha isla se hicieran á
menos costa e más provecho de los concejos.
18. Item si saben que los dichos tenientes e las otras justicias
hayan hecho los procesos criminales fuera de la cárcel, e si tienen ó
han tenido arca en que se guardar los procesos para que estén
recabdo e hayan tenido libro de todos los presos que han tenido e
venido á la cárcel, en que se declarase cada uno por qué fué preso,
e por cuyo mandado e qué bienes trajo, e cómo lo soltó e por qué, e
digan e declaren lo que cerca desto saben.
19. Item si saben, etc., que los dichos Licenciado, tenientes e las
otras justicias hayan consentido á los escribanos de concejo público
ú otros cualesquier que llevasen derechos de los procesos que
antellos pasaban que pertenecian al concejo.
20. Item si saben, etc., que los sobredichos tenientes e los
sobredichos regidores hayan consentido estar en cabildo algún
regidor hablando e platicando en cosas que le tocasen e que
hobiesen de dar votos de manera que pudiesen votar libremente, ó
platicándose alguna cosa que tocase algún debdo ó amigo ó familia
de los dichos regidores, e digan e declaren lo que cerca desto saben.
21. Item si saben que los sobredichos Licenciado, tenientes e las
otras justicias sobredichas ó alguno dellos hayan condenado algunas
penas ante otros escribanos que estaban diputados para las dichas
condenaciones, e si saben que las dichas penas en que así
condenaban las gastaban en cosas de su provecho ó en otra cosa de
lo que eran aplicadas, e si saben que el escribano ante quien se
condenaban las dichas penas si han sido alguna vez negligentes, ó
de otra manera si ha dejado de manifestar otro día después de la
condenación al escribano del concejo, e si han tomado las cuentas
en fin de cada un año al escribano de concejo e al escribano ante
quien pasaban.
22. Item si saben, etc., que los tenientes e las otras justicias ó
alguno dellos han sido negligentes en castigar los testigos falsos.
23. Item si saben que los dichos tenientes e los otros alcaldes e
jueces e justicias ó alguno dellos han dejado predicar algunas bulas
sin examinar si estaban examinadas por el obispo desta isla e
diocesano desta isla.
24. Item si saben que los dichos tenientes e otras justicias ó
alguno dellos han sacado ó dejado sacar desa dicha isla para fuera
parte della algunos indios para no los volver, e otras cosas vedadas
por provisión de Su Majestad e ordenanzas desta isla.