/
kojima_solver.py
84 lines (65 loc) · 2.31 KB
/
kojima_solver.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
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
import numpy as np
import scipy.sparse as sps
import matplotlib.pyplot as plt
from lcp import LCPObj
from utils.archiver import Unarchiver,Archiver
from solvers import augment_lcp,KojimaIPIterator,IterativeSolver
from solvers.termination import *
from solvers.notification import *
from solvers.recording import *
import time
import argparse
import sys
import os.path
###############################################
# Solvers
def kojima_solve(lcp,**kwargs):
thresh = kwargs.get('thresh',1e-12)
max_iter = kwargs.get('max_iter',2)
reg = kwargs.get('reg',1e-7)
(N,) = lcp.q.shape
D = np.random.rand(N)
#lcp.M += reg * sps.diags(D)
x0 = kwargs.get('x0',np.ones(N))
y0 = kwargs.get('y0',np.ones(N))
iterator = KojimaIPIterator(lcp,x0=x0,y0=y0)
solver = IterativeSolver(iterator)
term_conds = [InnerProductTerminationCondition(thresh),
MaxIterTerminationCondition(max_iter),
SteplenTerminationCondition(1e-20)]
announce = [IterAnnounce(),
PotentialAnnounce(),
PotentialDiffAnnounce()]
solver.termination_conditions.extend(term_conds)
solver.notifications.extend(announce)
solver.solve()
(p,d) = (iterator.get_primal_vector(),iterator.get_dual_vector())
return (p,d,iterator.data)
def solve_lcp_file(lcp_file):
unarch = Unarchiver(lcp_file)
lcp = LCPObj(unarch.M,unarch.q)
# Augment
(n,) = lcp.q.shape
alcp,x0,y0 = augment_lcp(lcp,5*n)
(N,) = alcp.q.shape
assert(N == n + 1) # Augmented
(p,d,data) = kojima_solve(alcp,
x0=x0,
y0=y0)
print '#'*20
print 'FINISHED'
print 'Slack variables', p[-1],d[-1]
# Strip augmented variable and expand omitted nodes
p = p[:-1]
d = d[:-1]
filename, file_extension = os.path.splitext(lcp_file)
print "Writing solution to ", filename + '.sol'
arch = Archiver(p=p,d=d)
arch.write(filename + '.sol')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Solve an LCP using Kojima.')
parser.add_argument('lcp_file_name', metavar='F', type=str,
help='LCP input file')
args = parser.parse_args()
#Read LCP file
solve_lcp_file(args.lcp_file_name)