Browse Source

Added option for python phasing rather than R

add-license-1
Trevor Irons 7 years ago
parent
commit
46583c96ea
2 changed files with 351 additions and 172 deletions
  1. 340
    170
      akvo/tressel/decay.py
  2. 11
    2
      akvo/tressel/mrsurvey.py

+ 340
- 170
akvo/tressel/decay.py View File

@@ -1,5 +1,7 @@
1
-import numpy, pylab,array #,rpy2
2
-
1
+import numpy, array #,rpy2
2
+from matplotlib import pyplot as plt
3
+import numpy as np
4
+from scipy.optimize import least_squares
3 5
 from rpy2.robjects.packages import importr
4 6
 
5 7
 import rpy2.robjects as robjects
@@ -52,7 +54,7 @@ def peakPicker(data, omega, dt):
52 54
 
53 55
 #################################################
54 56
 # Regress for T2 using rpy2 interface
55
-def regressCurve(peaks,times,sigma2=None  ,intercept=True):
57
+def regressCurve(peaks,times,sigma2=1,intercept=True):
56 58
 
57 59
     # TODO, if regression fails, it might be because there is no exponential
58 60
     # term, maybe do a second regression then on a linear model. 
@@ -65,23 +67,21 @@ def regressCurve(peaks,times,sigma2=None  ,intercept=True):
65 67
     robjects.globalenv['b1'] = b1
66 68
     robjects.globalenv['b2'] = b2
67 69
     robjects.globalenv['rT2'] = rT2
68
-    #robjects.globalenv['sigma2'] = sigma2
70
+    robjects.globalenv['sigma2'] = sigma2
69 71
     value = robjects.FloatVector(peaks)
70 72
     times = robjects.FloatVector(numpy.array(times))
71 73
     
72 74
 #    my_weights = robjects.RVector(value/sigma2)
73 75
 #    robjects.globalenv['my_weigts'] = my_weights
74 76
 
75
-    if sigma2 != None:
76
-        # print ("weighting")
77
-        #tw = numpy.array(peaks)/sigma2 
78
-        my_weights = robjects.FloatVector( sigma2 )
79
-    #else:
80
-    #    my_weights = robjects.FloatVector(numpy.ones(len(peaks))) 
77
+#    if sigma2 != 0:
78
+#        print "weighting"
79
+#        tw = numpy.array(peaks)/sigma2 
80
+#        my_weights = robjects.RVector( tw/numpy.max(tw) )
81
+#    else:
82
+#        my_weights = robjects.RVector(numpy.ones(len(peaks))) 
81 83
 
82
-        robjects.globalenv['my_weights'] = my_weights
83
-        #print (my_weights)
84
-        #print (len(peaks))
84
+#    robjects.globalenv['my_weights'] = my_weights
85 85
     
86 86
     if (intercept):
87 87
         my_list = robjects.r('list(b1=50, b2=1e2, rT2=0.03)')
@@ -107,27 +107,121 @@ def regressCurve(peaks,times,sigma2=None  ,intercept=True):
107 107
     env['times'] = times
108 108
     
109 109
     # ugly, but I get errors with everything else I've tried
110
-    #my_weights = robjects.r('rep(1,length(value))')
111
-    #for ii in range(len(my_weights)):
112
-    #    my_weights[ii] *= peaks[ii]/sigma2
113
-
114
-
110
+    my_weights = robjects.r('rep(1,length(value))')
111
+    for ii in range(len(my_weights)):
112
+        my_weights[ii] *= peaks[ii]/sigma2
115 113
     Error = False
116 114
     #fit = robjects.r.nls(fmla,start=my_list,control=my_cont,weights=my_weights)
117
-    if (sigma2 != None):
118
-        #print("SIGMA 2")
115
+    if (sigma2 != 1):
116
+        print("SIGMA 2")
119 117
         #fit = robjects.r.tryCatch(robjects.r.suppressWarnings(robjects.r.nls(fmla,start=my_list,control=my_cont,algorithm="port", \
120 118
         #                     weights=my_weights)), 'silent=TRUE')
119
+        fit = robjects.r.tryCatch(robjects.r.nls(fmla,start=my_list,control=my_cont))#, \
120
+                            # weights=my_weights))
121
+    else:
121 122
         try:
122
-            fit = robjects.r.tryCatch(    robjects.r.nls(fmla, start=my_list, control=my_cont, weights=my_weights, algorithm="port" , \
123
-                lower=my_lower,upper=my_upper))
123
+            fit = robjects.r.tryCatch(robjects.r.nls(fmla,start=my_list,control=my_cont,algorithm="port"))#,lower=my_lower,upper=my_upper))
124 124
         except:
125 125
             print("regression issue pass")
126 126
             Error = True
