-
Notifications
You must be signed in to change notification settings - Fork 2
/
robustunwrap.cpp
367 lines (286 loc) · 8.97 KB
/
robustunwrap.cpp
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*
3D Unwrapping algorithm
Rhodri Cusack 2000-2006
Algorithm described in
Cusack, R. & Papadakis, N. (2002)
"New robust 3-D phase unwrapping algorithms: application to magnetic field mapping and undistorting echoplanar images."
Neuroimage. 2002 Jul;16(3 Pt 1):754-64.
Distributed under MIT License
Comments to [email protected]
Version 3.00 Oct 2006 adapted for matlab
*/
#include "mex.h"
#include <stdio.h>
#include <string.h>
#include "math.h"
#include "getopt.h"
#include "matrix.h"
#define PI 3.14159265358979
#define FILEFORMAT_CAMRES 1
#define FILEFORMAT_ANALYZE 2
#define MAXFILENAMESIZE 1024
int errcode;
long dim[3];
long sze;
long polesze;
double *phase,*mag;
double *unwrapped;
bool *flag;
long m_bsx,m_bsy,m_bsz;
struct FIELD
{
double d; /* value of field */
long p[3]; /* at this offset */
int x,y,z;
};
struct QUEUEENTRY
{
int x,y,z;
long p;
double v;
};
struct FIELD_2
{
double d; /*value of field*/
long p; /*at this offset*/
int x,y,z;
};
void raiseerror(char *msg)
{
mexErrMsgTxt(msg);
errcode=1;
};
const long NUMQUEUES=10000;
const long DEFAULTBLOCK=100;
const long BLOCKINCREMENT=500;
long m_bot[NUMQUEUES], m_top[NUMQUEUES];
long m_size[NUMQUEUES], m_chunk[NUMQUEUES], m_sizeb[NUMQUEUES];
char *m_q[NUMQUEUES];
void InitQueue(int queuenum,int chunk)
{
m_chunk[queuenum]=chunk;
m_bot[queuenum]=0;
m_top[queuenum]=0;
m_size[queuenum]=DEFAULTBLOCK;
m_sizeb[queuenum]=m_size[queuenum]*m_chunk[queuenum];
m_q[queuenum]=0;
};
void TerminateQueue(int queuenum)
{
if (m_q[queuenum]) delete m_q[queuenum];
m_q[queuenum]=0;
};
int Push(int queuenum,void *x)
{
if (!m_q[queuenum]) m_q[queuenum]=new char[m_sizeb[queuenum]];
if (!m_q[queuenum])
{
printf("Out of memory - could not generate new point queue.");
return(-1);
};
int stacksize;
stacksize=m_top[queuenum]-m_bot[queuenum];
if (stacksize<0) stacksize+=m_size[queuenum];
memcpy(m_q[queuenum]+m_top[queuenum]*m_chunk[queuenum],x,m_chunk[queuenum]);
m_top[queuenum]++;
if (m_top[queuenum]==m_size[queuenum]) m_top[queuenum]=0;
if (m_top[queuenum]==m_bot[queuenum])
{
char *newq;
long newsize, newsizeb, abovebot_b;
// previously out of memory - now auto-expand
newsize=m_size[queuenum]+BLOCKINCREMENT;
newsizeb=newsize*m_chunk[queuenum];
newq=new char[newsizeb];
if (!newq)
{
printf("Out of memory - point queue full.");
return(-1);
};
// While we're shifting circular buffer, it is actually easier to re-origin it
// to zero.
// first, copy top bit from m_bot upwards
abovebot_b=(m_size[queuenum]-m_bot[queuenum])*m_chunk[queuenum];
if (abovebot_b>0) memcpy(newq,(char *)m_q[queuenum]+m_bot[queuenum]*m_chunk[queuenum],abovebot_b);
// then, do m_top downwards
if (m_top[queuenum]!=0) memcpy((char *) newq+abovebot_b,m_q[queuenum],m_top[queuenum]*m_chunk[queuenum]);
m_bot[queuenum]=0;
m_top[queuenum]=m_size[queuenum];
m_size[queuenum]=newsize;
m_sizeb[queuenum]=newsizeb;
delete m_q[queuenum]; // recover old memory
m_q[queuenum]=newq;
};
return(0);
};
int Pop(int queuenum,void *x)
{
if (m_bot[queuenum]==m_top[queuenum]) return(1);
memcpy(x,m_q[queuenum]+m_bot[queuenum]*m_chunk[queuenum],m_chunk[queuenum]);
m_bot[queuenum]++;
if (m_bot[queuenum]==m_size[queuenum]) m_bot[queuenum]=0;
return(0);
};
void Check(int primaryqueuenum, QUEUEENTRY* qe,long offp, int offx, int offy, int offz)
{
/* first check bounds */
QUEUEENTRY nqe;
nqe.x=qe->x+offx;
if ((nqe.x<0)||(nqe.x>=dim[0])) return;
nqe.y=qe->y+offy;
if ((nqe.y<0)||(nqe.y>=dim[1])) return;
nqe.z=qe->z+offz;
if ((nqe.z<0)||(nqe.z>=dim[2])) return;
nqe.p=qe->p+offp;
if (flag[nqe.p]) return; /* Already been here */
/* Actually do unwrap */
int wholepis;
wholepis=int((phase[nqe.p]-qe->v)/PI);
if (wholepis>=1)
nqe.v=(double) phase[nqe.p]-2*PI*int((wholepis+1)/2);
else if (wholepis<=-1)
nqe.v=(double) phase[nqe.p]+2*PI*int((1-wholepis)/2);
else nqe.v=phase[nqe.p];
unwrapped[nqe.p]=nqe.v;
flag[nqe.p]=true;
if (Push(primaryqueuenum,&nqe))
raiseerror("Out of memory!");
};
void unwrap(int seedx, int seedy, int seedz,long UNWRAPBINS)
{
long i;
long seedp;
errcode=0;
/* Minimum number of unwrapping bins is 2 */
if (UNWRAPBINS<2) UNWRAPBINS=2;
/* Find min and max */
double min,max;
min=(double) 1e38;
max=0;
for (i=0; i<sze; i++)
{
min=mag[i]<min?mag[i]:min;
max=mag[i]>max?mag[i]:max;
};
double diff;
diff=(double) 1.00001*(max-min);
seedp=seedx+dim[0]*(seedy+dim[1]*seedz);
flag=new bool[sze];
if (!flag) raiseerror("Out of memory. ");
for (i=0; i<sze; i++)
flag[i]=false;
for (i=0; i<UNWRAPBINS; i++)
InitQueue(i,sizeof(QUEUEENTRY));
QUEUEENTRY qe;
qe.p=seedp;
qe.x=seedx;
qe.y=seedy;
qe.z=seedz;
unwrapped[85]=phase[85];
unwrapped[seedp]=qe.v=phase[seedp];
flag[seedp]=true;
/* push seed */
Push(0,&qe);
int opc,pc;
opc=-1;
/* First, work out pole field threshold that we're going to use */
double *polefieldthresholds;
int ind=0;
int voxdone,voxdef;
polefieldthresholds=new double [UNWRAPBINS];
voxdef=voxdone=0;
for (i=0; i<(UNWRAPBINS); i++)
polefieldthresholds[ind++]=min+diff*i/(UNWRAPBINS-1);
opc=-10;
for (i=0; i<UNWRAPBINS ; i++)
{
voxdef=0;
while (!errcode && !Pop(i,&qe))
{
if (mag[qe.p]>polefieldthresholds[i]) /* too close to a scary pole, so just defer by pushing to other stack */
{
ind=i;
while (mag[qe.p]>polefieldthresholds[++ind]);
Push(ind,&qe); /* just defer by pushing to relevant stack */
voxdef++;
}
else
{
Check(i,&qe,+m_bsz,0,0,1);
Check(i,&qe,-m_bsz,0,0,-1);
Check(i,&qe,+m_bsy,0,1,0);
Check(i,&qe,-m_bsy,0,-1,0);
Check(i,&qe,+m_bsx,1,0,0);
Check(i,&qe,-m_bsx,-1,0,0);
voxdone++;
};
};
TerminateQueue(i); /* done with this Queue so free up memory */
if (errcode) break;
};
delete flag;
};
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
long i,j,k;
int seedx,seedy,seedz;
double *voxdims;
int ndims;
int numunwrapbins;
/* Check for proper number of arguments. */
if (nrhs <3) {
mexErrMsgTxt("Robust unwrapping algorithm as in Cusack & Papadakis (2002).\nExpect at least 3 input arguments, unwrappeddata=unwrap([seed coords, 3 vector],[phase data, 3D double array],[magnitude data, 3D double array],{[numunwrapbins]}) ");
} else if (nlhs > 1) {
mexErrMsgTxt("Too many output arguments");
}
/* The input must be a noncomplex scalar double.*/
ndims = mxGetNumberOfDimensions(prhs[1]);
if (!mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) || ndims!=3) {
mexErrMsgTxt("Data to be unwrapped must be a double 3D matrix.");
}
if (!mxIsDouble(prhs[2]) || mxIsComplex(prhs[2]) || ndims!=3) {
mexErrMsgTxt("Data to be unwrapped must be a double 3D matrix.");
}
if ( mxIsComplex(prhs[0])) {
mexErrMsgTxt("Voxel dimensions should not be complex.");
}
const int *dims;
double *maginput;
dims=mxGetDimensions(prhs[1]);
sze=1;
for (i=0; i<3; i++)
{
sze*=dims[i];
dim[i]=dims[i];
};
/* Create matrix for the return argument. */
plhs[0] = mxCreateNumericArray(ndims,dims, mxDOUBLE_CLASS,mxREAL);
voxdims=mxGetPr(prhs[0]);
seedx=int(voxdims[0])-1;
seedy=int(voxdims[1])-1;
seedz=int(voxdims[2])-1;
if (seedx<0 || seedx>=dims[0] || seedy<0 || seedy>=dims[1] || seedz<0 || seedz>=dims[2])
mexErrMsgTxt("The seed specified was outside the matrix bounds.");
phase=mxGetPr(prhs[1]);
/* Negate input as low polefield values unwrapped first */
maginput=mxGetPr(prhs[2]);
mag=new double[sze];
for(i=0; i<sze; i++)
mag[i]=-maginput[i];
unwrapped=mxGetPr(plhs[0]);
if (nrhs==4)
{
if (!mxIsDouble(prhs[3]) || mxIsComplex(prhs[3]))
{
mexErrMsgTxt("Number of unwrapping bins should be a non-complex double.");
}
numunwrapbins=int(*mxGetPr(prhs[3]));
}
else
numunwrapbins=10000;
m_bsx=1;
m_bsy=dims[0];
m_bsz=dims[0]*dims[1];
/* Assign pointers to each input and output. */
unwrap(seedx,seedy,seedz,numunwrapbins);
}