Mercurial > hg > pycsalgos
comparison pyCSalgos/GAP/gap.py @ 17:ef63b89b375a
Started working on GAP, but not complete
author | nikcleju |
---|---|
date | Sun, 06 Nov 2011 20:58:11 +0000 |
parents | |
children | a8ff9a881d2f |
comparison
equal
deleted
inserted
replaced
16:a6ca929f49f1 | 17:ef63b89b375a |
---|---|
1 # -*- coding: utf-8 -*- | |
2 """ | |
3 Created on Thu Oct 13 14:05:22 2011 | |
4 | |
5 @author: ncleju | |
6 """ | |
7 | |
8 #from numpy import * | |
9 #from scipy import * | |
10 import numpy as np | |
11 import scipy as sp | |
12 from scipy import linalg | |
13 import math | |
14 | |
15 from numpy.random import RandomState | |
16 rng = RandomState() | |
17 | |
18 | |
19 | |
20 def Generate_Analysis_Operator(d, p): | |
21 # generate random tight frame with equal column norms | |
22 if p == d: | |
23 T = rng.randn(d,d); | |
24 [Omega, discard] = np.qr(T); | |
25 else: | |
26 Omega = rng.randn(p, d); | |
27 T = np.zeros((p, d)); | |
28 tol = 1e-8; | |
29 max_j = 200; | |
30 j = 1; | |
31 while (sum(sum(abs(T-Omega))) > np.dot(tol,np.dot(p,d)) and j < max_j): | |
32 j = j + 1; | |
33 T = Omega; | |
34 [U, S, Vh] = sp.linalg.svd(Omega); | |
35 V = Vh.T | |
36 #Omega = U * [eye(d); zeros(p-d,d)] * V'; | |
37 Omega2 = np.dot(np.dot(U, np.concatenate((np.eye(d), np.zeros((p-d,d))))), V.transpose()) | |
38 #Omega = diag(1./sqrt(diag(Omega*Omega')))*Omega; | |
39 Omega = np.dot(np.diag(1 / np.sqrt(np.diag(np.dot(Omega2,Omega2.transpose())))), Omega2) | |
40 #end | |
41 ##disp(j); | |
42 #end | |
43 return Omega | |
44 | |
45 | |
46 def Generate_Data_Known_Omega(Omega, d,p,m,k,noiselevel, numvectors, normstr): | |
47 #function [x0,y,M,LambdaMat] = Generate_Data_Known_Omega(Omega, d,p,m,k,noiselevel, numvectors, normstr) | |
48 | |
49 # Building an analysis problem, which includes the ingredients: | |
50 # - Omega - the analysis operator of size p*d | |
51 # - M is anunderdetermined measurement matrix of size m*d (m<d) | |
52 # - x0 is a vector of length d that satisfies ||Omega*x0||=p-k | |
53 # - Lambda is the true location of these k zeros in Omega*x0 | |
54 # - a measurement vector y0=Mx0 is computed | |
55 # - noise contaminated measurement vector y is obtained by | |
56 # y = y0 + n where n is an additive gaussian noise with norm(n,2)/norm(y0,2) = noiselevel | |
57 # Added by Nic: | |
58 # - Omega = analysis operator | |
59 # - normstr: if 'l0', generate l0 sparse vector (unchanged). If 'l1', | |
60 # generate a vector of Laplacian random variables (gamma) and | |
61 # pseudoinvert to find x | |
62 | |
63 # Omega is known as input parameter | |
64 #Omega=Generate_Analysis_Operator(d, p); | |
65 # Omega = randn(p,d); | |
66 # for i = 1:size(Omega,1) | |
67 # Omega(i,:) = Omega(i,:) / norm(Omega(i,:)); | |
68 # end | |
69 | |
70 #Init | |
71 LambdaMat = np.zeros((k,numvectors)) | |
72 x0 = np.zeros((d,numvectors)) | |
73 y = np.zeros((m,numvectors)) | |
74 | |
75 M = rng.randn(m,d); | |
76 | |
77 #for i=1:numvectors | |
78 for i in range(0,numvectors): | |
79 | |
80 # Generate signals | |
81 #if strcmp(normstr,'l0') | |
82 if normstr == 'l0': | |
83 # Unchanged | |
84 | |
85 #Lambda=randperm(p); | |
86 Lambda = rng.permutation(int(p)); | |
87 Lambda = np.sort(Lambda[0:k]); | |
88 LambdaMat[:,i] = Lambda; # store for output | |
89 | |
90 # The signal is drawn at random from the null-space defined by the rows | |
91 # of the matreix Omega(Lambda,:) | |
92 [U,D,Vh] = sp.linalg.svd(Omega[Lambda,:]); | |
93 V = Vh.T | |
94 NullSpace = V[:,k:]; | |
95 #print np.dot(NullSpace, rng.randn(d-k,1)).shape | |
96 #print x0[:,i].shape | |
97 x0[:,i] = np.squeeze(np.dot(NullSpace, rng.randn(d-k,1))); | |
98 # Nic: add orthogonality noise | |
99 # orthonoiseSNRdb = 6; | |
100 # n = randn(p,1); | |
101 # #x0(:,i) = x0(:,i) + n / norm(n)^2 * norm(x0(:,i))^2 / 10^(orthonoiseSNRdb/10); | |
102 # n = n / norm(n)^2 * norm(Omega * x0(:,i))^2 / 10^(orthonoiseSNRdb/10); | |
103 # x0(:,i) = pinv(Omega) * (Omega * x0(:,i) + n); | |
104 | |
105 #elseif strcmp(normstr, 'l1') | |
106 elif normstr == 'l1': | |
107 print('Nic says: not implemented yet') | |
108 raise Exception('Nic says: not implemented yet') | |
109 #gamma = laprnd(p,1,0,1); | |
110 #x0(:,i) = Omega \ gamma; | |
111 else: | |
112 #error('normstr must be l0 or l1!'); | |
113 print('Nic says: not implemented yet') | |
114 raise Exception('Nic says: not implemented yet') | |
115 #end | |
116 | |
117 # Acquire measurements | |
118 y[:,i] = np.dot(M, x0[:,i]) | |
119 | |
120 # Add noise | |
121 t_norm = np.linalg.norm(y[:,i],2); | |
122 n = np.squeeze(rng.randn(m, 1)); | |
123 y[:,i] = y[:,i] + noiselevel * t_norm * n / np.linalg.norm(n, 2); | |
124 #end | |
125 | |
126 return x0,y,M,LambdaMat | |
127 | |
128 ##################### | |
129 | |
130 #function [xhat, arepr, lagmult] = ArgminOperL2Constrained(y, M, MH, Omega, OmegaH, Lambdahat, xinit, ilagmult, params) | |
131 def ArgminOperL2Constrained(y, M, MH, Omega, OmegaH, Lambdahat, xinit, ilagmult, params): | |
132 | |
133 # | |
134 # This function aims to compute | |
135 # xhat = argmin || Omega(Lambdahat, :) * x ||_2 subject to || y - M*x ||_2 <= epsilon. | |
136 # arepr is the analysis representation corresponding to Lambdahat, i.e., | |
137 # arepr = Omega(Lambdahat, :) * xhat. | |
138 # The function also returns the lagrange multiplier in the process used to compute xhat. | |
139 # | |
140 # Inputs: | |
141 # y : observation/measurements of an unknown vector x0. It is equal to M*x0 + noise. | |
142 # M : Measurement matrix | |
143 # MH : M', the conjugate transpose of M | |
144 # Omega : analysis operator | |
145 # OmegaH : Omega', the conjugate transpose of Omega. Also, synthesis operator. | |
146 # Lambdahat : an index set indicating some rows of Omega. | |
147 # xinit : initial estimate that will be used for the conjugate gradient algorithm. | |
148 # ilagmult : initial lagrange multiplier to be used in | |
149 # params : parameters | |
150 # params.noise_level : this corresponds to epsilon above. | |
151 # params.max_inner_iteration : `maximum' number of iterations in conjugate gradient method. | |
152 # params.l2_accurary : the l2 accuracy parameter used in conjugate gradient method | |
153 # params.l2solver : if the value is 'pseudoinverse', then direct matrix computation (not conjugate gradient method) is used. Otherwise, conjugate gradient method is used. | |
154 # | |
155 | |
156 #d = length(xinit) | |
157 d = xinit.size | |
158 lagmultmax = 1e5; | |
159 lagmultmin = 1e-4; | |
160 lagmultfactor = 2; | |
161 accuracy_adjustment_exponent = 4/5; | |
162 lagmult = max(min(ilagmult, lagmultmax), lagmultmin); | |
163 was_infeasible = 0; | |
164 was_feasible = 0; | |
165 | |
166 ####################################################################### | |
167 ## Computation done using direct matrix computation from matlab. (no conjugate gradient method.) | |
168 ####################################################################### | |
169 #if strcmp(params.l2solver, 'pseudoinverse') | |
170 if params['solver'] == 'pseudoinverse': | |
171 #if strcmp(class(M), 'double') && strcmp(class(Omega), 'double') | |
172 if M.dtype == 'float64' and Omega.dtype == 'double': | |
173 while 1: | |
174 alpha = math.sqrt(lagmult); | |
175 #xhat = np.concatenate((M, alpha*Omega(Lambdahat,:)]\[y; zeros(length(Lambdahat), 1)]; | |
176 xhat = np.concatenate((M, np.linalg.lstsq(alpha*Omega[Lambdahat,:],np.concatenate((y, np.zeros(Lambdahat.size, 1)))))); | |
177 temp = np.linalg.norm(y - np.dot(M,xhat), 2); | |
178 #disp(['fidelity error=', num2str(temp), ' lagmult=', num2str(lagmult)]); | |
179 if temp <= params['noise_level']: | |
180 was_feasible = 1; | |
181 if was_infeasible == 1: | |
182 break; | |
183 else: | |
184 lagmult = lagmult*lagmultfactor; | |
185 elif temp > params['noise_level']: | |
186 was_infeasible = 1; | |
187 if was_feasible == 1: | |
188 xhat = xprev; | |
189 break; | |
190 lagmult = lagmult/lagmultfactor; | |
191 if lagmult < lagmultmin or lagmult > lagmultmax: | |
192 break; | |
193 xprev = xhat; | |
194 arepr = np.dot(Omega[Lambdahat, :], xhat); | |
195 return xhat,arepr,lagmult; | |
196 | |
197 | |
198 ######################################################################## | |
199 ## Computation using conjugate gradient method. | |
200 ######################################################################## | |
201 #if strcmp(class(MH),'function_handle') | |
202 if hasattr(MH, '__call__'): | |
203 b = MH(y); | |
204 else: | |
205 b = np.dot(MH, y); | |
206 | |
207 norm_b = np.linalg.norm(b, 2); | |
208 xhat = xinit; | |
209 xprev = xinit; | |
210 residual = TheHermitianMatrix(xhat, M, MH, Omega, OmegaH, Lambdahat, lagmult) - b; | |
211 direction = -residual; | |
212 iter = 0; | |
213 | |
214 while iter < params.max_inner_iteration: | |
215 iter = iter + 1; | |
216 alpha = np.linalg.norm(residual,2)**2 / np.dot(direction.T, TheHermitianMatrix(direction, M, MH, Omega, OmegaH, Lambdahat, lagmult)); | |
217 xhat = xhat + alpha*direction; | |
218 prev_residual = residual; | |
219 residual = TheHermitianMatrix(xhat, M, MH, Omega, OmegaH, Lambdahat, lagmult) - b; | |
220 beta = np.linalg.norm(residual,2)**2 / np.linalg.norm(prev_residual,2)**2; | |
221 direction = -residual + beta*direction; | |
222 | |
223 if np.linalg.norm(residual,2)/norm_b < params['l2_accuracy']*(lagmult**(accuracy_adjustment_exponent)) or iter == params['max_inner_iteration']: | |
224 #if strcmp(class(M), 'function_handle') | |
225 if hasattr(M, '__call__'): | |
226 temp = np.linalg.norm(y-M(xhat), 2); | |
227 else: | |
228 temp = np.linalg.norm(y-np.dot(M,xhat), 2); | |
229 | |
230 #if strcmp(class(Omega), 'function_handle') | |
231 if hasattr(Omega, '__call__'): | |
232 u = Omega(xhat); | |
233 u = math.sqrt(lagmult)*np.linalg.norm(u(Lambdahat), 2); | |
234 else: | |
235 u = math.sqrt(lagmult)*np.linalg.norm(Omega[Lambdahat,:]*xhat, 2); | |
236 | |
237 | |
238 #disp(['residual=', num2str(norm(residual,2)), ' norm_b=', num2str(norm_b), ' omegapart=', num2str(u), ' fidelity error=', num2str(temp), ' lagmult=', num2str(lagmult), ' iter=', num2str(iter)]); | |
239 | |
240 if temp <= params['noise_level']: | |
241 was_feasible = 1; | |
242 if was_infeasible == 1: | |
243 break; | |
244 else: | |
245 lagmult = lagmultfactor*lagmult; | |
246 residual = TheHermitianMatrix(xhat, M, MH, Omega, OmegaH, Lambdahat, lagmult) - b; | |
247 direction = -residual; | |
248 iter = 0; | |
249 elif temp > params['noise_level']: | |
250 lagmult = lagmult/lagmultfactor; | |
251 if was_feasible == 1: | |
252 xhat = xprev; | |
253 break; | |
254 was_infeasible = 1; | |
255 residual = TheHermitianMatrix(xhat, M, MH, Omega, OmegaH, Lambdahat, lagmult) - b; | |
256 direction = -residual; | |
257 iter = 0; | |
258 if lagmult > lagmultmax or lagmult < lagmultmin: | |
259 break; | |
260 xprev = xhat; | |
261 #elseif norm(xprev-xhat)/norm(xhat) < 1e-2 | |
262 # disp(['rel_change=', num2str(norm(xprev-xhat)/norm(xhat))]); | |
263 # if strcmp(class(M), 'function_handle') | |
264 # temp = norm(y-M(xhat), 2); | |
265 # else | |
266 # temp = norm(y-M*xhat, 2); | |
267 # end | |
268 # | |
269 # if temp > 1.2*params.noise_level | |
270 # was_infeasible = 1; | |
271 # lagmult = lagmult/lagmultfactor; | |
272 # xprev = xhat; | |
273 # end | |
274 | |
275 #disp(['fidelity_error=', num2str(temp)]); | |
276 print 'fidelity_error=',temp | |
277 #if iter == params['max_inner_iteration']: | |
278 #disp('max_inner_iteration reached. l2_accuracy not achieved.'); | |
279 | |
280 ## | |
281 # Compute analysis representation for xhat | |
282 ## | |
283 #if strcmp(class(Omega),'function_handle') | |
284 if hasattr(Omega, '__call__'): | |
285 temp = Omega(xhat); | |
286 arepr = temp(Lambdahat); | |
287 else: ## here Omega is assumed to be a matrix | |
288 arepr = np.dot(Omega[Lambdahat, :], xhat); | |
289 | |
290 return xhat,arepr,lagmult | |
291 | |
292 | |
293 ## | |
294 # This function computes (M'*M + lm*Omega(L,:)'*Omega(L,:)) * x. | |
295 ## | |
296 #function w = TheHermitianMatrix(x, M, MH, Omega, OmegaH, L, lm) | |
297 def TheHermitianMatrix(x, M, MH, Omega, OmegaH, L, lm): | |
298 #if strcmp(class(M), 'function_handle') | |
299 if hasattr(M, '__call__'): | |
300 w = MH(M(x)); | |
301 else: ## M and MH are matrices | |
302 w = np.dot(np.dot(MH, M), x); | |
303 | |
304 if hasattr(Omega, '__call__'): | |
305 v = Omega(x); | |
306 vt = np.zeros(v.size); | |
307 vt[L] = v[L].copy(); | |
308 w = w + lm*OmegaH(vt); | |
309 else: ## Omega is assumed to be a matrix and OmegaH is its conjugate transpose | |
310 w = w + lm*np.dot(np.dot(OmegaH[:, L],Omega[L, :]),x); | |
311 | |
312 return w |