127
+    # If failure fall back on zero regression values   
128
+    if not Error:
129
+        #Error = fit[3][0]
130
+        report =  r.summary(fit)
131
+    b1 = 0
132
+    b2 = 0 
133
+    rT2 = 1
134
+    if (intercept):
135
+        if not Error:
136
+            b1  =  r['$'](report,'par')[0]
137
+            b2  =  r['$'](report,'par')[1]
138
+            rT2 =  r['$'](report,'par')[2]
139
+            #print  report
140
+            #print  r['$'](report,'convergence')
141
+            #print  r['convergence'] #(report,'convergence')
142
+            #print  r['$'](report,'par')[13]
143
+            #print  r['$'](report,'par')[14]
144
+        else:
145
+            print("ERROR DETECTED, regressed values set to default")
146
+            b1 = 1e1
147
+            b2 = 1e-2
148
+            rT2 = 1e-2
149
+            #print r['$'](report,'par')[0]
150
+            #print r['$'](report,'par')[1]
151
+            #print r['$'](report,'par')[2]
152
+        return [b1,b2,rT2] 
153
+    else:
154
+        if not Error:
155
+            rT2 =  r['$'](report,'par')[1]
156
+            b2  =  r['$'](report,'par')[0]
157
+        else:
158
+            print("ERROR DETECTED, regressed values set to default")
159
+        return [b2, rT2] 
160
+
161
+#################################################
162
+# Regress for T2 using rpy2 interface
163
+def regressCurve2(peaks,times,sigma2=[None],intercept=True):
164
+
165
+    if sigma2[0] != None:
166
+        my_weights = robjects.FloatVector( sigma2 )
167
+
168
+    # TODO, if regression fails, it might be because there is no exponential
169
+    # term, maybe do a second regression then on a linear model. 
170
+    b1  = 0                  # Bias
171
+    b2  = 0                  # Linear 
172
+    bb2  = 0                 # Linear 
173
+    rT2 = 0.3                # T2 regressed
174
+    rrT2 = 1.3               # T2 regressed
175
+    r   = robjects.r         
176
+
177
+    # Variable shared between R and Python
178
+    robjects.globalenv['b1'] = b1
179
+    robjects.globalenv['b2'] = b2
180
+    robjects.globalenv['rT2'] = rT2
181
+    
182
+    robjects.globalenv['bb2'] = b2
183
+    robjects.globalenv['rrT2'] = rT2
184
+    
185
+    #robjects.globalenv['sigma2'] = sigma2
186
+    value = robjects.FloatVector(peaks)
187
+    times = robjects.FloatVector(numpy.array(times))
188
+    
189
+    
190
+    if (intercept):
191
+        my_list = robjects.r('list(b1=.50, b2=1e2, rT2=0.03, bb2=1e1, rrT2=1.3)')
192
+        my_lower = robjects.r('list(b1=0, b2=0, rT2=.005, bb2=0, rrT2=.005 )')
193
+        my_upper = robjects.r('list(b1=2000, b2=2000, rT2=.700, bb2=2000, rrT2=1.3 )')
194
+    else:
195
+        my_list  = robjects.r('list(b2=.5, rT2=0.3,  bb2=.5, rrT2=1.3)')
196
+        my_lower = robjects.r('list(b2=0,  rT2=.005, bb2=0,  rrT2=.005)')
197
+        my_upper = robjects.r('list(b2=1,  rT2=2.6,    bb2=1,  rrT2=2.6)')
198
+
199
+    my_cont = robjects.r('nls.control(maxiter=1000, warnOnly=TRUE, printEval=FALSE)')
200
+
201
+    
202
+    if (intercept):
203
+        #fmla = robjects.RFormula('value ~ b1 + exp(-times/rT2)')
204
+        fmla = robjects.Formula('value ~ b1 + b2*exp(-times/rT2) + bb2*exp(-times/rrT2)')
205
+        #fmla = robjects.RFormula('value ~ b1 + b2*times + exp(-times/rT2)')
206
+    else:
207
+        fmla = robjects.Formula('value ~ b2*exp(-times/rT2) + bb2*exp(-times/rrT2)')
208
+
209
+    env = fmla.getenvironment()
210
+    env['value'] = value
211
+    env['times'] = times
212
+    
213
+    # ugly, but I get errors with everything else I've tried
214
+    Error = False
215
+    #fit = robjects.r.nls(fmla,start=my_list,control=my_cont,weights=my_weights)
216
+    if (sigma2[0] != None):
217
+        #print("SIGMA 2")
218
+        #fit = robjects.r.tryCatch(robjects.r.suppressWarnings(robjects.r.nls(fmla,start=my_list,control=my_cont,algorithm="port", \
219
+        #                     weights=my_weights)), 'silent=TRUE')
220
+        fit = robjects.r.tryCatch(robjects.r.nls(fmla,start=my_list,control=my_cont,algorithm='port',weights=my_weights,lower=my_lower,upper=my_upper))#, \
127 221
                             # weights=my_weights))
128 222
     else:
129 223
         try:
130
-            fit = robjects.r.tryCatch(robjects.r.nls(fmla,start=my_list,control=my_cont,algorithm="port",lower=my_lower,upper=my_upper))
224
+            fit = robjects.r.tryCatch(robjects.r.nls(fmla,start=my_list,control=my_cont,algorithm="port"))#,lower=my_lower,upper=my_upper))
131 225
         except:
132 226
             print("regression issue pass")
133 227
             Error = True
@@ -156,41 +250,138 @@ def regressCurve(peaks,times,sigma2=None  ,intercept=True):
156 250
             #print r['$'](report,'par')[0]
157 251
             #print r['$'](report,'par')[1]
158 252
             #print r['$'](report,'par')[2]
159
-        return [b1,b2,rT2] 
253
+        return [b1,b2,rT2, bb2, rrT2] 
160 254
     else:
161 255
         if not Error:
162 256
             rT2 =  r['$'](report,'par')[1]
