If Function in GAMS - if-statement

I've been busy with a model, but I'm uncomfortable about the result because I think GAMS violates a constraint. What I want to tell to GAMS is:
"check demand first -> then check current stocks -> IF there is enough stocks sell from current stocks -> IF there is not enough stocks first buy (produce) then sell."
I think in the model GAMS does not obey any demand (sell), any minimum values and sells everything without buying any.
The model is hereinbelow:
Sets
i items /s,p,b/
t time in quarters /1,2,3/
Parameters
price(i) selling price per unit i per quarter in euros /s 6.34, p 6.46, b 5.93/
inistock(i) initial stock in units /s 320000, p 296199, b 104208/
cap(i) capacity limit for each unit /s 400000, p 350000, b 150000/
c cost of holding 1 unit of i /s 10, p 15, b 12/
Scalars
tcap total capacity of warehouse /650000/
Variables
stock(i,t) stock stored at time t
sell(i,t) stock sold at time t
buy(i,t) stock bought at time t
cost total cost
Positive Variables stock,sell,buy
Equations
cst total cost occurs
stck(i,t) stock balance of unit i at time t;
cst.. cost=e=sum((i,t),price(i)*(buy(i,t)-sell(i,t))+c(i)*stock(i,t));
stck(i,t).. stock(i,t)=e=inistock(i)+stock(i,t-1)+buy(i,t)-sell(i,t);
stck.up(i,t)=tcap;
Option LP=Cplex ;
Option optcr=0;
Model TWH The Warehouse Problem / all /;
Solve TWH minimizing cost using lp;
Thank you in advance for your support!

You haven't set any demand constraints, and the only minimum values are the zero bounds from defining the variables as being positive.
What other constraint did you expect GAMS to obey?
Selling everything is the correct solution to the problem you have defined.
I also think this part is a mistake:
stck.up(i,t)=tcap;
You probably meant to write 'stock' rather than 'stck'.
If this was a lower bound (writing 'lo' instead of 'up'), you would have a problem with a non-trivial solution, as you are adding a constraint that the warehouse should be filled to maximum capacity.

Related

LP warehouse problem with a certain truck capacity

The problem that I need to solve is almost like the basic LP warehouse problem, where you have n warehouses, each one with a certain amount of a product, and m shops, each one demanding a certain amount of that product. So the goal is to minimize the amount of Km made by the trucks that have to deliver the products from the warehouses to the shops.
This was the easy part, I already identified the constraints and the objective function.
The part that I can't get my head around, is that the truck that delivers the products has a certain capacity, C. Every single truck has the same capacity. I can't tell if that piece of information is really relevant and should be included in some kind of constraint or something. I would really apreciate a hint, cause I've been stuck on this part for a while now and couldn't fine any example of this exact type of problem on the Internet
The number of trucs needed can be bounded by
numtrucs(i,j)*capacity >= shipment(i,j)
Add a term to the objective that minimizes the number of trucs.

Linear Programming - Re-setting a variable based on it's cumulative count

Detailed business problem:
I'm trying to solve a production scheduling business problem as below:
I have two plants producing FG A and B respectively.
Both the products consume the same Raw Material x
I need to create a 30 day production schedule looking at the Raw Material availability.
FG A and B can be produced if there is sufficient raw material available on the day.
After every 6 days of production the plant has to undergo maintenance and the production on that day will be zero.
Objective is to maximize the margin looking at the day level Raw material available and adhere to the production constraint (i.e. shutdown after every 6th day)
I need to build a linear programming to address the below problem:
Variable y: (binary)
variable z: cumulative of y
When z > 6 then y = 0. I also need to reset the cumulation of z after this point.
Desired output:
How can I build the statement to MILP constraint. Are there any techniques for solving this problem. Thank you.
I think you can model your maintenance differently. Just forbid any sequences of 7 ones for y. I.e.
y[t-6]+y[t-5]+y[t-4]+y[t-3]+y[t-2]+y[t-1]+y[t] <= 6 for t=1,..,T
This is easier than using your accumulator. Note that the beginning needs some attention: you can use historic data for this. I.e., at t=1, the values for t=0,-1,-2,.. are known.
Your accumulator approach is not inherently wrong. We often use it to model inventory. An inventory capacity is a restriction on how large the accumulated inventory can be.

Convert IF-ELSE statement in Linear Programming (ORTools)

