Code reference

friendlysam.opt

class friendlysam.opt.Add

Addition operator.

See Operation for a general description of operations.

Parameters:*args – Should be exactly two terms to add.

Examples

>>> x = VariableCollection('x')
>>> expr = x(1) + x(2)
>>> expr
<friendlysam.opt.Add at 0x...>
>>> expr == Add(x(1), x(2))
True
>>> x(1).value, x(2).value = 2, 3
>>> float(expr)
5.0
class friendlysam.opt.Constraint(expr, desc=None, **kwargs)

docstring for Constraint

exception friendlysam.opt.ConstraintError(*args, **kwargs)

docstring

class friendlysam.opt.Domain

Domain of a variable.

Variable and VariableCollection support these domains passed in with the domain keyword argument of the constructor.

Examples

>>> s = get_solver()
>>> prob = Problem()
>>> x = Variable('x', domain=Domain.integer)
>>> prob.objective = Minimize(x)
>>> prob += (x >= 41.5)
>>> solution = s.solve(prob)
>>> solution[x] == 42
True
class friendlysam.opt.Eq

The relation “equals”.

Warning

This operation does not have overloaded operators for creation, so instead you should use the constructor, Eq(a, b).

Examples

>>> x = Variable('x')
>>> x == 3 # Don't do this!
False
>>> equality = Eq(x, 3) # Do this instead.
>>> equality
<friendlysam.opt.Eq at 0x...>
>>> x.value = 3
>>> equality.value
True
>>> x.value = 4
>>> equality.value
False
class friendlysam.opt.Less

The relation “less than”.

Examples

>>> x = Variable('x')
>>> expr = (x < 1)
>>> expr
<friendlysam.opt.Less at 0x...>
>>> expr == Less(x, 1)
True
>>> x.value = 1
>>> expr.value
False

Note

There is no Greater class, but you can use the overloaded operator >.

>>> x > 1
<friendlysam.opt.Less at 0x...>
>>> print(_)
1 < x
>>> (x > 1) == (1 < x)
True
class friendlysam.opt.LessEqual

The relation “less than or equal to”.

Examples

>>> x = Variable('x')
>>> expr = (x <= 1)
>>> expr
<friendlysam.opt.LessEqual at 0x...>
>>> expr == LessEqual(x, 1)
True
>>> x.value = 1
>>> expr.value
True

Note

There is no GreaterEqual class, but you can use the overloaded operator >=.

>>> x >= 1
<friendlysam.opt.LessEqual at 0x...>
>>> print(_)
1 <= x
>>> (x >= 1) == (1 <= x)
True
class friendlysam.opt.Maximize(expr)

docstring for Maximize

class friendlysam.opt.Minimize(expr)

docstring for Minimize

class friendlysam.opt.Mul

Addition operator.

See Operation for a general description of operations.

Parameters:*args – Should be exactly two terms to multiply.

Examples

>>> x = VariableCollection('x')
>>> expr = x(1) * x(2)
>>> expr
<friendlysam.opt.Mul at 0x...>
>>> expr == Mul(x(1), x(2))
True
>>> x(1).value, x(2).value = 2, 3
>>> float(expr)
6.0

Note

There is currently no division operator, but the operator / is overloaded such that x = a / b is equivalent to x = a * (1/b). Hence, you can do simple things like

>>> print(x(1) / 4)
x(1) * 0.25
exception friendlysam.opt.NoValueError

Raised when a variable or expression has no value.

class friendlysam.opt.Operation

An operation on some arguments.

This is a base class. Concrete examples:

Arithmetic operations: Add, Sub, Mul, Sum

Relations: Less, LessEqual, Eq

Note

The Variable class and the arithmetic operation classes have overloaded operators which create Operation instances.

Examples

>>> x = Variable('x')
>>> isinstance(x * 2, Operation)
True
>>> x + 1
<friendlysam.opt.Add at 0x...>
args

The arguments of the operation.

See create().

Examples

>>> x, y = Variable('x'), Variable('y')
>>> expr = x + y
>>> expr
<friendlysam.opt.Add at 0x...>
>>> expr.args == (x, y)
True
>>> (x + y) * 2
<friendlysam.opt.Mul at 0x...>
>>> _.args
(<friendlysam.opt.Add at 0x...>, 2)
classmethod create(*args)

Classmethod to create a new object.