163 257
             b2  =  r['$'](report,'par')[0]
258
+            rrT2 =  r['$'](report,'par')[3]
259
+            bb2  =  r['$'](report,'par')[2]
164 260
         else:
165 261
             print("ERROR DETECTED, regressed values set to default")
166
-        return [b2, rT2] 
262
+        return [b2, rT2, bb2, rrT2] 
263
+
264
+def fun(x, t, y):
265
+    """ Cost function for regression, single exponential, no DC term 
266
+        x[0] = A0
267
+        x[1] = zeta 
268
+        x[2] = df
269
+        x[3] = T2
270
+    """
271
+    # concatenated real and imaginary parts  
272
+    pre =  np.concatenate((-x[0]*np.sin(2.*np.pi*x[2]*t + x[1])*np.exp(-t/x[3]), \
273
+                           +x[0]*np.cos(2.*np.pi*x[2]*t + x[1])*np.exp(-t/x[3])))  
274
+    return y-pre
275
+
276
+def fun2(x, t, y):
277
+    """ Cost function for regression, single exponential, no DC term 
278
+        x[0] = A0
279
+        x[1] = zeta 
280
+        x[2] = T2
281
+    """
282
+    # concatenated real and imaginary parts  
283
+    pre =  np.concatenate((x[0]*np.cos(x[1])*np.exp(-t/x[2]), \
284
+                       -1.*x[0]*np.sin(x[1])*np.exp(-t/x[2])))  
285
+    return y-pre
286
+
287
+
288
+def quadratureDetect2(X, Y, tt, x0="None"): 
289
+    """ Pure python quadrature detection using Scipy.  
290
+        X = real part of NMR signal 
291
+        Y = imaginary component of NMR signal 
292
+        tt = time 
293
+    """
294
+    print("Pure Python Quad Det")
295
+    # df 
296
+    if x0=="None":
297
+        x0 = np.array( [1., 0., 0., .2] )
298
+        res_lsq = least_squares(fun, x0, args=(tt, np.concatenate((X, Y))), loss='cauchy', f_scale=1.0,\
299
+            bounds=( [1., 0, -13, .005] , [1000., 2*np.pi, 13, .800] ))
300
+    else:
301
+        res_lsq = least_squares(fun, x0, args=(tt, np.concatenate((X, Y))), loss='cauchy', f_scale=1.0,\
302
+            bounds=( [1., 0, -13, .005] , [1000., 2*np.pi, 13, .800] ))
167 303
 
168
-def quadratureDetect(X, Y, tt):
169
-    
170
-    r   = robjects.r         
304
+        #bounds=( [0., 0, -20, .0] , [1., np.pi, 20, .6] ))
171 305
 
172
-    robjects.r(''' 
173
-         Xc <- function(E0, df, tt, phi, T2) {
174
-	            E0 * -sin(2*pi*df*tt + phi) * exp(-tt/T2)
175
-                }
306
+    x = res_lsq.x 
307
+    return res_lsq.success, x[0], x[2], x[1], x[3]
308
+    
309
+    # no df
310
+    #x = np.array( [1., 0., 0.2] )
311
+    #res_lsq = least_squares(fun2, x, args=(tt, np.concatenate((X, Y))), loss='soft_l1', f_scale=0.1)
312
+    #x = res_lsq.x 
313
+    #return conv, E0,df,phi,T2
314
+    #return res_lsq.success, x[0], 0, x[1], x[2]
176 315
 
177
-         Yc <- function(E0, df, tt, phi, T2) {
178
-	            E0 * cos(2*pi*df*tt + phi) * exp(-tt/T2)
179
-                } 
180
-         ''')  
316
+def quadratureDetect(X, Y, tt, CorrectFreq=False, BiExp=False, CorrectDC=False):
317
+ 
318
+    r   = robjects.r        
319
+
320
+    if CorrectDC:
321
+        robjects.r(''' 
322
+             Xc1 <- function(E01, df, tt, phi, T2_1, DC) {
323
+	                DC + E01*cos(2*pi*df*tt + phi) * exp(-tt/T2_1)
324
+            }
325
+    
326
+            Yc1 <- function(E01, df, tt, phi, T2_1, DC) {
327
+	                DC - E01*sin(2*pi*df*tt + phi) * exp(-tt/T2_1)
328
+            } 
329
+            ''')
330
+    else:   
331
+        robjects.r(''' 
332
+             Xc1 <- function(E01, df, tt, phi, T2_1) {
333
+	                E01*cos(2*pi*df*tt + phi) * exp(-tt/T2_1)
334
+            }
335
+    
336
+            Yc1 <- function(E01, df, tt, phi, T2_1) {
337
+	                -E01*sin(2*pi*df*tt + phi) * exp(-tt/T2_1)
338
+            } 
339
+            ''')
340
+
341
+    # bi-exponential 
342
+    if CorrectDC:
343
+        robjects.r(''' 
344
+             Xc2 <- function(E01, E02, df, tt, phi, T2_1, T2_2, DC) {
345
+	               DC + E01*cos(2*pi*df*tt + phi) * exp(-tt/T2_1) + 
346
+	                DC + E02*cos(2*pi*df*tt + phi) * exp(-tt/T2_2)
347
+            }
348
+
349
+            Yc2 <- function(E01, E02, df, tt, phi, T2_1, T2_2, DC) {
350
+	                DC - E01*sin(2*pi*df*tt + phi) * exp(-tt/T2_1) + 
351
+	                DC - E02*sin(2*pi*df*tt + phi) * exp(-tt/T2_2)
352
+            } 
353
+            ''')
354
+    else:   
355
+        robjects.r(''' 
356
+             Xc2 <- function(E01, E02, df, tt, phi, T2_1, T2_2) {
357
+	               E01*cos(2*pi*df*tt + phi) * exp(-tt/T2_1) + 
358
+	               E02*cos(2*pi*df*tt + phi) * exp(-tt/T2_2)
359
+            }
360
+
361
+            Yc2 <- function(E01, E02, df, tt, phi, T2_1, T2_2) {
362
+	                -E01*sin(2*pi*df*tt + phi) * exp(-tt/T2_1) + 
363
+	                -E02*sin(2*pi*df*tt + phi) * exp(-tt/T2_2)
364
+            } 
365
+            ''')
181 366
 
