LP modelling question... long time since school - algorithm

Sure, this isn't a programming question, per se... but I couldn't think of a better place to ask it all the same.
I'm writing an application that ultimately will assist a shopped to determine how to achieve the greatest savings on a specific site. The site provides two prices for just about every product - a regular price and a discounted price. The discounted price is available to anyone, but only one discounted item can be added to any given order. With just that information, the incentive is to minimize your order siz and instead place multiple orders. On the other hand, the total shipping costs are determined by the order size (by weight) and so the incentive there is to maximize the order size and place just one order.
I'm looking for a model to determine the most efficient way to balance the orders given the available discount for one item and the weight's influencing the shipping costs for the order(s).
I'm remembering back to school enough that I think this is a linear programming problem... but all I can remember about that class was how confusing it was.
Anyone have any tips on how to go about the math for this program?

This isn't regular linear programming, this is integer linear programming. The former is solvable in O(n²), the second is NP-hard.
Some variant of the branch-and-bound algorithm should be applicable to your program. If you don't feel like implementing it yourself, available libraries include GLPK, COIN-OR and CPLEX.

Expanding on my comment above, this problem depends heavily on the precise structure of the shipping costs. Suppose that the shipping costs are linear with a (potentially) non-zero constant term. Namely, shipping cost = C + Rw, where C and R are constants and w is the weight of an order. Then, it turns out that the optimal solution is simple: group every item where the discount is less than C into one order and order each item where the discount is greater than C separately (left as an exercise for the reader). In the degenerate case where C = 0, you would simply place a separate order for each item.
On the other hand, if the shipping cost has more of a threshold structure -- e.g.: if the weight of a shipment is less than B then the cost is C1 but if it's greater than B then the cost is C2 -- the situation becomes a form of the NP-complete bin-packing problem. I should note here that just because a situation is shaped like an NP-complete problem that you shouldn't immediately give up hope. For many real-world situations, good heuristics exist and it's entirely possible that the range of real-world inputs restricts the problem to manageable instances.
In real life, the odds are that the shipping costs are probably a combination of a bunch of different things (e.g.: maybe piece-wise linear with discontinuities) which makes modeling the problem that much harder. But, I hope I've demonstrated that it's crucial to have a clear idea of how these costs are structured in order to understand your problem.

Related

Algorithm to find best price combination when ordering product

I have a product A at 200$ with some supplier X
That same A product at 210$ with another supplier Y
I have product B at 100$ with supplier X and 150$ with supplier Y.
I need to order both A and B product.
Supplier X needs a minimum order amount of 100$ to do the delivery.
Supplier Y needs a minimum order amount of 140$ to do the delivery.
In real case there is much more products and much more suppliers to take into account.
Some suppliers may not have the product we need (but there always be at least 1 supplier that does have it).
Considering the above problem, what kind of algorithm/combination of algorithms can solve it ? I'm not asking for an answer directly but instead a line of thought.
Thanks!!
You need to look into Linear Optimization algorithms. On most cases they are easy to implement. You need
Z function to optimize ~ This is the target function which value you want to either minimize or maximize. It is usually related to total cost (minimize), risk (minimize), resources wasted (minimize), profit (maximize), etc. In you case, it can be to minimize the overall cost.
Variables ~ This are the values that must be changed. In your case that would be Xij (Amount of items of product i ordered from provider j)
Restrictions ~ This help to define an answer for the Z function. In your case that would be putting into a formula the amount of each product that you need, and the minimum purchase needed by the vendors.
The problem you mentioned is modeled as a linear programming algorithm
You want to maximize or minimize some function based on some constraints. Probably in your case Simplex algorithm should work.

Determining the cheapest way to buy n products online

