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