182 367
     # Make 0 vector 
183 368
     Zero = robjects.FloatVector(numpy.zeros(len(X)))
184 369
     
185 370
     # Fitted Parameters
186
-    E0 = 0.
371
+    E01 = 0.
372
+    E02 = 0.
187 373
     df = 0.
188 374
     phi = 0.
189
-    T2 = 0.
190
-    robjects.globalenv['E0'] = E0
375
+    T2_1 = 0.
376
+    T2_2 = 0.
377
+    DC = 0.
378
+    robjects.globalenv['DC'] = DC
379
+    robjects.globalenv['E01'] = E01
380
+    robjects.globalenv['E02'] = E02
191 381
     robjects.globalenv['df'] = df
192 382
     robjects.globalenv['phi'] = phi
193
-    robjects.globalenv['T2'] = T2
383
+    robjects.globalenv['T2_1'] = T2_1
384
+    robjects.globalenv['T2_2'] = T2_2
194 385
     XY = robjects.FloatVector(numpy.concatenate((X,Y)))
195 386
     
196 387
     # Arrays
@@ -199,10 +390,50 @@ def quadratureDetect(X, Y, tt):
199 390
     Y = robjects.FloatVector(numpy.array(Y))
200 391
     Zero = robjects.FloatVector(numpy.array(Zero))
201 392
 
202
-    #fmla = robjects.Formula('Zero ~ QI( E0, df, tt, phi, T2, X, Y )')
203
-    #fmla = robjects.Formula('X ~ Xc( E0, df, tt, phi, T2 )')
204
-    #fmla = robjects.Formula('Y ~ Yc( E0, df, tt, phi, T2 )')
205
-    fmla = robjects.Formula('XY ~ c(Xc( E0, df, tt, phi, T2 ), Yc( E0, df, tt, phi, T2 ))')
393
+    
394
+
395
+    if BiExp:
396
+        if CorrectDC:
397
+            fmla = robjects.Formula('XY ~ c(Xc2( E01, E02, df, tt, phi, T2_1, T2_2, DC ), Yc2( E01, E02, df, tt, phi, T2_1, T2_2, DC ))')
398
+            if CorrectFreq:    
399
+                start = robjects.r('list(E01=.100, E02=.01,   df=0,    phi=0.    ,  T2_1=.100, T2_2=.01, DC=0.0)')
400
+                lower = robjects.r('list(E01=1e-6, E02=1e-6,  df=-50,  phi=-3.14 ,  T2_1=.001, T2_2=.001, DC=0.0)')
401
+                upper = robjects.r('list(E01=1.00, E02=1.0,   df=50,   phi=3.14  ,  T2_1=.800, T2_2=.8, DC=0.5)')
402
+            else:
403
+                start = robjects.r('list(E01=.100, E02=.01,   phi=0.9   ,  T2_1=.100, T2_2=.01,  DC=0.0)')
404
+                lower = robjects.r('list(E01=1e-6, E02=1e-6,  phi=-3.14 ,  T2_1=.001, T2_2=.001, DC=0.0)')
405
+                upper = robjects.r('list(E01=1.00, E02=1.0,   phi=3.14  ,  T2_1=.800, T2_2=.8,   DC=0.5)')
406
+        else:
407
+            fmla = robjects.Formula('XY ~ c(Xc2( E01, E02, df, tt, phi, T2_1, T2_2 ), Yc2( E01, E02, df, tt, phi, T2_1, T2_2))')
408
+            if CorrectFreq:    
409
+                start = robjects.r('list(E01=.100, E02=.01,   df=0,    phi=0.    ,  T2_1=.100, T2_2=.01)')
410
+                lower = robjects.r('list(E01=1e-6, E02=1e-6,  df=-50,  phi=-3.14 ,  T2_1=.001, T2_2=.001)')
411
+                upper = robjects.r('list(E01=1.00, E02=1.0,   df=50,   phi=3.14  ,  T2_1=.800, T2_2=.8)')
412
+            else:
413
+                start = robjects.r('list(E01=.100, E02=.01,   phi=0.9   ,  T2_1=.100, T2_2=.01)')
414
+                lower = robjects.r('list(E01=1e-6, E02=1e-6,  phi=-3.14 ,  T2_1=.001, T2_2=.001)')
415
+                upper = robjects.r('list(E01=1.00, E02=1.0,   phi=3.14  ,  T2_1=.800, T2_2=.8)')
416
+    else: 
417
+        if CorrectDC:
418
+            fmla = robjects.Formula('XY ~ c(Xc1( E01, df, tt, phi, T2_1, DC), Yc1( E01, df, tt, phi, T2_1,DC))')
419
+            if CorrectFreq:    
420
+                start = robjects.r('list(E01=.100, df=0   , phi=0.   , T2_1=.100, DC=0.0)')
421
+                lower = robjects.r('list(E01=1e-6, df=-50., phi=-3.14, T2_1=.001, DC=0.0)')
422
+                upper = robjects.r('list(E01=1.00, df=50. , phi=3.14 , T2_1=.800, DC=0.5)')
423
+            else:
424
+                start = robjects.r('list(E01=.100, phi= 0.  , T2_1=.100, DC=0.0)')
425
+                lower = robjects.r('list(E01=1e-6, phi=-3.13, T2_1=.001, DC=0.0)')
426
+                upper = robjects.r('list(E01=1.00, phi= 3.13, T2_1=.800, DC=0.5)')
427
+        else:
428
+            fmla = robjects.Formula('XY ~ c(Xc1( E01, df, tt, phi, T2_1), Yc1( E01, df, tt, phi, T2_1))')
429
+            if CorrectFreq:    
430
+                start = robjects.r('list(E01=.100, df=0     , phi=0.   ,  T2_1=.100)')
431
+                lower = robjects.r('list(E01=1e-6, df=-50. , phi=-3.14 ,  T2_1=.001)')
432
+                upper = robjects.r('list(E01=1.00, df=50.  , phi=3.14  ,  T2_1=.800)')
433
+            else:
434
+                start = robjects.r('list(E01=.100, phi= 0.  , T2_1=.100)')
435
+                lower = robjects.r('list(E01=1e-6, phi=-3.13, T2_1=.001)')
436
+                upper = robjects.r('list(E01=1.00, phi= 3.13, T2_1=.800)')
206 437
 
