annotate scripts/ABSapproxMultiproc.py @ 29:bc2a96a03b0a

2011 nov 10. Rewrote a single ABSapprox file, reorganized functions
author nikcleju
date Thu, 10 Nov 2011 18:49:38 +0000
parents 1a88766113a9
children
rev   line source
nikcleju@27 1 # -*- coding: utf-8 -*-
nikcleju@27 2 """
nikcleju@27 3 Created on Sat Nov 05 18:08:40 2011
nikcleju@27 4
nikcleju@27 5 @author: Nic
nikcleju@27 6 """
nikcleju@27 7
nikcleju@27 8 import numpy as np
nikcleju@27 9 import scipy.io
nikcleju@27 10 import math
nikcleju@27 11 from multiprocessing import Pool
nikcleju@27 12 doplot = True
nikcleju@27 13 try:
nikcleju@27 14 import matplotlib.pyplot as plt
nikcleju@27 15 except:
nikcleju@27 16 doplot = False
nikcleju@27 17 if doplot:
nikcleju@27 18 import matplotlib.cm as cm
nikcleju@27 19 import pyCSalgos
nikcleju@27 20 import pyCSalgos.GAP.GAP
nikcleju@27 21 import pyCSalgos.SL0.SL0_approx
nikcleju@27 22
nikcleju@27 23 # Define functions that prepare arguments for each algorithm call
nikcleju@27 24 def run_gap(y,M,Omega,epsilon):
nikcleju@27 25 gapparams = {"num_iteration" : 1000,\
nikcleju@27 26 "greedy_level" : 0.9,\
nikcleju@27 27 "stopping_coefficient_size" : 1e-4,\
nikcleju@27 28 "l2solver" : 'pseudoinverse',\
nikcleju@27 29 "noise_level": epsilon}
nikcleju@27 30 return pyCSalgos.GAP.GAP.GAP(y,M,M.T,Omega,Omega.T,gapparams,np.zeros(Omega.shape[1]))[0]
nikcleju@27 31
nikcleju@27 32 def run_sl0(y,M,Omega,D,U,S,Vt,epsilon,lbd):
nikcleju@27 33
nikcleju@27 34 N,n = Omega.shape
nikcleju@27 35 #D = np.linalg.pinv(Omega)
nikcleju@27 36 #U,S,Vt = np.linalg.svd(D)
nikcleju@27 37 aggDupper = np.dot(M,D)
nikcleju@27 38 aggDlower = Vt[-(N-n):,:]
nikcleju@27 39 aggD = np.concatenate((aggDupper, lbd * aggDlower))
nikcleju@27 40 aggy = np.concatenate((y, np.zeros(N-n)))
nikcleju@27 41
nikcleju@27 42 sigmamin = 0.001
nikcleju@27 43 sigma_decrease_factor = 0.5
nikcleju@27 44 mu_0 = 2
nikcleju@27 45 L = 10
nikcleju@27 46 return pyCSalgos.SL0.SL0_approx.SL0_approx(aggD,aggy,epsilon,sigmamin,sigma_decrease_factor,mu_0,L)
nikcleju@27 47
nikcleju@27 48 def run_bp(y,M,Omega,D,U,S,Vt,epsilon,lbd):
nikcleju@27 49
nikcleju@27 50 N,n = Omega.shape
nikcleju@27 51 #D = np.linalg.pinv(Omega)
nikcleju@27 52 #U,S,Vt = np.linalg.svd(D)
nikcleju@27 53 aggDupper = np.dot(M,D)
nikcleju@27 54 aggDlower = Vt[-(N-n):,:]
nikcleju@27 55 aggD = np.concatenate((aggDupper, lbd * aggDlower))
nikcleju@27 56 aggy = np.concatenate((y, np.zeros(N-n)))
nikcleju@27 57
nikcleju@27 58 sigmamin = 0.001
nikcleju@27 59 sigma_decrease_factor = 0.5
nikcleju@27 60 mu_0 = 2
nikcleju@27 61 L = 10
nikcleju@27 62 return pyCSalgos.SL0.SL0_approx.SL0_approx(aggD,aggy,epsilon,sigmamin,sigma_decrease_factor,mu_0,L)
nikcleju@27 63
nikcleju@27 64
nikcleju@27 65 # Define tuples (algorithm setup function, algorithm function, name)
nikcleju@27 66 gap = (run_gap, 'GAP')
nikcleju@27 67 sl0 = (run_sl0, 'SL0_approx')
nikcleju@27 68
nikcleju@27 69 # Define which algorithms to run
nikcleju@27 70 # 1. Algorithms not depending on lambda
nikcleju@27 71 algosN = gap, # tuple
nikcleju@27 72 # 2. Algorithms depending on lambda (our ABS approach)
nikcleju@27 73 algosL = sl0, # tuple
nikcleju@27 74
nikcleju@27 75 def mainrun():
nikcleju@27 76
nikcleju@27 77 nalgosN = len(algosN)
nikcleju@27 78 nalgosL = len(algosL)
nikcleju@27 79
nikcleju@27 80 #Set up experiment parameters
nikcleju@27 81 d = 50.0;
nikcleju@27 82 sigma = 2.0
nikcleju@27 83 #deltas = np.arange(0.05,1.,0.05)
nikcleju@27 84 #rhos = np.arange(0.05,1.,0.05)
nikcleju@27 85 deltas = np.array([0.05, 0.45, 0.95])
nikcleju@27 86 rhos = np.array([0.05, 0.45, 0.95])
nikcleju@27 87 #deltas = np.array([0.05])
nikcleju@27 88 #rhos = np.array([0.05])
nikcleju@27 89 #delta = 0.8;
nikcleju@27 90 #rho = 0.15;
nikcleju@27 91 numvects = 100; # Number of vectors to generate
nikcleju@27 92 SNRdb = 20.; # This is norm(signal)/norm(noise), so power, not energy
nikcleju@27 93 # Values for lambda
nikcleju@27 94 #lambdas = [0 10.^linspace(-5, 4, 10)];
nikcleju@27 95 #lambdas = np.concatenate((np.array([0]), 10**np.linspace(-5, 4, 10)))
nikcleju@27 96 lambdas = np.array([0., 0.0001, 0.01, 1, 100, 10000])
nikcleju@27 97
nikcleju@27 98 meanmatrix = dict()
nikcleju@27 99 for i,algo in zip(np.arange(nalgosN),algosN):
nikcleju@27 100 meanmatrix[algo[1]] = np.zeros((rhos.size, deltas.size))
nikcleju@27 101 for i,algo in zip(np.arange(nalgosL),algosL):
nikcleju@27 102 meanmatrix[algo[1]] = np.zeros((lambdas.size, rhos.size, deltas.size))
nikcleju@27 103
nikcleju@27 104 jobparams = []
nikcleju@27 105 for idelta,delta in zip(np.arange(deltas.size),deltas):
nikcleju@27 106 for irho,rho in zip(np.arange(rhos.size),rhos):
nikcleju@27 107
nikcleju@27 108 # Generate data and operator
nikcleju@27 109 Omega,x0,y,M,realnoise = genData(d,sigma,delta,rho,numvects,SNRdb)
nikcleju@27 110
nikcleju@27 111 # Run algorithms
nikcleju@27 112 print "***** delta = ",delta," rho = ",rho
nikcleju@27 113 #mrelerrN,mrelerrL = runonce(algosN,algosL,Omega,y,lambdas,realnoise,M,x0)
nikcleju@27 114 jobparams.append((algosN,algosL, Omega,y,lambdas,realnoise,M,x0))
nikcleju@27 115
nikcleju@27 116 pool = Pool(4)
nikcleju@27 117 jobresults = pool.map(runoncetuple,jobparams)
nikcleju@27 118
nikcleju@27 119 idx = 0
nikcleju@27 120 for idelta,delta in zip(np.arange(deltas.size),deltas):
nikcleju@27 121 for irho,rho in zip(np.arange(rhos.size),rhos):
nikcleju@27 122 mrelerrN,mrelerrL = jobresults[idx]
nikcleju@27 123 idx = idx+1
nikcleju@27 124 for algotuple in algosN:
nikcleju@27 125 meanmatrix[algotuple[1]][irho,idelta] = 1 - mrelerrN[algotuple[1]]
nikcleju@27 126 if meanmatrix[algotuple[1]][irho,idelta] < 0 or math.isnan(meanmatrix[algotuple[1]][irho,idelta]):
nikcleju@27 127 meanmatrix[algotuple[1]][irho,idelta] = 0
nikcleju@27 128 for algotuple in algosL:
nikcleju@27 129 for ilbd in np.arange(lambdas.size):
nikcleju@27 130 meanmatrix[algotuple[1]][ilbd,irho,idelta] = 1 - mrelerrL[algotuple[1]][ilbd]
nikcleju@27 131 if meanmatrix[algotuple[1]][ilbd,irho,idelta] < 0 or math.isnan(meanmatrix[algotuple[1]][ilbd,irho,idelta]):
nikcleju@27 132 meanmatrix[algotuple[1]][ilbd,irho,idelta] = 0
nikcleju@27 133
nikcleju@27 134 # # Prepare matrices to show
nikcleju@27 135 # showmats = dict()
nikcleju@27 136 # for i,algo in zip(np.arange(nalgosN),algosN):
nikcleju@27 137 # showmats[algo[1]] = np.zeros(rhos.size, deltas.size)
nikcleju@27 138 # for i,algo in zip(np.arange(nalgosL),algosL):
nikcleju@27 139 # showmats[algo[1]] = np.zeros(lambdas.size, rhos.size, deltas.size)
nikcleju@27 140
nikcleju@27 141 # Save
nikcleju@27 142 tosave = dict()
nikcleju@27 143 tosave['meanmatrix'] = meanmatrix
nikcleju@27 144 tosave['d'] = d
nikcleju@27 145 tosave['sigma'] = sigma
nikcleju@27 146 tosave['deltas'] = deltas
nikcleju@27 147 tosave['rhos'] = rhos
nikcleju@27 148 tosave['numvects'] = numvects
nikcleju@27 149 tosave['SNRdb'] = SNRdb
nikcleju@27 150 tosave['lambdas'] = lambdas
nikcleju@27 151 try:
nikcleju@27 152 scipy.io.savemat('ABSapprox.mat',tosave)
nikcleju@27 153 except TypeError:
nikcleju@27 154 print "Oops, Type Error"
nikcleju@27 155 raise
nikcleju@27 156 # Show
nikcleju@27 157 if doplot:
nikcleju@27 158 for algotuple in algosN:
nikcleju@27 159 plt.figure()
nikcleju@27 160 plt.imshow(meanmatrix[algotuple[1]], cmap=cm.gray, interpolation='nearest',origin='lower')
nikcleju@27 161 for algotuple in algosL:
nikcleju@27 162 for ilbd in np.arange(lambdas.size):
nikcleju@27 163 plt.figure()
nikcleju@27 164 plt.imshow(meanmatrix[algotuple[1]][ilbd], cmap=cm.gray, interpolation='nearest',origin='lower')
nikcleju@27 165 plt.show()
nikcleju@27 166 print "Finished."
nikcleju@27 167
nikcleju@27 168 def genData(d,sigma,delta,rho,numvects,SNRdb):
nikcleju@27 169
nikcleju@27 170 # Process parameters
nikcleju@27 171 noiselevel = 1.0 / (10.0**(SNRdb/10.0));
nikcleju@27 172 p = round(sigma*d);
nikcleju@27 173 m = round(delta*d);
nikcleju@27 174 l = round(d - rho*m);
nikcleju@27 175
nikcleju@27 176 # Generate Omega and data based on parameters
nikcleju@27 177 Omega = pyCSalgos.GAP.GAP.Generate_Analysis_Operator(d, p);
nikcleju@27 178 # Optionally make Omega more coherent
nikcleju@27 179 U,S,Vt = np.linalg.svd(Omega);
nikcleju@27 180 Sdnew = S * (1+np.arange(S.size)) # Make D coherent, not Omega!
nikcleju@27 181 Snew = np.vstack((np.diag(Sdnew), np.zeros((Omega.shape[0] - Omega.shape[1], Omega.shape[1]))))
nikcleju@27 182 Omega = np.dot(U , np.dot(Snew,Vt))
nikcleju@27 183
nikcleju@27 184 # Generate data
nikcleju@27 185 x0,y,M,Lambda,realnoise = pyCSalgos.GAP.GAP.Generate_Data_Known_Omega(Omega, d,p,m,l,noiselevel, numvects,'l0');
nikcleju@27 186
nikcleju@27 187 return Omega,x0,y,M,realnoise
nikcleju@27 188
nikcleju@27 189 def runoncetuple(t):
nikcleju@27 190 return runonce(*t)
nikcleju@27 191
nikcleju@27 192 def runonce(algosN,algosL,Omega,y,lambdas,realnoise,M,x0):
nikcleju@27 193
nikcleju@27 194 d = Omega.shape[1]
nikcleju@27 195
nikcleju@27 196 nalgosN = len(algosN)
nikcleju@27 197 nalgosL = len(algosL)
nikcleju@27 198
nikcleju@27 199 xrec = dict()
nikcleju@27 200 err = dict()
nikcleju@27 201 relerr = dict()
nikcleju@27 202
nikcleju@27 203 # Prepare storage variables for algorithms non-Lambda
nikcleju@27 204 for i,algo in zip(np.arange(nalgosN),algosN):
nikcleju@27 205 xrec[algo[1]] = np.zeros((d, y.shape[1]))
nikcleju@27 206 err[algo[1]] = np.zeros(y.shape[1])
nikcleju@27 207 relerr[algo[1]] = np.zeros(y.shape[1])
nikcleju@27 208 # Prepare storage variables for algorithms with Lambda
nikcleju@27 209 for i,algo in zip(np.arange(nalgosL),algosL):
nikcleju@27 210 xrec[algo[1]] = np.zeros((lambdas.size, d, y.shape[1]))
nikcleju@27 211 err[algo[1]] = np.zeros((lambdas.size, y.shape[1]))
nikcleju@27 212 relerr[algo[1]] = np.zeros((lambdas.size, y.shape[1]))
nikcleju@27 213
nikcleju@27 214 # Run algorithms non-Lambda
nikcleju@27 215 for iy in np.arange(y.shape[1]):
nikcleju@27 216 for algofunc,strname in algosN:
nikcleju@27 217 epsilon = 1.1 * np.linalg.norm(realnoise[:,iy])
nikcleju@27 218 xrec[strname][:,iy] = algofunc(y[:,iy],M,Omega,epsilon)
nikcleju@27 219 err[strname][iy] = np.linalg.norm(x0[:,iy] - xrec[strname][:,iy])
nikcleju@27 220 relerr[strname][iy] = err[strname][iy] / np.linalg.norm(x0[:,iy])
nikcleju@27 221 for algotuple in algosN:
nikcleju@27 222 print algotuple[1],' : avg relative error = ',np.mean(relerr[strname])
nikcleju@27 223
nikcleju@27 224 # Run algorithms with Lambda
nikcleju@27 225 for ilbd,lbd in zip(np.arange(lambdas.size),lambdas):
nikcleju@27 226 for iy in np.arange(y.shape[1]):
nikcleju@27 227 D = np.linalg.pinv(Omega)
nikcleju@27 228 U,S,Vt = np.linalg.svd(D)
nikcleju@27 229 for algofunc,strname in algosL:
nikcleju@27 230 epsilon = 1.1 * np.linalg.norm(realnoise[:,iy])
nikcleju@27 231 gamma = algofunc(y[:,iy],M,Omega,D,U,S,Vt,epsilon,lbd)
nikcleju@27 232 xrec[strname][ilbd,:,iy] = np.dot(D,gamma)
nikcleju@27 233 err[strname][ilbd,iy] = np.linalg.norm(x0[:,iy] - xrec[strname][ilbd,:,iy])
nikcleju@27 234 relerr[strname][ilbd,iy] = err[strname][ilbd,iy] / np.linalg.norm(x0[:,iy])
nikcleju@27 235 print 'Lambda = ',lbd,' :'
nikcleju@27 236 for algotuple in algosL:
nikcleju@27 237 print ' ',algotuple[1],' : avg relative error = ',np.mean(relerr[strname][ilbd,:])
nikcleju@27 238
nikcleju@27 239 # Prepare results
nikcleju@27 240 mrelerrN = dict()
nikcleju@27 241 for algotuple in algosN:
nikcleju@27 242 mrelerrN[algotuple[1]] = np.mean(relerr[algotuple[1]])
nikcleju@27 243 mrelerrL = dict()
nikcleju@27 244 for algotuple in algosL:
nikcleju@27 245 mrelerrL[algotuple[1]] = np.mean(relerr[algotuple[1]],1)
nikcleju@27 246
nikcleju@27 247 return mrelerrN,mrelerrL
nikcleju@27 248
nikcleju@27 249 # Script main
nikcleju@27 250 if __name__ == "__main__":
nikcleju@27 251 #import cProfile
nikcleju@27 252 #cProfile.run('mainrun()', 'profile')
nikcleju@27 253
nikcleju@27 254 mainrun()