I am trying to create an Optimization for Gas Storage using Linear Programming (OR Tools).
I need to write a case like this:
if current_balance > 70% of Total Volume:
set a limit for gas injection as 10
else:
set a limit for gas injection as 30
Current balance is the Total amount of gas that is available today in a gas storage.
I tried looking at Big M notation.
Is there other way except Big M? And if i have to use Big M then how can I use it in above problem?
Edited:
How can i build equation for following case:
if current_balance > 70% of Total Volume and current_balance < 80% of Total Volume:
set a limit for gas injection as 10
else if current_balance > 80% of Total Volume:
set a limit for gas injection as 30
I don't think there is an other way but Big M, although Big M get much better when you put some thought into it and choose M wisely and not too big (as small as possible). When the current balance is never allowed to exceed the total volume the following formulation is the tightest to work for you case. Here exceed is a boolean variable indicating whether you are exceeding the 70% of the total volume.
current_balance - (30%TotalVolume)*exceed <= 70%TotalVolume
gas_injection <= 30 - 20*exceed

Quantlib Floating rate bond with known first cash flow and forecasted cash flows equal

I am trying to price a floating rate bond and I already have the discount curve built with quantlib on C++. Now what I would like to do is to use the FloatingRateBond class and create a set of cash flows where the first cash flow is known (given that the index associated to this cash flow was known at the last reset date) and forecasting the remaining cash flows using the current index.
To make it more graphical assume annual payments and that the index at the last reset date was 1% and that the reset margin is 1%. Then the first cash flow will be 2% roughly speaking. Now assume that today's index is 2%, then I want all the remaining cash flows to be 3% (with the proper adjustments from the Day Count convention and Business Day convention).
How can I create such a cash flow structure for an instance of the FloatingRateBond class?
First I'll go quickly through building the bond, copying some code from the bonds example in the QuantLib release (also, disclaimer: I haven't tried compiling the code below). For more details on the classes involved, see the QuantLib documentation.
Let's assume annual payments as you said:
Schedule schedule(startDate, maturityDate, Period(Annual),
calendar, convention, convention,
DateGeneration::Backward, true);
and for illustration, let's assume we'll use an USD Libor index. Its future fixing are forecast based on an interest-rate term structure we'll set later.
RelinkableHandle<YieldTermStructure> liborTermStructure;
boost::shared_ptr<IborIndex> libor(
new USDLibor(Period(1,Years),liborTermStructure));
Now build the bond, adding the margin as a spread on the LIBOR rate:
FloatingRateBond bond(settlementDays, faceAmount,
schedule, libor, dayCounter,
convention, fixingDays,
// gearings
std::vector<Real>(1, 1.0),
// spreads
std::vector<Rate>(1, 0.001));
Now to get the coupons you want, you'll just set the corresponding market data. To set the rate of the first cash flow, store the past fixing of the Libor index:
libor->addFixing(resetDate, 0.01);
And to set the future cash flows, create a flat interest-rate curve with the desired rate (minding the conventions so that they match those of the Libor index):
boost::shared_ptr<YieldTermStructure> flatRate(
new FlatForward(today, 0.01, dayCounter, Simple, Annual));
liborTermStructure.linkTo(flatRate);
(You're not necessarily limited to a flat rate; if you can bootstrap a Libor curve, you can use that one to get realistic estimates for future coupons.)
At this point, you should be able to extract the bond coupons and check that they're as expected:
std::vector<boost::shared_ptr<CashFlow> > cashflows = bond.cashflows();
for (std::size_t i=0; i < cashflows.size(); ++i)
std::cout << cashflows[i]->date() << " "
<< cashflows[i]->amount() << "\n";
If you also want to call methods such as bond.cleanPrice(), you'll need to tell the bond how to discount the cash flows:
RelinkableHandle<YieldTermStructure> discountingTermStructure;
boost::shared_ptr<PricingEngine> bondEngine(
new DiscountingBondEngine(discountingTermStructure));
bond.setPricingEngine(bondEngine);
You can use for discounting the same curve you're using for forecasting...
discountingTermStructure.linkTo(flatRate);
...or create and use a different one.

Data Mining and Frequent Datasets

I've been doing some work for my exams in a few days and I'm going through some past papers but unfortunately there are no corresponding answers. I've answered the question and I was wondering if someone could tell me if I am correct.
My question is
(c) A transactional dataset, T, is given below:
t1: Milk, Chicken, Beer
t2: Chicken, Cheese
t3: Cheese, Boots
t4: Cheese, Chicken, Beer,
t5: Chicken, Beer, Clothes, Cheese, Milk
t6: Clothes, Beer, Milk
t7: Beer, Milk, Clothes
Assume that minimum support is 0.5 (minsup = 0.5).
(i) Find all frequent itemsets.
Here is how I worked it out:
Item : Amount
Milk : 4
Chicken : 4
Beer : 5
Cheese : 4
Boots : 1
Clothes : 3
Now because the minsup is 0.5 you eliminate boots and clothes and make a combo of the remaining giving:
{items} : Amount
{Milk, Chicken} : 2
{Milk, Beer} : 4
{Milk, Cheese} : 1
{Chicken, Beer} : 3
{Chicken, Cheese} : 3
{Beer, Cheese} : 2
Which leaves milk and beer as the only frequent item set then as it is the only one above the minsup?
I agree you should go for the Apriori Algorithm.
The Apriori algorithm is based on the idea that for a pair o items to be frequent, each individual item should also be frequent.
If the hamburguer-ketchup pair is frequent, the hamburger itself must also appear frequently in the baskets. The same can be said about the ketchup.
So for the algorithm, it is established a "threshold X" to define what is or it is not frequent. If an item appears more than X times, it is considered frequent.
The first step of the algorithm is to pass for each item in each basket, and calculate their frequency (count how many time it appears).
This can be done with a hash of size N, where the position y of the hash, refers to the frequency of Y.
If item y has a frequency greater than X, it is said to be frequent.
In the second step of the algorithm, we iterate through the items again, computing the frequency of pairs in the baskets. The catch is that
we compute only for items that are individually frequent. So if item y and item z are frequent on itselves,
we then compute the frequency of the pair. This condition greatly reduces the pairs to compute, and the amount of memory taken.
Once this is calculated, the frequencies greater than the threshold are said frequent itemset.
(http://girlincomputerscience.blogspot.com.br/2013/01/frequent-itemset-problem-for-mapreduce.html)
There are two ways to solve the problem:
using Apriori algorithm
Using FP counting
Assuming that you are using Apriori, the answer you got is correct.
The algorithm is simple:
First you count frequent 1-item sets and exclude the item-sets below minimum support.
Then count frequent 2-item sets by combining frequent items from previous iteration and exclude the item-sets below support threshold.
The algorithm can go on until no item-sets are greater than threshold.
In the problem given to you, you only get 1 set of 2 items greater than threshold so you can't move further.
There is a solved example of further steps on Wikipedia here.
You can refer "Data Mining Concepts and Techniques" by Han and Kamber for more examples.
OK to start, you must first understand, data mining (sometimes called data or knowledge discovery) is the process of analyzing data from different perspectives and summarizing it into useful information - information that can be used to increase revenue, cuts costs, or both. Data mining software is one of a number of analytical tools for analyzing data. It allows users to analyze data from many different dimensions or angles, categorize it, and summarize the relationships identified. Technically, data mining is the process of finding correlations or patterns among dozens of fields in large relational databases.
Now, the amount of raw data stored in corporate databases is exploding. From trillions of point-of-sale transactions and credit card purchases to pixel-by-pixel images of galaxies, databases are now measured in gigabytes and terabytes. (One terabyte = one trillion bytes. A terabyte is equivalent to about 2 million books!) For instance, every day, Wal-Mart uploads 20 million point-of-sale transactions to an A&T massively parallel system with 483 processors running a centralized database. Raw data by itself, however, does not provide much information. In today's fiercely competitive business environment, companies need to rapidly turn these terabytes of raw data into significant insights into their customers and markets to guide their marketing, investment, and management strategies.
Now you must understand that association rule mining is an important model in data mining. Its mining algorithms discover all item associations (or rules) in the data that satisfy the user-specified minimum support (minsup) and minimum confidence (minconf) constraints. Minsup controls the minimum number of data cases that a rule must cover. Minconf controls the predictive strength of the rule. Since only one minsup is used for the whole database, the model implicitly assumes that all items in the data are of the same nature and/or have similar frequencies in the data. This is, however, seldom the case in real- life applications. In many applications, some items appear very frequently in the data, while others rarely appear. If minsup is set too high, those rules that involve rare items will not be found. To find rules that involve both frequent and rare items, minsup has to be set very low. This may cause combinatorial explosion because those frequent items will be associated with one another in all possible ways. This dilemma is called the rare item problem. This paper proposes a novel technique to solve this problem. The technique allows the user to specify multiple minimum supports to reflect the natures of the items and their varied frequencies in the database. In rule mining, different rules may need to satisfy different minimum supports depending on what items are in the rules.
Given a set of transactions T (the database), the problem of mining association rules is to discover all association rules that have support and confidence greater than the user-specified minimum support (called minsup) and minimum confidence (called minconf).
I hope that once you understand the very basics of data mining that the answer to this question shall become apparent.