207 438
     env = fmla.getenvironment()
208 439
     env['Zero'] = Zero
@@ -210,95 +441,51 @@ def quadratureDetect(X, Y, tt):
210 441
     env['Y'] = Y
211 442
     env['XY'] = XY 
212 443
     env['tt'] = tt
213
-    
214
-    # Bounds and control    
215
-    start = robjects.r('list(E0=100,   df= 0   , phi=   0.00,  T2=.100)')
216
-    lower = robjects.r('list(E0=1,     df=-13.0, phi=  -3.14,  T2=.005)')
217
-    upper = robjects.r('list(E0=1000,  df= 13.0, phi=   3.14,  T2=.800)')
218 444
 
219 445
     cont = robjects.r('nls.control(maxiter=10000, warnOnly=TRUE, printEval=FALSE)')
220 446
     
221 447
     fit = robjects.r.tryCatch(robjects.r.nls(fmla, start=start, control=cont, lower=lower, upper=upper, algorithm='port')) #, \
448
+    #fit = robjects.r.tryCatch(robjects.r.nls(fmla, start=start, control=cont)) #, \
222 449
     report =  r.summary(fit)
223
-    #print (report)
224
-    
225
-    E0  =  r['$'](report,'par')[0]
226
-    df  =  r['$'](report,'par')[1]
227
-    phi =  r['$'](report,'par')[2]
228
-    T2  =  r['$'](report,'par')[3]
229
-    #print ( E0,df,phi,T2 )
230
-    return E0,df,phi,T2
231
-    
232
-
233
-#################################################
234
-# Regress for T2 using rpy2 interface
235
-def regressSpec(w, wL, X): #,sigma2=1,intercept=True):
236 450
 
