EyesisAberrations.java 264 KB
Newer Older
Andrey Filippov's avatar
Andrey Filippov committed
1
package com.elphel.imagej.calibration;
Andrey Filippov's avatar
Andrey Filippov committed
2 3 4
import java.awt.Rectangle;
import java.io.File;
import java.util.ArrayList;
5
import java.util.Arrays;
Andrey Filippov's avatar
Andrey Filippov committed
6 7 8 9 10 11
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;

import javax.swing.SwingUtilities;

Andrey Filippov's avatar
Andrey Filippov committed
12 13
import com.elphel.imagej.common.DoubleFHT;
import com.elphel.imagej.common.DoubleGaussianBlur;
14
import com.elphel.imagej.common.ShowDoubleFloatArrays;
15
import com.elphel.imagej.common.WindowTools;
Andrey Filippov's avatar
Andrey Filippov committed
16
import com.elphel.imagej.jp4.JP46_Reader_camera;
17
import com.elphel.imagej.lwir.LwirReaderParameters;
Andrey Filippov's avatar
Andrey Filippov committed
18

19 20 21 22 23 24 25 26 27 28
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.Prefs;
import ij.gui.GenericDialog;
import ij.io.FileSaver;
import ij.io.Opener;
import ij.process.FloatProcessor;
import ij.process.ImageProcessor;

Andrey Filippov's avatar
Andrey Filippov committed
29 30 31
public class EyesisAberrations {
	public double [][][][] pdfKernelMap=null;
	JP46_Reader_camera JP4_INSTANCE=       new JP46_Reader_camera(false);
32
	ShowDoubleFloatArrays SDFA_INSTANCE=   new ShowDoubleFloatArrays();
Andrey Filippov's avatar
Andrey Filippov committed
33 34 35
    public AtomicInteger stopRequested=null; // 1 - stop now, 2 - when convenient
	public Distortions distortions=null;
	public AberrationParameters aberrationParameters=null;
36

Andrey Filippov's avatar
Andrey Filippov committed
37 38 39 40 41 42 43 44
    public EyesisAberrations (AtomicInteger stopRequested,
    		AberrationParameters aberrationParameters){
    	this.stopRequested=stopRequested;
    	this.aberrationParameters=aberrationParameters;
    }
   	public void setDistortions(Distortions distortions){
		this.distortions=distortions;
	}
45

Andrey Filippov's avatar
Andrey Filippov committed
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
   	int countExistentFiles(String directory,String [] paths, boolean remove){
   		int numFiles=0;
   		for (int i=0;i<paths.length;i++) if (paths[i]!=null){
   			String path= ( (directory!=null)?(directory+Prefs.getFileSeparator()):"")+paths[i];
   			if ((new File(path)).exists()) {
   				numFiles++;
   			} else if (remove) {
   				paths[i]=null;
   			}
   		}
   		return numFiles;
   	}

  	public boolean reverseKernels(
		    AtomicInteger stopRequested, // 1 - stop now, 2 - when convenient
  			EyesisAberrations.InverseParameters inverseParameters, // size (side of square) of direct PSF kernel
   			boolean                saveResult,
   			boolean                showResult,
   			boolean                updateStatus,          // UPDATE_STATUS
   			int                    threadsMax,
   			int                    globalDebugLevel
   	){
   		if ((this.aberrationParameters.aberrationsKernelDirectory==null) || (this.aberrationParameters.aberrationsKernelDirectory.length()==0)){
   			if (aberrationParameters.selectAberrationsKernelDirectory(true, this.aberrationParameters.aberrationsKernelDirectory, false)==null) {
   				String msg = "Nothing selected";
   				System.out.println("Warning"+msg);
   				IJ.showMessage("Warning",msg);
   				return false;
   			}
   		}
   		int numChannels=distortions.fittingStrategy.distortionCalibrationData.getNumChannels(); // number of used channels
    	boolean [] selectedChannels=this.aberrationParameters.getChannelSelection(distortions);
		String [] srcPaths=    new String[numChannels];
		String [] resultPaths= new String[numChannels];
		int numToProcess=0;
    	for (int nChn=0;nChn<selectedChannels.length;nChn++){
    		if (!selectedChannels[nChn]){
    			srcPaths[nChn]=null;
    			resultPaths[nChn]=null;
    		} else {
    			srcPaths[nChn]=this.aberrationParameters.psfKernelDirectory+Prefs.getFileSeparator()+
       			this.aberrationParameters.interpolatedPSFPrefix+String.format("%02d", nChn)+
       			this.aberrationParameters.interpolatedPSFSuffix;
    			resultPaths[nChn]=this.aberrationParameters.aberrationsKernelDirectory+Prefs.getFileSeparator()+
       			this.aberrationParameters.aberrationsPrefix+String.format("%02d", nChn)+
       			this.aberrationParameters.aberrationsSuffix;
    			if (!this.aberrationParameters.overwriteResultFiles && (new File(resultPaths[nChn])).exists()) {
    				srcPaths[nChn]=null;
    				if (globalDebugLevel>0) System.out.println("File "+resultPaths[nChn]+" already exists and overwrite is disabled in configuration, channel "+nChn+" will be skipped");
    			}
    			numToProcess++;
    		}
    	}
    	if (numToProcess==0){
				String msg = "No kernels to process";
   				System.out.println("Warning"+msg);
   				IJ.showMessage("Warning",msg);
   				return false;
    	}
   		int numProcessed=0;
   		Opener opener=new Opener();
   		ImagePlus impSpsf;
		long startTime=System.nanoTime(); // restart timer after possible interactive dialogs
   		for (int nChn=0;nChn<numChannels;nChn++) if (srcPaths[nChn]!=null){
   			if (!(new File(srcPaths[nChn])).exists()) {
   				String msg = "Interpolated PSF kernel stack for channel #"+nChn+": "+srcPaths[nChn]+" does not exist";
   				System.out.println("Warning"+msg);
   				continue;
   			}
   			impSpsf=opener.openImage("", srcPaths[nChn]);
   			if (impSpsf==null) {
   				System.out.println("Failed to open interpolated PSF kernel stack "+srcPaths[nChn]);
   				continue;
   			}
120 121
   			if ((impSpsf.getStackSize() < 3) && (impSpsf.getStackSize() != 1)) {
   				System.out.println("Need a 3-layer stack (for color) or single (for mono) with interpolated PSF kernels");
Andrey Filippov's avatar
Andrey Filippov committed
122 123
   				continue;
   			}
124

Andrey Filippov's avatar
Andrey Filippov committed
125 126 127 128 129
   			ImageStack stack= reversePSFKernelStack(
   					impSpsf.getStack(), // stack of 3 32-bit (float) images, made of square kernels
   					inverseParameters, // size (side of square) of direct PSF kernel
   					threadsMax, // size (side of square) of reverse PSF kernel
   					updateStatus,
130
   					globalDebugLevel);
Andrey Filippov's avatar
Andrey Filippov committed
131 132 133 134 135 136 137 138 139 140 141

   			ImagePlus impInvertedPSF = new ImagePlus("interpolated kernel stack", stack);
   			JP46_Reader_camera jp4_instance= new JP46_Reader_camera(false);
   			jp4_instance.decodeProperiesFromInfo(impSpsf);
   			// copy properties from the source image
   			jp4_instance.copyProperties (impSpsf,impInvertedPSF);
   			inverseParameters.setProperties("INVERSE.", impInvertedPSF);
   			jp4_instance.encodeProperiesToInfo(impInvertedPSF);
   			if (showResult) {
   				impInvertedPSF.getProcessor().resetMinAndMax(); // imp_psf will be reused
   				impInvertedPSF.show();
142
   			}
Andrey Filippov's avatar
Andrey Filippov committed
143 144 145
   			if (saveResult){
   				if (globalDebugLevel>0) System.out.println((numProcessed+1)+" of "+numToProcess+": saving invered (of the file"+srcPaths[nChn]+") kernel to "+resultPaths[nChn]+ " at "+ IJ.d2s(0.000000001*(System.nanoTime()-startTime),3));
   				FileSaver fs=new FileSaver(impInvertedPSF);
146 147 148
//   				fs.saveAsTiffStack(resultPaths[nChn]);
   				fs.saveAsTiff(resultPaths[nChn]);

Andrey Filippov's avatar
Andrey Filippov committed
149 150
   			}
   			numProcessed++;
151
    		if 	(stopRequested.get()>0) {
Andrey Filippov's avatar
Andrey Filippov committed
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
				if (globalDebugLevel>0) System.out.println("User requested stop");
				break;
    		}
   		}
   		if (numProcessed>0){
			if (globalDebugLevel>0) {
				System.out.println("Inverted "+numProcessed+" kernel stacks at "+ IJ.d2s(0.000000001*(System.nanoTime()-startTime),3));
			}
   		} else {
				String msg = "No kernel files to invert";
   				System.out.println("Warning"+msg);
   				return false;
   		}
   		return true;
   	}
167

Andrey Filippov's avatar
Andrey Filippov committed
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
	public ImageStack  reversePSFKernelStack(
			final ImageStack            PSFStack, // stack of 3 32-bit (float) images, made of square kernels
			final EyesisAberrations.InverseParameters inverseParameters, // size (side of square) of direct PSF kernel
			final int                 threadsMax, // size (side of square) of reverse PSF kernel
			final boolean           updateStatus,
			final int globalDebugLevel){  // update status info
		if (PSFStack==null) return null;
		final int tilesX=PSFStack.getWidth()/inverseParameters.dSize;
		final int tilesY=PSFStack.getHeight()/inverseParameters.dSize;
		final int nChn=PSFStack.getSize();
		final double [] sigmas={inverseParameters.blurIndividual,inverseParameters.blurIndividual,inverseParameters.blurChecker};
		final float [][] outPixels=new float[nChn][tilesX*inverseParameters.rSize*tilesY*inverseParameters.rSize];
		final Thread[] threads = newThreadArray(threadsMax);
		final AtomicInteger ai = new AtomicInteger(0);
		final int numberOfKernels=     tilesY*tilesX*nChn;
		final int numberOfKernelsInChn=tilesY*tilesX;
		for (int ithread = 0; ithread < threads.length; ithread++) {
			threads[ithread] = new Thread() {
186
				@Override
Andrey Filippov's avatar
Andrey Filippov committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
				public void run() {
					float [] pixels=null;
					double [] kernel= new double[inverseParameters.dSize*inverseParameters.dSize];
					double [] rKernel=new double[inverseParameters.rSize*inverseParameters.rSize];
					int  [][]selection;
					double [] ellipse_coeff;
					double [] variableSigmas;
					int chn,tileY,tileX;
					int chn0=-1;
					DoubleFHT fht_instance =new DoubleFHT(); // provide DoubleFHT instance to save on initializations (or null)
					for (int nTile = ai.getAndIncrement(); nTile < numberOfKernels; nTile = ai.getAndIncrement()) {
						chn=nTile/numberOfKernelsInChn;
						tileY =(nTile % numberOfKernelsInChn)/tilesX;
						tileX = nTile % tilesX;
						if (updateStatus) IJ.showStatus("Invertinging PSF, channel "+(chn+1)+" of "+nChn+", row "+(tileY+1)+" of "+tilesY);
						if (chn!=chn0) {
							pixels=(float[]) PSFStack.getPixels(chn+1);
							chn0=chn;
						}
206
						extractOneKernel( pixels, //  array of combined square kernels, each
Andrey Filippov's avatar
Andrey Filippov committed
207 208 209 210
								kernel, // will be filled, should have correct size before call
								tilesX, // number of kernels in a row
								tileX, // horizontal number of kernel to extract
								tileY); // vertical number of kernel to extract
Andrey Filippov's avatar
Andrey Filippov committed
211
						/* Find direct kernel approximation ellipse, increase it, mirror center around 0,0 and use it as a mask for the reversed kernel */
Andrey Filippov's avatar
Andrey Filippov committed
212 213 214 215
						selection=    findClusterOnPSF(kernel,  inverseParameters.psfCutoffEnergy, "",globalDebugLevel);
						ellipse_coeff=findEllipseOnPSF(kernel,  selection, "",globalDebugLevel); // coefficients for direct PSF, for rPSF [0] and [1] need to be opposite size

						rKernel=resizeForFFT(kernel,inverseParameters.rSize);
Andrey Filippov's avatar
Andrey Filippov committed
216
/* Apply variable blur to direct kernel using it's center X,Y */
Andrey Filippov's avatar
Andrey Filippov committed
217 218 219 220 221 222 223 224 225 226
						if (inverseParameters.filterDirect) {
							variableSigmas= createSigmasFromCenter(inverseParameters.rSize, // side of square
									inverseParameters.sigmaToRadiusDirect, // variable blurring - sigma will be proportional distance from the center
									sigmas[chn]*inverseParameters.sigmaScaleDirect, //blurring in the center sigma(r)=sqrt((sigma_to_radius*r)^2)+center_sigma^2)
									ellipse_coeff[0], // coordinates of the center (0:0 - size/2: size/2)
									ellipse_coeff[1]);
							rKernel=variableGaussBlurr(          rKernel, // input square pixel array, preferably having many exact zeros (they will be skipped)
									variableSigmas, // array of sigmas to be used for each pixel, matches pixels[]
									3.5, // drop calculatin if farther then nSigma
									0, // int WOICenterX, // window of interest in pixels[] array - do not generate data outside it
227
									0, // int WOICenterY, //
Andrey Filippov's avatar
Andrey Filippov committed
228 229 230 231
									inverseParameters.rSize, //int WOIWidth, reduce later
									inverseParameters.rSize, //int WOIHeight)
									globalDebugLevel);
						}
232

Andrey Filippov's avatar
Andrey Filippov committed
233
/* reverse PSF kernel */
Andrey Filippov's avatar
Andrey Filippov committed
234 235 236 237 238 239
						rKernel= cleanupAndReversePSF (rKernel,  // input pixels
								inverseParameters,
								//    						  false,  // fold high frequency into low, when false - use Hamming to cut off high frequencies
								fht_instance,
						"",
						globalDebugLevel); // just for the plot names
Andrey Filippov's avatar
Andrey Filippov committed
240
/*  mask  the reversed kernel */
Andrey Filippov's avatar
Andrey Filippov committed
241 242 243 244 245 246
						rKernel= maskReversePSFKernel(rKernel, // reversed psf, square array
								ellipse_coeff, // ellipse coefficients from _direct_ kernel
								inverseParameters.psfEllipseScale,
								inverseParameters.rpsfMinMaskThreshold); // zero output element if elliptical Gauss mask is below this threshold

						normalizeKernel(rKernel); // in-place
Andrey Filippov's avatar
Andrey Filippov committed
247
/* Apply variable blur to inversed kernel, using (and reversing sign) the center X,Y from the direct kernel */
Andrey Filippov's avatar
Andrey Filippov committed
248 249 250 251 252 253 254 255 256 257
						if (inverseParameters.filter) {
							variableSigmas= createSigmasFromCenter(inverseParameters.rSize, // side of square
									inverseParameters.sigmaToRadius, // variable blurring - sigma will be proportional distance from the center
									sigmas[chn]*inverseParameters.sigmaScale, //blurring in the center sigma(r)=sqrt((sigma_to_radius*r)^2)+center_sigma^2)
									-ellipse_coeff[0], // coordinates of the center (0:0 - size/2: size/2)
									-ellipse_coeff[1]);
							rKernel=variableGaussBlurr(          rKernel, // input square pixel array, preferrably having many exact zeros (they will be skipped)
									variableSigmas, // array of sigmas to be used for each pixel, matches pixels[]
									3.5, // drop calculation if farther then nSigma
									0, // int WOICenterX, // window of interest in pixels[] array - do not generate data outside it
258
									0, // int WOICenterY, //
Andrey Filippov's avatar
Andrey Filippov committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
									inverseParameters.rSize, //int WOIWidth, reduce later
									inverseParameters.rSize,
									globalDebugLevel); //int WOIHeight)

						}
						//TODO: verify if it is OK that sum changed (was 10.5) after variableGaussBlurr(), for now - just re-calibrate
						normalizeKernel(rKernel); // in-place

						storeOneKernel( outPixels[chn], // float [] array of combined square kernels - will be filled
								rKernel, // square kernel to store
								tilesX, // number of kernels in a row
								tileX, // horizontal number of kernel to store
								tileY); // vertical number of kernel to store

					}
				}
			};
		}
		startAndJoin(threads);
		//	  System.out.println("Threads done at "+IJ.d2s(0.000000001*(System.nanoTime()-startTime),3));
Andrey Filippov's avatar
Andrey Filippov committed
279
/* prepare result stack to return */
Andrey Filippov's avatar
Andrey Filippov committed
280 281 282 283 284 285
		final ImageStack outStack=new ImageStack(tilesX*inverseParameters.rSize,tilesY*inverseParameters.rSize);
		for (int chn=0;chn<nChn;chn++) {
			outStack.addSlice(PSFStack.getSliceLabel(chn+1), outPixels[chn]);
		}
		return outStack;
	}
286

Andrey Filippov's avatar
Andrey Filippov committed
287
	/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
Andrey Filippov's avatar
Andrey Filippov committed
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
	private double [] maskReversePSFKernel( double []rpsf_pixels, // reversed psf, square array
			double [] ellipse_coeff, // ellipse coefficients from _direct_ kernel
			double ellipse_scale,
			double min_mask_threshold) // zero output element if elliptical Gauss mask is below this threshold
	{
		int rpsf_size=(int)Math.sqrt(rpsf_pixels.length);
		double [] masked_rpsf=new double[rpsf_size*rpsf_size];
		int ix,iy;
		double x,y,r2;
		int indx=0;
		double k2=1/ellipse_scale/ellipse_scale;
		double m;
		for (iy=0;iy<rpsf_size;iy++) {
			y=iy-rpsf_size/2+ellipse_coeff[1];  // move center opposite to that of direct kernel (psf)
			for (ix=0;ix<rpsf_size;ix++) {
				x=ix -rpsf_size/2 +ellipse_coeff[0]; //  move center opposite to that of direct kernel (psf)
				r2=ellipse_coeff[2]*x*x+ellipse_coeff[3]*y*y+ellipse_coeff[4]*x*y;
				m=Math.exp(-k2*r2);
				masked_rpsf[indx]=(m>=min_mask_threshold)?(rpsf_pixels[indx]*Math.exp(-k2*r2)):0.0;
				indx++;
			}
		}
		return masked_rpsf;
	}

Andrey Filippov's avatar
Andrey Filippov committed
313
	/* ======================================================================== */
314 315


Andrey Filippov's avatar
Andrey Filippov committed
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
	private  double [] createSigmasFromCenter(
			int               size, // side of square
			double sigma_to_radius, // variable blurring - sigma will be proportional distance from the center
			double    center_sigma, //blurring in the center sigma(r)=sqrt((sigma_to_radius*r)^2)+center_sigma^2)
			double         centerX, // coordinates of the center (0:0 - size/2: size/2)
			double         centerY) {
		double [] sigmas = new double [size*size];
		int i,j;
		double x,y;
		double center_sigma2=center_sigma*center_sigma;
		double sigma_to_radius2=sigma_to_radius*sigma_to_radius;
		for (i=0;i<size;i++) for (j=0;j<size;j++) {
			y=i-size/2-centerY;
			x=j-size/2-centerX;
			sigmas[i*size+j]=Math.sqrt((x*x+y*y)*sigma_to_radius2+ center_sigma2);
		}
		return sigmas;
	}

335 336


Andrey Filippov's avatar
Andrey Filippov committed
337
	/* ======================================================================== */
Andrey Filippov's avatar
Andrey Filippov committed
338 339 340 341 342 343 344 345 346 347 348 349 350
	public double [] cleanupAndReversePSF (double []   psf_pixels,  // input pixels
			EyesisAberrations.InverseParameters inverseParameters, // size (side of square) of direct PSF kernel
			DoubleFHT fht_instance,  // provide DoubleFHT instance to save on initializations (or null)
			String           title,   // just for the plot names
			int debugLevel
	) {
		int size=(int) Math.sqrt(psf_pixels.length);
		double[][][] fft_complex;
		int i,j,ix,iy;
		double a,k,r,r2,k2;

		double [] cpixels=psf_pixels.clone();
		if (fht_instance==null) fht_instance=new DoubleFHT(); // move upstream to reduce number of initializations
Andrey Filippov's avatar
Andrey Filippov committed
351
/* Swapping quadrants, so the center will be 0,0 */
Andrey Filippov's avatar
Andrey Filippov committed
352
		fht_instance.swapQuadrants(cpixels);
Andrey Filippov's avatar
Andrey Filippov committed
353
/* get to frequency domain */
Andrey Filippov's avatar
Andrey Filippov committed
354
		fht_instance.transform(cpixels);
Andrey Filippov's avatar
Andrey Filippov committed
355
/* Convert from FHT to complex FFT - avoid that in the future, process FHT directly*/
Andrey Filippov's avatar
Andrey Filippov committed
356 357 358 359 360 361 362
		fft_complex= FHT2FFTHalf (cpixels,size);
		double [][]fft_energy=new double[(size/2)+1][size];
		for (i=0;i<(size/2+1);i++) for (j=0;j<size;j++) {
			fft_energy[i][j]=fft_complex[i][j][0]*fft_complex[i][j][0]+fft_complex[i][j][1]*fft_complex[i][j][1];
		}
		int  [][] clusterPS = findClusterOnPS(fft_energy, inverseParameters.otfCutoffEnergy,title,debugLevel);
		double [] ellipse_coeff = findEllipseOnPS(fft_energy, clusterPS, title,debugLevel);
Andrey Filippov's avatar
Andrey Filippov committed
363 364
/* create ellipse window using Hamming */
/* TODO: scale radius */
Andrey Filippov's avatar
Andrey Filippov committed
365 366 367 368 369 370 371 372 373 374 375 376 377 378
		double [][] ellipseMask=new double [size/2+1][size];
		k2=1/inverseParameters.otfEllipseScale/inverseParameters.otfEllipseScale;
		for (i=0;i<(size/2+1);i++) for (j=0;j<size;j++) {
			iy=(i==size/2)?-i:i;
			ix=(j>=(size/2))?(j-size):j;
			if (iy<0) ix=-ix;
			r2=ellipse_coeff[0]*ix*ix+ellipse_coeff[1]*iy*iy+ellipse_coeff[2]*ix*iy;
			if (inverseParameters.otfEllipseGauss){
				ellipseMask[i][j]=Math.exp(-k2*r2);
			} else {
				r=Math.sqrt(r2)/inverseParameters.otfEllipseScale;
				ellipseMask[i][j]=(r>1.0)?0.0:(0.54+0.46*Math.cos(r*Math.PI));
			}
		}
Andrey Filippov's avatar
Andrey Filippov committed
379
/* optionally display selection */
Andrey Filippov's avatar
Andrey Filippov committed
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
		if (debugLevel>2) {
			ImageProcessor ip_ellipse = new FloatProcessor(size,size);
			float [] ellipsePixels = new float [size*size];
			for (i=0;i<ellipsePixels.length;i++) {
				iy=i/size-size/2;
				ix=i%size-size/2;
				if (iy<0) {
					ix=-ix;
					iy=-iy;
				}
				ix= (ix+size) % size;
				ellipsePixels[i]= (float) ellipseMask[iy][ix];
			}
			ip_ellipse.setPixels(ellipsePixels);
			ip_ellipse.resetMinAndMax();
			ImagePlus imp_ellipse= new ImagePlus(title+"_EL-MASK_"+ inverseParameters.otfCutoffEnergy+"-"+inverseParameters.otfEllipseScale, ip_ellipse);
			imp_ellipse.show();
		}

Andrey Filippov's avatar
Andrey Filippov committed
399
/* inverse fft_complex */
Andrey Filippov's avatar
Andrey Filippov committed
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
		if (inverseParameters.invertRange>0.0) {
			/// Invert Z for large values, but make them Z - for small ones. So it will be a mixture of correlation and deconvolution
			//here the targets are round, but what will th\be the colrrect way fo assymmetrical ones?
			/// First - find maximal value
			double fft_max=0;
			for (i=0;i<fft_complex.length; i++) for (j=0;j<fft_complex[0].length;j++) {
				r2=fft_complex[i][j][0]*fft_complex[i][j][0]+fft_complex[i][j][1]*fft_complex[i][j][1];
				if (r2>fft_max) fft_max=r2;
			}
			k=Math.sqrt(fft_max)*inverseParameters.invertRange;
			k2=k*k;
			for (i=0;i<fft_complex.length; i++) for (j=0;j<fft_complex[0].length;j++) {
				r=Math.sqrt(fft_complex[i][j][0]*fft_complex[i][j][0]+fft_complex[i][j][1]*fft_complex[i][j][1]);
				a=-Math.atan2(fft_complex[i][j][1],fft_complex[i][j][0]); /// was zero for circular targets)
				r=r/(r*r+k2);
				fft_complex[i][j][0]=r*Math.cos(a);
				fft_complex[i][j][1]=r*Math.sin(a);
			}
Andrey Filippov's avatar
Andrey Filippov committed
418
/* multiply by ellipse window */
Andrey Filippov's avatar
Andrey Filippov committed
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
			for (i=0;i<fft_complex.length; i++) for (j=0;j<fft_complex[0].length;j++) {
				fft_complex[i][j][0]*=ellipseMask[i][j];
				fft_complex[i][j][1]*=ellipseMask[i][j];
			}
		} else { // Do just the division (low power frequencies will be masked out by ellipse window)
			for (i=0;i<fft_complex.length; i++) for (j=0;j<fft_complex[0].length;j++) if (ellipseMask[i][j]>=0.0){
				r2=fft_complex[i][j][0]*fft_complex[i][j][0]+fft_complex[i][j][1]*fft_complex[i][j][1];
				fft_complex[i][j][0]*= ellipseMask[i][j]/r2;
				fft_complex[i][j][1]*=-ellipseMask[i][j]/r2;
			} else {
				fft_complex[i][j][0]=0.0;
				fft_complex[i][j][1]=0.0;
			}
		}

		double [] pixels=null;
Andrey Filippov's avatar
Andrey Filippov committed
435
/* convert back original dimension array if there was no decimation or debug is set (in that case both sizes arrays will be converted) */
436
/* Convert fft array back to fht array and
Andrey Filippov's avatar
Andrey Filippov committed
437 438
    set fht pixels with new values */
	    pixels=FFTHalf2FHT (fft_complex,size);
Andrey Filippov's avatar
Andrey Filippov committed
439 440
/* optionally show the result FHT*/
/* transform to space */
Andrey Filippov's avatar
Andrey Filippov committed
441 442
		fht_instance.inverseTransform(pixels);
		fht_instance.swapQuadrants(pixels);
Andrey Filippov's avatar
Andrey Filippov committed
443
/*   return inverted psf pixels */
Andrey Filippov's avatar
Andrey Filippov committed
444 445
		return pixels;
	}
446

Andrey Filippov's avatar
Andrey Filippov committed
447
	/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
Andrey Filippov's avatar
Andrey Filippov committed
448

Andrey Filippov's avatar
Andrey Filippov committed
449
	/* finds cluster (with the center at DC)  by flooding from DC, so total energy is cutoff_energy fraction
Andrey Filippov's avatar
Andrey Filippov committed
450 451 452 453 454 455 456 457 458 459 460 461 462 463
	returns integer array (same dimensions as input) with 1 - selected, 0 - not selected */
		private int [][] findClusterOnPS(
				double [][]       ps, // half power spectrum, starting from 0.0 (DC)
				double cutoff_energy, // fraction of energy in the pixels to be used
				String         title,
				int       debugLevel) {
			int i,j;
			List <Integer> pixelList=new ArrayList<Integer>(100);
			Integer Index;
			int size=ps[0].length;
			int [][]clusterMap=new int[size/2+1][size];
			double full_energy=0.0;
			int [][] dirs={{-1,0},{-1,-1},{0,-1},{1,-1},{1,0},{1,1},{0,1},{-1,1}};
			for (i=0;i<(size/2+1);i++) for (j=0;j<size;j++) {
Andrey Filippov's avatar
Andrey Filippov committed
464
				full_energy+=((i%(size/2))==0)?ps[i][j]:(2*ps[i][j]); /* first and last line are counted once, others - twice */
Andrey Filippov's avatar
Andrey Filippov committed
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
				clusterMap[i][j]=0;
			}
			double threshold=full_energy*cutoff_energy;
			double cluster_energy=0.0;
			double maxValue;
			int ix,iy,ix1,iy1,maxX, maxY;
			int clusterSize=0;
			ix=0;
			iy=0;
			maxX=0;
			maxY=0;
			int listIndex;
			Index=iy*size + ix;
			pixelList.clear();
			pixelList.add (Index);
			clusterSize++;
			clusterMap[iy][ix]=1;
			cluster_energy+=ps[iy][ix];
			boolean noNew=true;
			while ((pixelList.size()>0) &&  (cluster_energy<threshold)) {
Andrey Filippov's avatar
Andrey Filippov committed
485
	/* Find maximal new neighbor */
Andrey Filippov's avatar
Andrey Filippov committed
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
				maxValue=0.0;
				listIndex=0;
				while (listIndex<pixelList.size()) {
					Index=pixelList.get(listIndex);
					iy=Index/size;
					ix=Index%size;
					noNew=true;
					for (j=0;j<8;j++) if (((iy > 0 ) || (dirs[j][1]>=0)) && ((iy < (size/2) ) || (dirs[j][1]<=0))){
						ix1=(ix+dirs[j][0]+size) % size;
						iy1= iy+dirs[j][1];
						if (clusterMap[iy1][ix1]==0) {
							noNew=false;
							if (ps[iy1][ix1]>maxValue) {
								maxValue= ps[iy1][ix1];
								maxX=ix1;
								maxY=iy1;
							}
						}
					}
					if (noNew) pixelList.remove(listIndex);  //  remove current list element
					else       listIndex++;     // increase list index
				}
				if (maxValue==0.0) { // Should
					System.out.println("findClusterOnPS: - should not get here - no points around >0, and threshold is not reached yet.");
					break;
				}
Andrey Filippov's avatar
Andrey Filippov committed
512
	/* Add this new point to the list */
Andrey Filippov's avatar
Andrey Filippov committed
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
				Index=maxY*size + maxX;
				pixelList.add (Index);
				clusterSize++;
				clusterMap[maxY][maxX]=1;
				cluster_energy+=((maxY%(size/2))==0)?ps[maxY][maxX]:(2*ps[maxY][maxX]);
			} // end of while ((pixelList.size()>0) &&  (cluster_energy<threshold))
			if (debugLevel>3)   System.out.println("findClusterOnPS: cluster size is "+clusterSize);
			if (debugLevel>6) {
				ImageProcessor ip2 = new FloatProcessor(size,size/2+1);
				float [] floatPixels = new float [size*(size/2+1)];
				for (i=0;i<floatPixels.length;i++) {
					floatPixels[i]=(float) ps[i/size][i%size];
				}
				ip2.setPixels(floatPixels);
				ip2.resetMinAndMax();
				ImagePlus imp2= new ImagePlus(title+"_PS1_"+cutoff_energy, ip2);
				imp2.show();
			}
			if (debugLevel>6) {
				ImageProcessor ip1 = new FloatProcessor(size,size);
				float [] floatPixels = new float [size*size];
				for (i=0;i<floatPixels.length;i++) {
					iy=i/size-size/2;
					ix=i%size-size/2;
					if (iy<0) {
						ix=-ix;
						iy=-iy;
					}
					ix= (ix+size) % size;
					floatPixels[i]=(float) ps[iy][ix];
				}
				ip1.setPixels(floatPixels);
				ip1.resetMinAndMax();
				ImagePlus imp1= new ImagePlus(title+"_PS_"+cutoff_energy, ip1);
				imp1.show();
			}

			if (debugLevel>5) {
				ImageProcessor ip = new FloatProcessor(size,size);
				float [] floatPixels = new float [size*size];
				for (i=0;i<floatPixels.length;i++) {
					iy=i/size-size/2;
					ix=i%size-size/2;
					if (iy<0) {
						ix=-ix;
						iy=-iy;
					}
					ix= (ix+size) % size;
561
					floatPixels[i]=clusterMap[iy][ix];
Andrey Filippov's avatar
Andrey Filippov committed
562 563 564 565 566 567 568 569 570
				}
				ip.setPixels(floatPixels);
				ip.resetMinAndMax();
				ImagePlus imp= new ImagePlus(title+"_SEL_"+cutoff_energy, ip);
				imp.show();
			}
			return clusterMap;
		}

Andrey Filippov's avatar
Andrey Filippov committed
571
	/* calculates ellipse (with the center at DC) that interpolates area of the points defined by flooding from DC, so total energy is cutoff_energy fraction
Andrey Filippov's avatar
Andrey Filippov committed
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
	returns {a,b,c} , where a*x^2+b*y^2 + c*x*y=r^2 , so r^2 can be used for a window that removes high frequancy components that are too low to be useful*/

		private double [] findEllipseOnPS(
				double [][]        ps,   // half power spectrum, starting from 0.0 (DC)
				int    [][] selection, // 0/1 - selected/not selected
				String          title,
				int debugLevel) {
			int i,j;
			double x,y;
			int size=ps[0].length;
			double SX2=0.0;
			double SY2=0.0;
			double SXY=0.0;
			double S0=0.0;
			double k=2.0;
			double d;
			double area=0; // selection area
			for (i=0;i<(size/2+1);i++) {
				k=((i%(size/2))==0)?1.0:2.0;
				y=i;
				for (j=0;j<size;j++) if (selection[i][j]>0){
					x=(j>(size/2))?(j-size):j;
					d=k*ps[i][j];
					S0+=d;
					SX2+=x*x*d;
					SY2+=y*y*d;
					SXY+=x*y*d;
					area+=1.0;
				}
			}
			if (debugLevel>5) {
				System.out.println("findEllipseOnPS: title="+title+" area="+area+" S0="+S0+" SX2="+SX2+" SY2="+SY2+" SXY="+SXY);
			}
			//k=Math.PI*Math.PI/(2.0*S0*S0*area*area);
			//double [] result = {k*SY2,k*SX2,2*k*SXY};
			k=Math.PI*Math.PI/(2.0*S0*area*area);
			double [] result = {k*SY2,k*SX2,-2*k*SXY};
			if (debugLevel>3) {
				System.out.println("findEllipseOnPS: title="+title+" a="+result[0]+" b="+result[1]+" c="+result[2]);
			}
			return result;
		}

615 616 617



Andrey Filippov's avatar
Andrey Filippov committed
618 619 620
	/* ======================================================================== */
	/* TODO: REPLACE doubleFHT  */
	/* converts FHT results (frequency space) to complex numbers of [fftsize/2+1][fftsize] */
Andrey Filippov's avatar
Andrey Filippov committed
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644

		private double[][][] FHT2FFTHalf (double [] fht_pixels, int fftsize) {
			double[][][] fftHalf=new double[(fftsize>>1)+1][fftsize][2];
			int row1,row2,col1,col2;

			for (row1=0;row1<=(fftsize>>1);row1++) {
				row2=(fftsize-row1) %fftsize;
				for (col1=0;col1<fftsize;col1++) {
					col2=(fftsize-col1) %fftsize;
					fftHalf[row1][col1][0]=   0.5*(fht_pixels[row1*fftsize+col1] + fht_pixels[row2*fftsize+col2]);
					fftHalf[row1][col1][1]=   0.5*(fht_pixels[row2*fftsize+col2] - fht_pixels[row1*fftsize+col1]);
				}
			}
			return fftHalf;
		}


		private double[] FFTHalf2FHT (double [][][] fft, int fftsize) {
			double[] fht_pixels=new double [fftsize*fftsize];
			int row1,row2,col1,col2;
			for (row1=0;row1<=(fftsize>>1);row1++) {
				row2=(fftsize-row1) %fftsize;
				for (col1=0;col1 < fftsize;col1++) {
					col2=(fftsize-col1) %fftsize;
645 646
					fht_pixels[row1*fftsize+col1]=fft[row1][col1][0]-fft[row1][col1][1];
					fht_pixels[row2*fftsize+col2]=fft[row1][col1][0]+fft[row1][col1][1];
Andrey Filippov's avatar
Andrey Filippov committed
647 648 649 650 651 652
				}
			}
			return fht_pixels;
		}


653 654


Andrey Filippov's avatar
Andrey Filippov committed
655
   	/* interpolate kernels minimizing memory image - use directly the image stack (32-bit, float) with kernels.
Andrey Filippov's avatar
Andrey Filippov committed
656 657
   	  Add kernels around by either replication or extrapolation to compensate for "margins" in the original; kernels */
 //TODO: FIXME: Does not work if overwrite is disabled
658
   	public boolean interpolateKernels(
Andrey Filippov's avatar
Andrey Filippov committed
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
		    AtomicInteger stopRequested, // 1 - stop now, 2 - when convenient
			EyesisAberrations.InterpolateParameters  interpolateParameters, // INTERPOLATE
			EyesisAberrations.MultiFilePSF           multiFilePSF ,         // MULTIFILE_PSF = new EyesisAberrations.MultiFilePSF(
   			boolean                saveResult,
   			boolean                showResult,
   			boolean                updateStatus,          // UPDATE_STATUS
   			int                    globalDebugLevel
   	){
   		if ((this.aberrationParameters.psfKernelDirectory==null) || (this.aberrationParameters.psfKernelDirectory.length()==0)){
   			if (aberrationParameters.selectPSFKernelDirectory(true, this.aberrationParameters.partialKernelDirectory, false)==null) {
   				String msg = "Nothing selected";
   				System.out.println("Warning"+msg);
   				IJ.showMessage("Warning",msg);
   				return false;
   			}
   		}
   		int numChannels=distortions.fittingStrategy.distortionCalibrationData.getNumChannels(); // number of used channels
    	boolean [] selectedChannels=this.aberrationParameters.getChannelSelection(distortions);
		String [] srcPaths=    new String[numChannels];
		String [] resultPaths= new String[numChannels];
		int numToProcess=0;
		for (int nChn=0;nChn<selectedChannels.length;nChn++){
			if (!selectedChannels[nChn]){
				srcPaths[nChn]=null;
				resultPaths[nChn]=null;
			} else {
				srcPaths[nChn]=this.aberrationParameters.psfKernelDirectory+Prefs.getFileSeparator()+
				this.aberrationParameters.psfPrefix+String.format("%02d", nChn)+
				this.aberrationParameters.psfSuffix;
				resultPaths[nChn]=this.aberrationParameters.psfKernelDirectory+Prefs.getFileSeparator()+
				this.aberrationParameters.interpolatedPSFPrefix+String.format("%02d", nChn)+
				this.aberrationParameters.interpolatedPSFSuffix;
				if (!this.aberrationParameters.overwriteResultFiles && (new File(resultPaths[nChn])).exists()) {
					srcPaths[nChn]=null;
					if (globalDebugLevel>0) System.out.println("File "+resultPaths[nChn]+" already exists and overwrite is disabled in configuration, channel "+nChn+" will be skipped");
					continue;
				}
				numToProcess++;
			}
		}
    	if (numToProcess==0){
				String msg = "No kernels to process";
   				System.out.println("Warning"+msg);
   				IJ.showMessage("Warning",msg);
   				return false;
    	}
   		int numProcessed=0;
   		Opener opener=new Opener();;
   		ImagePlus impSpsf;
		long startTime=System.nanoTime(); // restart timer after possible interactive dialogs
   		for (int nChn=0;nChn<numChannels;nChn++) if (srcPaths[nChn]!=null){
   			if (!(new File(srcPaths[nChn])).exists()) {
   				String msg = "Combined PSF kernel stack for channel #"+nChn+": "+srcPaths[nChn]+" does not exist";
   				System.out.println("Warning"+msg);
   				continue;
   			}
   			impSpsf=opener.openImage("", srcPaths[nChn]);
   			if (impSpsf==null) {
   				System.out.println("Failed to open raw PSF kernel stack "+srcPaths[nChn]);
   				continue;
   			}
720 721
   			if ((impSpsf.getStackSize() < 3) && (impSpsf.getStackSize() != 1)) {
   				System.out.println("Need a 3-layer stack (for color) or single (for mono) with raw PSF kernels");
Andrey Filippov's avatar
Andrey Filippov committed
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
   				continue;
   			}
   			ImageStack stack= interpolateKernelStack(
   					impSpsf.getStack(), // Image stack, each slice consists of square kernels of one channel
   					interpolateParameters,
   					updateStatus,
   					globalDebugLevel); // update status info

   			ImagePlus impInterpolatedPSF = new ImagePlus("interpolated kernel stack", stack);
   			JP46_Reader_camera jp4_instance= new JP46_Reader_camera(false);
   			jp4_instance.decodeProperiesFromInfo(impSpsf);
   			// copy properties from the source image
   			jp4_instance.copyProperties (impSpsf,impInterpolatedPSF);
   			interpolateParameters.setProperties("INTERPOLATE.", impInterpolatedPSF);
   			jp4_instance.encodeProperiesToInfo(impInterpolatedPSF);
   			if (showResult) {
   				impInterpolatedPSF.getProcessor().resetMinAndMax(); // imp_psf will be reused
   				impInterpolatedPSF.show();
740
   			}
Andrey Filippov's avatar
Andrey Filippov committed
741 742 743 744
   			if (saveResult){
   				if (globalDebugLevel>0) System.out.println((numProcessed+1)+" of "+numToProcess+": saving interpolation result (of the file"+srcPaths[nChn]+") to "+
   						resultPaths[nChn]+ " at "+ IJ.d2s(0.000000001*(System.nanoTime()-startTime),3));
   				FileSaver fs=new FileSaver(impInterpolatedPSF);
745 746
//   				fs.saveAsTiffStack(resultPaths[nChn]);
   				fs.saveAsTiff(resultPaths[nChn]);
Andrey Filippov's avatar
Andrey Filippov committed
747 748
   			}
   			numProcessed++;
749
    		if 	(stopRequested.get()>0) {
Andrey Filippov's avatar
Andrey Filippov committed
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
				if (globalDebugLevel>0) System.out.println("User requested stop");
				break;
    		}
   		}
   		if (numProcessed>0){
			if (globalDebugLevel>0) {
				System.out.println("Interpolated "+numProcessed+" kernel stacks at "+ IJ.d2s(0.000000001*(System.nanoTime()-startTime),3));
			}
   		} else {
				String msg = "No kernel files to interpolate";
   				System.out.println("Warning"+msg);
   				return false;
   		}
   		return true;
   	}




   		public ImageStack interpolateKernelStack(
   				ImageStack kernelStack, // Image stack, each slice consists of square kernels of one channel
   				EyesisAberrations.InterpolateParameters interpolateParameters,
   				boolean   updateStatus,
   				int globalDebugLevel) // update status info
   		{
   			DoubleFHT fht_instance =new DoubleFHT(); // provide DoubleFHT instance to save on initializations (or null)
   			if (kernelStack==null) return null;
   			int inTilesX=kernelStack.getWidth()/interpolateParameters.size;
   			int inTilesY=kernelStack.getHeight()/interpolateParameters.size;
   			int outTilesX= (inTilesX-1)*interpolateParameters.step +1 + interpolateParameters.add_left + interpolateParameters.add_right;
   			int outTilesY= (inTilesY-1)*interpolateParameters.step +1 + interpolateParameters.add_top + interpolateParameters.add_bottom;
   			int nChn=kernelStack.getSize();
   			float [][] outPixels=new float[nChn][outTilesX*interpolateParameters.size*outTilesY*interpolateParameters.size];
   			float [] pixels;
   			int i,j,chn;
   			int xTile0=(interpolateParameters.add_left>0)?-1:0;
   			int xTile1=inTilesX+((interpolateParameters.add_right>0)?0:-1);
   			int yTile0=(interpolateParameters.add_top>0)?-1:0;
   			int yTile1=inTilesY+((interpolateParameters.add_bottom>0)?0:-1);
   			int tileY,tileX; //,subTileY,subTileX;

   			int tileWidth, tileHeight; // for inner cells (interpolateParameters.step+1)*(interpolateParameters.step+1), for outer includes exte row/column fro extrapolation
   			//  int maxTileWidth= Math.max(interpolateParameters.step,1+Math.max(interpolateParameters.add_right,interpolateParameters.add_left));
   			//  int maxTileHeight=Math.max(interpolateParameters.step,1+Math.max(interpolateParameters.add_bottom,interpolateParameters.add_top));
   			boolean lastColumn=false;  //last column - inverse convert and copy the last column of rectangleFHT to the result array
   			boolean lastRow=false;     //last row - interpolate, inverse convert and copy the last row of rectangleFHT to the result array

   			double [] pointsVert;
   			double [] pointsHor;
   			double [][] fhtLine;
   			double extraScale=interpolateParameters.extrapolate/interpolateParameters.step;
   			int [] outTopLeft=new int [2]; // top left kernel in the output array
   			int [] inTopLeft=new int [2]; // top left kernel in the input array
   			double [][] firstFHTColumn=null;
   			double [][] secondFHTColumn=null;
805
   			double [][][] cornerFHT=new double[2][2][interpolateParameters.size*interpolateParameters.size]; //[y][x][pixel]
Andrey Filippov's avatar
Andrey Filippov committed
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
   			double [] swapArray=null;

   			for (chn=0;chn<nChn;chn++) {
   				pixels=(float[]) kernelStack.getPixels(chn+1);
   				for (tileY=yTile0;tileY<yTile1;tileY++) {
   					if (updateStatus) IJ.showStatus("Interpolating kernels, channel "+kernelStack.getSliceLabel(chn+1)+", row "+(tileY-yTile0+1)+" of "+(yTile1-yTile0));
   					lastRow=(tileY==(yTile1-1));
   					if (tileY<0) {
   						inTopLeft[1]=0;
   						tileHeight=interpolateParameters.add_top;
   						outTopLeft[1]=0;
   						pointsVert=new double[tileHeight];
   						for (i=0;i<tileHeight;i++)  pointsVert[i]=(i-tileHeight)*extraScale; // negative values
   					} else if (tileY>=(inTilesY-1)){
   						inTopLeft[1]=tileY-1;
   						tileHeight=interpolateParameters.add_bottom+1; // always last row, if got here at all (interpolateParameters.add_bottom>0)
   						outTopLeft[1]=interpolateParameters.add_top+interpolateParameters.step*tileY;
   						pointsVert=new double[tileHeight];
   						for (i=0;i<tileHeight;i++)  pointsVert[i]=1.0+i*extraScale;
   					} else {
   						inTopLeft[1]=tileY;
   						tileHeight=interpolateParameters.step+ (lastRow?1:0); // last tile row includes bottom outpout kernel row
   						outTopLeft[1]=interpolateParameters.add_top+interpolateParameters.step*tileY;
   						pointsVert=new double[tileHeight];
   						for (i=0;i<tileHeight;i++) pointsVert[i]=(1.0*i)/tileHeight;
   					}
   					firstFHTColumn=null; // invalidate
   					secondFHTColumn=null; // invalidate
   					for (tileX=xTile0;tileX<xTile1;tileX++) {
   						if (globalDebugLevel>2)  System.out.println(" interpolateKernelStack(): chn="+chn+" tileY="+tileY+" tileX="+tileX);

   						lastColumn=(tileX==(xTile1-1));
   						if (tileX<0) {
   							inTopLeft[0]=0;
   							tileWidth=interpolateParameters.add_left;
   							outTopLeft[0]=0;
   							pointsHor=new double[tileWidth];
   							for (i=0;i<tileWidth;i++)  pointsHor[i]=(i-tileWidth)*extraScale; // negative values
   						} else if (tileX>=(inTilesX-1)){
   							inTopLeft[0]=tileX-1;
   							tileWidth=interpolateParameters.add_right+1; // always last columnw, if got here at all (interpolateParameters.add_right>0)
   							outTopLeft[0]=interpolateParameters.add_left+interpolateParameters.step*tileX;
   							pointsHor=new double[tileWidth];
   							for (i=0;i<tileWidth;i++)  pointsHor[i]=1.0+ i*extraScale;
   							// else keep both firstFHTColumn and secondFHTColumn
   							if (globalDebugLevel>2)  System.out.println("last column: tileX="+tileX);
   						} else {
   							inTopLeft[0]=tileX;
   							tileWidth=interpolateParameters.step+ (lastColumn?1:0); // last tile column includes rightmost outpout kernel column
   							outTopLeft[0]=interpolateParameters.add_left+interpolateParameters.step*tileX;
   							pointsHor=new double[tileWidth];
   							for (i=1;i<tileWidth;i++)  pointsHor[i]=(1.0*i)/tileWidth;
   							//  if (DEBUG_LEVEL>2)  System.out.println("else: tileX="+tileX);
   							if (tileX!=0) {
   								firstFHTColumn=secondFHTColumn;
   								secondFHTColumn=null; // invalidate
   								//  if (DEBUG_LEVEL>2)  System.out.println(" secondFHTColumn==null");
Andrey Filippov's avatar
Andrey Filippov committed
863
   	/* swap columns, the new second one will be just reused */
Andrey Filippov's avatar
Andrey Filippov committed
864 865 866 867 868 869 870 871 872 873 874 875
   								swapArray=cornerFHT[0][0];
   								cornerFHT[0][0]=cornerFHT[0][1];
   								cornerFHT[0][1]=swapArray;
   								swapArray=cornerFHT[1][0];
   								cornerFHT[1][0]=cornerFHT[1][1];
   								cornerFHT[1][1]=swapArray;

   							} // else keep both firstFHTColumn and secondFHTColumn
   						}
   						if (globalDebugLevel>2)  System.out.println(" interpolateKernelStack(): tileHeight="+tileHeight+" tileWidth="+tileWidth+" inTopLeft[0]="+inTopLeft[0]+" inTopLeft[1]="+inTopLeft[1]+
   								" outTopLeft[0]="+outTopLeft[0]+" outTopLeft[1]="+outTopLeft[1]);

Andrey Filippov's avatar
Andrey Filippov committed
876
   						if (firstFHTColumn==null) { /* First colum needs to be input and calculated*/
877
   							extractOneKernel(          pixels, //  array of combined square kernels, each
Andrey Filippov's avatar
Andrey Filippov committed
878 879 880 881
   									cornerFHT[0][0], // will be filled, should have correct size before call
   									inTilesX, // number of kernels in a row
   									inTopLeft[0], // horizontal number of kernel to extract
   									inTopLeft[1]); // vertical number of kernel to extract
882
   							extractOneKernel(          pixels, //  array of combined square kernels, each
Andrey Filippov's avatar
Andrey Filippov committed
883 884 885 886
   									cornerFHT[1][0], // will be filled, should have correct size before call
   									inTilesX, // number of kernels in a row
   									inTopLeft[0], // horizontal number of kernel to extract
   									inTopLeft[1]+1); // vertical number of kernel to extract
Andrey Filippov's avatar
Andrey Filippov committed
887
   	/* convert to frequency domain */
Andrey Filippov's avatar
Andrey Filippov committed
888 889 890 891
   							fht_instance.swapQuadrants(cornerFHT[0][0]);
   							fht_instance.transform(    cornerFHT[0][0]);
   							fht_instance.swapQuadrants(cornerFHT[1][0]);
   							fht_instance.transform(    cornerFHT[1][0]);
Andrey Filippov's avatar
Andrey Filippov committed
892
   	/* inter/extrapolate the column */
Andrey Filippov's avatar
Andrey Filippov committed
893 894 895 896 897 898
   							firstFHTColumn=fht_instance.interpolateFHT (cornerFHT[0][0],    // first FHT array
   									cornerFHT[1][0],    // second FHT array
   									pointsVert,    // array of interpolation points - 0.0 - fht0, 1.0 - fht1
   									false);   // OK not to clone, so corners will be referenced?
   							if (globalDebugLevel>2)  System.out.println(" firstFHTColumn.length="+firstFHTColumn.length);
   						}
Andrey Filippov's avatar
Andrey Filippov committed
899
   						if (secondFHTColumn==null) { /* Last colum needs to be input and calculated*/
900
   							extractOneKernel(          pixels, //  array of combined square kernels, each
Andrey Filippov's avatar
Andrey Filippov committed
901 902 903 904
   									cornerFHT[0][1], // will be filled, should have correct size before call
   									inTilesX, // number of kernels in a row
   									inTopLeft[0]+1, // horizontal number of kernel to extract
   									inTopLeft[1]); // vertical number of kernel to extract
905
   							extractOneKernel(          pixels, //  array of combined square kernels, each
Andrey Filippov's avatar
Andrey Filippov committed
906 907 908 909
   									cornerFHT[1][1], // will be filled, should have correct size before call
   									inTilesX, // number of kernels in a row
   									inTopLeft[0]+1, // horizontal number of kernel to extract
   									inTopLeft[1]+1); // vertical number of kernel to extract
Andrey Filippov's avatar
Andrey Filippov committed
910
   	/* convert to frequency domain */
Andrey Filippov's avatar
Andrey Filippov committed
911 912 913 914
   							fht_instance.swapQuadrants(cornerFHT[0][1]);
   							fht_instance.transform(    cornerFHT[0][1]);
   							fht_instance.swapQuadrants(cornerFHT[1][1]);
   							fht_instance.transform(    cornerFHT[1][1]);
Andrey Filippov's avatar
Andrey Filippov committed
915
   	/* inter/extrapolate the column */
Andrey Filippov's avatar
Andrey Filippov committed
916 917 918 919 920 921 922 923 924 925 926
   							secondFHTColumn=fht_instance.interpolateFHT (cornerFHT[0][1],    // first FHT array
   									cornerFHT[1][1],    // second FHT array
   									pointsVert,    // array of interpolation points - 0.0 - fht0, 1.0 - fht1
   									false);   // OK not to clone, so corners will be referenced?

   							if (globalDebugLevel>2)  {
   								System.out.println(" secondFHTColumn.length="+secondFHTColumn.length);
   								for (i=0;i<pointsVert.length;i++) System.out.println(""+pointsVert[i]);
   								System.out.println("");
   							}
   						}
Andrey Filippov's avatar
Andrey Filippov committed
927 928
   	/* interpolate horizontally */
   	/* TODO: calculate top-left corner in output array */
Andrey Filippov's avatar
Andrey Filippov committed
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
   						/*
   	   if ((DEBUG_LEVEL>1) &&(tileY==0)) {
   	      SDFA_instance.showArrays(firstFHTColumn,size,size, "firstFHTColumn");
   	      SDFA_instance.showArrays(secondFHTColumn,size,size, "secondFHTColumn");
   	      DEBUG_LEVEL=4;
   	      return null;
   	   }
   						 */
   						for (i=0;i<tileHeight;i++) {
   							if (globalDebugLevel>2)  System.out.print("i="+i);

   							fhtLine=fht_instance.interpolateFHT ( firstFHTColumn[i],    // first FHT array
   									secondFHTColumn[i],    // second FHT array
   									pointsHor,    // array of interpolation points - 0.0 - fht0, 1.0 - fht1
   									true); //clone ends
   							if (globalDebugLevel>2)  System.out.print(": ");
   							for (j=0;j<tileWidth;j++) {
   								if (globalDebugLevel>2)  System.out.print(j);
   								fht_instance.inverseTransform(fhtLine[j]);
   								fht_instance.swapQuadrants   (fhtLine[j]);
   								storeOneKernel(           outPixels[chn], // float [] array of combined square kernels - will be filled
   										fhtLine[j], // square kernel to store
   										outTilesX, // number of kernels in a row
   										outTopLeft[0]+j, // horizontal number of kernel to store
   										outTopLeft[1]+i); // vertical number of kernel to store
   							}
   							if (globalDebugLevel>2)  System.out.println("");

   						}
   					}
   				}
960
   			}
Andrey Filippov's avatar
Andrey Filippov committed
961
   	/* prepare result stack to return */
Andrey Filippov's avatar
Andrey Filippov committed
962 963 964 965 966 967
   			ImageStack outStack=new ImageStack(outTilesX*interpolateParameters.size,outTilesY*interpolateParameters.size);
   			for (chn=0;chn<nChn;chn++) {
   				outStack.addSlice(kernelStack.getSliceLabel(chn+1), outPixels[chn]);
   			}
   			return outStack;
   		}
Andrey Filippov's avatar
Andrey Filippov committed
968
   	/* ======================================================================== */
969
   	/* Used in interpolateKernelStack() */
Andrey Filippov's avatar
Andrey Filippov committed
970 971 972 973 974 975 976 977 978 979 980 981 982 983
   		private void storeOneKernel(
   				float []  pixels, // float [] array of combined square kernels - will be filled
   				double [] kernel, // square kernel to store
   				int       numHor, // number of kernels in a row
   				int        xTile, // horizontal number of kernel to store
   				int        yTile) { // vertical number of kernel to store
   			int length=kernel.length;
   			int size=(int) Math.sqrt(length);
   			int i,j;
   			int pixelsWidth=numHor*size;
   			int base=(yTile*pixelsWidth+xTile)*size;
   			for (i=0;i<size;i++) for (j=0;j<size;j++) pixels[base+i*pixelsWidth+j]= (float) kernel[i*size+j];
   		}

Andrey Filippov's avatar
Andrey Filippov committed
984
   	/* ======================================================================== */
985 986


Andrey Filippov's avatar
Andrey Filippov committed
987 988
   	public String [][]  preparePartialKernelsFilesList(
   			int debugLevel){
989
   		DistortionCalibrationData distortionCalibrationData= distortions.fittingStrategy.distortionCalibrationData;
Andrey Filippov's avatar
Andrey Filippov committed
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
   		boolean [] selectedImages=distortions.fittingStrategy.selectedImagesNoBadKernels(this.aberrationParameters.allImages?-1:this.aberrationParameters.seriesNumber); // negative series number OK - will select all enabled
   		int num=0;
   		for (int imgNum=0;imgNum<selectedImages.length;imgNum++) if (selectedImages[imgNum]) num++;
   		if (debugLevel>1) {
   			System.out.println("Enabled "+num+" source files");
   		}
   		if (num==0){
				String msg="No enabled files selected. Command aborted";
   				System.out.println("Warning"+msg);
   				IJ.showMessage("Warning",msg);
   				return null;
   		}
   		String [] partialKernelPaths=new String [selectedImages.length];
   		for (int imgNum=0;imgNum<partialKernelPaths.length;imgNum++){
   			if (!selectedImages[imgNum]) {
   				partialKernelPaths[imgNum]=null;
   			} else {
   				partialKernelPaths[imgNum]=this.aberrationParameters.partialPrefix+IJ.d2s(distortionCalibrationData.gIP[imgNum].timestamp,6).replace('.','_')+
   				String.format("-%02d"+this.aberrationParameters.partialSuffix, distortionCalibrationData.gIP[imgNum].channel); // sensor number
   				//   			partialKernelPaths[imgNum]=this.aberrationParameters.sourceDirectory+Prefs.getFileSeparator()+filename;
1010

Andrey Filippov's avatar
Andrey Filippov committed
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
   		   		if (debugLevel>2) System.out.println("preparePartialKernelsFilesList() "+imgNum+": "+partialKernelPaths[imgNum]);

   			}
   		}
   		if (countExistentFiles(this.aberrationParameters.partialKernelDirectory,partialKernelPaths,false)==0){ // keep non-existent
   			if (aberrationParameters.selectPartialKernelDirectory(true, this.aberrationParameters.partialKernelDirectory, false)==null) {
   				String msg="No partial kernel directory selected. Command aborted";
   				System.out.println("Warning"+msg);
   				IJ.showMessage("Warning",msg);
   				return null;
   			}
   		}
   		if (countExistentFiles(this.aberrationParameters.partialKernelDirectory,partialKernelPaths,true)==0){ // will remove all non-existent files
   			String msg="No partial kernel files found. Command aborted";
   			System.out.println("Warning"+msg);
   			IJ.showMessage("Warning",msg);
   			return null;
   		}
1029 1030


Andrey Filippov's avatar
Andrey Filippov committed
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
   		int numChannels=distortions.fittingStrategy.distortionCalibrationData.getNumChannels(); // number of used channels
   		String [][] fileList=new String[numChannels][];
   		for (int numChn=0;numChn<numChannels;numChn++){
   			int n=0;
   			for (int  imgNum=0;imgNum<partialKernelPaths.length;imgNum++)
   				if ((partialKernelPaths[imgNum]!=null) && (distortionCalibrationData.gIP[imgNum].channel==numChn))n++;
   			if (n==0) {
   				fileList[numChn]=null;
   			} else {
   				fileList[numChn]=new String[n];
   				n=0;
   				for (int  imgNum=0;imgNum<partialKernelPaths.length;imgNum++)
   					if ((partialKernelPaths[imgNum]!=null) && (distortionCalibrationData.gIP[imgNum].channel==numChn)){
   						fileList[numChn][n++]=this.aberrationParameters.partialKernelDirectory+Prefs.getFileSeparator()+partialKernelPaths[imgNum];
   					}
   			}
   		}
   		if (debugLevel>0) {
   			System.out.println("Partial kernel files available:");
   			for (int numChn=0;numChn<numChannels;numChn++){
   				if (fileList[numChn]!=null) {
   					System.out.println("   channel "+numChn+": "+fileList[numChn].length+" files");

   					if (debugLevel>1) {
   						for (int i=0;i<fileList[numChn].length;i++) {
   							System.out.println(numChn+":"+i+": "+fileList[numChn][i]);
   						}
   					}
   				}
   			}
   		}
   		return fileList;
   	}
1064

1065
   	public boolean createPartialKernels(
Andrey Filippov's avatar
Andrey Filippov committed
1066
		    AtomicInteger stopRequested, // 1 - stop now, 2 - when convenient
1067 1068 1069
			LwirReaderParameters lwirReaderParameters, // null is OK
//			int            fft_overlap,
//			int               fft_size,
1070
			int           PSF_subpixel,
Andrey Filippov's avatar
Andrey Filippov committed
1071
			OTFFilterParameters otfFilterParameters,
1072
			OTFFilterParameters otfFilterParameters_lwir,
Andrey Filippov's avatar
Andrey Filippov committed
1073 1074 1075 1076 1077 1078 1079 1080
			PSFParameters psfParameters,
			int          PSFKernelSize, // size of square used in the new map (should be multiple of map step)
			double       gaussWidth,  // ** NEW
			MultiFilePSF multiFilePSF,
			MatchSimulatedPattern.DistortionParameters distortionParameters, //
			MatchSimulatedPattern.PatternDetectParameters patternDetectParameters,
			SimulationPattern.SimulParameters  simulParameters,
			ColorComponents colorComponents,
Andrey Filippov's avatar
Andrey Filippov committed
1081
			boolean resetBadKernels, // ignore and reset noUsefulKernels mark for selected channel
Andrey Filippov's avatar
Andrey Filippov committed
1082 1083 1084 1085 1086
			int threadsMax,
			boolean updateStatus,
			int loopDebugLevel, // debug level used inside loops
			int debugLevel
			){
1087
    	DistortionCalibrationData distortionCalibrationData= distortions.fittingStrategy.distortionCalibrationData;
1088
    	boolean partialToReprojected=this.aberrationParameters.partialToReprojected;
1089
    	boolean applySensorCorrection=this.aberrationParameters.partialCorrectSensor;
1090
    	// this.distortions is set to top level LENS_DISTORTIONS
Andrey Filippov's avatar
Andrey Filippov committed
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
		if (distortions==null){
    		String msg="Distortions instance does not exist, exiting";
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);

		}
		if (distortions.fittingStrategy==null){
    		String msg="Fitting strategy does not exist, exiting";
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);
		}
		long startTime=System.nanoTime(); // restart timer after possible interactive dialogs
//		long tmpTime;
1104 1105 1106 1107 1108
		//resetBadKernels
		int serNumber=this.aberrationParameters.allImages?-1:this.aberrationParameters.seriesNumber;
    	boolean [] selectedImages=resetBadKernels?
    			distortions.fittingStrategy.selectedImages(serNumber):
    			distortions.fittingStrategy.selectedImagesNoBadKernels(serNumber); // negative series number OK - will select all enabled
Andrey Filippov's avatar
Andrey Filippov committed
1109 1110 1111
    	boolean [] selectedChannels=this.aberrationParameters.getChannelSelection(distortions);
    	int numSelected=0;
    	int numDeselected=0;
Andrey Filippov's avatar
Andrey Filippov committed
1112
    	if (debugLevel>2){
Andrey Filippov's avatar
Andrey Filippov committed
1113 1114 1115 1116
    		for (int i=0;i<selectedChannels.length;i++){
    			System.out.println("Channel "+i+" is "+(selectedChannels[i]?"Enabled":"Disabled"));
    		}
    	}
Andrey Filippov's avatar
Andrey Filippov committed
1117 1118
    	for (int imgNum=0;imgNum<selectedImages.length;imgNum++) if (selectedImages[imgNum]) {
    		int numChannel=distortionCalibrationData.gIP[imgNum].channel;
Andrey Filippov's avatar
Andrey Filippov committed
1119
        	if (debugLevel>2){
Andrey Filippov's avatar
Andrey Filippov committed
1120
        		System.out.println("Image "+imgNum+" channel "+numChannel+" is "+(selectedChannels[numChannel]?"ENABLED":"DISABLED"));
1121
        	}
Andrey Filippov's avatar
Andrey Filippov committed
1122 1123 1124
    		if (!selectedChannels[numChannel]){
    			selectedImages[imgNum]=false;
    			numDeselected++;
1125 1126 1127 1128
    		}else{
    			distortions.fittingStrategy.setNoUsefulPSFKernels(imgNum,false); // reset noUsefulKernels mark (if it was not set - OK)
    			numSelected++;
    		}
Andrey Filippov's avatar
Andrey Filippov committed
1129
    	} else if (debugLevel>2){
Andrey Filippov's avatar
Andrey Filippov committed
1130
    		System.out.println("Skipping disabled image "+imgNum);
Andrey Filippov's avatar
Andrey Filippov committed
1131
    	}
1132
    	if (debugLevel>0)System.out.println("Enabled "+numSelected+" source files ("+numDeselected+") were removed by channel selection. partialToReprojected="+partialToReprojected);
Andrey Filippov's avatar
Andrey Filippov committed
1133 1134 1135 1136 1137 1138 1139 1140

    	String [] sourcePaths=new String [selectedImages.length];
    	// Set/verify source paths
    	int numFiles=0;
    	boolean skipMissing=false;
    	for (int imgNum=0;imgNum<sourcePaths.length;imgNum++){
    		if (!selectedImages[imgNum]) sourcePaths[imgNum]=null;
    		else {
1141 1142 1143 1144 1145
///    			String filename=this.aberrationParameters.sourcePrefix+IJ.d2s(distortionCalibrationData.gIP[imgNum].timestamp,6).replace('.','_')+
///    			String.format("-%02d"+this.aberrationParameters.sourceSuffix, distortionCalibrationData.gIP[imgNum].channel); // sensor number
///    			sourcePaths[imgNum]=this.aberrationParameters.sourceDirectory+Prefs.getFileSeparator()+filename;
    			sourcePaths[imgNum]=distortionCalibrationData.gIP[imgNum].source_path;

1146
    			File srcFile=new File(sourcePaths[imgNum]);
Andrey Filippov's avatar
Andrey Filippov committed
1147
    			if (!srcFile.exists()){
1148
    				String filename = sourcePaths[imgNum].substring(sourcePaths[imgNum].lastIndexOf(Prefs.getFileSeparator()));
Andrey Filippov's avatar
Andrey Filippov committed
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
    				if (skipMissing) {
    					if (debugLevel>0) System.out.println("Skipping missing file: "+sourcePaths[imgNum]);
    	    	    	sourcePaths[imgNum]=null;
    					continue;
    				}
    				GenericDialog gd=new GenericDialog("Missing source file(s)");
    				gd.addMessage ("Source file "+sourcePaths[imgNum]+" does not exist");
    				gd.addMessage ("This may be a file from the different source directory (acquired at different station).");
    				gd.addMessage ("You may change source and destination directories and re-run this command for another station.");
    				gd.enableYesNoCancel("Find file", "Skip  this and other missing files");
    	    	    gd.showDialog();
    	    	    if (gd.wasCanceled()) return false;
    	    	    if (!gd.wasOKed()){
    	    	    	skipMissing=true;
    	    	    	sourcePaths[imgNum]=null;
    	    	    	continue;
    	    	    }
    				String [] extensions={filename}; // just this one file
1167
    				MultipleExtensionsFileFilter parFilter = new MultipleExtensionsFileFilter("",extensions,filename);
Andrey Filippov's avatar
Andrey Filippov committed
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
    				String pathname=CalibrationFileManagement.selectFile(
    						false,
    						false,
    						"Find source file",
    						"Select",
    						parFilter,
    						this.aberrationParameters.sourceDirectory); //String defaultPath
    				if ((pathname==null) || (pathname=="")) return false;
    				sourcePaths[imgNum]=pathname;
    				this.aberrationParameters.sourceDirectory=pathname.substring(0, pathname.lastIndexOf(Prefs.getFileSeparator()));
    			}
				numFiles++;
    		}
    	}
    	if (numFiles==0 ){
    		String msg="createPartialKernels(): No files selected";
    		System.out.println("Warning: "+msg);
    		if (!aberrationParameters.noMessageBoxes)IJ.showMessage("Warning",msg);
    		return true;
    	}
    	if (debugLevel>0) {
    		System.out.println("Selected "+numFiles+" source files");
    	}

    	if (aberrationParameters.selectPartialKernelDirectory(true, this.aberrationParameters.partialKernelDirectory, true)==null){
    		String msg="createPartialKernels(): No partial kernel directory selected";
    		System.out.println("Warning: "+msg);
    		if (!aberrationParameters.noMessageBoxes)IJ.showMessage("Warning",msg);
    		return true;
    	}
    	String [] partialKernelsPaths=new String [selectedImages.length];
    	for (int imgNum=0;imgNum<sourcePaths.length;imgNum++){
    		if (sourcePaths[imgNum]==null){
    			partialKernelsPaths[imgNum]=null;
    		} else {
    			String filename=this.aberrationParameters.partialPrefix+IJ.d2s(distortionCalibrationData.gIP[imgNum].timestamp,6).replace('.','_')+
    			String.format("-%02d", distortionCalibrationData.gIP[imgNum].channel)+this.aberrationParameters.partialSuffix;
    			partialKernelsPaths[imgNum]=this.aberrationParameters.partialKernelDirectory+Prefs.getFileSeparator()+filename;
    		}
    	}
    	int numOld=0;
    	if (!this.aberrationParameters.overwriteResultFiles){
        	for (int imgNum=0;imgNum<sourcePaths.length;imgNum++) if (partialKernelsPaths[imgNum]!=null){
            	if (debugLevel>1){
            		System.out.println(imgNum+": "+partialKernelsPaths[imgNum]+((new File(partialKernelsPaths[imgNum]).exists())?" EXISTS":" DOES NOT EXIST"));
            	}
        		if (new File(partialKernelsPaths[imgNum]).exists()){
        			numOld++;
        			numFiles--;
        			partialKernelsPaths[imgNum]=null;
        			sourcePaths[imgNum]=null;
        		}
        	}
    	}
    	if (debugLevel>0){
    		System.out.println((numFiles+numOld)+" source files selected, "+((numOld>0)?(numOld+" existent files skipped, "):"")+numFiles+" to process");
    	}
    	if (numFiles<=0){
    		String msg="createPartialKernels(): No files to process";
    		System.out.println("Warning: "+msg);
    		if (!aberrationParameters.noMessageBoxes)IJ.showMessage("Warning",msg);
    		return true;
    	}
    	// reorder in the ascending channel number order
    	String [][] files=new String [numFiles][2]; // 0 - source, 1 - result
1233
    	int [] fileIndices =new int [numFiles]; // needed to mark bad kernels (and also to reference grid parameters to replace extracted)
Andrey Filippov's avatar
Andrey Filippov committed
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
    	int numListedFiles=0;
    	int numChannel=0;
    	while (numListedFiles<numFiles) {
    		for (int imgNum=0;imgNum<sourcePaths.length;imgNum++) if ((sourcePaths[imgNum]!=null) && (distortionCalibrationData.gIP[imgNum].channel<=numChannel)){
    			if (debugLevel>1) System.out.println("numListedFiles="+numListedFiles+" numFiles"+numFiles+" sourcePaths["+imgNum+"]="+sourcePaths[imgNum]+" numChannel="+numChannel);
    			files[numListedFiles][0]=sourcePaths[imgNum];
    			files[numListedFiles][1]=partialKernelsPaths[imgNum];
    			fileIndices[numListedFiles++]=imgNum;
    			sourcePaths[imgNum]=null;
    		}
    		numChannel++;
    	}
    	startTime=System.nanoTime(); // restart timer after possible interactive dialogs
    	for (int imgNum=0;imgNum<files.length;imgNum++){ // add stopRequested
			if (debugLevel>0) System.out.println("Processing file #"+(imgNum+1)+ " ( of "+files.length+") :"+files[imgNum][0]);
        	ImagePlus imp=new ImagePlus(files[imgNum][0]); // read source file
        	JP4_INSTANCE.decodeProperiesFromInfo(imp);
1251 1252 1253 1254
       		boolean is_lwir =      lwirReaderParameters.is_LWIR(imp);
       	    int     fft_size =     is_lwir ? distortionParameters.FFTSize_lwir :    distortionParameters.FFTSize;
       	    int     fft_overlap =  is_lwir ? distortionParameters.FFTOverlap_lwir : distortionParameters.FFTOverlap;
       	    imp.setProperty("MONOCHROME",""+is_lwir);
1255 1256 1257 1258 1259 1260 1261 1262
        	// pad image to full sensor size
			int numGridImage=fileIndices[imgNum];
			int chn = distortions.fittingStrategy.distortionCalibrationData.gIP[numGridImage].getChannel();
			int [] sensor_width_height = distortions.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorWidthHeight(chn);
        	imp = ShowDoubleFloatArrays.padBayerToFullSize(
					  imp, // ImagePlus imp_src,
					  sensor_width_height, // eyesisCorrections.pixelMapping.sensors[srcChannel].getSensorWH(),
					  true); // boolean replicate);
Andrey Filippov's avatar
Andrey Filippov committed
1263 1264 1265 1266 1267 1268 1269
// TODO: Add vignetting correction ?
        	MatchSimulatedPattern matchSimulatedPattern= new MatchSimulatedPattern(distortionParameters.FFTSize);
			boolean [] correlationSizesUsed=null;
			float [][] simArray=         	null;

        	int MaxRetries=4;
        	int iRetry=0;
Andrey Filippov's avatar
Andrey Filippov committed
1270
        	for (iRetry=0;iRetry<MaxRetries;iRetry++){ // is this retry needed?
Andrey Filippov's avatar
Andrey Filippov committed
1271
        		try {
1272

1273
        			double [][][] projectedGrid=null;
1274
        			double hintTolerance=0.0;
1275 1276
        			if (partialToReprojected){ // replace px, py with projected values form the grid
        				// this.distortions is set to the global LENS_DISTORTIONS
1277
///        				int numGridImage=fileIndices[imgNum];
1278
        				projectedGrid=distortions.estimateGridOnSensor( // return grid array [v][u][0- x,  1 - y, 2 - u, 3 - v]
1279
        						distortions.fittingStrategy.distortionCalibrationData.getImageStation(numGridImage), // station number,
1280
        						distortions.fittingStrategy.distortionCalibrationData.gIP[numGridImage].getChannel(), // subCamera,
1281 1282
        						Double.NaN, // goniometerHorizontal, - not used
        						Double.NaN, // goniometerAxial, - not used
1283
        						Double.NaN, // inter-axis angle, - not used ?
1284
        						distortions.fittingStrategy.distortionCalibrationData.gIP[numGridImage].getSetNumber(), //imageSet,
1285
        						false); // true); //filterBorder) // TODO: MAKE IT configurable parameter!
1286 1287 1288 1289
        				hintTolerance=5.0; // TODO:set from configurable parameter
        				if (applySensorCorrection){
        					boolean applied=distortions.correctGridOnSensor(
        							projectedGrid,
1290
        							distortions.fittingStrategy.distortionCalibrationData.gIP[numGridImage].getChannel());
1291 1292
                			if (debugLevel>0) {
                				if (applied) System.out.println("Applied sensor correction to the projected grid");
1293
                				else System.out.println("No sensor correction available to apply to the projected grid");
1294 1295
                			}
        				}
1296
        			}
1297

Andrey Filippov's avatar
Andrey Filippov committed
1298
        			int rslt=matchSimulatedPattern.calculateDistortions(
1299
        					lwirReaderParameters, // LwirReaderParameters lwirReaderParameters, // null is OK
Andrey Filippov's avatar
Andrey Filippov committed
1300 1301
        					distortionParameters, //
        					patternDetectParameters,
1302 1303
//        					patternDetectParameters.minGridPeriod/2,
//        		            patternDetectParameters.maxGridPeriod/2,
Andrey Filippov's avatar
Andrey Filippov committed
1304 1305
        					simulParameters,
        					colorComponents.equalizeGreens,
1306
        					imp, // has WOI_TOP and possibly - WOI_COMPENSATED
Andrey Filippov's avatar
Andrey Filippov committed
1307 1308
        					null, // LaserPointer laserPointer, // LaserPointer object or null
        					true, // don't care -removeOutOfGridPointers
1309 1310
        					projectedGrid, // null, //   double [][][] hintGrid, // predicted grid array (or null)
        					hintTolerance, // 0,    //   double  hintGridTolerance, // allowed mismatch (fraction of period) or 0 - orientation only
Andrey Filippov's avatar
Andrey Filippov committed
1311 1312 1313 1314 1315
        					threadsMax,
        					updateStatus,
        					debugLevel,
        					loopDebugLevel, // debug level
        					aberrationParameters.noMessageBoxes);
Andrey Filippov's avatar
Andrey Filippov committed
1316
        			if (rslt<0){
Andrey Filippov's avatar
Andrey Filippov committed
1317
            			if (debugLevel>0) System.out.println("calculateDistortions failed, returned error code "+rslt+" iRetry="+iRetry+" (of "+MaxRetries+")");
Andrey Filippov's avatar
Andrey Filippov committed
1318 1319
            			continue;
        			}
1320
        			// now replace extracted grid X,Y with projected (need to add sensor correction)
1321
        			if (projectedGrid!=null){
1322 1323 1324
        				int numReplaced= matchSimulatedPattern.replaceGridXYWithProjected(
        						projectedGrid,
        						((debugLevel>1)?imp.getTitle():null));
1325 1326
            			if (debugLevel>0) System.out.println("Replaced extracted XY with projected ones for "+numReplaced+" nodes");
        			}
Andrey Filippov's avatar
Andrey Filippov committed
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
        			correlationSizesUsed=matchSimulatedPattern.getCorrelationSizesUsed();
        			simArray=	(new SimulationPattern(simulParameters)).simulateGridAll (
        					imp.getWidth(),
        					imp.getHeight(),
        					matchSimulatedPattern,
        					2, // gridFrac, // number of grid steps per pattern full period
        					simulParameters,
        					threadsMax,
        					updateStatus,
        					debugLevel,
1337
        					loopDebugLevel+1); // debug level
1338

Andrey Filippov's avatar
Andrey Filippov committed
1339 1340 1341
        			createPSFMap(
        					matchSimulatedPattern,
        					matchSimulatedPattern.applyFlatField (imp), // if grid is flat-field calibrated, apply it (may throw here)
1342
        					lwirReaderParameters, //final LwirReaderParameters lwirReaderParameters, // null is OK
1343
        					null,     //  int [][][] sampleList, // optional (or null) 2-d array: list of coordinate pairs (2d - to match existent  PSF_KERNEL_MAP structure)
Andrey Filippov's avatar
Andrey Filippov committed
1344 1345 1346 1347 1348 1349
        					multiFilePSF.overexposedMaxFraction, //MULTIFILE_PSF.overexposedMaxFraction,
        					simulParameters, //SIMUL, //simulation parameters
        					patternDetectParameters, //PATTERN_DETECT, //MatchSimulatedPattern.PatternDetectParameters patternDetectParameters,
        					fft_overlap, //FFT_OVERLAP, // int            fft_overlap,
        					fft_size, // FFT_SIZE, // int               fft_size,
        					colorComponents, //COMPONENTS,   // ColorComponents colorComponents,
1350
        					PSF_subpixel, //PSF_SUBPIXEL, // int           PSF_subpixel,
1351 1352
        					(is_lwir?otfFilterParameters_lwir:otfFilterParameters),
//        					otfFilterParameters, // OTF_FILTER, // OTFFilterParameters otfFilterParameters,
Andrey Filippov's avatar
Andrey Filippov committed
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
        					psfParameters, //PSF_PARS, // final PSFParameters psfParameters
        					psfParameters.minDefinedArea , //PSF_PARS.minDefinedArea, // final double       minDefinedArea,
        					PSFKernelSize, //// int          PSFKernelSize, // size of square used in the new map (should be multiple of map step)
        					gaussWidth, //gaussWidth
        					simArray, // simArray
        					threadsMax,   // threadsMax,
        					updateStatus, // updateStatus,
        					debugLevel, //masterDebugLevel
        					debugLevel, //globalDebugLevel
        					loopDebugLevel);// debug level used inside loops
        			break; // success
        		} catch (Exception e) {
        			if (debugLevel>0) System.out.println("Attempt "+(iRetry+1)+" of "+MaxRetries+"Failed to find initial pattern in file #"+
        					(imgNum+1)+ " ( of "+files.length+") :"+files[imgNum][0]);
        			e.printStackTrace();
        			continue;
        		}
        	}
Andrey Filippov's avatar
Andrey Filippov committed
1371
        	if (iRetry==MaxRetries) {
Andrey Filippov's avatar
Andrey Filippov committed
1372
				System.out.println("File "+files[imgNum][1]+ " has problems - finished at "+ IJ.d2s(0.000000001*(System.nanoTime()-startTime),3));
1373
	    		if 	(stopRequested.get()>0) {
Andrey Filippov's avatar
Andrey Filippov committed
1374 1375 1376
					if (debugLevel>0) System.out.println("User requested stop");
					break;
	    		}
Andrey Filippov's avatar
Andrey Filippov committed
1377 1378
        		continue;
        	}
1379 1380


Andrey Filippov's avatar
Andrey Filippov committed
1381
			ImageStack stack=mergeKernelsToStack(this.pdfKernelMap);
1382

Andrey Filippov's avatar
Andrey Filippov committed
1383 1384
			// TODO: Add properties,
			// Save configuration (filename with timestamp?) before files from the top class, test directory is writable
1385 1386


Andrey Filippov's avatar
Andrey Filippov committed
1387 1388 1389 1390 1391 1392 1393 1394 1395
			if (stack!=null) {
				if (debugLevel>0) System.out.println("Saving result to"+files[imgNum][1]+ " at "+ IJ.d2s(0.000000001*(System.nanoTime()-startTime),3));
				 savePartialKernelStack(
						 files[imgNum][1],
							stack,
							imp,
							psfParameters,
							correlationSizesUsed);
			} else {
1396
				System.out.println("File "+files[imgNum][1]+ " has no useful PSF kernels - at "+ IJ.d2s(0.000000001*(System.nanoTime()-startTime),3));
Andrey Filippov's avatar
Andrey Filippov committed
1397
				distortions.fittingStrategy.setNoUsefulPSFKernels(fileIndices[imgNum], true); // mark (need to save configuration) not to try them next time
1398
// todo - write a placeholder file (different suffix/prefix) instead of using		setNoUsefulPSFKernels()?
Andrey Filippov's avatar
Andrey Filippov committed
1399
			}
1400
    		if 	(stopRequested.get()>0) {
Andrey Filippov's avatar
Andrey Filippov committed
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
				if (debugLevel>0) System.out.println("User requested stop");
				break;
    		}
    	}
		return true;
	}

	public boolean combinePSFKernels ( // save configuration to combined kernels directory before calling this method
		    AtomicInteger stopRequested, // 1 - stop now, 2 - when convenient
			EyesisAberrations.InterpolateParameters  interpolateParameters, // INTERPOLATE
			EyesisAberrations.MultiFilePSF           multiFilePSF ,         // MULTIFILE_PSF = new EyesisAberrations.MultiFilePSF(
//			showDoubleFloatArrays  sdfa_instance,        // SDFA_INSTANCE
			boolean                saveResult,
			boolean                showResult,
			boolean                updateStatus,          // UPDATE_STATUS
			int                    thisDebugLevel,
			int                    globalDebugLevel
	){
		String [][] fileList=  preparePartialKernelsFilesList(
				globalDebugLevel);
    	boolean [] selectedChannels=this.aberrationParameters.getChannelSelection(distortions);
		String [] resultPaths= new String[fileList.length];
    	for (int nChn=0;nChn<selectedChannels.length;nChn++){
    		if (!selectedChannels[nChn]){
    			fileList[nChn]=null;
    		} else {
    			resultPaths[nChn]=this.aberrationParameters.psfKernelDirectory+Prefs.getFileSeparator()+
    			this.aberrationParameters.psfPrefix+String.format("%02d", nChn)+
    			this.aberrationParameters.psfSuffix;
    	    	if (!this.aberrationParameters.overwriteResultFiles){
    	    		if ((new File(resultPaths[nChn])).exists()) {
    	    			fileList[nChn]=null;
    					if (globalDebugLevel>0) System.out.println("File "+resultPaths[nChn]+" already exists and overwrite is disabled in configuration, channel "+nChn+" will be skipped");
    	    		}
    	    	}
    		}
    	}
1438

1439
		ShowDoubleFloatArrays sdfa_instance=new ShowDoubleFloatArrays();
1440 1441


Andrey Filippov's avatar
Andrey Filippov committed
1442 1443 1444
		ImagePlus              impShow=new ImagePlus("CombinedKernels");              // just to show in the same window?
		long 	  startTime=System.nanoTime();
		for (int nChn=0; nChn<fileList.length;nChn++) if (fileList[nChn]!=null){
1445
			// TODO: add parameters to kernel files
Andrey Filippov's avatar
Andrey Filippov committed
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
			boolean OK=combinePSFKernels (
					interpolateParameters, // INTERPOLATE
					multiFilePSF ,         // MULTIFILE_PSF = new EyesisAberrations.MultiFilePSF(
					fileList[nChn],
					resultPaths[nChn],
					sdfa_instance,        // SDFA_INSTANCE
					impShow, // just to show in the same window?
					saveResult,
					showResult,
					updateStatus,          // UPDATE_STATUS
					thisDebugLevel,
					globalDebugLevel);
			if (OK && (globalDebugLevel>0)) System.out.println("Saved combined kernel for channel "+nChn+" to"+resultPaths[nChn]+ " at "+ IJ.d2s(0.000000001*(System.nanoTime()-startTime),3));
1459
    		if 	(stopRequested.get()>0) {
Andrey Filippov's avatar
Andrey Filippov committed
1460 1461 1462 1463 1464 1465 1466
				if (globalDebugLevel>0) System.out.println("User requested stop");
				break;
    		}

		}
		return true;
	}
1467 1468


Andrey Filippov's avatar
Andrey Filippov committed
1469 1470 1471 1472 1473
	public boolean combinePSFKernels(
			EyesisAberrations.InterpolateParameters  interpolateParameters, // INTERPOLATE
			EyesisAberrations.MultiFilePSF           multiFilePSF ,         // MULTIFILE_PSF = new EyesisAberrations.MultiFilePSF(
			String []              filenames,
			String                 resultPath,
1474
			ShowDoubleFloatArrays  sdfa_instance,        // SDFA_INSTANCE
Andrey Filippov's avatar
Andrey Filippov committed
1475 1476 1477 1478 1479 1480
			ImagePlus              imp_sel, // just to show in the same window?
			boolean                saveResult,
			boolean                showResult,
			boolean                updateStatus,          // UPDATE_STATUS
			int                    thisDebugLevel,
			int                    globalDebugLevel
1481
	){
Andrey Filippov's avatar
Andrey Filippov committed
1482
		double [][][][] psfKernelMap; // will be lost - do we need it outside
1483
		double [][][][][] kernelsElllipsePars = new double[filenames.length][][][][]; //x0,y0,a,b,c,area
Andrey Filippov's avatar
Andrey Filippov committed
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
		if (thisDebugLevel>0){
			System.out.println("combinePSFKernels(): filenames.length="+filenames.length);
		}
//		int i;
//		int nFile;
		int impProtoIndex=-1; // image index to copy all properties from (add combine? - i.e. 32/64 correlation)
		JP46_Reader_camera jp4_instance= new JP46_Reader_camera(false);
		Opener opener=new Opener();
		for (int nFile=0;nFile<filenames.length;nFile++) {
			if (updateStatus) IJ.showStatus("Scanning file "+(nFile+1)+" (of "+(filenames.length)+"): "+filenames[nFile]);
			if (thisDebugLevel>1) System.out.println((nFile+1)+": "+filenames[nFile]);
			imp_sel=opener.openImage("", filenames[nFile]);  // or (path+filenames[nFile])
			// see if it has any usable properties and impProto is not set yet
			if (impProtoIndex<0){
				if ((imp_sel.getProperty("timestamp")==null) || (((String) imp_sel.getProperty("timestamp")).length()==0)) {
					jp4_instance.decodeProperiesFromInfo(imp_sel);
					if ((imp_sel.getProperty("timestamp")!=null) && (((String) imp_sel.getProperty("timestamp")).length()>0)) {
						impProtoIndex=nFile;
					}
				}
			}


			kernelsElllipsePars[nFile]= kernelStackToEllipseCoefficients( // null pointer
					imp_sel.getStack(), // Image stack, each slice consists of square kernels of one channel
					interpolateParameters.size, // size of each kernel (should be square)
					multiFilePSF.validateThreshold,
					globalDebugLevel);               //      threshold) // to find ellipse
		}

		// Visualize the array as stacks
		int nFiles=kernelsElllipsePars.length;
		int kHeight=kernelsElllipsePars[0].length;
		int kWidth=kernelsElllipsePars[0][0].length;
		int kLength=kHeight*kWidth;
		int nChn=imp_sel.getStack().getSize();
		int numResults=7;
		double [][][][] c= new double[numResults][nChn][nFiles+1][kLength];
		double [][][] numVals=new double[numResults][nChn][kLength];
//		int chn, tileY,tileX;
		boolean [] channels=new boolean[nChn];
		double a;
1526
		if (thisDebugLevel>1) {
Andrey Filippov's avatar
Andrey Filippov committed
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
			System.out.println("nFiles="+nFiles);
			System.out.println("kWidth="+kWidth);
			System.out.println("kHeight="+kHeight);
			System.out.println("nChn="+nChn);
		}
		Double D;
		int nOut;
		for (int chn=0;chn<nChn;chn++) {
			channels[chn]=false;
			for (int nFile=0;nFile<nFiles;nFile++) for (int tileY=0;tileY<kHeight;tileY++) for (int tileX=0;tileX<kWidth;tileX++) {
				//   			  System.out.println("nChn="+nChn+" nFile="+nFile+" tileY="+tileY+" tileX="+tileX);
				if (kernelsElllipsePars[nFile][tileY][tileX][chn]!=null) {
					channels[chn]=true;
1540 1541 1542 1543 1544
					c[0][chn][nFile+1][tileY*kWidth+tileX]=kernelsElllipsePars[nFile][tileY][tileX][chn][0]; // x0
					c[1][chn][nFile+1][tileY*kWidth+tileX]=kernelsElllipsePars[nFile][tileY][tileX][chn][1]; // y0
					c[2][chn][nFile+1][tileY*kWidth+tileX]=kernelsElllipsePars[nFile][tileY][tileX][chn][2]; // a
					c[3][chn][nFile+1][tileY*kWidth+tileX]=kernelsElllipsePars[nFile][tileY][tileX][chn][3]; // b
					c[4][chn][nFile+1][tileY*kWidth+tileX]=kernelsElllipsePars[nFile][tileY][tileX][chn][4]; // c
Andrey Filippov's avatar
Andrey Filippov committed
1545 1546 1547
					a=1/Math.sqrt(kernelsElllipsePars[nFile][tileY][tileX][chn][2]*kernelsElllipsePars[nFile][tileY][tileX][chn][3]-
							kernelsElllipsePars[nFile][tileY][tileX][chn][4]*kernelsElllipsePars[nFile][tileY][tileX][chn][4]/4);
					c[5][chn][nFile+1][tileY*kWidth+tileX]= Math.sqrt(a); // radius
1548
					c[6][chn][nFile+1][tileY*kWidth+tileX]=kernelsElllipsePars[nFile][tileY][tileX][chn][5]; // area
Andrey Filippov's avatar
Andrey Filippov committed
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561

				} else {
					c[0][chn][nFile+1][tileY*kWidth+tileX]=Double.NaN;
					c[1][chn][nFile+1][tileY*kWidth+tileX]=Double.NaN;
					c[2][chn][nFile+1][tileY*kWidth+tileX]=Double.NaN;
					c[3][chn][nFile+1][tileY*kWidth+tileX]=Double.NaN;
					c[4][chn][nFile+1][tileY*kWidth+tileX]=Double.NaN;
					c[5][chn][nFile+1][tileY*kWidth+tileX]=Double.NaN;
					c[6][chn][nFile+1][tileY*kWidth+tileX]=Double.NaN;
				}

			}
		}
1562
		/*
Andrey Filippov's avatar
Andrey Filippov committed
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
		 * Combine files - now just average all that are not NaN
		 */
		int [][] dirs={{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}};
//		int yn,xn,index;
		// remove any tiles that are not OK in all channels
		double [][] weights=new double[nFiles+1][kLength];
		for (int nFile=0;nFile<nFiles;nFile++) {
			for (int i=0;i<kLength;i++){
				weights[nFile+1][i]=1.0;
				for (int chn=0;chn<nChn;chn++) {
					D=c[0][chn][nFile+1][i];
					if (D.isNaN()) weights[nFile+1][i]=0.0;
				}
			}
1577
			// Set weight to 0.5 if it has zero cells around
Andrey Filippov's avatar
Andrey Filippov committed
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
			for (int tileY=0;tileY<kHeight;tileY++) for (int tileX=0;tileX<kWidth;tileX++) {
				int index=tileY*kWidth+tileX;
				if ( weights[nFile+1][index]>0.0){
					for (int i=0;i<dirs.length;i++) {
						int yn=tileY+dirs[i][1];
						int xn=tileX+dirs[i][0];
						if ((yn>=0) && (yn<kHeight) && (xn>=0) && (xn<kWidth) && (weights[nFile+1][yn*kWidth+xn]==0.0)){
							weights[nFile+1][index]=0.5; // multiFilePSF.weightOnBorder; //0.5->0.01;
						}
					}
1588 1589
				}
				weights[0][index]+=weights[nFile+1][index];
Andrey Filippov's avatar
Andrey Filippov committed
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
			}
		}
		if (thisDebugLevel>1) sdfa_instance.showArrays(weights, kWidth, kHeight,  true, "weights0");

		// remove any border ones if non-border is present in the same cell
		double [][] weightsMasked=new double[weights.length][];
		for (int i=0;i<weights.length;i++) weightsMasked[i]=weights[i].clone();
		double [][] weightsNotMasked=new double[weights.length][];
		for (int i=0;i<weights.length;i++) weightsNotMasked[i]=weights[i].clone();
		for (int i=0;i<kLength;i++){
			weightsMasked[0][i]=0.0;
			double maxWeight=0.0;
			for (int nFile=0;nFile<nFiles;nFile++)if (weightsMasked[nFile+1][i]>maxWeight) maxWeight=weightsMasked[nFile+1][i];
			for (int nFile=0;nFile<nFiles;nFile++) if ((weightsMasked[nFile+1][i]<1.0) && (maxWeight >= 1.0)) weightsMasked[nFile+1][i]=0.0; // do not count  half-weights if full one(s) are present
			for (int nFile=0;nFile<nFiles;nFile++)  weightsMasked[0][i]+=weightsMasked[nFile+1][i];
		}
		if (thisDebugLevel>1) sdfa_instance.showArrays(weightsMasked, kWidth, kHeight,  true, "weightsMasked");
1607

Andrey Filippov's avatar
Andrey Filippov committed
1608
		double [][][] psfRadius=c[5]; // later may remove all other calculations for c[i]?
1609
		double [][][] pxfCenterX=c[0]; // some outlier kernels have large x/y shift with normal radius - remove them too
Andrey Filippov's avatar
Andrey Filippov committed
1610 1611 1612 1613 1614 1615 1616
		double [][][] pxfCenterY=c[1];
		if (thisDebugLevel>1) {
			for (int color=0;color<nChn;color++) sdfa_instance.showArrays(psfRadius[color], kWidth, kHeight,  true, "psfRadius-"+color);
			for (int color=0;color<nChn;color++) sdfa_instance.showArrays(pxfCenterX[color], kWidth, kHeight,  true, "pxfCenterX-"+color);
			for (int color=0;color<nChn;color++) sdfa_instance.showArrays(pxfCenterY[color], kWidth, kHeight,  true, "pxfCenterY-"+color);
		}
		double [][][] radiusRatio=new double[nChn][nFiles+1][kLength];
1617 1618 1619 1620
		int ref_color = 2; // green
		if (ref_color >= nChn) {
			ref_color = 0;
		}
Andrey Filippov's avatar
Andrey Filippov committed
1621 1622 1623 1624 1625 1626 1627 1628
		for (int tileY=0;tileY<kHeight;tileY++) for (int tileX=0;tileX<kWidth;tileX++) {
			int index=tileY*kWidth+tileX;
			int totalNumSamples=0;
			for (int nFile=0;nFile<nFiles;nFile++) if ( weights[nFile+1][index]>0.0) totalNumSamples++;
			int samplesAfterWorse=totalNumSamples - ((int) Math.floor(multiFilePSF.maxFracDiscardWorse*totalNumSamples));
			int samplesAfterAll=  totalNumSamples - ((int) Math.floor(multiFilePSF.maxFracDiscardAll*totalNumSamples));

			int numSamples=totalNumSamples;
1629

Andrey Filippov's avatar
Andrey Filippov committed
1630 1631 1632 1633 1634 1635 1636 1637
			while (numSamples>samplesAfterAll){ // calculate and remove worst sample until it is close enough to the average or too few samples are left
				boolean removeOnlyWorse=numSamples>samplesAfterWorse;
				for (int color=0;color<nChn;color++){
					radiusRatio[color][0][index]=0.0;
					pxfCenterX[color][0][index]=0.0; // same as c[0], zero before calculating average
					pxfCenterY[color][0][index]=0.0;
				}
				double sumWeights=0.0;
1638
				for (int nFile=0;nFile<nFiles;nFile++) 	if ((weightsMasked[nFile+1][index]>0.0) && (weights[nFile+1][index]>0.0)){ // both, with outliers removed
Andrey Filippov's avatar
Andrey Filippov committed
1639 1640 1641
					for (int i=0;i<dirs.length;i++) {
						int yn=tileY+dirs[i][1];
						int xn=tileX+dirs[i][0];
1642
						if ((yn>=0) && (yn<kHeight) && (xn>=0) && (xn<kWidth) && (weightsNotMasked[nFile+1][yn*kWidth+xn]>0.0)){ // including removed outliers
Andrey Filippov's avatar
Andrey Filippov committed
1643 1644 1645
							int indexNeib=xn+ kWidth*yn;
							double weight=weightsMasked[nFile+1][indexNeib];
							if (multiFilePSF.sharpBonusPower>0) {
1646
								weight/=Math.pow(psfRadius[ref_color][nFile+1][indexNeib],multiFilePSF.sharpBonusPower); // use green color ava.lang.ArrayIndexOutOfBoundsException: 2
Andrey Filippov's avatar
Andrey Filippov committed
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
							}
							sumWeights+=weight;
							for (int color=0;color<nChn;color++) {
								radiusRatio[color][0][index]+=weight*psfRadius[color][nFile+1][indexNeib];
								pxfCenterX[color][0][index]+=weight*pxfCenterX[color][nFile+1][indexNeib];
								pxfCenterY[color][0][index]+=weight*pxfCenterY[color][nFile+1][indexNeib];
							}
						}
					}
				}
				/*
			System.out.println(tileY+":"+tileX+" - "+IJ.d2s(radiusRatio[0][0][index],3)+
					" "+IJ.d2s(radiusRatio[1][0][index],3)+
					" "+IJ.d2s(radiusRatio[2][0][index],3)+
					" sumWeights="+IJ.d2s(sumWeights,3));
				 */
				if (sumWeights>0.0) for (int color=0;color<nChn;color++) {
1664 1665 1666
					radiusRatio[color][0][index]/=sumWeights; // average radius, without border-over-non-border cells
					pxfCenterX[color][0][index]/=sumWeights;
					pxfCenterY[color][0][index]/=sumWeights;
Andrey Filippov's avatar
Andrey Filippov committed
1667 1668 1669 1670
				}
				double [] diffs=new double[nFiles];
				double [] diffsXY2=new double[nFiles];
//				for (int nFile=0;nFile<nFiles;nFile++) 	if ( weights[nFile+1][index]>0.0){ // here all , not just masked - why?
1671
				for (int nFile=0;nFile<nFiles;nFile++) 	if ((weights[nFile+1][index]>0.0) && (weightsMasked[nFile+1][index]>0.0)){ //no outliers, no masked - find worst
Andrey Filippov's avatar
Andrey Filippov committed
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
					diffs[nFile]=0;
					diffsXY2[nFile]=0;
					for (int color=0;color<nChn;color++) {
						radiusRatio[color][nFile+1][index]=psfRadius[color][nFile+1][index]/radiusRatio[color][0][index];
						double diff=(radiusRatio[color][nFile+1][index]>1.0)?(radiusRatio[color][nFile+1][index]-1.0):(1.0/radiusRatio[color][nFile+1][index]-1.0);
						if (diff>diffs[nFile]) diffs[nFile]=diff; // worst of 3 colors
						double diffX=pxfCenterX[color][nFile+1][index]-pxfCenterX[color][0][index];
						double diffY=pxfCenterY[color][nFile+1][index]-pxfCenterY[color][0][index];
						double diffXY2=diffX*diffX+diffY*diffY;
						if (diffXY2>diffsXY2[nFile]) diffsXY2[nFile]=diffXY2; // worst of 3 colors
						if (removeOnlyWorse && (psfRadius[color][nFile+1][index]<radiusRatio[color][0][index])) diffXY2=0.0; // only remove if radius is greater than average
						diffs[nFile]+=multiFilePSF.shiftToRadiusContrib*(Math.sqrt(diffXY2)/radiusRatio[color][0][index]); // now difference combines size and position
					}
				}
1686
				// mask out outliers
Andrey Filippov's avatar
Andrey Filippov committed
1687 1688 1689
				//weightsMasked[0]

				// TODO: when averaging, divide by r^2 to some power to give bonus low-radius samples.
1690
				//       also - combine dX^2+dY2+dR^2 when selecting outliers
Andrey Filippov's avatar
Andrey Filippov committed
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
				if (thisDebugLevel>1) {
					System.out.print("\n === "+tileY+":"+tileX);
					for (int nFile=0;nFile<nFiles;nFile++) if ( weights[nFile+1][index]>0.0){
						System.out.print(" "+nFile);
					}
					System.out.println();
				}

				//			while (true){
//				int numSamples=0;
				numSamples=0;
				double worstDiff=0.0;
				int worstFile=0;
				for (int nFile=0;nFile<nFiles;nFile++) if ( weights[nFile+1][index]>0.0){
					numSamples++;
					int numNeib=0;
					for (int i=0;i<dirs.length;i++) {
						int yn=tileY+dirs[i][1];
						int xn=tileX+dirs[i][0];
						if ((yn>=0) && (yn<kHeight) && (xn>=0) && (xn<kWidth) && (weights[nFile+1][yn*kWidth+xn]>0.0))numNeib++;
					}
					double scale= 8.0/(8.0+  multiFilePSF.internalBonus*numNeib); // make internal cells look better
					double diff=diffs[nFile]*scale;
					if (diff>worstDiff){
						worstDiff=diff;
						worstFile=nFile;
					}
					if (thisDebugLevel>2) {
						System.out.println(tileY+":"+tileX+" - "+
								" nFile="+nFile+
								" scale=="+IJ.d2s(scale,3)+
								" diff="+diff+
								" numNeib="+numNeib);
						}

				}
				if (thisDebugLevel>1) {
				System.out.println(tileY+":"+tileX+" - "+
						" numSamples="+numSamples+
						" worstDiff="+IJ.d2s(worstDiff,3)+
						" removeOnlyWorse="+removeOnlyWorse+
						" worstFile="+worstFile+" ("+filenames[worstFile]+")");
1733

Andrey Filippov's avatar
Andrey Filippov committed
1734 1735 1736
				System.out.println(
						" this radius  ={"+psfRadius[0][worstFile+1][index]+","+psfRadius[1][worstFile+1][index]+","+psfRadius[2][worstFile+1][index]+"}\n"+
						" mean radius  ={"+radiusRatio[0][0][index]+","+radiusRatio[1][0][index]+","+radiusRatio[2][0][index]+"}\n"+
1737

Andrey Filippov's avatar
Andrey Filippov committed
1738 1739
						" this center X={"+pxfCenterX[0][worstFile+1][index]+","+pxfCenterX[1][worstFile+1][index]+","+pxfCenterX[2][worstFile+1][index]+"}\n"+
						" mean center X={"+pxfCenterX[0][0][index]+","+pxfCenterX[1][0][index]+","+pxfCenterX[2][0][index]+"}\n"+
1740

Andrey Filippov's avatar
Andrey Filippov committed
1741 1742 1743
						" this center Y={"+pxfCenterY[0][worstFile+1][index]+","+pxfCenterY[1][worstFile+1][index]+","+pxfCenterY[2][worstFile+1][index]+"}\n"+
						" mean center Y={"+pxfCenterY[0][0][index]+","+pxfCenterY[1][0][index]+","+pxfCenterY[2][0][index]+"}");
				}
1744
				if (numSamples<1) break; // nothing left
Andrey Filippov's avatar
Andrey Filippov committed
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
				if (worstDiff>multiFilePSF.radiusDiffHigh){
					if ( (numSamples==1) && (globalDebugLevel>0)){
						System.out.println("PSF size for the cell "+tileX+":"+tileY+", file# "+worstFile+" varies too much from the neighbor cells, so it is removed, creating a gap");
					}
					weights[worstFile+1][index]=0.0;
					continue;
				} else if ((worstDiff>multiFilePSF.radiusDiffLow) && (numSamples>1)){
					weights[worstFile+1][index]=0.0;
					continue;
				}
				break;
			}
			// recalculate sum of weights;
			weights[0][index]=0.0;
			for (int nFile=0;nFile<nFiles;nFile++) if ( weights[nFile+1][index]>0.0){
				weights[0][index]+=weights[nFile+1][index];
			}
		}
1763 1764


Andrey Filippov's avatar
Andrey Filippov committed
1765
		// for each channel, each cell - compare radius calculated for neighbors (use masked weights) and the cell
1766 1767


1768
		// TODO: Filter out outliers: Add bonus to cells surrounded by others?
1769 1770


Andrey Filippov's avatar
Andrey Filippov committed
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
		//    	double [][][][] c= new double[numResults][nChn][nFiles+1][kLength];
		//     	double [][][] numVals=new double[numResults][nChn][kLength];
		for (int chn=0;chn<nChn;chn++) {

			for (nOut=0;nOut<c.length;nOut++) {
				c[nOut][chn][0]=null;
				for (int i=0;i<kLength;i++) {
					numVals[nOut][chn][i]=0.0;
				}
			}
			if (channels[chn]) {
				for (nOut=0;nOut<c.length;nOut++) {
					c[nOut][chn][0]=new double [kLength];
					for (int nFile=0;nFile<nFiles;nFile++) {
						for (int i=0;i<kLength;i++){
							D=c[nOut][chn][nFile+1][i];
							if (!D.isNaN()){
								numVals[nOut][chn][i]+=1.0;
								c[nOut][chn][0][i]+=D*weights[nFile+1][i]/weights[0][i];
							}
						}

					}
					for (int i=0;i<kLength;i++){
						if (numVals[nOut][chn][i]==0.0 )c[nOut][chn][0][i]=Double.NaN;
						//    			  else c[nOut][chn][0][i]/=numVals[nOut][chn][i];
1797
					}
Andrey Filippov's avatar
Andrey Filippov committed
1798
				}
1799

Andrey Filippov's avatar
Andrey Filippov committed
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
				if (multiFilePSF.validateShowEllipse) {
						sdfa_instance.showArrays(radiusRatio[chn], kWidth, kHeight,  true, "ratio-"+chn);
						sdfa_instance.showArrays(c[5][chn],kWidth, kHeight,  true, "radius-"+chn);
					if (thisDebugLevel>1) {
						sdfa_instance.showArrays(c[0][chn], kWidth, kHeight,  true, "x-shift-"+chn);
						sdfa_instance.showArrays(c[1][chn], kWidth, kHeight,  true, "y-shift-"+chn);
						sdfa_instance.showArrays(c[2][chn], kWidth, kHeight,  true, "x2-"+chn);
						sdfa_instance.showArrays(c[3][chn], kWidth, kHeight,  true, "y2-"+chn);
						sdfa_instance.showArrays(c[4][chn], kWidth, kHeight,  true, "xy-"+chn);
						sdfa_instance.showArrays(c[6][chn], kWidth, kHeight,  true, "area-"+chn);
1810
					}
Andrey Filippov's avatar
Andrey Filippov committed
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
				}
			}

		}
		if (multiFilePSF.showWeights) sdfa_instance.showArrays(weights, kWidth, kHeight,  true, "weights");
		//    	double [][] weights=new double[nFiles+1][kLength];
		for (int i=0;i<kLength;i++) weights[0][i]=0.0;
		psfKernelMap=new double [kHeight][kWidth][nChn][];
		for (int tileY=0;tileY<kHeight;tileY++) for (int tileX=0;tileX<kWidth;tileX++) for (int chn=0;chn<nChn;chn++){
			psfKernelMap[tileY][tileX][chn]=null;
		}
		String [] originalSliceLabels=null;
		for (int nFile=0;nFile<nFiles;nFile++) {
			if (updateStatus) IJ.showStatus("Accumulating file "+(nFile+1)+" (of "+nFiles+"): "+filenames[nFile]);
			if (thisDebugLevel>1) System.out.println("Accumulating file "+nFile+": "+filenames[nFile]);
			imp_sel=opener.openImage("", filenames[nFile]);  // or (path+filenames[nFile])
			if (originalSliceLabels==null) {
				originalSliceLabels=imp_sel.getStack().getSliceLabels();
			}
			accumulatePartialKernelStack(
					psfKernelMap,
					imp_sel.getStack(), // Image stack with partial array of kernels, each slice consists of square kernels of one channel
					interpolateParameters.size, // size of each kernel (should be square)
					weights[nFile+1], // weights of the kernel tiles in the current stack
					weights[0],
					globalDebugLevel);// weights of the kernel tiles already accumulated (will be updated)

		}
// optionally fill in blanks from nearest neighbors
		int filledMissing=0;
		//Finalize accumulated kernels - transform them from frequency to space domain
		inverseTransformKernels(psfKernelMap);
1843
// should be done after inversion, because filled in kernels are just pointers to original ones
Andrey Filippov's avatar
Andrey Filippov committed
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
		if (multiFilePSF.fillMissing) filledMissing=fillMissingKernels (psfKernelMap);
		int numMissing=0;
		ImageStack mergedStack= mergeKernelsToStack(psfKernelMap,originalSliceLabels);
		System.out.println("mergedStack.getSize()= "+mergedStack.getSize());
		System.out.println("mergedStack.getWidth()= "+mergedStack.getWidth()  );
		System.out.println("mergedStack.getHeight()= "+mergedStack.getHeight()  );
		System.out.println("psfKernelMaplength= "+psfKernelMap.length  );
		System.out.println("psfKernelMap[0].length= "+psfKernelMap[0].length  );
		System.out.println("mergedStack= "+((mergedStack==null)?"null":"not null"));

		if (mergedStack.getSize()==0) {
			System.out.println("*** Error - result is empty");
			return false;
		}

		for (int tileY=0;tileY<kHeight;tileY++) for (int tileX=0;tileX<kWidth;tileX++) if ((psfKernelMap[tileY][tileX]==null) || (psfKernelMap[tileY][tileX][0]==null)) numMissing++;
        ImagePlus imp_psf = new ImagePlus(resultPath, mergedStack);
1861

Andrey Filippov's avatar
Andrey Filippov committed
1862
        if (impProtoIndex>=0){
1863
			imp_sel=opener.openImage("", filenames[impProtoIndex]);
Andrey Filippov's avatar
Andrey Filippov committed
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
			jp4_instance.decodeProperiesFromInfo(imp_sel);
			// copy properties from the source image
			jp4_instance.copyProperties (imp_sel,imp_psf);
        }
        multiFilePSF.setProperties("MULTIFILE_PSF.", imp_psf);
  // other properties
		jp4_instance.encodeProperiesToInfo(imp_psf);
        if (showResult) {
        	imp_psf.getProcessor().resetMinAndMax();
        	imp_psf.show();
        }
		if (saveResult) {
			if (numMissing==0) {
			  if (thisDebugLevel>1) System.out.println("Saving result to "+resultPath);
			  FileSaver fs=new FileSaver(imp_psf);
1879 1880
//			  fs.saveAsTiffStack(resultPath);
			  fs.saveAsTiff(resultPath);
Andrey Filippov's avatar
Andrey Filippov committed
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
			  if (multiFilePSF.fillMissing && (filledMissing>0)) {
					System.out.println("*** Warning "+filledMissing+" kernel tiles are missing from the results (insufficient overlap) \n"+
					"You may disable filling missing kernels from neighbors in Conf. Multifile");
/*
  					IJ.showMessage("Warning",filledMissing+" kernel tiles were missing from the results\n"+
 							"(i.e.insufficient overlap) and filled from neighbors, it is OK only for the fisheye lens.\n"+
					        "You may disable filling missing kernels from neighbors in Conf. Multifile");*/
			  }
			  return true;
			} else {
				System.out.println("*** Error "+numMissing+" kernel tiles are missing from the results (insufficient overlap), result is not saved\n"+
				"You may enable filling missing kernels from neighbors if it is a fisheye lens (in Conf. Multifile)");

				IJ.showMessage("Error",numMissing+" kernel tiles are missing from the results\n (insufficient overlap), result file is not saved\n"+
				"You may enable filling missing kernels from neighbors if it is a fisheye lens (in Conf. Multifile)");

				if (!showResult) { // not yet shown
		        	imp_psf.getProcessor().resetMinAndMax();
		        	imp_psf.show();
				}
				return false;
			}
		}
		if (numMissing>0) {
			System.out.println("*** Error "+numMissing+" kernel tiles are missing from the results (insufficient overlap) \n"+
					"You may enable filling missing kernels from neighbors if it is a fisheye lens (in Conf. Multifile)");
			IJ.showMessage("Error",numMissing+" kernel tiles are missing from the results\n (insufficient overlap)\n"+
					"You may enable filling missing kernels from neighbors if it is a fisheye lens (in Conf. Multifile)");
			return false;

		} else if (multiFilePSF.fillMissing && (filledMissing>0)) {
			System.out.println("*** Warning "+filledMissing+" kernel tiles are missing from the results (insufficient overlap) \n"+
			"You may disable filling missing kernels from neighbors in Conf. Multifile");
			IJ.showMessage("Warning",filledMissing+" kernel tiles were missing from the results\n"+
					"(i.e.insufficient overlap) and filled from neighbors, it is OK only for the fisheye lens.\n"+
			        "You may disable filling missing kernels from neighbors in Conf. Multifile");
		}
		return true;
	}
1920

Andrey Filippov's avatar
Andrey Filippov committed
1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
	private int fillMissingKernels(double [][][][] kernels){
		int [][] dirs={{-1,0},{1,0},{0,-1},{0,1}};
		List <Integer> kernelList=new ArrayList<Integer>(100);
		Integer Index;
		kernelList.clear();
		int tileY,tileX,newTileY,newTileX,nDir,numMissing=0;
		int width= kernels[0].length;
		int height=kernels.length;
		for (tileY=0;tileY<height;tileY++) for (tileX=0;tileX<width;tileX++) {
			if ((kernels[tileY][tileX]==null) || (kernels[tileY][tileX][0]==null)) {
				Index=tileY*width+tileX;
				for (nDir=0;nDir<dirs.length;nDir++) {
					newTileX=tileX+dirs[nDir][0];
					newTileY=tileY+dirs[nDir][1];
					if ((newTileX>=0) && (newTileY>=0) && (newTileX<width) && (newTileY<height) &&
							(kernels[newTileY][newTileX]!=null) && (kernels[newTileY][newTileX][0]!=null) ) {
						kernelList.add(Index);
					}
1939
				}
Andrey Filippov's avatar
Andrey Filippov committed
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
				numMissing++;
			}
		}
		System.out.println("fillMissingKernels: numMissing="+numMissing);
		System.out.println("fillMissingKernels: kernelList.size()="+kernelList.size());

		while (kernelList.size()>0) {
			Index=kernelList.get(0);
			kernelList.remove(0);
			tileY=Index/width;
			tileX=Index%width;
			if ((kernels[tileY][tileX]==null) || (kernels[tileY][tileX][0]==null)) {// may be duplicates (added several times)
//TODO: - change order of directions?
				for (nDir=0;nDir<dirs.length;nDir++) {
					newTileX=tileX+dirs[nDir][0];
					newTileY=tileY+dirs[nDir][1];
					if ((newTileX>=0) && (newTileY>=0) && (newTileX<width) && (newTileY<height)) {
						if ((kernels[newTileY][newTileX]==null) || (kernels[newTileY][newTileX][0]==null)) {
							Index=newTileY*width+newTileX;
							kernelList.add(Index);
						} else if ((kernels[tileY][tileX]==null) || (kernels[tileY][tileX][0]==null)) { // may be already added
1961
// need to copy - they will be subject to reverse fht	?
Andrey Filippov's avatar
Andrey Filippov committed
1962 1963 1964 1965 1966 1967 1968 1969 1970
							kernels[tileY][tileX]=kernels[newTileY][newTileX];
							System.out.println("fillMissingKernels: filled "+tileX+"/"+tileY);
						}
					}
				}
			}
		}
		return numMissing;
	}
1971 1972 1973



Andrey Filippov's avatar
Andrey Filippov committed
1974
	/* ======================================================================== */
Andrey Filippov's avatar
Andrey Filippov committed
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
	//Finalize accumulated kernels - transform them from frequency to space domain
	public void inverseTransformKernels(
			double [][][][] psfKernelMap){
		DoubleFHT fht_instance =new DoubleFHT(); // provide DoubleFHT instance to save on initializations (or null)
		int tilesX=psfKernelMap[0].length;
		int tilesY=psfKernelMap.length;
		int tileY,tileX, chn; //,subTileY,subTileX;
		for (tileY=0;tileY<tilesY;tileY++) for (tileX=0;tileX<tilesX;tileX++) for (chn=0; chn<psfKernelMap[tileY][tileX].length; chn++){
			if (psfKernelMap[tileY][tileX][chn]!=null) {
				fht_instance.inverseTransform(psfKernelMap[tileY][tileX][chn]);
				fht_instance.swapQuadrants   (psfKernelMap[tileY][tileX][chn]);
			}
		}
	}


1991 1992 1993



Andrey Filippov's avatar
Andrey Filippov committed
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
	// Will build global PSF_KERNEL_MAP (each [][][]element should be set to null?
	// kernels are supposed to be normalized?
	public void accumulatePartialKernelStack(
			double [][][][] psfKernelMap,
			ImageStack   kernelStack, // Image stack with partial array of kernels, each slice consists of square kernels of one channel
			int                 size, // size of each kernel (should be square)
			double []   theseWeights, // weights of the kernel tiles in the current stack
			double []   accumWeights,// weights of the kernel tiles already accumulated (will be updated)
			int debugLevel){
		DoubleFHT fht_instance =new DoubleFHT(); // provide DoubleFHT instance to save on initializations (or null)
		int tilesX=kernelStack.getWidth()/size;
		int tilesY=kernelStack.getHeight()/size;
		int nChn=kernelStack.getSize();
		int tileY,tileX, chn; //,subTileY,subTileX;
		float [] pixels;
		int length=size*size;
		double [] kernel=new double[length];
		int index;
		int debugTileX=18;
		int debugTileY=22;
		int debugIndex=debugTileY*tilesX+debugTileX;
		boolean lastChn;
		for (chn=0;chn<nChn;chn++) {
			pixels=(float[]) kernelStack.getPixels(chn+1);
			lastChn= (chn==(nChn-1));
			for (tileY=0;tileY<tilesY;tileY++) for (tileX=0;tileX<tilesX;tileX++) {
				index=tileY*tilesX+tileX;
				boolean debugThis= (index==debugIndex) && (debugLevel>1);
				if (theseWeights[index]>0.0){
					extractOneKernel(
2024
							pixels, //  array of combined square kernels, each
Andrey Filippov's avatar
Andrey Filippov committed
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
							kernel, // will be filled, should have correct size before call
							tilesX, // number of kernels in a row
							tileX, // horizontal number of kernel to extract
							tileY); // vertical number of kernel to extract
					// convert to frequency domain (interpolation is for FHT)
					fht_instance.swapQuadrants(kernel);
					fht_instance.transform(    kernel);
					if (debugThis) System.out.println("tileY="+tileY+" tileX="+tileX+" chn= "+chn+
							" theseWeights["+index+"]="+theseWeights[index]+" accumWeights["+index+"]="+accumWeights[index]);
					if (!(accumWeights[index]>0.0)) { // nothing yet in this tile
						psfKernelMap[tileY][tileX][chn]=kernel.clone();
						if (lastChn) accumWeights[index]=theseWeights[index];
					} else { // "accumulate" - interpolate between existent and new kernel, using/updating weights
						if (debugLevel>5) {
							System.out.println("tileY="+tileY+" tileX="+tileX+" chn= "+chn);
							System.out.println("PSF_KERNEL_MAP[tileY][tileX][chn].length= "+psfKernelMap[tileY][tileX][chn].length);
							System.out.println("kernel.length= "+kernel.length);
						}

//						kernel=fht_instance.interpolateFHT (
						psfKernelMap[tileY][tileX][chn]=fht_instance.interpolateFHT (
								psfKernelMap[tileY][tileX][chn],    // first FHT array
								kernel,    // second FHT array
								theseWeights[index]/accumWeights[index]);    //interpolation ratio - 0.0 - fht0, 1.0 - fht1
						if (lastChn) accumWeights[index]+=theseWeights[index];
					}
				}
			}
		}
	}

2056 2057


Andrey Filippov's avatar
Andrey Filippov committed
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
	public double [][][][] kernelStackToEllipseCoefficients(
			ImageStack kernelStack, // Image stack, each slice consists of square kernels of one channel
			int               size, // size of each kernel (should be square)
			double       threshold,
			int         debugLevel) // to find ellipse
	// update status info
	{
		//	  DoubleFHT fht_instance =new DoubleFHT(); // provide DoubleFHT instance to save on initializations (or null)
		if (kernelStack==null) return null;
		int tilesX=kernelStack.getWidth()/size;
		int tilesY=kernelStack.getHeight()/size;
		int nChn=kernelStack.getSize();
		float [] pixels;
		int i,j;
		int tileY,tileX, chn; //,subTileY,subTileX;
		double [][][][] ellipseCoeffs=new double [tilesY][tilesX][nChn][];
		int length=size*size;
2075
		double [] kernel=new double[length];
Andrey Filippov's avatar
Andrey Filippov committed
2076 2077 2078 2079 2080 2081 2082 2083
		double max;
		int  [][]selection;
		double [] ec;
		int l;
		for (chn=0;chn<nChn;chn++) {
			pixels=(float[]) kernelStack.getPixels(chn+1);
			for (tileY=0;tileY<tilesY;tileY++) for (tileX=0;tileX<tilesX;tileX++) {
				extractOneKernel(
2084
						pixels, //  array of combined square kernels, each
Andrey Filippov's avatar
Andrey Filippov committed
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
						kernel, // will be filled, should have correct size before call
						tilesX, // number of kernels in a row
						tileX, // horizontal number of kernel to extract
						tileY); // vertical number of kernel to extract
				max=0.0;
				for (i=0;i<length;i++) if (max<kernel[i]) max=kernel[i];
				if (max<=0.0) ellipseCoeffs[tileY][tileX][chn]=null;
				else {
					selection= findClusterOnPSF(
							kernel, // PSF function, square array
							threshold, // fraction of energy in the pixels to be used
					"",
					debugLevel);
					//				  ellipseCoeffs[tileY][tileX][chn]=findEllipseOnPSF(kernel,  selection,   "");
2099 2100
					ec=findEllipseOnPSF(kernel,  selection,   "", debugLevel); // x0,y0,a,b,c (r2= a* x^2*+b*y^2+c*x*y)

Andrey Filippov's avatar
Andrey Filippov committed
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
					l=ec.length;
					ellipseCoeffs[tileY][tileX][chn]=new double[l+1];
					for (i=0;i<ec.length;i++) ellipseCoeffs[tileY][tileX][chn][i]=ec[i];
					ellipseCoeffs[tileY][tileX][chn][l]=0;
					for (i=0;i<selection.length;i++) for (j=0;j<selection[0].length;j++) ellipseCoeffs[tileY][tileX][chn][l]+=selection[i][j];
				}
			}
		}
		return ellipseCoeffs;

2111 2112
	}

Andrey Filippov's avatar
Andrey Filippov committed
2113
	/* ======================================================================== */
Andrey Filippov's avatar
Andrey Filippov committed
2114
	private void extractOneKernel(
2115
			float []  pixels, //  array of combined square kernels, each
Andrey Filippov's avatar
Andrey Filippov committed
2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
			double [] kernel, // will be filled, should have correct size before call
			int       numHor, // number of kernels in a row
			int        xTile, // horizontal number of kernel to extract
			int        yTile) { // vertical number of kernel to extract
		int length=kernel.length;
		int size=(int) Math.sqrt(length);
		int i,j;
		int pixelsWidth=numHor*size;
		int pixelsHeight=pixels.length/pixelsWidth;
		int numVert=pixelsHeight/size;
Andrey Filippov's avatar
Andrey Filippov committed
2126
/* limit tile numbers - effectively add margins around the known kernels */
Andrey Filippov's avatar
Andrey Filippov committed
2127 2128 2129 2130 2131 2132 2133 2134
		if (xTile<0) xTile=0;
		else if (xTile>=numHor) xTile=numHor-1;
		if (yTile<0) yTile=0;
		else if (yTile>=numVert) yTile=numVert-1;
		int base=(yTile*pixelsWidth+xTile)*size;
		for (i=0;i<size;i++) for (j=0;j<size;j++) kernel [i*size+j]=pixels[base+i*pixelsWidth+j];
	}

2135 2136 2137 2138 2139 2140





//=======================================================
Andrey Filippov's avatar
Andrey Filippov committed
2141 2142 2143 2144 2145 2146 2147
	public void savePartialKernelStack(
			String path,
			ImageStack stack,
			ImagePlus impSrc, // properties - decoded
			PSFParameters psfParameters,
			boolean [] correlationSizesUsed
	){
2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
		int [] corrSizes={};
		if (correlationSizesUsed!=null) {
			int numDifferentFFT=0;
			for (int i=0;i<correlationSizesUsed.length;i++) if (correlationSizesUsed[i]) {
				numDifferentFFT++;
			}
			corrSizes=new int [numDifferentFFT];
			int index=0;
			for (int i=0;i<correlationSizesUsed.length;i++) if (correlationSizesUsed[i]) {
				corrSizes[index++]=1<<i;
			}
Andrey Filippov's avatar
Andrey Filippov committed
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
		}
		ImagePlus impPsf = new ImagePlus(path, stack);

		JP46_Reader_camera jp4_instance= new JP46_Reader_camera(false);
		if ((impSrc.getProperty("timestamp")==null) || (((String) impSrc.getProperty("timestamp")).length()==0)) {
			jp4_instance.decodeProperiesFromInfo(impSrc);
		}
		// copy properies from the source image
		jp4_instance.copyProperties (impSrc,impPsf);
		// save psf parameters (same as in configuration file)
		psfParameters.setProperties("PSF_PARS.", impPsf);
		for (int i=0;i<corrSizes.length;i++){
			impPsf.setProperty("corr_size_"+corrSizes[i], true+"");
		}
//TODO:  Add more properties?

		jp4_instance.encodeProperiesToInfo(impPsf);
		FileSaver fs=new FileSaver(impPsf);
2177 2178
//		fs.saveAsTiffStack(path);
		fs.saveAsTiff(path);
Andrey Filippov's avatar
Andrey Filippov committed
2179
	}
2180 2181 2182



Andrey Filippov's avatar
Andrey Filippov committed
2183 2184 2185 2186 2187 2188 2189 2190
	private  ImageStack mergeKernelsToStack(double [][][][] kernels) {
		return mergeKernelsToStack(kernels,null);

	}
	private  ImageStack mergeKernelsToStack(double [][][][] kernels,String [] names) { // use oldStack.getSliceLabels() to get names[]
		if (kernels==null) return null;
		int tilesY=kernels.length;
		int tilesX=kernels[0].length;
2191
		int i=0,j=0,k,nChn, chn,x,y,index;
Andrey Filippov's avatar
Andrey Filippov committed
2192
		double [][]kernel=null;
2193 2194 2195 2196
		for (i=0;(i<tilesY) && (kernel==null);i++) {
			for (j=0;(j<tilesX) && (kernel==null);j++) {
				kernel=kernels[i][j];
			}
Andrey Filippov's avatar
Andrey Filippov committed
2197
		}
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
		System.out.println("Got non-empty kernel at "+i+":"+j);

		if (kernel==null) return null;
///		int length=0;
///		for (i=0;i<kernel.length;i++) if (kernel[i]!=null){
///			length=kernel[i].length;
///			break;
///		}

		int length = kernel.length; // number of color channels

2209 2210 2211 2212
		if (length==0){
			System.out.println("mergeKernelsToStack(): no non-null kernels");
			return null;
		}
Andrey Filippov's avatar
Andrey Filippov committed
2213 2214 2215 2216 2217
		int [] channelsMask = new int [kernel.length];
		for (i=0;i<kernel.length;i++) channelsMask[i]=0;
		for (i=0;i<tilesY ;i++)  for (j=0;j<tilesX;j++) if (kernels[i][j]!=null) {
			for (k=0;(k<kernel.length)&& (k<channelsMask.length);k++) if (kernels[i][j][k]!=null) {
				channelsMask[k]=1;
2218
				if (kernels[i][j][k].length > length) length=kernels[i][j][k].length;
Andrey Filippov's avatar
Andrey Filippov committed
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
			}
		}

		nChn=0;
		for (i=0;i<channelsMask.length;i++) if (channelsMask[i]!=0) nChn++;
		int [] channels = new int [nChn];
		nChn=0;
		for (i=0;i<channelsMask.length;i++) if (channelsMask[i]!=0) channels[nChn++]=i;

		//	    for (i=0;i<kernel.length;i++) if (kernel[i]!=null)  if (nChn<channels.length) channels[nChn++]=i;
		int size=(int) Math.sqrt(length);
		int outWidth= size*tilesX;
		int outHeight=size*tilesY;

		ImageStack stack=new ImageStack(outWidth,outHeight);
2234
		int numKernels=0;
Andrey Filippov's avatar
Andrey Filippov committed
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
		float [] fpixels;
		for (chn=0;chn<nChn;chn++) {
			fpixels= new float [outWidth*outHeight];
			k=channels[chn];
			for (i=0; i<tilesY;i++)  for (j=0;j<tilesX;j++) {
				for (y=0;y<size;y++) for (x=0;x<size;x++) {
					index=((i*size+y)*outWidth)+(j*size+x);
					if ((kernels[i][j]==null || (kernels[i][j][k]==null))) fpixels[index]=0.0f;
					else {
						fpixels[index]= (float) kernels[i][j][k][y*size+x];
					}
				}
2247
				if ((kernels[i][j]!=null && (kernels[i][j][k]!=null))) numKernels++;
Andrey Filippov's avatar
Andrey Filippov committed
2248 2249 2250 2251
			}
			if (names==null) stack.addSlice("channel"+k, fpixels);
			else             stack.addSlice(names[chn], fpixels);
		}
2252 2253 2254 2255 2256
		if (numKernels==0){
			System.out.println("mergeKernelsToStack(): all kernels are empty");
			return null;
		}
		System.out.println("mergeKernelsToStack(): got "+numKernels +" non-null kernels");
Andrey Filippov's avatar
Andrey Filippov committed
2257 2258 2259 2260 2261 2262
		return stack;
	}


	public double [][][][] createPSFMap(
			final MatchSimulatedPattern commonMatchSimulatedPattern, // to be cloned in threads, using common data
2263
			final ImagePlus         imp_sel, // linearized Bayer mosaic image from the camera, GR/BG
2264
			final LwirReaderParameters lwirReaderParameters, // null is OK
2265
			final int [][][]        sampleList, // optional (or null) 2-d array: list of coordinate pairs (2d - to match existent  pdfKernelMap structure)
Andrey Filippov's avatar
Andrey Filippov committed
2266 2267 2268 2269 2270 2271
			final double  overexposedAllowed, // fraction of pixels OK to be overexposed
			final SimulationPattern.SimulParameters simulParameters,
			final MatchSimulatedPattern.PatternDetectParameters patternDetectParameters,
			final int            fft_overlap,
			final int               fft_size,
			final ColorComponents colorComponents,
2272
			final int           PSF_subpixel,
Andrey Filippov's avatar
Andrey Filippov committed
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283
			final OTFFilterParameters otfFilterParameters,
			final PSFParameters psfParameters,
			final double       minDefinedArea,
			final int          PSFKernelSize, // size of square used in the new map (should be multiple of map step)
			final double       gaussWidth,  // ** NEW
			final float [][]   simArray,    // ** NEW
			final int          threadsMax,
			final boolean      updateStatus,          // UPDATE_STATUS
			final int          masterDebugLevel, // get rid of it? // ** NEW
			final int          globalDebugLevel,// ** NEW
			final int          debug_level){// debug level used inside loops
2284 2285 2286 2287 2288 2289 2290 2291
		boolean is_lwir = ((lwirReaderParameters != null) && lwirReaderParameters.is_LWIR(imp_sel));
		boolean is_mono = false;
		try {
			is_mono = Boolean.parseBoolean((String) imp_sel.getProperty("MONOCHROME"));
		} catch (Exception e) {
		}
		is_mono |= is_lwir;

2292 2293 2294
		final int full_fft_size = fft_size * PSF_subpixel / (is_mono? 2: 1); // for LWIR - 64, 5MPix: 1024. fft_size = 32/256


2295
		final boolean debugLateralShifts=(globalDebugLevel>1);
Andrey Filippov's avatar
Andrey Filippov committed
2296 2297 2298 2299 2300 2301
		System.out.println("createPSFMap(): masterDebugLevel="+masterDebugLevel+" globalDebugLevel="+globalDebugLevel+" debug_level="+debug_level); // 2 2 0
		final long startTime = System.nanoTime();
		  Runtime runtime = Runtime.getRuntime();
		  runtime.gc();
		  if (globalDebugLevel>1) System.out.println("--- Free memory="+runtime.freeMemory()+" (of "+runtime.totalMemory()+")");

2302
		// Generate hi-res pattern bitmap (one cell)
Andrey Filippov's avatar
Andrey Filippov committed
2303 2304 2305 2306 2307
		SimulationPattern simulationPattern= new SimulationPattern();
		simulationPattern.debugLevel=globalDebugLevel;
		final double [] bitmaskPattern= simulationPattern.patternGenerator(simulParameters);
		int nTileX,nTileY;
		int numPatternCells=0;
Andrey Filippov's avatar
Andrey Filippov committed
2308
/* Filter results based on correlation with the actual pattern */
Andrey Filippov's avatar
Andrey Filippov committed
2309
		boolean [][]   PSFBooleanMap; // map of 2*fft_size x 2*fft_size squares with 2*fft_overlap step, true means that that tile can be used for PSF
2310 2311 2312 2313 2314
		final int mapWidth=imp_sel.getWidth();
		final int tile_size =    (is_mono? 1 : 2) * fft_size;
		final int tile_overlap = (is_mono? 1 : 2) * fft_overlap;


Andrey Filippov's avatar
Andrey Filippov committed
2315
		if (sampleList==null){
2316
			    // tiles are twice smaller for monochrome
Andrey Filippov's avatar
Andrey Filippov committed
2317 2318
				PSFBooleanMap= mapFromPatternMask ( // count number of defined cells
						commonMatchSimulatedPattern,
2319 2320 2321
						mapWidth,     // imp_sel.getWidth(), // image (mask) width
						tile_size,    // fft_size*2,
						tile_overlap, // fft_overlap*2,
2322
						fft_size,     // backward compatibility margin==tileSize/2
Andrey Filippov's avatar
Andrey Filippov committed
2323 2324 2325 2326 2327 2328
						gaussWidth,
						//	psfParameters.minDefinedArea);
						minDefinedArea,
						globalDebugLevel);
		} else {
			PSFBooleanMap= new boolean[sampleList.length][sampleList[0].length];
2329 2330 2331 2332 2333
			for (int i=0;i<sampleList.length;i++) {
				for (int j=0;j<sampleList[0].length;j++) {
					PSFBooleanMap[i][j]=(sampleList[i][j][0]>=0); // all with positive X
				}
			}
Andrey Filippov's avatar
Andrey Filippov committed
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346
		}
		if (PSFBooleanMap==null) return null;
		numPatternCells=0;
		for (nTileY=0;nTileY<PSFBooleanMap.length;nTileY++) for (nTileX=0;nTileX<PSFBooleanMap[0].length;nTileX++) if (PSFBooleanMap[nTileY][nTileX]) numPatternCells++;
		if (globalDebugLevel>1) {
			System.out.println("Remapped for PSF measurment- converted to an array["+PSFBooleanMap.length+"]["+PSFBooleanMap[0].length+"], "+
					numPatternCells+" cells (of "+(PSFBooleanMap.length*PSFBooleanMap[0].length)+") with pattern detected");
		}
		pdfKernelMap=new double[PSFBooleanMap.length][PSFBooleanMap[0].length][][]; //pdfKernelMap - global (or final)
//		int saved_globalDebugLevel=globalDebugLevel;
//		globalDebugLevel=debug_level;
		simulationPattern.debugLevel=globalDebugLevel;
		int ncell=0;
2347
/* Create array of coordinates of cells to process, fill result array with zeros (to be actually written by threads */
Andrey Filippov's avatar
Andrey Filippov committed
2348 2349 2350 2351 2352 2353
		final int [][] tilesToProcessXY=new int [numPatternCells][4];

		for (nTileY=0;nTileY<PSFBooleanMap.length;nTileY++) for (nTileX=0;nTileX<PSFBooleanMap[0].length;nTileX++){
			if (PSFBooleanMap[nTileY][nTileX]) {
				tilesToProcessXY[ncell  ][0]=nTileX;
				tilesToProcessXY[ncell  ][1]=nTileY;
2354 2355 2356 2357 2358
				tilesToProcessXY[ncell  ][2]=(sampleList==null)?(tile_overlap * nTileX) : sampleList[nTileY][nTileX][0];
				tilesToProcessXY[ncell++][3]=(sampleList==null)?(tile_overlap * nTileY) : sampleList[nTileY][nTileX][1];
				if (is_mono) {
					pdfKernelMap[nTileY][nTileX]=new double[1][];
				} else {
2359
					pdfKernelMap[nTileY][nTileX]=new double[colorComponents.colorsToCorrect.length][];
2360 2361
				}

Andrey Filippov's avatar
Andrey Filippov committed
2362 2363
			} else pdfKernelMap[nTileY][nTileX]=null;
		}
2364 2365 2366 2367
		final double [][][][] debugLateral=new double [PSFBooleanMap.length][PSFBooleanMap[0].length][][];
		for (nTileY=0;nTileY<debugLateral.length;nTileY++) for (nTileX=0;nTileX<debugLateral[0].length;nTileX++){
			debugLateral[nTileY][nTileX]=null;
		}
Andrey Filippov's avatar
Andrey Filippov committed
2368
		final Thread[] threads = newThreadArray(threadsMax);
2369
		if (globalDebugLevel>1) System.out.println("Starting "+threads.length+" threads: "+IJ.d2s(0.000000001*(System.nanoTime()-startTime),3));
Andrey Filippov's avatar
Andrey Filippov committed
2370 2371 2372 2373 2374
		final AtomicInteger ai = new AtomicInteger(0);
		final int patternCells=numPatternCells;
		//	  final double []   overexposedMap, // map of overexposed pixels in the image (may be null)
		final double [] overexposed=(overexposedAllowed>0)?JP4_INSTANCE.overexposedMap (imp_sel):null;
   		final AtomicInteger tilesFinishedAtomic = new AtomicInteger(1); // first finished will be 1
2375
   		final int debugNumColors = is_mono? 1 : colorComponents.colorsToCorrect.length;
2376
//   		final int dbgTile0 = 217; // -1; // 245; //
Andrey Filippov's avatar
Andrey Filippov committed
2377 2378 2379
		for (int ithread = 0; ithread < threads.length; ithread++) {
			// Concurrently run in as many threads as CPUs
			threads[ithread] = new Thread() {
2380
				@Override
Andrey Filippov's avatar
Andrey Filippov committed
2381 2382 2383 2384 2385
				public void run() {

					// Each thread processes a few items in the total list
					// Each loop iteration within the run method has a unique 'i' number to work with
					// and to use as index in the results array:
2386
					//	double [] sum_kern_el=new double[6]; // just testing
Andrey Filippov's avatar
Andrey Filippov committed
2387 2388
					int x0,y0,nTX,nTY,nChn;
					double [][] kernels;
2389 2390 2391 2392 2393 2394 2395 2396
					// change to true (first 2 only?) to separate memory arrays for threads
				    MatchSimulatedPattern matchSimulatedPattern=commonMatchSimulatedPattern.cloneDeep(
				    		false, // boolean clonePATTERN_GRID,
				    		false, // boolean cloneTargetUV,
				    		false, // boolean clonePixelsUV,
				    		false, // boolean cloneFlatFieldForGrid,
				    		false  // boolean cloneFocusMask
				    		);
Andrey Filippov's avatar
Andrey Filippov committed
2397 2398 2399 2400
				    matchSimulatedPattern.debugLevel=globalDebugLevel;
					SimulationPattern simulationPattern= new SimulationPattern(bitmaskPattern);
					simulationPattern.debugLevel=globalDebugLevel;
					double [] windowFFTSize=    matchSimulatedPattern.initWindowFunction(fft_size,gaussWidth); //=initHamming( fft_size) calculate once
2401 2402 2403
					// same width - different size?
///					double [] windowFullFFTSize = matchSimulatedPattern.initWindowFunction(fft_size*PSF_subpixel,gaussWidth); //=initHamming( fft_size*subpixel);
					double [] windowFullFFTSize = matchSimulatedPattern.initWindowFunction(full_fft_size,gaussWidth); //=initHamming( fft_size*subpixel);
Andrey Filippov's avatar
Andrey Filippov committed
2404 2405
					DoubleFHT fht_instance =new DoubleFHT(); // provide DoubleFHT instance to save on initializations (or null)
					double over;
2406
// individual per-thread - will be needed when converted to doubleFHT
Andrey Filippov's avatar
Andrey Filippov committed
2407 2408 2409 2410 2411 2412
//				    MatchSimulatedPattern matchSimulatedPattern=new MatchSimulatedPattern(FFT_SIZE);
					for (int nTile = ai.getAndIncrement(); nTile < patternCells; nTile = ai.getAndIncrement()) {
						nTX=tilesToProcessXY[nTile][0];
						nTY=tilesToProcessXY[nTile][1];
						y0=tilesToProcessXY[nTile][3];
						x0=tilesToProcessXY[nTile][2];
2413 2414
						boolean debugThis = false; // (y0==48) && (x0==80);
						if (debugThis) {
2415 2416
							System.out.println("#!# "+x0+":"+y0+" Processing tile["+nTY+"]["+nTX+"] ("+(nTile+1)+" of "+patternCells+") : "+IJ.d2s(0.000000001*(System.nanoTime()-startTime),3));
						}
Andrey Filippov's avatar
Andrey Filippov committed
2417 2418 2419
						if (updateStatus) IJ.showStatus("Processing tile["+nTY+"]["+nTX+"] ("+(nTile+1)+" of "+patternCells+")");
						if (masterDebugLevel>1) System.out.println("#!# "+x0+":"+y0+" Processing tile["+nTY+"]["+nTX+"] ("+(nTile+1)+" of "+patternCells+") : "+IJ.d2s(0.000000001*(System.nanoTime()-startTime),3));
						if (overexposed!=null){
2420 2421
							over=JP4_INSTANCE.fracOverExposed(
									overexposed, // map of overexposed pixels 0.0 - 0K, >0 (==1.0) - overexposed
Andrey Filippov's avatar
Andrey Filippov committed
2422 2423 2424
									mapWidth,    // width of the map
									x0,          // X of the top left corner of the selection
									y0,          // Y of the top left corner of the selection
2425 2426
									tile_size,   // selection width
									tile_size);  // selection height
Andrey Filippov's avatar
Andrey Filippov committed
2427 2428 2429 2430 2431
						} else over=-1.0;
						if ( over > overexposedAllowed) {
							pdfKernelMap[nTY][nTX]=null;
							if (globalDebugLevel>0) System.out.println("Overexposed fraction of "+over+" at x0="+x0+" y0="+y0+" width"+(2*fft_size));
						} else {
2432 2433
							if (debugLateralShifts) {
								debugLateral[nTY][nTX]= new double [debugNumColors][];    // X/Y shift of the PSF array, in Bayer component pixel coordinates (same as PSF arrays)
2434
							}
2435 2436 2437
							kernels=getPSFKernels(
									imp_sel,
									lwirReaderParameters,  //LwirReaderParameters lwirReaderParameters, // null is OK
Andrey Filippov's avatar
Andrey Filippov committed
2438
									simArray, //simulation image, scaled PSF_subpixel/2
2439
									tile_size,        // 2*fft_size,    // size in pixels (twice fft_size for Bayer only?)
Andrey Filippov's avatar
Andrey Filippov committed
2440 2441
									x0,               // top left corner X (pixels)
									y0,               // top left corner Y (pixels)
2442
									simulationPattern, // should be individual for each sensor type? Probably not, it is just a high res bitmap
Andrey Filippov's avatar
Andrey Filippov committed
2443 2444 2445 2446
									matchSimulatedPattern,
									patternDetectParameters,
									windowFFTSize,    //=initHamming( fft_size) calculate once
									windowFullFFTSize,//=initHamming( fft_size*subpixel);
2447
									PSF_subpixel,     // use finer grid than actual pixels
Andrey Filippov's avatar
Andrey Filippov committed
2448 2449 2450 2451 2452 2453 2454
									simulParameters,
									colorComponents,  // color channels to process, equalizeGreens
									otfFilterParameters,
									5,                // int referenceComp, // number of color component to reference lateral chromatic aberration to (now 4 - checkerboard greens)
									psfParameters,
									fht_instance,      // provide DoubleFHT instance to save on initializations (or null)
									debug_level,// ((x0<512)&& (y0<512))?3:debug_level DEBUG during "focusing"
2455 2456 2457
									masterDebugLevel+ (debugThis? 3:0), // get rid of it? // ** NEW
									globalDebugLevel + (debugThis? 3:0),// ** NEW
									debugLateralShifts?debugLateral[nTY][nTX] : null
Andrey Filippov's avatar
Andrey Filippov committed
2458 2459
							);
							if (kernels!=null) {
2460 2461 2462
								if (kernelLength(kernels)>(PSFKernelSize*PSFKernelSize)) {
									kernels=resizeForFFT(kernels,PSFKernelSize); // shrink before normalizing
								}
Andrey Filippov's avatar
Andrey Filippov committed
2463
								normalizeKernel(kernels); // in-place
2464 2465 2466
								if (kernelLength(kernels)<(PSFKernelSize*PSFKernelSize)) {
									kernels=resizeForFFT(kernels,PSFKernelSize); // expand after normalizing
								}
Andrey Filippov's avatar
Andrey Filippov committed
2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
								for (nChn=0;nChn<kernels.length;nChn++) if (kernels[nChn]!=null){
									pdfKernelMap[nTY][nTX][nChn]=kernels[nChn]; // not .clone()?
								}
//(new showDoubleFloatArrays()).showArrays(kernels, "***kernels-"+nTX+"-"+nTY);
							} else {
								if (masterDebugLevel>1) System.out.println("Empty kernel for tile["+nTY+"]["+nTX+"]");
							}
							//save results into common array
							//pdfKernelMap[nTY][nTX]
						}
   						final int numFinished=tilesFinishedAtomic.getAndIncrement();
   						SwingUtilities.invokeLater(new Runnable() {
2479 2480
   							@Override
							public void run() {
Andrey Filippov's avatar
Andrey Filippov committed
2481 2482 2483 2484 2485 2486 2487 2488 2489
   								IJ.showProgress(numFinished,patternCells);
   							}
   						});

					}
				}
			};
		}
		startAndJoin(threads);
2490
		if (globalDebugLevel>1) System.out.println("Threads done at "+IJ.d2s(0.000000001*(System.nanoTime()-startTime),3));
Andrey Filippov's avatar
Andrey Filippov committed
2491
//		globalDebugLevel=saved_globalDebugLevel;
2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
		if (debugLateralShifts) {
		    boolean [] debugUsedColors=new boolean [debugNumColors];
		    Arrays.fill(debugUsedColors,false);
			for (double [][][] dbgRow:debugLateral) for (double [][] dbgTile:dbgRow) if (dbgTile!=null) for (int c=0;c<dbgTile.length;c++){
				if (dbgTile[c]!=null) debugUsedColors[c]=true;
			}
			int numUsedColors=0;
			for (boolean b:debugUsedColors) if (b) numUsedColors++;
			if (numUsedColors>0) {
				int [] cIndex=new int [numUsedColors];
				int index=0;
				for (int i=0;i<debugUsedColors.length;i++) if (debugUsedColors[i]) cIndex[index++]=i;
				String [] dbgComponets={"latChromX","latChromY","shftX","shftY","centX","centY"};
				String [] debugTitles=new String[dbgComponets.length*numUsedColors];
				index=0;
				for (int i=0;i<dbgComponets.length;i++) for (int j=0;j<cIndex.length;j++){
					debugTitles[index++]=dbgComponets[i]+"-"+cIndex[j];
				}
				double [][] dbgLat= new double [debugTitles.length][debugLateral.length*debugLateral[0].length];
				int layer=0;
				for (int i=0;i<dbgComponets.length;i++) for (int j=0;j<cIndex.length;j++){
					Arrays.fill(dbgLat[layer],Double.NaN);
					for (nTileY=0;nTileY<debugLateral.length;nTileY++) for (nTileX=0;nTileX<debugLateral[0].length;nTileX++) if (debugLateral[nTileY][nTileX]!=null){
						if (debugLateral[nTileY][nTileX][cIndex[j]]!=null) dbgLat[layer][nTileY*debugLateral[0].length+nTileX]=debugLateral[nTileY][nTileX][cIndex[j]][i];
					} layer++;
2517
				}
2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
				SDFA_INSTANCE.showArrays(dbgLat, debugLateral[0].length, debugLateral.length, true, "lateral"+imp_sel.getTitle(), debugTitles);
				/*
					debugLateralTile[i][0]=lateralChromatic[i][0];
					debugLateralTile[i][1]=lateralChromatic[i][1];
					debugLateralTile[i][2]=PSF_shifts[i][0];
					debugLateralTile[i][3]=PSF_shifts[i][1];
					debugLateralTile[i][4]=PSF_centroids[i][0];
					debugLateralTile[i][5]=PSF_centroids[i][1];
						    			sdfra_instance.showArrays(pointedBayer.clone(), halfWidth, halfHeight, true, title+"-bayer", subtitles);

				 */
			}
		}
Andrey Filippov's avatar
Andrey Filippov committed
2531 2532
		return pdfKernelMap;
	}
Andrey Filippov's avatar
Andrey Filippov committed
2533
	/* Combine both greens as a checkerboard pattern (after oversampleFFTInput()) */
Andrey Filippov's avatar
Andrey Filippov committed
2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
	private  double [][] combineCheckerGreens (double[][] input_pixels,   // pixel arrays after oversampleFFTInput() or extractSimulPatterns())
			int ratio) { // same as used in oversampleFFTInput() - oversampling ratio
		int width=(int) Math.sqrt(input_pixels[0].length);
		return combineCheckerGreens (input_pixels,   // pixel arrays after oversampleFFTInput() or extractSimulPatterns())
				width,   // width of the image
				ratio);
	}

	private  double [][] combineCheckerGreens (double[][] input_pixels,   // pixel arrays after oversampleFFTInput() or extractSimulPatterns())
			int width,   // width of the image
			int ratio) { // same as used in oversampleFFTInput() - oversampling ratio
		if ((ratio<2) ||
				(input_pixels==null) ||
				((input_pixels.length>5) && (input_pixels[5]!=null)) ||
				(input_pixels.length<4) ||
				(input_pixels[0]==null) ||
				(input_pixels[3]==null)) return input_pixels;
		int height=input_pixels[0].length/width;
		int i,j;
		double [][] pixels={null,null,null,null,null,null};
		for (i=0;i<input_pixels.length;i++) pixels[i]=input_pixels[i];
		pixels[5]= new double[input_pixels[0].length];
		int index=0;
		int index_diff=(width+1)*ratio/2;
		double d;
		for (i=0;i<height;i++) for (j=0;j<width;j++) {
			d=input_pixels[0][index];
			if ((i>=ratio) && (j>=ratio)) d=0.5*(d+input_pixels[3][index-index_diff]);
			pixels[5][index++]=d;
		}
		return pixels;
	}
2566
/*
Andrey Filippov's avatar
Andrey Filippov committed
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588
	private  double [] combineDiagonalGreens (double [] green0, double []green3, int half_width, int half_height) {
		int y,x,base;
		int base_b=0;
		double [] result= new double [green0.length];
		for (y=0;y<half_height/2; y++){
			base=half_height*half_width/2+ y* (half_width+1);
			for (x=0; x<half_width/2; x++) {
				result[base_b++]=green0[base];
				base-=half_width;
				result[base_b++]=green3[base++];
			}
			base=half_height*half_width/2+ y* (half_width+1);
			for (x=0; x<half_width/2; x++) {
				//System.out.println("2:y="+y+" x="+x+" base_b="+base_b+" base="+base);
				result[base_b++]=green3[base++];
				result[base_b++]=green0[base];
				base-=half_width;
			}
		}
		return result;
	}
	*/
Andrey Filippov's avatar
Andrey Filippov committed
2589
	/* ======================================================================== */
Andrey Filippov's avatar
Andrey Filippov committed
2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614
	private  double[][] normalizeAndWindow (double [][] pixels, double [] windowFunction) {
		return normalizeAndWindow (pixels, windowFunction, true);
	}
	/*
	private  double[] normalizeAndWindow (double [] pixels, double [] windowFunction) {
		return normalizeAndWindow (pixels, windowFunction, true);
	}
	*/
	private  double[][] normalizeAndWindow (double [][] pixels, double [] windowFunction, boolean removeDC) {
		int i;
		for (i=0;i<pixels.length;i++)  if (pixels[i]!=null) pixels[i]=normalizeAndWindow (pixels[i],  windowFunction, removeDC);
		return pixels;
	}
	private  double[] normalizeAndWindow (double [] pixels, double [] windowFunction, boolean removeDC) {
		int j;
		double s=0.0;
		if (pixels==null) return null;
		if (removeDC) {
			for (j=0;j<pixels.length;j++) s+=pixels[j];
			s/=pixels.length;
		}
		for (j=0;j<pixels.length;j++) pixels[j]=(pixels[j]-s)*windowFunction[j];
		return pixels;
	}

2615
	/* inserts zeros between pixels */
Andrey Filippov's avatar
Andrey Filippov committed
2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
	private  double [][] oversampleFFTInput (double[][] input_pixels,
			int ratio) {
		double [][] pixels=new double[input_pixels.length][];
		int i;
		for (i=0;i<pixels.length;i++) pixels[i]= oversampleFFTInput (input_pixels[i], ratio);
		return pixels;
	}


	private  double [] oversampleFFTInput (double[] input_pixels, int ratio) {
		if (input_pixels==null) return null;
		int width=(int) Math.sqrt(input_pixels.length);
		return oversampleFFTInput (input_pixels,
				width,   // width of the image
				ratio);
	}

	private  double [] oversampleFFTInput (double[] input_pixels,
			int width,   // width of the image
			int ratio) {
		if (input_pixels==null) return null;
		double [] pixels=new double[input_pixels.length*ratio*ratio];
		int i,j,x,y;
		int height=input_pixels.length/width;
		for (i=0;i<pixels.length;i++) pixels[i]=0.0;
		j=0;
		for (y=0;y<height;y++) {
			i=width*ratio*ratio*y;
			for (x=0;x<width;x++) {
				pixels[i]=input_pixels[j++];
				i+=ratio;
			}
		}
		return pixels;
	}


Andrey Filippov's avatar
Andrey Filippov committed
2653
/* ======================================================================== */
Andrey Filippov's avatar
Andrey Filippov committed
2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667
	private  void normalizeKernel(double [][] kernel) {
		int i;
		for (i=0;i<kernel.length;i++) if (kernel[i]!=null) normalizeKernel(kernel[i]);
	}

	private  void normalizeKernel(double [] kernel) {
		//	    if (kernel==null) return null;
		int i;
		double s=0;
		for (i=0;i<kernel.length;i++) s+= kernel[i];
		s=1.0/s;
		for (i=0;i<kernel.length;i++) kernel[i]*=s;
	}

Andrey Filippov's avatar
Andrey Filippov committed
2668 2669
/* ======================================================================== */
/* extends/shrinks image to make it square for FFT */
Andrey Filippov's avatar
Andrey Filippov committed
2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
	private double[][] resizeForFFT (double[][]kernels, int size) {
		if (kernels==null) return null;
		double [][]result=new double [kernels.length][];
		for (int i=0;i<kernels.length;i++) {
			if (kernels[i]!=null) result[i]=resizeForFFT(kernels[i],size);
			else result[i]=null;
		}
		return result;
	}

	private double[] resizeForFFT (double[]kernel, int size) {
		int ksize=(int) Math.sqrt(kernel.length);
		double [] kernelForFFT = new double[size*size];
		int i,j,index, full_index;
//		if (DEBUG_LEVEL>10) System.out.println("resizeForFFT: new size="+size+" old size="+ksize);
		index=0;
		if (size==ksize) {
			return kernel.clone();
		} else if (size>ksize) {
			for (full_index=0;full_index<kernelForFFT.length; full_index++) kernelForFFT [full_index]=0.0;
			for (i=0;i<ksize; i++) {
				full_index=size* (size/2- ksize/2 + i) +size/2-ksize/2;
				for (j=0;j<ksize; j++) kernelForFFT[full_index++]=kernel[index++];
			}
		} else {
			for (i=0; i<size; i++) {
				full_index= ksize* (ksize/2-(size/2) +i) + (ksize/2-(size/2));
				for (j=0; j<size; j++) kernelForFFT[index++]=kernel[full_index++];
			}
		}
		return kernelForFFT;
	}
Andrey Filippov's avatar
Andrey Filippov committed
2702
/* ======================================================================== */
Andrey Filippov's avatar
Andrey Filippov committed
2703 2704 2705 2706 2707 2708 2709

	private  int kernelLength(double[][]kernels) {
		if (kernels==null) return 0;
		for (int i=0; i<kernels.length;i++) if (kernels[i]!=null) return kernels[i].length;
		return 0;
	}

2710 2711 2712 2713
// should return [1] for mono
	public double [][] getPSFKernels (
			ImagePlus             imp,
			LwirReaderParameters lwirReaderParameters, // null is OK
2714
			float [][]            simArray, //simulation image, scaled PSF_subpixel/2 (or null), [0] - main pixels, [1] - shifted diagonally by 0.5 pixels (for checker greens)
2715
			int                   tile_size,   // size in pixels (twice FFT_SIZE for Bayer, equals FFT size for mono)
2716 2717
			int                   x0,          // top left corner X (pixels)
			int                   y0,          // top left corner Y (pixels)
Andrey Filippov's avatar
Andrey Filippov committed
2718 2719 2720
			SimulationPattern     simulationPattern,
		    MatchSimulatedPattern matchSimulatedPattern,
			MatchSimulatedPattern.PatternDetectParameters patternDetectParameters,
2721
			double []             Hamming, //=initHamming( fft_size) calculate once
2722
			double []             fullHamming, //=initHamming( fft_size*subpixel); for mono - twice smaller !
2723
			int                   subpixel, // use finer grid than actual pixels
Andrey Filippov's avatar
Andrey Filippov committed
2724 2725 2726
			SimulationPattern.SimulParameters  simulParameters,
			EyesisAberrations.ColorComponents colorComponents,
			EyesisAberrations.OTFFilterParameters otfFilterParameters,
2727
			int                   referenceComp, // number of color component to reference lateral chromatic aberration to (now 4 - checkerboard greens)
Andrey Filippov's avatar
Andrey Filippov committed
2728 2729
			EyesisAberrations.PSFParameters psfParameters,
			DoubleFHT fht_instance, // provide DoubleFHT instance to save on initializations (or null)
2730 2731 2732 2733
			int                   masterDebugLevel, // get rid of it? // ** NEW
			int                   globalDebugLevel,// ** NEW
			int                   debug,
			double [][]           debugLateralTile
Andrey Filippov's avatar
Andrey Filippov committed
2734
	){
2735
		boolean debugThis= false; // (y0==48) && (x0==80); //(y0==384) && ((x0==448) || (x0==512));// false;
Andrey Filippov's avatar
Andrey Filippov committed
2736
		if (globalDebugLevel>1){
2737
			System.out.println("getPSFKernels(), simArray is "+((simArray==null)?"":"not ")+"null");
Andrey Filippov's avatar
Andrey Filippov committed
2738 2739 2740 2741
		}
		if (imp==null) return null; // Maybe convert to double pixel array once to make it faster?
		if (fht_instance==null) fht_instance=new DoubleFHT(); // move upstream to reduce number of initializations
		String title=imp.getTitle()+"X"+x0+"Y"+y0;
2742 2743 2744

		boolean is_lwir = ((lwirReaderParameters != null) && lwirReaderParameters.is_LWIR(imp));
		boolean is_mono = false;
2745
		boolean invert_pattern = is_lwir;
2746 2747 2748 2749 2750 2751 2752 2753
		try {
			is_mono = Boolean.parseBoolean((String) imp.getProperty("MONOCHROME"));
		} catch (Exception e) {

		}
		is_mono |= is_lwir;
		if (is_mono) referenceComp = 0; //

2754 2755
		int fft_size=is_mono ? tile_size : (tile_size/2);          // for LWIR - 32
		int full_fft_size = fft_size * subpixel / (is_mono? 2: 1); // for LWIR - 64
2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778

		Rectangle PSFCell=new Rectangle (
				x0,
				y0,
				tile_size,
				tile_size);

		double [][] kernels=         new double[is_mono?1:6][];


		double [][] input_bayer_or_mono=null; // single mono slice will have twice dimensions of the bayer
		if (is_mono) {
			input_bayer_or_mono = new double[1][];
			input_bayer_or_mono[0] = matchSimulatedPattern.getNoBayer(
					imp,
					PSFCell);
		} else {
			input_bayer_or_mono=matchSimulatedPattern.splitBayer(
					imp,
					PSFCell,
					colorComponents.equalizeGreens); // does it work the same?
		}

Andrey Filippov's avatar
Andrey Filippov committed
2779 2780 2781 2782 2783
		//int greensToProcess=4;
		int i,j,l;
		double [][] simul_pixels;
		double [][]wVectors=new double[2][2];
		int imgWidth=imp.getWidth();
2784

Andrey Filippov's avatar
Andrey Filippov committed
2785
		double [][] dbgSimPix=null;
2786

2787
		double [] localBarray;
2788 2789 2790 2791
		double min_half_period = (is_lwir? patternDetectParameters.minGridPeriodLwir: patternDetectParameters.minGridPeriod)/2;
		double max_half_period = (is_lwir? patternDetectParameters.maxGridPeriodLwir:patternDetectParameters.maxGridPeriod)/2;


2792

2793
		if ((simArray==null) || (psfParameters.approximateGrid)){ // just for testing(never here?)
Andrey Filippov's avatar
Andrey Filippov committed
2794
			/* Calculate pattern parameters, including distortion */
Andrey Filippov's avatar
Andrey Filippov committed
2795
			if (matchSimulatedPattern.PATTERN_GRID==null) {
2796 2797
				double[][] distortedPattern= matchSimulatedPattern.findPatternDistorted(
						input_bayer_or_mono,             // pixel array to process (no windowing!)
Andrey Filippov's avatar
Andrey Filippov committed
2798
						patternDetectParameters,
2799 2800
						min_half_period, // patternDetectParameters.minGridPeriod/2,
						max_half_period, // patternDetectParameters.maxGridPeriod/2,
2801
						(!is_mono), //true, //(greensToProcess==4), // boolean greens, // this is a pattern for combined greens (diagonal), adjust results accordingly
Andrey Filippov's avatar
Andrey Filippov committed
2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814
						title); // title prefix to use for debug  images

				if (distortedPattern==null) return null;
				if (globalDebugLevel>3){
					System.out.println(
							" W0x="+     IJ.d2s(distortedPattern[0][0],4)+
							" W0y="+     IJ.d2s(distortedPattern[0][1],4)+
							" W0_phase="+IJ.d2s(distortedPattern[0][2],2)+
							" W1x="+     IJ.d2s(distortedPattern[1][0],4)+
							" W1y="+     IJ.d2s(distortedPattern[1][1],4)+
							" W1_phase="+IJ.d2s(distortedPattern[1][2],2));

				}
2815
				localBarray=simulationPattern.simulatePatternFullPatternSafe(
Andrey Filippov's avatar
Andrey Filippov committed
2816 2817 2818 2819 2820 2821 2822 2823
						distortedPattern[0][0],
						distortedPattern[0][1],
						distortedPattern[0][2],
						distortedPattern[1][0],
						distortedPattern[1][1],
						distortedPattern[1][2],
						distortedPattern[2], //
						simulParameters.subdiv,
2824
						fft_size, // FIXME?
2825 2826
						simulParameters.center_for_g2,
						false);//boolean mono
Andrey Filippov's avatar
Andrey Filippov committed
2827 2828 2829 2830 2831 2832 2833 2834
				wVectors[0][0]=2.0*distortedPattern[0][0]/subpixel;
				wVectors[0][1]=2.0*distortedPattern[0][1]/subpixel;
				wVectors[1][0]=2.0*distortedPattern[1][0]/subpixel;
				wVectors[1][1]=2.0*distortedPattern[1][1]/subpixel;
			} else { // approximate pattern grid and simulate it
				double[][] distPatPars= matchSimulatedPattern.findPatternFromGrid(
						x0, // top-left pixel of the square WOI
						y0,
2835
						tile_size, // size of square (pixels)
Andrey Filippov's avatar
Andrey Filippov committed
2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856
						Hamming, // only half-window!
						false,  // use linear approximation (instead of quadratic)
						1.0E-10,  // thershold ratio of matrix determinant to norm for linear approximation (det too low - fail)
						1.0E-20);  // thershold ratio of matrix determinant to norm for quadratic approximation (det too low - fail)
				int [] iUV={(int) Math.floor(distPatPars[0][2]),(int) Math.floor(distPatPars[1][2])};
				boolean negative=((iUV[0]^iUV[1])&1)!=0;
				double [] simCorr={
						distPatPars[0][3]/4,
						distPatPars[0][4]/4,
						distPatPars[0][5]/4,
						distPatPars[1][3]/4,
						distPatPars[1][4]/4,
						distPatPars[1][5]/4,
						0.0,0.0,0.0,0.0};
				double [] phases={
						1.0*Math.PI*(distPatPars[0][2]-iUV[0]+(negative?(-0.5):0.5)), // measured from the center of white
						1.0*Math.PI*(distPatPars[1][2]-iUV[1]+0.5)};
				wVectors[0][0]=distPatPars[0][0];
				wVectors[0][1]=distPatPars[0][1];
				wVectors[1][0]=distPatPars[1][0];
				wVectors[1][1]=distPatPars[1][1];
2857
				localBarray=simulationPattern.simulatePatternFullPatternSafe(
Andrey Filippov's avatar
Andrey Filippov committed
2858 2859 2860 2861 2862 2863 2864 2865
						wVectors[0][0],
						wVectors[0][1],
						phases[0],
						wVectors[1][0],
						wVectors[1][1],
						phases[1],
						simCorr, //
						simulParameters.subdiv,
2866
						fft_size, // FIXME!
2867 2868
						simulParameters.center_for_g2,
						false);//boolean mono
Andrey Filippov's avatar
Andrey Filippov committed
2869
			}
2870 2871
			if (is_mono) {
				simul_pixels= new double[1][];
2872
				// TODO: so many places to invert LWIR pattern... or not
2873 2874
				simul_pixels[0]=  simulationPattern.extractSimulMono ( // TODO: can use twice smaller barray
						localBarray,
2875
						invert_pattern,
2876
						simulParameters,
2877 2878
						subpixel, // 1,  // subdivide output pixels - now 4
						full_fft_size, // fft_size*subpixel,    // number of Bayer cells in width of the square selection (half number of pixels)
2879 2880 2881
						0,    // selection center, X (in pixels)
						0);
			} else {
2882 2883 2884 2885
				simul_pixels= simulationPattern.extractSimulPatterns (
						localBarray,		// this version is thread safe
						simulParameters,
						subpixel, // subdivide pixels
2886
						full_fft_size, // fft_size*subpixel, // number of Bayer cells in width of the square selection (half number of pixels)
2887 2888
						0.0,    // selection center, X (in pixels)
						0.0);   // selection center, y (in pixels)
2889 2890 2891 2892 2893 2894 2895
				if (subpixel>1) {
					if (colorComponents.colorsToCorrect[5])  simul_pixels=combineCheckerGreens (simul_pixels,   // pixel arrays after oversampleFFTInput() or extractSimulPatterns())
							subpixel); // same as used in oversampleFFTInput() - oversampling ratio
				}
				for (i=0;i<simul_pixels.length; i++) {
					if (!colorComponents.colorsToCorrect[i]) simul_pixels[i]=null; // removed unused
				}
Andrey Filippov's avatar
Andrey Filippov committed
2896 2897
			}
			simul_pixels= normalizeAndWindow (simul_pixels, fullHamming);
2898

2899
		} else { //if ((simArray==null) || (psfParameters.approximateGrid)){ // never above?
2900 2901 2902 2903 2904
			Rectangle PSFCellSim = new Rectangle (
					x0 * subpixel/2,
					y0 * subpixel/2,
					tile_size * subpixel/2,
					tile_size * subpixel/2); // getting here
2905
			if (is_mono) {
2906
				//FIXME: Somewhere need to invert color for LWIR
2907
				simul_pixels=new double[1][];
2908
				simul_pixels[0]=simulationPattern.extractBayerSim ( // works with mono now
2909 2910 2911 2912
						simArray, // [0] - regular pixels, [1] - shifted by 1/2 diagonally, for checker greens
						imgWidth*subpixel/2,
						PSFCellSim,
						subpixel, // 4
2913
						(invert_pattern? -2: -1)); //New :  -1 - extract mono TODO: see if 1/2pix shift is needed
2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924
			} else {
				simul_pixels=new double[6][];
				for (i=0;i<simul_pixels.length; i++) {
					if (colorComponents.colorsToCorrect[i]) simul_pixels[i]=simulationPattern.extractBayerSim (
							simArray, // [0] - regular pixels, [1] - shifted by 1/2 diagonally, for checker greens
							imgWidth*subpixel/2,
							PSFCellSim,
							subpixel, // 4
							i);
					else simul_pixels[i]=null;
				}
2925
			}
2926 2927 2928
//System.out.println("PSFCell.y="+PSFCell.y+" PSFCell.height="+PSFCell.height+" imgWidth="+imgWidth+" PSFCell.x="+PSFCell.x+" PSFCell.width="+PSFCell.width+" matchSimulatedPattern.UV_INDEX.length="+matchSimulatedPattern.UV_INDEX.length);
			int index=matchSimulatedPattern.getUVIndex(
					(PSFCell.y+PSFCell.height/2)*imgWidth+(PSFCell.x+PSFCell.width/2));
2929

Andrey Filippov's avatar
Andrey Filippov committed
2930 2931 2932 2933
			if (index<0) {
				System.out.println ("Error, No UV pattern @ x="+(PSFCell.x+PSFCell.width/2)+", y="+(PSFCell.y+PSFCell.height/2));
				return null;
			}
2934

Andrey Filippov's avatar
Andrey Filippov committed
2935 2936 2937 2938 2939 2940 2941 2942 2943 2944
			int [] iUV={index % matchSimulatedPattern.getDArrayWidth(), index / matchSimulatedPattern.getDArrayWidth()}; // TODO: make sure it is correct?
			if (matchSimulatedPattern.getDArray(iUV[1],iUV[0])==null) {
				if (globalDebugLevel>0){
					System.out.println ( "Tried to extract wave vectors from non-existent node "+iUV[0]+"/"+iUV[1]);
					System.out.println ( "index="+index+"  matchSimulatedPattern.getDArrayHeight()"+ matchSimulatedPattern.getDArrayHeight());
					System.out.println("PSFCell.y="+PSFCell.y+" PSFCell.height="+PSFCell.height+" imgWidth="+imgWidth+" PSFCell.x="+PSFCell.x+" PSFCell.width="+PSFCell.width+
							" matchSimulatedPattern.UV_INDEX.length="+matchSimulatedPattern.UV_INDEX.length);
				}
				return null;
			}
2945

Andrey Filippov's avatar
Andrey Filippov committed
2946 2947 2948 2949
			if (matchSimulatedPattern.getDArray(iUV[1],iUV[0],1)==null) {
				if (globalDebugLevel>0) System.out.println ( "Tried to extract non-existent wave vectors from "+iUV[0]+"/"+iUV[1]);
				return null;
			}
2950

Andrey Filippov's avatar
Andrey Filippov committed
2951 2952 2953
			//TODO:  Need to define wave vectors here - how?
			wVectors[0]=matchSimulatedPattern.getDArray(iUV[1],iUV[0],1); //null pointer
			wVectors[1]=matchSimulatedPattern.getDArray(iUV[1],iUV[0],2);
2954

2955
			// should it be averaged WV?
2956 2957 2958 2959 2960 2961 2962
			if (debugThis || (globalDebugLevel>2)) System.out.println ( " x0="+x0+" y0="+y0);
			if (debugThis || (globalDebugLevel>2)) {
				SDFA_INSTANCE.showArrays(input_bayer_or_mono, true, title+"-in");
			}
			if (debugThis || (globalDebugLevel>2)) {
				SDFA_INSTANCE.showArrays(simul_pixels, true, title+"-S");
			}
2963

Andrey Filippov's avatar
Andrey Filippov committed
2964 2965 2966 2967 2968 2969 2970 2971 2972
			if (masterDebugLevel>1){
				dbgSimPix=new double[simul_pixels.length][];
				for (int ii=0;ii<dbgSimPix.length;ii++)
					if (simul_pixels[ii]!=null) dbgSimPix[ii]=simul_pixels[ii].clone();
					else dbgSimPix[ii]=null;

			}
			simul_pixels= normalizeAndWindow (simul_pixels, fullHamming);
		}
2973

2974
		input_bayer_or_mono= normalizeAndWindow (input_bayer_or_mono, Hamming);
2975 2976 2977
		if (debugThis || (globalDebugLevel>2)) {
			SDFA_INSTANCE.showArrays(input_bayer_or_mono, true, title+"-in-norm");
		}
Andrey Filippov's avatar
Andrey Filippov committed
2978
		if (subpixel>1) {
2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990
			if (is_mono) {
				if (subpixel > 2) { // mono requires >1 !)
					input_bayer_or_mono= oversampleFFTInput (input_bayer_or_mono, subpixel/2);
				}
			} else {
				input_bayer_or_mono= oversampleFFTInput (input_bayer_or_mono,subpixel);
				if (colorComponents.colorsToCorrect[5])  input_bayer_or_mono=combineCheckerGreens (input_bayer_or_mono,   // pixel arrays after oversampleFFTInput() or extractSimulPatterns())
						subpixel); // same as used in oversampleFFTInput() - oversampling ratio
			}
		}
		if (!is_mono) {
			for (i=0;i<4;i++) if (!colorComponents.colorsToCorrect[i]) input_bayer_or_mono[i]=null; // leave composite greens even if disabled
Andrey Filippov's avatar
Andrey Filippov committed
2991 2992
		}
		if (debugThis) {
2993
//			SDFA_INSTANCE.showArrays(input_bayer_or_mono, full_fft_size, full_fft_size, title);
Andrey Filippov's avatar
Andrey Filippov committed
2994
		}
2995

2996
		if (globalDebugLevel>2) System.out.println ( " input_bayer.length="+input_bayer_or_mono.length+" simul_pixels.length="+simul_pixels.length+" full_fft_size="+full_fft_size*subpixel);
2997 2998
		for (i=0;(i<input_bayer_or_mono.length) && (i<simul_pixels.length);i++) if ((colorComponents.colorsToCorrect[i]) && (input_bayer_or_mono[i]!=null)){
			if (globalDebugLevel>2) System.out.println ( "input_bayer["+i+"].length="+input_bayer_or_mono[i].length+" simul_pixels["+i+"].length="+simul_pixels[i].length);
Andrey Filippov's avatar
Andrey Filippov committed
2999
		}
3000

3001 3002 3003 3004 3005 3006
		if (debugThis) {
			SDFA_INSTANCE.showArrays(input_bayer_or_mono, true, title+"-input");
		}
		if (debugThis) {
			SDFA_INSTANCE.showArrays(simul_pixels, true, title+"-SIM");
		}
Andrey Filippov's avatar
Andrey Filippov committed
3007

3008
//if (globalDebugLevel>2)globalDebugLevel=0; //************************************************************
3009

3010
		double [][] inverted=new double[is_mono? 1 : colorComponents.colorsToCorrect.length][];
Andrey Filippov's avatar
Andrey Filippov committed
3011 3012 3013
		double wvAverage=Math.sqrt(0.5*(wVectors[0][0]*wVectors[0][0]+wVectors[0][1]*wVectors[0][1]+
				wVectors[1][0]*wVectors[1][0]+wVectors[1][1]*wVectors[1][1]));

3014 3015
		for (i=0;(i<input_bayer_or_mono.length) && (i<simul_pixels.length);i++) {
			if ((is_mono ||  colorComponents.colorsToCorrect[i]) && (input_bayer_or_mono[i]!=null)){
3016 3017
				if (globalDebugLevel>2) System.out.println ( "Color "+colorComponents.getColorName(i)+" is re-calculated into bayer pixels ");
				if (globalDebugLevel>2) System.out.println ( "input_bayer["+i+"].length="+input_bayer_or_mono[i].length+" simul_pixels["+i+"].length="+simul_pixels[i].length);
3018 3019
				inverted[i]=limitedInverseOfFHT(
						input_bayer_or_mono[i],
3020
						simul_pixels[i],
3021
						full_fft_size, // fft_size*subpixel,
3022 3023
						(i==5),     //    boolean checker // checkerboard pattern in the source file (use when filtering)
						true, //      forwardOTF,
3024
						(subpixel / (is_mono? 2 : 1)),
3025 3026
						otfFilterParameters,
						fht_instance,
3027
						psfParameters.mask1_sigma * (fft_size * 2) * wvAverage,      // normalize to wave vectors!
3028
						psfParameters.mask1_threshold,
3029
						psfParameters.gaps_sigma * (fft_size * 2) * wvAverage,     // normalize to wave vectors!
3030 3031
						psfParameters.mask_denoise,
						debug,
3032
						(globalDebugLevel + (debugThis? 3:0)),
3033 3034
						title+"-"+i);
			}
3035
		}
3036
		int debugThreshold=1;
3037 3038 3039
		if (debugThis) {
			SDFA_INSTANCE.showArrays(inverted, title+"_Combined-PSF"); // Here OK with mono
		}
Andrey Filippov's avatar
Andrey Filippov committed
3040 3041
/* correct composite greens */
/* Here we divide wave vectors by subpixel as the pixels are already added */
Andrey Filippov's avatar
Andrey Filippov committed
3042
		double [][] wVrotMatrix= {{0.5,0.5},{-0.5,0.5}};
3043
		double [][]wVectors4= new double [2][2]; // Will only be used for color, combined diagonal greens
Andrey Filippov's avatar
Andrey Filippov committed
3044 3045 3046 3047
		for (i=0;i<2;i++) for (j=0;j<2;j++) {
			wVectors4[i][j]=0.0;
			for (l=0;l<2;l++) wVectors4[i][j]+=wVectors[i][l]*wVrotMatrix[l][j];
		}
3048 3049 3050 3051 3052 3053 3054 3055

		double [][] PSF_shifts =          new double [input_bayer_or_mono.length][]; // X/Y shift of the PSF array, in Bayer component pixel coordinates (same as PSF arrays)
		double [][] PSF_centroids =       new double [input_bayer_or_mono.length][]; // X/Y coordinates of the centroids of PSF in Bayer component pioxel coordinates (same as PSF arrays) (after they were optionally shifted)
		double [][] lateralChromatic =    new double [input_bayer_or_mono.length][]; // X/Y coordinates of the centroids of Bayer component PSF in sensor pixel coordinates
		double [][] kernelsForFFT =       new double [input_bayer_or_mono.length][];
		double [][] psf_inverted =        new double [input_bayer_or_mono.length][];
		double [][] psf_inverted_masked = new double [input_bayer_or_mono.length][];
		double [] lateralChromaticAbs =   new double [input_bayer_or_mono.length];
Andrey Filippov's avatar
Andrey Filippov committed
3056
		double [] zeroVector={0.0,0.0};
3057
		for (i=input_bayer_or_mono.length-1;i>=0;i--) {
3058
			if (is_mono || colorComponents.colorsToCorrect[i]) {
Andrey Filippov's avatar
Andrey Filippov committed
3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072
				PSF_shifts[i]=       zeroVector.clone();
				PSF_centroids[i]=    zeroVector.clone();
				lateralChromatic[i]= zeroVector.clone();
			} else {
				PSF_shifts[i]=       null;
				PSF_centroids[i]=    null;
				lateralChromatic[i]= null;
			}
			lateralChromaticAbs[i]=0.0;
			kernelsForFFT[i]=null;
			psf_inverted[i]=null;
			psf_inverted_masked[i]=null;
		}
		//int [][]  clusterMask;
Andrey Filippov's avatar
Andrey Filippov committed
3073
/* Start with referenceComp */
3074 3075 3076
		i = referenceComp; // now 0 for mono
		if (globalDebugLevel > debugThreshold) {
			System.out.println(x0+":"+y0+"1-PSF_shifts.length= "+PSF_shifts.length+" i="+i+" input_bayer.length="+input_bayer_or_mono.length);
Andrey Filippov's avatar
Andrey Filippov committed
3077 3078
			System.out.println("Before: color Component "+i+" PSF_shifts["+i+"][0]="+IJ.d2s(PSF_shifts[i][0],3)+
					" PSF_shifts["+i+"][1]="+IJ.d2s(PSF_shifts[i][1],3));
3079
		}
Andrey Filippov's avatar
Andrey Filippov committed
3080

3081 3082
		kernels[i]=combinePSF (
				inverted[i], // Square array of pixels with multiple repeated PSF (alternating sign)
3083
				!psfParameters.absoluteCenter, //true, // master, force ignoreChromatic
Andrey Filippov's avatar
Andrey Filippov committed
3084 3085 3086 3087 3088 3089 3090 3091
				PSF_shifts[i],  // centerXY[] - will be modified inside combinePSF() if PSF_PARS.ignoreChromatic is true
				PSF_centroids[i], // will return array of XY coordinates of the result centroid
				(i==4)?wVectors4:wVectors, // two wave vectors, lengths in cycles/pixel (pixels match pixel array)
						psfParameters,
						fht_instance,
						title+"_"+i,    // reduce the PSF cell size to this part of the area connecting first negative clones
						(globalDebugLevel>4),
						globalDebugLevel
3092 3093
				);

3094 3095
		if (globalDebugLevel>debugThreshold)     System.out.println(x0+":"+y0+"After-1: color Component "+i+"    PSF_shifts["+i+"][0]="+IJ.d2s(PSF_shifts   [i][0],3)+"    PSF_shifts["+i+"][1]="+IJ.d2s(   PSF_shifts[i][1],3));
		if (globalDebugLevel>debugThreshold)     System.out.println(x0+":"+y0+"After-1: color Component "+i+" PSF_centroids["+i+"][0]="+IJ.d2s(PSF_centroids[i][0],3)+" PSF_centroids["+i+"][1]="+IJ.d2s(PSF_centroids[i][1],3));
Andrey Filippov's avatar
Andrey Filippov committed
3096

3097
		if (!is_mono && !psfParameters.ignoreChromatic && !psfParameters.absoluteCenter) { /* Recalculate center to pixels from greens (diagonal)) and supply it to other colors (lateral chromatic aberration correction) */
3098
			for (j=0;j<input_bayer_or_mono.length;j++) if ((colorComponents.colorsToCorrect[j]) && (j!=referenceComp)) {
Andrey Filippov's avatar
Andrey Filippov committed
3099
				PSF_shifts[j]=shiftSensorToBayer (shiftBayerToSensor(PSF_shifts[referenceComp],referenceComp,subpixel),j,subpixel);
3100
				if (globalDebugLevel>debugThreshold)       System.out.println(x0+":"+y0+"After-2 (recalc): color Component "+j+" PSF_shifts["+j+"][0]="+IJ.d2s(PSF_shifts[j][0],3)+" PSF_shifts["+j+"][1]="+IJ.d2s(PSF_shifts[j][1],3));
Andrey Filippov's avatar
Andrey Filippov committed
3101 3102 3103 3104 3105 3106 3107 3108
			}
		}

		lateralChromatic[i]=shiftBayerToSensor ( PSF_shifts[i][0]+PSF_centroids[i][0],
				PSF_shifts[i][1]+PSF_centroids[i][1],
				i,
				subpixel);
		lateralChromaticAbs[i]=Math.sqrt(lateralChromatic[i][0]*lateralChromatic[i][0]+lateralChromatic[i][1]*lateralChromatic[i][1]);
3109

Andrey Filippov's avatar
Andrey Filippov committed
3110
/* Now process all the other components */
3111 3112
		for (i=0; i<input_bayer_or_mono.length;i++) if ((i!=referenceComp) && (colorComponents.colorsToCorrect[i])) {
			// Will never get here for mono
3113
			if (globalDebugLevel>debugThreshold) {
3114
				System.out.println(x0+":"+y0+"2-PSF_shifts.length= "+PSF_shifts.length+" i="+i+" input_bayer.length="+input_bayer_or_mono.length);
Andrey Filippov's avatar
Andrey Filippov committed
3115 3116 3117

				System.out.println(x0+":"+y0+"Before: color Component "+i+" PSF_shifts["+i+"][0]="+IJ.d2s(PSF_shifts[i][0],3)+
						" PSF_shifts["+i+"][1]="+IJ.d2s(PSF_shifts[i][1],3));
3118
			}
Andrey Filippov's avatar
Andrey Filippov committed
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128
			kernels[i]=combinePSF (inverted[i], // Square array of pixels with multiple repeated PSF (alternating sign)
					false, // !master, use ignoreChromatic
					PSF_shifts[i],  // centerXY[] - will be modified inside combinePSF() if psfParameters.ignoreChromatic is true
					PSF_centroids[i], // will return array of XY coordinates of the result centroid
					(i==4)?wVectors4:wVectors, // two wave vectors, lengths in cycles/pixel (pixels match pixel array)
							psfParameters,
							fht_instance,
							title+"_"+i,    // reduce the PSF cell size to this part of the area connecting first negative clones
							(globalDebugLevel>4),
							globalDebugLevel);
3129 3130
			if (globalDebugLevel>debugThreshold)     System.out.println(x0+":"+y0+"After-1: color Component "+i+"    PSF_shifts["+i+"][0]="+IJ.d2s(PSF_shifts   [i][0],3)+"    PSF_shifts["+i+"][1]="+IJ.d2s(   PSF_shifts[i][1],3));
			if (globalDebugLevel>debugThreshold)     System.out.println(x0+":"+y0+"After-1: color Component "+i+" PSF_centroids["+i+"][0]="+IJ.d2s(PSF_centroids[i][0],3)+" PSF_centroids["+i+"][1]="+IJ.d2s(PSF_centroids[i][1],3));
Andrey Filippov's avatar
Andrey Filippov committed
3131 3132 3133 3134 3135 3136 3137 3138 3139
			lateralChromatic[i]=shiftBayerToSensor ( PSF_shifts[i][0]+PSF_centroids[i][0],
					PSF_shifts[i][1]+PSF_centroids[i][1],
					i,
					subpixel);
			lateralChromaticAbs[i]=Math.sqrt((lateralChromatic[i][0]-lateralChromatic[referenceComp][0])*(lateralChromatic[i][0]-lateralChromatic[referenceComp][0])+
					(lateralChromatic[i][1]-lateralChromatic[referenceComp][1])*(lateralChromatic[i][1]-lateralChromatic[referenceComp][1]));
		}
		if (globalDebugLevel>1) { //1
			for (i=0;i<PSF_shifts.length;i++) if (colorComponents.colorsToCorrect[i]){
3140
				if (globalDebugLevel>debugThreshold) { //2
Andrey Filippov's avatar
Andrey Filippov committed
3141 3142
					System.out.println(x0+":"+y0+" Color Component "+i+" subpixel="+subpixel+
							" psfParameters.ignoreChromatic="+psfParameters.ignoreChromatic+
3143
							" psfParameters.absoluteCenter="+psfParameters.absoluteCenter+
Andrey Filippov's avatar
Andrey Filippov committed
3144 3145 3146 3147 3148 3149 3150 3151 3152
							" psfParameters.symm180="+psfParameters.symm180);
					System.out.println(x0+":"+y0+                     " PSF_shifts["+i+"][0]="+IJ.d2s(PSF_shifts[i][0],3)+
							" PSF_shifts["+i+"][1]="+IJ.d2s(PSF_shifts[i][1],3)+
							" PSF_centroids["+i+"][0]="+IJ.d2s(PSF_centroids[i][0],3)+
							" PSF_centroids["+i+"][1]="+IJ.d2s(PSF_centroids[i][1],3));
					System.out.println(x0+":"+y0+"  lateralChromatic["+i+"][0]="+IJ.d2s(lateralChromatic[i][0],3)+
							"  lateralChromatic["+i+"][1]="+IJ.d2s(lateralChromatic[i][1],3));
				}
			}
3153 3154 3155 3156 3157 3158 3159
			if (colorComponents.colorsToCorrect[referenceComp]) {
				for (i=0;i<colorComponents.colorsToCorrect.length;i++) {
					if ((colorComponents.colorsToCorrect[i])&& (i!=referenceComp)){
						System.out.println("#!# "+x0+":"+y0+" "+colorComponents.getColorName(i)+" lateral chromatic (from green) "+IJ.d2s(lateralChromaticAbs[i],3)+"pix(sensor):  ["+i+"][0]="+IJ.d2s(lateralChromatic[i][0]-lateralChromatic[referenceComp][0],3)+
								"  ["+i+"][1]="+IJ.d2s(lateralChromatic[i][1]-lateralChromatic[referenceComp][1],3));
					}
				}
Andrey Filippov's avatar
Andrey Filippov committed
3160 3161 3162 3163
			}
			System.out.println("#!# "+x0+":"+y0+" "+"Lateral shift green from simulation "+IJ.d2s(lateralChromaticAbs[referenceComp],3)+"pix(sensor):  ["+referenceComp+"][0]="+IJ.d2s(lateralChromatic[referenceComp][0],3)+
					"  ["+referenceComp+"][1]="+IJ.d2s(lateralChromatic[referenceComp][1],3));
		}
3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176
		if (debugLateralTile != null)	{
			for (i = 0; i < PSF_shifts.length; i++) {
				if (is_mono || colorComponents.colorsToCorrect[i]){
					debugLateralTile[i] =    new double [6];
					debugLateralTile[i][0] = lateralChromatic[i][0];
					debugLateralTile[i][1] = lateralChromatic[i][1];
					debugLateralTile[i][2] = PSF_shifts[i][0];
					debugLateralTile[i][3] = PSF_shifts[i][1];
					debugLateralTile[i][4] = PSF_centroids[i][0];
					debugLateralTile[i][5] = PSF_centroids[i][1];
				} else {
					debugLateralTile[i] = null;
				}
3177 3178
			}
		}
Andrey Filippov's avatar
Andrey Filippov committed
3179 3180 3181 3182 3183 3184
		if (debugThis && (kernels!=null)){
			int debugSize=0;
			for (int ii=0;ii<kernels.length;ii++) if (kernels[ii]!=null){
				debugSize=(int)Math.sqrt(kernels[ii].length);
				break;
			}
3185 3186 3187
			if (debugSize>0) {
				SDFA_INSTANCE.showArrays(kernels, debugSize, debugSize, title+"_KERNELS");
			}
Andrey Filippov's avatar
Andrey Filippov committed
3188 3189 3190
		}
		return kernels;
	}
Andrey Filippov's avatar
Andrey Filippov committed
3191 3192
	/* ======================================================================== */
	/* shift (like lateral chromatic aberration) in Bayer component to sensor pixels */
Andrey Filippov's avatar
Andrey Filippov committed
3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240

		private  double [] shiftBayerToSensor ( double [] dxy,
				int color,
				int subPixel) {
			return shiftBayerToSensor (dxy[0], dxy[1], color, subPixel);
		}

		private  double [] shiftBayerToSensor ( double dx,
				double dy,
				int color,
				int subPixel) {
			double [] dxy=new double[2];
			switch (color) {
			case 5:
			case 0:
			case 1:
			case 2:
			case 3:dxy[0]=2.0*dx/subPixel;  dxy[1]= 2.0*dy/subPixel;  break;
			case 4:dxy[0]=(dx+dy)/subPixel; dxy[1]= (dy-dx)/subPixel; break;
			}
//			if (DEBUG_LEVEL>2)  System.out.println("shiftBayerToSensor(), color="+color+" subPixel="+subPixel+" ["+IJ.d2s(dx,3)+"/"+IJ.d2s(dy,3)+"] ->["+IJ.d2s(dxy[0],3)+"/"+IJ.d2s(dxy[1],3)+"]");
			return dxy;
		}

		private  double [] shiftSensorToBayer ( double [] dxy,
				int color,
				int subPixel) {
			return shiftSensorToBayer (dxy[0], dxy[1], color, subPixel);
		}
		private  double [] shiftSensorToBayer ( double dx,
				double dy,
				int color,
				int subPixel) {
			double [] dxy=new double[2];
			switch (color) {
			case 5:
			case 0:
			case 1:
			case 2:
			case 3:dxy[0]=0.5*dx*subPixel;      dxy[1]=0.5*dy*subPixel; break;
			case 4:dxy[0]=0.5*(dx-dy)*subPixel; dxy[1]=0.5*(dx+dy)*subPixel; break;
			}
//			if (DEBUG_LEVEL>2)  System.out.println("shiftSensorToBayer(), color="+color+" subPixel="+subPixel+" ["+IJ.d2s(dx,3)+"/"+IJ.d2s(dy,3)+"] ->["+IJ.d2s(dxy[0],3)+"/"+IJ.d2s(dxy[1],3)+"]");

			return dxy;
		}


Andrey Filippov's avatar
Andrey Filippov committed
3241
	/* ======================================================================== */
Andrey Filippov's avatar
Andrey Filippov committed
3242

3243 3244
	private double[] limitedInverseOfFHT(
			double [] measuredPixels,  // measured pixel array
Andrey Filippov's avatar
Andrey Filippov committed
3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258
			double [] modelPixels,  // simulated (model) pixel array)
			int size,  // FFT size
			boolean checker,  // checkerboard pattern in the source file (use when filtering)
			boolean forward_OTF,  // divide measured by simulated when true, simulated by measured - when false
			int oversample,  // measured array is sampled at 1/oversample frequency than model (will add more parameters later)
			EyesisAberrations.OTFFilterParameters filterOTFParameters,  //  fraction of the maximal value to be used to limit zeros
			DoubleFHT fht_instance,  // add rejection of zero frequency (~2-3pix)
			double mask1_sigma,
			double mask1_threshold,
			double gaps_sigma,
			double mask_denoise,
			int debug,
			int globalDebugLevel,
			String title){ // title base for optional plots names
3259 3260
		return limitedInverseOfFHT(
				measuredPixels,
Andrey Filippov's avatar
Andrey Filippov committed
3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303
				modelPixels,
				size,
				checker,
				forward_OTF,
				oversample,  // measured array is sampled at 1/oversample frequency than model (will add more parameters later)
				filterOTFParameters.deconvInvert,
				filterOTFParameters.zerofreqSize,  // add rejection of zero frequency (~2-3pix)
				filterOTFParameters.smoothPS,       // 0 - none, otherwise Gauss width
				filterOTFParameters.thresholdHigh,  // reject completely if energy is above this part of maximal
				filterOTFParameters.thresholdLow,  // leave intact if energy is below this part of maximal
				-1.0, // if 0 use normalize amplitude, if 0..1 - make binary: 1.0 if > threshold, 0.0 - otherwise -1 - disable mask
				0.0, // low-pass result with low pass filter (should be later defined automatically)
				fht_instance,
				mask1_sigma,
				mask1_threshold,
				gaps_sigma,
				mask_denoise,
				debug,
				globalDebugLevel,
				title);
	}
// TODO: It now selects a single PSF, so combinePSF() and binPSF() can be simplified and eliminated
	private double[] limitedInverseOfFHT(double [] measuredPixels,  // measured pixel array
			double [] modelPixels,  // simulated (model) pixel array)
			int size,  // FFT size
			boolean checker,  // checkerboard pattern in the source file (use when filtering)
			boolean forward_OTF,  // divide measured by simulated when true, simulated by measured - when false
			int oversample,  // measured array is sampled at 1/oversample frequency than model (will add more parameters later)
			double deconvInvert,  //  fraction of the maximal value to be used to limit zeros
			double zerofreq_size,  // add rejection of zero frequency (~2-3pix)
			double smoothPS,       // 0 - none, otherwise Gauss width = FFT size/2/smoothPS
			double threshold_high,  // reject completely if energy is above this part of maximal
			double threshold_low,  // leave intact if energy is below this part of maximal
			double threshold, // if 0 use normalize amplitude, if 0..1 - make binary: 1.0 if > threshold, 0.0 - otherwise -1 - disable mask
			double radius, // low-pass result with low pass filter (should be later defined automatically)
			DoubleFHT fht_instance, // provide DoubleFHT instance to save on initializations (or null)
			double mask1_sigma,
			double mask1_threshold,
			double gaps_sigma,
			double mask_denoise,
			int debug,
			int globalDebugLevel,
			String title){
3304

Andrey Filippov's avatar
Andrey Filippov committed
3305 3306
		double [] denominatorPixels= forward_OTF? modelPixels.clone():    measuredPixels.clone();
		double [] nominatorPixels=   forward_OTF? measuredPixels.clone(): modelPixels.clone();
3307 3308 3309 3310 3311
		if ((debug>2) ||((globalDebugLevel>2) && (title!=""))) { /* Increase debug level later */ // was 3
			double [][] meas_sim = {measuredPixels, modelPixels};
//			String [] dbg_titles = {"measured","simulated"};
			SDFA_INSTANCE.showArrays(meas_sim, true, title+"-MEAS_SIM");
		}
Andrey Filippov's avatar
Andrey Filippov committed
3312 3313 3314 3315 3316 3317 3318 3319 3320
		if (fht_instance==null) fht_instance=new DoubleFHT(); // move upstream to reduce number of initializations
		int i;
		fht_instance.swapQuadrants(denominatorPixels);
		fht_instance.transform(denominatorPixels);
		double [] mask= null;
		double [] mask1=null;
		DoubleGaussianBlur gb=new DoubleGaussianBlur();
		if ((oversample>1) && (threshold_low<1.0)) {
			double [] ps=fht_instance.calculateAmplitude2(denominatorPixels);
Andrey Filippov's avatar
Andrey Filippov committed
3321
/* create mask */
Andrey Filippov's avatar
Andrey Filippov committed
3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
			mask= maskAliases (denominatorPixels,   // complex spectrum, [size/2+1][size]
					checker, // checkerboard pattern in the source file (use when filtering)
					oversample,   // measured array is sampled at 1/oversample frequency than model (will add more parameters later)
					zerofreq_size,   // add rejection of zero frequency (~2-3pix)
					smoothPS,
					deconvInvert,
					threshold_high,   // reject completely if energy is above this part of maximal
					threshold_low,  // leave intact if energy is below this part of maximal
					fht_instance,
					globalDebugLevel);
Andrey Filippov's avatar
Andrey Filippov committed
3332 3333
/* debug show the mask */
			if ((debug>2) ||((globalDebugLevel>2) && (title!=""))) { /* Increase debug level later */ // was 3
Andrey Filippov's avatar
Andrey Filippov committed
3334 3335 3336
				SDFA_INSTANCE.showArrays(mask, title+"-MASK");
			}
			for (int ii=0;ii<ps.length;ii++) ps[ii]=Math.log(ps[ii]); // can be twice faster
Andrey Filippov's avatar
Andrey Filippov committed
3337
			if ((debug>2) ||((globalDebugLevel>2) && (title!=""))) { /* Increase debug level later */ // was 3
Andrey Filippov's avatar
Andrey Filippov committed
3338 3339 3340 3341
				SDFA_INSTANCE.showArrays(ps, "LOG-"+title);
			}
			double [] ps_smooth=ps.clone();
			gb.blurDouble(ps_smooth, size, size, mask1_sigma, mask1_sigma, 0.01);
Andrey Filippov's avatar
Andrey Filippov committed
3342
			if ((debug>2) ||((globalDebugLevel>2) && (title!=""))) { /* Increase debug level later */ // was 3
Andrey Filippov's avatar
Andrey Filippov committed
3343 3344 3345 3346 3347
				SDFA_INSTANCE.showArrays(ps_smooth, "SM-"+title);
			}
			double threshold1=Math.log(2.0*mask1_threshold);
			mask1=new double [ps.length];
			for (int ii=0;ii<ps.length;ii++) mask1[ii]= ps[ii]-ps_smooth[ii]-threshold1;
Andrey Filippov's avatar
Andrey Filippov committed
3348
			if ((debug>2) ||((globalDebugLevel>2) && (title!=""))) { /* Increase debug level later */ // was 3
Andrey Filippov's avatar
Andrey Filippov committed
3349 3350 3351 3352 3353 3354 3355 3356 3357 3358
				SDFA_INSTANCE.showArrays(mask1, "M1-"+title);
			}
			fht_instance.swapQuadrants(mask1); // zero in the corner
			for (int ii=0;ii<mask1.length;ii++){
				if (mask1[ii]<0) {
					//				mask[ii]=0.0;
					mask1[ii]=0.0;
				}
				mask1[ii]*=mask[ii];
			}
Andrey Filippov's avatar
Andrey Filippov committed
3359
			if ((debug>2) ||((globalDebugLevel>2) && (title!=""))) { /* Increase debug level later */ // was 3
Andrey Filippov's avatar
Andrey Filippov committed
3360 3361 3362
				SDFA_INSTANCE.showArrays(mask1, "M1A-"+title);
			}
		}
3363
/* Mask already includes zeros on ps, so we can just use divisions of FHT*/
Andrey Filippov's avatar
Andrey Filippov committed
3364 3365 3366 3367
		//Swapping quadrants of the nominator, so the center will be 0,0
		fht_instance.swapQuadrants(nominatorPixels);
		//get to frequency domain
		fht_instance.transform(nominatorPixels);
Andrey Filippov's avatar
Andrey Filippov committed
3368
		if ((debug>2) ||((globalDebugLevel>2) && (title!=""))) { /* Increase debug evel later */ // was 3
Andrey Filippov's avatar
Andrey Filippov committed
3369 3370
			SDFA_INSTANCE.showArrays(nominatorPixels, title+"-NOM-FHT");
			SDFA_INSTANCE.showArrays(denominatorPixels, title+"-DENOM-FHT");
3371
		}
Andrey Filippov's avatar
Andrey Filippov committed
3372
		double [] pixels=fht_instance.divide(nominatorPixels,denominatorPixels);
Andrey Filippov's avatar
Andrey Filippov committed
3373
		if ((debug>2) ||((globalDebugLevel>2) && (title!=""))) { /* Increase debug evel later */ // was 3
Andrey Filippov's avatar
Andrey Filippov committed
3374
			SDFA_INSTANCE.showArrays(pixels, title+"-DECONV");
3375
		}
Andrey Filippov's avatar
Andrey Filippov committed
3376 3377 3378 3379
		for (i=0;i<pixels.length;i++) {
			if (mask[i]==0.0) pixels[i]=0.0; // preventing NaN*0.0
			else pixels[i]*=mask[i];
		}
Andrey Filippov's avatar
Andrey Filippov committed
3380
		if ((debug>2) ||((globalDebugLevel>2) && (title!=""))) { /* Increase debug level later */ // was 3
Andrey Filippov's avatar
Andrey Filippov committed
3381 3382 3383
			SDFA_INSTANCE.showArrays(pixels, title+"-MASKED");
			double [][] aphase=fht_instance.fht2AmpHase(pixels,true);
			SDFA_INSTANCE.showArrays(aphase, true,"AP="+title+"-MASKED");
3384

Andrey Filippov's avatar
Andrey Filippov committed
3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396
		}
		if (gaps_sigma>0.0){
			double [][] fft_reIm_centered=fht_instance.fht2ReIm(pixels, true); //0 in the center, full square
			fht_instance.swapQuadrants(mask1); // zero in the center
			for (int ii=0;ii<2;ii++) for (int jj=0;jj<mask1.length;jj++) fft_reIm_centered[ii][jj]*=mask1[jj];
			gb.blurDouble(mask1, size, size, gaps_sigma, gaps_sigma, 0.01);
			gb.blurDouble(fft_reIm_centered[0], size, size, gaps_sigma, gaps_sigma, 0.01);
			gb.blurDouble(fft_reIm_centered[1], size, size, gaps_sigma, gaps_sigma, 0.01);
			for (int ii=0;ii<2;ii++) for (int jj=0;jj<mask1.length;jj++)
				if (mask1[jj]>mask_denoise) fft_reIm_centered[ii][jj]/=mask1[jj];
				else if (mask1[jj]>=0.0) fft_reIm_centered[ii][jj]/=mask_denoise;
				else  fft_reIm_centered[ii][jj]=0.0;
Andrey Filippov's avatar
Andrey Filippov committed
3397
			if ((debug>2) ||((globalDebugLevel>2) && (title!=""))) { /* Increase debug level later */ // was 3
Andrey Filippov's avatar
Andrey Filippov committed
3398 3399 3400 3401 3402
				SDFA_INSTANCE.showArrays(fft_reIm_centered, true,"ReIm-"+title);
			}
			fht_instance.swapQuadrants(fft_reIm_centered[0]); // zero in the corner
			fht_instance.swapQuadrants(fft_reIm_centered[1]); // zero in the corner
			pixels=fht_instance.FFTHalf2FHT(fft_reIm_centered, size);
3403
		//mask_denoise
Andrey Filippov's avatar
Andrey Filippov committed
3404 3405 3406 3407
		}
		/// transform to space
		fht_instance.inverseTransform(pixels);
		fht_instance.swapQuadrants(pixels);
Andrey Filippov's avatar
Andrey Filippov committed
3408
		if ((debug>2) ||((globalDebugLevel>2) && (title!=""))) { /* Increase debug level later */ // was 3
Andrey Filippov's avatar
Andrey Filippov committed
3409 3410 3411 3412 3413
			SDFA_INSTANCE.showArrays(pixels, "PSF-"+title);
		}
		return pixels;
	}

Andrey Filippov's avatar
Andrey Filippov committed
3414 3415
	/* ======================================================================== */
	/* Trying to remove aliasing artifacts when the decimated (pixel resolution) image is deconvolved with full resolution (sub-pixel resolution)
3416
	model pattern. This effect is also easily visible if the decimated model is deconvolved with the same one at full resolution.
Andrey Filippov's avatar
Andrey Filippov committed
3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433
	Solution is to clone the power spectrum of the full resolution model with the shifts to match oversampling (15 clones for the 4x oversampling),
	And add them together (adding also zero frequerncy point - it might be absent on the model) but not include the original (true one) and
	use the result to create a rejectiobn mask - if the energy was high, (multiplicative) mask should be zero at those points. */

		private double [] maskAliases (double [] fht, // complex spectrum, [size/2+1][size]
				boolean checker, // checkerboard pattern in the source file (use when filtering)
				int oversample,  // measured array is sampled at 1/oversample frequency than model (will add more parameters later)
				double zerofreq_size,  // add rejection of zero frequency (~2-3pix)
				double sigma,
				double deconvInvert,
				double threshold_high,  // reject completely if energy is above this part of maximal
				double threshold_low,  // leave intact if energy is below this part of maximal
				DoubleFHT fht_instance,
				int globalDebugLevel){ // provide DoubleFHT instance to save on initializations (or null)

			int length=fht.length;
			int size=(int) Math.sqrt(fht.length);
3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444
// temporary fix to match original parameters for size = 10254 (LWIR - 64)

//			double threshold_high_mod = threshold_high * 1024/size;
//			double threshold_low_mod = threshold_low *   1024/size;

//			double th=threshold_high_mod * threshold_high_mod;
//			double tl=threshold_low_mod *  threshold_low_mod;

			double th=threshold_high * threshold_high;
			double tl=threshold_low *  threshold_low;

Andrey Filippov's avatar
Andrey Filippov committed
3445 3446 3447
			//	double [][] ps=new double [size/2+1][size];
			int i,ix,iy, cloneNx, cloneNy, cloneX, cloneY;
			int cloneStep=size/oversample;
Andrey Filippov's avatar
Andrey Filippov committed
3448
	/* generating power spectrum for the high-res complex spectrum, find maximum value and normalize */
Andrey Filippov's avatar
Andrey Filippov committed
3449 3450 3451 3452 3453 3454
			if (fht_instance==null) fht_instance=new DoubleFHT(); // move upstream to reduce number of initializations
			double [] ps=fht_instance.calculateAmplitude2(fht);
			double psMax=0.0;
			for (i=0;i<length; i++) if (psMax<ps[i]) psMax=ps[i];
			double k=1.0/psMax;
			for (i=0;i<length; i++) ps[i]*=k;
3455 3456 3457
			if (globalDebugLevel>2) {
				SDFA_INSTANCE.showArrays(ps, "PS");
			}
Andrey Filippov's avatar
Andrey Filippov committed
3458
	/* Add maximum at (0,0) */
Andrey Filippov's avatar
Andrey Filippov committed
3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469
			double [] psWithZero=ps;
			if (zerofreq_size>0.0) {
				psWithZero=ps.clone();
				int zs=(int) (4*zerofreq_size);
				int base=size*(size+1)/2;
				k=0.5/(zerofreq_size*zerofreq_size);
				if (zs>=size/2) zs =size/2;
				for (iy=-zs;iy<=zs;iy++) for (ix=-zs; ix <= zs; ix++) {
					psWithZero[base+iy*size+ix]+=Math.exp(-k*(iy*iy+ix*ix));
				}
			}
Andrey Filippov's avatar
Andrey Filippov committed
3470
	/* put zero in the center */
Andrey Filippov's avatar
Andrey Filippov committed
3471 3472
			double [] mask=new double [length];
			for (i=0;i<length; i++) mask[i]=0.0;
Andrey Filippov's avatar
Andrey Filippov committed
3473
	/* clone spectrums */
Andrey Filippov's avatar
Andrey Filippov committed
3474 3475 3476 3477 3478 3479 3480 3481
			for (iy=0;iy<size;iy++) for (ix=0;ix<size;ix++){
				for (cloneNy=0;cloneNy<oversample;cloneNy++) for (cloneNx=0;cloneNx<oversample;cloneNx++)
					if (((cloneNy!=0) || (cloneNx!=0)) && // not a zero point
							(!checker ||                      // use all if it is not a checkerboard pattren
									(((cloneNx ^ cloneNy) & 1)==0) )) { // remove clones in a checker pattern
						cloneY=(iy+cloneNy*cloneStep)%size;
						cloneX=(ix+cloneNx*cloneStep)%size;
						mask[cloneY*size+cloneX]+=psWithZero[iy*size+ix];
3482
					}
Andrey Filippov's avatar
Andrey Filippov committed
3483
			}
Andrey Filippov's avatar
Andrey Filippov committed
3484
	/* debug show the mask */
3485 3486 3487
			if (globalDebugLevel>2) {
				SDFA_INSTANCE.showArrays(mask, "PS-cloned");
			}
Andrey Filippov's avatar
Andrey Filippov committed
3488 3489 3490
			if (sigma>0) {
				DoubleGaussianBlur gb = new DoubleGaussianBlur();
				gb.blurDouble(mask,size,size,sigma,sigma, 0.01);
3491 3492 3493
				if (globalDebugLevel>2) {
					SDFA_INSTANCE.showArrays(mask, "PS-smooth");
				}
Andrey Filippov's avatar
Andrey Filippov committed
3494 3495
			}

Andrey Filippov's avatar
Andrey Filippov committed
3496
	/* make mask of cloned power spectrums */
Andrey Filippov's avatar
Andrey Filippov committed
3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507
			double a;
			double k2=deconvInvert*deconvInvert;
			double min=0.01*k2; // less than 1/10 of that value - mask=0.0
			if (globalDebugLevel>2) System.out.println("maskAliases() threshold_high="+threshold_high+" threshold_low="+threshold_low+" th="+th+" tl="+tl+" k2="+k2+" min="+min);
			for (i=0;i<length;i++) {
				if      (mask[i]<tl)  mask[i]=1.0;
				else if (mask[i]>th) mask[i]=0.0;
				else { // make smooth transition
					a=(2.0 * mask[i] - th - tl)/(th - tl);
					mask[i]=0.5*(1.0-a*a*a);
				}
3508
				// now mask out zeros on the ps
Andrey Filippov's avatar
Andrey Filippov committed
3509 3510 3511 3512 3513
				if (ps[i]<min) mask[i]=0.0;
				else {
					mask[i]*=ps[i]/(ps[i]+k2);
				}
			}
3514 3515 3516
			if (globalDebugLevel>2) {
				SDFA_INSTANCE.showArrays(mask, "mask-all");
			}
3517
			/* zeros are now for FHT - in the top left corner */
Andrey Filippov's avatar
Andrey Filippov committed
3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544
			fht_instance.swapQuadrants(mask);
			return mask;
		}


	private boolean [][] mapFromPatternMask (
			MatchSimulatedPattern matchSimulatedPattern, // to use windowFunction
			int width, // image (mask) width
			int tileSize,
			int tileStep,
			int margin,   // backward compatibility margin==tileSize/2
			double gaussWidth,
			double threshold,
			int debugLevel){
		int [] uvIndex=matchSimulatedPattern.getUVIndex(); // int array, >=0 - uv exist, <0 - empty
		if (uvIndex==null) return null;
		double[] windowFunction= matchSimulatedPattern.initWindowFunction(tileSize, gaussWidth);
		int height =uvIndex.length/width;
		int tileHeight=(height-2*margin)/tileStep+1;
		int tileWidth= (width- 2*margin)/tileStep+1;
		boolean [][] result = new boolean [tileHeight][tileWidth];
		int index;
		int len=tileSize*tileSize;
		double absThresh=0.0, sum;
		for (index=0;index<len;index++) absThresh+=windowFunction[index];
		absThresh*=threshold;
		if (debugLevel>1) System.out.println(" threshold="+threshold+" absThresh="+absThresh);
3545

Andrey Filippov's avatar
Andrey Filippov committed
3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558
		int y,x,y0,x0;
		for (int tileY=0;tileY<tileHeight;tileY++) for (int tileX=0;tileX<tileWidth;tileX++) {
			y0=-tileSize/2+margin+tileStep*tileY;
			x0=-tileSize/2+margin+tileStep*tileX;
			sum=0;
			for (index=0;index<len;index++) {
				y=index/tileSize+y0;
				x=index%tileSize+x0;
				if ((y>=0) && (x>=0) && (y<height) && (x<width) && (uvIndex[y*width+x]>=0)) sum+= windowFunction[index];
//				if ((globalDebugLevel>0) && (tileY==22) && (tileX==32)) System.out.println(" x="+x+" y="+y);
//				if ((globalDebugLevel>0) && (tileY==22) && (tileX==32) && (y>=0) && (x>=0) && (y<height) && (x<width))System.out.println(" uvIndex["+(y*width+x)+"]="+uvIndex[y*width+x]);
			}
			result[tileY][tileX]=(sum>absThresh);
3559
			if (debugLevel>1) System.out.println(" tileY="+tileY+" tileX="+tileX+" x0="+x0+" y0="+y0+" sum="+sum+" threshold="+threshold+" absThresh="+absThresh+" rrsult="+result[tileY][tileX]);
Andrey Filippov's avatar
Andrey Filippov committed
3560 3561 3562
		}
		return result;
	}
3563 3564

	/* ========================================================================
Andrey Filippov's avatar
Andrey Filippov committed
3565 3566 3567 3568 3569
	/**
	 * Mostly done, need to move where szis\
	 * TODO: currently the shift of the PSF during binning is done with the integer steps. If ignoreChromatic - to all colors
	 * independently, if it is false - all components are moved in sync, but again - with integer steps. That causes
	 * mis-match between the PSF calculated in nearly identical runs (i.e. use the data shifted by 2 pixels) caused by 1 pixel shift.
3570
	 * That can be improved if PSF are shifted smoothly (not so easy though). It is probably already handled when averaging PSF -
Andrey Filippov's avatar
Andrey Filippov committed
3571
	 * amplitude and phase is handled separately so shift should be OK.
3572
	 *
Andrey Filippov's avatar
Andrey Filippov committed
3573
	 */
3574 3575


Andrey Filippov's avatar
Andrey Filippov committed
3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587
		double [] combinePSF (double []pixels,         // Square array of pixels with multiple repeated PSF (alternating sign)
				boolean   master,          // force ignoreChromatic
				double[] centerXY,         // coordinates (x,y) of the center point (will update if ignoreChromatic is true)
				double [] centroid_xy,    // RETURNS centroid of the result array (should be small) if ignoreChromatic is true
				double [][] wVectors,    // two wave vectors, lengths in cycles/pixel (pixels match pixel array)
				EyesisAberrations.PSFParameters psfParameters,    // minimal instance contrast to use in binning
				DoubleFHT fht_instance, // provide DoubleFHT instance to save on initializations (or null) // used for sub-pixel shift, null OK
				String title,     // reduce the PSF cell size to this part of the area connecting first negative clones
				boolean debug,
				int debugLevel)
		{
			if (pixels==null) return null;
3588 3589 3590
//			if (centroid_xy == null) {
//				return null; // debugging LWIR, never before
//			}
Andrey Filippov's avatar
Andrey Filippov committed
3591 3592 3593 3594 3595 3596 3597 3598
			//    double [] contrastCache=new double[pixelSize*pixelSize];
			int i,j;

			if (debugLevel>2) {
				System.out.println("combinePSF title="+title+" wV[0][0]="+IJ.d2s(wVectors[0][0],4)+" wV[0][1]="+IJ.d2s(wVectors[0][1],4));
				System.out.println("combinePSF title="+title+" wV[1][0]="+IJ.d2s(wVectors[1][0],4)+" wV[1][1]="+IJ.d2s(wVectors[1][1],4));
			}

Andrey Filippov's avatar
Andrey Filippov committed
3599
	/* vectors perpendicular to the checkerboard edges, lengths equal to the periods */
Andrey Filippov's avatar
Andrey Filippov committed
3600 3601 3602 3603 3604 3605 3606 3607 3608
			double [][] f= {{wVectors[0][0]/(wVectors[0][0]*wVectors[0][0]+wVectors[0][1]*wVectors[0][1]),
				wVectors[0][1]/(wVectors[0][0]*wVectors[0][0]+wVectors[0][1]*wVectors[0][1])},
				{wVectors[1][0]/(wVectors[1][0]*wVectors[1][0]+wVectors[1][1]*wVectors[1][1]),
					wVectors[1][1]/(wVectors[1][0]*wVectors[1][0]+wVectors[1][1]*wVectors[1][1])}};
			if (debugLevel>2) {
				System.out.println("combinePSF title="+title+" f[0][0]="+IJ.d2s(f[0][0],4)+" f[0][1]="+IJ.d2s(f[0][1],4));
				System.out.println("combinePSF title="+title+" f[1][0]="+IJ.d2s(f[1][0],4)+" f[1][1]="+IJ.d2s(f[1][1],4));
			}

Andrey Filippov's avatar
Andrey Filippov committed
3609
	/* vectors parallel to checkerboard edges, lenghs equal to the period along those lines */
Andrey Filippov's avatar
Andrey Filippov committed
3610 3611 3612 3613 3614 3615 3616 3617 3618
			double l2f1=   f[0][0]*f[0][0]+f[0][1]*f[0][1];
			double l2f2=   f[1][0]*f[1][0]+f[1][1]*f[1][1];
			double pf1f2  =f[0][1]*f[1][0]-f[1][1]*f[0][0];
			double [][]g0= {{f[0][1]*l2f2/pf1f2,  -f[0][0]*l2f2/pf1f2},
					{f[1][1]*l2f1/pf1f2,  -f[1][0]*l2f1/pf1f2}};
			if (debugLevel>2) {
				System.out.println("combinePSF title="+title+" g0[0][0]="+IJ.d2s(g0[0][0],4)+" g[0][1]="+IJ.d2s(g0[0][1],4));
				System.out.println("combinePSF title="+title+" g0[1][0]="+IJ.d2s(g0[1][0],4)+" g[1][1]="+IJ.d2s(g0[1][1],4));
			}
Andrey Filippov's avatar
Andrey Filippov committed
3619
	/* calculate vectors connecting centers of the "positive" PSF copies */
Andrey Filippov's avatar
Andrey Filippov committed
3620 3621 3622 3623 3624 3625 3626 3627 3628 3629

			double [][] g= {{0.5*(g0[0][0]+g0[1][0]), 0.5*(g0[0][1]+g0[1][1])},
					{0.5*(g0[0][0]-g0[1][0]), 0.5*(g0[0][1]-g0[1][1])}};

			if (debugLevel>2) {
				System.out.println("combinePSF title="+title+" g[0][0]="+IJ.d2s(g[0][0],4)+" g[0][1]="+IJ.d2s(g[0][1],4));
				System.out.println("combinePSF title="+title+" g[1][0]="+IJ.d2s(g[1][0],4)+" g[1][1]="+IJ.d2s(g[1][1],4));
			}
			/// =================

Andrey Filippov's avatar
Andrey Filippov committed
3630
	/* calculate outSize to be able to use FFT here */
Andrey Filippov's avatar
Andrey Filippov committed
3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651
			double sizeNegatives= Math.max(Math.max(Math.abs(g[0][0]+ g[1][0]),Math.abs(g[0][1]+ g[1][1])),
					Math.max(Math.abs(g[0][0]- g[1][0]),Math.abs(g[0][1]- g[1][1])));
			double scaleSize=2.5; /// Will include next positive centers and overlap
			int outSize;
			for (outSize=8;outSize<scaleSize*sizeNegatives; outSize<<=1);
			int halfOutSize=outSize/2;
			if (debugLevel>2) {
				System.out.println("sizeNegatives="+sizeNegatives+ " scaled="+ (scaleSize*sizeNegatives)+" outSize="+outSize+" halfOutSize="+halfOutSize);
			}

			double [] pixelsPSF= binPSF(pixels,
					g,
					outSize,
					psfParameters.minContrast,  // minimal contrast of PSF clones
					centerXY,  //  coordinates (x,y) of the center point
					null,  // coordinates of the center of symmetry - not applicable
					1, // pass 1
					title,
					debug,
					debugLevel);
			//                   true);
3652

3653
			if (!master && !psfParameters.ignoreChromatic && !psfParameters.absoluteCenter && psfParameters.centerPSF && (centerXY!=null)){
Andrey Filippov's avatar
Andrey Filippov committed
3654 3655
//				System.out.println("1:pixelsPSF.length="+pixelsPSF.length+" outSize+"+outSize);

3656
				// TODO: Shift +/- 0.5 Pix here {centerXY[0]-Math.round(centerXY[0]),centerXY[1]-Math.round(centerXY[1])}
Andrey Filippov's avatar
Andrey Filippov committed
3657 3658 3659 3660 3661
				if (fht_instance==null) fht_instance=new DoubleFHT();
//				fht_instance.debug=(centerXY[0]-Math.round(centerXY[0]))<-0.4; // just reducing number
//				double dx=centerXY[0]-Math.round(centerXY[0]);
//				double dy=centerXY[1]-Math.round(centerXY[1]);
//				if (dx<-0.4) SDFA_INSTANCE.showArrays(pixelsPSF.clone(), "before:"+dx+":"+dy);
3662

Andrey Filippov's avatar
Andrey Filippov committed
3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685
				pixelsPSF=fht_instance.translateSubPixel (
						 pixelsPSF,
						 -(centerXY[0]-Math.round(centerXY[0])),
						 -(centerXY[1]-Math.round(centerXY[1])));
//				fht_instance.debug=false;
//				if (dx<-0.4) SDFA_INSTANCE.showArrays(pixelsPSF.clone(), "after:"+dx+":"+dy);

			}

			double distToNegativeClones=0.5*Math.sqrt(((g[0][0]+g[1][0])*(g[0][0]+g[1][0])+
					(g[0][1]+g[1][1])*(g[0][1]+g[1][1])+
					(g[0][0]-g[1][0])*(g[0][0]-g[1][0])+
					(g[0][1]-g[1][1])*(g[0][1]-g[1][1]))/2.0);
			if (debugLevel>2) {
				System.out.println("distToNegativeClones="+distToNegativeClones+ " gaussWidth="+ distToNegativeClones*psfParameters.smoothSeparate);
			}
			double smoothSigma=distToNegativeClones*psfParameters.smoothSeparate;

			//	double [] smoothPixelsPSF= lowPassGauss(pixelsPSF, smoothSigma, true);
			double [] smoothPixelsPSF= pixelsPSF.clone();
			DoubleGaussianBlur gb=new DoubleGaussianBlur();
			gb.blurDouble(smoothPixelsPSF, outSize, outSize, smoothSigma, smoothSigma, 0.01);

Andrey Filippov's avatar
Andrey Filippov committed
3686
	/* find amplitude of smoothed pixel array */
Andrey Filippov's avatar
Andrey Filippov committed
3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709
			double smoothMin=0.0;
			double smoothMax=0.0;
			for (i=0;i<smoothPixelsPSF.length;i++) {
				if      (smoothPixelsPSF[i] > smoothMax) smoothMax=smoothPixelsPSF[i];
				else if (smoothPixelsPSF[i] < smoothMin) smoothMin=smoothPixelsPSF[i];
			}
			int [][]  clusterMask = findClusterOnPSF(smoothPixelsPSF, // PSF function, square array (use smooth array)
					-psfParameters.topCenter, // fraction of energy in the pixels to be used (or minimal level if it is negative)
					outSize/2,  // location of a start point, x-coordinate
					outSize/2,  // location of a start point, y-coordinate
					title,
					debugLevel);
			double [] centroidXY=       calcCentroidFromCenter(pixelsPSF, // use original array (mask from the smoothed one)
					//--centroidXY is in function call arguments
					//centroidXY=            calcCentroidFromCenter(pixelsPSF, // use original array (mask from the smoothed one)
					clusterMask, // integer mask -0 - don't use this pixel, 1 - use it
					psfParameters.topCenter);// subtract level below topCenter*max
			double [] centroidXY_smooth=calcCentroidFromCenter(smoothPixelsPSF, // use smooth - not final, just for clones rejection
					clusterMask, // integer mask -0 - don't use this pixel, 1 - use it
					psfParameters.topCenter);// subtract level below topCenter*max

			if (debugLevel>2) System.out.println("Centroid after first binPSF: x="+IJ.d2s(centroidXY[0],3)+" y="+IJ.d2s(centroidXY[1],3)+" center was at x="+IJ.d2s(centerXY[0],3)+" y="+IJ.d2s(centerXY[1],3));

Andrey Filippov's avatar
Andrey Filippov committed
3710
	/* Re-bin results with the new center if ignoreChromatic is true, update centerXY[](shift of the result PSF array) and centroidXY[] (center of the optionally shifted PDF array) */
3711
			if (!psfParameters.absoluteCenter && (master || psfParameters.ignoreChromatic)) {
Andrey Filippov's avatar
Andrey Filippov committed
3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727
				if (centerXY!=null) {
					centerXY[0]+=centroidXY[0];
					centerXY[1]+=centroidXY[1];
				}
				pixelsPSF= binPSF(   pixels,
						g,
						outSize,
						psfParameters.minContrast,  // minimal contrast of PSF clones
						centerXY,  // now includes centroid from the pass 1
						psfParameters.symm180?centroidXY:null,
								2, // pass2
								title,
								debug,
								debugLevel);
				if (psfParameters.centerPSF && (centerXY!=null)){
//					System.out.println("2:pixelsPSF.length="+pixelsPSF.length+" outSize+"+outSize);
3728
					// TODO: Shift +/- 0.5 Pix here {centerXY[0]-Math.round(centerXY[0]),centerXY[1]-Math.round(centerXY[1])}
Andrey Filippov's avatar
Andrey Filippov committed
3729 3730 3731 3732 3733 3734 3735 3736
					if (fht_instance==null) fht_instance=new DoubleFHT();
//					fht_instance.debug=(centerXY[0]-Math.round(centerXY[0]))<-0.4; // just reducing number
					pixelsPSF=fht_instance.translateSubPixel (
							 pixelsPSF,
							 -(centerXY[0]-Math.round(centerXY[0])),
							 -(centerXY[1]-Math.round(centerXY[1])));
//					fht_instance.debug=false;
				}
Andrey Filippov's avatar
Andrey Filippov committed
3737
	/*  recalculate centroids  */
Andrey Filippov's avatar
Andrey Filippov committed
3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761
				smoothPixelsPSF= pixelsPSF.clone();
				gb.blurDouble(smoothPixelsPSF, outSize, outSize, smoothSigma, smoothSigma, 0.01);
				smoothMin=0.0;
				smoothMax=0.0;
				for (i=0;i<smoothPixelsPSF.length;i++) {
					if      (smoothPixelsPSF[i] > smoothMax) smoothMax=smoothPixelsPSF[i];
					else if (smoothPixelsPSF[i] < smoothMin) smoothMin=smoothPixelsPSF[i];
				}
				clusterMask = findClusterOnPSF(smoothPixelsPSF, // PSF function, square array (use smooth array)
						-psfParameters.topCenter, // fraction of energy in the pixels to be used (or minimal level if it is negative)
						outSize/2,  // location of a start point, x-coordinate
						outSize/2,  // location of a start point, y-coordinate
						title,
						debugLevel);
				centroidXY= calcCentroidFromCenter(pixelsPSF, // use original array (mask from the smoothed one)
						clusterMask, // integer mask -0 - don't use this pixel, 1 - use it
						psfParameters.topCenter);// subtract level below topCenter*max
				// seems it is not used anymore
				centroidXY_smooth=calcCentroidFromCenter(smoothPixelsPSF, // use smooth - not final, just for clones rejection
						clusterMask, // integer mask -0 - don't use this pixel, 1 - use it
						psfParameters.topCenter);// subtract level below topCenter*max
				if (debugLevel>2) System.out.println("Centroid after second binPSF: x="+IJ.d2s(centroidXY[0],3)+" y="+IJ.d2s(centroidXY[1],3)+" center was at x="+IJ.d2s(centerXY[0],3)+" y="+IJ.d2s(centerXY[1],3));

			}
3762 3763 3764



Andrey Filippov's avatar
Andrey Filippov committed
3765
	/* compensate center point and/or add center-symmetrical points if enabled */
Andrey Filippov's avatar
Andrey Filippov committed
3766 3767 3768
			double [] rejectedClonesPixels=null;
			double [][] modelPSFVectors={{0.5*(g[0][0]+g[1][0]),0.5*(g[0][1]+g[1][1])},
					{0.5*(g[0][0]-g[1][0]),0.5*(g[0][1]-g[1][1])}};
3769
	/********* removed subtraction of clones *****************************************************************/
Andrey Filippov's avatar
Andrey Filippov committed
3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790
			rejectedClonesPixels=pixelsPSF; // Maybe fo the opposite?
			maskClonesPSF(rejectedClonesPixels, // square pixel array where the model PSF is added
					psfParameters.windowFrac, // multiply window by this value
					centroidXY[0], // Center of the remaining single PSF
					centroidXY[1], // same for Y
					modelPSFVectors, // vectors that connect center of PSF with two oppositre sign clones
					psfParameters.useWindow);  // use Hamming window, if false - just cut sharp

			if (psfParameters.wingsEnergy>0.0) {
				rejectedClonesPixels=cutPSFWings (rejectedClonesPixels, // direct PSF function, square array, may be proportionally larger than reversed
						psfParameters.wingsEnergy, // fraction of energy in the pixels to be used
						psfParameters.wingsEllipseScale,
						0.003, // wings_min_mask_threshold, // zero output element if elliptical Gauss mask is below this threshold
						title+"-w",
						debugLevel);
			}
			double [] sigmas=createSigmasRadius(rejectedClonesPixels, // input square pixel array, preferrably having many exact zeros (they will be skipped)
					psfParameters.sigmaToRadius, // sigma is proportional to the distance from the center
					centroidXY[0], // model PSF center X-coordinate (in pixels[] units, from the center of the array )
					centroidXY[1], // same for Y
					0, // int WOICenterX, // window of interest in pixels[] array - do not generate data outside it
3791
					0, // int WOICenterY, //
Andrey Filippov's avatar
Andrey Filippov committed
3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802
					outSize, //int WOIWidth, reduce later
					outSize); //int WOIHeight)

			double max1=0;
			for (i=0;i<smoothPixelsPSF.length;i++) if (smoothPixelsPSF[i]>max1) max1=smoothPixelsPSF[i];
			double minSigma=0.5;
			double varSigmaTop=1.0 ; //0.7;
			double kk;

			for (i=0;i<sigmas.length;i++) {
				kk=smoothPixelsPSF[i]/max1;
3803
				if (kk>varSigmaTop) sigmas[i]=minSigma;
Andrey Filippov's avatar
Andrey Filippov committed
3804 3805 3806 3807 3808 3809
				else                sigmas[i] = minSigma+ sigmas[i]*((varSigmaTop-kk)*(varSigmaTop-kk)/varSigmaTop/varSigmaTop);
			}
			double [] varFilteredPSF=variableGaussBlurr(rejectedClonesPixels, // input square pixel array, preferrably having many exact zeros (they will be skipped)
					sigmas, // array of sigmas to be used for each pixel, matches pixels[]
					3.5, // drop calculatin if farther then nSigma
					0, // int WOICenterX, // window of interest in pixels[] array - do not generate data outside it
3810
					0, // int WOICenterY, //
Andrey Filippov's avatar
Andrey Filippov committed
3811 3812 3813 3814 3815 3816
					outSize, //int WOIWidth, reduce later
					outSize,
					debugLevel); //int WOIHeight)


			if (debugLevel>2) {
Andrey Filippov's avatar
Andrey Filippov committed
3817
	/* Sigmas are 0 here ??? */
Andrey Filippov's avatar
Andrey Filippov committed
3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834
				if (psfParameters.sigmaToRadius>0.0) {
					float [] floatPixelsSigmas=new float[sigmas.length];
					for (j=0;j<sigmas.length;j++) floatPixelsSigmas[j]=(float) sigmas[j];
					ImageProcessor ip_Sigmas=new FloatProcessor(outSize,outSize);
					ip_Sigmas.setPixels(floatPixelsSigmas);
					ip_Sigmas.resetMinAndMax();
					ImagePlus imp_Sigmas=  new ImagePlus(title+"_Sigmas", ip_Sigmas);
					imp_Sigmas.show();
				}

				System.out.println("title="+title+" center X(pix)="+centroidXY_smooth[0]+"(smooth) center Y(pix)="+centroidXY_smooth[1]+"(smooth)");
				System.out.println("title="+title+" center X(pix)="+centroidXY[0]+"          center Y(pix)="+centroidXY[1]);
			}
			centroid_xy[0]=centroidXY[0];
			centroid_xy[1]=centroidXY[1];
			return  varFilteredPSF;
		}
Andrey Filippov's avatar
Andrey Filippov committed
3835
		/* ======================================================================== */
Andrey Filippov's avatar
Andrey Filippov committed
3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867
		public double [][] matrix2x2_invert(double [][] m ){
			double det=m[0][0]*m[1][1]-m[0][1]*m[1][0];
			double [][] rslt= {{ m[1][1]/det,  -m[0][1]/det},
					{-m[1][0]/det,   m[0][0]/det}};
			return rslt;
		}
		public double [][] matrix2x2_mul(double [][] a, double [][] b ){
			double [][] rslt={{a[0][0]*b[0][0]+a[0][1]*b[1][0], a[0][0]*b[0][1]+a[0][1]*b[1][1]},
					{a[1][0]*b[0][0]+a[1][1]*b[1][0], a[1][0]*b[0][1]+a[1][1]*b[1][1]}};
			return rslt;
		}
		public double [] matrix2x2_mul(double [][] a, double [] b ){
			double [] rslt={a[0][0]*b[0]+a[0][1]*b[1],
					a[1][0]*b[0]+a[1][1]*b[1]};
			return rslt;
		}
		public double [][] matrix2x2_scale(double [][] a, double  b ){
			double [][] rslt={{a[0][0]*b, a[0][1]*b},
					{a[1][0]*b, a[1][1]*b}};
			return rslt;
		}

		public double [][] matrix2x2_add(double [][] a, double [][] b ){
			double [][] rslt={{a[0][0]+b[0][0], a[0][1]+b[0][1]},
			         		  {a[1][0]+b[1][0], a[1][1]+b[1][1]}};
			return rslt;
		}

		public double [] matrix2x2_add(double [] a, double [] b ){
			double [] rslt={a[0]+b[0], a[1]+b[1]};
			return rslt;
		}
3868

Andrey Filippov's avatar
Andrey Filippov committed
3869 3870 3871 3872 3873
		public double [][] matrix2x2_transp(double [][] m ){
			double [][] rslt= {{ m[0][0],  m[1][0]},
			            	   { m[0][1],  m[1][1]}};
			return rslt;
		}
3874

Andrey Filippov's avatar
Andrey Filippov committed
3875 3876
		/* ======================================================================== */
		/* zeroes out area outside of the area bound by 4 negative clones (or a fraction of it), either sharp or with Hamming */
Andrey Filippov's avatar
Andrey Filippov committed
3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887
			private double [] maskClonesPSF(double [] pixels, // square pixel array where the model PSF is added
					double windowPart, // multiply window by this value
					double xc, // Center of the remaining single PSF
					double yc, // same for Y
					double[][] vectors, // vectors that connect center of PSF with two oppositre sign clones
					boolean  useHamming  // use Hamming window, if false - just cut sharp
			) {
				int ix,iy;
				int size = (int) Math.sqrt (pixels.length);
				double [] xy= new double[2];
				double [] uv;
Andrey Filippov's avatar
Andrey Filippov committed
3888
		/* matrix that converts u,v (lengths along the) 2 input vectors connecting opposite sign PSFs into x,y coordinates */
Andrey Filippov's avatar
Andrey Filippov committed
3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904
				double [][] uv2xy= {{vectors[0][0]*windowPart,vectors[1][0]*windowPart},
						{vectors[0][1]*windowPart,vectors[1][1]*windowPart}};
				double [][] xy2uv=  matrix2x2_invert(uv2xy);
				for (iy=0;iy<size;iy++) {
					xy[1]=(iy-size/2)-yc;
					for (ix=0;ix<size;ix++) {
						xy[0]=(ix-size/2)-xc;
						uv=matrix2x2_mul(xy2uv, xy);
						if ((Math.abs(uv[0])>1.0) || (Math.abs(uv[1])>1.0)) pixels[iy*size+ix]=0.0;
						else if (useHamming) {
							pixels[iy*size+ix]*=(0.54+0.46*Math.cos(uv[0]*Math.PI))*(0.54+0.46*Math.cos(uv[1]*Math.PI));
						}
					}
				}
				return pixels;
			}
Andrey Filippov's avatar
Andrey Filippov committed
3905
			/* ======================================================================== */
Andrey Filippov's avatar
Andrey Filippov committed
3906 3907 3908 3909
			private double [] variableGaussBlurr (double []pixels, // input square pixel array, preferrably having many exact zeros (they will be skipped)
					double []sigmas, // array of sigmas to be used for each pixel, matches pixels[]
					double nSigma, // drop calculatin if farther then nSigma
					int WOICenterX, // window of interest in pixels[] array - do not generate data outside it
3910
					int WOICenterY, //
Andrey Filippov's avatar
Andrey Filippov committed
3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936
					int WOIWidth, //
					int WOIHeight,
					int globalDebugLevel){ //
				int size = (int) Math.sqrt(pixels.length);
				double [] result =new double [size*size];
				double [] gauss= new double [2*size];
				int x0= (size-WOIWidth)/2 +WOICenterX;
				int y0= (size-WOIHeight)/2+WOICenterY;
				int x1=x0+WOIWidth;
				int y1=x0+WOIHeight;
				int i,ix,iy,max_i;
				double sum,k,sigma,d,gy,scale,g;
				int xk0,xk1,yk0,yk1, ikx,iky, index;
				for (i=0;i<result.length;i++) result[i]=0.0;
				if (globalDebugLevel>2) {
					System.out.println(" variableGaussBlurr(), x0="+x0+" y0="+y0+" x1="+x1+" y1="+y1);
				}
				if (x0<0) x0=0; if (x1>size) x1=size; if (y0<0) y0=0; if (y1>size) y1=size;
				for (iy=0;iy<size;iy++) {
					for (ix=0;ix<size;ix++) {
						d=pixels[iy*size+ix];
						if (d!=0.0) {
							sigma=sigmas[iy*size+ix];
							if (sigma==0.0) {
								result[iy*size+ix]+=d; // just copy input data, no convolving
							} else {
Andrey Filippov's avatar
Andrey Filippov committed
3937
		/* opposite to "normal" convolution we have diffrent kernel for each point, so we need to make sure that two points with the same values but
Andrey Filippov's avatar
Andrey Filippov committed
3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972
		  diffrent sigma values will not move "energy" from one to another. For this we can do accumulation both ways - from the source point to all
		   points "reachable" by the kernel (proportional to the pixel value) and also in opposite direction - from those other points to the current
		   pointer (where kernel is centered) with the value proportional to that othre point  */

								max_i= (int) (sigma*nSigma+1);
								k=1.0/(2.0*sigma*sigma);
								if (max_i>=gauss.length) max_i=gauss.length-1;
								sum=-0.5; // 0 is counted twice
								for (i=0; i<=max_i; i++) {
									gauss[i]=Math.exp(-k*i*i);
									sum+= gauss[i]; // could use - more errors for small values of gamma 1/Math.sqrt(2*Math.PI*sigma*sigma)
								}
								scale=0.5/sum;
								for (i=0; i<=max_i; i++) gauss[i]*=scale;
								yk0=-max_i; if (yk0<(y0-iy)) yk0=y0-iy;
								yk1= max_i; if (yk1>=(y1-iy)) yk1=y1-iy-1;
								xk0=-max_i; if (xk0<(x0-ix)) xk0=x0-ix;
								xk1= max_i; if (xk1>=(x1-ix)) xk1=x1-ix-1;

								for (iky=yk0;iky<=yk1;iky++) {
									gy=gauss[Math.abs(iky)]/2; // Extra /2 because we'll calculate the convolution twice from the [ix,iy] and to [ix,iy]
									for (ikx=xk0;ikx<=xk1;ikx++) {
										index=(iy+iky)*size+ix+ikx;
										g=gy*gauss[Math.abs(ikx)];
										result[index]+=d*g;
										result[iy*size+ix]+=pixels[index]*g;

									}
								}
							}
						}
					}
				}
				return result;
			}
3973 3974 3975



Andrey Filippov's avatar
Andrey Filippov committed
3976 3977
		/* ======================================================================== */
		/* find ellipse approximating section of the PSF, scale ellipse and use it as a mask to remove PSF far wings */
Andrey Filippov's avatar
Andrey Filippov committed
3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027
			private double [] cutPSFWings (double [] psf_pixels, // direct PSF function, square array, may be proportionally larger than reversed
					double cutoff_energy, // fraction of energy in the pixels to be used
					double ellipse_scale,
					double min_mask_threshold, // zero output element if elliptical Gauss mask is below this threshold
					String title,
					int globalDebugLevel)
			{
				int psf_size=(int)Math.sqrt(psf_pixels.length);
				double [] masked_psf=new double[psf_size*psf_size];
				int  [][]selection=   findClusterOnPSF(psf_pixels, cutoff_energy, title, globalDebugLevel);
				double [] ellipse_coeff=findEllipseOnPSF(psf_pixels,  selection,    title, globalDebugLevel);
				int ix,iy;
				double x,y,r2;
				int indx=0;
				double k2=1/ellipse_scale/ellipse_scale;
				double m;

				for (iy=0;iy<psf_size;iy++) {
					y=(iy-psf_size/2)-ellipse_coeff[1];  // scale to the original psf (and ellipse_coeff)
					for (ix=0;ix<psf_size;ix++) {
						x=(ix-psf_size/2)-ellipse_coeff[0]; // scale to the original psf (and ellipse_coeff)
						r2=ellipse_coeff[2]*x*x+ellipse_coeff[3]*y*y+ellipse_coeff[4]*x*y;
						m=Math.exp(-k2*r2);
						masked_psf[indx]=(m>=min_mask_threshold)?(psf_pixels[indx]*Math.exp(-k2*r2)):0.0;
						indx++;
					}
				}

				if (globalDebugLevel>2) {
					ImageProcessor ip_ellipse = new FloatProcessor(psf_size,psf_size);
					float [] ellipsePixels = new float [psf_size*psf_size];
					indx=0;
					for (iy=0;iy<psf_size;iy++) {
						y=(iy-psf_size/2)+ellipse_coeff[1];  // scale to the original psf (and ellipse_coeff), move center opposite to that of direct kernel (psf)
						for (ix=0;ix<psf_size;ix++) {
							x=(ix-psf_size/2)+ellipse_coeff[0]; // scale to the original psf (and ellipse_coeff), move center opposite to that of direct kernel (psf)
							r2=ellipse_coeff[2]*x*x+ellipse_coeff[3]*y*y+ellipse_coeff[4]*x*y;
							m=Math.exp(-k2*r2);
							ellipsePixels[indx++]=(float)((m>=min_mask_threshold)?(Math.exp(-k2*r2)):0.0);
						}
					}
					ip_ellipse.setPixels(ellipsePixels);
					ip_ellipse.resetMinAndMax();
					ImagePlus imp_ellipse= new ImagePlus(title+"_PSFWINGS-MASK_"+cutoff_energy+"-"+ellipse_scale, ip_ellipse);
					imp_ellipse.show();
				}
				return masked_psf;
			}


Andrey Filippov's avatar
Andrey Filippov committed
4028
		/* ======================================================================== */
Andrey Filippov's avatar
Andrey Filippov committed
4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041
			private double PSFAtXY(double [] pixels, int size, double x, double y) {
				int ix=(int) Math.round(x);
				int iy=(int) Math.round(y);
				if      (ix <  -size/2) ix=-size/2;
				else if (ix >=  size/2) ix= size/2-1;
				if      (iy <  -size/2) iy=-size/2;
				else if (iy >=  size/2) iy= size/2-1;
				int index=size* (size/2 + iy)+ size/2 + ix;
				if ((index<0) || (index > pixels.length)) {
					System.out.println("PSFAtXY error, x="+IJ.d2s(x,0)+" y="+IJ.d2s(y,0)+ " index="+(size*(size/2 + (int) Math.round(y))+ size/2 + (int) Math.round(x))+ " pixels.length="+pixels.length);
				}
				return pixels[index];
			}
Andrey Filippov's avatar
Andrey Filippov committed
4042
		/* ======================================================================== */
Andrey Filippov's avatar
Andrey Filippov committed
4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071

			private double contrastAtXY(int sign, double [] pixels, int size, double x, double y, double [][] g, double [] cache) {
				int ir= (int) Math.round(0.2*Math.min(Math.max(Math.abs(g[0][0]),Math.abs(g[1][0])),Math.max(Math.abs(g[0][1]),Math.abs(g[1][1])))); // sample at square 1 1/2x1/2 of the grid "square"

				int ix=(int) Math.round(x);
				int iy=(int) Math.round(y);
				if      (ix <  -size/2) ix=-size/2;
				else if (ix >=  size/2) ix= size/2-1;
				if      (iy <  -size/2) iy=-size/2;
				else if (iy >=  size/2) iy= size/2-1;
				int index= size* (size/2 + iy)+ size/2 + ix;
				//  if ((cache!=null) && (cache[index]>=0)) return sign*cache[index];
				if ((cache!=null) && (cache[index]>=0)) return cache[index];
				double rslt=0.0;
				int i,j;
				for (i=-ir;i<=ir;i++) for (j=-ir;j<=ir;j++) {
					rslt+=     PSFAtXY(pixels,size,j+ix,i+iy) -
					0.25* (PSFAtXY(pixels,size,j+ix+(g[0][0]+ g[1][0])/2  ,i+iy+(g[0][1]+ g[1][1])/2)+
							PSFAtXY(pixels,size,j+ix+(g[0][0]- g[1][0])/2  ,i+iy+(g[0][1]- g[1][1])/2)+
							PSFAtXY(pixels,size,j+ix-(g[0][0]+ g[1][0])/2  ,i+iy-(g[0][1]+ g[1][1])/2)+
							PSFAtXY(pixels,size,j+ix-(g[0][0]- g[1][0])/2  ,i+iy-(g[0][1]- g[1][1])/2));

				}
				rslt=rslt*sign;
				cache[index] = (rslt>0.0)?rslt:0.0;
				return rslt/ir/ir;
			}


Andrey Filippov's avatar
Andrey Filippov committed
4072 4073
		/* ======================================================================== */
		/* create aray (to be used with variableGaussBlurr() ) of per-pixel sigma values for gauss blur, proportional to distance from the specified center */
Andrey Filippov's avatar
Andrey Filippov committed
4074 4075 4076 4077 4078
			private double [] createSigmasRadius (double []pixels, // input square pixel array, preferrably having many exact zeros (they will be skipped)
					double sigmaToRadius, // sigma is proportional to the distance from the center
					double xc, // model PSF center X-coordinate (in pixels[] units, from the center of the array )
					double yc, // same for Y
					int WOICenterX, // window of interest in pixels[] array - do not generate data outside it
4079
					int WOICenterY, //
Andrey Filippov's avatar
Andrey Filippov committed
4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107
					int WOIWidth, //
					int WOIHeight) {
				int size = (int) Math.sqrt(pixels.length);
				double [] sigmas =new double [size*size];
				int x0= (size-WOIWidth)/2 +WOICenterX;
				int y0= (size-WOIHeight)/2+WOICenterY;
				int x1=x0+WOIWidth;
				int y1=x0+WOIHeight;
				int i,ix,iy;
				double r,x,y;
				for (i=0;i<sigmas.length;i++) sigmas[i]=0.0;
				if (x0<0) x0=0; if (x1>size) x1=size; if (y0<0) y0=0; if (y1>size) y1=size;
				for (iy=0;iy<size;iy++) {
					y=(iy-size/2)-yc;
					for (ix=0;ix<size;ix++) {
						x=(ix-size/2)-xc;
						r=Math.sqrt(x*x+y*y);
						//        sigma=r*sigmaToRadius;
						//        sigma=r*r/radiusSigma;
						//        sigmas[iy*size+ix]=(r*sigmaToRadius)+1;
						sigmas[iy*size+ix]=(r*sigmaToRadius);
					}
				}


				return sigmas;
			}

Andrey Filippov's avatar
Andrey Filippov committed
4108
			/* calculates ellipse (with the center at DC) that interpolates area of the points defined by flooding from the initial center,
Andrey Filippov's avatar
Andrey Filippov committed
4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151
			so total energy is cutoff_energy fraction
			returns {x0,y0,a,b,c} , where a*x^2+b*y^2 + c*x*y=r^2 , so r^2 can be used for a window that removes high far pixels
			distribute the whol mass at the ends of short and long ellipse axis
			u^2/Ru^2+V^2/Rv^2=1, u=cos(a)*x+sin(a)*y, v=-sin(a)*x+cos(a)*y
			c=cos(a), s=sin(a), S0=sum(f(x,y), SX2=sum(f(x,y)*(x-x0)*(x-x0)),SY2=sum(f(x,y)*(y-y0)*(y-y0)), SXY=sum(f(x,y)*(x-x0)*(y-y0))
			"effective" squared radius (to be used in Gaussian)
			r2= u^2/Ru^2+V^2/Rv^2
			r2= 1/Ru^2 * 1/Rv^2 * (x^2*(c^2*Rv^2+s^2*Ru^2)+y^2*(c^2*Ru^2+s^2*Rv^2)+2*x*y*c*s*(Rv^2-Ru^2)

			SX2/S0=1/2* ((c*Ru)^2 + (s*Rv)^2)         =1/2*(c^2*Ru^2 + s^2*Rv^2)
			SY2/S0=1/2* ((s*Ru)^2 + (c*Rv)^2)         =1/2*(c^2*Rv^2 + s^2*Ru^2)
			SXY/S0=1/2* ((c*Ru)*(s*Ru)-(c*Rv)*(s*rv)) =1/2*(c*s*(Ru^2 -Rv^2))

			r2= 1/Ru^2 * 1/Rv^2 * (x^2*(2*SY2/S0))+y^2*(2*SX2/S0)-2*2*x*y*(SXY/S0)

			SX2/S0+SY2/S0= 1/2*(Ru^2 + Rv^2)
			Ru^2+Rv^2= 2*(SX2+SY2)/S0
			Ru^2-Rv^2= 2* SXY /S0

			Ru^2=(SX2+SY2+SXY)/S0
			Rv^2=(SX2+SY2-SXY)/S0

			r2= a* x^2*+b*y^2+c*x*y
			a=  1/Ru^2 * 1/Rv^2 * (2*SY2/S0)
			b=  1/Ru^2 * 1/Rv^2 * (2*SX2/S0)
			c= -1/Ru^2 * 1/Rv^2 * (4*SXY/S0)
				 */
				private double [] findEllipseOnPSF(
						double []         psf,   // Point Spread Function (may be off-center)
						int    [][] selection, // 0/1 - selected/not selected
						String          title,
						int globalDebugLevel) {
					int i,j;
					double x,y;
					int size=(int) Math.sqrt(psf.length);
					double SX=0.0;
					double SY=0.0;
					double SX2=0.0;
					double SY2=0.0;
					double SXY=0.0;
					double S0=0.0;
					double d; //,k;
					//	double area=0; // selection area
Andrey Filippov's avatar
Andrey Filippov committed
4152
			/* find centyer */
Andrey Filippov's avatar
Andrey Filippov committed
4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171

					for (i=0;i<size;i++) {
						y=i-size/2;
						for (j=0;j<size;j++) if (selection[i][j]>0){
							x=j-size/2;
							d=psf[i*size+j];
							S0+=d;
							SX+=x*d;
							SY+=y*d;
							//			area+=1.0;
						}
					}
					double centerX=SX/S0;
					double centerY=SY/S0;
					if (globalDebugLevel>5) {
						//		System.out.println("findEllipseOnPSF: title="+title+" area="+area+" S0="+S0+" SX="+SX+" SY="+SY+" centerX="+centerX+" centerY="+centerY);
						System.out.println("findEllipseOnPSF: title="+title+" S0="+S0+" SX="+SX+" SY="+SY+" centerX="+centerX+" centerY="+centerY);
					}

Andrey Filippov's avatar
Andrey Filippov committed
4172
			/* second pass (could all be done in a single) */
Andrey Filippov's avatar
Andrey Filippov committed
4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212
					SX2=0.0;
					SY2=0.0;
					SXY=0.0;
					for (i=0;i<size;i++) {
						y=i-size/2-centerY;
						for (j=0;j<size;j++) if (selection[i][j]>0){
							x=j-size/2-centerX;
							d=psf[i*size+j];
							SX2+=x*x*d;
							SY2+=y*y*d;
							SXY+=x*y*d;
						}
					}
					if (globalDebugLevel>5) {
						System.out.println("findEllipseOnPXF: title="+title+" SX2="+SX2+" SY2="+SY2+" SXY="+SXY);
					}
					/*
			Ru^2=(SX2+SY2+SXY)/S0
			Rv^2=(SX2+SY2-SXY)/S0

			r2= a* x^2*+b*y^2+c*x*y
			a=  1/Ru^2 * 1/Rv^2 * (2*SY2/S0)
			b=  1/Ru^2 * 1/Rv^2 * (2*SX2/S0)
			c= -1/Ru^2 * 1/Rv^2 * (4*SXY/S0)
					 */
					double Ru2=(SX2+SY2+SXY)/S0;
					double Rv2=(SX2+SY2-SXY)/S0;
					double [] result = {centerX,
							centerY,
							1/Ru2 * 1/Rv2 * (2*SY2/S0),
							1/Ru2 * 1/Rv2 * (2*SX2/S0),
							-1/Ru2 * 1/Rv2 * (4*SXY/S0)};
					//	k=Math.PI*Math.PI/(2.0*S0*area*area);
					//	double [] result = {centerX,centerY,k*SY2,k*SX2,-2*k*SXY};
					if (globalDebugLevel>3) {
						System.out.println("findEllipseOnPS: title="+title+" x0="+result[0]+" y0="+result[1]+" a="+result[2]+" b="+result[3]+" c="+result[4]);
					}
					return result;
				}

4213

Andrey Filippov's avatar
Andrey Filippov committed
4214 4215
		/* ======================================================================== */
		/* finds cluster on the PSF (with the center at specidfied point)  by flooding from the specified center, so total energy is cutoff_energy fraction
Andrey Filippov's avatar
Andrey Filippov committed
4216
		returns integer array (same dimensions as input) with 1 - selected, 0 - not selected
4217
		cutoff_energy: if positive - specifies fraction of total energy, if negative -cutoff_energy is the minimal value of the pixel to be included
Andrey Filippov's avatar
Andrey Filippov committed
4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253
		UPDATE: follows gradient from the start point to a local maximum if "cutoff_energy" is negative" */
			private int [][] findClusterOnPSF(
					double []        psf, // PSF function, square array
					double cutoff_energy, // fraction of energy in the pixels to be used
					String         title,
					int            globalDebugLevel) {
				int size=(int) Math.sqrt(psf.length);
				return findClusterOnPSF(psf,          // PSF function, square array
						cutoff_energy, // fraction of energy in the pixels to be used
						size/2,        // X0
						size/2,        // Y0
						title,
						globalDebugLevel);
			}



			private int [][] findClusterOnPSF(
					double []        psf, // PSF function, square array
					double cutoff_energy, // fraction of energy in the pixels to be used (or minimal level if it is negative)
					int           startX,  // location of a start point, x-coordinate
					int           startY,  // location of a start point, y-coordinate
					String         title,
					int globalDebugLevel) {
				int i,j;
				int ix,iy,ix1,iy1,maxX, maxY;
				List <Integer> pixelList=new ArrayList<Integer>(100);
				Integer Index;
				int size=(int) Math.sqrt(psf.length);
				int [][]clusterMap=new int[size][size];
				double full_energy=0.0;
				int [][] dirs={{-1,0},{-1,-1},{0,-1},{1,-1},{1,0},{1,1},{0,1},{-1,1}};
				ix=startX;
				iy=startY;
				Index=iy*size + ix;
				double maxValue=psf[Index];
Andrey Filippov's avatar
Andrey Filippov committed
4254
		/* Make ix,iy to start from the maximal value on PSF */
Andrey Filippov's avatar
Andrey Filippov committed
4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308
				Index=0;
				for (i=0;i<size;i++) for (j=0;j<size;j++) {
					full_energy+=psf[Index];
					clusterMap[i][j]=0;
					if (psf[Index]>maxValue){
						maxValue=psf[Index];
						ix=j;
						iy=i;
					}
					Index++;
				}
				boolean noThreshold=(cutoff_energy<=0);
				double threshold=full_energy*((cutoff_energy>0)?cutoff_energy:1.0); // no limit for negative values of cutoff_energy
				double minValue=0.0; // no limit if total energy is controlled
				double cluster_energy=0.0;
				int clusterSize=0;
				boolean noNew=true;
				if (cutoff_energy<=0) { // find nearest local maximum following gradient
					ix=startX;
					iy=startY;
					maxValue=psf[iy*size + ix];
					for (noNew=false;noNew==false;){
						noNew=true;
						for (j=0;j<dirs.length;j++) if (((iy > 0 )        || (dirs[j][1]>=0)) &&
								((iy < (size-1) ) || (dirs[j][1]<=0)) &&
								((ix > 0 )        || (dirs[j][0]>=0)) &&
								((ix < (size-1) ) || (dirs[j][0]<=0))){
							ix1= ix+dirs[j][0];
							iy1= iy+dirs[j][1];
							if (psf[iy1*size+ix1]>maxValue) {
								noNew=false;
								maxValue= psf[iy1*size+ix1];
								ix=ix1;
								iy=iy1;
								break;
							}
						}
					}
					minValue=maxValue*(-cutoff_energy);
				}
		//
		if (globalDebugLevel>1)		System.out.println("findClusterOnPSF: full_energy="+full_energy+" minValue="+minValue+" maxValue="+maxValue);
		if (globalDebugLevel>1)		System.out.println("findClusterOnPSF: ix="+ix+" iy="+iy);
				maxX=0;
				maxY=0;
				int listIndex;
				Index=iy*size + ix;
				pixelList.clear();
				pixelList.add (Index);
				clusterSize++;
				clusterMap[iy][ix]=1;
				cluster_energy+=psf[Index];
				noNew=true;
				while ((pixelList.size()>0) &&  (noThreshold || (cluster_energy<threshold) )) { // will break from the loop if  (psf[Index] <minValue)
Andrey Filippov's avatar
Andrey Filippov committed
4309
		/* Find maximal new neighbor */
Andrey Filippov's avatar
Andrey Filippov committed
4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332
					maxValue=0.0;
					listIndex=0;
					while (listIndex<pixelList.size()) {
						Index=pixelList.get(listIndex);
						iy=Index/size;
						ix=Index%size;
						noNew=true;
						for (j=0;j<8;j++) if (((iy > 0 ) || (dirs[j][1]>=0)) && ((iy < (size-1) ) || (dirs[j][1]<=0))){
							ix1=(ix+dirs[j][0]+size) % size;
							iy1= iy+dirs[j][1];
							if (clusterMap[iy1][ix1]==0) {
								noNew=false;
								if (psf[iy1*size+ix1]>maxValue) {
									maxValue= psf[iy1*size+ix1];
									maxX=ix1;
									maxY=iy1;
								}
							}
						}
						if (noNew) pixelList.remove(listIndex);  //  remove current list element
						else       listIndex++;     // increase list index
					}
					if (maxValue==0.0) { // Should
4333 4334 4335 4336 4337
						if (!noThreshold) {
							SDFA_INSTANCE.showArrays(psf, title+"-failed_cluster");
							System.out.println("findClusterOnPSF: - should not get here - no points around >0, and threshold is not reached yet."+
							" startX="+startX+" startY="+startY);
						}
Andrey Filippov's avatar
Andrey Filippov committed
4338 4339
						break;
					}
Andrey Filippov's avatar
Andrey Filippov committed
4340
		/* Add this new point to the list */
Andrey Filippov's avatar
Andrey Filippov committed
4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364
					if (psf[Index]<minValue) break; // break if the condition was value, not total energy
					Index=maxY*size + maxX;
					pixelList.add (Index);
					clusterSize++;
					clusterMap[maxY][maxX]=1;
					cluster_energy+=psf[Index];

				} // end of while ((pixelList.size()>0) &&  (cluster_energy<threshold))
				if (globalDebugLevel>3)   System.out.println("findClusterOnPSF: cluster size is "+clusterSize);
				if (globalDebugLevel>6) {
					ImageProcessor ip2 = new FloatProcessor(size,size);
					float [] floatPixels = new float [size*size];
					for (i=0;i<floatPixels.length;i++) {
						floatPixels[i]=(float) psf[i];
					}
					ip2.setPixels(floatPixels);
					ip2.resetMinAndMax();
					ImagePlus imp2= new ImagePlus(title+"_PSF1_"+cutoff_energy, ip2);
					imp2.show();
				}
				if (globalDebugLevel>5) {
					ImageProcessor ip = new FloatProcessor(size,size);
					float [] floatPixels = new float [size*size];
					for (i=0;i<floatPixels.length;i++) {
4365
						floatPixels[i]=clusterMap[i/size][i%size];
Andrey Filippov's avatar
Andrey Filippov committed
4366 4367 4368 4369 4370 4371 4372 4373 4374
					}
					ip.setPixels(floatPixels);
					ip.resetMinAndMax();
					ImagePlus imp= new ImagePlus(title+"_PSF-SEL_"+cutoff_energy, ip);
					imp.show();
				}
				return clusterMap;
			}

Andrey Filippov's avatar
Andrey Filippov committed
4375 4376 4377
			/* ======================================================================== */
			/* ======================================================================== */
			/* calculates 2x2 matrix that converts two pairs of vectors: u2=M*u1, v2=M*v1*/
Andrey Filippov's avatar
Andrey Filippov committed
4378

Andrey Filippov's avatar
Andrey Filippov committed
4379
			/* ======================================================================== */
Andrey Filippov's avatar
Andrey Filippov committed
4380

Andrey Filippov's avatar
Andrey Filippov committed
4381
			/* ======================================================================== */
Andrey Filippov's avatar
Andrey Filippov committed
4382 4383 4384 4385 4386 4387 4388 4389 4390

				private  int [] convert2d_1d(int [][] pixels){
					int i,j;
					int width=pixels[0].length;
					int [] rslt=new int[pixels.length*pixels[0].length];
					for (i=0;i<pixels.length;i++) for (j=0;j<width;j++) rslt[i*width+j]=pixels[i][j];
					return rslt;
				}

Andrey Filippov's avatar
Andrey Filippov committed
4391
			/* pixels should be a square array, zero is in the center (/center+0.5 for even dimensions) */
Andrey Filippov's avatar
Andrey Filippov committed
4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431
//				private  double [] calcCentroidFromCenter(double [] pixels) {return calcCentroidFromCenter(pixels, (int[]) null, 0.0);}
				private  double [] calcCentroidFromCenter(double [] pixels, // square pixel array
						int[][] mask, // integer mask -0 - don't use this pixel, 1 - use it
						double refLevel) { // subtract this fraction of maximal level from all pixels
					return calcCentroidFromCenter(pixels, convert2d_1d(mask), refLevel);
				}
				private  double [] calcCentroidFromCenter(double [] pixels, // square pixel array
						int[] mask, // integer mask -0 - don't use this pixel, 1 - use it
						double refLevel) { // subtract this fraction of maximal leve from all pixels
					int size = (int) Math.sqrt ( pixels.length);
					int c= size/2;
					double S0=0.0;
					double SX=0.0;
					double SY=0.0;
					double x,y,p;
					int i,j,indx;
					double maxValue = 0.0;
					if (refLevel>0.0) for (i=0;i<pixels.length;i++) if (((mask==null) || (mask[i]>0)) && (pixels[i] > maxValue)) maxValue=pixels[i];

					double minValue=refLevel*maxValue;

					for (i=0;i<size;i++) {
						y=i-c;
						for (j=0;j<size;j++) {
							indx=i*size+j;
							if ((mask==null) || (mask[indx]>0)) {
								x=j-c;
								p=pixels[indx]-minValue;
								if (p>0.0) { // with mask mis-match there could be negative total mask
									S0+=p;
									SX+=p*x;
									SY+=p*y;
								}
							}
						}
					}
					double [] result={SX/S0,SY/S0};
					return result;
				}

Andrey Filippov's avatar
Andrey Filippov committed
4432
		/* ======================================================================== */
Andrey Filippov's avatar
Andrey Filippov committed
4433 4434 4435
		private double [] binPSF(double [] pixels,
				double [][] g,
				int outSize,
4436
				//		int      decimate,     // sub-pixel decimation
Andrey Filippov's avatar
Andrey Filippov committed
4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458
				double minContrast,
				double [] centerXY,    // coordinates (x,y) of the center point (will be alway subtracted)
				double[] symmXY,       // coordinates (x,y) of the center of symmetry (to combine with 180 if enabled by symm180)
				int pass,              // mostly for debug purposes
				String title,
				boolean debug,
				int globalDebugLevel) {
			int multiple=2;         // 0 - use each pixel once, 1 - add first negatives (4), 2 - second positives()4)
			int pixelSize=(int) Math.sqrt(pixels.length);
			int halfOutSize=outSize/2;
			int indx,i,j,outIndex,ix,iy;
			double x,y,xc,yc,uc,vc,u,v,p,q,d, du, dv, dp,dq, xr,yr, overThreshold;
			int np,nq;
			int PSF_sign=1;
			double [] contrastCache=new double[pixelSize*pixelSize];
			double [] debugPixels=null;
			if (debug)  debugPixels=new double[pixelSize*pixelSize];

			double det_g=g[0][0]*g[1][1]-g[0][1]*g[1][0];
			double [][] xy2uv= {{-2.0*g[0][1]/det_g,  2.0*g[0][0]/det_g},
					{-2.0*g[1][1]/det_g,  2.0*g[1][0]/det_g}};
			double [][] uv2xy= matrix2x2_scale(matrix2x2_invert(xy2uv),2); // real pixels are twice
4459
			double [] pixelsPSF       =new double [outSize*outSize];
Andrey Filippov's avatar
Andrey Filippov committed
4460
			int    [] pixelsPSFCount  =new int    [outSize*outSize];
4461
			double [] pixelsPSFWeight =new double [outSize*outSize];
Andrey Filippov's avatar
Andrey Filippov committed
4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495
			double [] center=centerXY;
			for (i=0;i<contrastCache.length;i++) {
				contrastCache[i]=-1.0;
			}
			double threshold=minContrast*contrastAtXY(1, pixels, pixelSize, 0.0, 0.0,  g, contrastCache);
			if (debug)  {
				System.out.println("binPSF title="+title+" g[0][0]="+IJ.d2s(g[0][0],4)+" g[0][1]="+IJ.d2s(g[0][1],4));
				System.out.println("binPSF title="+title+" g[1][0]="+IJ.d2s(g[1][0],4)+" g[1][1]="+IJ.d2s(g[1][1],4));
				System.out.println("  center[0]="+center[0]+"  center[1]="+center[1]);
				//		System.out.println("  decimate="+decimate+"  threshold="+threshold);
				System.out.println("  threshold="+threshold);
			}

			if (center==null) {
				center = new double[2];
				center[0]=0.0;
				center[1]=0.0;
			}
			for (i=0;i<pixelsPSF.length;i++) {
				pixelsPSF[i]=0.0;
				pixelsPSFCount[i]=0;
				pixelsPSFWeight[i]=0.0;
			}

			for (indx=0;indx<pixels.length;indx++) {
				y= indx / pixelSize- pixelSize/2;
				x= indx % pixelSize- pixelSize/2;
				u= xy2uv[0][0]*x + xy2uv[0][1]*y;
				v= xy2uv[1][0]*x + xy2uv[1][1]*y;
				p=u+v;
				q=u-v;
				np=(int)Math.floor((1+p)/2);
				nq=(int)Math.floor((1+q)/2);
				//if (debug)  debugPixels[indx]=(int)Math.floor((1+q)/2);
Andrey Filippov's avatar
Andrey Filippov committed
4496
	/* see if the point is in the cell of positive or negative OTF instance */
Andrey Filippov's avatar
Andrey Filippov committed
4497
				PSF_sign= (((np + nq) & 1)==0)?1:-1;
Andrey Filippov's avatar
Andrey Filippov committed
4498
	/* find x,y coordinates of the center of the cell */
Andrey Filippov's avatar
Andrey Filippov committed
4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509
				uc=0.5*(np+nq);
				vc=0.5*(np-nq);
				//xc=g[0][0]*uc + g[1][0]*vc;
				//yc=g[0][1]*uc + g[1][1]*vc;

				yc=-g[0][0]*uc - g[1][0]*vc;
				xc= g[0][1]*uc + g[1][1]*vc;


				//if (debug) debugPixels[indx]=p/2-Math.round(p/2);

Andrey Filippov's avatar
Andrey Filippov committed
4510
	/* See if this cell has enough contrast */
Andrey Filippov's avatar
Andrey Filippov committed
4511 4512 4513 4514 4515 4516 4517 4518
				overThreshold=contrastAtXY(PSF_sign,pixels, pixelSize, xc,yc,  g, contrastCache);
				//if (debug) debugPixels[indx]=overThreshold;
				if (overThreshold<threshold) {
					if (debug) debugPixels[indx]=0.0;
					//if (debug) debugPixels[indx]=yc;
				} else {
					//if (debug) debugPixels[indx]=yc;

Andrey Filippov's avatar
Andrey Filippov committed
4519
	/* Do binning itself here */
Andrey Filippov's avatar
Andrey Filippov committed
4520 4521
					d=PSF_sign*PSFAtXY(pixels, pixelSize, x,y);

4522
	/* map to the segment around 0,0 */
Andrey Filippov's avatar
Andrey Filippov committed
4523 4524
					dp=p/2-Math.round(p/2);
					dq=q/2-Math.round(q/2);
Andrey Filippov's avatar
Andrey Filippov committed
4525
	/* dp, dq are between +/- 0.5 - use them for Hamming windowing -NOT HERE, moved later*/
Andrey Filippov's avatar
Andrey Filippov committed
4526 4527 4528
					du=(dp+dq)/2;
					dv=(dp-dq)/2;

Andrey Filippov's avatar
Andrey Filippov committed
4529
	/* bin this point to the center and some (positive) duplicates if enabled */
Andrey Filippov's avatar
Andrey Filippov committed
4530 4531 4532 4533 4534
					for (i=-(multiple/2); i<=(multiple/2); i++) for (j=-(multiple/2); j<=(multiple/2); j++) {
						xr= uv2xy[0][0]*(j+du) + uv2xy[0][1]*(i+dv);
						yr= uv2xy[1][0]*(j+du) + uv2xy[1][1]*(i+dv);
						xr= Math.round(xr-center[0]);
						yr= Math.round(yr-center[1]);
Andrey Filippov's avatar
Andrey Filippov committed
4535
	/* does it fit into output array ? */
Andrey Filippov's avatar
Andrey Filippov committed
4536 4537 4538 4539 4540 4541 4542
						if ((yr>=-halfOutSize) && (yr<halfOutSize) && (xr>=-halfOutSize) && (xr<halfOutSize)) {
							outIndex=outSize*(outSize/2+ ((int) yr))+(outSize/2)+((int) xr);
							pixelsPSFCount[outIndex]++;
							pixelsPSF[outIndex]+=d*overThreshold;
							pixelsPSFWeight[outIndex]+=overThreshold;
						}
					}
Andrey Filippov's avatar
Andrey Filippov committed
4543
	/* bin this to center-symmetrical point if enabled */
Andrey Filippov's avatar
Andrey Filippov committed
4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558
					if (symmXY!=null) {
						for (i=-(multiple/2); i<=(multiple/2); i++) for (j=-(multiple/2); j<=(multiple/2); j++) {
							xr= uv2xy[0][0]*(j+du) + uv2xy[0][1]*(i+dv);
							yr= uv2xy[1][0]*(j+du) + uv2xy[1][1]*(i+dv);
							xr= Math.round(symmXY[0]*2.0-xr-center[0]);
							yr= Math.round(symmXY[1]*2.0-yr-center[1]);
							//does it fit into output array ?
							if ((yr>=-halfOutSize) && (yr<halfOutSize) && (xr>=-halfOutSize) && (xr<halfOutSize)) {
								outIndex=outSize*(outSize/2+ ((int) yr))+(outSize/2)+((int) xr);
								pixelsPSFCount[outIndex]++;
								pixelsPSF[outIndex]+=d*overThreshold;
								pixelsPSFWeight[outIndex]+=overThreshold;
							}
						}
					}
Andrey Filippov's avatar
Andrey Filippov committed
4559
	/* Now bin this point to the negative duplicates if enabled (debug feature). Normally it will be skipped */
Andrey Filippov's avatar
Andrey Filippov committed
4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572
					if (multiple>0) for (i=-((multiple+1)/2); i<((multiple+1)/2); i++) for (j=-((multiple+1)/2); j<((multiple+1)/2); j++) {
						xr= uv2xy[0][0]*(j+du+0.5) + uv2xy[0][1]*(i+dv+0.5);
						yr= uv2xy[1][0]*(j+du+0.5) + uv2xy[1][1]*(i+dv+0.5);
						xr= Math.round(xr-center[0]);
						yr= Math.round(yr-center[1]);
						//does it fit into output array ?
						if ((yr>=-halfOutSize) && (yr<halfOutSize) && (xr>=-halfOutSize) && (xr<halfOutSize)) {
							outIndex=outSize*(outSize/2+ ((int) yr))+(outSize/2)+((int) xr);
							pixelsPSFCount[outIndex]++;
							pixelsPSF[outIndex]-=d*overThreshold;
							pixelsPSFWeight[outIndex]+=overThreshold;
						}
					}
Andrey Filippov's avatar
Andrey Filippov committed
4573 4574
	/* bin this to center-symmetrical point if enabled */
	/* Now bin this point to the negative duplicates if enabled (debug feature). Normally it will be skipped */
Andrey Filippov's avatar
Andrey Filippov committed
4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596
					if (symmXY!=null) {
						if (multiple>0) for (i=-((multiple+1)/2); i<((multiple+1)/2); i++) for (j=-((multiple+1)/2); j<((multiple+1)/2); j++) {
							xr= uv2xy[0][0]*(j+du+0.5) + uv2xy[0][1]*(i+dv+0.5);
							yr= uv2xy[1][0]*(j+du+0.5) + uv2xy[1][1]*(i+dv+0.5);
							xr= Math.round(symmXY[0]*2.0-xr-center[0]);
							yr= Math.round(symmXY[1]*2.0-yr-center[1]);
							//does it fit into output array ?
							if ((yr>=-halfOutSize) && (yr<halfOutSize) && (xr>=-halfOutSize) && (xr<halfOutSize)) {
								outIndex=outSize*(outSize/2+ ((int) yr))+(outSize/2)+((int) xr);
								pixelsPSFCount[outIndex]++;
								pixelsPSF[outIndex]+=d*overThreshold;
								pixelsPSFWeight[outIndex]+=overThreshold;
							}
						}
					}
				}
			}


			for (i=0;i<pixelsPSF.length;i++) {
				if (pixelsPSFWeight[i]>0.0) pixelsPSF[i]/=pixelsPSFWeight[i];
			}
Andrey Filippov's avatar
Andrey Filippov committed
4597
	/* Interpolate  missing points (pixelsPSFCount[i]==0) */
Andrey Filippov's avatar
Andrey Filippov committed
4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615

			for (i=0;i<pixelsPSF.length;i++) if (pixelsPSFWeight[i]==0.0){
				iy=i/outSize;
				ix=i%outSize;
				if ((ix>0)&&(ix<(outSize-1))&&(iy>0)&&(iy<(outSize-1))) {
					if ((pixelsPSFWeight[(iy-1)*outSize+ix  ]>0.0) &&
							(pixelsPSFWeight[(iy+1)*outSize+ix  ]>0.0) &&
							(pixelsPSFWeight[(iy  )*outSize+ix-1]>0.0) &&
							(pixelsPSFWeight[(iy  )*outSize+ix+1]>0.0)) {
						if (globalDebugLevel>5) System.out.println("Interpolating missing OTF point at x="+ix+" y="+iy);
						pixelsPSF[i]=
							0.25*(pixelsPSF[(iy-1)*outSize+ix  ]+
									pixelsPSF[(iy+1)*outSize+ix  ]+
									pixelsPSF[(iy  )*outSize+ix-1]+
									pixelsPSF[(iy  )*outSize+ix+1]);
					}
				}
			}
Andrey Filippov's avatar
Andrey Filippov committed
4616
	/* optionally show original array with masked out low-contrast cells */
Andrey Filippov's avatar
Andrey Filippov committed
4617 4618 4619 4620
			if ((globalDebugLevel>2) && (pass==1))  SDFA_INSTANCE.showArrays(pixelsPSF, title+"_Used-PSF");
			if (debug) {
				SDFA_INSTANCE.showArrays(debugPixels, title+"_mask_PSF");
				double [] doublePixelsPSFCount=new double [pixelsPSF.length];
4621
				for (j=0;j<doublePixelsPSFCount.length;j++) doublePixelsPSFCount[j]=pixelsPSFCount[j];
Andrey Filippov's avatar
Andrey Filippov committed
4622 4623 4624
				SDFA_INSTANCE.showArrays(doublePixelsPSFCount, title+"_PSF_bin_count");
				SDFA_INSTANCE.showArrays(pixelsPSFWeight,      title+"_PSF_bin_weight");
				double [] doubleContrastCache=new double [contrastCache.length];
4625
				for (j=0;j<doubleContrastCache.length;j++) doubleContrastCache[j]=(contrastCache[j]>=0.0)?contrastCache[j]:-0.00001;
Andrey Filippov's avatar
Andrey Filippov committed
4626 4627 4628 4629 4630
				SDFA_INSTANCE.showArrays(doubleContrastCache,  title+"_ContrastCache");
			}
			return pixelsPSF;
		}

4631 4632 4633 4634




Andrey Filippov's avatar
Andrey Filippov committed
4635 4636
	/* ======================================================================== */
	/* Create a Thread[] array as large as the number of processors available.
Andrey Filippov's avatar
Andrey Filippov committed
4637 4638 4639 4640 4641 4642 4643 4644
		 * From Stephan Preibisch's Multithreading.java class. See:
		 * http://repo.or.cz/w/trakem2.git?a=blob;f=mpi/fruitfly/general/MultiThreading.java;hb=HEAD
		 */
		private Thread[] newThreadArray(int maxCPUs) {
			int n_cpus = Runtime.getRuntime().availableProcessors();
			if (n_cpus>maxCPUs)n_cpus=maxCPUs;
			return new Thread[n_cpus];
		}
Andrey Filippov's avatar
Andrey Filippov committed
4645
	/* Start all given threads and wait on each of them until all are done.
Andrey Filippov's avatar
Andrey Filippov committed
4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657
		 * From Stephan Preibisch's Multithreading.java class. See:
		 * http://repo.or.cz/w/trakem2.git?a=blob;f=mpi/fruitfly/general/MultiThreading.java;hb=HEAD
		 */
		public static void startAndJoin(Thread[] threads)
		{
			for (int ithread = 0; ithread < threads.length; ++ithread)
			{
				threads[ithread].setPriority(Thread.NORM_PRIORITY);
				threads[ithread].start();
			}

			try
4658
			{
Andrey Filippov's avatar
Andrey Filippov committed
4659 4660 4661 4662 4663 4664 4665
				for (int ithread = 0; ithread < threads.length; ++ithread)
					threads[ithread].join();
			} catch (InterruptedException ie)
			{
				throw new RuntimeException(ie);
			}
		}
Andrey Filippov's avatar
Andrey Filippov committed
4666
		/* === Parameter classes === */
Andrey Filippov's avatar
Andrey Filippov committed
4667 4668 4669 4670 4671 4672 4673 4674
		public static class MultiFilePSF {
			public double  overexposedMaxFraction; // allowed fraction of the overexposed pixels in the PSF kernel measurement area
			public double  weightOnBorder=0.5;
			public double  radiusDiffLow= 0.1; // do not remove partial kernel cell if radius differs from average less than by this fraction
			public double  radiusDiffHigh=0.25;  // remove this cell even if it is the only one
			public double  shiftToRadiusContrib=1.0; // Center shift (in pixels) addition to the difference relative to radius difference (in pixels)
			public double  sharpBonusPower=2.0; // increase weight of the "sharp" kernels by dividing weight by radius to this power
			public double  maxFracDiscardWorse=0.1; // discard up to this fraction of samples that have larger radius (i.e. falling on the target seam that may only make PSF larger)
4675
			public double  maxFracDiscardAll=0.5; // continue removing outliers (combined radius and shift), removing not more that this fraction (including maxFracDiscardWorse)
Andrey Filippov's avatar
Andrey Filippov committed
4676 4677 4678 4679 4680 4681 4682
			public double  internalBonus=1.0;    // cell having 8 around will "seem" twice better than having none (radiusDiff* twice higher)
			public double  validateThreshold;      // fraction of full PSF "energy"
			public boolean validateShowEllipse;    // show ellipse parameters of partial PSF arrays
			public boolean showWeights;            // show image indicating frame coverage
			public boolean fillMissing;            // replace missing kernels with neighbors
			public MultiFilePSF (
					double  overexposedMaxFraction,
4683
					double  weightOnBorder,
Andrey Filippov's avatar
Andrey Filippov committed
4684 4685 4686 4687 4688
					double  radiusDiffLow, // do not remove partial kernel cell if radius differs from average less than by this fraction
					double  radiusDiffHigh,  // remove this cell even if it is the only one
					double  shiftToRadiusContrib, // Center shift (in pixels) addition to the difference relative to radius difference (in pixels)
					double  sharpBonusPower, // increase weight of the "sharp" kernels by dividing weight by radius to this power
					double  maxFracDiscardWorse, // discard up to this fraction of samples that have larger radius (i.e. falling on the target seam that may only make PSF larger)
4689
					double  maxFracDiscardAll,  // continue removing outliers (combined radius and shift), removing not more that this fraction (including maxFracDiscardWorse)
Andrey Filippov's avatar
Andrey Filippov committed
4690 4691 4692 4693 4694 4695 4696
					double  internalBonus,
					double  validateThreshold,
					boolean validateShowEllipse,
					boolean showWeights,
					boolean fillMissing
			) {
				this.overexposedMaxFraction=overexposedMaxFraction;
4697
				this.weightOnBorder=weightOnBorder;
Andrey Filippov's avatar
Andrey Filippov committed
4698 4699 4700 4701 4702
				this.radiusDiffLow=radiusDiffLow; // do not remove partial kernel cell if radius differs from average less than by this fraction
				this.radiusDiffHigh=radiusDiffHigh;  // remove this cell even if it is the only one
				this.shiftToRadiusContrib=shiftToRadiusContrib; // Center shift (in pixels) addition to the difference relative to radius difference (in pixels)
				this.sharpBonusPower=sharpBonusPower; // increase weight of the "sharp" kernels by dividing weight by radius to this power
				this.maxFracDiscardWorse=maxFracDiscardWorse; // discard up to this fraction of samples that have larger radius (i.e. falling on the target seam that may only make PSF larger)
4703
				this.maxFracDiscardAll=maxFracDiscardAll; // continue removing outliers (combined radius and shift), removing not more that this fraction (including maxFracDiscardWorse)
Andrey Filippov's avatar
Andrey Filippov committed
4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741
				this.internalBonus=internalBonus;
				this.validateThreshold=validateThreshold;
				this.validateShowEllipse=validateShowEllipse;
				this.showWeights=showWeights;
				this.fillMissing=fillMissing;
			}

			public void setProperties(String prefix,Properties properties){
				properties.setProperty(prefix+"overexposedMaxFraction",this.overexposedMaxFraction+"");
				properties.setProperty(prefix+"weightOnBorder",this.weightOnBorder+"");
				properties.setProperty(prefix+"radiusDiffLow",this.radiusDiffLow+"");
				properties.setProperty(prefix+"radiusDiffHigh",this.radiusDiffHigh+"");
				properties.setProperty(prefix+"shiftToRadiusContrib",this.shiftToRadiusContrib+"");
				properties.setProperty(prefix+"sharpBonusPower",this.sharpBonusPower+"");
				properties.setProperty(prefix+"maxFracDiscardWorse",this.maxFracDiscardWorse+"");
				properties.setProperty(prefix+"maxFracDiscardAll",this.maxFracDiscardAll+"");
				properties.setProperty(prefix+"internalBonus",this.internalBonus+"");
				properties.setProperty(prefix+"validateThreshold",this.validateThreshold+"");
				properties.setProperty(prefix+"validateShowEllipse",this.validateShowEllipse+"");
				properties.setProperty(prefix+"showWeights",this.showWeights+"");
				properties.setProperty(prefix+"fillMissing",this.fillMissing+"");
			}

			public void setProperties(String prefix,ImagePlus properties){
				properties.setProperty(prefix+"overexposedMaxFraction",this.overexposedMaxFraction+"");
				properties.setProperty(prefix+"weightOnBorder",this.weightOnBorder+"");
				properties.setProperty(prefix+"radiusDiffLow",this.radiusDiffLow+"");
				properties.setProperty(prefix+"radiusDiffHigh",this.radiusDiffHigh+"");
				properties.setProperty(prefix+"shiftToRadiusContrib",this.shiftToRadiusContrib+"");
				properties.setProperty(prefix+"sharpBonusPower",this.sharpBonusPower+"");
				properties.setProperty(prefix+"maxFracDiscardWorse",this.maxFracDiscardWorse+"");
				properties.setProperty(prefix+"maxFracDiscardAll",this.maxFracDiscardAll+"");
				properties.setProperty(prefix+"internalBonus",this.internalBonus+"");
				properties.setProperty(prefix+"validateThreshold",this.validateThreshold+"");
				properties.setProperty(prefix+"validateShowEllipse",this.validateShowEllipse+"");
				properties.setProperty(prefix+"showWeights",this.showWeights+"");
				properties.setProperty(prefix+"fillMissing",this.fillMissing+"");
			}
4742

Andrey Filippov's avatar
Andrey Filippov committed
4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760
			public void getProperties(String prefix,Properties properties){
				if (properties.getProperty(prefix+"overexposedMaxFraction")!=null) this.overexposedMaxFraction=Double.parseDouble(properties.getProperty(prefix+"overexposedMaxFraction"));
				if (properties.getProperty(prefix+"weightOnBorder")!=null) this.weightOnBorder=Double.parseDouble(properties.getProperty(prefix+"weightOnBorder"));
				if (properties.getProperty(prefix+"radiusDiffLow")!=null) this.radiusDiffLow=Double.parseDouble(properties.getProperty(prefix+"radiusDiffLow"));
				if (properties.getProperty(prefix+"radiusDiffHigh")!=null) this.radiusDiffHigh=Double.parseDouble(properties.getProperty(prefix+"radiusDiffHigh"));
				if (properties.getProperty(prefix+"shiftToRadiusContrib")!=null)
					this.shiftToRadiusContrib=Double.parseDouble(properties.getProperty(prefix+"shiftToRadiusContrib"));
				if (properties.getProperty(prefix+"sharpBonusPower")!=null)
					this.sharpBonusPower=Double.parseDouble(properties.getProperty(prefix+"sharpBonusPower"));
				if (properties.getProperty(prefix+"maxFracDiscardWorse")!=null)
					this.maxFracDiscardWorse=Double.parseDouble(properties.getProperty(prefix+"maxFracDiscardWorse"));
				if (properties.getProperty(prefix+"maxFracDiscardAll")!=null)
					this.maxFracDiscardAll=Double.parseDouble(properties.getProperty(prefix+"maxFracDiscardAll"));
				if (properties.getProperty(prefix+"internalBonus")!=null) this.internalBonus=Double.parseDouble(properties.getProperty(prefix+"internalBonus"));
				if (properties.getProperty(prefix+"validateThreshold")!=null)this.validateThreshold=Double.parseDouble(properties.getProperty(prefix+"validateThreshold"));
				if (properties.getProperty(prefix+"validateShowEllipse")!=null)this.validateShowEllipse=Boolean.parseBoolean(properties.getProperty(prefix+"validateShowEllipse"));
				if (properties.getProperty(prefix+"showWeights")!=null)this.showWeights=Boolean.parseBoolean(properties.getProperty(prefix+"showWeights"));
				if (properties.getProperty(prefix+"fillMissing")!=null)this.fillMissing=Boolean.parseBoolean(properties.getProperty(prefix+"fillMissing"));
4761

Andrey Filippov's avatar
Andrey Filippov committed
4762 4763 4764 4765 4766 4767 4768 4769 4770
			}

		}

    public static class AberrationParameters{
    	public String sourceDirectory="";
    	public String partialKernelDirectory="";
    	public String psfKernelDirectory="";
    	public String aberrationsKernelDirectory="";
4771
    	public String calibrationDirectory="";
Andrey Filippov's avatar
Andrey Filippov committed
4772 4773 4774 4775 4776
    	public boolean autoRestore;
    	public String calibrationPath="";
    	public String strategyPath="";
    	public String gridPath="";
    	public String sensorsPath="";
4777 4778
    	public boolean autoRestoreSensorOverwriteOrientation=false; // dangerous! true; // overwrite camera parameters from sensor calibration files
    	public boolean autoRestoreSensorOverwriteDistortion= false; // dangerous! true; // overwrite camera parameters from sensor calibration files
Andrey Filippov's avatar
Andrey Filippov committed
4779 4780
		public boolean autoReCalibrate=true; // Re-calibrate grids on autoload
		public boolean autoReCalibrateIgnoreLaser=false; // "Ignore laser pointers on recalibrate"
4781 4782
    	public boolean autoFilter=false; // true;
    	public boolean trustEnabled= true; // mark all enabled images as hintedMatch=2 on Read Calibration
Andrey Filippov's avatar
Andrey Filippov committed
4783 4784
    	public boolean noMessageBoxes=true;
    	public boolean overwriteResultFiles=false;
4785
    	public boolean partialToReprojected=true; // Use reprojected grid for partial kernel calculation (false - use extracted)
4786
    	public boolean partialCorrectSensor=true; // Apply sensor correction to the projected grid
Andrey Filippov's avatar
Andrey Filippov committed
4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799
    	public int     seriesNumber=0;
    	public boolean allImages;
    	public String sourcePrefix="";
    	public String sourceSuffix=".tiff";
    	public String partialPrefix="partial-";
    	public String partialSuffix=".ppsf-tiff";
    	public String psfPrefix="direct-psf-";
    	public String psfSuffix=".psf-tiff";
    	public String interpolatedPSFPrefix="interpolated-psf-";
    	public String interpolatedPSFSuffix=".ipsf-tiff";
    	public String aberrationsPrefix="kernel-";
    	public String aberrationsSuffix=".kernel-tiff";
    	public boolean [] selectedChannels=null;
4800 4801 4802



Andrey Filippov's avatar
Andrey Filippov committed
4803 4804 4805 4806 4807
		public void setProperties(String prefix,Properties properties){
			properties.setProperty(prefix+"sourceDirectory",this.sourceDirectory);
			properties.setProperty(prefix+"partialKernelDirectory",this.partialKernelDirectory);
			properties.setProperty(prefix+"psfKernelDirectory",this.psfKernelDirectory);
			properties.setProperty(prefix+"aberrationsKernelDirectory",this.aberrationsKernelDirectory);
4808
			properties.setProperty(prefix+"calibrationDirectory",this.calibrationDirectory);
4809

Andrey Filippov's avatar
Andrey Filippov committed
4810 4811 4812 4813 4814 4815
			properties.setProperty(prefix+"autoRestore",this.autoRestore+"");
			properties.setProperty(prefix+"calibrationPath",this.calibrationPath);
			properties.setProperty(prefix+"strategyPath",this.strategyPath);
			properties.setProperty(prefix+"gridPath",this.gridPath);
			properties.setProperty(prefix+"sensorsPath",this.sensorsPath);
			properties.setProperty(prefix+"autoRestoreSensorOverwriteOrientation",this.autoRestoreSensorOverwriteOrientation+"");
4816
			properties.setProperty(prefix+"autoRestoreSensorOverwriteDistortion",this.autoRestoreSensorOverwriteDistortion+"");
Andrey Filippov's avatar
Andrey Filippov committed
4817 4818
			properties.setProperty(prefix+"autoReCalibrate",this.autoReCalibrate+"");
			properties.setProperty(prefix+"autoReCalibrateIgnoreLaser",this.autoReCalibrateIgnoreLaser+"");
4819
			properties.setProperty(prefix+"autoFilter",this.autoFilter+"");
4820
			properties.setProperty(prefix+"trustEnabled",this.trustEnabled+"");
Andrey Filippov's avatar
Andrey Filippov committed
4821 4822
			properties.setProperty(prefix+"noMessageBoxes",this.noMessageBoxes+"");
			properties.setProperty(prefix+"overwriteResultFiles",this.overwriteResultFiles+"");
4823
			properties.setProperty(prefix+"partialToReprojected",this.partialToReprojected+"");
4824
			properties.setProperty(prefix+"partialCorrectSensor",this.partialCorrectSensor+"");
4825 4826


Andrey Filippov's avatar
Andrey Filippov committed
4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845
			properties.setProperty(prefix+"seriesNumber",this.seriesNumber+"");
			properties.setProperty(prefix+"allImages",this.allImages+"");

			properties.setProperty(prefix+"sourcePrefix",this.sourcePrefix);
			properties.setProperty(prefix+"sourceSuffix",this.sourceSuffix);
			properties.setProperty(prefix+"partialPrefix",this.partialPrefix);
			properties.setProperty(prefix+"partialSuffix",this.partialSuffix);
			properties.setProperty(prefix+"psfPrefix",this.psfPrefix);
			properties.setProperty(prefix+"psfSuffix",this.psfSuffix);
			properties.setProperty(prefix+"interpolatedPSFPrefix",this.interpolatedPSFPrefix);
			properties.setProperty(prefix+"interpolatedPSFSuffix",this.interpolatedPSFSuffix);
			properties.setProperty(prefix+"aberrationsPrefix",this.aberrationsPrefix);
			properties.setProperty(prefix+"aberrationsSuffix",this.aberrationsSuffix);
			if (this.selectedChannels!=null){
				String sSelectedChannels="";
				for (int i=0;i<this.selectedChannels.length;i++) sSelectedChannels+= selectedChannels[i]?"+":"-";
				properties.setProperty(prefix+"selectedChannels",sSelectedChannels);
			}

4846

Andrey Filippov's avatar
Andrey Filippov committed
4847 4848 4849 4850 4851 4852
		}
		public void getProperties(String prefix,Properties properties){
			if (properties.getProperty(prefix+"sourceDirectory")!=null)	           this.sourceDirectory=properties.getProperty(prefix+"sourceDirectory");
			if (properties.getProperty(prefix+"partialKernelDirectory")!=null)     this.partialKernelDirectory=properties.getProperty(prefix+"partialKernelDirectory");
			if (properties.getProperty(prefix+"psfKernelDirectory")!=null)         this.psfKernelDirectory=properties.getProperty(prefix+"psfKernelDirectory");
			if (properties.getProperty(prefix+"aberrationsKernelDirectory")!=null) this.aberrationsKernelDirectory=properties.getProperty(prefix+"aberrationsKernelDirectory");
4853
			if (properties.getProperty(prefix+"calibrationDirectory")!=null)       this.calibrationDirectory=properties.getProperty(prefix+"calibrationDirectory");
4854

Andrey Filippov's avatar
Andrey Filippov committed
4855 4856 4857 4858 4859 4860 4861
			if (properties.getProperty(prefix+"autoRestore")!=null)                this.autoRestore=Boolean.parseBoolean(properties.getProperty(prefix+"autoRestore"));
			if (properties.getProperty(prefix+"calibrationPath")!=null)            this.calibrationPath=properties.getProperty(prefix+"calibrationPath");
			if (properties.getProperty(prefix+"strategyPath")!=null)               this.strategyPath=properties.getProperty(prefix+"strategyPath");
			if (properties.getProperty(prefix+"gridPath")!=null)                   this.gridPath=properties.getProperty(prefix+"gridPath");
			if (properties.getProperty(prefix+"sensorsPath")!=null)                this.sensorsPath=properties.getProperty(prefix+"sensorsPath");
			if (properties.getProperty(prefix+"autoRestoreSensorOverwriteOrientation")!=null)
				this.autoRestoreSensorOverwriteOrientation=Boolean.parseBoolean(properties.getProperty(prefix+"autoRestoreSensorOverwriteOrientation"));
4862 4863
			if (properties.getProperty(prefix+"autoRestoreSensorOverwriteDistortion")!=null)
				this.autoRestoreSensorOverwriteDistortion=Boolean.parseBoolean(properties.getProperty(prefix+"autoRestoreSensorOverwriteDistortion"));
4864

Andrey Filippov's avatar
Andrey Filippov committed
4865 4866
			if (properties.getProperty(prefix+"autoReCalibrate")!=null)            this.autoReCalibrate=Boolean.parseBoolean(properties.getProperty(prefix+"autoReCalibrate"));
			if (properties.getProperty(prefix+"autoReCalibrateIgnoreLaser")!=null) this.autoReCalibrateIgnoreLaser=Boolean.parseBoolean(properties.getProperty(prefix+"autoReCalibrateIgnoreLaser"));
4867
			if (properties.getProperty(prefix+"autoFilter")!=null)                 this.autoFilter=Boolean.parseBoolean(properties.getProperty(prefix+"autoFilter"));
4868
			if (properties.getProperty(prefix+"trustEnabled")!=null)               this.trustEnabled=Boolean.parseBoolean(properties.getProperty(prefix+"trustEnabled"));
Andrey Filippov's avatar
Andrey Filippov committed
4869 4870
			if (properties.getProperty(prefix+"noMessageBoxes")!=null)             this.noMessageBoxes=Boolean.parseBoolean(properties.getProperty(prefix+"noMessageBoxes"));
			if (properties.getProperty(prefix+"overwriteResultFiles")!=null)       this.overwriteResultFiles=Boolean.parseBoolean(properties.getProperty(prefix+"overwriteResultFiles"));
4871
			if (properties.getProperty(prefix+"partialToReprojected")!=null)       this.partialToReprojected=Boolean.parseBoolean(properties.getProperty(prefix+"partialToReprojected"));
4872
			if (properties.getProperty(prefix+"partialCorrectSensor")!=null)       this.partialCorrectSensor=Boolean.parseBoolean(properties.getProperty(prefix+"partialCorrectSensor"));
4873 4874


Andrey Filippov's avatar
Andrey Filippov committed
4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886
			if (properties.getProperty(prefix+"seriesNumber")!=null)               this.seriesNumber=Integer.parseInt(properties.getProperty(prefix+"seriesNumber"));
			if (properties.getProperty(prefix+"allImages")!=null)                  this.allImages=Boolean.parseBoolean(properties.getProperty(prefix+"allImages"));
			if (properties.getProperty(prefix+"sourcePrefix")!=null)	      this.sourcePrefix=properties.getProperty(prefix+"sourcePrefix");
			if (properties.getProperty(prefix+"sourceSuffix")!=null)	      this.sourceSuffix=properties.getProperty(prefix+"sourceSuffix");
			if (properties.getProperty(prefix+"partialPrefix")!=null)	      this.partialPrefix=properties.getProperty(prefix+"partialPrefix");
			if (properties.getProperty(prefix+"partialSuffix")!=null)         this.partialSuffix=properties.getProperty(prefix+"partialSuffix");
			if (properties.getProperty(prefix+"psfPrefix")!=null)	          this.psfPrefix=properties.getProperty(prefix+"psfPrefix");
			if (properties.getProperty(prefix+"psfSuffix")!=null)	          this.psfSuffix=properties.getProperty(prefix+"psfSuffix");
			if (properties.getProperty(prefix+"interpolatedPSFPrefix")!=null) this.interpolatedPSFPrefix=properties.getProperty(prefix+"interpolatedPSFPrefix");
			if (properties.getProperty(prefix+"interpolatedPSFSuffix")!=null) this.interpolatedPSFSuffix=properties.getProperty(prefix+"interpolatedPSFSuffix");
			if (properties.getProperty(prefix+"aberrationsPrefix")!=null)     this.aberrationsPrefix=properties.getProperty(prefix+"aberrationsPrefix");
			if (properties.getProperty(prefix+"aberrationsSuffix")!=null)     this.aberrationsSuffix=properties.getProperty(prefix+"aberrationsSuffix");
4887 4888


Andrey Filippov's avatar
Andrey Filippov committed
4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901
			if (properties.getProperty(prefix+"selectedChannels")!=null){
				String sSelectedChannels=properties.getProperty(prefix+"selectedChannels");
				this.selectedChannels=new boolean[sSelectedChannels.length()];
				for (int i=0;i<this.selectedChannels.length;i++) selectedChannels[i]= sSelectedChannels.charAt(i)=='+';
			}
		}
		/**
		 * calibration files paths
		 * @param distortions Distortion class instance
		 * @param combine when true - return the configured paths if current is not set, false - return null
		 *  for the paths that are not set or did not change from configured
		 * @return array of 4 paths
		 */
4902

Andrey Filippov's avatar
Andrey Filippov committed
4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918
		public String [] currentConfigPaths(Distortions distortions, boolean combine){
    		String currentCalibrationPath=null;
    		String currentStrategyPath=null;
    		String currentGridPath=null;
    		String currentSensorsPath=null;
    		if (distortions!=null) {
    			if (distortions.fittingStrategy!=null){
    				currentStrategyPath=distortions.fittingStrategy.pathName;
//        			System.out.println("currentConfigPaths():currentStrategyPath="+((currentStrategyPath==null)?"null":currentStrategyPath));
        			if (distortions.fittingStrategy.distortionCalibrationData!=null) {
        				currentCalibrationPath=distortions.fittingStrategy.distortionCalibrationData.pathName;
        			} else {
//            			System.out.println("currentConfigPaths():distortions.fittingStrategy.distortionCalibrationData==null");
        			}
    			} else {
//        			System.out.println("currentConfigPaths():distortions.fittingStrategy==null");
4919

Andrey Filippov's avatar
Andrey Filippov committed
4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953
    			}
    			currentGridPath=distortions.patternParameters.pathName;
//    			System.out.println("currentConfigPaths():currentGridPath="+((currentGridPath==null)?"null":currentGridPath));
    			currentSensorsPath=distortions.getSensorPath(-1);
//    			System.out.println("currentConfigPaths():currentSensorsPath="+((currentSensorsPath==null)?"null":currentSensorsPath));
    		} else {
    			System.out.println("currentConfigPaths():distortions==null");
    		}
    		if ((currentCalibrationPath==null) || (currentCalibrationPath.equals(this.calibrationPath)) || (currentCalibrationPath.length()==0))
    			currentCalibrationPath=combine?this.calibrationPath:null;
    		if ((currentStrategyPath==   null) || (currentStrategyPath.equals   (this.strategyPath))    || (currentStrategyPath.length()==0))
    			currentStrategyPath=combine?this.strategyPath:null;
    		if ((currentGridPath==       null) || (currentGridPath.equals       (this.gridPath))        || (currentGridPath.length()==0))
    			currentGridPath=combine?this.gridPath:null;
    		if ((currentSensorsPath==    null) || (currentSensorsPath.equals    (this.sensorsPath))     || (currentSensorsPath.length()==0))
    			currentSensorsPath=combine?this.sensorsPath:null;
    		String [] result={
    				currentCalibrationPath,
    				currentStrategyPath,
    				currentGridPath,
    				currentSensorsPath
    		};
			return result;
		}
		public String [] autoLoadPaths(){
    		String [] result={
    				this.calibrationPath,
    				this.strategyPath,
    				this.gridPath,
    				this.sensorsPath
    		};
			return result;
		}
		public boolean [] getChannelSelection(Distortions distortions){
4954 4955 4956
			if ((distortions==null) ||
					(distortions.fittingStrategy == null) ||
					(distortions.fittingStrategy.distortionCalibrationData == null)) return null;
Andrey Filippov's avatar
Andrey Filippov committed
4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969
		   	int numChannels=distortions.fittingStrategy.distortionCalibrationData.getNumChannels(); // number of used channels
    		if (this.selectedChannels==null) {
    			this.selectedChannels=new boolean[1];
    			this.selectedChannels[0]=true;
    		}
    		if (this.selectedChannels.length!=numChannels){
    			boolean [] tmp=this.selectedChannels;
    			this.selectedChannels=new boolean[numChannels];
    			for (int i=0;i<numChannels;i++){
    				this.selectedChannels[i]=(i<tmp.length)?tmp[i]:tmp[tmp.length-1];
    			}
    		}
    		return this.selectedChannels;
4970

Andrey Filippov's avatar
Andrey Filippov committed
4971 4972
		}
		public boolean selectChannelsToProcess(String title, Distortions distortions) {
4973
    		boolean [] newSelecttion=getChannelSelection(distortions); // .clone(); //java.lang.NullPointerException
Andrey Filippov's avatar
Andrey Filippov committed
4974
			if (newSelecttion==null) return false;
4975
			newSelecttion = newSelecttion.clone();
Andrey Filippov's avatar
Andrey Filippov committed
4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993
			int numChannels=newSelecttion.length;
    		while (true) {
    			GenericDialog gd = new GenericDialog(title);
    			for (int i=0;i<numChannels;i++) gd.addCheckbox("channel "+i, newSelecttion[i]);
    			gd.enableYesNoCancel("OK", "All like channel 0");
    			WindowTools.addScrollBars(gd);
    			gd.showDialog();
    			if (gd.wasCanceled()) return false;
    			for (int i=0;i<numChannels;i++) newSelecttion[i]=gd.getNextBoolean();
    			if (gd.wasOKed()){
    				for (int i=0;i<numChannels;i++) this.selectedChannels[i]=newSelecttion[i];
    				return true;
    			} else {
    				for (int i=1;i<numChannels;i++) newSelecttion[i]=newSelecttion[0];
    			}
    		}
		}

4994
    	public boolean showDialog(String title, Distortions distortions) {
Andrey Filippov's avatar
Andrey Filippov committed
4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006
    		String [] currentConfigs;
    		String []nulls={null,null,null,null};
    		currentConfigs=(distortions!=null)?currentConfigPaths(distortions, false):nulls;
    		GenericDialog gd = new GenericDialog(title);
    		gd.addStringField("Source files directory", this.sourceDirectory, 60);
    		gd.addCheckbox("Select source directory", false);
    		gd.addStringField("Partial kernels directory", this.partialKernelDirectory, 60);
    		gd.addCheckbox("Select partial kernels directory", false);
    		gd.addStringField("Combined kernels directory", this.psfKernelDirectory, 60);
    		gd.addCheckbox("Select combined kernsls directory", false);
    		gd.addStringField("Aberrations kernels directory", this.aberrationsKernelDirectory, 60);
    		gd.addCheckbox("Select aberrations kernels directory", false);
5007 5008
    		gd.addStringField("Calibration directory (sensor, grid, strategy...)", this.calibrationDirectory, 60);
    		gd.addCheckbox("Select calibration directory", false);
Andrey Filippov's avatar
Andrey Filippov committed
5009 5010
    		gd.addCheckbox("Supress non-essential message boxes", this.noMessageBoxes);
    		gd.addCheckbox("Overwrite result files if they exist", this.overwriteResultFiles);
5011
    		gd.addCheckbox("Use reprojected grids for partial kernel calculation (false - extracted grids)", this.partialToReprojected);
5012
    		gd.addCheckbox("Apply sensor correction during for partial kernel calculation", this.partialCorrectSensor);
5013

Andrey Filippov's avatar
Andrey Filippov committed
5014 5015 5016 5017
    		gd.addNumericField("Fitting series number to use for image selection", this.seriesNumber,0);
    		gd.addCheckbox("Process all enabled image files (false - use selected fitting series)", this.allImages);
    		gd.addMessage("===== Autoload options (when restoring configuration) =====");
    		gd.addCheckbox("Autoload additional files on \"Restore\"", this.autoRestore);
5018 5019
    		gd.addCheckbox("Overwrite all (including position/orientation) SFE parameters from the sensor calibration files (at auto-load) DANGEROUS!", this.autoRestoreSensorOverwriteOrientation);
    		gd.addCheckbox("Overwrite SFE distortion parameters from the sensor calibration files (at auto-load) DANGEROUS!", this.autoRestoreSensorOverwriteDistortion);
5020

Andrey Filippov's avatar
Andrey Filippov committed
5021 5022
    		gd.addCheckbox("Re-calibrate grids on autoload", this.autoReCalibrate);
    		gd.addCheckbox("Ignore laser pointers on recalibrate", this.autoReCalibrateIgnoreLaser);
5023
    		gd.addCheckbox("Filter grids after restore", this.autoFilter);
5024
    		gd.addCheckbox("Trust enabled images on input (mark as hintedGrid=2)", this.trustEnabled);
5025

Andrey Filippov's avatar
Andrey Filippov committed
5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045
    		gd.addMessage("Calibration: "+(((this.calibrationPath==null) || (this.calibrationPath.length()==0))?"not configured ":(this.calibrationPath+" "))+
    				((currentConfigs[0]!=null)?("(current: "+currentConfigs[0]+")"):("") ));
    		gd.addMessage("Strategy: "+(((this.strategyPath==null) || (this.strategyPath.length()==0))?"not configured ":(this.strategyPath+" "))+
    				((currentConfigs[1]!=null)?("(current: "+currentConfigs[1]+")"):("") ));
    		gd.addMessage("Pattern grid: "+(((this.gridPath==null) || (this.gridPath.length()==0))?"not configured ":(this.gridPath+" "))+
    				((currentConfigs[2]!=null)?("(current: "+currentConfigs[2]+")"):("") ));
    		gd.addMessage("Sensors(one of): "+(((this.sensorsPath==null) || (this.sensorsPath.length()==0))?"not configured ":(this.sensorsPath+" "))+
    				((currentConfigs[3]!=null)?("(current: "+currentConfigs[3]+")"):("") ));
    		gd.addCheckbox("Update configured (for auto-load) paths from current ones", false);
    		gd.addMessage("Filename prefixes/suffixes:");
    		gd.addStringField("Source files prefix",             this.sourcePrefix, 40);
    		gd.addStringField("Source files suffix",             this.sourceSuffix, 40);
    		gd.addStringField("Partial kernels prefix",          this.partialPrefix, 40);
    		gd.addStringField("Partial kernels suffix",          this.partialSuffix, 40);
    		gd.addStringField("Combined kernels prefix",         this.psfPrefix, 40);
    		gd.addStringField("Combined kernels suffix",         this.psfSuffix, 40);
    		gd.addStringField("Interpolated kernels prefix",     this.interpolatedPSFPrefix, 40);
    		gd.addStringField("Interpolated kernels suffix",     this.interpolatedPSFSuffix, 40);
    		gd.addStringField("Inverted (final) kernels prefix", this.aberrationsPrefix, 40);
    		gd.addStringField("Inverted (final) kernels suffix", this.aberrationsSuffix, 40);
5046

Andrey Filippov's avatar
Andrey Filippov committed
5047
    		gd.addCheckbox("Select channels to process", true);
5048

Andrey Filippov's avatar
Andrey Filippov committed
5049 5050 5051 5052
    		WindowTools.addScrollBars(gd);
    		gd.showDialog();
    		if (gd.wasCanceled()) return false;
    		this.sourceDirectory=       gd.getNextString();
5053
    		if (gd.getNextBoolean()) selectSourceDirectory(false, this.sourceDirectory, false);
Andrey Filippov's avatar
Andrey Filippov committed
5054
    		this.partialKernelDirectory=gd.getNextString();
5055
    		if (gd.getNextBoolean()) selectPartialKernelDirectory(false, this.partialKernelDirectory, false);
Andrey Filippov's avatar
Andrey Filippov committed
5056
    		this.psfKernelDirectory=gd.getNextString();
5057
    		if (gd.getNextBoolean()) selectPSFKernelDirectory(false, this.psfKernelDirectory, false);
Andrey Filippov's avatar
Andrey Filippov committed
5058 5059
    		this.aberrationsKernelDirectory=gd.getNextString();
    		if (gd.getNextBoolean()) selectAberrationsKernelDirectory(false, this.aberrationsKernelDirectory, false);
5060 5061
    		this.calibrationDirectory=gd.getNextString();
    		if (gd.getNextBoolean()) selectCalibrationDirectory(false, this.calibrationDirectory, false);
Andrey Filippov's avatar
Andrey Filippov committed
5062 5063
    		this.noMessageBoxes=        gd.getNextBoolean();
    		this.overwriteResultFiles=  gd.getNextBoolean();
5064
    		this.partialToReprojected=  gd.getNextBoolean();
5065
    		this.partialCorrectSensor=  gd.getNextBoolean();
Andrey Filippov's avatar
Andrey Filippov committed
5066 5067 5068 5069
    		this.seriesNumber=    (int) gd.getNextNumber();
    		this.allImages=             gd.getNextBoolean();
    		this.autoRestore=           gd.getNextBoolean();
    		this.autoRestoreSensorOverwriteOrientation= gd.getNextBoolean();
5070
    		this.autoRestoreSensorOverwriteDistortion= gd.getNextBoolean();
Andrey Filippov's avatar
Andrey Filippov committed
5071 5072
    		this.autoReCalibrate=           gd.getNextBoolean();
    		this.autoReCalibrateIgnoreLaser=gd.getNextBoolean();
5073
    		this.autoFilter=            gd.getNextBoolean();
5074
    		this.trustEnabled=          gd.getNextBoolean();
5075

Andrey Filippov's avatar
Andrey Filippov committed
5076 5077 5078 5079 5080 5081
    		if (gd.getNextBoolean()) {
    			if (currentConfigs[0]!=null) this.calibrationPath=currentConfigs[0];
    			if (currentConfigs[1]!=null) this.strategyPath=   currentConfigs[1];
    			if (currentConfigs[2]!=null) this.gridPath=       currentConfigs[2];
    			if (currentConfigs[3]!=null) this.sensorsPath=    currentConfigs[3];
    		}
5082

Andrey Filippov's avatar
Andrey Filippov committed
5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098
    		this.sourcePrefix=          gd.getNextString();
    		this.sourceSuffix=          gd.getNextString();
    		this.partialPrefix=         gd.getNextString();
    		this.partialSuffix=         gd.getNextString();
    		this.psfPrefix=             gd.getNextString();
    		this.psfSuffix=             gd.getNextString();
    		this.interpolatedPSFPrefix= gd.getNextString();
    		this.interpolatedPSFSuffix= gd.getNextString();
    		this.aberrationsPrefix=     gd.getNextString();
    		this.aberrationsSuffix=     gd.getNextString();
    		if (gd.getNextBoolean()) selectChannelsToProcess("Select channels to process", distortions);
    		return true;
    	}
    	public String selectSourceDirectory(boolean smart, String defaultPath, boolean newAllowed) { // normally newAllowed=false
    		String dir= CalibrationFileManagement.selectDirectory(
    				smart,
5099
    				newAllowed, // save
Andrey Filippov's avatar
Andrey Filippov committed
5100 5101 5102 5103 5104 5105 5106 5107 5108 5109
    				"Source (acquired from the camera) image directory", // title
    				"Select source directory", // button
    				null, // filter
    				defaultPath); // this.sourceDirectory);
    		if (dir!=null) this.sourceDirectory=dir;
    		return dir;
    	}
    	public String selectPartialKernelDirectory(boolean smart, String defaultPath, boolean newAllowed) {
    		String dir= CalibrationFileManagement.selectDirectory(
    				smart,
5110
    				newAllowed, // save
Andrey Filippov's avatar
Andrey Filippov committed
5111 5112 5113 5114 5115 5116 5117 5118 5119 5120
    				"Partial PSF directory", // title
    				"Select partial PSF files directory", // button
    				null, // filter
    				defaultPath); //this.sourceDirectory);
    		if (dir!=null) this.partialKernelDirectory=dir;
    		return dir;
    	}
    	public String selectPSFKernelDirectory(boolean smart, String defaultPath, boolean newAllowed) {
    		String dir= CalibrationFileManagement.selectDirectory(
    				smart,
5121
    				newAllowed, // save
Andrey Filippov's avatar
Andrey Filippov committed
5122 5123 5124 5125 5126 5127 5128 5129 5130 5131
    				"Combined direct PSF kernel directory", // title
    				"Select combined kernel directory", // button
    				null, // filter
    				defaultPath); //this.sourceDirectory);
    		if (dir!=null) this.psfKernelDirectory=dir;
    		return dir;
    	}
    	public String selectAberrationsKernelDirectory(boolean smart, String defaultPath, boolean newAllowed) {
    		String dir= CalibrationFileManagement.selectDirectory(
    				smart,
5132
    				newAllowed, // save
Andrey Filippov's avatar
Andrey Filippov committed
5133 5134 5135 5136 5137 5138 5139
    				"Aberrations kernel directory", // title
    				"Select aberrations kernel directory", // button
    				null, // filter
    				defaultPath); //this.sourceDirectory);
    		if (dir!=null) this.aberrationsKernelDirectory=dir;
    		return dir;
    	}
5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151
    	public String selectCalibrationDirectory(boolean smart, String defaultPath, boolean newAllowed) {
    		String dir= CalibrationFileManagement.selectDirectory(
    				smart,
    				newAllowed, // save
    				"Calibration directory", // title
    				"Select calibration directory", // button
    				null, // filter
    				defaultPath); //this.sourceDirectory);
    		if (dir!=null) this.calibrationDirectory=dir;
    		return dir;
    	}
//
5152

Andrey Filippov's avatar
Andrey Filippov committed
5153
    }
5154 5155 5156



Andrey Filippov's avatar
Andrey Filippov committed
5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170
	public static class ColorComponents {
		public boolean [] colorsToCorrect=    new boolean[6];
		public int        referenceComponent; // component to calculate lateral chromatic from (0 - G1, 1 - R, 2 - B, 3 - G2,4 - diagonal greens, 5 - checker greens)
		public boolean    equalizeGreens;   // equalize 2 greens in Bayer mosaic
		public static String [] componentColorNames={"green1","red","blue","green2", "greens (diagonal)", "greens (checker)"};
		public static String [] stackColorNames={"red","green","blue"};
		public String getColorName(int i) {return  componentColorNames[i];}
		public String getStackColorName(int i) {return  stackColorNames[i];}

		public ColorComponents (
				boolean green1,
				boolean red,
				boolean blue,
				boolean green2,
5171
				boolean diagonal, // both greens combined in a 45-degree rotated array
Andrey Filippov's avatar
Andrey Filippov committed
5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225
				boolean checker,   // both greens combined in a checkerboard pattern
				int        referenceComponent,
				boolean    equalizeGreens
		) {
			this.colorsToCorrect[0]=green1;
			this.colorsToCorrect[1]=red;
			this.colorsToCorrect[2]=blue;
			this.colorsToCorrect[3]=green2;
			this.colorsToCorrect[4]=diagonal;
			this.colorsToCorrect[5]=checker;
			this.referenceComponent=referenceComponent;
			this.equalizeGreens=equalizeGreens;
		}
		public void setProperties(String prefix,Properties properties){
			properties.setProperty(prefix+"green1",this.colorsToCorrect[0]+"");
			properties.setProperty(prefix+"red",this.colorsToCorrect[1]+"");
			properties.setProperty(prefix+"blue",this.colorsToCorrect[2]+"");
			properties.setProperty(prefix+"green2",this.colorsToCorrect[3]+"");
			properties.setProperty(prefix+"diagonal",this.colorsToCorrect[4]+"");
			properties.setProperty(prefix+"checker",this.colorsToCorrect[5]+"");
			properties.setProperty(prefix+"referenceComponent",this.referenceComponent+"");
			properties.setProperty(prefix+"equalizeGreens",this.equalizeGreens+"");
		}
		public void getProperties(String prefix,Properties properties){
			this.colorsToCorrect[0]=Boolean.parseBoolean(properties.getProperty(prefix+"green1"));
			this.colorsToCorrect[1]=Boolean.parseBoolean(properties.getProperty(prefix+"red"));
			this.colorsToCorrect[2]=Boolean.parseBoolean(properties.getProperty(prefix+"blue"));
			this.colorsToCorrect[3]=Boolean.parseBoolean(properties.getProperty(prefix+"green2"));
			this.colorsToCorrect[4]=Boolean.parseBoolean(properties.getProperty(prefix+"diagonal"));
			this.colorsToCorrect[5]=Boolean.parseBoolean(properties.getProperty(prefix+"checker"));
			this.referenceComponent=Integer.parseInt(properties.getProperty(prefix+"referenceComponent"));
			this.equalizeGreens=Boolean.parseBoolean(properties.getProperty(prefix+"equalizeGreens"));
		}
	}

	public static class OTFFilterParameters {
		public double deconvInvert;
		public double zerofreqSize;
		public double smoothPS;
		public double thresholdHigh;
		public double thresholdLow;

		public OTFFilterParameters(
				double deconvInvert,
				double zerofreqSize,
				double smoothPS,
				double thresholdHigh,
				double thresholdLow) {
			this.deconvInvert = deconvInvert;
			this.zerofreqSize = zerofreqSize;
			this.smoothPS = smoothPS;
			this.thresholdHigh = thresholdHigh;
			this.thresholdLow = thresholdLow;
		}
5226 5227
        @Override
		public OTFFilterParameters clone() {
Andrey Filippov's avatar
Andrey Filippov committed
5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258
        	return new OTFFilterParameters(
        			this.deconvInvert,
        			this.zerofreqSize,
        			this.smoothPS,
        			this.thresholdHigh,
        			this.thresholdLow);
        }
		public void setProperties(String prefix,Properties properties){
			properties.setProperty(prefix+"deconvInvert",this.deconvInvert+"");
			properties.setProperty(prefix+"zerofreqSize",this.zerofreqSize+"");
			properties.setProperty(prefix+"smoothPS",this.smoothPS+"");
			properties.setProperty(prefix+"thresholdHigh",this.thresholdHigh+"");
			properties.setProperty(prefix+"thresholdLow",this.thresholdLow+"");
		}
		public void getProperties(String prefix,Properties properties){
			this.deconvInvert=Double.parseDouble(properties.getProperty(prefix+"deconvInvert"));
			this.zerofreqSize=Double.parseDouble(properties.getProperty(prefix+"zerofreqSize"));
			this.smoothPS=Double.parseDouble(properties.getProperty(prefix+"smoothPS"));
			this.thresholdHigh=Double.parseDouble(properties.getProperty(prefix+"thresholdHigh"));
			this.thresholdLow=Double.parseDouble(properties.getProperty(prefix+"thresholdLow"));
		}

	}


	public static class PSFParameters {
		public double minContrast;
		public double windowFrac;
		public boolean useWindow;
		public boolean symm180;
		public boolean ignoreChromatic;
5259
		public boolean absoluteCenter;
Andrey Filippov's avatar
Andrey Filippov committed
5260 5261 5262 5263 5264 5265
		public double smoothSeparate;
		public double topCenter;
		public double sigmaToRadius;
		public double wingsEnergy;
		public double wingsEllipseScale;
		public double minDefinedArea;   // minimal (weighted) fraction of the defined patter pixels in the FFT area
5266 5267
		public boolean approximateGrid; // approximate grid with polynomial
		public boolean centerPSF;       // Center PSF by modifying phase
Andrey Filippov's avatar
Andrey Filippov committed
5268 5269 5270 5271
		public double mask1_sigma;
		public double mask1_threshold;
		public double gaps_sigma;
		public double mask_denoise;
5272

Andrey Filippov's avatar
Andrey Filippov committed
5273 5274 5275 5276 5277 5278

		public PSFParameters(double minContrast,
				double windowFrac,
				boolean useWindow,
				boolean symm180,
				boolean ignoreChromatic,
5279
				boolean absoluteCenter,
Andrey Filippov's avatar
Andrey Filippov committed
5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298
				double smoothSeparate,
				double topCenter,
				double sigmaToRadius,
				double wingsEnergy,
				double wingsEllipseScale,
				double minDefinedArea, // minimal (weighted) fraction of the defined patter pixels in the FFT area
				boolean approximateGrid, // approximate grid with polynomial
				boolean centerPSF,       // Center PSF by modifying phase
				double mask1_sigma,
				double mask1_threshold,
				double gaps_sigma,
				double mask_denoise

		) {
			this.minContrast = minContrast;
			this.windowFrac = windowFrac;
			this.useWindow = useWindow;
			this.symm180 = symm180;
			this.ignoreChromatic = ignoreChromatic;
5299
			this.absoluteCenter=absoluteCenter;
Andrey Filippov's avatar
Andrey Filippov committed
5300 5301 5302 5303 5304 5305
			this.smoothSeparate = smoothSeparate;
			this.topCenter = topCenter;
			this.sigmaToRadius = sigmaToRadius;
			this.wingsEnergy = wingsEnergy;
			this.wingsEllipseScale = wingsEllipseScale;
			this.minDefinedArea = minDefinedArea; // minimal (weighted) fraction of the defined patter pixels in the FFT area
5306 5307
			this.approximateGrid = approximateGrid; // approximate grid with polynomial
			this.centerPSF = centerPSF; // approximate grid with polynomial
Andrey Filippov's avatar
Andrey Filippov committed
5308 5309 5310 5311 5312 5313 5314
			this.mask1_sigma = mask1_sigma;
			this.mask1_threshold = mask1_threshold;
			this.gaps_sigma=gaps_sigma;
			this.mask_denoise=mask_denoise;


		}
5315 5316
        @Override
		public PSFParameters clone(){
Andrey Filippov's avatar
Andrey Filippov committed
5317 5318 5319 5320 5321 5322
        	return new PSFParameters(
        			this.minContrast,
        			this.windowFrac,
        			this.useWindow,
        			this.symm180,
        			this.ignoreChromatic,
5323
        			this.absoluteCenter,
Andrey Filippov's avatar
Andrey Filippov committed
5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343
        			this.smoothSeparate,
        			this.topCenter,
        			this.sigmaToRadius,
        			this.wingsEnergy,
        			this.wingsEllipseScale,
        			this.minDefinedArea, // minimal (weighted) fraction of the defined patter pixels in the FFT area
        			this.approximateGrid, // approximate grid with polynomial
        			this.centerPSF, // approximate grid with polynomial
        			this.mask1_sigma,
        			this.mask1_threshold,
        			this.gaps_sigma,
        			this.mask_denoise
                      );
        }
        public void setProperties(String prefix,Properties properties){
        	properties.setProperty(prefix+"minContrast",this.minContrast+"");
        	properties.setProperty(prefix+"windowFrac",this.windowFrac+"");
        	properties.setProperty(prefix+"useWindow",this.useWindow+"");
        	properties.setProperty(prefix+"symm180",this.symm180+"");
        	properties.setProperty(prefix+"ignoreChromatic",this.ignoreChromatic+"");
5344
        	properties.setProperty(prefix+"absoluteCenter",this.absoluteCenter+"");
Andrey Filippov's avatar
Andrey Filippov committed
5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363
        	properties.setProperty(prefix+"smoothSeparate",this.smoothSeparate+"");
        	properties.setProperty(prefix+"topCenter",this.topCenter+"");
        	properties.setProperty(prefix+"sigmaToRadius",this.sigmaToRadius+"");
        	properties.setProperty(prefix+"wingsEnergy",this.wingsEnergy+"");
        	properties.setProperty(prefix+"wingsEllipseScale",this.wingsEllipseScale+"");
        	properties.setProperty(prefix+"minDefinedArea",this.minDefinedArea+"");
        	properties.setProperty(prefix+"approximateGrid",this.approximateGrid+"");
        	properties.setProperty(prefix+"centerPSF",this.centerPSF+"");
        	properties.setProperty(prefix+"mask1_sigma",this.mask1_sigma+"");
        	properties.setProperty(prefix+"mask1_threshold",this.mask1_threshold+"");
        	properties.setProperty(prefix+"gaps_sigma",this.gaps_sigma+"");
        	properties.setProperty(prefix+"mask_denoise",this.mask_denoise+"");
        }
        public void setProperties(String prefix, ImagePlus properties){
        	properties.setProperty(prefix+"minContrast",this.minContrast+"");
        	properties.setProperty(prefix+"windowFrac",this.windowFrac+"");
        	properties.setProperty(prefix+"useWindow",this.useWindow+"");
        	properties.setProperty(prefix+"symm180",this.symm180+"");
        	properties.setProperty(prefix+"ignoreChromatic",this.ignoreChromatic+"");
5364
        	properties.setProperty(prefix+"absoluteCenter",this.absoluteCenter+"");
Andrey Filippov's avatar
Andrey Filippov committed
5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384
        	properties.setProperty(prefix+"smoothSeparate",this.smoothSeparate+"");
        	properties.setProperty(prefix+"topCenter",this.topCenter+"");
        	properties.setProperty(prefix+"sigmaToRadius",this.sigmaToRadius+"");
        	properties.setProperty(prefix+"wingsEnergy",this.wingsEnergy+"");
        	properties.setProperty(prefix+"wingsEllipseScale",this.wingsEllipseScale+"");
        	properties.setProperty(prefix+"minDefinedArea",this.minDefinedArea+"");
        	properties.setProperty(prefix+"approximateGrid",this.approximateGrid+"");
        	properties.setProperty(prefix+"centerPSF",this.centerPSF+"");
        	properties.setProperty(prefix+"mask1_sigma",this.mask1_sigma+"");
        	properties.setProperty(prefix+"mask1_threshold",this.mask1_threshold+"");
        	properties.setProperty(prefix+"gaps_sigma",this.gaps_sigma+"");
        	properties.setProperty(prefix+"mask_denoise",this.mask_denoise+"");
        }

		public void getProperties(String prefix,Properties properties){
			if (properties.getProperty(prefix+"minContrast")!=null)       this.minContrast=Double.parseDouble(properties.getProperty(prefix+"minContrast"));
			if (properties.getProperty(prefix+"windowFrac")!=null)        this.windowFrac=Double.parseDouble(properties.getProperty(prefix+"windowFrac"));
			if (properties.getProperty(prefix+"useWindow")!=null)         this.useWindow=Boolean.parseBoolean(properties.getProperty(prefix+"useWindow"));
			if (properties.getProperty(prefix+"symm180")!=null)           this.symm180=Boolean.parseBoolean(properties.getProperty(prefix+"symm180"));
			if (properties.getProperty(prefix+"ignoreChromatic")!=null)   this.ignoreChromatic=Boolean.parseBoolean(properties.getProperty(prefix+"ignoreChromatic"));
5385
			if (properties.getProperty(prefix+"absoluteCenter")!=null)   this.absoluteCenter=Boolean.parseBoolean(properties.getProperty(prefix+"absoluteCenter"));
Andrey Filippov's avatar
Andrey Filippov committed
5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527
			if (properties.getProperty(prefix+"smoothSeparate")!=null)    this.smoothSeparate=Double.parseDouble(properties.getProperty(prefix+"smoothSeparate"));
			if (properties.getProperty(prefix+"topCenter")!=null)         this.topCenter=Double.parseDouble(properties.getProperty(prefix+"topCenter"));
			if (properties.getProperty(prefix+"sigmaToRadius")!=null)     this.sigmaToRadius=Double.parseDouble(properties.getProperty(prefix+"sigmaToRadius"));
			if (properties.getProperty(prefix+"wingsEnergy")!=null)       this.wingsEnergy=Double.parseDouble(properties.getProperty(prefix+"wingsEnergy"));
			if (properties.getProperty(prefix+"wingsEllipseScale")!=null) this.wingsEllipseScale=Double.parseDouble(properties.getProperty(prefix+"wingsEllipseScale"));
			if (properties.getProperty(prefix+"minDefinedArea")!=null)    this.minDefinedArea=Double.parseDouble(properties.getProperty(prefix+"minDefinedArea"));
			if (properties.getProperty(prefix+"approximateGrid")!=null)   this.approximateGrid=Boolean.parseBoolean(properties.getProperty(prefix+"approximateGrid"));
			if (properties.getProperty(prefix+"centerPSF")!=null)         this.centerPSF=Boolean.parseBoolean(properties.getProperty(prefix+"centerPSF"));
			if (properties.getProperty(prefix+"mask1_sigma")!=null)       this.mask1_sigma=Double.parseDouble(properties.getProperty(prefix+"mask1_sigma"));
			if (properties.getProperty(prefix+"mask1_threshold")!=null)   this.mask1_threshold=Double.parseDouble(properties.getProperty(prefix+"mask1_threshold"));
			if (properties.getProperty(prefix+"gaps_sigma")!=null)        this.mask1_threshold=Double.parseDouble(properties.getProperty(prefix+"gaps_sigma"));
			if (properties.getProperty(prefix+"mask_denoise")!=null)        this.mask_denoise=Double.parseDouble(properties.getProperty(prefix+"mask_denoise"));
		}
	}

	public static class InverseParameters {
		public int dSize;
		public int rSize;
		public double invertRange;
		public double otfCutoffEnergy;
		public double otfEllipseScale;
		public boolean otfEllipseGauss;
		public double psfCutoffEnergy;
		public double psfEllipseScale;
		public double rpsfMinMaskThreshold;
		public boolean filter;
		public double blurIndividual;
		public double blurDiagonal;
		public double blurChecker;
		public double gaussianSigmaIndividual;
		public double gaussianSigmaDiagonal;
		public double gaussianSigmaChecker;
		public double sigmaScale;
		public double sigmaToRadius;
		public boolean filterDirect;
		public double sigmaScaleDirect;
		public double sigmaToRadiusDirect;

		public InverseParameters(int dSize, int rSize, double invertRange,
				double otfCutoffEnergy, double otfEllipseScale,
				boolean otfEllipseGauss, double psfCutoffEnergy,
				double psfEllipseScale, double rpsfMinMaskThreshold,
				boolean filter, double blurIndividual, double blurDiagonal, double blurChecker,
				double gaussianSigmaIndividual, double gaussianSigmaDiagonal, double gaussianSigmaChecker,
				double sigmaScale, double sigmaToRadius,
				boolean filterDirect, double sigmaScaleDirect, double sigmaToRadiusDirect
				) {
			this.dSize = dSize;
			this.rSize = rSize;
			this.invertRange = invertRange;
			this.otfCutoffEnergy = otfCutoffEnergy;
			this.otfEllipseScale = otfEllipseScale;
			this.otfEllipseGauss = otfEllipseGauss;
			this.psfCutoffEnergy = psfCutoffEnergy;
			this.psfEllipseScale = psfEllipseScale;
			this.rpsfMinMaskThreshold = rpsfMinMaskThreshold;
			this.filter = filter;
			this.blurIndividual = blurIndividual;
			this.blurDiagonal = blurDiagonal;
			this.blurChecker = blurChecker;
			this.gaussianSigmaIndividual = gaussianSigmaIndividual;
			this.gaussianSigmaDiagonal = gaussianSigmaDiagonal;
			this.gaussianSigmaChecker = gaussianSigmaChecker;
			this.sigmaScale = sigmaScale;
			this.sigmaToRadius = sigmaToRadius;
			this.filterDirect=filterDirect;
			this.sigmaScaleDirect=sigmaScaleDirect;
			this.sigmaToRadiusDirect=sigmaToRadiusDirect;
		}

		public void setProperties(String prefix,Properties properties){
			properties.setProperty(prefix+"dSize",this.dSize+"");
			properties.setProperty(prefix+"rSize",this.rSize+"");
			properties.setProperty(prefix+"invertRange",this.invertRange+"");
			properties.setProperty(prefix+"otfCutoffEnergy",this.otfCutoffEnergy+"");
			properties.setProperty(prefix+"otfEllipseScale",this.otfEllipseScale+"");
			properties.setProperty(prefix+"otfEllipseGauss",this.otfEllipseGauss+"");
			properties.setProperty(prefix+"psfCutoffEnergy",this.psfCutoffEnergy+"");
			properties.setProperty(prefix+"psfEllipseScale",this.psfEllipseScale+"");
			properties.setProperty(prefix+"rpsfMinMaskThreshold",this.rpsfMinMaskThreshold+"");
			properties.setProperty(prefix+"filter",this.filter+"");
			properties.setProperty(prefix+"blurIndividual",this.blurIndividual+"");
			properties.setProperty(prefix+"blurDiagonal",this.blurDiagonal+"");
			properties.setProperty(prefix+"blurChecker",this.blurChecker+"");
			properties.setProperty(prefix+"gaussianSigmaIndividual",this.gaussianSigmaIndividual+"");
			properties.setProperty(prefix+"gaussianSigmaDiagonal",this.gaussianSigmaDiagonal+"");
			properties.setProperty(prefix+"gaussianSigmaChecker",this.gaussianSigmaChecker+"");
			properties.setProperty(prefix+"sigmaScale",this.sigmaScale+"");
			properties.setProperty(prefix+"sigmaToRadius",this.sigmaToRadius+"");
			properties.setProperty(prefix+"filterDirect",this.filterDirect+"");
			properties.setProperty(prefix+"sigmaScaleDirect",this.sigmaScaleDirect+"");
			properties.setProperty(prefix+"sigmaToRadiusDirect",this.sigmaToRadiusDirect+"");
		}

		public void setProperties(String prefix,ImagePlus properties){
			properties.setProperty(prefix+"dSize",this.dSize+"");
			properties.setProperty(prefix+"rSize",this.rSize+"");
			properties.setProperty(prefix+"invertRange",this.invertRange+"");
			properties.setProperty(prefix+"otfCutoffEnergy",this.otfCutoffEnergy+"");
			properties.setProperty(prefix+"otfEllipseScale",this.otfEllipseScale+"");
			properties.setProperty(prefix+"otfEllipseGauss",this.otfEllipseGauss+"");
			properties.setProperty(prefix+"psfCutoffEnergy",this.psfCutoffEnergy+"");
			properties.setProperty(prefix+"psfEllipseScale",this.psfEllipseScale+"");
			properties.setProperty(prefix+"rpsfMinMaskThreshold",this.rpsfMinMaskThreshold+"");
			properties.setProperty(prefix+"filter",this.filter+"");
			properties.setProperty(prefix+"blurIndividual",this.blurIndividual+"");
			properties.setProperty(prefix+"blurDiagonal",this.blurDiagonal+"");
			properties.setProperty(prefix+"blurChecker",this.blurChecker+"");
			properties.setProperty(prefix+"gaussianSigmaIndividual",this.gaussianSigmaIndividual+"");
			properties.setProperty(prefix+"gaussianSigmaDiagonal",this.gaussianSigmaDiagonal+"");
			properties.setProperty(prefix+"gaussianSigmaChecker",this.gaussianSigmaChecker+"");
			properties.setProperty(prefix+"sigmaScale",this.sigmaScale+"");
			properties.setProperty(prefix+"sigmaToRadius",this.sigmaToRadius+"");
			properties.setProperty(prefix+"filterDirect",this.filterDirect+"");
			properties.setProperty(prefix+"sigmaScaleDirect",this.sigmaScaleDirect+"");
			properties.setProperty(prefix+"sigmaToRadiusDirect",this.sigmaToRadiusDirect+"");
		}

		public void getProperties(String prefix,Properties properties){
			this.dSize=Integer.parseInt(properties.getProperty(prefix+"dSize"));
			this.rSize=Integer.parseInt(properties.getProperty(prefix+"rSize"));
			this.invertRange=Double.parseDouble(properties.getProperty(prefix+"invertRange"));
			this.otfCutoffEnergy=Double.parseDouble(properties.getProperty(prefix+"otfCutoffEnergy"));
			this.otfEllipseScale=Double.parseDouble(properties.getProperty(prefix+"otfEllipseScale"));
			this.otfEllipseGauss=Boolean.parseBoolean(properties.getProperty(prefix+"otfEllipseGauss"));
			this.psfCutoffEnergy=Double.parseDouble(properties.getProperty(prefix+"psfCutoffEnergy"));
			this.psfEllipseScale=Double.parseDouble(properties.getProperty(prefix+"psfEllipseScale"));
			this.rpsfMinMaskThreshold=Double.parseDouble(properties.getProperty(prefix+"rpsfMinMaskThreshold"));
			this.filter=Boolean.parseBoolean(properties.getProperty(prefix+"filter"));
			this.blurIndividual=Double.parseDouble(properties.getProperty(prefix+"blurIndividual"));
			this.blurDiagonal=Double.parseDouble(properties.getProperty(prefix+"blurDiagonal"));
			this.blurChecker=Double.parseDouble(properties.getProperty(prefix+"blurChecker"));
			this.gaussianSigmaIndividual=Double.parseDouble(properties.getProperty(prefix+"gaussianSigmaIndividual"));
			this.gaussianSigmaDiagonal=Double.parseDouble(properties.getProperty(prefix+"gaussianSigmaDiagonal"));
			this.gaussianSigmaChecker=Double.parseDouble(properties.getProperty(prefix+"gaussianSigmaChecker"));
			this.sigmaScale=Double.parseDouble(properties.getProperty(prefix+"sigmaScale"));
			this.sigmaToRadius=Double.parseDouble(properties.getProperty(prefix+"sigmaToRadius"));
			this.filterDirect=Boolean.parseBoolean(properties.getProperty(prefix+"filterDirect"));
			this.sigmaScaleDirect=Double.parseDouble(properties.getProperty(prefix+"sigmaScaleDirect"));
			this.sigmaToRadiusDirect=Double.parseDouble(properties.getProperty(prefix+"sigmaToRadiusDirect"));
		}
	}
5528 5529


Andrey Filippov's avatar
Andrey Filippov committed
5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573
	public static class InterpolateParameters {
		public int    size;        // size of each kernel (should be square)
		public int    step;        // number of subdivisions from input to output
		public int    add_top;     // add this number of kernel rows to the output above the existent/interpolated
		public int    add_left;    // add this number of kernel columns to the output on the left of the existent/interpolated
		public int    add_right;   // add this number of kernel columns to the output on the right of the existent/interpolated
		public int    add_bottom;  // add this number of kernel rows to the output below the existent/interpolated
		public double extrapolate; // 0 - duplicate, 1.0 - extrapolate outside of the known kernels

		public InterpolateParameters(
				int    size,
				int    step,
				int    add_top,
				int    add_left,
				int    add_right,
				int    add_bottom,
				double extrapolate
		) {
			this.size=size;
			this.step=step;
			this.add_top=add_top;
			this.add_left=add_left;
			this.add_right=add_right;
			this.add_bottom=add_bottom;
			this.extrapolate=extrapolate;
		}
		public void setProperties(String prefix,Properties properties){
			properties.setProperty(prefix+"size",this.size+"");
			properties.setProperty(prefix+"step",this.step+"");
			properties.setProperty(prefix+"add_top",this.add_top+"");
			properties.setProperty(prefix+"add_left",this.add_left+"");
			properties.setProperty(prefix+"add_right",this.add_right+"");
			properties.setProperty(prefix+"add_bottom",this.add_bottom+"");
			properties.setProperty(prefix+"extrapolate",this.extrapolate+"");
		}
		public void setProperties(String prefix,ImagePlus properties){
			properties.setProperty(prefix+"size",this.size+"");
			properties.setProperty(prefix+"step",this.step+"");
			properties.setProperty(prefix+"add_top",this.add_top+"");
			properties.setProperty(prefix+"add_left",this.add_left+"");
			properties.setProperty(prefix+"add_right",this.add_right+"");
			properties.setProperty(prefix+"add_bottom",this.add_bottom+"");
			properties.setProperty(prefix+"extrapolate",this.extrapolate+"");
		}
5574

Andrey Filippov's avatar
Andrey Filippov committed
5575 5576 5577 5578 5579 5580 5581 5582 5583
		public void getProperties(String prefix,Properties properties){
			this.size=Integer.parseInt(properties.getProperty(prefix+"size"));
			this.step=Integer.parseInt(properties.getProperty(prefix+"step"));
			this.add_top=Integer.parseInt(properties.getProperty(prefix+"add_top"));
			this.add_left=Integer.parseInt(properties.getProperty(prefix+"add_left"));
			this.add_right=Integer.parseInt(properties.getProperty(prefix+"add_right"));
			this.add_bottom=Integer.parseInt(properties.getProperty(prefix+"add_bottom"));
			this.extrapolate=Double.parseDouble(properties.getProperty(prefix+"extrapolate"));
		}
5584

Andrey Filippov's avatar
Andrey Filippov committed
5585 5586
	}

5587 5588


Andrey Filippov's avatar
Andrey Filippov committed
5589 5590

}