I'm currently working on a simple script for personal use which would take a list of all the items I want to buy and the prices of each item from price comparators online and try to find the cheapest way to buy all of them (keeping in mind that if you buy mulptiple items from the same store, you're only going to pay the shipping cost once). What would be the easiest way to achieve this?
I thought about using Hungarian algorithm for this but realized this may not be the best idea as buying from the same store is often precisely what we do want, not something to avoid. Trying to greedily find the stores with the most items at hand, on the other hand, also falls short cause the fact that they do sell them does not mean they sell them at the best price, even if we only pay the shipping costs once.
What would you recommend? Is there some easily implementable solution to this?
I think this is a hard problem to solve exactly, because if you could solve this exactly you could take problems from https://en.wikipedia.org/wiki/Set_cover_problem and set up costs so that the exact solution to your problem would a solution of the set cover problem. Possibly some of the approximate solutions given in that article, or elsewhere, would help. The easiest way to throw high technology at it might be to find an integer linear programming package and use that.
This is not an answer, but rather a clarification on your problem. Since it's too long to fit into a comment, I post it here.
Let there be M shops and N items. A matrix A is given, where A(i, j) is the price of buying item j from shop i (we set A(i, j) to infinity if shop i doesn't sell item j). Also given is an array S, where S(i) is the shipping cost of shop i.
Problem: find the function b:{1,...,N} -> {1,...,M}, meaning buying item j from shop b(j), which minimizes the total cost.
Already you can see that this is different from the setting of Hungarian algorithm, the latter asking for a minimizing PERMUTATION of {1,...,N}.
At this point, there are several questions about the nature of the inputs:
what are the ranges of M and N? If either of them are very small (e.g. < 20), an exponential algorithm might be acceptable.
is the matrix A sparse (i.e. most items can only be bought in few shops) or dense (i.e. most items are available in most shops)?

maximize profit with n products satisfying certain constraints

I am given a list of n products with associated profits and costs per unit. The aim is to maximize the profits while keeping the total cost below some threshold. For each product either one or zero are produced.
Now suppose we have three products and Suppose we label these products 1,2 and 3. Then all possible combinations of productions can be given as the binary numbers 111,110,101,011,100,010,001 and 000, where a 1 in the i^th position denotes a production of one of product i and similarly for zero. We could then easily check which of these combinations has a production cost under the threshold and has the maximum profit. This algorithm would then be of order O(2^n) because for n products we have to check 2^n binary numbers. We can probably make this a little faster by recognizing that if 100 is above the threshold already we need not check 110 and 111 and some stuff like this but the order will not change because of this. How can I make a smarter algorithm maybe that has a better time complexity. The n can be as large as 100 in which case checking 2^100 numbers is not possible. Thanks in advance
If your costs are integers that are not too big, you can use the dynamic programming solution for the knapsack problem, which is listed in the link mentioned in David Eisenstat's comment. If your costs are either big integers or fractional, then your best bet is using one of the existing knapsack solvers that e.g. reduce to an integer linear programming problem and then do something like branch and bound in order to solve. At any rate, your problem IS the knapsack problem, with the only slight modification that you don't have to fill the knapsack completely, you can fill it partially as long as you don't overfill it. However this variant is also studied along with the original formulation, and there are solvers for it. Also it is easy to modify the dynamic programming solution to handle this, let me know if it's unclear how and I'll update my answer with an explanation.

Algorithm for sorting people into rooms based on age and nationality

I’m working on program for the English Language school I work for. I’m not being paid, its just a kind of a hobby to improve / automate my work flow.
It’s a residential school and one aspects I’m looking at automating is the way we allocate room to students, and although I don’t want a full blown solution I was hoping someone could point me in the right direction… Suggestions of the way you might approach this or by suggesting algorithms to look at etc.
Basically at the school we have a whole bunch of different rooms ranging from singles to dormitories for 8 people. We get lots of different nationalities from all over the world, and we always try to maker sure each room has a mix of nationalities. Where there is more than one nationality we try to balance them. Age is also important, we always put students of a similar age together, while still trying to mix nationalities, and its unusual for us to have students sharing with more than two years between them.
I suppose more generically speaking, I am in interested in how to sort a given set of students based on two parameters to an optimal result with a few rules attached.
I hope I’ve explain clearly what I am trying to achieve… in a way it sounds really simple, but I’ve trying to think how to do it in a simple way, i.e. by sorting by nationality and then by age but it just doesn’t cut it and I know there must be a better way of approaching this. When I do it “by hand” on an excel sheet it does feel quite intuitive.
Thank you to anyone who offers help / advice.
This is an interesting question but it's not easy to answer. Somehow it's connected with subdivsion and bin packing or the cutting-stock problem. You may want to look for a topological sort too. You can look for Drools a business logic platform that let you define such rules.
First of all you might find this interesting: Stable Room-mates Problem (wikipedia). Unfortunately it does not answer your question.
Try a genetic algorithm.
There are three main criteria for using a genetic algorithm:
ability to represent a solution as a mutable array. We can have an array of integers such that a[i] is the room for the ith student.
mutation of the state should produce predictable results. In our case this is true. Mutating the array will predictably shuffle students between the rooms.
easy to write a fast fitness function. Shouldn't be too hard to write a O(n) fitness function.
This is an interesting problem. I'll try writing some code with this approach and we'll see what happens.
How about, you think of a room as something that repels students of a nationality it already has, and attracts students of a close age to what it already has. The closer the age to the average age, the more it attracts it, and the more guys of X nationality are in the room, the more if repels guys of X nationality.
Then you would, for every new student to be added, iterate through each room and see which is the one that attracts it more. I guess if the room is empty you can set all forces to 0. Also, you would have a couple of constants that multiply each of both "forces" so you can calibrate it depending on how important is to have the same age against how important is to have different nationalities.
I'd analyze each student and create a 'personality' vector based on his/her age & nationality. Then I'd sort the vectors, and maybe scramble the results a bit after sorting to encourage diversity.
The general theme of "assign x to y with respect to constraints while optimizing some quantity" falls within operations research or more specifically http://en.wikipedia.org/wiki/Mathematical_optimization. The usual approach is to formally specify the problem and use a generic optimization solver such as one of those listed in http://en.wikipedia.org/wiki/List_of_optimization_software.
Give it a try, the formal specification languages for using the existing solvers are rather easy to learn and you might get an optimal solution without having to debug a complicated algorithm.
Formulation as a General Optimization Problem
It will be useful to formalize constraints and parameters. Let us assume that for 1 <= i <= 8, we have n_i rooms available of size i. Now let us impose the hard constraint that in a particular room S, every two students a, b \in S, we have that:
|Grade(a) - Grade(b)| <= 2 (1)
Now we are interested in optimizing the "diversity" function which intuitively represents the idea that we want rooms to be as mixed as possible. So we can represent this goal as:
max over all arrangements {{ Sum over all rooms S of DiversityScore(S) }}
where we have DiversityScore(S) = # of Different Nationalities in the Room
Formulation as a Graph Problem
This is the most general setting, but clearly max over all arrangements is not computationally feasible. Now let us pose this as a sort of graph problem with the hard grade constraints. Denote all students as a vertex in a Graph G. Connect two vertices if students satisfy constraint (1). Now a clique in this graph represents a group of students that can all be placed in the same room. Now proceed in a greedy manner. Choose the largest clique of size 4 which has the largest Diversity Score. Then place them in a room and continue until all rooms are filled. This clique search method can also incorporate gender constraints which is useful, however not that Clique finding is NP Hard Problem.
Now before trying to come up with something that may be faster, let us think about how to weaken the hard constraint (1). We can massage our graph formulation by including edge weights into the picture. So if the hard constraint is satisfied denote the edge weight from i to j as 1. If two students i and j deviate by age more than 2 denote the edge weight as 1 / (Age Difference)^2 or something. Then the score of a clique should be a product of the cliques edge weights with some diversity score. However it becomes clear that now the problem is on a complete graph, which is just the general optimization we hoped to avoid, so we need to impose some hard restrictions to reduce the connectivity of our graph.
A Basic Sorting Approximation Algorithm
Sort all students by their age, so we have a sorted array where all students in a[i] have the same age, and all students in a[i] are older than all students in a[j] for all j < i.
Now consider each pair i, j, of which there are O(n^2), where we also have that |Age[i] - Age[j]| <= 2. Find the largest group of students with different nationalities and place them in a room together. We successively iterate over O(n^2) index pairs which satisfy the hard constraint and take any students with nationality difference (which we can find by preprocessing and hashing on the index pairs). Doing this carefully (like looking at indices i j which are spread apart before close together) improves running time further. It feels like it should be polytime, but I think there are certain subtleties to address first before saying so.

What are some examples of problems well suited for Integer Linear Programming?

I've always been writing software to solve business problems. I came across about LIP while I was going through one of the SO posts. I googled it but I am unable to relate how I can use it to solve business problems. Appreciate if some one can help me understand in layman terms.
ILP can be used to solve essentially any problem involving making a bunch of decisions, each of which only has several possible outcomes, all known ahead of time, and in which the overall "quality" of any combination of choices can be described using a function that doesn't depend on "interactions" between choices. To see how it works, it's easiest to restrict further to variables that can only be 0 or 1 (the smallest useful range of integers). Now:
Each decision requiring a yes/no answer becomes a variable
The objective function should describe the thing we want to maximise (or minimise) as a weighted combination of these variables
You need to find a way to express each constraint (combination of choices that cannot be made at the same time) using one or more linear equality or inequality constraints
Example
For example, suppose you have 3 workers, Anne, Bill and Carl, and 3 jobs, Dusting, Typing and Packing. All of the people can do all of the jobs, but they each have different efficiency/ability levels at each job, so we want to find the best task for each of them to do to maximise overall efficiency. We want each person to perform exactly 1 job.
Variables
One way to set this problem up is with 9 variables, one for each combination of worker and job. The variable x_ad will get the value 1 if Anne should Dust in the optimal solution, and 0 otherwise; x_bp will get the value 1 if Bill should Pack in the optimal solution, and 0 otherwise; and so on.
Objective Function
The next thing to do is to formulate an objective function that we want to maximise or minimise. Suppose that based on Anne, Bill and Carl's most recent performance evaluations, we have a table of 9 numbers telling us how many minutes it takes each of them to perform each of the 3 jobs. In this case it makes sense to take the sum of all 9 variables, each multiplied by the time needed for that particular worker to perform that particular job, and to look to minimise this sum -- that is, to minimise the total time taken to get all the work done.
Constraints
The final step is to give constraints that enforce that (a) everyone does exactly 1 job and (b) every job is done by exactly 1 person. (Note that actually these steps can be done in any order.)
To make sure that Anne does exactly 1 job, we can add the constraint that x_ad + x_at + x_ap = 1. Similar constraints can be added for Bill and Carl.
To make sure that exactly 1 person Dusts, we can add the constraint that x_ad + x_bd + x_cd = 1. Similar constraints can be added for Typing and Packing.
Altogether there are 6 constraints. You can now supply this 9-variable, 6-constraint problem to an ILP solver and it will spit back out the values for the variables in one of the optimal solutions -- exactly 3 of them will be 1 and the rest will be 0. The 3 that are 1 tell you which people should be doing which job!
ILP is General
As it happens, this particular problem has a special structure that allows it to be solved more efficiently using a different algorithm. The advantage of using ILP is that variations on the problem can be easily incorporated: for example if there were actually 4 people and only 3 jobs, then we would need to relax the constraints so that each person does at most 1 job, instead of exactly 1 job. This can be expressed simply by changing the equals sign in each of the 1st 3 constraints into a less-than-or-equals sign.
First, read a linear programming example from Wikipedia
Now imagine the farmer producing pigs and chickens, or a factory producing toasters and vacuums - now the outputs (and possibly constraints) are integers, so those pretty graphs are going to go all crookedly step-wise. That's a business application that is easily represented as a linear programming problem.
I've used integer linear programming before to determine how to tile n identically proportioned images to maximize screen space used to display these images, and the formalism can represent covering problems like scheduling, but business applications of integer linear programming seem like the more natural applications of it.
SO user flolo says:
Use cases where I often met it: In digital circuit design you have objects to be placed/mapped onto certain parts of a chip (FPGA-Placing) - this can be done with ILP. Also in HW-SW codesign there often arise the partition problem: Which part of a program should still run on a CPU and which part should be accelerated on hardware. This can be also solved via ILP.
A sample ILP problem will looks something like:
maximize 37∙x1 + 45∙x2
where
x1,x2,... should be positive integers
...but, there is a set of constrains in the form
a1∙x1+b1∙x2 < k1
a2∙x1+b2∙x2 < k2
a3∙x1+b3∙x2 < k3
...
Now, a simpler articulation of Wikipedia's example:
A farmer has L m² land to be planted with either wheat or barley or a combination of the two.
The farmer has F grams of fertilizer, and P grams of insecticide.
Every m² of wheat requires F1 grams of fertilizer, and P1 grams of insecticide
Every m² of barley requires F2 grams of fertilizer, and P2 grams of insecticide
Now,
Let a1 denote the selling price of wheat per 1 m²
Let a2 denote the selling price of barley per 1 m²
Let x1 denote the area of land to be planted with wheat
Let x2 denote the area of land to be planted with barley
x1,x2 are positive integers (Assume we can plant in 1 m² resolution)
So,
the profit is a1∙x1 + a2∙x2 - we want to maximize it
Because the farmer has a limited area of land: x1+x2<=L
Because the farmer has a limited amount of fertilizer: F1∙x1+F2∙x2 < F
Because the farmer has a limited amount of insecticide: P1∙x1+P2∙x2 < P
a1,a2,L,F1,F2,F,P1,P2,P - are all constants (in our example: positive)
We are looking for positive integers x1,x2 that will maximize the expression stated, given the constrains stated.
Hope it's clear...
ILP "by itself" can directly model lots of stuff. If you search for LP examples you will probably find lots of famous textbook cases, such as the diet problem
Given a set of pills, each with a vitamin content and a daily vitamin
quota, find the cheapest cocktail that matches the quota.
Many such problems naturally have instances that require varialbe to be integers (perhaps you can't split pills in half)
The really interesting stuff though is that actually a big deal of combinatorial problems reduce to LP. One of my favourites is the assignment problem
Given a set of N workers, N tasks and an N by N matirx describing how
much each worker charges for the each task, determine what task to
give to each worker in order to minimize cost.
Most solution that naturally come up have exponential complexity but there is a polynomial solution using linear programming.
When it comes to ILP, ILP has the added benefit/difficulty of being NP-complete. This means that it can be used to model a very wide range of problems (boolean satisfiability is also very popular in this regard). Since there are many good and optimized ILP solvers out there it is often viable to translate an NP-complete problem into ILP instead of devising a custom algorithm of your own.
You can apply linear program easily everywhere you want to optimize and the target function is linear. You can make schedules (I mean big, like train companies, who need to optimize the utilization of the vehicles and tracks), productions (optimize win), almost everything. Sometimes it is tricky to formulate your problem as IP and/or sometimes you meet the problem that your solution is, that you have to produce e.g. 0.345 cars for optimum win. That is of course not possible, and so you constraint even more: Your variable for the number of cars must be integer. Even when it now sounds simpler (because you have infinite less choices for your variable), its actually harder. In this moment it gets NP-hard. Which actually means you can solve ANY problem from your computer with ILP, you just have to transform it.
For you I would recommend an intro into reading some basic (I)LP stuff. From my mind I dont know any good online site (but if you goolge you will find some), as book I can recommend Linear Programming from Chvatal. It has very good examples, and describes also real use cases.
The other answers here have excellent examples. Two of the gold standards in business of using integer programming and more generally operations research are
the journal Interfaces published by INFORMS (The Institute for Operations Research and the Management Sciences)
winners of the the Franz Edelman Award for Achievement in Operations Research and the Management Sciences
Interfaces publishes research that uses operations research applied to real-world problems, and the Edelman award is a highly competitive award for business use of operations research techniques.

Resources