237
-    # compute s
238
-    s = -1j*w
239
-
240
-    # TODO, if regression fails, it might be because there is no exponential
241
-    # term, maybe do a second regression then on a linear model. 
242
-    a   = 0                  # Linear 
243
-    rT2 = 0.1                # T2 regressed
244
-    r   = robjects.r         
245
-
246
-    # Variable shared between R and Python
247
-    robjects.globalenv['a'] = a
248
-    #robjects.globalenv['w'] = w
249
-    robjects.globalenv['rT2'] = rT2
250
-    robjects.globalenv['wL'] = wL
251
-    robjects.globalenv['nb'] = 0
252
-
253
-    #s = robjects.ComplexVector(numpy.array(s))
254
-    w = robjects.FloatVector(numpy.array(w))
255
-    XX = robjects.FloatVector(X)
256
-    #Xr = robjects.FloatVector(numpy.real(X))
257
-    #Xi = robjects.FloatVector(numpy.imag(X))
258
-    #Xa = robjects.FloatVector(numpy.abs(X))
259
-    #Xri = robjects.FloatVector(numpy.concatenate((Xr,Xi)))
260
-    
261
-    #my_lower = robjects.r('list(a=.001, rT2=.001, nb=.0001)')
262
-    my_lower = robjects.r('list(a=.001, rT2=.001)')
263
-    #my_upper = robjects.r('list(a=1.5, rT2=.300, nb =100.)')
264
-    my_upper = robjects.r('list(a=1.5, rT2=.300)')
265
-     
266
-    #my_list = robjects.r('list(a=.2, rT2=0.03, nb=.1)')
267
-    my_list = robjects.r('list(a=.2, rT2=0.03)')
268
-    my_cont = robjects.r('nls.control(maxiter=5000, warnOnly=TRUE, printEval=FALSE)')
269
-    
270
-    #fmla = robjects.Formula('Xri ~ c(a*Re((wL) / (wL^2+(s+1/rT2)^2 )), a*Im((wL)/(wL^2 + (s+1/rT2)^2 )))') # envelope
271
-    ##fmla = robjects.Formula('Xri ~ c(a*Re((wL) / (wL^2+(s+1/rT2)^2 )), a*Im((wL)/(wL^2 + (s+1/rT2)^2 )))') # envelope
272
-    #fmla = robjects.Formula('XX ~ a*(wL) / (wL^2 + (s+1/rT2)^2 )') # complex
273
-    #fmla = robjects.Formula('Xa ~ abs(a*(wL) / (wL^2 + (s+1/rT2)^2 )) + nb') # complex
274
-    #fmla = robjects.Formula('XX ~ Re(a*( s + 1./rT2 )  / (wL^2 + (s+1/rT2)^2 ))') # complex
275
-    fmla = robjects.Formula('XX ~ a*(.5/rT2)  / ((1./rT2)^2 + (w-wL)^2 )')
276
-    #fmla = robjects.Formula('Xa ~ (s + 1./T2) / ( wL**2 + (1/T2 + 1j*w)**2 ) ')
277
- 
278
-    env = fmla.getenvironment()
279
-    #env['s'] = s
280
-    env['w'] = w
281
-    #env['Xr'] = Xr
282
-    #env['Xa'] = Xa
283
-    #env['Xi'] = Xi
284
-    #env['Xri'] = Xri
285
-    env['XX'] = XX
286
-     
287
-    #fit = robjects.r.tryCatch(robjects.r.nls(fmla,start=my_list, control=my_cont)) #, lower=my_lower, algorithm='port')) #, \
288
-    fit = robjects.r.tryCatch(robjects.r.nls(fmla, start=my_list, control=my_cont, lower=my_lower, upper=my_upper, algorithm='port')) #, \
289
-    report =  r.summary(fit)
290
-    #print report 
291
-    #print(r.warnings())
292
- 
293
-    a  =  r['$'](report,'par')[0]
294
-    rT2 =  r['$'](report,'par')[1]
295
-    nb =  r['$'](report,'par')[2]
451
+    conv = r['$'](fit,'convergence')[0]
452
+    #if conv:
453
+    #    print (report)
454
+    #    print ("conv", conv)
455
+    print ("Conv",  r['$'](fit,'convergence'))  # T2
456
+    print (report)
457
+    
458
+    if BiExp:
459
+        if CorrectFreq:    
460
+            E0   =  r['$'](report,'par')[0]   # E01
461
+            E0  +=  r['$'](report,'par')[1]   # E02
462
+            df  =  r['$'](report,'par')[2]   # offset
463
+            phi =  r['$'](report,'par')[3]   # phase 
464
+            T2  =  r['$'](report,'par')[4]   # T2
465
+        else:
466
+            E0   =  r['$'](report,'par')[0]   # E01
467
+            E0  +=  r['$'](report,'par')[1]   # E02
468
+            phi =  r['$'](report,'par')[2]   # phase 
469
+            T2  =  r['$'](report,'par')[3]   # T2
470
+    else:
471
+        if CorrectFreq:    
472
+            E0   =  r['$'](report,'par')[0]   # E01
473
+            df  =  r['$'](report,'par')[1]   # offset
474
+            phi =  r['$'](report,'par')[2]   # phase 
475
+            T2  =  r['$'](report,'par')[3]   # T2
476
+        else:
477
+            E0   =  r['$'](report,'par')[0]   # E01
478
+            phi =  r['$'](report,'par')[1]   # phase 
479
+            T2  =  r['$'](report,'par')[2]   # T2
480
+    #phi = 0.907655876627
481
+    #phi = 0
482
+    #print ("df", df)# = 0
483
+    return conv, E0,df,phi,T2
296 484
     
297
-    return a, rT2, nb
298 485
 
299 486
 #################################################
300 487
 # Regress for T2 using rpy2 interface
301
-def regressModulus(w, wL, X): #,sigma2=1,intercept=True):
488
+def regressSpec(w, wL, X): #,sigma2=1,intercept=True):
302 489
 
303 490
     # compute s
304 491
     s = -1j*w
@@ -355,11 +542,11 @@ def regressModulus(w, wL, X): #,sigma2=1,intercept=True):
355 542
     rT2 =  r['$'](report,'par')[1]
356 543
     nb =  r['$'](report,'par')[2]
357 544
     
358
-    return a, rT2
545
+    return a, rT2, nb
359 546
 
360 547
 #################################################
361 548
 # Regress for T2 using rpy2 interface
362
-def regressSpecComplex(w, wL, X, known=True, win=None): #,sigma2=1,intercept=True):
549
+def regressSpecComplex(w, wL, X): #,sigma2=1,intercept=True):
363 550
 
364 551
     # compute s
365 552
     s = -1j*w
@@ -394,19 +581,14 @@ def regressSpecComplex(w, wL, X, known=True, win=None): #,sigma2=1,intercept=Tru
394 581
      
395 582
     #print (numpy.shape(X))
396 583
     
