-
Notifications
You must be signed in to change notification settings - Fork 0
/
constraints.py
43 lines (36 loc) · 1.39 KB
/
constraints.py
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
class Constraint():
"""Constraints loaded from a file."""
def __init__(self, fname):
"""
Construct a Constraint object from a constraints file
:param fname: Name of the file to read the Constraint from (string)
"""
with open(fname, "r") as f:
lines = f.readlines()
# Parse the dimension from the first line
self.n_dim = int(lines[0])
# Parse the example from the second line
self.example = [float(x) for x in lines[1].split(" ")[0:self.n_dim]]
# Run through the rest of the lines and compile the constraints
self.exprs = []
for i in range(2, len(lines)):
# support comments in the first line
if lines[i][0] == "#":
continue
self.exprs.append(compile(lines[i], "<string>", "eval"))
return
def get_example(self):
"""Get the example feasible vector"""
return self.example
def get_ndim(self):
"""Get the dimension of the space on which the constraints are defined"""
return self.n_dim
def apply(self, x):
"""
Apply the constraints to a vector, returning True only if all are satisfied
:param x: list or array on which to evaluate the constraints
"""
for expr in self.exprs:
if not eval(expr):
return False
return True