This method is the default evaluator function used in evaluate(). Usually you don’t want to use this function, but instead the constructor.

Parameters:*args – The arguments the operation operates on.

Examples

>>> x = Variable('x')
>>> args = (2, x)
>>> Add.create(*args) == 2 + x
True
>>> LessEqual.create(*args) == (2 <= x)
True
evaluate(replace=None, evaluators=None)

Evaluate the expression recursively.

Evaluating an expression:

1. Get an evaluating function. If the class of the present expression is in the evaluators dict, use that. Otherwise, take the create() classmethod of the present expression class.

2. Evaluate all the arguments. For each argument arg, first try to replace it by looking for replace[arg]. If it’s not there, try to evaluate it by calling arg.evaluate() with the same arguments supplied to this call. If arg.evaluate() is not present, leave the argument unchanged.

  1. Run the evaluating function func(*evaluated_args) and return the result.
Parameters:
  • replace (dict, optional) – Replacements for arguments. Arguments matching keys will be replaced by specified values.
  • evaluators (dict, optional) – Evaluating functions to use instead of the default (which is the create() classmethod of the argument’s class). An argument whose __class__ equals a key will be evaluated with the specified function.

Examples

>>> x = VariableCollection('x')
>>> expr = x(1) + x(2)
>>> print(expr.evaluate())
x(1) + x(2)
>>> expr.evaluate(replace={x(1): 10, x(2): 20})
<friendlysam.opt.Add at 0x...>
>>> print(_)
10 + 20
>>> expr.evaluate(replace={x(1): 10, x(2): 20}, evaluators=fs.CONCRETE_EVALUATORS)
30
leaves

The leaves of the expression tree.

The leaves of an Operation are all the args which do not themselves have a leaves property.

Examples

>>> x, y = Variable('x'), Variable('y')
>>> expr = (42 + x * y * 3.5) * 2
>>> expr.leaves == {42, x, y, 3.5, 2}
True
value

The concrete value of the expression, if possible.

This property should only be used when you expect a concrete value. It is computed by calling evaluate() with the evaluators argument set to CONCRETE_EVALUATORS. If the returned value is a number or boolean, it is returned.

Raises::excNoValueError if the expression did not evaluate to a number or boolean.
variables

All leaves which are instances of Variable.

Examples

>>> x, y = Variable('x'), Variable('y')
>>> expr = (42 + x * y * 3.5) * 2
>>> expr.variables == {x, y}
True
class friendlysam.opt.Problem(constraints=None, objective=None)

An optimization problem

add(*additions)

docstring

solve()

Try to solve the optimization problem

class friendlysam.opt.Relation

Base class for binary relations.

See child classes:

class friendlysam.opt.SOS1(variables, **kwargs)

docstring for SOS1

class friendlysam.opt.SOS2(variables, **kwargs)

docstring for SOS2

exception friendlysam.opt.SolverError

A generic exception raised by a solver instance.

class friendlysam.opt.Sub

Addition operator.

See Operation for a general description of operations.

Parameters:*args – Should be exactly two items to subtract.

Examples

>>> x = VariableCollection('x')
>>> expr = x(1) - x(2)
>>> expr
<friendlysam.opt.Sub at 0x...>
>>> expr == Sub(x(1), x(2))
True
>>> x(1).value, x(2).value = 2, 3
>>> float(expr)
-1.0
class friendlysam.opt.Sum

A sum of items.

See the base class Operation for a basic description of attributes and methods.

args

A tuple of items to be summed.

Examples

Note that the constructor takes an iterable of arguments, just like the built-in sum() function, but the classmethod create() takes a list of arguments, as follows.

>>> x = VariableCollection('x')
>>> terms = [x(i) for i in range(4)]
>>> Sum(terms) == Sum.create(*terms)
True
>>> s = Sum(terms)
>>> s.evaluate(evaluators={Sum: sum})
Traceback (most recent call last):
...
TypeError: sum expected at most 2 arguments, got 4
>>> s.evaluate(evaluators={Sum: lambda *args: sum(args)})
<friendlysam.opt.Add at 0x...>
static __new__(vector)

Create a new Sum object

Parameters:vector (iterable) – The items to sum. Can be any iterable, also a generator, and may be zero length.
classmethod create(*args)

Classmethod to create a new Sum object.