397
-    #######################################################################
398
-
399
-    if known:
400
-        # known Frequency
401
-        my_lower = robjects.r('list(a=.001, rT2=.001, phi2=-3.14)')
402
-        my_upper = robjects.r('list(a=3.5, rT2=.300, phi2=3.14)')
403
-        my_list = robjects.r('list(a=.2, rT2=0.03, phi2=0)')
404
-    else:
405
-        # Unknown Frequency
406
-        my_lower = robjects.r('list(a=.001, rT2=.001, phi2=-3.14, wL2=wL-5)')
407
-        my_upper = robjects.r('list(a=3.5, rT2=.300, phi2=3.14, wL2=wL+5)')
408
-        my_list = robjects.r('list(a=.2, rT2=0.03, phi2=0, wL2=wL)')
409
-    
584
+    #my_lower = robjects.r('list(a=.001, rT2=.001, nb=.0001)')
585
+    #my_lower = robjects.r('list(a=.001, rT2=.001)') # Working
586
+    my_lower = robjects.r('list(a=.001, rT2=.001, phi2=-3.14, wL2=wL-5)')
587
+    #my_upper = robjects.r('list(a=1.5, rT2=.300, nb =100.)')
588
+    my_upper = robjects.r('list(a=3.5, rT2=.300, phi2=3.14, wL2=wL+5)')
589
+     
590
+    #my_list = robjects.r('list(a=.2, rT2=0.03, nb=.1)')
591
+    my_list = robjects.r('list(a=.2, rT2=0.03, phi2=0, wL2=wL)')
410 592
     my_cont = robjects.r('nls.control(maxiter=5000, warnOnly=TRUE, printEval=FALSE)')
411 593
     
412 594
     #fmla = robjects.Formula('Xri ~ c(a*Re((wL) / (wL^2+(s+1/rT2)^2 )), a*Im((wL)/(wL^2 + (s+1/rT2)^2 )))') # envelope
@@ -415,18 +597,7 @@ def regressSpecComplex(w, wL, X, known=True, win=None): #,sigma2=1,intercept=Tru
415 597
     
416 598
     #fmlar = robjects.Formula('Xr ~ (Kwr(a, phi2, s, rT2, wL)) ') # envelope
417 599
     #fmlai = robjects.Formula('Xi ~ (Kwi(a, phi2, s, rT2, wL)) ') # envelope
418
-    
419
-
420
-    
421
-    if known:
422
-        ###########################################3
423
-        # KNOWN freq 
424
-        fmla = robjects.Formula('Xri ~ c(Kwr(a, phi2, s, rT2, wL), Kwi(a, phi2, s, rT2, wL) ) ') # envelope
425
-    else:
426
-        ####################################################################################################3
427
-        # unknown frequency
428
-        fmla = robjects.Formula('Xri ~ c(Kwr(a, phi2, s, rT2, wL2), Kwi(a, phi2, s, rT2, wL2) ) ') # envelope
429
-
600
+    fmla = robjects.Formula('Xri ~ c(Kwr(a, phi2, s, rT2, wL2), Kwi(a, phi2, s, rT2, wL2) ) ') # envelope
430 601
     #fmla = robjects.Formula('Xri ~ (Kwri(a, phi2, s, rT2, wL)) ') # envelope
431 602
     
432 603
     #fmla = robjects.Formula('Xa ~ (abs(a*(sin(phi2)*s + ((1/rT2)*sin(phi2)) + wL*cos(phi2)) / (wL^2+(s+1/rT2)^2 )))') # envelope
@@ -451,9 +622,8 @@ def regressSpecComplex(w, wL, X, known=True, win=None): #,sigma2=1,intercept=Tru
451 622
     env['Xri'] = Xri
452 623
     env['XX'] = XX
453 624
      
454
-    #fit = robjects.r.tryCatch(robjects.r.nls(fmla,start=my_list, control=my_cont)) #, lower=my_lower, algorithm='port')) #, \
455
-    #fit = robjects.r.tryCatch(robjects.r.nls(fmlar, start=my_list, control=my_cont, lower=my_lower, upper=my_upper, algorithm='port')) #, \
456
-    fit = robjects.r.tryCatch(robjects.r.nls(fmla, start=my_list, control=my_cont, lower=my_lower, upper=my_upper, algorithm='port')) #, \
625
+    fit = robjects.r.tryCatch(robjects.r.nls(fmla,start=my_list, control=my_cont)) #, lower=my_lower, algorithm='port')) #, \
626
+    #fitr = robjects.r.tryCatch(robjects.r.nls(fmlar, start=my_list, control=my_cont, lower=my_lower, upper=my_upper, algorithm='port')) #, \
457 627
     
458 628
     #env = fmlai.getenvironment()
459 629
     #fiti = robjects.r.tryCatch(robjects.r.nls(fmlai, start=my_list, control=my_cont, lower=my_lower, upper=my_upper, algorithm='port')) #, \
@@ -466,7 +636,7 @@ def regressSpecComplex(w, wL, X, known=True, win=None): #,sigma2=1,intercept=Tru
466 636
     #print( reportr )
467 637
     #print( reporti  )
468 638
     #exit()
469
-    #print ( r.warnings())
639
+    #print  r.warnings()
470 640
  
471 641
     #a   =  (r['$'](reportr,'par')[0] + r['$'](reporti,'par')[0]) / 2.
472 642
     #rT2 =  (r['$'](reportr,'par')[1] + r['$'](reporti,'par')[1]) / 2.
