aboutsummaryrefslogtreecommitdiffstats
path: root/native/include/linprog/model.h
blob: 22f96e42db9211750234a25815ada08c44086055 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#ifndef LINPROG_MODEL_H
#define LINPROG_MODEL_H

#include <vector>
#include <utility>

#include "stl-helper.h"

typedef std::pair<double, unsigned int> Term;
typedef std::vector<Term> Terms;

class LinearExpression
{
private:
	Terms terms;

public:
	void add_term(double coefficient, unsigned int variable_index)
	{
		terms.push_back(Term(coefficient, variable_index));
	}

	// by default, assumes coefficient == 1
	void add_var(unsigned int variable_index)
	{
		add_term(1.0, variable_index);
	}

	const Terms& get_terms(void) const
	{
		return terms;
	}

	bool has_terms(void) const
	{
		return !terms.empty();
	}
};

typedef std::pair<LinearExpression *, double> Constraint;
typedef std::vector<Constraint> Constraints;

// builds a maximization problem piece-wise
class LinearProgram
{
	// the function to be maximized
	LinearExpression *objective;

	// linear expressions constrained to an exact value
	Constraints equalities;

	// linear expressions constrained by an upper bound (exp <= bound)
	Constraints inequalities;

public:
	LinearProgram() : objective(new LinearExpression()) {};

	~LinearProgram()
	{
		delete objective;
		foreach(equalities, eq)
			delete eq->first;
		foreach(inequalities, ineq)
			delete ineq->first;
	}

	void set_objective(LinearExpression *exp)
	{
		delete objective;
		objective = exp;
	}

	void add_inequality(LinearExpression *exp, double upper_bound)
	{
		if (exp->has_terms())
			inequalities.push_back(Constraint(exp, upper_bound));
		else
			delete exp;
	}

	void add_equality(LinearExpression *exp, double equal_to)
	{
		if (exp->has_terms())
			inequalities.push_back(Constraint(exp, equal_to));
		else
			delete exp;
	}

	const LinearExpression *get_objective() const
	{
		return objective;
	}

	LinearExpression *get_objective()
	{
		return objective;
	}

	const Constraints& get_equalities() const
	{
		return equalities;
	}

	const Constraints& get_inequalities() const
	{
		return inequalities;
	}
};

#endif