Note that create() has a different signature than the constructor. The constructor takes an iterable as only argument, but create() takes a list of arguments.

Example

>>> x = VariableCollection('x')
>>> terms = [x(i) for i in range(4)]
>>> Sum(terms) == Sum.create(*terms)
True
class friendlysam.opt.Variable(name=None, lb=None, ub=None, domain=<Domain.real: 0>)

A variable to build expressions with.

Parameters:
  • name (str, optional) – A name of the variable. It has no relation to the identity of the variable. Just a name used in string representations.
  • lb (number, optional) – If supplied, a lower bound on the variable in optimization problems. If not supplied, the variable is unbounded downwards.
  • ub (number, optional) – If supplied, an upper bound on the variable in optimization problems. If not supplied, the variable is unbounded upwards.
  • domain (any of the Domain values) – The domain of the variable, enforced in optimization problems.

Note

The name, lb, ub and domain can also be set as attributes after creation.

>>> a = Variable('a')
>>> a.lb = 10
>>> a.Domain = Domain.integer

is equivalent to

>>> a = Variable('a', lb=10, domain=Domain.integer)

Examples

The namespace() context manager can be used to conveniently name groups of variables.

>>> with namespace('dimensions'):
...     w = Variable('width')
...     h = Variable('height')
...
>>> w.name, h.name
('dimensions.width', 'dimensions.height')
evaluate(replace=None, evaluators=None)

Evaluate a variable.

See Operation.evaluate() for a general explanation of expression evaluation.

A Variable is evaluated with the following priority order:

  1. If it has a value, that is returned.

2. Otherwise, if the variable is a key in the replace dictionary, the corresponding value is returned.

  1. Otherwise, the variable itself is returned.
Parameters:
  • replace (dict, optional) – Replacements.
  • evaluators (dict, optional) – Has no effect. Just included to be compatible with the signature of Operation.evaluate().

Examples

>>> x = Variable('x')
>>> x.evaluate() == x
True
>>> x.evaluate({x: 5}) == 5
True
>>> x.value = -1
>>> x.evaluate() == -1
True
>>> x.evaluate({x: 5}) == -1 # .value goes first!
True
>>> del x.value
>>> x.value
Traceback (most recent call last):
...
friendlysam.opt.NoValueError
take_value(solution)

Try setting the value of this variable from a dictionary.

Set self.value = solution[self] if possible.

Raises:KeyError if ``solution[self]`` is not available.
value

Value property.

Warning

There is nothing stopping you from setting value to a value which is inconsistent with the bounds and the domain of the variable.

class friendlysam.opt.VariableCollection(name=None, **kwargs)

docstring for VariableCollection

friendlysam.opt.get_solver(engine='pulp', options=None)

Get a solver object.

Parameters:
  • engine (str, optional) – Which engine to use.
  • options (dict, optional) –

    Parameters to the engine constructor.

    If engine == 'pulp', the engine is created using PulpSolver(options). See PulpSolver constructor for details.

friendlysam.opt.namespace(name)

Context manager for prefixing variable names.

Examples

>>> with namespace('dimensions'):
...     w = Variable('width')
...     h = VariableCollection('heights')
...
>>> w
<friendlysam.opt.Variable at 0x...: dimensions.width>
>>> h(3)
<friendlysam.opt.Variable at 0x...: dimensions.heights(3)>

friendlysam.parts

class friendlysam.parts.Cluster(*parts, **kwargs)

docstring for Cluster

class friendlysam.parts.ConstraintCollection(owner)

docstring for ConstraintCollection

class friendlysam.parts.FlowNetwork(resource, **kwargs)

docstring for FlowNetwork

class friendlysam.parts.Node(**kwargs)

docstring for Node

class friendlysam.parts.Part(name=None)

docstring for Part

iter_times_between(start, end)

Only works if time is orderable!!

times_between(start, end)

Only works if time is orderable!!

class friendlysam.parts.Storage(resource, capacity=None, maxchange=None, **kwargs)

docstring for Storage

friendlysam.models

class friendlysam.models.MyopicDispatchModel(t0=None, horizon=None, step=None, name=None, require_cost=True)

docstring for MyopicDispatchModel

friendlysam.common

friendlysam.compat

friendlysam.solvers

class friendlysam.solvers.pulpengine.PulpSolver(options)

docstring for PulpSolver

friendlysam.solvers.pulpengine.maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.