@@ -475,8 +645,8 @@ def regressSpecComplex(w, wL, X, known=True, win=None): #,sigma2=1,intercept=Tru
475 645
     rT2 =  r['$'](report,'par')[1] 
476 646
     nb  =  r['$'](report,'par')[2] #phi2 
477 647
 
478
-    #print ("Python wL2", r['$'](report,'par')[3] )   
479
-    #print ("Python zeta", r['$'](report,'par')[2] )   
648
+    print ("Python wL2", r['$'](report,'par')[3] )   
649
+    print ("Python zeta", r['$'](report,'par')[2] )   
480 650
  
481 651
     return a, rT2, nb
482 652
 
@@ -517,27 +687,27 @@ if __name__ == "__main__":
517 687
     envelope   =  numpy.exp(-t/T2)
518 688
     renvelope  =  numpy.exp(-t/rT2)
519 689
 
520
-    outf = file('regress.txt','w')
521
-    for i in range(len(times)):
522
-        outf.write(str(times[i]) + "   " +  str(peaks[i]) + "\n")  
523
-    outf.close()
690
+    #outf = file('regress.txt','w')
691
+    #for i in range(len(times)):
692
+    #    outf.write(str(times[i]) + "   " +  str(peaks[i]) + "\n")  
693
+    #outf.close()
524 694
 
525
-    pylab.plot(t,data, 'b')
526
-    pylab.plot(t,cdata, 'g', linewidth=1)
527
-    pylab.plot(t,envelope, color='violet', linewidth=4)
528
-    pylab.plot(t,renvelope, 'r', linewidth=4)
529
-    pylab.plot(times, numpy.array(peaks), 'bo', markersize=8, alpha=.25)
530
-    pylab.legend(['noisy data','clean data','real envelope','regressed env','picks'])
531
-    pylab.savefig("regression.pdf")
695
+    plt.plot(t,data, 'b')
696
+    plt.plot(t,cdata, 'g', linewidth=1)
697
+    plt.plot(t,envelope, color='violet', linewidth=4)
698
+    plt.plot(t,renvelope, 'r', linewidth=4)
699
+    plt.plot(times, numpy.array(peaks), 'bo', markersize=8, alpha=.25)
700
+    plt.legend(['noisy data','clean data','real envelope','regressed env','picks'])
701
+    plt.savefig("regression.pdf")
532 702
 
533 703
 
534 704
     # FFT check
535 705
     fourier = fft(data)
536
-    pylab.figure()
706
+    plt.figure()
537 707
     freq = fftfreq(len(data), d=dt)
538
-    pylab.plot(freq, (fourier.real))
708
+    plt.plot(freq, (fourier.real))
539 709
     
540
-    pylab.show()
710
+    plt.show()
541 711
 
542 712
     # TODO do a bunch in batch mode to see if T2 estimate is better with or without 
543 713
     # weighting and which model is best.

+ 11
- 2
akvo/tressel/mrsurvey.py View File

@@ -16,6 +16,9 @@ import matplotlib.pyplot as plt
16 16
 import matplotlib.ticker 
17 17
 from matplotlib.ticker import MaxNLocator
18 18
 
19
+import multiprocessing 
20
+import itertools 
21
+
19 22
 import akvo.tressel.adapt as adapt
20 23
 #import akvo.tressel.cadapt as adapt # cython for more faster
21 24
 import akvo.tressel.decay as decay
@@ -528,7 +531,7 @@ class GMRDataProcessor(SNMRDataProcessor):
528 531
         NRmax = {}
529 532
         REmax = {}
530 533
         IMmax = {}
531
-
534
+        E0,phi,df,T2 = 100.,0,0,.2
532 535
         first = False
533 536
         self.sigma = {}
534 537
         for pulse in self.DATADICT["PULSES"]:
@@ -564,7 +567,13 @@ class GMRDataProcessor(SNMRDataProcessor):
564 567
                     IP[pulse][chan][ipm,:] = np.angle(ht)[clip::]
565 568
                     #############################################################
566 569
                     # Rotated amplitude
567
-                    [E0, df, phi, T2] = decay.quadratureDetect( ht.real, ht.imag, self.DATADICT[pulse]["TIMES"] )
570
+                    #if ipm != 0:
571
+                    [success, E0, df, phi, T2] = decay.quadratureDetect2( ht.real, ht.imag, self.DATADICT[pulse]["TIMES"], (E0,phi,df,T2))
572
+                    #[ E0, df, phi, T2] = decay.quadratureDetect( ht.real, ht.imag, self.DATADICT[pulse]["TIMES"] )
573
+                    #else:
574
+                    #    [success, E0, df, phi, T2] = decay.quadratureDetect2( ht.real, ht.imag, self.DATADICT[pulse]["TIMES"])
575
+                    #[success, E0, df, phi, T2] = decay.quadratureDetect( ht.real, ht.imag, self.DATADICT[pulse]["TIMES"] )
576
+                    print("success", success, "E0", E0, "phi", phi, "df", df, "T2", T2)
568 577
                     D = self.RotateAmplitude( ht.real, ht.imag, phi, df, self.DATADICT[pulse]["TIMES"] )
569 578
                     CA[pulse][chan][ipm,:] = D.imag[clip::]  # amplitude data 
570 579
                     NR[pulse][chan][ipm,:] = D.real[clip::]  # noise data

Loading…
Cancel
Save